text:
Q: for loop inside the if and else if if(code==1)
                {
                System.out.print("Enter product number: ");
                int productnumber=Integer.parseInt(a.readLine());
                System.out.print("Enter product name: ");
                String productname=a.readLine();
                System.out.print("Enter price: ");
                int price1=Integer.parseInt(a.readLine());
                System.out.println("");
                {
                        int p=0;
                            for(int q=1;q<=1;q++)
                            {
                                System.out.println("1. Maintenance");
                                System.out.println("2. Transaction");
                                System.out.println("");

                                System.out.print("Enter Code: ");
                                int code1=Integer.parseInt(a.readLine());
                                System.out.println("");
                            }
                }
                {
                int w;
                for(productnumber=2; productnumber<=2; productnumber++)
                {
                System.out.println("Product number: "+productnumber);
                System.out.print("Product name: ");
                String prodname=a.readLine();
                System.out.print("Price: ");
                int price2=Integer.parseInt(a.readLine());
                System.out.println("");
                }
                }
                }
                     else if(code==2)
                         {
                            System.out.println("Display List of Product-Prices");
                            System.out.print("Display product number: ");
                            int productnumber2=Integer.parseInt(a.readLine());
                            System.out.println("Total: ");
                            System.out.print("Payment: ");
                            int payment=Integer.parseInt(a.readLine());
                            }
                        }

//What's the problem in this code guys? There's an option which is the 1. Maintenance and 2. Transaction. If i press the number 1, it will read this following codes:
int w;
                for(productnumber=2; productnumber<=2; productnumber++)
                {
                System.out.println("Product number: "+productnumber);
                System.out.print("Product name: ");
                String prodname=a.readLine();
                System.out.print("Price: ");
                int price2=Integer.parseInt(a.readLine());
                System.out.println("");

//But if i press the number 2, it will read the same code with the number 1.. What will I do to read the statements inside the "else if(code==2)" when i press the number 2? Thankyou for those who will help me. :)

A: You will need to show us complete code. Only then can we understand where are you going wrong. Based on above whatever snippet you've provided i've build a wrapper around it and ran the code it seems to be fine. Look below:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class test123 {
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader a = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your code : ");
        int code = Integer.parseInt(a.readLine());
        System.out.println();
        if (code == 1) {
            System.out.print("Enter product number: ");
            int productnumber = Integer.parseInt(a.readLine());
            System.out.print("Enter product name: ");
            String productname = a.readLine();
            System.out.print("Enter price: ");
            int price1 = Integer.parseInt(a.readLine());
            System.out.println("");
            {
                int p = 0;
                for (int q = 1; q <= 1; q++) {
                    System.out.println("1. Maintenance");
                    System.out.println("2. Transaction");
                    System.out.println("");

                    System.out.print("Enter Code: ");
                    int code1 = Integer.parseInt(a.readLine());
                    System.out.println("");
                }
            }
            {
                int w;
                for (productnumber = 2; productnumber <= 2; productnumber++) {
                    System.out.println("Product number: " + productnumber);
                    System.out.print("Product name: ");
                    String prodname = a.readLine();
                    System.out.print("Price: ");
                    int price2 = Integer.parseInt(a.readLine());
                    System.out.println("");
                }
            }
        } else if (code == 2) {
            System.out.println("Display List of Product-Prices");
            System.out.print("Display product number: ");
            int productnumber2 = Integer.parseInt(a.readLine());
            System.out.println("Total: ");
            System.out.print("Payment: ");
            int payment = Integer.parseInt(a.readLine());
        }
        a.close();
    }
}

This looks fine. Show us your complete code. for further investigation.


text:
Q: Show the following measure theory result. Let $A$ be a unbounded Lebesgue measurable subset of $\mathbb{R}$ such that $m(A) < \infty$. Show that for each $\epsilon > 0$,there exists a bounded Lebesgue measurable set $B$ in $\mathbb{R}$ such that $B \subset A$ and $m(A \setminus B)< \epsilon $.

I have no idea how to approach these kind of problems.

A: By Monotone Convergence Theorem, we have $m(A\cap[-n,n])\rightarrow m(A)$. Now $m(A)<\infty$ allows us to have the estimate that $m(A)-m(A\cap[-n,n])<\epsilon$ for large $n$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: maximum value of $|\text{Re}[E e^{i \phi}]|$ for a complex 3-vector E In physics we often have a complex vector $\vec E^*$ in 3 dimensions, which is used to keep track of what we really care about, which is the oscillating real vector $\vec E(t) \equiv \text{Re}[\vec E^* e^{i \omega t}]$ where $\omega$ and $t$ are real numbers and Re entails taking the real part of each of the vector components.
A question that came up is: What is the maximum value of $|E(t)|^2$, and what $t$ does that occur at?
For readers who prefer symbols to prose & context: For complex numbers $a,b,c$, is there a way to compute
$${\arg \max}_{\phi\in\mathbb{R}} \left[(\text{Re}[ae^{i\phi}])^2 + (\text{Re}[be^{i\phi}])^2 + (\text{Re}[ce^{i\phi}])^2\right]$$
which is more elegant / efficient than brute-force numerical maximization?

A: Write $E=E_r+E_ii$. You have the vector valued function
$$f(t):={\rm Re}(Ee^{it})={\rm Re}((E_r+E_ii)(\cos(t)+i\sin(t)))=E_r\cos(t)-E_i\sin(t).$$
Note also that
$$
f^{\prime}(t)=-(E_r\sin(t)+E_i\cos(t))\;.
$$
Setting the derivative of the dot product $\vert f(t) \vert^2=f(t)\cdot f(t)$ equal to zero, you get
$$2f^{\prime} (t)\cdot f(t)=0\Leftrightarrow f^{\prime}(t) \perp f(t)\;.$$
Bilinearity of the dot product gives
$$0=f^{\prime}(t)\cdot f(t)=E_i\cdot E_r (\sin^2(t)-\cos^2(t))+\sin(t)\cos(t)(\vert E_i \vert^2-\vert E_r \vert^2)$$
so
$$
E_i\cdot E_r (\sin^2(t)-\cos^2(t))=\sin(t)\cos(t)(\vert E_i \vert^2-\vert E_r \vert^2)
$$
Using the double angle formula, $\sin(t)\cos(t)=\frac{1}{2}\sin(2t)$ and $\sin^2(t)-\cos^2(t)=-\cos(2t)$, you have
$$
-2E_i\cdot E_r \cos(2t)=\sin(2t)(\vert E_i \vert^2-\vert E_r \vert^2)
$$
Notice that if $E_r$ and $E_i$ are orthonormal, then $f^{\prime}(t)$ and $f(t)$ are perpendicular for all $t$. hence $\vert f(t) \vert$ is constant. Otherwise, we solve
$$
\frac{2E_i\cdot E_r }{\vert E_r \vert^2-\vert E_i \vert^2}=\tan(2t)\Rightarrow t=\frac{1}{2}\tan^{-1}\Big(\frac{2E_i\cdot E_r }{\vert E_r \vert^2-\vert E_i \vert^2}\Big)+\frac{n\pi}{2}
$$
Substituting this value of $t$ into
$$\vert f(t)\vert^2=\vert E_r\vert^2\cos(t)^2-2E_r\cdot E_i\cos(t)\sin(t)+\vert E_i\vert^2\sin^2(t)$$
will give you the result (you have to check which values of $n$ correspond to maxima).


text:
Q: Trying to apply a class to a styled-component for an onclick event In using standard JSX and CSS, I can add a className attribute with some logic to add a class name based on a boolean value, but when using styled-components, this doesn't appear to be as easy.  This is what I have at the moment:
Menu.tsx
interface IMenuProps {
  showMenu: boolean;
  menuToggle: () => void;
}

const Menu: React.FC<IMenuProps> = ({ showMenu, menuToggle }) => {
  return (
    <MenuWrapper onClick={menuToggle} {showMenu ? "showMenu" : ""}>
      ...

At the moment, there's a red line under the showMenu within the ternary statement.
'...' expected.

Hopefully you can see what I'm trying to do here.

A: You forgot to add className.

const Menu: React.FC<IMenuProps> = ({ showMenu, menuToggle }) => {
  return (
    <MenuWrapper onClick={menuToggle} className={showMenu ? "showMenu" : ""}>

BTW:
If there isn't any logic inside your component you can write it as

const Example: FC = () => (

Example

);

A: Have you written types for your styled MenuWrapper?
If not, try something like this:
const MenuWrapper = styled.div<{showMenu?:boolean}>


text:
Q: HBase looks for hadoop-common library on HDFS I am trying to run a hadoop(version:2.2.0) job on a single machine which writes the reducer output into a Hbase(version 0.98) table. When I run the job, HBase looks for hadoop-common.jar file in the HDFS:

2014-03-07 10:52:44,499 ERROR [main] security.UserGroupInformation
  (UserGroupInformation.java:doAs(1494)) - PriviledgedActionException
  as:ubuntu (auth:SIMPLE) cause:java.io.FileNotFoundException: File does
  not exist:
  hdfs://127.0.0.1:9000/home/ubuntu/workspace/XXXX/lib/hadoop-common-2.2.0.jar

Here is my job configuration:
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "127.0.0.1");
Job job = Job.getInstance(conf, "CreateLookUpTable");
job.setJarByClass(HBaseLookUp.class);
// configure output and input source
N3TextInputFormat.addInputPath(job, new Path(inputText));
job.setInputFormatClass(N3InputFormat.class);
// configure mapper and reducer
job.setMapperClass(HBaseLookUp.Map.class);
// configure output
TableMapReduceUtil.initTableReducerJob("LookUp", HBaseLookUp.Red.class, job);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setReducerClass(HBaseLookUp.Red.class);

job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NullWritable.class);

Any idea about this issue?


text:
Q: Spyder no starting in Ubuntu bu GUI I'm not able to launch Spyder by GUI in Ubuntu through the icon is there. When I click on the icon, spyder icon appears on the launcher and disappears soon. Nothing happens then. I had installed Spyder by sudo apt-get install spyder. But when I try to open it by the terminal, by the command 'spyder' it opens, though the python console is not available. To avail Python console, I want it to open by GUI.
When I tried installing by Ubuntu software, on searching for 'spyder', it said, "No application found".
How to launch spyder from the GUI?


text:
Q: Hacknet Jailbreak mission I'm stuck in the Hacknet Jailbreak mission.
I already discovered the mobile, but I don't have the software to break the eOS device.
It also says I need 3 ports cracked, but probe just shows 2 ports.
Anyone know what to do?

A: You logged into one of the eos devices before. All eos devices seem to have the same username and passwords

A: You must hack a computer and run eosDeviceScan.exe, then there is an IP and you must do connect *IP*, then press enter-now you are in the smartphone. Then log in with the Username: admin & Password: alpine then your are done!

A: I CAN'T BELIEVE!
For this mission, you need to reply the IP address of the eOS device!
The description of the mission totally throws you away from what you need to do!


text:
Q: Internal error running expressjs 4 on iis and windows azure I have the basic express 4 app running locally using the node provided web server.
I attempted to view/edit in Webmatrix and use IIS so I could then upload to Azure as a node app. Azure's template uses older versions of node and express.
When run from Webmatrix using IIS - and when published to Azure, I receive the following:
HRESULT: 0x2
HTTP status: 500
HTTP reason: Internal Server Error

I believe the issue is somehow related to the web.config file but all articles and fixes I've found are dated and have not resolved the issue.
My web.config file:
<configuration>
<system.webServer>

<handlers>
  <!-- indicates that the app.js file is a node.js application to be handled by the iisnode module -->
  <add name="iisnode" path="app.js" verb="*" modules="iisnode" />
</handlers>

<rewrite>
  <rules>

    <!-- Don't interfere with requests for node-inspector debugging -->
    <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
      <match url="^app.js\/debug[\/]?" />
    </rule>

    <!-- First we consider whether the incoming URL matches a physical file in the /public folder -->
    <rule name="StaticContent">
      <action type="Rewrite" url="public{REQUEST_URI}" />
    </rule>

    <!-- All other URLs are mapped to the Node.js application entry point -->
    <rule name="DynamicContent">
      <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True" />
      </conditions>
      <action type="Rewrite" url="app.js" />
    </rule>
  </rules>
</rewrite>

<!-- You can control how Node is hosted within IIS using the following options -->
<!--
  <iisnode
      node_env="%node_env%"
      nodeProcessCountPerApplication="1"
      maxConcurrentRequestsPerProcess="1024"
      maxNamedPipeConnectionRetry="3"
      namedPipeConnectionRetryDelay="2000"
      maxNamedPipeConnectionPoolSize="512"
      maxNamedPipePooledConnectionAge="30000"
      asyncCompletionThreadCount="0"
      initialRequestBufferSize="4096"
      maxRequestBufferSize="65536"
      watchedFiles="*.js"
      uncFileChangesPollingInterval="5000"
      gracefulShutdownTimeout="60000"
      loggingEnabled="true"
      logDirectoryNameSuffix="logs"
      debuggingEnabled="true"
      debuggerPortRange="5058-6058"
      debuggerPathSegment="debug"
      maxLogFileSizeInKB="128"
      appendToExistingLog="false"
      logFileFlushInterval="5000"
      devErrorsEnabled="true"
      flushResponse="false"
      enableXFF="false"
      promoteServerVars=""
    />
  -->

</system.webServer>
</configuration>

I've contacted the Azure team and they've started a discussion but I have more faith in what stackoverflow users can provide.

A: @Matthew,
here is my guess, i think you didn`t config your app to listen to the right port when deploy to azure app service. you will need to do something similar to below code to get port number from enviroment valirable "process.env.port"
var app = require('express')();
var port = process.env.port || 8080; // 8080 for local or whatever number u want
var listener = app.listen(port, function(){
    console.log('Listening on port ' + port);
});


text:
Q: VBA to save attachments as subject field Hope someone can help with this... thanks in advance!
I have numerous emails that are saved to the hard drive. Each email contains attachments with the same name as in the other emails. I have a working macro (thanks go Google) that will extract the attachments, save to a specific folder with a prefix to keep from overwriting. But what I really need for it to do is to rename the file based on the subject field. Or.. to at least be able to read some of the information from the subject line. Each email will have a set of numbers, followed by four characters within parenthesis. For example the subject will read... Successfully processed for your customer 123456789 (123A) accounts payable. I would like for the file to be saved as 123456789_123A and to add a _1 or _2 depending on how many files are in the email and to convert from XLSX to CSV.
We run this process biweekly and opening each email and doing "save as" is very time consuming as we are working with approximately 70 emails that each contain two attachments.
Below is the code that I am using. Any help would be most appreciated!!
Option Explicit
Const csOutlookIn As String = "In"
Const csOutlookOut As String = "Out"
Const csFilePrefix As String = "file"
Sub Extract_Emails_Demo2()
Application.ScreenUpdating = False

Dim sCurrentFolder As String
sCurrentFolder = ActiveWorkbook.Path & "\"

Dim FSO As Scripting.FileSystemObject
Set FSO = New Scripting.FileSystemObject

Dim fldrOutlookIn As Scripting.Folder
Set fldrOutlookIn = FSO.GetFolder(sCurrentFolder & csOutlookIn)

Dim oApp As Outlook.Application
Set oApp = New Outlook.Application

Dim oMail As Outlook.MailItem
Dim oAttach As Outlook.Attachment

Dim fileItem As Scripting.File
Dim sAttachName As String
Dim lcounter As Long
lcounter = 0
Dim scounter As String
For Each fileItem In fldrOutlookIn.Files
Set oMail = oApp.CreateItemFromTemplate(fileItem.Path)
For Each oAttach In oMail.Attachments
lcounter = lcounter + 1
scounter = Format(lcounter, "000")
sAttachName = oAttach.Filename
sAttachName = sCurrentFolder & csOutlookOut & "\" & scounter & "_" & sAttachName
oAttach.SaveAsFile sAttachName
Next oAttach
Set oMail = Nothing
Next fileItem

MsgBox "Finished Extrating Files"
Application.ScreenUpdating = True
End Sub

Thanks in advance!

A: Please, test the next adapted code. It will not take in consideration mails not having any attachment and will send a message containing the email subjects not containing two numbers. It uses two functions to build the necessary names to save the attachments, open them, save as csv and delete the xls* workbook:
Sub Extract_Emails_Demo2()
 Const csOutlookIn As String = "In", csOutlookOut As String = "Out"
 Const csFilePrefix As String = "file", prefixName As String = "abcdefg_"

 Dim sCurrentFolder As String
 sCurrentFolder = ActiveWorkbook.Path & "\"

 Dim FSO As Scripting.FileSystemObject
 Set FSO = New Scripting.FileSystemObject

 Dim fldrOutlookIn As Scripting.Folder
 Set fldrOutlookIn = FSO.GetFolder(sCurrentFolder & csOutlookIn)

 Dim oApp As Outlook.Application
 Set oApp = New Outlook.Application

 Dim oMail As Outlook.MailItem
 Dim oAttach As Outlook.Attachment

 Dim fileItem As Scripting.file, sAttachName As String, scounter As String
 Dim lcounter As Long, strSubject As String, arr, strNoPattern As String, strExt As String

 For Each fileItem In fldrOutlookIn.files
    Set oMail = oApp.CreateItemFromTemplate(fileItem.path)
    strSubject = oMail.Subject: lcounter = 0
    For Each oAttach In oMail.Attachments
        'Debug.Print oAttach.DisplayName: Stop
        lcounter = lcounter + 1
        arr = extrAllNumb(strSubject)             'extract an array of found numbers in the subject text
        sAttachName = buildName(arr, strSubject) 'build the name of the attachment to be saved
        If sAttachName = "" Then 'if no any number found in the subject
            strNoPattern = strNoPattern & fileItem & vbCrLf 'build the string of non conform Pattern files
            GoTo LoopEnd                         'skip the following code iteration lines
        End If
        strExt = Split(oAttach.DisplayName, ".")(UBound(Split(oAttach.DisplayName, ".")))
        sAttachName = sAttachName & "_" & lcounter 'add the attachment number
        sAttachName = sCurrentFolder & csOutlookOut & "\" & prefixName & sAttachName & "." & strExt
        oAttach.SaveAsFile sAttachName 'save the attachment using the above built name
        If strExt Like "xls*" Then     'saving excluding extension as pdf, doc, txt etc.
            Dim wb As Workbook, CSVName As String
            Application.ScreenUpdating = False     'some optimization for opening wb and process it
             Set wb = Workbooks.Open(sAttachName)  'open the workbook
             CSVName = Replace(sAttachName, "." & strExt, ".csv") 'build the csv name
             wb.saveas CSVName, xlCSV              'save the wb as csv
             wb.Close False                        'close the wb without saving
            Application.ScreenUpdating = True
             Kill sAttachName                      'delete the original attachment xls* file
        End If
    Next oAttach
LoopEnd:
 Next fileItem
 MsgBox "Finished Extrating Files"
 If strNoPattern <> "" Then MsgBox "Wrong pattern files: " & vbCrLf & strNoPattern
End Sub

Function buildName(arr As Variant, strSubject As String) As String
  Dim lngStart As Long, strChar As String
  If Not IsArray(arr) Then buildName = "": Exit Function
  If UBound(arr) >= 1 Then
    lngStart = InStr(strSubject, arr(0)) + Len(CStr(arr(0)))
    strChar = Mid(strSubject, InStr(lngStart, strSubject, arr(1)) + Len(CStr(arr(1))), 1)
    'buildName = arr(0) & "_" & arr(1) & IIf(strChar = ")", "", strChar)
    buildName = arr(1) & IIf(strChar = ")", "", strChar) & "_" & arr(0)
  Else
    buildName = arr(0)
  End If
End Function

Private Function extrAllNumb(strVal As String) As Variant
    Dim res As Object, El, arr, i As Long
    With CreateObject("VBscript.RegExp")
        .Pattern = "(\d{3,10})"
        .Global = True
        If .Test(strVal) Then
            Set res = .Execute(strVal)
            ReDim arr(res.count - 1)
            For Each El In res
                arr(i) = El: i = i + 1
            Next
        End If
    End With
    extrAllNumb = arr
End Function

If something not clear enough, please do not hesitate to ask for clarifications.


text:
Q: Including Typescript code in Relay (System.js import) How to include system.js to fix the error below? Or is there any other solution?
I downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit), changed the database.js to database.ts with the below content (Snippet 1).
I ran "npm run update-schema" and got the error
System.register([], function (exports_1) {
^

ReferenceError: System is not defined
    at Object.<anonymous> (database.js:9:1)
    at Module._compile (module.js:410:26)
..

I know it occurs because update-schema uses scripts/updateSchema.js -> data/schema.js -> which imports objects from data/database.js (compiled version of database.ts) has -
System.register([], function(exports_1) {

Snippet 1:
/// <reference path="./interface.d.ts" />

export class User implements IUser{
    constructor (public id: String, public name: String){
        this.id = id;
        this.name = name;
    }
}
// Model types
class UserModel extends User implements IUserModel {

     constructor(public id: String, public name: String){
         super (id,name);
     }
     getUser ():IUser{
         return this;
     }
     setUser (_User:IUser) : void {
         this.id = _User.id;
         this.name = _User.name;
     }
    getUserbyId (_id:String):IUser{
        if (_id === this.id){
            return this;
        } else {
            return null;
        }
    }

}

export class Widget implements IWidget{
    constructor (public id: String, public name: String){
        this.id = id;
        this.name = name;
    }
}
// Model types
class WidgetModel extends Widget implements IWidgetModel {

     constructor(public id: String, public name: String){
         super (id,name);
     }
     getWidget ():IWidget{
         return this;
     }
     setWidget (_Widget:IWidget) : void {
         this.id = _Widget.id;
         this.name = _Widget.name;
     }
    getWidgetbyId (_id:String):IWidget{
        if (_id === this.id){
            return this;
        } else {
            return null;
        }
    }
}

// Mock data
var viewer:IUserModel = new UserModel('1','Anonymous');

var widgets:IWidget[] = ['What\'s-it', 'Who\'s-it', 'How\'s-it'].map((name:String, i:any) => {
  let widget:IWidgetModel = new WidgetModel(name,`${i}`);
  return widget;
});
  export function getUser (_id:String):IUser {
          return viewer.getUserbyId(_id);
  }
  export function getViewer ():IUser {
      return viewer.getUser();
  }
  export function getWidget (_id:String):any {
      widgets.forEach(
          w => {
              if (w.id === _id)
                  return w;
              else
                  return null;
          }
      );
  }
  export function getWidgets (): IWidget[]{
      return widgets;
  }

A: tsconfig.json had
"module": "system",
Changed it to
"module": "umd",
and it worked.


text:
Q: How could I make this code more React - like I am quite new to React and I want to learn to write it better. I tried Googling for answers for this matter but I can't seem to find anything useful.
I have a list of projects which are objects with id (not a number, but a string), name, and target. I want to create another list of new objects which also have the sum of donations and minDonations values. Those I get from another list "donations". The lists are separate since I get them from two different APIs.
I managed to get the information I wanted and to create a new list of objects from them, but this seems very unReact-like way of doing this. How could I make this code better?
I hope this is the right place for this kind of question.
Thank you in advance.
    useEffect(() => {
        //use the data gathered to create new list of object containing
        //the project and the amount invested/targeted to them and minDonations value
        var helperProjectList = projects.map(p => {
            const projectObject = {
                id: p.id,
                name: p.name,
                target: p.target,
                minDonations: 0,
                sum: 0
            }
            return projectObject
        })

        for (var p = 0; p < helperProjectList.length; p++) {
            for (var d = 0; d < donations.length; d++) {
                if (donations[d].target == helperProjectList[p].id) {
                    helperProjectList[p].sum += donations[d].sum
                    helperProjectList[p].minDonations += donations[d].sum
                }
            }
        }
        //this cant be on the for loops above for it loops too many times.
        var ut = 0;
        for(var d = 0; d < donations.length; d++) {
            if (donations[d].target === undefined) {
                ut += donations[d].sum
            }
        }

        setProjectDonations(helperProjectList)
        setUnTargetedDonationsSum(ut)
    }, [projects, donations])

A: I think this might help you:
useEffect(() => {
  //use the data gathered to create new list of object containing
  //the project and the amount invested/targeted to them and minDonations value
  var helperProjectList = projects.map((p) => {
    const foundIndex = donations?.findIndex(donation => donation.target == p.id);
    if(foundIndex !== -1){
      return {
        id: p.id,
        name: p.name,
        target: p.target,
        minDonations: donations[foundIndex].minDonations + p.minDonations,
        sum: donations[foundIndex].sum + p.sum,
      };
    }else {
      return {
        id: p.id,
        name: p.name,
        target: p.target,
        minDonations: 0,
        sum: 0,
      };
    }
  });
  var ut = 0;
  for (var d = 0; d < donations.length; d++) {
    if (donations[d].target === undefined) {
      ut += donations[d].sum;
    }
  }

  setProjectDonations(helperProjectList);
  setUnTargetedDonationsSum(ut);
}, [projects, donations]);


text:
Q: How to change admin user of HTTP Gitolite repository? I have setup a Gitolite repository accessed via HTTP according to directions in http://gitolite.com/gitolite/http.html and https://github.com/sitaramc/gitolite/blob/master/t/smart-http.root-setup.
In the latest link, there's a command to setup the respository as
HOME=$GITOLITE_HTTP_HOME gitolite setup -a adminusername

After creation, I can clone the gitolite-admin.git repository after HTTP authentication as user adminusername, and manage it normally. However, I would like to know whether there's a way to change the admin user name form adminusername, as repo administration is an employee's role, but if the employee leaves, I would have to transfer it to someone else, and I am not too comfortable with  creating an additional LDAP user to manage the repo (I set up HTTP authentication to use our LDAP server).
Thanks.


text:
Q: Adjust iframe to embedded facebook video's original height / aspect ratio I am trying to embed Facebook videos on my website. However like many before me I am struggling with sizing them.
Following the official documentation, I realized that the first way of doing it (with the js SDK) provided an easy method to have adjustable videos, but was about twice as slow as using the iframe. But of course in the latter case, only the width of the video will adjust to its container.
I tried accessing the iframe's data to fetch the video's original height and CSS to adjust its width based on code samples I found on the internet, but can't due to same origin policy.
https://codepen.io/Angc/pen/ExYGNOO

  https://www.facebook.com/destanie.wagner/videos/2391334934255393/

.embed-iframe-facebook {
  max-width: 300px;
}

.embed-iframe-facebook div {
  position: relative;
  height: 0;
  padding-top: 178%;
}

.embed-iframe-facebook iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

Furthermore, I can't seem to find a way to tell the iframe to "adjust its size to its content". Ideally I would want to do that, and detect its height so I can adjust its width, to create an artificial "max-height".
My question is therefore: how can I have the iframe adjust its height to the embedded video ?

A: It's possible to let an iFrame fill its parent div.
For example:
.container {
    display: block;
    height: 100vw;
}
.iframeContainer {
    display: block;
    width: 100%;
    height: 100%;
    padding: 0px;
    clear: both;
}
.embed-area {
    clear: both;
    width: 100vw;
}

And use the following HTML markup.


text:
Q: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu I get the following error message which I tried to deal with it by throwing .to(self.device) everywhere but it doesn't work.
  ab = torch.lgamma(torch.tensor(a+b, dtype=torch.float, requires_grad=True).to(device=local_device))
Traceback (most recent call last):
  File "Script.py", line 923, in <module>
    average_epoch_loss, out , elbo2 =train(epoch)
  File "Script.py", line 848, in train
    loss_dict = net.get_ELBO(X)
  File "Script.py", line 546, in get_ELBO
    elbo -= compute_kumar2beta_kld(self.kumar_a[:, k].to(self.device), self.kumar_b[:, k].to(self.device), self.prior, (self.K-1-k)* self.prior).mean().to(self.device)
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

Here is a snippet of my script which is related to the error:
def compute_kumar2beta_kld(a, b, alpha, beta):
    SMALL = 1e-16
    EULER_GAMMA = 0.5772156649015329
    ab    = torch.mul(a,b)+ SMALL
    a_inv = torch.pow(a + SMALL, -1)
    b_inv = torch.pow(b + SMALL, -1)
    kl = torch.mul(torch.pow(1+ab,-1), beta_fn(a_inv, b))
    for idx in range(10):
        kl += torch.mul(torch.pow(idx+2+ab,-1), beta_fn(torch.mul(idx+2., a_inv), b))
    kl = torch.mul(torch.mul(beta-1,b), kl)
    psi_b = torch.digamma(b+SMALL)
    kl += torch.mul(torch.div(a-alpha,a+SMALL), -EULER_GAMMA - psi_b - b_inv)

    kl += torch.log(ab) + torch.log(beta_fn(alpha, beta) + SMALL)

    kl += torch.div(-(b-1),b +SMALL)
    return kl

class VAE(GMMVAE):
    def __init__(self, hyperParams, K, nchannel, base_channels, z_dim, w_dim, hidden_dim, device, img_width, batch_size, include_elbo2):
        global local_device
        local_device = device
        super(VAE, self).__init__(K, nchannel, base_channels, z_dim, w_dim, hidden_dim,  device, img_width, batch_size)

        self.prior      = hyperParams['prior']
        self.K          = hyperParams['K']
        self.z_dim      = hyperParams['latent_d']
        self.hidden_dim = hyperParams['hidden_d']
    def get_ELBO(self, X):

        elbo = torch.tensor(0, dtype=torch.float)
        if self.include_elbo2:
            for k in range(self.K-1):
                elbo -= compute_kumar2beta_kld(self.kumar_a[:, k], self.kumar_b[:, k], self.prior, (self.K-1-k)* self.prior).mean().to(self.device)

I appreciate it if someone can suggest how to fix the error.

A: I am not sure if this is the "only" problem, but one of the device-related problems is this:
 elbo = torch.tensor(0, dtype=torch.float) <- this will create the elbo tensor on CPU
and when you do, elbo -= <some result>,
The result is on cuda (or self.device). This will clearly cause a problem. To fix, this just do
elbo = torch.tensor(0, dtype=torch.float, device=self.device)


text:
Q: RadContextMenu.DropDownOpened called before RadGridView.CurrentRow is changed I'm trying to change an item on my RadContextMenu depending on the currently selected row in my RadGridView (edit: OrderList). I want the item to be enabled if the databound item in the current row has the correct property value.
The problem is that when I directly rightclick a row to open the RadContextmenu the CurrentRow has not yet been updated, so DropDownOpened is called with the old row.
If I left click or double right click it works fine.
Here's a bit of the code:
OrderMenu.DropDownOpened += OrderMenu_DropDownOpened;

And the method
private void OrderMenu_DropDownOpened(object sender, EventArgs e)
{
    GoToParentOrderBtn.Enabled = GetSelectedOrder()?.ParentOrderId != null;
}

private OrderViewModel GetSelectedOrder()
{
    return (OrderViewModel)OrderList.CurrentRow.DataBoundItem;
}

A: Use dataGridView.EndEdit(); This function commits and ends the edit operation on the current cell being edited.
More info here

A: Sorry for not specifying that I'm using a radgridview.
I found a related answer which helped me solve my problem.
I ended up making an extension (so I can use it all around the application) to RadGridView which fire an event on mousedown:
public partial class RadExtendedGridViewController : RadGridView
{
    public RadExtendedGridViewController()
    {
        InitializeComponent();
        base.MouseDown += RadExtendedGridViewController_MouseDown;
    }

    private void RadExtendedGridViewController_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            var element = this.ElementTree.GetElementAtPoint(e.Location);
            GridDataCellElement cell = element as GridDataCellElement;
            if (cell?.RowElement is GridDataRowElement)
            {
                Rows[cell.RowIndex].IsSelected = true;
            }
        }
    }
}

I then changed my GetSelectedOrder to using SelectedRows instead of Current:
    private OrderViewModel GetSelectedOrder()
    {
        return (OrderViewModel)OrderList.SelectedRows.FirstOrDefault()?.DataBoundItem;
    }

And now it works as intended. Thanks for taking your time trying to help me :-)


text:
Q: Uniqueness of sinusoidal functions for first order differential equations with constant shift I am wondering about solutions to the following differential equation:
$f(x)=C_1 \cdot f'(x+C_2) \; \forall x \in \mathbb{R} \; \exists \; C_1, C_2 \in \mathbb{R}$. With $C_1, C_2$ being constant. Are the solutions uniquely in the family of sin/cos functions? It bugs me that I was not able to come up with a counterexample except for the trivial solution $f(x)=0$.

A: for c2=0 you have the solution $$f(x)=A*e^{1/c_1}$$  with  c2!=0 you have $$f(x)=A*e^{1/c_1} -c2/c1$$ no sin or cos
you get sin or cos for second order equations
trula

A: With the help of the Laplace transform and assuming some simplifications as for instance
$$
f(x) = c_1\phi(x+c_2)f'(x+c_2)
$$
with $\phi(x)$ the Heaviside step function, an approximation can be worked out. After Laplace transforming we have
$$
F(s) = c_1\left(s e^{c_2 s}F(s)-f(c_2)\right)
$$
or
$$
F(s) = -\frac{c_1f(c_2)}{1-c_1 s e^{c_2 s}}
$$
now introducing the Padé approximation of first order for $|c_2| < 1$
$$
e^{c_2 s} \approx \frac{1+\frac{c_2 s}{2}}{1-\frac{c_2 s}{2}}
$$
we have for small $c_2$
$$
f(t)=\frac{f\left(c_2\right) e^{-\left(\frac{1}{2 c_1}+\frac{1}{c_2}\right)t} \left(\left(6 c_1+c_2\right)
   \sinh \left(\frac{\sqrt{4 c_1^2+12 c_2 c_1+c_2^2} t}{2 c_1 c_2}\right)-\sqrt{4 c_1^2+12
   c_2 c_1+c_2^2} \cosh \left(\frac{\sqrt{4 c_1^2+12 c_2 c_1+c_2^2} t}{2 c_1
   c_2}\right)\right)}{\sqrt{4 c_1^2+12 c_2 c_1+c_2^2}}
$$


text:
Q: Having an error " Illegal arguments: string, undefined " while trying to post data using postman API For user authentication in node using bcrypt I have the following code but i get an error when i try to post using postman api  the error is "message": "Illegal arguments: string, undefined"
The data sent through the postman is
    {
       "password":"1234",
       "email":"prashanthyarram@gmail.com"
    }

I cannot find whats wrong with the code can you please help me through this.
This is the code for server.js
import express from 'express';
import userdata from './userdata.js';
import mongoose  from 'mongoose';
import userrouter from './routers/userrouter.js';
import productRouter from './routers/productrouter.js';

const app=express();

mongoose.connect(process.env.MONGODB_URL ||  'mongodb://localhost:27017/purpleshades',{
        useUnifiedTopology: true,
        useNewUrlParser: true
})

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get('/users/api/:id',(req,res)=>{
    const k=parseInt(req.params.id)
    const user1=userdata.users.find((x)=>x.uID===k)
    const cartinfo=user1.ucart
    const cartproductlist=[]
for (let i = 0; i < cartinfo.length; i++) {
    const pid = cartinfo[i];
    const productreal = data.products.find((x) => x.id === pid );
    cartproductlist.push(productreal)
}
    res.send(cartproductlist)
})

app.use('/api/users',userrouter)
app.use('/api/products',productRouter)
app.use((err,req,res,next)=>{
    res.status(500).send({message:err.message})
})
const port=process.env.PORT || 5000
app.listen(5000,()=>{
    console.log(`serve at http://localhost:${port}`);
})

code for userrouter.js
import express from "express";
import userdata from "../userdata.js";
import User from "../models/usermodel.js";
import expressAsyncHandler from "express-async-handler";
import bcrypt from 'bcryptjs'

const userrouter=express.Router()

userrouter.get('/seed',expressAsyncHandler( async(req,res)=>{
    const createdusers=await User.insertMany(userdata.users)
    res.send({createdusers})
}))

userrouter.post('/signin',expressAsyncHandler(async(req,res)=>{
    const user=User.findOne({email: req.body.email})
    if(user){
        if(bcrypt.compareSync(req.body.password,user.password)){
            res.send({
                _id:user._id,
                name:user.name,
                isAdmin:user.isAdmin,
            })
            return
        }
    }
    res.status(401).send({message:'invalid Email or Password'})
}))

export default userrouter

code for usermodel.js
import mongoose  from "mongoose";

const userschema=new mongoose.Schema(
    {
        name:{type:String,required:true},
        email:{type:String,required:true,unique:true},
        password:{type:String,required:true},
        isadmin:{type: Boolean,required:true ,default:false}
    },
    {
        timestamps:true
    }
)

const User=mongoose.model('User',userschema)
export default User

A: The findOne function is asynchronous, so this line assigns a promise to the variable user:
const user=User.findOne({email: req.body.email})

Since a promise is truish, this proceeds to call compareSync, but the promise does not have a password property:
    if(user){
        if(bcrypt.compareSync(req.body.password,user.password)){

Await the result of the findOne to get the document instead of a promise.


text:
Q: Remove jQuery tablesorter from table I am using the jQuery tablesorter (http://tablesorter.com).
After being applied to a table by $('#myTable').tablesorter(), how can I remove it again from the table?

A: Latest version of table sorter library provides Destroy method
From version 2.16 destroy() method has been added in table sorter library, use this method to remove tablesorter from the table.

A: use the function given below onclick event of remove shorting element
function removeTableShorter(){
$("#myTable").tablesorter({
headers: {
 0: {sorter: false},
 1: {sorter: false},
 2: {sorter: false},
 3: {sorter: false},
 4: {sorter: false},
 5: {sorter: false}
}
});
$('#myTable th').removeAttr('class');}

u may increase the number of headers according the number of columns of table.

A: There isn't a built-in function to do this, but you could remove the class names and event bindings to stop its functioning... try something like this:
$('table')
 .unbind('appendCache applyWidgetId applyWidgets sorton update updateCell')
 .removeClass('tablesorter')
 .find('thead th')
 .unbind('click mousedown')
 .removeClass('header headerSortDown headerSortUp');

The above won't work if you have the pager plugin running.

A: tablesorter2.0
$("#table").trigger("destroy");

or if you just in need to update all after appending new thead :
$("#table").trigger("updateAll");

-> http://mottie.github.io/tablesorter/docs/index.html


text:
Q: A subgroup of $\mathbb{Z}$ Let $A$  be a subgroup of $\mathbb{Z}$. Show that $A=\{0\}$ or $A\cong\mathbb{Z}$.
My intuition is to do something with the generator(s) of A (maybe it's not the best thought), but I have no idea how to start the proof.

A: Hint: If $A \neq \{0\}$ then $A$ must contain a positive number (why? inverses!) so there exists a smallest positive number in $A$, call this $a$.  Define $\mathbb Z \to A$ by $n \mapsto na$ and try to show that this is surjective (use the remainder theorem) and injective (easy).


text:
Q: Is it possible to get a notification when observable is completed for cold stream? I am writing an http filter that works on a stream:
override fun handleStream(ctx: StreamServerRequestContext): Observable<T> {
    counter.incrementAndGet()
    val observable: Observable<T> = ctx.invokeStream<T>()
    observable.subscribe(object : Observer<T> {
        override fun onError(e: Throwable?) {
            val dec = counter.decrementAndGet()
            logger.info { "value after error dec $dec" }
        }

        override fun onNext(t: T) {
        }

        override fun onCompleted() {
            val dec = counter.decrementAndGet()
            logger.info { "value after dec $dec" }
        }
    })
    return observable
}

I would like to increase a counter before the request and decrease it after. Since it is working with cold stream the effect is that the observable code is executed twice with the above code.
Can I "listen" to stream completion without actually invoking it again?

A: You can just use doFinally operator:
override fun <T> handleStream(ctx: StreamServerRequestContext): Observable<T> {
    counter.incrementAndGet()
    return ctx.invokeStream<T>()
        .doFinally {
            val dec = counter.decrementAndGet()
            logger.info { "value after dec $dec" }
        }
}


text:
Q: Git bash frozen after git push I'm new to git and I was learning to use git push a changed file to a repository in my github. But when I use git push origin master nothing comes up and it break until I use cntrl + c. I saw many faced the same issue but none of the solutions worked for me. Something that I realized, sometimes as I break the session a window pops up and ask for user name passwords for Github, but when I enter it say broken pipe. I assue it should pop up before I break the session using cntrl+ c but not luck yet. Any ideas?
P.S : I have cloned a repository and and git remote -v returns origin  https://github.com/username/reponame (fetch) origin  https://github.com/username/reponame (push)


text:
Q: Is there any way to change R# font size? is there any way to change the resharper dialogs font size.
Supposedly it should be a way to do this on VS going to tools-> options-> environment -> fonts and colors -> resharper...
But in my case there is no such option. Am I missing something obvious here?
I tryed uninstalling resharper, repairing resharper, uninstall VS and re install R# but nothing seems to work....(And I tryied in four different machines)
I'm running R#7, VS2012 on a Win8 machine.
Any help will be apreciated.

A: Under Fonts and Colors -> Show settings for: -> "Environment Font"
You might find that R# uses the "Environment Font" which is the same font for things like Solution Explorer, menu items, etc.  Try changing it and see if it effects resharper.  Of course if they designed it this way, it means your entire VS environment is affected.


text:
Q: Replacing old indexed data with new data in Apache Solr with zero downtime Requirement-
Replace old indexed data with new indexed data every night in Apache Solr.
Until the new data is indexed completely, I want old data to be searched for this duration. And when new data indexing is completed, then there should be switching logic, that will point the searching to new data in no time. After this old data should be deleted.
Is there a switching concept in Apache Solr which handle this scenario?
There are 100 000 documents which need to be indexed.

A: there is: Aliases.

*

*Your app should hit solr via aliases, not hitting real collection directly

*You build a new collection while the old one is being used

*After it is built, you change the alias to point to the new collection, no downtime

*you delete the old collection (if you want).

The above is if you are using SolrCloud. If you are not, you can do a similar thing with the Core api


text:
Q: Updating Progress bar from another class I am writing a code that reads considerably large arxml file and stores data from it. I have a main class ARXMLParser and a class called ParsedDatabase. I am calling a function from main loadFromArxml and passing the path of file as parameter. The function would read and store that data. I want to update Progress bar in main as the function loadFromArxml is reading data.
I am using class Task and performing my function in it. However I don't know how would I update progress from it.
This is my main code
import java.io.File;

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import parser.ParsedDatabase;

public class ARXMLParser extends Application {
    private ProgressBar progress;

    @Override
    public void start(Stage primaryStage) {

        TextField arxmlPath = new TextField("");
        arxmlPath.setEditable(false);
        arxmlPath.setFocusTraversable(false);
        arxmlPath.setPromptText("ARXMl File");

        Label arxmlLbl = new Label("No File Selected");

        Button btnArxml = new Button("Browse");
        btnArxml.setOnAction(e -> {
            FileChooser chooser = new FileChooser();
            chooser.setInitialDirectory(new File(System.getProperty("user.dir")));
            FileChooser.ExtensionFilter fileExtensions = new FileChooser.ExtensionFilter("ARXML Files (*.arxml)",
                    "*.arxml");
            chooser.getExtensionFilters().add(fileExtensions);
            File file = chooser.showOpenDialog(primaryStage);
            if (file != null) {
                arxmlPath.setText(file.getAbsolutePath());
                arxmlLbl.setText(file.getName());
            }
        });

        HBox arxmlHbox = new HBox();
        arxmlHbox.setSpacing(10);
        arxmlHbox.getChildren().addAll(arxmlPath, btnArxml);
        HBox.setHgrow(arxmlPath, Priority.ALWAYS);
        HBox.setHgrow(btnArxml, Priority.ALWAYS);

        progress = new ProgressBar();
        progress.setPrefWidth(Double.MAX_VALUE);

        Button btnParse = new Button("Parse");
        btnParse.setOnAction(e -> {
            ParsedDatabase parsedDatabase = new ParsedDatabase();
            if (!arxmlPath.getText().isEmpty()) {
                Task<Void> parse = new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {
                        // Function that reads the file
                        parsedDatabase.loadFromArxml(arxmlPath.getText());
                        return null;
                    }
                };

                progress.progressProperty().bind(parse.progressProperty());
                Thread thread = new Thread(parse);
                thread.setDaemon(true);
                thread.start();
            }
        });

        VBox vBox = new VBox();
        vBox.setFillWidth(true);
        vBox.setSpacing(15);
        vBox.getChildren().addAll(arxmlHbox, arxmlLbl, btnParse, progress);
        vBox.setPadding(new Insets(15, 10, 15, 10));

        Scene scene = new Scene(vBox, 500, 170);
        primaryStage.setTitle("ARXML Parser");
        primaryStage.setResizable(false);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public void setProgressBar(Double value) {
        progress.setProgress(value);
    }

    public double getProgress() {
        return progress.getProgress();
    }
}

And my ParsedDatabase class
package parser;

import java.io.File;
import java.util.Scanner;

public class ParsedDatabase {

    public void loadFromArxml(String arxmlPath) throws Exception {

        File file = new File(arxmlPath);
        Scanner scan = new Scanner(file);
        while (scan.hasNext()) {
            System.out.println(scan.nextLine());
            // Update progress based on file length
        }
        scan.close();
        // Update progress
        exportToExcel();
        // Update progress
    }

    public void exportToExcel() {
        // Export to excel
       // Update progress
    }
}

I was wondering how to update progress from the method. I do know there is a way I can do it. That is if I call both functions from main and from there updating progress is easy. Something like this
updateProgress(0, 1.0);
parsedDatabase.loadFromArxml(arxmlPath.getText());
updateProgress(0.5, 1.0);
parsedDatabase.exportToExcel();
updateProgress(1, 1.0);

However, The progress bar then will not progress smoothly but will go from 0 to 50 and to 100. I want it to be continuous. If there is a better way to achieve the same thing please let me know. This isn't an assignment. I am just learning concurrency at my own.

A: One possible solution is to have the code that you are running in loadFromArxml() be moved to the Task's call() method.
Then you can update the progress from within the actual working method. Then just bind your ProgressBar as usual.
Here is a complete example to demonstrate, with loadFromArxml() in a separate class.

ProgressTaskExample.java:

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ProgressTaskExample extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {

        // Simple Interface
        VBox root = new VBox(10);
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(10));

        // The ProgressBar
        ProgressBar progressBar = new ProgressBar(0.0);

        // Button to start the task
        Button button = new Button("Run Task");
        button.setOnAction(event -> {

            System.out.println("Starting task ...");

            // Get the loading Task
            final Task<Void> task = Datasource.loadFromArxml();

            // Catch any exceptions
            task.setOnFailed(wse -> {
                System.out.println("Error");
                task.getException().printStackTrace();
            });

            // Print success when complete
            task.setOnSucceeded(wse -> {
                System.out.println("DONE!");
                progressBar.setStyle("-fx-accent: #19ee15");
            });

            // Bind our ProgressBar's properties
            progressBar.progressProperty().bind(task.progressProperty());

            // Run the task
            new Thread(task).start();

        });

        // Add our nodes to the scene
        root.getChildren().addAll(button, progressBar);

        // Show the stage
        primaryStage.setScene(new Scene(root));
        primaryStage.setTitle("Sample");
        primaryStage.show();
    }
}

Datasource.java:

import javafx.concurrent.Task;

public class Datasource {

    public static Task<Void> loadFromArxml() {
        return new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                // Do your processing here

                updateProgress(0, 100);

                // Run for 5 seconds
                int i = 0;
                while (i < 100) {
                    Thread.sleep(50);
                    i++;

                    updateProgress(i, 100);
                }

                return null;
            }
        };
    }
}


text:
Q: What is the expected behaviour of `C_wrapKey` API if wrapping key is not provided? In the library that I have developer passes source key and CK_INVALID_HANDLE (instead of wrapping key) to C_wrapKey API and in return I get success.
I doubt this behaviour. Is this the correct return code?

A: If you mean that C_WrapKey receives an invalid value for hWrappingKey parameter, then it should return CKR_WRAPPING_KEY_HANDLE_INVALID.


text:
Q: Mudar Nome de Uma String em um Vetor de Estruturas Boa tarde galera, to travando em uma parte do meu código e realmente não sei a lógica para resolver ele.
Se o nome do fabricante do vetor carros na posição j for igual Chevrolet, mude ele para GM.
for(j = 0; j < qtd; j++) {
    if(carros[j].fabricante == "Chevrolet") {
       carros[j].fabricante = "GM";
    }
}

A: Utilize a função strcmp. Adicionalmente, você precisa utilizar a função strcpy para fazer a atribuição do valor GM. Ambas são definidas no cabeçalho string.h
for (j = 0; j < qtd; j++) {
    if (strcmp(carros[j].fabricante, "Chevrolet") == 0) {
       strcpy(carros[j].fabricante, "GM");
    }
}


text:
Q: Situation where Users can add/remove Columns Situation Overview
The current question is about a situation where the software user, the client, wants to make an evaluation of a material. This evaluation can be done with 1 or more criterias that the user can add and remove from a supervisor area of the software. Notice that the evaluation must be saved in the database for future consultation.
Extra information: The software is coded in Java.
Objective
Suppose Three tables. Table Material, table Evaluation and Table Criteria.
Notice that the PK idMaterial is a FK in Evaluation.
The image below illustrates the tables:

These three tables are a simplification of the real tables. The Criteria table name the criteria variable and set its weight for the final score calculted on the evaluation.
In this case, the objective is that the user be able to add and delete criteria.
With the criteria defined, he can then create evaluations for the materials.
And use these criterias to save an evaluation on the database.
In other words, I need to store the score given to each user-defined criteria.
Problem
From a technical point of view, we notice that:

*

*The software would have to allow the user to delete and add columns. That is a bit tricky since if he deletes 2 columns and adds 1, the code would have to find which column he deleted and delete them only and then just add a single column. That example is tricky in the sense that, if we could just delete all columns and just add the ones he maintained/added would be easier in code.

*Messing with table columns seems dangerous for the integrity of the table. Especially under unknown connection(?) circumstances.

I'm looking for a better and safer solution.
Any advice is greatly appreciated. I hope I made the question as clear as possible.
Constraints
There are no constraints for a solution except that, I'm using Java and MySQL.
I can create more tables if needed and I can allow the user to add/delete columns.

A: Based on your comment then, you should just create a table for criteria, where the user adds a row which specifies what the evaluation criterion is. This will be much safer to add and delete to as you are not altering the actual table properties, but instead manipulating entries
EDIT:
To use this simply use an INSERT INTO statement, where you insert the values into the columns.

A:
But How Do I create an Evaluation afterwards? Since in your solution every criteria is a row... Would you exemplify, please?

We have something equal in one of our systems, where the user can define 0 upto infinite criterias for something.
Thus, you need to use rows.
In Detail, A user can attach one or more filters (they are or'd) where each filter can contain one or more criterias (they are and'd)
Evaluation from the code side looks like this. (This is no copy/paste code, but might give you an idea). environmentVariables is basically a map containing the objects properties on which we are trying to apply the filter:
public static boolean evaluate(Filter filter, Map<String, Object> environmentVariables) {
    for (Criteria criteria : filter.getCriterias()) {
        if (!evaluateCriteria(criteria, environmentVariables)) {
            // one missmatch -> false.
            return false;
        }
    }

    // all criterias matched, that filter is true.
    return true;
}

public static boolean evaluateCriteria(Criteria criteria, Map<String, Object> environmentVariables) {
    if (environmentVariables != null) {
        if (environmentVariables.containsKey(criteria.getKey())) {
            return evaluateCriteria(criteria, environmentVariables.get(criteria.getKey()));
        }
    }
    return false;
}

private static boolean evaluateCriteria(Criteria criteria, Object value) {
    switch (criteria.getOperator()) {
        case LIKE:
            if (value != null) {
                return value.toString().toLowerCase().contains(criteria.getValue().toString().toLowerCase());
            } else {
                return false;
            }
        //other OperatorTypes
        case STARTSWITH: // code...
        case ENDSWITH: // code...
        case EQUALS: // code...
        case GREATER_THAN: // code...
        case GREATER_THAN_EQUAL: // code...
        case LESSER_THAN: // code...
        case LESSER_THAN_EQUAL: // code...
        default:
          throw new UnsupportedOperationException(criteria.getOperator() + " is not defined");

    }
}

A: add the extra table criteria with two foreign features as primary key..two solutions exist the last one as i said and this you have draw


text:
Q: Time series regression with overlapping data I am seeing a regression model which is regressing Year-on-Year stock index returns on lagged (12 months) Year-on-Year returns of the same stock index, credit spread (difference between monthly mean of risk-free bonds and corporate bond yields), YoY Inflation rate and YoY index of industrial production.
It looks thus (though you'd subsitute the data specific to India in this case):
SP500YOY(T) = a + b1*SP500YOY(T-12) + b2*CREDITSPREAD(T) +
b4*INDUSTRIALPRODUCTION(T+2) + b3*INFLATION(T+2) + b4*INFLATIONASYMM(T+2)

SP500YOY is the year-on-year returns for SP500 index To compute this, monthly average of SP500 values is computed and then converted to year-on-year returns for each month (i.e. Jan'10-Jan'11, Feb'10-Feb'11, Mar'10-Mar'11, . . ). On the explanatory variables side, a 12-month lagged value of the SP500YOY is used along with the CREDITSPREAD at time T and INFLATION and INDUSTRIALPRODUCTION two period AHEAD. The INFLATIONASYMM is a dummy for whether the Inflation is above a threshold value of 5.0%. The index in the parenthesis shows the time index for each variable.
This is estimated by standard OLS linear regression. To use this model for forecasting the 1,2 and 3-months ahead YOY returns of SP500, one has to generate 3,4 and 5-month ahead forecasts for Inflation and the Index of Industrial Production. These forecasts are done after fitting an ARIMA model to each of the two individually. The CreditSpread forecasts for 1,2 and 3 month ahead are just thrown in as mental estimates.
I'd like to know whether this OLS linear regression is correct/incorrect, efficient/inefficient or generally valid statistical practice.
The first problem I see is that of using overlapping data. i.e. the daily values of the stock index are averaged each month, and then used to compute yearly returns which are rolled over monthly. This should make the error term autocorrelated. I would think that one would have to use some 'correction' on the lines of one of the following:

*

*White's heteroscedasticity consistent covariance estimator

*Newey & West heteroscedasticity and autocorrelation consistent (HAC) estimator

*heteroscedasticity-consistent version of Hansen & Hodrick

Does it really make sense to apply standard OLS linear regression (without any corrections) to such overlapping data, and more so, use 3-period ahead ARIMA forecasts for explanatory variables to use in the original OLS linear regression for forecasting SP500YOY? I have not seen such a form before, and hence cannot really judge it, without the exception of correcting for the use of overlapping observations.


text:
Q: Import Esri/ArcGIS .e00 files to QGIS on Linux (getting error message)? I can't seem to import Esri .e00 files into QGIS, and I can't figure out why.  I'm trying to import files I've downloaded from ftp://ftp.granit.sr.unh.edu/pub/GRANIT_Data/Vector_Data/Environment_and_Conservation/d-landcover/d-1995/.  Based on the answer to this question: Adding .e00 data into QGIS, I tried importing lan23205.e00 as a vector file, and get an error message stating that it is "not a valid or recognized data source"
What is going on here?
Note: I'm running Ubuntu Linux.

A: They are raster coverages, not vector.  I was able to open one of them using the Add Raster Layer button in QGIS.  Here's what gdalinfo says about the file:
Driver: E00GRID/Arc/Info Export E00 GRID
Files: lan231.e00
Size is 345, 223
Coordinate System is `'
Origin = (1059406.313363000100000,1023401.084660700100000)
Pixel Size = (93.493327489275273,-93.493327489238126)
Corner Coordinates:
Upper Left  ( 1059406.313, 1023401.085)
Lower Left  ( 1059406.313, 1002552.073)
Upper Right ( 1091661.511, 1023401.085)
Lower Right ( 1091661.511, 1002552.073)
Center      ( 1075533.912, 1012976.579)
Band 1 Block=345x1 Type=Int32, ColorInterp=Undefined
Min=200.000 Max=791.000
Minimum=200.000, Maximum=791.000, Mean=448.930, StdDev=75.639
NoData Value=-2147483647

A: One way is to convert it to another format using ogr2ogr:
http://geospatialdesktop.com/2011/11/converting-e00-files/


text:
Q: Do we say "a student quits class/school" when he is lazy to go to class/school but not quit class/school permanently? When we say "he quit school" it means he left school permanently and never come back.
However, some students are lazy to go to class/school but that doesn't mean they "quit class/school permanently". They will go back to class/school the next day.
Do we say "the boy quit class today because he was lazy but he will be back tomorrow"?

A: Simply put:

he skipped class/school

This reveals how he did not come for class and will come back, therefore "skip".


text:
Q: Abelian and non-abelian group where $a^{3} = e$? I was asked to find a group where $a^{3} = e$ $ \forall a \in G$, G being the group. I came across the Heisenberg group(which from my understand is the group of all $3 \times 3$ matrices which has one along its diagonals and 0s in the bottom half, and real numbers in the top half). But when I multiplied such a matrix by itself 3 times, I did not land up with the identity matrix.
Can someone help me if my definition of Heisenberg group is wrong, and with helping me find abelian and non-abelian groups where if the elements are cubed, we get the identity?

A: The original Heisenberg group is the group you describe: the $3\times 3$ matrices of the form
$$\left(\begin{array}{ccc}
1 & a & c\\
0 & 1 & b\\
0 & 0 & 1
\end{array}\right)\tag{1}$$
with $a,b,c\in\mathbb{R}$, which form a group under the usual matrix multiplication.
However, there is a generalization, and they are all generally known as "the Heisenberg group", and one is supposed to know which by context. Given any field $F$ (for example, the rationals, the complex numbers, the reals, the algebraic numbers, or a finite field of order $p$), you consider the matrices of the form $(1)$, but where now $0$, $1$, and $a,b,c$ are taken in the field $F$.
You should verify that these matrices form a group. In particular, if you take the entries in $\mathbb{F}_3=\mathbb{Z}/3\mathbb{Z}$, the integers modulo $3$, you obtain a nonabelian group of order $27$. (In general, taking them in $\mathbb{Z}/p\mathbb{Z}$ gives you a nonabelian group of order $p^3$). You should verify that it has the property you want.

A: $\mathbb{Z}_{3}$
$\mathbb{Z}_{3} \oplus\mathbb{Z}_{3}$
$\underbrace{\mathbb{Z}_3\oplus\cdots\oplus\mathbb{Z}_3}_{n\text{ factors}}$
All are examples of abelian groups whose every non identity element has order 3.
What you have mentioned, Heisenberg Group has order $27$.
it is collection of all upper triangular matrices with diagonal
entries 1 (entries of upper half comes from integer modulo 3 ($\mathbb{Z}_3$).


text:
Q: how to remove "call requires permission which may.." error in Android Studio My code
private void continueCall() {
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + phoneNoToCall));
        startActivity(callIntent);
}

Above requires whether user grant permission CALL_PHONE at run time which I have checked as
private void call() {
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
        continueCall();
    } else {
        requestCallPermission();
    }
}

Still Android studio showing error "call requires permission which may..."
How to remove this error? Or at least suppress it.

A: The method continueCall() could be called from multiple places. So it isn't guaranteed to have the permission check in call()
So you can only suppress the error by adding:
@SuppressWarnings("MissingPermission")

A: you need to put
 Intent callIntent = new Intent(Intent.ACTION_CALL);
 callIntent.setData(Uri.parse("tel:" + phoneNoToCall));
 startActivity(callIntent);

inside if block
private void call() {
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
        Intent callIntent = new Intent(Intent.ACTION_CALL);
        callIntent.setData(Uri.parse("tel:" + phoneNoToCall));
        startActivity(callIntent);
   } else {
        requestCallPermission();
   }
}

A: I think you need CALL_PRIVILEGED permission:

CALL_PRIVILEGED
Added in API level 1
String CALL_PRIVILEGED Allows an application to call any phone number,
  including emergency numbers, without going through the Dialer user
  interface for the user to confirm the call being placed.
Not for use by third-party applications.
Constant Value: "android.permission.CALL_PRIVILEGED"


text:
Q: How do I get the userID which is in most rows? SQL problem I am unable to move forward and can't find the appropriate example using Google Search. Maybe I just don't know how to phrase my search. Anyway, it is probably simple, and I just don't know how to get it.
How do I get the userID which is in most rows (the user that raised most tickets)?

Any tip or link to a similar solution would be really helpful.

A: I am not sure what you are looking for as the question is very vague. It would help to post sample data with expected results.
But, from what I understand, find the UserID with more tickets raised. The below query would give you the count of users with most on top.
SELECT UserId, COUNT(*)
  FROM Table
 GROUP BY UserId
 ORDER BY 2 DESC

A: Here's my take on it. Group counts by user ID, order by counts descending, and only take the first one.
SELECT
userID,
COUNT(*)
FROM unknown_table_name
GROUP BY userID
ORDER BY 2 DESC
LIMIT 1

EDIT: Adding disclaimer that LIMIT would not be supported on DB2, MSSQL, Oracle, and Informix

A: This query should do the trick
SELECT t1.UserId,
(
 SELECT COUNT(*)
 FROM {table} t2
 WHERE t2.UserId = t1.UserId
) counter
FROM {table} t1
 GROUP BY t1.UserId
 ORDER BY counter
DESC LIMIT 1

We count all the rows in which UserId appears, sort them in descending order and filter out the rest.


text:
Q: React Router with Node JS When using React-Router, you only serve up the original index.html with Node because the client handles the rest. I understand how to route between different pages once the user is at the home page. However, let's say the user types in the URL '/about'. Node will serve up the index.html, but how do you tell React-Router to then immediately take the user to the about page? Thank you.

A: If you have your BUILT create-react-app project sitting inside you node/public folder.  you need to let express know that the index.html file will be handling the routes.  see super simple server example below.  this will use react routers setup properly.
const express = require('express');

const app = express();
const path = require('path');

app.use(express.static(path.join(__dirname, 'public')));
app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'public/index.html')));

app.listen(3000);


text:
Q: RewriteRule for the dynamic part of url which is not permanent I have a
RewriteRule ^([^/]+)/id([0-9]+)/?$ /?page=$1&id=$2&location=$3 [L]

I need to make a rule for the part &location=
This part of url &location= is not permanent. The url originally presented without &location= but some links will include with part and I need to add it to the RewriteRule.
I was trying to do this way
RewriteRule ^([^/]+)/id([0-9]+)/([0-9]+)/?$ /?page=$1&id=$2&location=$3 [L]

But in this case the url like this
http://www.example.com/travel/id725

not found without 3-rd parameter. But I need it to work both ways
http://www.example.com/travel/id725
AND
example.com/travel/id725/43

Can you help me with it please?

A: You can add two different rules. First, when all three parameters are present; and then for the case where only two parameters are present.
RewriteRule ^([^/]+)/id(\d+)/(\d+)/?$ /?page=$1&id=$2&location=$3 [L]
RewriteRule ^([^/]+)/id(\d+)/?$ /?page=$1&id=$2 [L]


text:
Q: Doctrine MIN() low performance I have table (~150 columns with ~150k records) and project on Symfony 3 with Doctrine. In project is clasic filter to show results.
If you submit form i collect data in object $selectedInputOptions and build query looks like:
$query = $repository
        ->createQueryBuilder('t')
        ->select('t.idkatcountry', 't.idkatlocality', 't, MIN(t.price) AS priceFrom'......);

if(count($selectedInputOptions->getCountry()) > 0)
   $query->andWhere('t.idkatcountry IN (:idkatcountry )')->setParameter('idkatcountry ', $selectedInputOptions->getCountry());

if(count($selectedInputOptions->getLocality()) > 0)
   $query->andWhere('t.idkatlocality IN (:idkatlocality )')->setParameter('idkatlocality ', $selectedInputOptions->getLocality());

price column have decimal(15,2) datatype
Before i have in $repository->select('t.price') and everything was OK but after change this to 't, MIN(t.price) AS priceFrom' query execution time was increased +40% and in few cases (any input in form be blank = checks all records) +900%.
So my questions:
How i can cut execution time? (Is there some idexes for this?, Will help change datetype range let's say to decimal(6,2)?)
And bonus question :) Table has ~150columns but query for filtering using ~10-15 columns can i set some type of index for quicker selects?
EDIT:

*

*changed column price to ineger - did not help

*added index to column pricte - did not help

SOLUTION!
It was little mistake in select parameter using MIN().
Insted of:
't, MIN(t.price) AS priceFrom'
I used:
'MIN(t.price) AS priceFrom')'
Because t takes ALL columns (~150 in my case) and I didn't notice this... So now is everything OK and time is normal.

A: Here you can do one thing, stop loading unwanted data in entity, by using unset in jsonSerialize() method.


text:
Q: RabbitMq Consumer not processing messages I have made a consumer for RabbitMQ as a console application written in C#.NET. It is programmed to listen to a queue perpetually and whenever it find a message in the queue, it processes it. The consumer processes on an average 35 messages / second. The consumers are scheduled to run at system startup in the task scheduler. The consumers run fine for 3 - 4 days. But then, they keep on running but don't process any messages although the queue has messages in it. When the consumer is stopped and again started, it again starts processing the messages properly. But, by the time you manually restart, millions of messages get queued. Can someone please help me explain this abnormal behavior. I have other queues too which are running since months together without ceasing to stop.
Requesting prompt response. Thanks in advance to the experts.

A: I suggest you to look at the consumer code, it might be running but stuck in RabbitMQ exceptions. It sounds odd that it runs fine for 3-4 days.
I had similar problem of consumer not consuming messages in the queue because I was using "RabbitMQ.Client.QueueingBasicConsumer" to dequeue the message and when the queue was closed  abruptly although consumer was running but it was in System.IO.EndOfStreamException. I am using "RabbitMQ.Client.Events.EventingBasicConsumer" which has helped me to solve the issue.


text:
Q: What is the difference between entitlement and license key? Maybe it is more about business model than technical details.
It seemed to me that license key is giving users access to a product, while entitlement allows users to use some sort of service (like 2GB storage a month)?

A: Both are part of the same hierarchy of Customer Software Management.
At the point of sale for a software product the customer has purchased a license key and explicitly (with the specific EULA details he agrees to) gets the immediate benefits and responsibilities of that contract/license key.
But the customer also implicitly 'inherits' any add on privileges and benefits (entitlements) of that software sale too... such as future free versions within a time period, volume licensing, discount pricing.. which he may or may not make use of.
Further research on this... Safenet company...
http://www.safenet-inc.com/software-monetization/sentinel-entitlement-management/


text:
Q: Working with tables of equations in different units I frequently work with tables of engineering equations in different units. I suppose physicists might do the same thing. For example, a table might look like this:

Some of the values are inputs and others are computed from the inputs. I put them in spreadsheets with each column representing a different set of units, as you can see. In some cases I copy a formula from one column to the other. Other times, I will convert the value in one column to the other column using a unit conversion.
How can I do something like this in Mathematica? Ideally I would like the input values to be easily editable.
The Dream
What would be really cool is if any of the values could be edited and the other values would compute correctly. When I use a spreadsheet, this is impossible. I either have to make the cell contain a number (an independent value), or a formula (a dependent value). Usually, I color the inputs blue. If I could make it so that any cell could be edited and all the others would solve and update correctly, that would be very cool.

A: I think you want something like this.  I use InputField expressions with Dynamic values, and the second parameter of Dynamic to update Symbols.
tF = tC = -40;

TableForm[{InputField[Dynamic[tC, (tC = #; tF = 9/5 # + 32) &]],
  InputField[Dynamic[tF, (tF = #; tC = 5/9 (# - 32)) &]]},
 TableHeadings -> {{"Celsius", "Fahrenheit"}}]

Metaprogramming
From your comment below I take it that this behavior is what you want, but you seek an easy way to extend this to larger tables.  Here is one approach to that.  My function (toFields) takes a List of related equations, each with a single Symbol on the left-hand side which will become the field variable.  These Symbols must be unassigned (cleared) at that time.  The output is a list of InputFields as shown above, which may then be used in a Row, Grid, TableForm, etc. as desired.
Basic example
Clear[tC, tF, tK]

toFields[
  {tC == 5/9 (tF - 32), tF == 9/5 tC + 32, tK == tC + 273 + 3/20}
] // Column

A complete table
Clear[tC, tF, tK, ft, in, cm]

eq = {
   {tC == 5/9 (tF - 32), tF == 9/5 tC + 32, tK == tC + 273 + 3/20},
   {ft == in/12, in == cm 50/127, cm == 127/50 in}
   };

labels = {{"Celsius", "Fahrenheit", "Kelvin"},
          {"foot", "inch", "centimeter"}};

Grid[
  MapThread[Riffle, {toFields[FieldSize -> 5] /@ eq, labels}]
  , Alignment -> Left
]

Function code
toDynamic[s_][expr : _Equal | _And] :=
  Dynamic[s, (s = #; expr) & /. {Equal -> Set, And -> CompoundExpression}]

toFields[opts : OptionsPattern[InputField]][rel_] := toFields[rel, opts]

toFields[rel : {(_Symbol == _) ..}, opts___] :=
  With[{var = rel[[All, 1]]},
    InputField[#, opts] & @ toDynamic[#]@Reduce[rel, DeleteCases[var, #]] & /@ var
  ]


text:
Q: Default values of template parameters in the class template specializations Consider the following code:
template <class x1, class x2 = int*>
struct CoreTemplate { };

template <class x1, class x2>
struct CoreTemplate<x1*, x2*> { int spec; CoreTemplate() { spec = 1; } };

template <class x>
struct CoreTemplate<x*> { int spec; CoreTemplate() { spec = 3; } };

int main(int argc, char* argv[])
{
    CoreTemplate<int*, int*> qq1;
    printf("var=%d.\r\n", qq1.spec);

    CoreTemplate<int*> qq2;
    printf("var=%d.\r\n", qq2.spec);
}

MSVC compiles this code fine and selects the second specialization in both cases. For me these specializations are identical. How legal is the second specialization in the first hand?
Just curious, any thoughts about this?

A: The second partial specialization is legal, and is not identical to the first.
The second partial specialization doesn't list an argument for the second template parameter in its template argument list, so uses the default argument of int*, so it is equivalent to:
template <class x>
struct CoreTemplate<x*, int*> { ... };

Which will be selected for any instantiation where the first template argument is a pointer type and the second template argument is int*.
That is more specialized than the first partial specialization, which will be used when the first template argument is a pointer type and the second template argument is any pointer type except int*.
In your program both qq1 and qq2 use int* as the second template argument (either explicitly or using the default argument) so both select the second instantiation.


text:
Q: Wireshark traffice capture- one subnet to another subnet My setup is a computer with wireshark connected to switch on LAN network. The subnet IP that the wireshark is on is .0.# . I would like to capture traffic between subnet IP of .0.# and .2.#. However when I include the filter:
tcp and ip.addr==192.###.2.# && ip.addr==192.###.0.# (with # being numbers), I do not see traffic between those two IP's ? I have ping both IP FINE!
So is this possible and by click Edit Filter and putting in the above am I setting the filter correct?
Links or Tutorials would be great!

A: You need to make sure the switch is sending this traffic to the port that the Wireshark machine is plugged into. You can do this in a number of ways:

*

*If it's a manageable switch that supports port monitoring (also called port mirroring or other similar names) you can see what port one of your target endpoint machines (or the router between the subnets) is plugged into, and mirror that port to the port your Wireshark machine is on.

*If you don't have a manageable switch, but you happen to have a hub around, you can use a hub instead of the switch (or between the switch and one of the traffic endpoints). Unfortunately, there's no such thing as a gigabit switch, so this solution only works if you're okay with 10/100 mbit speeds.

*Run Wireshark on one of the endpoints of the test, or on the router that's connecting the subnets. Sometimes running a sniffer on one of the devices involved in the test can interfere with the test, so caveat lector.


text:
Q: extract dataframe from dataframe column an place it besides parent in R I have a dataframe consisting on 10 columns, one of them is another dataframe as a result of a rowwise() operation.
something like this (just an example, column2 is a dataframe not in a list):
   id   column1   column2
    1213   a         df
    2234   b         df
    4565   c         df

class(df$column2)
[1] "data.frame"

So, the data is grouped by row (see rowwise() in tidyverse site) and the issue is I want to extract the column2 dataframe and place it besides the rest of columns.as they have the same number of rows.
The usual tidyr::unnest() approach gives one error:
 unnest(c, cols = c(column2))
Error: Assigned data `map(data[[col]], as_df, col = col)` must be compatible with existing data.
x Existing data has 24356 rows.
x Assigned data has 124 rows.
i Only vectors of size 1 are recycled.

So I have extracted the column2 into another dataframe and then dplyr::bind_cols() but This is very dirty and I guess if there is a cleaner approach.

A: In base R you can try with
cbind(df[1:2], do.call(rbind, df$column2))

Using dplyr -
library(dplyr)
bind_cols(df[1:2], bind_rows(df$column2))

and tidyr -
tidyr::unnest_wider(df, column2)

#    id column1   mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
#  <int> <chr>   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1  1213 a          21     6   160   110   3.9  2.62  16.5     0     1     4     4
#2  2234 b          21     6   160   110   3.9  2.62  16.5     0     1     4     4
#3  4565 c          21     6   160   110   3.9  2.62  16.5     0     1     4     4

data
Tested all the answers on this data -
df <- structure(list(id = c(1213L, 2234L, 4565L), column1 = c("a",
"b", "c"), column2 = list(structure(list(mpg = 21, cyl = 6, disp = 160,
    hp = 110, drat = 3.9, wt = 2.62, qsec = 16.46, vs = 0, am = 1,
    gear = 4, carb = 4), row.names = "Mazda RX4", class = "data.frame"),
    structure(list(mpg = 21, cyl = 6, disp = 160, hp = 110, drat = 3.9,
        wt = 2.62, qsec = 16.46, vs = 0, am = 1, gear = 4, carb = 4), row.names = "Mazda RX4", class = "data.frame"),
    structure(list(mpg = 21, cyl = 6, disp = 160, hp = 110, drat = 3.9,
        wt = 2.62, qsec = 16.46, vs = 0, am = 1, gear = 4, carb = 4), row.names = "Mazda RX4", class = "data.frame"))), row.names = c(NA,
-3L), class = "data.frame")


text:
Q: what should be auto-loaded in emacs libraries? Emacs allows you to "autoload" functions with little cookies like ;;;###autoload
Is there any consensus on what should be autoloaded though? For example, does it make sense to autoload every interactive function in a module (suppose there are a lot of them, e.g. 50)? Or, does it make sense to only autoload the "main" ones.

A: You only autoload the "main" ones. For example, python-mode.el only has a few occurances of autoload:
;;;###autoload
(add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'")  'python-mode))
;;;###autoload
(add-to-list 'interpreter-mode-alist (cons (purecopy "python[0-9.]*") 'python-mode))
--
;;;###autoload
(defun run-python (cmd &optional dedicated show)
--
;;;###autoload
(define-derived-mode python-mode prog-mode "Python"

Only the "entry" functions are autoloaded. The dozens of helper functions are only needed once you're already in python-mode.

A: There are several possible scenarios here, and the answer will depend on which one you are working with.
The simple and obvious situation is with a library with a lot of interactive functions but only a few "main" entry points.  The version control modes for Emacs are good examples -- there are many ways to interact with the version control back end, but the first step will usually happen when you check out a piece of code from version control, or want to examine what changes you have made in order to start committing.  So these are the main entry points, and the others will be useful only when you start one of these operations (at least in the typical case).
A somewhat likely but unfortunate scenario would be a "module" which really is many small modules who want to be modules of their own.  If internal cohesion is weak, maybe you should think about moving some parts of the code into separate, smaller libraries.  (There are Emacs libraries which ship with the distribution which fit this description.)
If you really have a complex problem which requires a lot of different entry points, perhaps in fact you do want to expose them all.  Grasping a bit at straws here, I think of e.g. a statistics package -- there are many, many methods to choose from, and you don't know in advance which one will make sense for each scenario.  (Typically this sort of behemoth package will require at least a Bachelor's degree in the subject matter to operate properly, though!)


text:
Q: Convert HTML entities in plain text to characters I scraped news article titles and URLs, and stored the titles and urls in a tsv file as plain text. For some reason, the scraper I use converts some characters (€ for example) into hexacode. I have tried to change this on the scraper side, but no luck. What I want, is to change the hexacode into the actual character, so that I can load the actual strings into a Postgres database.
An example could be the following string: Motorists could be charged for every mile they drive to raise €35bn, which should be stored in the db as Motorists could be charged for every mile they drive to raise €35bn
What I have tried so far is find all hexacodes in the file, strip off the &#x parts, and convert the hexacode into the actual character with in the € case:
s_decoded = bytes.fromhex("20AC").decode('ascii')
and
s_decoded = bytes.fromhex("20AC").decode('utf-8')
which respectively give the errors: UnicodeDecodeError: 'ascii' codec can't decode byte 0xac in position 1: ordinal not in range(128) and UnicodeDecodeError: 'utf-8' codec can't decode byte 0xac in position 1: invalid start byte.
I have been going over loads of previous questions on here, but just can't seem to figure out why this is happening in my case. Sorry if this is a duplicate, but if someone could then point me to what would solve my problem, that would be much appreciated.

A: To decode HTML Entities like of your example you could use the following code.
html_encoded = 'Motorists could be charged for every mile they drive to raise €35bn'
import html
html_decoded = html.unescape(html_encoded)
print(html_decoded)


text:
Q: Issue adding a new field to an entity in crm 2011 I am running into an issue when adding a new field to an entity. In my entity I had 526 fields, I tried to add a new one but I got the error message "Attribute xxx cannot be created because we have hit a maximum number of attributes allowed for an entity (1000)". However I only have 526 fields in the entity. Furthermore, I deleted one field I don't need anymore and I tried to add my new field but I still have the same error message even though I've deleted one field. Could anyone help me out please. I do appreciate it. Thanks !
Walloud

A: You will be hitting the column limit, even with only 526 fields.
You have to remember that CRM will add its own fields in addition to the ones that you have, such as ones for base currency. This can take you over the limit.
Also consider that the Filtered Views that CRM automatically creates have extra columns for lookup (name), optionset (name) and date (local) fields which can also mean you exceed the limit there.
I think your only options are to delete more fields in order to free up the room, or re-architect your entity design to split it over multiple related entities instead

A: Looks like you are facing the SQL Server 8k row limit
you can check the field names and verify this.
more information here:
http://mileyja.blogspot.com/2013/09/dealing-with-8k-sql-server-row-limits.html

A: You need to remember that some fields, such as currency will have two separate fields in SQL thus increment the column count by two for each one you create. If you have 500+ fields on a single entity then it is time to normalize the data and start breaking it out into related entities. It will be better for performance and your data in the long run.
http://en.wikipedia.org/wiki/Database_normalization
Cheers!


text:
Q: Can't call method from onClickListener I'm new to android, just trying to get my head around it, but I can't seem to get this to work: I want when a user taps a button a method will be called to see if the 2 password boxed contain the same text, if they do n AlertDialog box will pop up saying that the password has been set. However the alertdialog box never pops up at all for somereason, thanks for your help.
package com.example.jhonti.test2;

import android.app.Activity;
import android.app.AlertDialog;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MyActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    // It works when I put it here
    //AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
    //altDialog.setMessage("Password set"); // here add your message
    //altDialog.show();

    final EditText a = (EditText) findViewById(R.id.editText);
    final EditText c = (EditText) findViewById(R.id.editText2);

    Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

            if(a.getText().toString() == c.getText().toString())
            {
                setPass(a.getText().toString(), c.getText().toString());
            }
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.my, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void setPass(String i, String o)
{
    if((i == o) && (i != ""))
    {
        AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
        altDialog.setMessage("Password set"); // here add your message
        altDialog.show();

    }
}

}

A: Try this used .equals() method for String comparison
 if(a.getText().toString().equals(c.getText().toString()))

A: in your code instead of
a.getText().toString() == c.getText().toString()

use
a.getText().toString().equals(c.getText().toString())

you can't compare two strings the way are you doing

A: You should remove final. Instead use nothing or public


text:
Q: C# getting the HTML document from a Javascript Iframe I am trying to access this webpage http://www.pof.com with C# code.
I figured out that the Document element is stored in an iframe after I successfully logged in as a user and I am not familiar with how to access the document element.
All I want to do is to get the HTML format of that page which is loaded with an iframe and go to some of the links of that site.

A: Use following code:
document.getElementById('iframe1').contentWindow.document

or simply,
var elemVal;
if (iframeDocument) {
   elemVal= iframeDocument.getElementById('#iframe1');
}


text:
Q: Choose where tab content goes in jQuery tabs I was wondering if anyone knows how to choose where to add the content, I tried adding the option load : function() {} or added in ajaxOptions: { success : function() {...} }

Learn@UW

HCI 570

Finance 300

Handball

Accounting 301

EPD 375

+

        // Put the content here...

Thanks a lot!
Matt Mueller

A: Change contentContainer to tabs-1 and place it next to your links.

Learn@UW

HCI 570

Finance 300

Handball

     // Put the content here...

Example here : http://jqueryui.com/demos/tabs/#ajax


text:
Q: Why shouldn't you use a global variables for the Selenium webdriver? As I am new to OO programming this may seem a trite question.
I am trying to write a basic End-User testing framework which has a class Pageobject with the majority of method code.
I have a testing script which instantiates the selenium driver at the top-level and then I have a number of Page object method calls to "do stuff".
If I instantiate the driver at the top-level then I need to pass the driver object to any method that needs it which is fine but I would like to minimise the number of parameters passed to a method call for the saake of readability.
eg. home_page.login(this_user) reads a little better than home_page.login(this_user, selenium_driver).
I know global variables are frowned upon so is there any other way that all method can have access to an object in a different scope.

A: I access all my Page objects in my tests through a PageRepo class that initializes all of my Page objects.
I initialize the PageRepo class in a base class that my test classes inherit from This is also where I initialize my WebDriver.
so my tests look like this.
PageRepo.HomePage().DoSomething()


text:
Q: How to send Mat H=findHomography return to Matlab I try to use the OpenCV Function findHomography. I use Mex OpenCV. My Problem is how can I return the Mat H Array to MATLAB.
I hope anybody can help me :-)
Example code is:
enter code here

#include "opencvmex.hpp"
#include "math.h"
#include "mex.h"
#include "matrix.h"

using namespace std;
using namespace cv;

void mexFunction(int nlhs, mxArray *plhs[],
            int nrhs, const mxArray *prhs[]){

    //create "CV_32FC2" Array
    Mat srcPoints(4,1,CV_32FC2);

    srcPoints.at<int>(0)=221;
    srcPoints.at<int>(1)=227;
    srcPoints.at<int>(2)=237;
    srcPoints.at<int>(3)=255;

    Mat dstPoints(4,1,CV_32FC2);

    dstPoints.at<int>(0)=120;
    dstPoints.at<int>(1)=67;
    dstPoints.at<int>(2)=91;
    dstPoints.at<int>(3)=113;

    // findHomography

    Mat H;

    int method=0;
    double ransacReprojThreshold=3;
    int maxIters = 2000;
    double confidence = 0.995;

     H = findHomography(srcPoints,dstPoints);
  }

A: You can use ocvMxArrayFromMat_{DataType}, in your case probably best to use:
plhs[0]=ocvMxArrayFromMat_double(H);

Here is the documentation of the OpenCV interface, so you can look at the available fucntions.


text:
Q: hide html attribute in inspection browsers i want to create a video learning site.

I want people can't get to download my videos.

how to hide element attribute in inspection browsers because people can't get the video URL in inspection browsers

how to disable download button in video element

A: You can't hide a HTML element from the browser. You could create a seperate website which host the video's but doesn't show the real link to the video (proxy website) and only allow the ip-address of the "front-end" website to access those videos.

A: It's simply not possible. It will be visible in the HTML source code anyways. Only server-side code won't appear in the page's source on client-side.
Sidenote: Even if you could hide the video tag or the video's URL in the source, the browser should download the video itself which can be found in Chrome (or other browser's) Developer Console.


text:
Q: Set cookies when downloading files with Salt Is there a way to set cookie values for files downloaded by HTTP on file.managed or archive.extracted. Something along the lines of
my-archive:
  archive.extracted:
    - name: /opt/
    - archive_format: tar
    - tar_options: z
    - source: http://myserver/my-archive.tar.gz
    - source_cookies:
      - cookie1: value1
      - cookie2: value2

My concrete use case is downloading jdk from oracle which requires a cookie accepting the license to be downloaded?
Is there anyway to achieve that?

A: That would be an awesome option to have, but it's not available yet. I've seen this done, though.  It's kind of hackish, but should work.

install-java:
  cmd.run:
    - name: |
        cd /tmp
        mkdir -p /usr/lib/jvm
        wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u40-b26/server-jre-8u40-linux-x64.tar.gz
        tar xzf server-jre-8u40-linux-x64.tar.gz -C /usr/lib/jvm
        update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_40/bin/java" 1
        update-alternatives --set java /usr/lib/jvm/jdk1.8.0_40/bin/java
    - cwd: /tmp
    - shell: /bin/bash
    - timeout: 300
    - reload_modules: true
    - unless: test -x /usr/lib/jvm/jdk1.8.0_40

A: There is no way to do this on this level unfortunately.
Please note that for the particular use case you mentioned (downloading oracle java) there is a formula available: https://github.com/saltstack-formulas/sun-java-formula
You can download/install the UnlimitedJCEPolicy files with too.

A: No, the archive module does not have any such functionality. Try rewriting the state to use cmd.run instead - this way you can pass whatever parameters you need to the download command.


text:
Q: in SRC assembly, what's the difference between "la" and "ld" commands? i know "la" stands for "load address", but is there's a difference at the loaded value to the register?
for example:
"la r1,X"
"ld r1,20"

in:
    0 ld r1,30
...
X: 20 add r6,7

where X is in address 20.

A: I'm not familiar with this assembler, but in general if you have a variable declared as X, then "la r1,X" will load the address of X and "ld r1,X" will load the contents of X.  In this case, that means that ld r1,20 will read the memory at location 20 and put the contents into r1, where la r1,x will just put 20 into r1 without an additional memory read.

A: la r2,X means ....load dispalcemebt X to r2.....its opcode in SRC architecture is 5
while
ld r1,20  means content of memory ie 20 is stored in r1...its opcode in SRC architecture is 1