Q:

Static class member shows confusing syntax error

This is my project setup:
Main.hpp
#pragma once
#ifndef MAIN_HPP
#define MAIN_HPP

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <stdio.h>
#include <stdarg.h>

#include <iostream>
#include <string>
#include <map>

#include "Util/Cache.hpp"

#include "SampInternal.hpp"

BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved);

#endif

Main.cpp
#include "Main.hpp"

BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved)
{
    DisableThreadLibraryCalls(hModule);

    if (dwReason != DLL_PROCESS_ATTACH)
        return FALSE;

    return (CreateThread(NULL, NULL, &SampInternal::Initialize, NULL, NULL, NULL) > 0);
}

SampInternal.hpp (Foo.hpp before edit)
#pragma once
#ifndef SAMPINTERNAL_HPP
#define SAMPINTERNAL_HPP

#include "Main.hpp"

#define D3D9_NAME                           "d3d9"
#define SAMP_NAME                           "samp"

#define D3D9_DLL                            "d3d9.dll"
#define SAMP_DLL                            "samp.dll"

class SampInternal
{

public:

    static DWORD APIENTRY Initialize(LPVOID lpArgs);

private:

    static Cache<HMODULE> s_moduleCache;

};

#endif

SampInternal.cpp
#include "SampInternal.hpp"

Cache<HMODULE> SampInternal::s_moduleCache;

DWORD APIENTRY SampInternal::Initialize(LPVOID lpArgs)
{

    return 0;
}

Cache.hpp
#pragma once
#ifndef CACHE_HPP
#define CACHE_HPP

#include "../Main.hpp"

template<typename T>
class Cache
{

public:

    void Add(std::string name, T value);
    T Get(std::string name);

private:

    std::map<std::string, T> m_storage;;

};

template<typename T>
void Cache<T>::Add(std::string name, T value)
{
    m_storage[name] = value;
}

template<typename T>
T Cache<T>::Get(std::string name)
{
    if (m_storage.find(name) != m_storage.end())
        return m_storage[name];

    return nullptr;
}

#endif

(Cache.cpp is empty - only #include "Cache.hpp")
I'm a beginner in C++ but I can't see any errors here.
The compiler (using Visual Studio 2015) outputs me:
Syntax Error: Missing ';' before '<'
Unexpected token before ';'
Both on the line static Cache<HMODULE> s_moduleCache;
Sorry if this looks trivial to you, but I don't know whats the problem here.

A:

This seems like a normal circular inclusion dependency problem to me: Cache.hpp needs Main.hpp which needs SampInternal.hpp which needs Cache.hpp ... etc. and so on.
The simplest way to break this circle (as far as I can see) is to not include Main.hpp in the Cache.hpp file. In the Cache.hpp file include the files it needs explicitly, e.g. <map> and <string>.


Q:

Mount SkyDrive as a network drive

SkyDrive offers 25GB free space, but only offers a way too simple web upload one file at a time.
Does software exist, that makes it possible to mount it as a network drive?
Edit: The solutions work for a while, but stop working after awhile.

A:

A little update if anyone out there is interested like me :) http://skydrivesimpleviewer.codeplex.com/ gives you WebDAV url's so you can mount Skydrive folders natively in Windows Explorer with "Map network drive".
UPDATE:
In case this method does not work for you (for some users it says invalid username or password), I managed to map skydrive as network drive using MS Word (publish to sky drive and taking url from there).
See Microsoft Office and web section in this document: http://www.mikeplate.com/2010/01/17/how-to-connect-to-skydrive-with-webdav/

A:

You need to use the Gladinet software  to do this.


Q:

How to get local characters from MySql database on remote server

I'm trying to get local characters č ž đ... from MySql database.
On localhost the problem doesn't exists, but on remote server the local characters are missing.
Database and table collation is utf8_general_ci (according to one answer here )
my connection:
try {
    $db = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME.';charset=utf8_general_ci', DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}
catch (PDOException $e) {
    echo $e->getMessage();
    exit;
}

here I have the error - Unknown character set. Writing only charset=utf8 the error is removing, but this doesn't help about local characters.
edit.php
include ("menut.php");
SET character_set_client = "utf8";  //line 12
SET character_set_results = "utf8";
SET collation_connection = "utf8_general_ci";
$stmt = $db->prepare("SELECT id, title, content FROM  $table WHERE id = :id");
$stmt->execute(array(':id' => $_GET['id']));
$row = $stmt->fetch();

Here I have the error - Unexpected T String on line 12 (marked abowe).
Any help.

A:

SET character_set_client = "utf8";  //line 12
SET character_set_results = "utf8";
SET collation_connection = "utf8_general_ci";

Above are mysql commands, and you need to execute query to run these commands:
$db->query('SET character_set_client = "utf8"');
$db->query('SET character_set_results = "utf8"');
$db->query('SET collation_connection = "utf8_general_ci"');


Q:

Triggering a "Click" event without user input

I have a Windows Forms Link Label, "Refresh", that refreshes the display.
In another part of my code, part of a separate windows form, I have a dialog that changes the data loaded into the display in the first place. After executing this other code, pressing "Refresh" updates the data correctly.
Is there a simple way for the dialog menu to "click" the "refresh" Link Label after it has finished altering the data?
Using Visual Studio 2008.

A:

For button is really simple, just use:
button.PerformClick()

Anyway, I'd prefer to do something like:
private void button_Click(object sender, EventArgs e)
{
   DoRefresh();
}

public void DoRefresh()
{
   // refreshing code
}

and call DoRefresh() instead of PerformClick()

EDIT (according to OP changes):
You can still use my second solution, that is far preferable:
private void linkLabel_Click(object sender, EventArgs e)
{
   DoRefresh();
}

public void DoRefresh()
{
   // refreshing code
}

And from outside the form, you can call DoRefresh() as it is marked public.
But, if you really need to programmatically generate a click, just look at Yuriy-Faktorovich's Answer

A:

You could call the PerformClick method. But Generally it is better to have the Click event of the button call a Refresh method you write. And the menu call that method as well. Otherwise your menu depends on the button being there.
Edit:
A LinkLabel implements the IButtonControl explicitly. So you could use:
((IButtonControl)button).PerformClick();


Q:

HTML Agility Pack

I'm trying to use HTML Agility Pack to get the description text from inside the:
<meta name="description" content="**this is the text i want to extract and store in a string**" />

And someone on Stackoverflow a little while ago suggested I use HTMLAgilityPack. But I don't know how to use it, and the documentation for it that I've found (including the docs contained in the downloads) all have invalid links and therefor cannot view the documentation.
Can somebody please help me solve this?

A:

The usage is very similar to XmlDocument; you could use MSDN  on XmlDocument for a broad overview; you might also want to learn xpath syntax (MSDN).
Example:
HtmlDocument doc = new HtmlDocument();
doc.Load(path); // or .LoadHtml(html);
HtmlNode node = doc.DocumentNode.SelectSingleNode("//meta[@name='description']");
if (node != null) {
    string desc = node.GetAttributeValue("content", "");
    // TODO: write desc somewhere
}

The second argument to GetAttributeValue is the default returned in case the attribute is not found.


Q:

Which Javascript functions need to be Awaited?

I've done some searching and not able to find a clear answer on which functions need to be awaited. Or perhaps I'm not using the word "function" correctly.
I'm mostly curious about intrinsic functions in Javascript, like .replace(). Do we need to await this?
In other words, this code:
let cusName = 'Unknown Name'

cusName = cusName.replace('Unknown', '');

console.log(cusName);

Is there a guarantee that this will log 'Name' every time? What if the server is running a little slow? If this runs a billion times, is it possible that 'Unknown Name' ever gets logged?
Or is it important to we need to do this:
let cusName = 'Unknown Name'

cusName = await cusName.replace('Unknown', '');

console.log(cusName);

A:

The only functions that you await are those that return a promise (or are async, which is the same thing). I recommend you start by researching promises (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) and once you have a firm grasp of promises, you can learn the async/await pattern.
In your example, replace is synchronous, and does not return a promise, so you don't need to await it.


Q:

How to get MatchAllFilter to work properly and add other filters to MatchAllfilter?

I do not think the MatchAllFilter class that I have created is storing the filters I am trying to add to it properly. When I pass a list in none of the filters are working. How do I properly store other filters into MatchAllFitlers and have the filters stored inside maf filter the lists I will be passing? I have tested all my filters one by one; I know they work.
public class MatchAllFilter implements Filter {
 private ArrayList<Filter>filt;
 private String nameF;
 public MatchAllFilter(){
     filt= new ArrayList<Filter>();

    }
public void addFilter(Filter f){
    filt.add(f);

}

public boolean satisfies(QuakeEntry qe) {
    for(Filter f:filt){
        if (f.satisfies(qe)){
            return true;

        }

    }
    return false;
}

}
 public void testMatchAllFilter(){
    EarthQuakeParser parser = new EarthQuakeParser();
    //String source = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.atom";
    String source = "data/nov20quakedatasmall.atom";
    ArrayList<QuakeEntry> list  = parser.read(source);
    MatchAllFilter maf=new MatchAllFilter();
    double depthMin=-100000.0;
    double depthMax=-10000.0;
    Filter f=  new DepthFilter(-100000.0,-10000.0);
    maf.addFilter(f);
    Filter e= new MagnitudeFilter(0.0, 2.0);
    maf.addFilter(e);
    Filter g= new PhraseFilter("any","a");
    maf.addFilter(g);

    //ArrayList<QuakeEntry>m10= filter(list,maf);
    //for (QuakeEntry qe: list) {
        //System.out.println(qe);
    System.out.println(maf);
    }

A:

If what you are trying to do is check if all the filters in filt are applicable to qe then the problem is that right now you are checking if any of the filters satisfy its criteria and then exiting the function. In other words, instead off all filters you are checking for any filters. e.g.:
public boolean satisfies(QuakeEntry qe) {
    for(Filter f : filt) {
        if (f.satisfies(qe)) { // one of the filters worked, let's exit
            return true;
        }
    }
    return false;
}

If you need to check if all filters apply to qe then you have to traverse through the whole list of filters in filt
public boolean satisfies(QuakeEntry qe) {
    for(Filter f : filt){
        if (!f.satisfies(qe)) { // any of the filters criteria failed, then exit
            return false;
        }
    }
    return true; // the code will only reach this point if all the filters were applied
}

If you are using Java 8+, you can use streams e.g.
public boolean satisfies(QuakeEntry qe) {
    return filt.stream().allMatch(f -> f.satisfies(qe));
}


Q:

How to get Current position of a control on Win Form

Am trying very hard but not find any method to get the location(x,y) of the control like picturebox on the form .. please help me ...

A:

you can just use  picturebox1.Left as you X  and picturebox1.Top as your Y
or
you can  combine PointToScreen and PointToClient:
Point locationOnForm = control.FindForm().PointToClient(
    control.Parent.PointToScreen(picturebox1.Location));


Q:

fName set as Variant, still showing mismatch error when trying to stop macro if no file selected by GetOpenFileName function

I am trying to run my code with GetOpenFileName function in it. When I am not selecting a file, I am unsure of what is the value that is returned in variable fName. The way my code is right now, If I "Do Not" select a file, it returns the message box as written(which is what I want) but as I click ok, it takes me to a random spot in my workbook(something I also need help on), but main issue is, when I "Do" select a file to run, it gives me back a "Type mismatch error" even when my variable is defined as Variant. Without this addition to my code, the code runs great but I want to add this functionality. Thanks in advance for the help!
     Dim fName As Variant

     fName = Application.GetOpenFilename( _
        FileFilter:="*.xlsx(*.xlsx),*.xls,*.xlsm (*.xlsm),*.xlsm", _
        Title:="Select a file or files", _
        MultiSelect:=True)

     If fName = "False" Then
        MsgBox "Select a file to proceed"

     Else

      Sheets("Main").Select

       If IsArray(Fname) Then
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    For N = LBound(Fname) To UBound(Fname)

        ' Get only the file name and test to see if it is open.
        FnameInLoop = Right(Fname(N), Len(Fname(N)) - InStrRev(Fname(N), Application.PathSeparator, , 1))
        If bIsBookOpen(FnameInLoop) = False Then

            Set mybook = Nothing
            On Error Resume Next
            Set mybook = Workbooks.Open(Fname(N))
            On Error GoTo 0

 ' Sub CopyData()
 '
 ' CopyData Macro
 '

 '
Sheets("Sheet1").Select
Columns("A:O").Select
Selection.Copy
Windows("SupplierDeliveryPerfWall_MasterSheet").Activate

' ActiveSheet.Select
' ActiveSheet.Name = "Data"

Sheets("Data").Select

Range("A1").Select

ActiveSheet.Paste

Application.CutCopyMode = False

            If Not mybook Is Nothing Then

                mybook.Close SaveChanges:=True
            End If
        Else
            MsgBox "We skipped this file : " & Fname(N) & " because it is already open."
        End If
    Next N
    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
End If

' Change drive/directory back to SaveDriveDir.
ChDrive SaveDriveDir
ChDir SaveDriveDir

   'Insert data validation column

    Windows("SupplierDeliveryPerfWall_MasterSheet").Activate

    Sheets("Data").Select

    Range("A2:O2000").Select

    ' Unmerge data that is copied from Oracle

      Range("A2:O2000").UnMerge

    ' Sub sbInsertingColumns()

    'Inserting a Column at Column E for reason codes

     Range("E1").EntireColumn.Insert
     Range("E1").Select

     ActiveCell.FormulaR1C1 = "Reason Code"

     ActiveCell.Offset(1, 0).Range("A1").Select

    'Inserting a Column at Column F for Comments

     Range("F1").EntireColumn.Insert

     Range("F1").Select

ActiveCell.FormulaR1C1 = "Comments"
Range("F1").Select

Application.CutCopyMode = False

' Inserting data validation

Sheets("Main").Select
Range("AF2:AF2000").Select
Selection.Copy
Sheets("Data").Select
Range("E2").Select

ActiveSheet.Paste

' Insert Comment in data validation

Range("E2").Select
Range(Selection, Selection.End(xlDown)).Select
With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="='Reason Codes'!$A$2:$A$500"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = "Select Reason Code"
    .ErrorTitle = "Select from list"
    .InputMessage = ""
    .ErrorMessage = "If exception, enter in COMMENTS column"
    .ShowInput = True
    .ShowError = True
End With
Range("E2").Select
Range(Selection, Selection.End(xlDown)).Select
With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="='Reason Codes'!$A$2:$A$500"
    .IgnoreBlank = True
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = "Select from list"
    .InputMessage = "Select Reason Code"
    .ErrorMessage = "If exception, enter in COMMENTS column"
    .ShowInput = True
    .ShowError = True
End With

      Next

     End If
     End Sub

A:

main issue is, when I "Do" select a file to run, it gives me back a "Type mismatch error" even when my variable is defined as Variant.

This is because you have MultiSelect:=True. This is problematic because sometimes the result will be an array and other times (if the user cancels) it will be a boolean.  So first you need to test whether the return value is an array or not. If it's an array, the iterate the selected files. If not, then do the MsgBox prompt.
Sub foo()
Dim FileNames
Dim file

FileNames = Application.GetOpenFilename( _
        FileFilter:="*.xlsx(*.xlsx),*.xls,*.xlsm (*.xlsm),*.xlsm", _
        Title:="Select a file or files", _
        MultiSelect:=True)

If IsArray(FileNames) Then
    For Each file In FileNames

        'Do something to each file

    Next
Else
    'This really can't be anything other than FALSE:
    If Not FileNames Then
        MsgBox "No files selected"
        Exit Sub
    End If
End If

End Sub

If you don't need to allow multi-select, then just use the Dir() function.
 fName = Application.GetOpenFilename( _
    FileFilter:="*.xlsx(*.xlsx),*.xls,*.xlsm (*.xlsm),*.xlsm", _
    Title:="Select a file", _
    MultiSelect:=False)

 If Dir(CStr(fName)) = vbNullString Then
    MsgBox "Select a file to proceed"
    Exit Sub
 Else
    'Do something to the file

 End If


Q:

Binding List to CheckBoxGroup in vaadin

I have an enum:
public enum Roles {
   USER,ADMIN;
}

And a CheckBoxGroup on my form:
private CheckBoxGroup<String> rolesCheckbox = new CheckBoxGroup<>("User roles");

Instance of a User class binded to this form has a field:
private List<Roles> roles;

And what I want to do now is just check correct checkboxes when opening form for a specific User instance. I probably has to do something insinde binder.forField but I don't really know how:
binder.forField(rolesCheckbox).bind(...

A:

The example from the Vaadin docs uses String for brevity, but you can easily use objects. Suppose you have a Role enum and a User like below:
// possible roles
public enum Role {
    ADMIN, USER, GUEST
}

// bean for binding
public class User {
    private Set<Role> roles;
    private String name;

    public User(String name, Set<Role> roles) {
        this.roles = roles;
        this.name = name;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "roles=" + roles +
                ", name='" + name + '\'' +
                '}';
    }
}

... you could create your form similar to:
public class CheckboxEnumBinding extends VerticalLayout {

    public CheckboxEnumBinding() {
        // form components
        TextField nameTextField = new TextField("Name");
        CheckBoxGroup<Role> roleCheckBoxGroup = new CheckBoxGroup<>("Roles", DataProvider.ofItems(Role.values()));

        // binder setup
        Binder<User> userBinder = new Binder<>();

        // name binding
        userBinder.forField(nameTextField)
                .asRequired("Please provide a user name")
                .bind(User::getName, User::setName);

        // role binding
        userBinder.forField(roleCheckBoxGroup)
                .asRequired("Please select at least one role")
                .bind(User::getRoles, User::setRoles);

        // bind to bean
        userBinder.setBean(new User("Morfic", EnumSet.of(Role.ADMIN, Role.GUEST)));

        // simulate a save action
        Button saveButton = new Button("Save", event -> Notification.show("Saved new user info: " + userBinder.getBean()));

        // add fields to the UI
        addComponents(nameTextField, roleCheckBoxGroup, saveButton);
    }
}

Result:

Bonus: By default Vaadin will use the enum name to display the values. If you want something different, like capitalizing only the first letter you can use an ItemCaptionGenerator:
// spring boot app, don't reinvent the wheel
import org.springframework.util.StringUtils;
...
roleCheckBoxGroup.setItemCaptionGenerator(role -> StringUtils.capitalize(role.name().toLowerCase()));


Q:

How to buy and sell Ardor

I know this community is for bitcoin but I couldn't find any community to talk about crypto-currencies in general so I thought this may be the right place to ask.
I am interested on investing money on Ardor but I am kind of new in the world of crypto-currencies. So if someone could explain me how to buy and then sell Ardor in an easy way and avoiding places that could end up like mt.gox that would be nice.

A:

Poloniex is probably the best place to invest into Ardor.
Changelley (https://changelly.com) would be better if you don't want to keep the tokens on an exchange like Poloniex.
From the website:
Note: If you have ARDR tokens, do NOT send them to the address you create on the Ardor Testnet. Please send them to a Nxt Wallet from Nxt.org as ARDR is currently an asset on the Nxt blockchain until its launch in Q3.
Notice even the Ardor explorer is on Nxt:
https://www.mynxt.info/asset/12422608354438203866


Q:

Sort Stacked Bar Chart Individually in Matplotlib

I am trying to sort components of a stacked bar chart individually for better readability (either in the DataFrame itself) or once the chart is graphed and I cannot figure out if there is a good way to do this.
For example, I have this dictionary of players & the time spent against their opponents -
so_oppo_dict = {
  'Player 1': {'Opponent 1': 2.15, 'Opponent 2': 3.5333, 'Opponent 3': 3.1},
  'Player 2': {'Opponent 1': 2.2167, 'Opponent 2': 1.8667, 'Opponent 3': 2.3333},
  'Player 3': {'Opponent 1': 1.5333, 'Opponent 2': 4.3833, 'Opponent 3': 4.15}
}

I then graph it using the following code to turn it into a stacked bar chart -
fig, ax = plt.subplots()
ax = plt.subplot(111)
so_oppo_df.T.plot(kind="barh", stacked=True, ax=ax)
fig.tight_layout()
fig.savefig('opponents-stacked.png')

My resulting graph looks like this and each component of the stacked bar graph is sorted in the same order. What I would like to do is rearrange the the componets of the bars to sort by highest to lowest (so the green and orange bars would come before the blue bars) - is this possible to do?

A:

Based on this phenomenal answer I was able to produce exactly what was needed. Here is the code snippet that I finalized below & the resulting image (with a much larger dictionary).
x = so_oppo_df.index
indexes = np.argsort(so_oppo_df.values).T
widths = np.sort(so_oppo_df.values).T
order = -1
lefts = widths[::order].cumsum(axis=0)
lefts = np.insert(lefts, 0, np.zeros(len(lefts[0])), axis=0)

mpp_colors = dict(zip(so_oppo_df.columns, plt.cm.get_cmap("tab20c").colors))

for k, (idxs, vals) in enumerate(list(zip(indexes, widths))[::order]):
    mps = np.take(np.array(so_oppo_df.columns), idxs)
    ax1.barh(x, width=vals, left=lefts[k], color=[mpp_colors[m] for m in mps])

ax1.legend((np.take(np.array(so_oppo_df.columns), np.argsort(so_oppo_df.values)[0]))[::-1], bbox_to_anchor=(1.05, 1), loc='upper left', ncol=1)
ax1.title.set_text(f"Team Opposition - 5v5 Sorted TOI")


Q:

Capturar grupos en expresión regular condicionados por los siguientes caracteres

Estoy agrupando registros (tareas) que tienen un código identificador.
El código es único, pero hay tareas que son continuación de otras y eso se refleja en su código. Por ejemplo:

12345: Registro original
12345A: Nueva versión del registro 12345
12345B: Otra version del registro 12345
12345C: Tercera versión del registro 12345

Y aquí viene mi problema:

12345CONT: Continuación (de la versión activa) del 12345 (da igual si la activa es la original o la A, B o C)
12345CONT2: Segunda continuación del 12345
12345PF: Información final
... (otras terminaciones, siempre de más de una letra

Quiero capturar los siguientes grupos:
ID - Versión (A,B,C,D -opcional-) - Tipo de tarea (CONT<n>, PF<n>, ...)

Mi regex actualmente es la siguiente:
(\d+)[ABCD]?(CONT\d?|PF\d?|REV|REP)?

Pero tiene el problema de que 12345CONT me captura 12345 - C y me descarta el ONT. Estoy mirando opciones "look-ahead", pero no termino de encontrar la solución.
¿Cómo capturar CONT y C por separado?

A:

Puedes usar 'negative lookahead':
(\d+)(A|B|C(?!ONT)|D)?(CONT\d?|PF\d?|REV|REP)?

C(?!ONT) capturará C solo cuando no es seguido por ONT.
(demo)


Q:

Book request: teaching proving and reasoning at an American university

I am a European postdoc who recently teaching at a large public university in the United States. I will have to teach a course for undergraduate students that introduces them to proving and reasoning in mathematics.
The students have possibly no exposure to mathematical reasoning in general. At the end of the course, they should be able to read and write proofs, and use the standard logical/set-theoretical notation.
What books or lecture notes can you recommend (or dis-recommend) for such a course? I am particularly interested in material that gets them as close as possible to being able to read non-American textbooks.

A:

Some things we're currently considering for a similar course at a large urban community college:

Epp, Discrete Mathematics with Applications
Artin, Algebra
Gilbert, Elements of Modern Algebra
Lay, Analysis with an Introduction to Proof
Wade, An Introduction to Analysis

And also some OER (open educational resources) options:

Sundstrom, Mathematical Reasoning: Writing and Proof (formerly a mass-market textbook) http://scholarworks.gvsu.edu/books/9/
Hammack, Book of Proof http://www.people.vcu.edu/~rhammack/BookOfProof/
Hutchings, Introduction to Mathematical Arguments (27 pages; I esp. like the "Logic in a nutshell" table on p. 9) http://math.berkeley.edu/~hutching/teach/proofs.pdf
Turner, A Brief Introduction to Proofs (9 pages; meant as a primer to any course involving proofs) http://persweb.wabash.edu/facstaff/turnerw/Writing/proofs.pdf

Edit: Struck out Arten's Algebra from list above due to consensus in comments.

A:

Another free option is Lehman, Leighton, and Meyer's Mathematics for Computer Science. It's written for an MIT introductory discrete math course that emphasizes training students in proof-writing.

A:

I know no better book for reasoning than
Thinking Mathematically, by John Mason, Leone Burton and Kaye Stacey.
It is superb in inspiring action and instilling methods of reasoning. Quoting from the introduction:

Experience in working with students of all ages has convinced us that mathematical thinking can be improved by
● tackling questions conscientiously;
● reflecting on this experience;
● linking feelings with action;
● studying the process of resolving problems; and
● noticing how what you learn fits in with your own experience.

The authors delineate the process of thinking mathematically, presenting a rubric for attacking problems. This rubric does not mean a recipe, but a set of words designed to get you thinking and prompt you toward action (in the spirit of Polya's questions). However, the book does not explicitly deal with problems to prove, and for that I recommend two other books:
How to Prove It, by Daniel Velleman,
and
How to Think like a Mathematician, by Kevin Houston.
These two books combined will help students discuss and learn:

Logic (Sentential and Quantitative) - Velleman
Proof strategies (negations, conditionals, quantifiers, existence and uniqueness, contradiction, induction, etc) - Velleman and Houston
Relations - Velleman and Houston
Functions - Velleman and Houston
How to read definitions and theorems - Houston
Divisors, the Euclidean algorithm and modular arithmetic - Houston

I believe the combination of these three more will result in an overhaul in your students' thinking habits. Their abilities of reasoning will vastly improve.


Q:

Google Calendar App Script to pull Data into a Spreadsheet periodically

I've been using this script to pull Data from Google Calendar into a spreadsheet. I have a couple questions for improvements:

Is it possible to have this pull data from multiple calendars to the same spreadsheet without them overwriting each other?
Is it possible to have it add a new column of data to the spreadsheet that marks which calendar each row came from?
Also, how would you go about setting this up to run automatically every 24 hours?

THANKS!
function caltest3(){
  var ss = SpreadsheetApp.openById("SPREADSHEET ID");
  SpreadsheetApp.setActiveSpreadsheet(ss);
  var cal=CalendarApp.getCalendarById("CALENDAR ID");
  var sheet = SpreadsheetApp.getActiveSheet();

  var events = cal.getEvents(new Date("January 1, 2013"), new Date("January 13, 2013"));
for (var i=0;i<events.length;i++) {
  //http://www.google.com/google-d-s/scripts/class_calendarevent.html
      var details=[[events[i].getTitle(), events[i].getStartTime(),
                    events[i].getEndTime(), events[i].getDescription(),
                    events[i].getLocation()]];
  var row=i+1;
  var range=sheet.getRange(row+1,1,1,5);
  range.setValues(details);
    }
  }
}

A:

Short answers then an example:

You cannot do this with a single call to the CalendarApp, but if you loop through a list of calendarIds and add the resultant events for that calendar to an array, you can then sort this array and put this to the spreadsheet
Simply add the calendar name (or id) as another item in your details array, just remember to increase your range column count by 1
Add a script trigger to whatever period you want, the documentation describes this best.

Whether you are building an array of calendar events from multiple calendars or just one, adding them to an array in a loop and then writing them to the spreadsheet outside any loop is better practice than writing row by row as every time you call the getRange() & setValues methods they are separate API calls and these calls are most expensive in time for Apps Script. Call each only once with a range to suit your data and your script will run an order of magnitude quicker.
Script below illustrates answers 1 & 2. Your needs may vary if you are setting a timer to this as you may be wanting to affect the period of time you are querying?
function caltest3(){

  var ss = SpreadsheetApp.openById( 'spreadsheetId' ),
      sheet = ss.getSheetByName( 'sheetName' ),
      cals = ['id1', 'id2', 'id3'], c, cal, calName,
      start = new Date( 'whenever' ), end = new Date( 'whenever' ),
      events, i, details,
      eventslog = [], e,
      rows = [], range;

  for (c = 0; c < cals.length; c += 1) {

    cal = CalendarApp.getCalendarById(cals[c]);
    calName = cal.getTitle();
    events = cal.getEvents(start, end);

    // add the events of the current calendar to the array of all events
    eventslog = eventslog.concat(
      events.map(function(event) {
        return {
          time: new Date(event.getStartTime()).getTime(), // sort by this
          details: [
            event.getTitle(),
            event.getStartTime(),
            event.getEndTime(),
            event.getDescription(),
            event.getLocation(),
            calName // change calendar info position in array to suit
          ]
        };
      })
    );
  }

  // sort array of event so date order can be either way by reversing a & b
  eventslog.sort(function(a, b) { return a.time - b.time; });

  rows = eventslog.map(function(entry) { return entry.details; });

  range = sheet.getRange(2, 1, rows.length, 6);
  range.setValues(rows);
}

code spaced out for clarity


Q:

Change default rule type in SonarQube 6.4

Is there a way to change the type for rules existing in SonarQube 6.4 (not custom rules). For example, can I change an existing rule from a bug to a vulnerability or a code smell etc.. ?
Thanks in advance

A:

Sorry, rule type is not settable, although as @Simon pointed out, you can change the type of an issue.


Q:

WPF loading panel and UI freeze

I have a mainwindow which displays a 'Please wait' panel containing a loading gif whenever I do some work in a Task. The gif plays fine when the data is being compiled, but when the INPC logic to refresh the UI controls is being executed (thus on the main UI thread), the app freezes for a split second and my gif does not play smoothly anymore.
For instance, I am following the MVVM pattern, I have a datagrid in my view which is binded to an ObservableCollection MyBindedCollection. In the constructor of my viewmodel which runs in a Task, I create a tmp observable collection and when the process is finished, I set the variable MyBindedCollection to tmp (thus not adding one by one my items to it). The INPC logic is of course in the setter of my property MyBindedCollection.
Is there anyway to prevent this? any idea would be appreciated.

A:

@ZoolWay yes, no way around that I'm affraid. I'll just fade out my wait panel and thread.Wait enough time for the animation to finish before displaying my content. Thus it'll appear smooth. Thanks for your time.


Q:

EntityWrapper Confusion

WPF
Entity Framework 6.0
Database first, entities are generated by TT file.
I'm having some problems with EntityWrapper, and can't find any useful information about it.
I have some entities, that when generated looks like this:
//generated code
public partial class scm_SupplierDepot : IPartsEntity, INotifyPropertyChanged
{
    [...]
    public virtual dms_Address dms_Address { get; set; }
}

public partial class dms_Address : IPartsEntity, INotifyPropertyChanged
{
    //shortened for brevity
    public System.Guid AddressId  { get; set; }
    public string StreetNumber  { get; set; }
    public string StreetName  { get; set; }
    public string ApartmentNumber  { get; set; }
    public string City  { get; set; }
    public string StateProvince  { get; set; }
    public string PostalCode  { get; set; }
    public string HouseName  { get; set; }
    public string Country  { get; set; }
    public string Address2  { get; set; }
    public string County  { get; set; }

    //INotifyPropertyChanged
    [..]
}

I extend the address class slightly with an interface:
public partial class dms_Address : IAddress {  }

public interface IAddress
{
    String StreetNumber { get; set; }
    String StreetName { get; set; }
    String ApartmentNumber { get; set; }
    String Address2 { get; set; }
    String City { get; set; }
    String StateProvince { get; set; }
    String PostalCode { get; set; }
    String County { get; set; }
    String Country { get; set; }
}

I am having some confusion and issues around getting the dms_Address entity from the scm_SupplierDepot entity. In most cases I can cast the Depot.dms_Address as IAddress and work with the entity with no issues.
But when I try binding this object to a Custom Control, the actual object that the control receives is a EntityWrapper< dms_Address > or EntityWrapperWithoutRelationships< dms_Address >
I had to make my control's dependency property accept an object, rather than an IAddress as I would prefer. Now I cannot work with the object as it will not cast to IAddress. I can't even cast it to EntityWrapper as I can't figure out the correct namespace to include.
    public static readonly DependencyProperty AddressProperty = DependencyProperty.Register("Address", typeof(object), typeof(AddressForm), new FrameworkPropertyMetadata(null, AddressChanged));
    public object Address
    {
        get { return (object)GetValue(AddressProperty); }
        set { SetValue(AddressProperty, value); }
    }

More information about my Custom Control and this Dependency Property issue can be read in a previous question: WPF Custom Control: DependencyProperty never Set (on only 1 of many properties)
Questions:

Can anyone explain to me what is going on here?
I don't understand where this wrapper is coming from. How can I make it go away?
How can I get the control to receive the IAddress instead of the wrapper?
Or how can I cast the EntityWrapper object to IAddress so I can access the properties in code? (oddly enough the template bindings work fine)

A:

I figured out how to do what I needed by using Reflection.
        Type objectType = Address.GetType();
        Type iAdd = objectType.GetInterface("IAddress");

        if (iAdd != null)
        {
            PropertyInfo info = objectType.GetProperty("StateProvince");
            if (info != null)
            {
                string currentProvince = info.GetValue(Address) as string;

                if (currentProvince != newValue)
                    info.SetValue(Address, newValue);
            }
        }

I am still stumped on why I'm seeing this behaviour; if it has the interface, why can't I cast it?
Type iAdd = Address.GetType().GetInterface("IAddress"); //iAdd is not null,
IAddress IA = (Address as IAddress); //IA is null

.
In the end I managed to switch my code around to make all of this code unnecessary >.<


Q:

What is the criteria that Android depends on to join contacts from different accounts?

I'm synchronizing my contacts from many accounts (Hotmail, Facebook, Gmail), everything have worked well and the OS has joined (or shows them as one) the accounts that refer to the same person. But not all accounts, since some accounts have not been joined although both accounts have the same name and one email exists in both as well.
I wonder what is the criteria that Android depends on to join the accounts?
Note: I do know that I can join them by myself in the contants list, but I would let it know them by itself.

A:

Raw contacts are joined according to rules described at Using the Contacts API:

Two raw contacts are considered to be a match if at least one of these
  conditions is met:

They have matching names.
Their names consist of the same words but in different order (for example, "Bob Parr" and "Parr, Bob")
One of them has a common short name for the other (for example, "Bob Parr" and "Robert Parr") One of them has just a first or last name and it matches the other raw contact. This rule is less reliable, so it only applies if the two raw contacts are also sharing some other data like a phone number, an email address or a nickname (for example, Helen ["elastigirl"] = Helen Parr ["elastigirl"])
At least one of the two raw contacts is missing the name altogether and they are sharing a phone number, an email address or a nickname (for example, Bob Parr> [incredible@android.com] = incredible@android.com).

When comparing
  names, the system ignores upper/lower case differences (Bob=BOB=bob)
  and diacritical marks (Hélène=Helene). When comparing two phone
  numbers the system ignores special characters such as "*", "#", "(",
  ")", and whitespace. Also if the only difference between two numbers
  is that one has a country code and the other does not, then the system
  considers those to be a match (except for numbers in the Japan country
  code).
Automatic aggregation is not permanent; any change of a constituent
  raw contact may create a new aggregate or break up an existing one.

There is also explicit aggregation, that can be set for raw contacts, if a user explicitly wants two contacts to be joined. Read more about it in the article.


Q:

How to flatten string encoded json with jq?

Hi I have the following json.
[
    {
        "myfield1": "foo",
        "myfield2": "{\"field1\":6366987, \"field2\":5501072}"
    },
    {
        "myfield1": "bar",
        "myfield2": "{\"field1\":123456, \"field2\":123456}"
    }
]

And would like to get...
[
    {
        "myfield1": "foo",
        "field1": 6366987,
        "field2": 5501072
    },
    {
        "myfield1": "foo",
        "field1": 123456,
        "field2": 123456
    },
]

So far I got this...
jq '[.[0] | {myfield1: .myfield1, myfield2: .myfield2|fromjson}]'
But this means I have to specify each json field plus it doesn't flatten the json encoded string.
Edit:
I think I got it with this...
jq '[.[0]|with_entries(select(.key != "myfield2"))+(.myfield2|fromjson)]'
Does it make sense?

A:

You're right that the solution involves fromjson, but a simpler, more direct, and more efficient approach would be as follows:
map( { myfield1 } + ( .myfield2 | fromjson ) )

If you want to retain all the fields except "myfield2", consider:
map( del(.myfield2) + ( .myfield2 | fromjson ) )


Q:

Underscore does not generate HTML

The following code is not generating the HTML.
Underscore template:

JSON:
{
    "features": {
        "status": true,
        "response": {
            "predictions": [
                ["shirt", "90.12"],
                ["jeans", "09.88"]
            ]
        }
    }
}

jQuery code:
var predictions = [];

_.each(response.features.response.predictions, function(prediction, i) {
     predictions.push({
          prediction: prediction[0],
          score: prediction[1]
     });
});

var tpl = _.template(featureTemplate, predictions));

console.log( tpl);

I can see the predictions array is created with values.
Why doesn't this code generate proper HTML?

A:

I tested with the latest version of underscore (1.8.3), other versions may have differences.
The documentation of _.template says that the data is given after the compilation of the template:
var compiled = _.template(featureTemplate);
var tpl = compiled({predictions:predictions});

I also added a foreach loop in the template:


Q:

Who is the first human to be assimilated by the Borg?

Was the family of seven of nine the first humans to be assimilated in the 2350s? Was it because of them that the Borg first learnt about humanity?

A:

Chronologically, no. The first humans assimilated by Borg were crew members of Picard's Enterprise-E on  April 5, 2063 ("Star Trek: First Contact"); after the Borg jumped back in time to prevent First Contact between Vulcans and Humans as a result of Cochrane's first Warp flight, and Enterprise followed the Borg Sphere to prevent that.
Next incident was from the same time discrepancy - in 2153, the remains of Borg Sphere that Enterprise destroyed were found and thawed out Borg assimilated the research team
The next one was 2356 assimilation of the Raven, with Hansen family aboard.
More details on Memory Alpha: http://en.memory-alpha.org/wiki/Human-Borg_history


Q:

Creating relationships in neo4j

I have done a lot of reading by I can't seem to find the answer on this. If there's a duplicate post somewhere please point me to it!
Anyways, here it goes.
I'm trying to import data into Neo4J and create the relationships in order to easily graph the data. I was able to import the data without a problem using the LOAD CSV WITH HEADERS command now I'm not sure how to create the relationship piece.
My CSV/Table looks like this
source  target  action
172.x.x.x   172.y.y.y  accept
172.x.x.x   172.y.y.y  drop

All the data ends up in the same database and "table"
My goal is to have the following relationship scheme:
"Source"-------[action]------->"Target"

My first attempt was:
START n=node(*)
WHERE HAS(n.source) AND HAS(n.destination)
CREATE (n)-[:CONNECTS_TO]->(n)

I could not see the relationship at all after running this even though the browser shell said that it did create them and besides this does not take care of the "action" piece.
Any help would be appreciated.

A:

You can load CSV into Neo4j by using following command
 load csv with headers from "file:///file_path" as input
 match (from:Node {source: input .source}),(to:Node {target:input.target})
 create (from)-[:RELATION  {type: input.action }]->(to)

*Note: You have to mention your lable name in the above query by replacing "Node".


Q:

What is the distinction between ALL_PROCEDURES and DBA_PROCEDURES, and other schema tables?

I recently failed to find a known procedure when searching ALL_PROCEDURES, and on a whim tried DBA_PROCEDURES: lo, there it is.  The doc pages (ALL_; DBA_) both say "...lists all functions and procedures along with their associated properties."  Oracle seems to have a curious definition of "all".
I'm posting this on DBA rather than SO, though it's a pretty basic question, on the basis that schema management is generally a DBA role rather than a developer role.

A:

From here
USER_TABLES describes the relational tables owned by the current user.
ALL_TABLES describes the relational tables accessible to the current user.
DBA_TABLES describes all relational tables in the database.

Accessible != all!


Q:

adding gradient to UIView in drawRect

I am trying to add a CAGradientLayer in my drawRect, the code is the following:
- (void)drawRect:(CGRect)rect {

    CAGradientLayer *gradientOverlay = [CAGradientLayer layer];
    CGColorRef grayColor = [UIColor colorWithRed:37/255.f green:37/255.f
                                            blue:37/255.f alpha:1.0].CGColor;
    CGColorRef blueColor = [UIColor colorWithRed:23.0/255.0 green:171.0/255.0
                                            blue:219.0/255.0 alpha:1.0].CGColor;
    gradientOverlay.colors = [NSArray arrayWithObjects:
                              (id) grayColor,
                              (id) grayColor,
                              (id) blueColor,
                              nil];
    gradientOverlay.locations = [NSArray arrayWithObjects:
                                 [NSNumber numberWithFloat:0],
                                 [NSNumber numberWithFloat:0.4],
                                 [NSNumber numberWithFloat:1],
                                 nil];

    CGPoint startPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMidY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMaxX(rect), CGRectGetMidY(rect));

    gradientOverlay.startPoint = startPoint;
    gradientOverlay.frame = self.bounds;
    gradientOverlay.endPoint = endPoint;

    self.layer.mask = gradientOverlay;

}

Any idea why this is not working?

A:

Add your CAGradientLayer as a sublayer of your self.layer.

Note: If you're doing it in the drawRect: method make sure you're not adding a new CAGradientLayer every time drawRect: is called.
UPDATE (regarding the comment):
Here's the code for what you're asking:
    //Create a layer that holds your background image and add it as sublayer of your self.layer
    CALayer *layer = [CALayer layer];
    layer.frame = self.layer.frame;
    layer.contents = (id)[UIImage imageNamed:@"background.png"].CGImage;
    [self.layer addSublayer:layer];

//Create your CAGradientLayer
    CAGradientLayer *gradientOverlay = [CAGradientLayer layer];
    CGColorRef grayColor = [UIColor colorWithRed:37/255.f green:37/255.f
                                            blue:37/255.f alpha:1.0].CGColor;
    CGColorRef blueColor = [UIColor colorWithRed:23.0/255.0 green:171.0/255.0
                                            blue:219.0/255.0 alpha:1.0].CGColor;
    gradientOverlay.colors = [NSArray arrayWithObjects:
                              (id) grayColor,
                              (id) grayColor,
                              (id) blueColor,
                              nil];
    gradientOverlay.locations = [NSArray arrayWithObjects:
                                 [NSNumber numberWithFloat:0],
                                 [NSNumber numberWithFloat:0.4],
                                 [NSNumber numberWithFloat:1],
                                 nil];

    CGPoint startPoint = CGPointMake(CGRectGetMinX(rect), CGRectGetMidY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMaxX(rect), CGRectGetMidY(rect));

    gradientOverlay.startPoint = startPoint;
    gradientOverlay.frame = self.layer.frame;
    gradientOverlay.endPoint = endPoint;
//set its opacity from 0 ~ 1
    gradientOverlay.opacity = 0.6f;
//add it as sublayer of self.layer (it will be over the layer with the background image
    [self.layer addSublayer:gradientOverlay];

Note: You don't have to do this in drawRect: method. Create your layer hierarchy in the init method for example, if you need to change the geometry of some views/layers override the layoutSubviews method.


Q:

web api method to return data in json format?

I am making a web api call and I want the controller method to return data in json format.
The model class I used is User.cs :
public partial class User
{
     public int UserID { get; set; }
     public string city { get; set; }
     public string email { get; set; }
     public string firstName { get; set; }
     public string lastName { get; set; }
     public string phone { get; set; }
     public string password { get; set; }
 }

I want to return all the users email data in json format through the following controller method.
public string GetUsers()
{
   IEnumerable<User> users = db.Users.ToList();
   var jsonSerialiser = new JavaScriptSerializer();
   var json = jsonSerialiser.Serialize(users);
   return json;
   //string json = JsonConvert.SerializeObject(users);
   //return json;
}

All I am getting is empty json like:
[]

Please help. I have covered all the methods recommended on stackoverflow.

A:

This is a lot simpler than you think, you do not need to use a jsonSerializer.
You can change your method to the following:
public List<string> GetEmails()
{
    return db.Users.Select(e => e.email).ToList();
}

Then if the client specifies application/json the content is returned as json.
Please note with the above, I am only sending back the email address and not the full user details as I very much doubt you will want to send passwords out as json.


Q:

How can I query a Salesforce object to return only specific fields (columns)?

I created a connection with Salesforce. Selected the Account object which has 100s of fields (we've maxed out the allowed number of fields). This errors out with the error below (Requested URI Too Long).
This works fine on smaller tables.
Is there a way to create a custom query that selects only the fields (columns) I want? Either by modifying the automatically-generated query:
let
    Source = Salesforce.Data("[salesforce URL]", [CreateNavigationProperties = true]),
    Account1 = Source{[Name="Account"]}[Data]
in
    Account1

OR by modifying the actual SOQL request that is sent to Salesforce?
Here's the error
DataSource.Error: Web.Contents failed to get contents from '[salesforce URL]/services/data/v29.0/query?q=SELECT%20Id%2CIsDeleted%2C<MANY ADDITIONAL FIELDS DELETED>(414): Request-URI Too Long
Details:
    DataSourceKind=Salesforce
    DataSourcePath=[Salesforce URL]
    Url=[Salesforce URL]/services/data/v29.0/query?q=SELECT%20Id%2CIsDeleted%2C<MANY ADDITIONAL FIELDS DELETED>Product_Interest__c%2CFea...

A:

Table.SelectColumns should fold for Salesforce, so see if this works:
let
    Source = Salesforce.Data("[salesforce URL]", [CreateNavigationProperties = true]),
    Account1 = Source{[Name="Account"]}[Data],
    Account2 = Table.SelectColumns(Account1, { "First Column", "Second Column" })
in
    Account2


Q:

Given that $\binom{n+1}{r-2}=28$, find $(n-7)!$

Is there a neat analytic way to solving a problem like this?

If $\dbinom{n+1}{r-2}=28$, find the value of $(n-7)!$

Assume $n,r\in\mathbb{N}$ with $0\le r\le n+1$.
An easy way to do it would be to memorize or construct Pascal's triangle to find out that the first instance of $28$ in the array for $\dbinom jk$ occurs when $j=8$, and so for this problem $n+1=8\implies n=7$ (and $r-2=2$ or $r-2=6$, so that $r=4$). Then finding $(n-7)!$ is trivial. But I don't particularly like relying on rote memorization or table construction.
I was wondering if this would be doable with the recursive formula $\dbinom j{k-1}+\dbinom jk=\dbinom{j+1}k$. It seems to me that the argument $r-2$ complicates any attempt to decompose $\dbinom{n+1}{r-2}$ into simpler coefficients but I wouldn't know where to begin. I suspect a clever manipulation of the factorial formula might also be useful, though nothing immediately comes to mind.

A:

As $\binom{m}{k}$ is a product and quotient of numbers $\le m$, and the prime $7$ divides $28$ we get that $7 \le n+1$.
Now, the fact  $\binom{m}{1}= m$ always yields a trvial solution, also $\binom{m}{m-1}=m$ but this is excluded.
Ignoring the extremal cases $m=0,1,m-1,m$ we have $\binom{m}{k}\ge m(m-1)/2$.
Then $m(m-1)/2 \le 28$ yields $m \le 8$. Thus $7 \le n+1 \le 8$. And one is pretty close to having found your solution.


Q:

SQL update site url and domain for wordpress

Can you help me on my sql code?  It gives me a red line under under replace.
UPDATE wp_options SET option_value = replace(option_value, 'http://olddomain.com', 'http://newdomain.com') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'http://olddomain.com','http://newdomain.com');

UPDATE wp_posts SET post_content = replace(post_content, 'http://olddomain.com', 'http://newdomain.com');

UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://olddomain.com', 'http://newdomain.com');

A:

Put "Where" clause in your sql
You can try it
UPDATE wp_options SET option_value = replace(option_value, 'http://olddomain.com', 'http://newdomain.com') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'http://olddomain.com','http://newdomain.com') where guid>0;

UPDATE wp_posts SET post_content = replace(post_content, 'http://olddomain.com', 'http://newdomain.com') where ID>0;

UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://olddomain.com', 'http://newdomain.com')  where meta_id>0;


Q:

How to cd to a folder with two dots in the path

I am removing some files on my CentOS server which a virus scan has deemed to be infected.
Two of the files have ".." in the path. I understand that normally .. is how we navigate up to the parent directory. In this case the two dots seem to be part of the actual path.
For example, if the path of the file is:
/var/lib/mysql/mysql/..\bin\cna12.dll

Then I can cd to:
/var/lib/mysql/mysql/

If I then type cd and press tab twice, I am offered the option to autocomplete to several options. One of the options is:
..\bin\cna12.dll

See it in this pasted text (notice it in the first column):
..\bin\cna12.dll                    help_topic.frm                      slow_log.CSV
columns_priv.frm                    help_topic.MYD                      slow_log.frm
columns_priv.MYD                    help_topic.MYI                      tables_priv.frm

Normally I can type a few characters of the autocomplete suggestions and press tab again to bring the autocomplete to completion... but I can't seem to select it to, uh, complete the autocomplete.
Nothing I do seems to work. Including putting it in quotes such as:
cd "..\bin\"

Note that Linux slashes are this way, "/", while the above cited slashes are Windows style "\".
How do I cd to the bin directory so I can erase that .dll file?

A:

I don't believe that is an actual directory, I suspect that that is just a file with backslashes. Try deleting that file directly and it should be removed.
This will work: rm '..\lib\plugin\amd.dll'
I am also not sure how smart cd is on a CentOS system, it might only show autocomplete options for directories only. In which you would have to do rmdir '..\lib\plugin\amd.dll' (assuming it is empty). You can determine this by running ls -l in the /var/lib/mysql/mysql/ directory and seeing if that is a file or a directory and then issue the correct command accordingly.
On a Linux system the backslahes are just treated as characters in the file name and not directory separators. Therefore there is no special distinction when using them in the context of directories. Backslashes are typically used as escape characters for special characters.

A:

There are two problems.  You don't say what you're typing before autocomplete, which complicates matters, and you're behaving as if that's a file in another directory, which it's not - backslashes aren't path separators in unix, as you've noted, they're just characters in a filename.
As for the second, stop trying to cd.  Shell won't autocomplete that filename to cd, whatever you do, because it's not a directory.  The file is in ., just rm it.
As to the first, you can't just type .. to autocomplete, as that's not an unambiguous match (the directory also contains .., as it must).  You can't just type ..\ to autocomplete, because backslash is a metacharacter which escapes the one that follows it, and shell doesn't know what that is - it could be anything, or nothing.  If, however, you type
rm ..\\

then hit TAB (assuming this is bash), then the filename should get filled in correctly.  I just tried it, and it worked for me (bash 4.3.42(1) under Fedora 22).


Q:

Simulate the switch comportment in template specialization

Here is the following code that shows a design I use. I made a wrapper class that encapsulates a template class. A method of the wrapper permits with a switch to choose the specialization I want :
#include <memory>
#include <string>

/* Interface
 */
struct IFoo
{
    virtual void lol(void) = 0;
};

/* Template Specialization
 */
template<std::size_t N>
class Foo : public IFoo
{
    void lol(void) {}
};

/* Wrapper for the template
 */
class FooWrapper : public IFoo
{
    std::unique_ptr<IFoo>   mfoo;

    public:
    void setSize(std::size_t size)
    {
        switch (size) // how to 'simulate' this switch comportement
                      // with min/max constexpr variables ?
        {
            case 1u:
                mfoo = std::make_unique< Foo<1u> >();
                break ;
            case 2u:
                mfoo = std::make_unique< Foo<2u> >();
                break ;
            case 3u:
                mfoo = std::make_unique< Foo<3u> >();
                break ;
            default:
                throw std::runtime_error(std::to_string(size) + " not supported.");
        }
    }

    FooWrapper(std::size_t size)
    {
        this->setSize(size);
    }

    void lol(void)
    {
        mfoo->lol();
    }
};

int main(void)
{
    FooWrapper  a(3u);  // ok
    a.setSize(2u);      // ok
    a.setSize(0u);      // will throw an exception at runtime

    return EXIT_SUCCESS;
}

Is it a way to have the same comportment, but using minimum and maximum constexpr values, and an automated version of the switch that loops on the range and does the good template for each value ?
Edit: I am searching for a runtime solution, since the parameter of setSize must be chosen by users through a GUI.

A:

As with all template metaprogramming problems, somehow index_sequence is involved. In this case, build up an inindex_sequence of the values you accept for the template parameter on Foo and iterate over them. For simplicity, here's a version that uses 0 as a minimum and 4 as a maximum:
template <std::size_t... Is>
std::unique_ptr<IFoo> create(std::size_t N, std::index_sequence<Is...> ) {
    std::unique_ptr<IFoo> mfoo;

    using swallow = int[];
    (void)swallow{0,
        (void(N == Is ? mfoo = std::make_unique<Foo<Is>>() : mfoo), 0)...
    };

    return mfoo;
}

std::unique_ptr<IFoo> create(std::size_t N) {
    return create(N, std::make_index_sequence<4>{} );
}

create(N) will either give you a Foo<N> (if 0 <= N < 4) or an unset unique_ptr. If it gives you back nothing, you can just throw:
void setSize(std::size_t size) {
    auto new_foo = create(size); // or call with index_sequence
    if (!new_foo) {
        // throw
    }

    mfoo = std::move(new_foo);
}

I'll leave generating index_sequence<1, 2, 3> as an exercise.


Q:

Using LINQ2SQL and MVC for wizard-type save functionality

I have an ASP.NET MVC application that uses LINQ2SQL as the database layer.  I can save data back to the database no problem but I've came across a few issues when trying to save using a wizard-type scenario where data is collected over a few different forms but not saved to the database until the last form "Save" button is clicked.
At first I tried adding new objects to the datacontext, using InsertOnSubmit() or DeleteOnSubmit() and on the final page using SubmitChanges() to commit to the database.  The problem with this is that if I tried to DeleteOnSubmit() an object that hadn't been submitted yet I would get an error.
I got round it eventually by writing a lot of code to manage the state of each object (insert, update or delete) and then on the final submit I make all changes to the DataContext before saving.
I'm wondering if there is a better way of managing the state of objects across pages using LINQ2SQL or if the manual code is the best way round it?

A:

If you use TempData["key"] = data; you can pass data between redirections.
It uses session state but that can be overriden using you own provider that implements ITempDataProvider (probably the default will work you though!)
I'd build object through wizard and then do one SubmitChanges() in last page of wizard.
Kindness & HTH,
Dan


Q:

Fibonacci sequence Javascript do while loop

I have been going through various threads and languages on this topic but I do not seem to find a solution for setting a bar for a fibonacci sequence to stop below 100 with a do while loop in Javascript.
var fbnci = [0, 1];
var i = 2;

do {
   // Add the fibonacci sequence: add previous to one before previous
   fbnci[i] = fbnci [i-2] + fbnci[i-1];
   console.log(fbnci[i]);
   fbnci[i]++;
}
while (fbnci[i] < 100);

For some reason, the code above only runs once. What should I set the while condition to in order to keep printing the result until it reaches the closest value to 100?

A:

You have an error in the code, it should be :
var fbnci = [0, 1], max = 100, index = 1, next;
do {
  index++;
  next = fbnci[index-2] + fbnci[index-1];
  if (next <= max) {
      console.log(next);
      fbnci[index] = next;
  }
} while(next < max);

Solution that prints all fib numbers that are lower than max.


Q:

VM migration and IP address

When a VM offering a service is migrated to a different server is it an important requirement from the client applications point of view to retain the same IP the VM had before ?
For long lived TCP sessions it won't make a difference because the connection will be reset anyway. But with web based services typically the TCP sessions are not long lived. So the VM retaining the IP on a migration can significantly reduce the downtime for client applications.

A:

Since you tagged the question with vmware-esxi, I presume you're referring to VMware's VMotion live migration.
With VMotion, you do not need to worry about this - all network sessions will remain valid throughout the migration.


Q:

Powermockito: using thenReturn efficiently

I have mocked a method called methodA().
I have a linked list called linkedListA.
Now,
i have a line of code to mock the return of methodA, as such
when(methodA()).thenReturn(linkedListA.get(0)).thenReturn(linkedListA.get(1)).thenReturn(linkedListA.get(2)) and so on
Now, is there a more efficient/cleaner way to write all the thenReturns, for instance, like in a loop? So, that I do not have to write tons of thenReturns
Thanks

A:

I think the first improvement would be to use this:
when(methodA()).thenReturn(linkedListA.get(0), linkedListA.get(1), linkedListA.get(2)) and so on

Moreover, you could you the thenAnswer method to return a value:
final AtomicInteger i = new AtomicInteger(0);
when(methodA()).thenAnswer(new Answer<YourType>() {

 @Override
 public YourType answer(InvocationOnMock invocation) {
     return linkedListA.get(i.getAndIncrement());
 }
});

Example:
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Blub.class)
public class Mockexample {

@Test
public void test() {
    Blub blub = PowerMockito.mock(Blub.class);
    final List<Integer> counter = Arrays.asList(1, 2, 3);
    final AtomicInteger i = new AtomicInteger(0);

    // blub.size() is final, only reason to use PowerMockito here
    when(blub.size()).thenAnswer(new Answer<Integer>() {

        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            return counter.get(i.getAndIncrement());
        }

    });
    System.out.println(blub.size());
    System.out.println(blub.size());
    System.out.println(blub.size());
}

}

The Blub clas:
public class Blub {
 public final int size() {
    return 0;
 }
}


Q:

How to make a join with two tables with django-tables2

Can anyone provide a clear example of how to show a table using django-tables2 that selects and presents data from two(or more) related models?
I've found lots of posts about that, most of them quite old, and none really a working example.
These are my models:
class Person(models.Model):
    name = models.CharField(verbose_name="Name",max_length=50)
    fname = models.CharField(verbose_name="F.Name",max_length=50)

class Speech(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    said = models.CharField(verbose_name="Said",max_length=50)

I simply want to show a table with columns "Name, F.Name, Said". Which is the best way? And with multiple tables?
Thanks in advance.

A:

Well, nobody answered my question. After digging and trying I found a way to show fields from related models in one table. The thing is the table definition into tables.py should be like this:
class SpeechTable(tables.Table):
    name = tables.Column(accessor='person.name')
    fname = tables.Column(accessor='person.fname')
    said = tables.Column()
    class Meta:
        attrs = {"class": "paleblue"}

Not sure if this is the best way, but it is simple and works fine.


Q:

WPF navigation using MVVM

I want to know some things regarding navigation using MVVM.

Q1: Clicking in the Login Button if the authentication is ok, I want to open a completely new window, how I can do this without loosing the MVVM pattern. (I know the simple approach NewWindow w = new NewWindow(), show & hide and its ok) but this is so terrible that I have nightmares thinking about it. How can I do it?
Q2: The recovery button I want to completely reshape the login page, two have new text boxes and two buttons (submit recovery and cancel) using cancel I want to show the login again. How can I do it?
What I know: having two buttons in the same MainView and loading different views but the buttons have to stay there like a web page (this is a desktop app in the first iteration, will evolve to mobile as well).
Best regards,

A:

WPF/XAML is an extraordinary technology, there are many ways to do the same thing and even the simplest of explanations is too complicated to deliver on a forum like SO. To fully understand WPF, MVVM and XAML you need to look at example code and lots of it, you need to pick it apart and see how its working then modify it to do something else, strip parts out to implement in your own code and follow tutorials. Only by doing that 24/7/52 can you expect to become familiar with it.....
I'm not going to post any code here coz there is just too much. So here is a download to just about the simplest example I could come up with
http://www.mediafire.com/download/3bubiq7s6xw7i73/Navigation1.rar
the example is a modification of Rachel Lim example. It  simply contains Views and ViewModels, there are no Models or data. It demonstrates switching between two different Views. Download and un-RAR it (with win RAR) You will need to step though the code, figure out what its doing and how its doing it then modify it to suit your needs... Or modify your needs to suit the code.....
Maybe as your first task, Using my example code from the download link, you should try to add a third view plus code\Button to switch between three views....
Good luck


Q:

Linking FlexBox to Visual Studio Code

Im starting to learn about flexbox / Bootstrap with visual studio  code but I wonder how can I link flexbox to visual code , is it an extension ? when I searched for it it showed a flexbox cheatsheet only . Thanks !:)

A:

The CSS property flex is part of standard CSS, not a framework like Bootstrap.
The term 'Flexbox' simply refers to CSS 'Flexible Box Layout'. Hence there is nothing for you to link to in Visual Studio Code.
For more details about flex refer to Mozilla's CSS reference >>> https://developer.mozilla.org/en-US/docs/Web/CSS/flex


Q:

Get ID after inserting Item into SharePoint 2013 Host Web List

I am currently creating a SharePoint 2013 hosted app on Office 365 and I currently have some JavaScript that inserts item into a host web list.
I wondering if it is possible to get the ID of the item that has just been created in the list using the current JavaScript code:
function Sumbit() {
$('#submitBtn').click(function () {
    var ctx = new SP.ClientContext(appweburl);
    var appCtxSite = new SP.AppContextSite(ctx, hostweburl);

    var web = appCtxSite.get_web();
    var List = web.get_lists().getByTitle('List Title');

    var itemCreateInfo = new SP.ListItemCreationInformation();
    var ListItem = List.addItem(itemCreateInfo);

    ListItem.set_item('Title', $('#title').val());
    ListItem.set_item('Description', $('#Description').val());

    ListItem.update();

    ctx.load(ListItem);

    ctx.executeQueryAsync(
        Function.createDelegate(this, QuerySucceeded),
        Function.createDelegate(this, QueryFailed));
});
}

function QuerySucceeded(sender, args) {
console.log("success");

 }

function QueryFailed(sender, args) {
console.log(args.get_message() + '\n' + args.get_stackTrace());

}

I have tried getting the ID inside of the 'QuerySucceeded' function by using:

ListItem.get_id();

However this was returning '-1' any help with this would be greatly appreciated.

A:

May be you should try declaring your ListItem variable globally, what I can see from your code is that it is local to Submit function. Refer below code change.
// Declared globally which can be accessible in other functions as well
var ListItem = null;

function Sumbit() {
    $('#submitBtn').click(function () {
        var ctx = new SP.ClientContext(appweburl);
        var appCtxSite = new SP.AppContextSite(ctx, hostweburl);

        var web = appCtxSite.get_web();
        var List = web.get_lists().getByTitle('List Title');

        var itemCreateInfo = new SP.ListItemCreationInformation();
        ListItem = List.addItem(itemCreateInfo);

        ListItem.set_item('Title', $('#title').val());
        ListItem.set_item('Description', $('#Description').val());

        ListItem.update();

        ctx.load(ListItem);

        ctx.executeQueryAsync(
            Function.createDelegate(this, QuerySucceeded),
            Function.createDelegate(this, QueryFailed));
    });
}

function QuerySucceeded(sender, args) {
    console.log("success");
}

function QueryFailed(sender, args) {
    console.log(args.get_message() + '\n' + args.get_stackTrace());
}


Q:

gcloud Datastore transaction issue using nodejs

I am using nodejs to contact the google datastore. This is my code:
dataset.runInTransaction(function(transaction, done,err) {
                    // From the `transaction` object, execute dataset methods as usual.
                    // Call `done` when you're ready to commit all of the changes.

                    transaction.save(entities, function(err) {

                        if(err){
                            console.log("ERROR TRNASCTION");
                            transaction.rollback(done);
                            return;
                        }else{
                            console.log("TRANSACTION SUCCESS!");
                            done();
                        }

                    });

                });

If the save was not successful, I would like the transaction to rollback and if it was I want it to commit. The problem I am facing is that neither of them seem to be running, just no output on the console. Nothing is being sent to my database so I would assume at least the 'if(err)' condition would run but it doesn't. I am new to glcoud so I am not sure if I am doing something wrong here? I am following the doc at https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.26.0/datastore/transaction?method=save.

A:

In the context of a transaction, the save method doesn't actually need a callback. The things you wish to save are queued up until you call done(). Calling done will commit the transaction.
You can then handle errors from the commit operation in a second function passed to runInTransaction. See https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.26.0/datastore/dataset?method=runInTransaction for examples of that.
--
Just mentioning this since it relates to the rollback part: https://github.com/GoogleCloudPlatform/gcloud-node/issues/633 -- we're waiting on an upgrade to Datastore's API before tackling that issue.


Q:

Finding numbers in a command output and save it as variables

In a bash script, I wish to get some numbers from the output of a command and store them in variables. An example of the command output:
25 results [22 valid, 2 invalid, 1 undefined]

I would like to save the four numbers in the previous command-output as variables called results, valid, invalid, undefined.

A:

Since you want to store multiple separate values, I assume that you want to store them in an array:
$ str='25 results [22 valid, 2 invalid, 1 undefined]'

$ readarray -t arr < <( grep -E -o '[0-9]+' <<<"$str" )

This reads the output of grep into an array called arr. The grep command will output each separate number found in $str on its own line by matching the extended regular expression [0-9]+ against the string and extracting each match.  grep reads the string from a "here-string", and readarray reads the grep result using a process substitution.
The values may then be used as
$ printf 'value: %s\n' "${arr[@]}"
value: 25
value: 22
value: 2
value: 1

or, to look at individual values, use e.g. "${arr[0]}", "${arr[1]}", etc.  The array contains "${#arr}" values.
results=${arr[0]}
valid=${arr[1]}
invalid=${arr[2]}
undefined=${arr[3]}

To read directly from a command:
readarray -t arr < <( mycommand | grep -E -o '[0-9]+' )

A:

Let's say that the output of this command is saved in a file called output.txt, then you can use the commands awk and grep as follows:
results=$(grep results output.txt | awk '{print $1}')
valid=$(grep valid output.txt | awk '{print $3}' | tr -d [])
invalid=$(grep invalid output.txt | awk '{print $5}' | tr -d [])
undefined=$(grep undefinedoutput.txt | awk '{print $7}' | tr -d [])

Include these four lines in your bash where it fits.
Instead, you can only use awk to find a matching pattern, as follows:
results=$(awk '/results/{ print $1 }' output.txt)
valid=(awk '/valid/{ print $3 }' output.txt | tr -d [])
invalid=(awk '/invalid/{ print $5 }' output.txt | tr -d [])
undefined=(awk '/undefined/{ print $7 }' output.txt | tr -d [])

A:

Assuming your output is in a variable called output, you can split it with sed, keeping just the spaces and digits, to allow you easily split the "words" into an array:
tim@host:~$ res=($(sed 's/[^0-9 ]*//g' <<< $output))
tim@host:~$ printf "results: %s\nvalid: %s\ninvalid: %s\nundefined: %s\n" "${res[@]}"
results: 25
valid: 22
invalid: 2
undefined: 1


Q:

cisco router 1814 interface activation with single IP routing

i have this simple diagram below:

I need to make 192.168.55.1 talk with 10.0.2.59 by open the interface 0/1 [192.168.56.254]
by talk mean what is router commands required to open new interface and make the ip route ONLY route the 2 endpoints? let me say it in other words:the ip "192.168.55.1" should only ping/reach "10.0.2.59". if it try to ping any other host it should fail to reach it.
please provide the commands set ASAP. and excuse me if i used wrong terms to describe the requirements but it's been over 6 years since the last time i used to config routers.

A:

Do you have any routing setup already between the boxes?
You could do the following..
Router 1(left Side of diagram)
interface FastEthernet0/1
  ip address 192.168.56.253 255.255.255.252
  no shut

ip route 192.168.55.1 255.255.255.255 192.168.56.254

Router 2(right side)
interface FastEthernet0/1
   ip address 192.168.56.254 255.255.255.252
   no shut

ip route 192.168.2.59 255.255.255.255 192.168.56.253

Or you could just build the routes between them for the native subnets, and apply an access list between them (Which is probably the better solution if you expect more hosts to need to talk across
This examples assumes no access list 101, and  /24 networks.
Router 1(left Side of diagram)
interface FastEthernet0/1
  ip address 192.168.56.253 255.255.255.252
  ip access-group 101 in
  no shut

ip route 192.168.55.0 255.255.255.0 192.168.56.254
ip access-list 101 permit 192.168.55.1 255.255.255.255 192.168.2.59 255.255.255.255
ip access-list 101 deny any any

Router 2(right side)
interface FastEthernet0/1
   ip address 192.168.56.254 255.255.255.252
   ip access-group 101 in
   no shut

ip route 192.168.2.0 255.255.255.0 192.168.56.253
ip access-list 101 permit 192.168.2.59 255.255.255.255 192.168.55.1 255.255.255.255
ip access-list 101 deny any any


Q:

Are specific internet sites blocked in some countries?

Last month I was travelling in Croatia.
I was unable to access the Aeroplan website (Canadian air miles plan), the only way to change a flight booked on points.
To be clear, all computers that I tried failed to even go to the log-in site; so it was not a problem with my account.
Some program called Incapsula (?) seemed to be involved.
Access to the site was available in other geographical areas.
Any idea what was going on, if it might happen elsewhere, and how to avoid/circumvent it?

A:

Yes, some countries do have country-level filters, but they're usually quite obvious with error messages (for example, here's Singapore's), and they tend to target things like porn and political dissent, not frequent flyer mileage sites.
Incapsula appears to be content delivery network, so the most likely explanation is that Aeroplan uses them worldwide and they had some glitch specific to Croatia.  The only potential workaround is to use a VPN, so you appears to be connecting from somewhere else and may be able to connect.


Q:

Alternative for ternary operator in the case a ? a : b without repetition (JavaScript)

The scenario is the following: I want to return the value of a when a is defined and else I want to return b. I need an expression because of JSX.
I am looking for a better way to write the expression a ? a : b where a and b are variables. I was trying !a&&b. The problem is when a is defined, then it returns of course false instead of the value of a which I want to receive then. I think I have my wires crossed at the moment. If someone has an idea, I would highly appreciated it.

A:

You could take a default approach with a logical OR ||. This returns a, if this values is truthy, otherwise the default value of b.
a || b


Q:

Prevent trigger recursion

I have 2 triggers:
The first:
trigger AutoProduct on Opportunity (before insert,after insert) {

    for(Opportunity newOppt : Trigger.new){

           if  ((trigger.isBefore)&&(Trigger.isInsert)){

               // SET SOME FIELDS
                }

              opptsToInsert.add(newOppt);

            if ((Trigger.isAfter)&&(Trigger.isInsert)){
               //GET OPPORTUNITY
                //CREATE OPPORTUNITY LINE ITEM FOR EACH NEW OPPORTUNITY
                //CREATE OPPORTUNITY LINE ITEM QUANTITY AND REVENUE SCHEDULE FOR EACH NEW OPPORTUNITY PRODUCT
                          }

                   }

The second
trigger AutoProductupdate on Opportunity ( before update,after update) {

    for(Opportunity newOppt : Trigger.new){

           if  (trigger.isAfter){

                                 //DELETE OPPORTUNITY LINE ITEM SCHEDULES FOR ALL THE PRODUCTS
                                 // UPDATE OPPORTUNITY LINE ITEM

                                 // CREATE OPPORTUNITY LINE ITEM SCHEDULES FOR ALL THE PRODUCTS
                     }

             }

}

The problem is that when i insert an opportunity(execution first trigger) it's also executed the second trigger on update.
I want that on creation of an opportunity is only executed the first trigger.
How can avoid this?
Thank in advantage for any advice.
BR.

A:

A few initial points:
1. You don't need to have the line "opptsToInsert.add(newOppt);" in your before trigger. The before trigger will just fill the right values in the fields, and the system will do the DML anyway.
2. When you add OppLineItem records to an Opportunity, it affects the Opportunity (Roll-up amount to the Opp.Amount field) so an Opportunity trigger could fire.
Put in a recursion static boolean preventer so you don't execute the second trigger. To do that, search Google for "trigger prevent recursive firing" or something similar.


Q:

How can we be sure of the efficiency of a neural network

I trained a Forward Neural Net for binary classification and I got an accuracy of 83%, which (I hope)I'm going to improve later by changing parameters in inputs.  But some tests make me feel confused :

My dataset length is 671 so I divide it as 513 train set, 58 Validation set and 100 test set

When I change the size of my sets (Train, Validation, Test), the accuracy score can decrease to some very low scores like 40%
The neural net is supposed to learn from the train set but when I test, after the training, with the same Train set and not the Test set, I thought that the model should score 100 %, because he just learned from it, watched it, but it only improves a few with 87% ...

I'm a beginner in ML so I don't know if it's normal or not, I'm just curious and wanna catch all the small things to know, to understand perfectly what I'm doing. I guess it's maybe the normalization of my vectors sets, but I don't know very much about it. I can share you my full code if you want to, but as every neural net, it's quite long but easy to read.

A:

As suggested by many people 3:1:1 (60:20:20 = train-validate-test) ratio is a thumb rule to split data, if you are playing with small data set it better to stick with 80:20 or 70:30 just train-test,I usually go for 90:10 ratio for better results.
Before you start with classification, first check whether your data set is balanced or imbalanced ( there should not be less example belongs to one class as compared to other ) because even though it gives you good accuracy it will mislead the results.
If data set is imbalanced, pre-processed data set with sampling algorithm  (for e.g SMOTE) and re-sample it. It will create equal sets of examples for class based on neighbors.
As correctly mentioned in other answer, use cross validation classification such as K-fold. The concept of cross validation is done to tweak the parameters used for training in order to optimize its accuracy and to nullify the effect of over-fitting on the training data, it also remove the noise in data set. I usually go for 10-fold cross validation where data set divided in 10 partition and in each iteration 1/10 partition use as test and rest as training. Take the average of the 10 computations to get a good estimate of the performance of your classifier.


Q:

static variables in php

hello I am using zend framework and i am trying to combine it with doctrine. Not the hardest thing to do but what I wanted to do is a class with a static member that will be the entity manager and I want to create it just ONCE in THE WHOLE APPLICATION CONTEXT.
When I was playing with static variables in php to learn how it works in order to do what I want I realize that php creates a new instance of a static variable in each request. So the static variable only remains static through the request not the entire application is that correct, can someone tell how to do static variables for the whole application no matter the request that came to the server.

A:

You can't do this with PHP directly, you'd need some kind of persistence, like serializing the object and saving it in a database, and even then, you're going to run into a lot of concurrency issues.
PHP not only creates a new instance of each static variable for each request, it basically runs your entire application with each request. In fact, assuming you're running a web server like apache, it's running more than one instance of your application at once, since apache is capable of handling mutiliple requests at once. So even if you were able to serialize an object to a some sort of persistence like a database, you'd probably be overwriting changes that another instance of your application had made to it.


Q:

Is it ok to Mention company name in answer or question?

I come across a question where a person mention his company name in answer.
Name of company has nothing to do with answer.
But a question come in my mind is : Should any one do this?
Is it consider as wrong? (Because I am thinking so.)
What community think about this?
One Example : IPhone app and Web Services
I have comment on that answer. So it may happen that when you visit link he has remove company name.
I am not sure for which tag to use. So if you find it wrong please make edit.

A:

If the affiliation is relevant to the post, then not only should the poster disclose it but he must.  Going beyond disclosure to an actual link to the company home page is a little tacky but probably not actionable.
If the affiliation has nothing to do with the post, however, then it's a tagline or signature, not content relevant to the question, and should be removed.  The proper venue for advertising your company, projects, web site, or anything else is the user profile.


Q:

Resize a 2:1 image to put into a 1:1 div

Just want to let all the product images using the same 1:1 responsive area. The problem is, if the image is 2:1, it uses more space than expected (1:1).
How to use css to resize it to show like this? (first example)
current setting:
max-width: 100%;
width: 100%;
height: auto;
max-height: 100%;
margin: 0 auto;

A:

You could use object-fit:cover; to cover the entire container where the image is in.
In the following example, I've loaded in a 200x100 pixel image, and contained it in a 100x100 pixel area.
Note that IE does not support this: https://caniuse.com/#search=object-fit

#product {
  width:100px;
  height:100px;
}

#product img {
  object-fit:cover;
  width:100%;
  height:100%;
}


Q:

Can React context be mutated by nested component?

I have two components located at different places in the component tree. They cannot be nested because of layout but I need them to communicate.
I've tried React context but to my understanding the consumer needs to be a child to the provider, defeating the purpose.
Is there a way to have three components: an overarching provider, a component that will mutate the providers state and a consumer?
Pseudocode to help clarify:
<PROVIDER />
   <SOURCE OF DATA />
   <CONSUMER />
<PROVIDER />

A:

Yep, in React data always flow down the tree.
These kinds of state-management problems are really common; a lot of libraries (e.g. Redux, Mobx) have been designed to solve these issues, and I would recommend you looking into them.
However, if you really can't separate out the two components, and if you don't want to learn/include a state-management library at the moment, then you can use a context to thread the data though; the trick is to pass a callback function alongside the data you're threading through in the context.
When the <SOURCE OF DATA /> component gathers new data, it can invoke this callback with the new data; this callback function (defined in the provider component) will then update the state of the provider, and that will then cause an entire refresh of all the child components with the new data values. (I've (very) roughly illustrated this below; the syntax will vary depending on whether you're using hooks or not.)
PROVIDER COMPONENT:
   state = data
   callback = (newData) => updateState(data <= newData)
   return(
       <MyContext.Provide { data, callback } >     // provides { data, callback }
           <SOURCE OF DATA />   // consumes callback from context and invokes callback(newData)
           <CONSUMER />         // consumes data/newData from context
       </MyContext.Provider>
   );

Now if the components you've indicated above are really both 'siblings' in the provider, then you shouldn't need a context: a simple callback via props will work.


Q:

Why does this c code of addition and assignment of type float not output the correct result?

Beginner exercise of adding fractions S=1/2 + (1*3)/(2*4) + (1*3*5)/(2*4*6) +...+ (1*3*5*...(2*n-1))/(2*4*6*...2*n))
The exercise takes the value of n from user input but I initialized it with 5 for this example.
        #include <stdio.h>

int main() {

int numerator=1, denominator=1, k, n=5;
float S=0;

for (k=1; k<=n; k++) {

    numerator *= (2*k - 1);
    denominator *= 2*k;
    S += numerator/denominator; //this does not work and I can't tell why

    printf("numerator= %d\n", numerator);
    printf("denominator= %d\n", denominator);
    printf("S= %f\n", S);
    }

printf("S= %f\n", S); // this should print 1.70703125 but it prints 0.000000

scanf_s("%d", &n);
return 0;
}

A:

The division numerator/denominator is an integer division. The result is an integer, all decimals are truncated (cut off).
At least one of the parts in the division needs to be a floating point value for the whole expression be floating point. As in (float)numerator/denominator.


Q:

What is the solution of the last operation?

Each symbol represents a number between 0 and 9. You need found the number which is the solution to the last operation. The two triangles in the first operation and the triangle and the rectangle of the third operation represent a number of two digits, not a multiplication operation.

So, which is the number that corresponds to the last operation?

A:

Let G, R, Y, B denote the digits corresponding to the four shapes in the order they appear (green star, red octagon, yellow triangle, blue rectangle).
In the first equation,

 two 1-digit numbers sum to YY, so Y=1 (22 is too large).

In the second equation we learn B=R+1.
Now the third equation is

 1B-R = 1(R+1)-R = 11,

so the answer is

 11, or two yellow triangles.


Q:

SizeChanged Event Isn't Firing

So, I've been researching the SizeChanged event recently because I want my font size to scale proportionally, and though I have searched through many posts, none of them are working for me - my object isn't firing.
Here's my code:
private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e) {
    welcomeTitleText.Text = "hi";
}

This doesn't even use like the window size, it just changes the text, to make sure it's firing. However, it's not working for some reason. Any ideas?

A:

Ensure you are subscribing to the event. You have to register the handler for the event, either in code or in xaml.
In Code example:
public MainWindow()
{

    // This call is required by the designer.
    InitializeComponent();

    // Add any initialization after the InitializeComponent() call.
    this.SizeChanged += MainWindow_SizeChanged;
}

or in xaml:
<Window
    x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
    ...
    Loaded="AboutWindow_Loaded">
...

Also note that some times the sizeChanged event does not fire if wpf's backend thinks the change is too insignificant. See the docs for more details.
A Tip, you might try wrapping your Text in a Viewbox, this will autosize it to the maximum fill size. Then you can just limit the size (i.e. maxwidth, maxheight) of the view box (or it's container (i'd recommend using a grid, and seeing column & row height using * (stars) or pt, more details here) to achieve reasonable scaling. E.g:
<Viewbox MaxHeight="50">
    <TextBlock>I'm Scaled Text</TextBlock>
</Viewbox>


Q:

WCF services on Azure

I am planning to migrate all my VPS functions to a my Azure subscription.
I have the free 3 year bizSpark subscription which gives me 20 cores, 6 hosted services and 5 storages. I believe this is 2 small instances.
My Main aim is to transfer my 10 or so WCF applications which I currently run on a IIS7.0 server.
How many WCF services am I able to host with my Azure?
Ive been reading about and playing with Azure all day, but still completely confused what it all does. From my current playing, it seems each WCF service needs its own hosted service, to which i only ahve 6 of? or am I getting confused. Do the WCF services need to be put in a 'hosted service'?
Thanks.

A:

Let me see if I can help out a bit:

Windows Azure is a platform where you can deploy applications to the cloud and not worry about building the plumbing for underlying infrastructure or features such as caching, identity management, etc.
Each Windows Azure subscription has multiple deployment slots, or Hosted Services. This is limited to 6, meaning you can deploy up to six complete deployment packages (with each deployment package consisting of one or more Virtual Machine instances).
Each Virtual Machine, also called a Role, takes up a certain number of cores. A Small role uses 1 core, medium=2, large=4, and extra large=8.
BizSpark gives you 1500 core-hours monthly. If you ran a Small role instance for an entire month, you'd consume just under 750 hours. Thus, you can run 2 Small role instances 24x7 and still fit within the 1500 included core-hours.
Your account is capped at 20 cores, meaning you can crank up your role instances beyond 2. However, if you ran this 24x7, you'd start incurring costs. If you keep your monthly consumption under 1500 core-hours, you're fine. So, if you ran all 20 cores for 24 hours, you'd consume 20x24=480 core-hours. At that rate, you'd consume your included hours in about 3 days.
Each Role is essentially Windows Server 2008 R2. A Web Role differes from Worker Role in that a Web Role has IIS enabled.
Each Deployment (e.g. Hosted Service) may expose up to 25 externally-facing endpoints (e.g. tcp, http, or https ports). You may host a WCF service on any of your exposed ports
You may host all of your WCF services in a single role, or place them in separate roles. Your choice, really. It's less expensive to host in a single role, as you can now have your entire service stack running in 2 instances. The downside is that, if you have one very busy service, and the remaining services relatively idle, the busy service can starve the other services. So sometimes it's beneficial to separate services into different roles, and scale accordingly.
Note that I said you can run everything in 2 instances. If you only host in one instance, you will incur occasional downtime whenever that instance is rebooted (e.g. hardware failure, Role Instance OS upgrade, or Host OS upgrade).

You should really download the Windows Azure Platform Training Kit. There, you'll find easy-to-follow labs that walk you through all the basics, hosting services, deploying to multiple roles, etc.
Good luck!


Q:

GPU memory is overloaded

I'm using iStats Menu to monitor the loading of my MBP.
And when my external 4k monitor LG 27UK850-W is connected via USB type C I can see that my GPU Memory is overloaded (currently 744%), though Processor seems fine.
Is it a bug or it should be this way?
And of course, Fans are almost always on. Is it ok?

A:

It appeared to be an "iStats Menu" issue
And it is fixed in the newest version


Q:

remove (* char) from the required field label in form

I'm trying to change the label of the fields that are required in django form using labels in Meta class .
so after writing the code using this doc , i have a problem because the name of the field changes but the -> * character <- stays there .
Code :
from django.utils.translation import gettext_lazy as _
class Meta:
    model = ...
    fields = ...
    widgets = ...

    labels = {
        'email': _('email (necessary)'),
        'username': _('name (necessary)'), # the result of this -> name(necessary)*
    }

Template :
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}

USERS REGISTER PAGE IS FOUND!

    <form method="POST">
        {% csrf_token %}
        <fieldset class="form-group">
            <legend class="border-bottom mb-4">Join Today</legend>
            {{ form|crispy }}
        </fieldset>

            <button type="submit" class="btn btn-outline-info">Sign Up</button>

    </form>

            Already Have An Account ? Sign In

{% endblock content %}

so , how can I remove this annoying * ?

A:

The root cause here was apparently the django-crispy-forms package being used for rendering the form.
Its documentation has a section on the "required" asterisks; the easiest, as linked, is to hide the asterisk field; you don't need to change the labels:
.asteriskField {
    display: none;
}


Q:

how to get XML content over HTTP request?

I'm building a module and I need to  get XML content over HTTP request.
The idea is to create nodes programmatically with the retrieved data from the xml file.
Can I do this?

A:

Its a little bit of a learning curve , but I would recommend using the feeds module for this
https://www.drupal.org/project/feeds
you can then load xml (or csv) to nodes, and map its contents to nodes.
This is preferable to writing your own custom functionality.
but if you do, drupal_http_request(), and then node_save() for constructing the nodes would be the way to do things.
If you do code it yourself, Id recommend getting comfortable with running scripts with drush, as that'll be easier than battling timeouts in the browser


Q:

Is it possible to move a windows frame or application frame by frame?

OCD QUESTION
The Example:
I have this application open on my desktop: Application when first opened

When I open this particular application, I like to have it in the far right hand corner on my second monitor.
Like this: Application after manually moved

The Description:
I want to know if you can move an application frame by frame so that when I move one into the corner like that, I can move it without my shaky hands preventing me from lining the application properly. (I am aware of the keyboard shortcut for moving between displays such as: Shift+Windows+←&→).
This is what I do not like: Application while struggling to move with shaky hands

(Where the background is showing to the top and right of the application)
The Question
Is there another keyboard shortcut for moving applications, essentially, frame by frame, or something of the like? I have searched quite a bit on the inter-webs and cannot find anything for this specific issue. (For example: If you are using an application such as PowerPoint, and you insert a picture you can use ←&→ to move the picture left and right.

A:

I could not see the screenshots right now, but are you looking for something like this:

Inside a window which is not maximized, press ALT +
Space, then m to move.
Inside a window which is maximized the you first restore it using
the same menu ALT + Space