text:
Q: Parse complex XML to CSV using Python I am trying to parse a complex XML file to CSV.
This is how my XML file looks like:
<?xml version="1.0" encoding="UTF-8"?>
<ke3600-menu-file language="en" display="English" index="1">
  <version major="0" minor="1" patch="0"/>
  <locale name="en_EN" timezone="CET-1CEST,M3.5.0,M10.5.0/3"/>
  <menu name="main_menu" display="Main Menu">
    <menu name="broadband" display="Broadband" help="100_help_broadband">
      <onenter proc="activateGfast"/>
      <menu name="load_save_profiles" display="Load and Save Profiles" help="601_help_profiles">
        <application name="load_profiles" display="Load Profile"/>
        <application name="save_profiles" display="Save Profile"/>
        <application name="remove_profiles" display="Delete Profile"/>
      </menu>
      <parameter type="list" name="wanInterface" display="Interface" help="101_help_wanInterface">
        <value id="0" name="ifDSL" display="xDSL"/>
        <value id="1" name="ifSFP" display="SFP"/>
        <value id="2" name="ifETH" display="Ethernet"/>
        <!-- <value i d="3" name="ifWLAN" display="WLAN"/> -->
        <value id="4" name="ifSHDSL" display="SHDSL"/>
      </parameter>

      <menu name="xdslinterface" display="xDSL Interface" help="200_help_xDslInterface">
        <parameter type="list" name="annex" display="xDSL Mode" help="201_help_xdslModi">
          <value id="0" name="xdsl_line_annex_a" display="Annex A/M"/>
          <value id="1" name="xdsl_line_annex_b" display="Annex B/J"/>
        </parameter>
        <application name="xdsl_macAddr" display="MAC Address" caption="MAC Address">
          <param type="string" name="xdsl_mac_addr" display="MAC Address" length="25"/>
        </application>
        <parameter type="list" name="xdsl_vectoring_mode" display="Vectoring Mode" help="202_help_Vectoring">
          <value id="0" name="xdsl_vectoring_mode_disabled" display="Disabled"/>
          <value id="1" name="xdsl_vectoring_mode_enabled" display="Enabled"/>
          <value id="2" name="xdsl_vectoring_mode_friendly" display="Friendly"/>
        </parameter>
        <parameter type="list" name="xdsl_gfast_mode" display="G.FAST">
          <value id="0" name="xdsl_gfast_mode_disabled" display="Disabled"/>
          <value id="1" name="xdsl_gfast_mode_enabled" display="Enabled"/>
        </parameter>
        <parameter type="list" name="resync" display="Auto Re-Sync">
          <value id="1" name="re_sync_on" display="On"/>
          <value id="0" name="re_sync_off" display="Off"/>
        </parameter>
        <parameter type="list" name="seamlessRateAdaption" display="Seamless Rate Adaption">
          <value id="0" name="sra_off" display="Off"/>
          <value id="1" name="sra_on" display="On"/>
        </parameter>
        <parameter type="list" name="xdsl_ginp" display="G.INP">
          <value id="0" name="xdsl_ginp_none" display="Off"/>
          <value id="1" name="xdsl_ginp_down" display="Down"/>
          <value id="2" name="xdsl_ginp_up" display="Up"/>
          <value id="3" name="xdsl_ginp_both" display="Down/Up"/>
        </parameter>
        <parameter type="list" name="power_cut_back" display="Power Cut Back">
          <value id="0" name="power_cut_back_off" display="Off"/>
          <value id="1" name="power_cut_back_on" display="On"/>
        </parameter>
        <parameter type="list" name="atmType" display="ATM Type">
          <value id="0" name="atm_type_aal5" display="AAL5"/>
          <value id="1" name="atm_type_aal0pkt" display="AAL0PKT"/>
          <value id="2" name="atm_type_aal0cell" display="AAL0CELL"/>
        </parameter>
        <parameter type="list" name="voip_atmType" display="Voip Interface ATM Type">
          <value id="0" name="voip_atm_type_aal5" display="AAL5"/>
          <value id="1" name="voip_atm_type_aal0pkt" display="AAL0PKT"/>
          <value id="2" name="voip_atm_type_aal0cell" display="AAL0CELL"/>
        </parameter>
        <parameter type="list" name="iptv_atmType" display="Iptv Interface ATM Type">
          <value id="0" name="iptv_atm_type_aal5" display="AAL5"/>
          <value id="1" name="iptv_atm_type_aal0pkt" display="AAL0PKT"/>
          <value id="2" name="iptv_atm_type_aal0cell" display="AAL0CELL"/>
        </parameter>
      </menu>

      <menu name="ethernetinterface" display="Ethernet Interface" help="300_help_ethernetInterface">
        <parameter type="list" name="ethInterfaceAuto" display="Autonegotiation">
          <value id="1" name="ethInterfaceAutoOn" display="On"/>
          <value id="0" name="ethInterfaceAutoOff" display="Off"/>
        </parameter>
        <parameter type="list" name="ethInterfaceSpeed" display="Speed">
          <value id="2" name="ethIf1000" display="1000MBit/s"/>
          <value id="1" name="ethIf100" display="100MBit/s"/>
          <value id="0" name="ethIf10" display="10MBit/s"/>
        </parameter>
        <parameter type="list" name="ethInterfaceDuplexMode" display="Duplex Mode">
          <value id="1" name="ethIfFull" display="Full"/>
          <value id="0" name="ethIfHalf" display="Half"/>
        </parameter>
      </menu>

      <menu name="shdslinterface" display="SHDSL Interface" help="400_help_shdslInterface">
        <menu name="shdslservice" display="SHDSL Service">
          <parameter type="list" name="shdslmode" display="SHDSL Mode" help="401_help_shdslModi">
            <value id="0" name="shdslAtm" display="ATM"/>
            <value id="1" name="shdslEfm" display="EFM"/>
            <value id="2" name="shdslTdm" display="TDM"/>
            <value id="3" name="shdslTu12" display="TU-12oSHDSL"/>
          </parameter>
          <parameter type="uint" name="shdsl_vpi" display="VPI" min="0" max="127" step="1" default="1" help="402_help_shdsl_vpi"/>
          <parameter type="uint" name="shdsl_vci" display="VCI" min="32" max="255" step="1" default="32"/>
          <parameter type="list" name="shdsl_encapsulation" display="Encapsulation">
            <value id="0" name="encap_vcmux" display="VCMUX"/>
            <value id="1" name="encap_llc" display="LLC"/>
          </parameter>
          <parameter type="list" name="shdsl_eth_fcs" display="Eth-FCS in PDU">
            <value id="1" name="eth_fcs_enabled" display="Enabled"/>
            <value id="0" name="eth_fcs_disabled" display="Disabled"/>
          </parameter>
          <parameter type="list" name="shdsl_efm_standard" display="Standard">
            <value id="0" name="shdsl_efm_standard_8023ah" display="IEEE 802.3ah"/>
            <value id="1" name="shdsl_efm_standard_g9912" display="G.991.2"/>
            <value id="2" name="shdsl_efm_standard_auto" display="Auto"/>
          </parameter>
          <parameter type="list" name="shdsl_tdm_framing" display="Clockmode">
            <value id="4" name="shdsl_tdm_framing_cm3a" display="CM3a: Synchron"/>
            <value id="1" name="shdsl_tdm_framing_cm1" display="CM1: Plesiochron"/>
            <value id="2" name="shdsl_tdm_framing_cm2" display="CM2: Plesiochron NTR"/>
          </parameter>
          <parameter type="list" name="shdsl_tdm_loop" display="Loopback">
            <value id="0" name="shdsl_tdm_loop_disabled" display="Disabled"/>
            <value id="1" name="shdsl_tdm_loop_lineside" display="Lineside"/>
          </parameter>
        </menu>
        <parameter type="list" name="shdsl_side" display="Side">
          <value id="0" name="shdsl_tur" display="STU-R"/>
          <value id="1" name="shdsl_tuc" display="STU-C"/>
        </parameter>
        <menu name="shdslmapping" display="Line Mapping">
          <parameter type="list" name="shdsl_mapping_line0" display="Line 1">
            <value id="0" name="shdsl_mapping_line0_0" display="4+5"/>
            <value id="1" name="shdsl_mapping_line0_1" display="3+6"/>
            <value id="2" name="shdsl_mapping_line0_2" display="7+8"/>
            <value id="3" name="shdsl_mapping_line0_3" display="1+2"/>
          </parameter>
          <parameter type="list" name="shdsl_mapping_line1" display="Line 2">
            <value id="1" name="shdsl_mapping_line1_1" display="3+6"/>
            <value id="2" name="shdsl_mapping_line1_2" display="7+8"/>
            <value id="3" name="shdsl_mapping_line1_3" display="1+2"/>
            <value id="0" name="shdsl_mapping_line1_0" display="4+5"/>
          </parameter>
          <parameter type="list" name="shdsl_mapping_line2" display="Line 3">
            <value id="2" name="shdsl_mapping_line2_2" display="7+8"/>
            <value id="3" name="shdsl_mapping_line2_3" display="1+2"/>
            <value id="0" name="shdsl_mapping_line2_0" display="4+5"/>
            <value id="1" name="shdsl_mapping_line2_1" display="3+6"/>
          </parameter>
          <parameter type="list" name="shdsl_mapping_line3" display="Line 4">
            <value id="3" name="shdsl_mapping_line3_3" display="1+2"/>
            <value id="0" name="shdsl_mapping_line3_0" display="4+5"/>
            <value id="1" name="shdsl_mapping_line3_1" display="3+6"/>
            <value id="2" name="shdsl_mapping_line3_2" display="7+8"/>
          </parameter>
        </menu>

I want to extract the following data:
"Count" "Label" "Name" "Type"
"1" "" "locale" ""
"1" "Main Menu" "menu" ""
"2" "Broadband" "menu" ""
"3" "Load and Save Profiles" "menu" ""

The first line defines the column names, and the rest of the data is just tab separated values, one line per record. The Count represents the menu position in the XML tree.
I have tried using the following code:
import xml.etree.ElementTree as ET
import csv

tree = ET.parse("menu.xml")
root = tree.getroot()

# open a file for writing

menu_data = open('/tmp/menu.csv', 'w')

# create the csv writer object

csvwriter = csv.writer(menu_data)
menu_head = []

count = 0
for member in root.findall('menu'):
    menu = []
    menu_list = []
    if count == 0:
        name = member.find('name').tag
        menu_head.append(name)
        label = member.find('Label').tag
        menu_head.append(Label)
        Count = member[3].tag
        menu_head.append(Count)
        csvwriter.writerow(menu_head)
        count = count + 1

    name = member.find('name').text
    menu.append(name)
    Count = member[3][0].text
    menu_list.append(Count)
    csvwriter.writerow(menu)
menu_data.close()

But I get the following error:
Detail AttributeError: 'NoneType' object has no attribute 'tag'

I can't figure out what's wrong. Also the tutorial I am following doesnt have much sub branches, But I have menu inside menu inside menu as you can see in my XML file.  Please let me know if you have any suggestion.

A:
Question: 'NoneType' object has no attribute 'tag'

You get that Error at this Line:
name = member.find('name').tag

The Reason, there is no Tag <name>, 'name' is a attribute of the Tag <menu name="main_menu">. Therefore you have to use:
name = member.attrib['name']

I assume you want something like that:
    csvwriter.writerow(["Count", "Label", "Name", "Type"])

    def iter_menu(menu_list, level=[1], deep=1):
        for n, menu in enumerate(menu_list, 1):
            level[deep-1] = n

            csvwriter.writerow(('.'.join([str(i) for i in level]), menu.attrib['display'], menu.attrib['name'], 'Type?'))
            level.append(0)
            iter_menu(menu.findall('menu'), level, deep+1)
            level = level[:deep]

    iter_menu(root.findall('menu'))

Output:
Count,Label,Name,Type
1,Main Menu,main_menu,Type?
1.1,Broadband,broadband,Type?
1.1.1,Load and Save Profiles,load_save_profiles,Type?
1.2,xDSL Interface,xdslinterface,Type?
1.3,Ethernet Interface,ethernetinterface,Type?
1.4,SHDSL Interface,shdslinterface,Type?
1.4.1,SHDSL Service,shdslservice,Type?
1.4.2,Line Mapping,shdslmapping,Type?

Tested with Python: 3.4.2


text:
Q: Populating ComboBox from SQL in C# I am trying to populate my combobox from sql but when i assign a value member to it, it gives me the following error
cannot explicitly convert int into string

Could you help me understand and correct my mistake?
 void Fillcombo()
    {
         string query_select = "SELECT * FROM department";
         DataTable dt = DataAccess.selectData(query_select);
         SqlDataReader dr = DataAccess.selectDataReader(query_select);
         while (dr.Read())
            {
                string dpt_name = dr.GetString(1);
                int dpt_id = (int)dr.GetValue(0);
                comboBox1.DataSource = dt;
                comboBox1.ValueMember = dpt_id; // error here
                comboBox1.DisplayMember = dpt_name;

            }
    }

A: You must assign name of column in DataSource (DataTable) to ValueMenmber and DisplayMember as string, and you don't need to use while loop, like this :
void Fillcombo()
{
    string query_select = "SELECT * FROM department";
    DataTable dt = DataAccess.selectData(query_select);
    comboBox1.DataSource = dt;
    comboBox1.ValueMember = "ColumnName_DepartmentID";
    comboBox1.DisplayMember = "ColumnName_DepartmentName";
}

A: You should write it in a string format:
comboBox1.ValueMember = "dpt_id";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Second embedded Javascript not running in HTML I have two embedded scripts in my HTML files but only the first one runs. The second one doesn't execute, it's just supposed to change the text of the paragraph. I'm really not familiar with javascript and don't know if there's some async wizardry going on. If I remove the jquery include (and change the code to use the plain method of changing elements), it works fine.

            Next Track

A: You have to separate the script tag, you cannot close it on the opening.

            Next Track


text:
Q: Axios Can't access Heroku app - Error : Network Error I'm using Express js as Server, and deploy to Heroku, and client side using React native (Expo) networking using Axios,
My problem when I use Postman and native Browser to request api, its perfecly working, but when I use axios to request api, show Network Error
Network Error
- node_modules/axios/lib/core/createError.js:15:17 in createError
- node_modules/axios/lib/adapters/xhr.js:88:22 in handleError
- node_modules/event-target-shim/dist/event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:575:10 in setReadyState
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:389:6 in __didCompleteResponse
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue

This my react native request api
useEffect(() => {
    axios.get('http://myapp.herokuapp.com/member-test', {
      headers:{
        "Content-Type": "application/json",
        'Accept': 'application/json',
      },
    })
      .then(res => {
        alert(res)
        const categories = res.data;
        console.log("Sukses");
      })
      .catch(function (response) {
        console.log(response)
        alert(response.message)
      })
  }, []);

And my server side
const app = express();
const PORT = process.env.PORT || 3000
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var corsOptions ={
  origin : true,
  credentials: true,
  exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar'],
  optionsSuccessStatus : 200
}
app.use(cors({corsOptions}));
app.get('/member-test', (req, res) => {
  res.send('Api Live');
});
app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

I dont know where the problem, I'm stuck for this few days,
I really need help for this problem

A: You are passing corsOptions as an Object to cors middleware, try to change this line
app.use(cors({corsOptions}));

In this
app.use(cors(corsOptions));

I hope it can be help you.


text:
Q: Shiny Server Error - could not find function "renderplot" I am new to Shiny and am trying to add a chord diagram to a shiny server. When I hit the runApp button in RStudio I get the application to run and it generates the UI, but then closes down immediately and I get the following error in the RConsole window: Error in (structure(function (input, output)  :
  could not find function "renderplot".
Unfortunately, I cannot attach the data as it is proprietary, but I am just creating an adjacency matrix in order to generate the chord plot. The Chord plot works fine outside Shiny. Thanks in advance!
My UI and Server code is below:
library(shiny)

# Starting line
shinyUI(fluidPage(

  # Application title
  titlePanel("Chord Chart"),

  # Sidebar
  sidebarLayout(
    sidebarPanel(
      #Data selection for Chord Chart
      selectInput("data","Select a Dataset:",
                  c("Marine"))),

    #The plot created in server.R is displayed
    mainPanel(
      plotOutput("plot")
)))
)

library(circlize)
library(dplyr)
library(reshape2)
library(manipulate)
library(shiny)

# read marine summaries
marine <- readfile("C:/Personal/R/MarineDataSummary.csv")

# group and summarize by O-D
marine.sum <- marine %>%group_by(Handling_Port, OD_Port_Country) %>%
  summarise(tons <-sum(tonnes))    # prepare pivot table
marine.sum1 <- acast(marine.sum, Handling_Port~OD_Port_Country, value.tons="z")    # reshape matrix
marine.sum1[is.na(marine.sum1)] <- 0    # set NA to zero

#initialization of server.R
shinyServer(function(input, output) {

  output$plot <- renderplot({
    c <- chordDiagram(marine.sum1,annotationTrack="grid",preAllocateTracks=list(track.height = 0.3))
    ##change axis
    c <- c + circos.trackPlotRegion(track.index=1, panel.fun=function(x,y) {
      xlim = get.cell.meta.data("xlim")
      ylim = get.cell.meta.data("ylim")
      sector.name=get.cell.meta.data("sector.index")
      circos.text(mean(xlim), ylim[1], sector.name,facing="clockwise",
                  niceFacing=TRUE,adj=c(0,0.4), cex = 0.4)},bg.border=NA)
    print(c)

  })
})


text:
Q: Transform Optional String and return Date in Java 8? I am currently parsing a nullable String to a Date. I try to use Optional to avoid using if statement. Here is what I have written so far :
Client client = new Client();

Optional.ofNullable(methodThatMayReturnStringOrNull())
.ifPresent((s) -> {
    try {
    client.setBirthDate(DateUtils.parseDate(
        StringUtils.substring(s, 0, 10),
        new String[]{"yyyy-MM-dd"}));
    } catch (ParseException e) {
        throw new TechnicalException("error.parsing.date", e);
    }
});

Is it possible to transform this lambda so I can make it a method similar to the following but java 8 style?
private Date parse(String complexString) {
    Date birthDate = null;
    if (complexString != null) {
        try {
            birthDate = DateUtils.parseDate(
                    StringUtils.substring(complexString, 0, 10),
                    new String[]{"yyyy-MM-dd"});
        } catch (final ParseException e) {
            throw new TechnicalException("error.parsing.date", e);
        }
    }
    return birthDate;
}

A: Not sure how far you want to go, but you can start with
Optional<Date> date = Optional.ofNullable(methodThatMayReturnStringOrNull())
.map((s) -> {
    try {
    return DateUtils.parseDate(
        StringUtils.substring(s, 0, 10),
        new String[]{"yyyy-MM-dd"}));
    } catch (ParseException e) {
        throw new TechnicalException("error.parsing.date", e);
    }
});

You might also consider using flatMap instead of map and returning empty optional instead of throwing exception on error - depends on how you want to progress you flow.
On completely unrelated note, get rid of Date and use either joda or new java time classes ;)


text:
Q: How to read the config parameter inside a interceptor? Does exist a way to consult the value of object config inside a interceptor? I want to view the config values before and after every request.
In the following code, how can I print the entire structure of config and response object in their respective case?
$provide.factory('myHttpInterceptor', function() {
  return {
    // optional method
    'request': function(config) {
      // do something on success
      return config;
    }

    'response': function(response) {
      // do something on success
      return response;
    }
  };
});

A: You can simply print the config and response object using :
console.log("config : "+ angular.toJson(config));
console.log("response : "+ angular.toJson(response));


text:
Q: Multithreaded Observer in Java - preserve proper order I am implementing something that I would call "Observable Set". It is just a normal set, but it can have some observers that are notified about adding new elements.
What is important for me, is that elements may be added from many threads at time, and also there are many observing threads. I hold Observers in CopyOnWriteArrayList (it is thread-safe).  The key point is to inform observers about adding elements in way, that informing order for each of observers is the same as order of adding elements.
What is best approach?
The most naive one is to put adding and informing in "synchronized" block. But i believe it can be slow etc.
Second I've tried was to just add element to set, and add it to "informing queue". With each addition of element it was checked whether informing is turned on. If not, it was started until the queue was empty. It was working quite OK but i was afraid that it wasn't nice approach.
The last that I've implemented, i would call as "informing threads". With adding observers, each observer has it's own "informing thread" created. That thread runs in background and checks if it's at end of global "informing queue". If it isn't it informs specific thread about new elements. However I've problems with synchronization, and while(true) loop. I don't know how to set condition to end thread. The next problem I noticed when writing it, is that every new thread will be informed from beginning... It's not good.
I hope I have described everything quite well. If not, please let me know, i will try to fix it.
What is best way to accomplish this task?
Thanks!

A: Your second solution could be improved to use a BlockingQueue: with it you don't need to check whether "informing is turned on", you just call take(), and it will wait for something to appear in the queue.
You could also look into the RxJava project. It is somewhat complex, but it has lots of features you might need.

It extends the observer pattern to support sequences of data/events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety and concurrent data structures.


text:
Q: dSPACE MicroAutoBox-PWM-Generation I have a problem with the so-called MicroAutoBox 2 with the DIO that when i genrate a PWM signal, then the signal remains almost at 0V, but if I change the duty cycle or frequency then the shape of the signal changes. and I also tried to set a pin on HIGH but also without success. i am sure that i have selected the right pins. The MAB is DS1505 and DS1507. to my question: what could be my mistake that the DIO dose not work ?
Model:

Signal:


text:
Q: Good way to manage very large collection I am trying to think of a fast and efficient way to handle a ton of items, all of the same struct type, in which the array can grow over time and quickly and selectively remove items when the conditions are right.
The application will have a large amount of data streaming in at a relatively fast rate, and I need to quickly analyze it, update some UI info, and drop the older datapoints to make room for new ones. There are certain data points of interest that I need to hang onto for a longer amount of time than others.
The data payload contains 2 integer numbers that represent physical spectrum data: frequency, power, etc. The "age out" thing was just some meta-data I was going to use to determine when it was a good time to drop old data.
I thought that using a LinkedList would be a good choice as it can easily remove items from the middle of the collection, but I need to be able to perform the following pseudo-code:
for(int i = 0; i < myCollection.Length; i++)
{
    myCollection[i].AgeOutVal--;

    if(myCollection[i].AgeOutVal == 0)
    {
       myCollection.Remove(i);
       i--;
    }
}

But I'm getting compiler errors indicating that I cannot use a collection like this. What would be a good/fast way to do this?

A: I would recommend that first, you do some serious performance analysis of your program. Processing a million items per second only leaves you a few thousand cycles per item, which is certainly doable. But with that kind of performance goal your performance is going to be heavily influenced by things like data locality and the resulting cache misses.
Second, I would recommend that you separate the concern of "does this thing need to be removed from the queue" from whatever concern the object itself represents.
Third, you do not say how big the "age" field can get, just that it is counting down. It seems inefficient to mutate the entire collection every time through the loop just to find the ones to remove. Some ideas:

*

*Suppose the "age" counts down from ten to zero. Instead of creating one collection and each item in the collection has an age, create ten collections, one for things that will time out in one, one for things that will time out in two, and so on.  Each tick you throw away the "time out in one" collection, then the "time out in two" collection becomes the "time out in one" collection, and so on. Every time through the loop you just move around a tiny number of collection references, rather than mutating a huge number of items.

*Why is "age" counting down at all?  Time is increasing. Mark each item according to when it was created, and never change that.  Use a queue, so you can insert new items on one end and delete them from the other end. The queue will therefore be sorted by age. Each tick, dequeue items that are too old until you get to an item that is not too old.  As mentioned elsewhere, a circular buffer implementation of a queue is likely to be efficient.


text:
Q: Creating a stored procedure to remove all constraints before truncating all data and restoring the data without dropping the database Dropping the database requires exclusive access to the Database which isn't feasible in my scenario as I am testing another program which has access to the DB at the same time.
The issue I am having is that I can't truncate every tables data unless all constraints are removed which I can achieve using
EXEC sp_MSforeachtable @command1="ALTER TABLE ? DROP CONSTRAINT FOREIGNKEY"
except that where FOREIGNKEY is I need to provide the name of the foreign key which is different for every table.
I can find the constraint name using sql using
select CONSTRAINT_NAME from INFORMATION_SCHEMA.TABLE_CONSTRAINTS but I'm not sure how to combine these two pieces of data
Solution:
EXEC sp_MSforeachtable @command1="DELETE FROM ?"
GO

Delete From doesn't require dropping constraints like truncate does.

A: I assume you have already scripted the constraints to be able to rebuild them after dropping them - if not do this before dropping them!
Then execute the query in a dynamic SQL loop which reads the constraint list sequentially. Example below (you may want to adjust the @SQL variable, I have commented out the execution and replaced it by a print so that you can safely execute it to see what it does).
DECLARE @ConstraintList TABLE (ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED, constraint_name VARCHAR(255), table_name VARCHAR(255), constraint_type VARCHAR(255))
INSERT INTO @ConstraintList (constraint_name, table_name, constraint_type) SELECT CONSTRAINT_NAME, TABLE_SCHEMA+'.'+TABLE_NAME, CONSTRAINT_TYPE FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'
DECLARE @constraint_name VARCHAR(255)
DECLARE @table_name VARCHAR(255)
DECLARE @constraint_type VARCHAR(255)
DECLARE @SQL VARCHAR(MAX)
DECLARE @i INT
DECLARE @j INT
SET @i = (SELECT MIN(ID) FROM @ConstraintList)
SET @j = (SELECT MAX(ID) FROM @ConstraintList)
WHILE @i <= @j
BEGIN
    SET @constraint_name = (SELECT constraint_name FROM @ConstraintList WHERE ID = @i)
    SET @table_name = (SELECT table_name FROM @ConstraintList WHERE ID = @i)
    SET @constraint_type = (SELECT constraint_type FROM @ConstraintList WHERE ID = @i)
    SET @SQL = ('ALTER TABLE '+@table_name+' DROP CONSTRAINT '+@constraint_name+' FOREIGNKEY')
    -- EXEC (@SQL)
    PRINT @SQL
SET @i = @i+1
END


text:
Q: SQL add processed ids to a single cell seperated with a comma i have the following sql query to get an idea of what it does please read the description below
select catalogid, numitems, allitems - numitems ignoreditems
    from (
      select i.catalogid,
        sum(case when (ocardtype in ('PayPal','Sofort') OR
                       ocardtype in ('mastercard','visa') and
                       odate is not null) AND NOT EXISTS (
                         select * from booked b
                         where b.ignoredoid = o.orderid
                       ) then numitems
                       else 0 end) numitems,
        sum(numitems) allitems
      from orders o
      join oitems i on i.orderid=o.orderid
      group by i.catalogid
    ) X

and the following sql tables
oitems table
+---------+-----------+----------+
| orderid | catalogid | numitems |
+---------+-----------+----------+
| O737    |       353 |        1 |
| O738    |       364 |        4 |
| O739    |       353 |        3 |
| O740    |       364 |        6 |
| O741    |       882 |        2 |
| O742    |       224 |        5 |
| O743    |       224 |        2 |
+---------+-----------+----------+

Orders table
 +-----------------+------------+------------+
    |         orderid | ocardtype  |   odate    |
    +-----------------+------------+------------+
    |     O737        | Paypal     |            | 'OK
    |     O738        | MasterCard | 01.02.2012 | 'OK
    |     O739        | MasterCard | 02.02.2012 | 'OK
    |     O740        | Visa       | 03.02.2012 | 'OK
    |     O741        | Sofort     |            | 'OK
    |     O742        |            |            | 'ignore because ocardtype is empty
    |     O743        | MasterCard |            | 'ignore because Mastercard no odate
    +-----------------+------------+------------+

the reusltant datatable
+-----------+----------+--------------+
| catalogid | numitems | ignoreditems |
+-----------+----------+--------------+
|       353 |        4 |            0 |
|       364 |       10 |            0 |
|       882 |        2 |            0 |
|       224 |        0 |            7 |
+-----------+----------+--------------+

idea is to sum the numitems column for products that have the same catalogid depinding on the data in the oitems table with the following conditions

*

*if ocardtype is empty then ignore the numitems and consider it as 0
in the sum and sum the ignored items to the ignoreditems column

*if ocardtype for some order is MasterCard or Visa and the odate is
empty then ignore the numitems and consider it as 0 and sum the
ignored items to the ignoreditems column

*if ocardtype is Paypal or Sofort, then just do the numitems sum
without checking the odate because those types require no odate

*in another table called booked i have a column called ignoredoid,
this columns contains orderids from the above table that i want to
ignore even if the 3 conditions above are satsfied

To this point the query is working perfectly thanks to @Richard aka cyberkiwi to his answer in this question

The Question is, i need the result datatable to look like the following
+-----------+----------+--------------+-------------------+
| catalogid | numitems | ignoreditems | orderidcollection |
+-----------+----------+--------------+-------------------+
|       353 |        4 |            0 | O737,O739         |
|       364 |       10 |            0 | O738,O740         |
|       882 |        2 |            0 | O741              |
|       224 |        0 |            7 |                   |'O742 & O743 are ignored
+-----------+----------+--------------+-------------------+

as you can see the only change is the addition of orderidcollection column,  it have to add the orderid to the new column seperated by a comma only if that order is not ignored in the code, i've been googling for couple hours with no luck!
is this even possible with SQL?

A: My Linq-to-Sql answer to your previous question extended to this one (LINQpad query):
Dim odateRequired = {"MasterCard", "Visa"}
Dim odateNotRequired = {"Paypal", "Sofort"}

Dim result = From o In Orders Join i In Oitems On o.orderid Equals i.orderid _
             Let check = Not (From b In Bookeds Where b.ignoredoid=i.orderid).Any _
                     AndAlso o.ocardtype IsNot Nothing _
                     AndAlso ((odateRequired.Contains(o.ocardtype) AndAlso o.odate IsNot Nothing) _
                        OrElse odateNotRequired.Contains(o.ocardtype)) _
         Group By i.catalogid Into _
         numitems = Sum(If(check, i.numitems, 0)), _
         ignoreditems = Sum(If(check, 0, i.numitems)), _
         group
         Select catalogid, numitems, ignoreditems, _
             orderidcollection = String.Join(",", (From g in group Where g.check Select g.i.orderid))
result.Dump

Note this solution issues multiple SQL queries to determine the orderids for each catalogid where check is True to accumulate each orderidcollection. There may be a more efficient solution (either using some, probably convoluted, Linq-to-Sql that causes the generated SQL to do the equivalent of String.Join, or get the catalogid, numitems, check, orderid using Linq-to-Sql and then use Linq-to-objects to do the final accumulations).
Note also this query includes your Booked table (with LINQpad's pluralisation).


text:
Q: How do I echo an
* tag once in a while loop in PHP? Thanks for taking a look at my question, what I'm trying to do is output an ul once but have it's li elements loop normally within the while loop, if the UL is echoed more than once it messes up my website styling.
My solution was to create two variables which would contain the opening and closing UL tags and then establish if statementz to put the variables values to an empty string once the while loop iterated once... well that didn't work:
    $ulStart='
';
    $ulEnd='
';
    $checkIteration=0;
    $checkIteration2=0;

    while($row=mysqli_fetch_array($result))
        {

            if($checkIteration>0){
                $ulStart='';
                $checkIteration++;
            }

            if($checkIteration2>0){
                $ulEnd='';
                $checkIteration2++;
            }

         $fd= $fd.$ulStart.'

'.$fake.'

               '.$fake_var.'
               Take a look

'.$ulEnd;

        }

Any ideas on how I could achieve this? I would greatly appreciate any help on this! THANK YOU!

A: $fd = "";
$fd .='
';
while($row=mysqli_fetch_array($result))
    {
        $fd .='

'.$fake.'

           '.$fake_var.'
           Take a look

'

}
$fd .='
';
echo $fd;

echoing the echo '
'; will already generate the closing tag for
 i.e.
. Best options to these things are, save the whole html in a variable and then echo the html once the loop ends.

A: Hello try below code may it helps you.
   $fd = "";
    echo '
';
    while($row=mysqli_fetch_array($result))
        {
            $fd .='

'.$fake.'

               '.$fake_var.'
               Take a look

'

    }
   echo $fd;
    echo '
';

i think you have no need to write ul inside loop here what i have did write ul outside the loop.before loop open ul tag after loop close. And if you need ul tag ones then no need to write in loop.  i hope it is helpful for you.

A: If you would like
 to be in the same echo statement you can do:
$fd = "";
while($row=mysqli_fetch_array($result))
    {
    $fd .='

'.$fake.'

       '.$fake_var.'
       Take a look

'

}
echo '
' . $fd . '
';

But it's almost the same as Dinesh Bhojvani answer so I am not sure it will help.


text:
Q: How to set Date Field on insert form to null if date is not required I am trying to set date field to allow null values on my insert form but every method I have tried comes back with " cannot insert null values".  I simply want to allow users the option to insert a date or not. I am using Sharepoint 2013 and javascript.
I read on https://msdn.microsoft.com/en-us/library/office/jj245356.aspx to use CSOM null - but there is no example and I am very new to sharepoint.  I dont want to use min.value || new date(0).
   if (DateField == "")
    {
       DateField = new Date(0); // this is the closest I have got but need this to be empty
       oListItem.set_item('DateField ', DateField);
    }

A: Even i also had the same issue a month ago, and i researched on Internet but didn't found a proper solution.
So as most of the blogs written, it says that the date column cannot be left blank. Now if you want to show date column on your form, use Jquery and bind that with the text box in the list column. That is the only workaround that i see, In case you found some, pls do share.
Thanks :)

A: To work around the issue I simply added an if statement to stop the insert if the date field is empty i.e.
if(Date != "")oListItem.set_item('Date', covertToAmericanFormat(Date));

I hope this helps others as it is a real pain passing null dates!! The insert will only work if there is a date present in the textbox otherwise it will not insert. Problem resolved :)


text:
Q: NSDateFormatter not converting NSString properly Simple case of trying to prove I can convert NSString to NSDate. Create an NSDate, turn it into an NSString, then back into an NSDate. The date looks fine as a string, but when I convert it back I always get some date like 12/25/2011 .... Can someone spot my error?
 NSDateFormatter *df = [[NSDateFormatter alloc] init];
 [df setDateFormat:@"dd/MM/YY hh:mm a"];
 NSDate* b = [[NSDate alloc] init];
 NSString* f = [df stringFromDate:b]; // has the current date and time
 NSDate* dt =[df dateFromString:f];  // 12/25/2011 - where does it get this?

A: Try to use the following:
[df setDateFormat:@"dd/MM/yyyy hh:mma"]; // or @"dd/MM/yy hh:mma"

This is the result:
Printing description of b:
2012-06-12 13:06:16 +0000
Printing description of dt:
2012-06-12 13:06:00 +0000

If you need more info I suggest to read date-formatter-examples.
If you don't use ARC make attention to memory leaks. For example, use [NSDate date] instead of [[NSDate alloc] init].
Hope that helps.

A: For me it looks like your system is using a Datestyle.
May you should set the formatter to use no style:
[df setDateStyle:NSDateFormatterNoStyle];
And why you are not using the style in general? It seems like the NSDateFormatterShortStyle  is what you want. You only have to set the time style as well and use setLocal: to bring the date in the order you want.


text:
Q: How to make a UILocalNotification like iOS5 embbed Weather Notification in NotificationCenter first, it can not be closed unless you shut it down in settings/notification
second, simple UILocalNotification can just show a string text in NotificationCenter, but weather notification can show much more complex
three, simple UILocalNotification can just be clicked, and active the app, but weather notification can be slided to show two different views, week view and today view

A: Till today (iOS 5.0.1) is not possible. There are not public API for doing that.
Some "insiders" claim it will be possible in future (and I also hope so of course).


text:
Q: "were to" VS "is to"

*

*The following three major challenges have to be met if a family business is to flourish for 100 years and more.

*The following three major challenges have to be met if a family business were to flourish for 100 years and more.

Which is the correct way to construct a conditional sentense?

A: EDIT:
You should use the first one, i.e. "The following three major challenges have to be met if a family business is to flourish for 100 years and more."

Since a family business to flourish for 100 years and more is not impossible, you should be using Future Real Conditional explained here: Future Conditional Forms | ENGLISH PAGE

Future Real Conditional
FORM
[If / When ... simple present ..., ... simple future ...]
[... simple future ... if / when ... simple present ...]
Notice that there is no future in the if- or when-clause.

An example:

I am going to read if there is nothing on TV.


text:
Q: Distinguishing device disconnects from timeouts When using ReadFile on a communications resource it is possible to detect read timeouts by checking if less bytes than the requested amount of bytes were read. For example, when I want to read 1 byte, in case of a read timeout, 0 bytes are returned and the function succeeds.
However, when I disconnect the device (after reading some bytes) from the COM-Port and start a read operation on its old handle, the same thing happens: Function succeeds and says that 0 bytes were returned.
How can I distinguish between a device disconnect and a simple read timeout since no data is currently available?
Currently, I'm checking if 0 bytes were returned, and if yes, I check if the device is still connected using WMI. However, this does not look very clean and I hope that I can find a better solution here.
Update
Some more information about the device (as asked in comments):
dcb.fDtrControl = DTR_CONTROL_ENABLE;
dcb.fRtsControl = RTS_CONTROL_ENABLE;

CTS and DSR are both set during data transfer and also after the device gets disconnected by unplugging the cable from the USB port.

A: If you're using Windows, you possibly need the SetCommTimeoutsFunction.  You should also check out the othe communications functions for dealing with RS232.
Edit:  I had a very similar situation when moving some code from a hand-held device with an actual RS232, to one with a USB RS232.  Wobble the USB, and the port would get 'lost' unbeknownst to the application.  The code I wrote to get around this is as follows (Win32 platform)
COMMTIMEOUTS    CTO;
CTO.ReadIntervalTimeout = 500;
CTO.ReadTotalTimeoutConstant = 500;
CTO.ReadTotalTimeoutMultiplier = 0;
if (SetCommTimeouts(hPort,&CTO) == 0)
{
    DWORD dwError = GetLastError();
    if (dwError == 5)
    {
        // Access denied, possibly loose USB, return error code or throw exception
        return Housten__We_have_a_problem;
    }
}

A: Just for completeness:
On Linux, read and select also return 0, but tcgetattr, will return an error on disconnect and 0 on timeout, so that's one way to do it.


text:
Q: What is xmlValue doing in this code snippit? One way I have been learning has been to work my way slowly through other people's code, figure out what they did. I found this neat bit of code on GitHub that returns the number of search results for a search term.
I understand every line of this function, EXCEPT the line that begins with "search.value". What is this line doing? I know it takes an html div with a number and extracts the number, but for the life of me I have no idea HOW it does that.
Any help would be much appreciated.
require(RCurl)
require(XML)

google.counts<-function(s){
search.url<-paste("http://www.google.com/search?q=",gsub(" ","+",s),sep="")
search.html<-getURL(search.url)
parse.search<-htmlTreeParse(search.html,useInternalNodes = TRUE)
search.nodes<-getNodeSet(parse.search,"//div[@id='resultStats']")
search.value<-strsplit(xmlValue(search.nodes[[1]])," ",fixed=TRUE)[[1]][2]
return(as.numeric(gsub(",","",search.value,fixed=TRUE)))
}

A: You can use debug functionality
debug(google.counts)
google.counts("test")

This will put you into a debugging "browser" and you can keep on hitting enter to step through each line of function step by step.  You can also see contents of the variables as you would do in a normal R prompt.


text:
Q: why does overload operator= makes exception safety Very straight forward question.
class Bitmap {...};
class Widget {
    ...
    private:
        Bitmap* pb;
};

when overloaded copy assignment, the book (Effective C++) said: belowing codes are exception safety.
Widget& Widget::operator=(const Widget& rhs) {
    if (rhs == *this) return;
    Bitmap* pOrig = pb; //?? why remember the pb can do exception safety?
    pb = new Bitmap(*rhs.pb);
    delete pOrig;
    return *this;
  }

Book said : even through the new Bitmap(*rhs.pb) met the exception, the above code can do exception safety, the pb can keep the same, not pointer to the NULL? but how, why ? someone can help me? thanks!

A: Although the question might not be too precise, I think I still got the point:
Imagine, the code would have been written as follows:
Widget& Widget::operator=(const Widget& rhs)
{
    if (rhs == *this) // actually, you'd rather do &rhs == this!
                      // you don't want self-assignment
        return;
    delete pb;
    pb = new Bitmap(*rhs.pb);
    return *this;
}

What happens, if new Bitamp() fails with an exception - then pb is already deleted - and points to invalid memory!
So you remember first the value of pb, and if creation fails with an exception, you have not modified this and it remains valid even if an exception occured.

A: If an exception is thrown during construction of new Bitmap(*rhs.pb), the state of Widget is still unchanged.
If you simply delete pb before doing new Bitmap(*rhs.pb):
Widget& Widget::operator=(const Widget& rhs) {
    if (rhs == *this) return;
    delete pb; // unsafe
    pb = new Bitmap(*rhs.pb);
    return *this;
  }

And new Bitmap(*rhs.pb) fails (throws an exception), there there is no Bitmap instance anymore inside Widget, and pb points to a deleted instance of Bitmap. This will crash during destruction of Widget.


text:
Q: findone operation to check wheather a value present in json object in my table, I have tagId column, which contains data in JSON format. example [1,2]; I need to find the id of that row by checking whether the tag id is present or not. for example, if tag id 2 is present in [1,2] so I need to fetch that corresponding table row
Node.js sequlze SQL code is used
i try in,contains and many solution in google but i just retriveing empty data
const response = await db.UserTag.findAll({
  where: { tagId: { [Op.contains]: ["1"] } },
});
return response;

A: const const response = await db.UserTag.findAll({
  where: {
    tagId: {
      [Op.regexp]: 1,
    },
  },
  attributes: ['Id'],
})


text:
Q: How to import Azure BlobService in python? We are able to import azure.storage, but not access the BlobService attribute
The documentation says to use the following import statement:
from azure.storage import BlobService

But that get's the following error:
ImportError: cannot import name BlobService

We tried the following:
import azure.storage
...
foo = azure.storage.BlobService(...)

But that received the following error:
AttributeError: 'module' object has no attribute 'BlobService'

We also tried all of the above with "azure.storage.blob" instead of "azure.storage"
We tried updating azure-storage package but it is up to date (version 0.30.0)
We also tried uninstalling azure-storage and installing the entire azure package, but we got the same results. We tried installing them with both pip and conda, but same results both times.
I am aware that the output suggests that this version of azure.storage has no BlobService attribute, but the documentation clearly states to import from there.
https://azure.microsoft.com/en-us/documentation/articles/machine-learning-data-science-create-features-blob/

A: I had the same issue after using pip to install the azure package and, as the chosen answer suggests, this can be fixed by installing azure.storage 0.33.0.
However, if you're using pip, you might need to use the "--upgrade" option for it to install properly (this was my experience):
pip install azure-storage --upgrade

A: If you want to use BlobService, you could install package azure.storage 0.20.0, there is BlobService in that version. In the latest azure.storage 0.30.0 , BlobSrvice is split into BlockBlobService, AppendBlobService, PageBlobService object, you could use BlockBlobService replace BlobService.

A: I had version 1.0.3 installed (which includes azure.storage version 0.20) on Ubuntu server 16.04 LTS and pip only reinstalled version 0.20 of azure.storage when I uninstalled and reinstalled the azure package. This was according to the pypi page for the azure package v. 2.0.0rc6 which recommends that to upgrade from 1.0.3 to version 2 you should do
sudo pip3 uninstall azure
sudo pip3 install azure

pypi/azure
Instead, this worked for me,
sudo pip3 uninstall azure
sudo pip3 install azure==2.0.0rc6

A: It's possible the library has changed since that tutorial was published, but...
I just tried this a few moments ago, successfully:
from azure.storage.blob import BlockBlobService

blob_service = BlockBlobService(account_name="...",account_key="...")

And I installed Azure storage locally via:
pip install azure-storage

I was able to test this by downloading an object from storage:
blob_service.get_blob_to_path("containername","blobname","localfilename")

Note: You could import PageBlobService in similar fashion, but you might not find that too valuable, since page blobs are primarily for vhd's.


text:
Q: Want "Cancel" Button to stop downloading images in c# Using following code I am downloading images from database over HTTPWebRequest.
 BackgroundWorker bgWorker = (BackgroundWorker)sender;

 string baseUrl = "http://some path";
 int numIterations = 10;
 for (int i = 0; i < numIterations; i++)
        {
         if (bw.CancellationPending == true)
           {
                e.Cancel = true;
                break;
           }

         else
            {
             HttpWebRequest request = null;
             foreach (var fileName in fileNames)
                   {
                      string url = string.Format(baseUrl, fileName);
                      request = (HttpWebRequest)WebRequest.Create(url);
                      request.Method = "GET";
                      request.ContentType = "application/x-www-form-urlencoded";
                      request.CookieContainer = container;

                      response = (HttpWebResponse)request.GetResponse();
                      Stream stream = response.GetResponseStream();
                      Image img = Image.FromStream(stream);

                      img.Save("some path" + fileName);

                      ZoomThumbnail = img;
                      ZoomSmall = img;
                      ZoomLarge = img;

                      ZoomThumbnail = GenerateThumbnail(ZoomThumbnail, 86, false);

                      ZoomSmall  = GenerateThumbnail(ZoomSmall, 400, false);

                      ZoomLarge = GenerateThumbnail(ZoomLarge, 1200, false);

                      if (img != null)
                      ZoomThumbnail.Save("some path" + fileName + "_Thumb.jpg");
                      ZoomSmall.Save("some path" + fileName + "_ZoomSmall.jpg");
                      ZoomLarge.Save("some path" + fileName + "_ZoomLarge.jpg");
                      System.Threading.Thread.Sleep(200);
                    }
                }

This code is located under ButtonProcess_click and is working perfectly fine. There is one more button "Cancel". Whenever user clicks on "Cancel", I want process of downloading and saving images to stop. Can anyone help? Here is code for cancel button that does nothing but to disable "Process" button.
ButtonProcess.Enabled = false;
Button btnSender = sender as Button;
btnSender.Enabled = false;
bw.CancelAsync();

A: From the line bw.CancelAsync() I guess use use a BackgroundWorker. I also guess that the above code is executed by the background worker.
In no place in that code, however, I can see that you're actually checking whether the process should be canceled. Also, you're downloading the image in one go in this line:
Image img = Image.FromStream(stream);

This does not support cancellation. So problems are:

*

*You can not cancel the loop over all the files as you're not checking whether the background worker should be cancelled

*You can not cancel an individual image download, as you're downloading it in one go

Solutions:

*

*In your loop, add condition that exits the loop if the background worker is cancelled

*Change the image download so that you get chunks of bytes, call this in a loop and also check for cancellation there.

Possible solution for the first:
if (bw.CancellationPending)
{
    return;
}

Possible solution for the second:
Stream stream = response.GetResponseStream();
byte[] buffer = new byte[512];
int bytesRead = 0;
do
{
    bytesRead = stream.Read(buffer, 0, buffer.Length);
    if (bytesRead > 0)
    {
        // Save the bytes to a memory stream
    }
}
while (bytesRead > 0 && !bw.CancellationPending)

if (!bw.CancellationPending)
    img = Image.FromStream(<yourMemoryStream>);


text:
Q: Can SBT resolve only .pom files as dependencies without jars? So, as the title suggests, can sbtresolve .pom files dependencies that contain only configurations/properties and have no .jar file associated?
Im currently developing a new frontend app using Play! Framework and angularjs. Here's the scenario:

*

*Root Project (à la maven compilation/deploy)

*

*Core business Module - pom.xml

*Web modules - pom.xml

*

*Rest API-pom.xml

*

*Module - pom.xml

*Module - pom.xml

*Frontend (à la SBT compilation, multi-module project)

*

*Mod1 - build.sbt

*Mod2 - build.sbt (depends on mod1)

*

*More modules inside - build.sbt

build.sbt
project/build.scala

*Web Commons (used on the Rest API and Frontend) - pom.xml

The sbt compilation is ran via maven using a plugin, sbt-launcher if im not mistaken. Everything runs and compiles as expected, however, we ran into a problem when we added WebCommons as a dependency in the frontend's build.sbt file.
The problem relys on the fact that, the root's pom.xml has a parent of his own, lets call it X, and X contains several .pom files that delegate to child modules (in this case the root project) config/properties/dependencies that are necessary to ease RPM packaging.
Running maven clean install, the compilation process goes perfectly fine, we reach the frontend and the sbt compilation cycle starts as expected. When sbt tries to resolve the web-commons dependency, it also resolves every parent. In this case, web-commons->web-modules->root->X. When he reaches X, finds that there are several dependencies with him (not relevant at all for the frontend...) but these are made of .pom files not jar's. These .pom files are downloaded correctly using resolvers but then, sbt searches for the corresponding .jar files taking an enormous time to finish the build, and when it does, errors, errors everywhere (missing dependencies).
I've tried several possible solutions:
1.intransitive() in web-commons dependency, not effective, still trying to find parents dep.
2.exclude(organization,filename*), again not effective.
3.excludeAll( ExclusionRule(org,dep1) ExclusionRule(org,dep2) ... ), sadly, not effective.
Im currently using sbt 0.13.2/6 (tried both).
My next step was to define an ivy.xml and ivysettings.xml that configures this dependency and force the type=pom. Might this work? Any other sugestion/workaround?
Thanks in advance.

A: Hopefully good news for you!
I've had a similar problem recently with SBT 0.13.13 where I have two projects, each publishing a POM file (no jars!) where one of the POM depends on the other.
Adding a dependency to a POM in a *.sbt file looks like this:
libraryDependencies +=
  "<org>"
  % "<artifact>"
  % "<version pattern>"
  artifacts
  Artifact("<artifact>", `type`="pom", extension="pom")

If you're interested in an example, see here:
https://github.com/TIWG/com.nomagic.magicdraw.sysml.plugin/blob/release/18.0-sp6/build.sbt#L63
The POM is published here:
https://bintray.com/tiwg/org.omg.tiwg.vendor.nomagic/com.nomagic.magicdraw.sysml.plugin/18.0-sp6.2
That POM has a dependency on another POM published here:
https://bintray.com/tiwg/org.omg.tiwg.vendor.nomagic/com.nomagic.magicdraw.package/18.0-sp6.2


text:
Q: C^1 function twice differentiable only at origin? Is there a $C^1$ function $f:\mathbb{R}\rightarrow \mathbb{R}$ such that $f$ is twice differentiable only at origin? Can this phenomena occur in higher dimension?
N.B I constructed a $C^1$ function that is twice differentiable nowhere but could not manipulate for one point. Any help is much appreciated.

A: Let $h(x)$ be a continuous, nowhere differentiable function on $\mathbb{R}$. Then $g(x)=x^2h(x)$ is continuous, and is differentiable only at $x=0$.
Therefore if we define $f(x)=\int_0^xg(t)\;dt$, then $f^{\prime}(x)=g(x)$ by the Fundamental Theorem of Calculus, so $f$ is $C^1$ and is twice differentiable only at $x=0$.


text:
Q: Use of unassigned variable (string) I have a piece of code that iterates over XML attributes:
string groupName;
do
{
    switch (/* ... */)
    {
        case "NAME":
            groupName = thisNavigator.Value;
            break;
        case "HINT":
            // use groupName

But this way I get the error of using an unassigned variable. If I assign something to groupName then I cannot change it because that's how the strings work in C#. Any workarounds ?

A: You are right that strings are immutable in .NET, but your assumption that a string variable can't be changed is wrong.
This is valid and fine:
string groupName = null;
groupName = "aName";
groupName = "a different Name";

Your code will not have an error if you do the following:
string groupName = string.Empty; // or null, if empty is meaningful
do
{
    switch (/* ... */)
    {
        case "NAME":
            groupName = thisNavigator.Value;
            break;
        case "HINT":
            // use groupName

A: Does the default of your switch assign a value to groupName? If not, then that will be causing the error.
switch
{
  case "NAME":
    groupName = thisNavigator.Value;
    break;
  //...
  default:
    groupName = "something";
    break;
}

A: string groupName = string.Empty;

Just assign an empty string and your should be okej.

A: The compiler is unaware of the context of your switch statement (e.g. there's no guarantee that the switch will always match a case).
So it's possible for groupName to remain unassigned even after the switch.
You can instantiate groupName with String.Empty or use default: in your switch statement.

A: Set groupName in each case and use default key in switch statement or assign groupName to null before switch.


text:
Q: Pandas dataframe lookup a value in different dataframe and assign a value I have 2 different dataframes.
The first one looks like:
     joint  label     x    z      y    pt
0        1    NaN  50.4  0.0  -8.40    10
1        2  shell  52.2  0.0  -8.40    20
2        3  shell  54.0  0.0  -8.40    30
3        4  shell  55.8  0.0  -8.40    40
4        5  shell  57.6  0.0  -8.40    50

and my second dataframe looks like:
     member  joint1  joint2        joint1_pt        joint2_pt
0         1       1       2                0                0
1         2       2       3                0                0
2         3       3       4                0                0
3         4       4       5                0                0

I would like take use the pt value that corresponds on a specific jointe and use it on the second dataframe so it will look like the following:
     member  joint1  joint2        joint1_pt        joint2_pt
0         1       1       2                10              20
1         2       2       3                20              30
2         3       3       4                30              40
3         4       4       5                40              50

can you please help me with an example/idear on how should i approach this?
Thank you in advance!!

A: You need map by dict created from Series with set_index and to_dict as pointed in P-robot in comments:
d = df1.set_index('joint')['pt'].to_dict()
#mapping by Series works, but a bit slowier
#d = df1.set_index('joint')['pt']
print (d)
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}

df2['joint1_pt'] = df2['joint1'].map(d)
df2['joint2_pt'] = df2['joint2'].map(d)
print (df2)
   member  joint1  joint2  joint1_pt  joint2_pt
0       1       1       2         10         20
1       2       2       3         20         30
2       3       3       4         30         40
3       4       4       5         40         50

A: you can use merge, after merging ,assign pt to joint1_pt & joint2_pt , finally drop unwanted columns.
df= pd.merge(df2,df1[['joint','pt']], right_on='joint',left_on='joint1',how='left')
df= pd.merge(df,df1[['joint','pt']], right_on='joint',left_on='joint2',how='left')
df[['joint1_pt','joint2_pt']] =df[['pt_x','pt_y']]
df=df[['member','joint1','joint2','joint1_pt','joint2_pt']]
print df

Output
   member  joint1  joint2  joint1_pt  joint2_pt
0       1       1       2         10         20
1       2       2       3         20         30
2       3       3       4         30         40
3       4       4       5         40         50


text:
Q: How can I reduce Source Games load times, specifically Half-Life 2? These games takes like 30-60 seconds to load a new section, depending on how many assets need to be loaded
Any way to decrease these load times? 10 seconds would feel like heaven, any help appreciated.
Specs:

*

*CPU - AMD Ryzen 3 3100

*Graphics Card - AMD Radeon RX 550/500 Series

*RAM - 16 GB

*SSD - 1 TB


text:
Q: Is there a way to run Azure Storage Emulator on Ubuntu? I'm trying to set up my development environment, and I need to use Azure Storage Emulator for my project. Currently I'm running the emu on a VM and my software connects to it.
Is there another way to do this?

A: There is no Azure Storage emulator for Linux and there will be none according to Microsoft response on this customer feedback.
They advise, however, using open-source alternative like Azurite.

A: Update 2022
Azurite has replaced the Azure Storage Emulator. See the documentation.
Azurite works, among others, on Ubuntu. From their official repository: "Based on Node.js, Azurite provides cross platform experiences for customers wanting to try Azure Storage easily in a local environment."


text:
Q: Return value in 'for' loop in nodejs backend I'm wondering if there is s possibility to return value on every loop iteration?
Something like this but in correct way:
for(....) {
    ...
    return value[i]
}

In my case I have an Angular app and nodeJs backend. In app I have subscription to function requesting a specific endpoint.
What I want to archieve is to return value on each loop iteration and show it in app.
I've already done that using websocket but I'm curious if there is any other way?
Thanks for your time.


text:
Q: Is there a current in \$R_1\$ in this precision rectifier if so, where does it go?
So Wikipedia on Precision Rectifier says that :

... when the input is greater than zero, \$D1\$ is off, and \$D2\$ is on, so the output is zero because the other end of \${\displaystyle R_{2}}\$ is connected to the virtual ground and there is no current through \${\displaystyle R_{2}}\$

Now when we see \$R_1\$ it has a potential drop of \$V_{in}\$ across its ends , so a current must flow through it. But then where does it go? I cannot see a closed loop in which current can flow. It can only go through \$D1\$ but then it cannot flow back into op amp.
So my question is : In which path does the current flow? or If there is no current flowing through \$R_1\$ how is there a potential difference across it?

A:
But then where does it go? I cannot see a closed loop in which current
can flow. It can only go through D1 but then it cannot flow back into
op amp.

Sure it can (but not through D1). The op-amp output will be about 0.7 volts negative (in order to preserve the virtual ground at -Vin) and positive current will flow through R1, then through D2 and to the op-amp output: -


text:
Q: Adding jQuery plugin to angular app Frameworks used

*

*Angular: 5.2.3

*Foundation(Zurb): 6.2.4

Created an angular app using
> ng new foundation-plugin-app --style=sass
> cd foundation-plugin-app
> npm install foundation-sites --save

Everything work as expected till this.
Then I added foundation-datepicker
> npm install foundation-datepicker --save

This is how the plugin is initialized.
$('#scenario_start_date').fdatepicker({
  initialDate: '02-12-1989',
  format: 'mm-dd-yyyy',
  disableDblClickSelection: true,
  leftArrow: '<<',
  rightArrow: '>>',
  closeIcon: 'X',
  closeButton: true
});

Now, to make it work, followed these steps
1.Added styleUrls in app.component.ts
styleUrls: [
    // ...,
    '../../node_modules/foundation-datepicker/scss/foundation-datepicker.scss'    ]

2.Added scripts in angular-cli.json
"scripts": [
    "node_modules/foundation-datepicker/js/foundation-datepicker.js"
]

3.Added typings to app.component.ts
npm install --save-dev @types/jquery

and imported jquery and foundation-datepicker plugin to the page
import * as $ from 'jquery';
import 'foundation-datepicker';

4.Lastly, called the plugin in ngOnInit() of app.component.ts
$('#scenario_start_date').fdatepicker(/*...*/);

Which gave error as

fdatepicker is not defined.
  So I type-casted it as

(<any>$('#scenario_start_date')).fdatepicker(/*...*/);

to suppress the error.
This gives a new error

Uncaught TypeError: Cannot read property 'fn' of undefined
at eval (webpack-internal:///../../../../foundation-datepicker/js/foundation-datepicker.min.js:1)
    at eval (webpack-internal:///../../../../foundation-datepicker/js/foundation-datepicker.min.js:1)
    at Object.../../../../foundation-datepicker/js/foundation-datepicker.min.js (vendor.bundle.js:36)
    at __ webpack_require __ (inline.bundle.js:55)
    at eval (webpack-internal:///../../../../../src/app/app.component.ts:15)
    at Object.../../../../../src/app/app.component.ts (main.bundle.js:21)
    at __ webpack_require __ (inline.bundle.js:55)
    at eval (webpack-internal:///../../../../../src/app/app.module.ts:11)
    at Object.../../../../../src/app/app.module.ts (main.bundle.js:29)
    at __ webpack_require __ (inline.bundle.js:55)

What am I doing wrong with the code? Any pointers will be helpful.

A: Your import statement seems to be wrong.
Please try import $ from 'jquery';
And make sure that jQuery is bundled with your generated bundle file.
In your case it is either not globally exported or not included in the window context.
In this case try
window.jQuery = $;
window.$ = $;


text:
Q: can we catch the 'double right click' event on google-maps-v3? can we ?
i want to do something like this:
google.maps.event.addListener(map, 'db_right_click', function(event) {
   alert('ssss')
}

how to catche the 'db_right_click'  event ??
is there any way  ??

A: i get it
and
this is my code:
//***********  double right click ********/
                                var c =0 ;
                                $('#map_canvas')[0].onmousedown=function(event){
                                    if(event.button == 2){
                                        c++;
                                setTimeout(cc, 600);
                                }
                             if (c >1){
                                   alert('ok i get it')
                                }
                                }
                                function cc{
                                    c=0;
                                }
                              //***********  double right click ********/

A: I couldn't see an easy way to capture the double right click event on google maps.
But here's the work around I used for my use case:
What I needed was to perform an action on a single right click, but not perform that action on a double right click, just let the map zoom out like normal.
I also noticed that google maps emits just 1 rightclick event even when you double right click.
So all I did was listen on google's rightclick event, and then setTimeout for 300 milliseconds and if the new zoom was different than the old zoom, that means they double right clicked, else perform my action:
google.maps.event.addListener(map, "rightclick", function(event) {
    var zoom = map.getZoom()
      setTimeout(function () {
      if (map.getZoom() == zoom) { // zooms are the same so they didn't double right click.
        handleSingleRightClick() // <-- your code here
      }
    }, 300)
});

A: You can catch double right click event by JavaScript, but it's not enough if you need some specific data from google maps event. For example, you need to get coordinates of the place that was double right clicked. Here is solution:
// variable to store right clicked place coordinates
let rightClickCoordinates;
// variable to store amounts of right clicks
let rightClicksAmount = 0;

// listener for google map right click event
google.maps.event.addDomListener(map, 'rightclick', (e) => {
    // store coordinates of place was right clicked
    rightClickCoordinates = e.latLng;
});

// listener for google map container double right click event
document.getElementById('your_map_container_id').addEventListener('mousedown', () => {
    // check for double right click
    if(e.button == 2) {
        // if right mouse button clicked increase amount by 1
        rightClicksAmount++;
    }

    // if we had more than 1 right click during the 300 ms - we caught right double click event
    if (rightClicksAmount > 1) {
        // do what you want with coordinates
        console.log(rightClickCoordinates.lat() + ', ' + rightClickCoordinates.lng());
    }

    // after 300ms set right clicks amount to 0
    setTimeout(()=> {
        rightClicksAmount = 0;
    }, 300);
}});

You can get any google map event property in the same way.


text:
Q: Cross-platform inheritance of view models So I have run to a problem while trying to follow the MVVM pattern for my WPF project and I spent hours searching for a solution with no luck. The problem is the following: Let's assume that I have a .net Standard library where I have all my view models for my application, for example let's assume that there are the following view models :

BaseDropDownMenuViewModel that inherits from the BaseControlViewModel
AdvancedDropDownMenuViewModel that inherits from the BaseDropDownMenuViewModel
MultiDropDownViewModel that inherits from the AdvancedDropDownViewModel

The view models contain both the functionality of the controls and variables used for their appear for example a BackColor and a ForeColor property that are placed in the BaseControlViewModel. Now ,even though this is sufficient enough for me, I want to add some properties that apply only for desktop platforms, for example a MouseOverBackColor and a MouseOverForeColor property and I also need to be able to override the existing ones ex BackColor. These properties of course would only make sense on desktop platform and not a mobile platform.
Now I have found two solutions for my problem but both of them are not sufficient enough...

*

*Create a new .net standard library with an interface that forces the implementation of properties available only for desktop applications and create a class for every view model of the base library and implement that interface. In this scenario I will have a huge amount of duplicate code but I will be able to use these classes for my Windows version of my app and the mobile version will not have unused variables for every single one of its controls for example a MouseOverBackColor property that it can't take advantage of.

*Which leads us to my second option which is to implement those properties (MouseOverBackColor,MouseOverForeColor,...) on the BaseControlViewModel on the base .net standard library and have all the versions of my app have those variables even though some might not be able to utilize them. That way I want have duplicate code...
I believe that this problem would be easy to solve if C# supported multi inheritance of classes but since it doesn't I am trying to find another "magic" way of solving this issue. Note: I have also searched about tricks to achieve "multi class inheritance" but those that I was interested in were storing the classes as variables in the main class, which none of this is interests me at the moment because the application would require a massive modification to take advantage of this trick...

A: You can do this with interfaces:
Example - One class, two interfaces
public interface IDesktopProperties
{
    Color BackColor {get; set;}
    Color MouseOverBackColor {get; set;}
}

public interface IMobileProperties
{
    Color BackColor {get; set;}
    Orientation ScreenOrientation {get; set;}
}

public class MySuperFancyViewModel : IDesktopProperties, IMobileProperties
{
    public Color BackColor {get; set;}
    public Color MouseOverBackColor {get; set;}
    public Orientation ScreenOrientation {get; set;}
}

Now in your Desktop App, you'll have something like
// Will only see properties BackColor and MouseOverBackColor
private IDesktopProperties myProps;
public MyDesktopUI( IDesktopProperties properties ) // <= injected: MySuperFancyViewModel
{
    myProps = properties;
}

And accordingly for Mobile
// Will only see properties BackColor and ScreenOrientation
private IMobileProperties myProps;
public MyMobileUI( IMobileProperties properties ) // <= injected: MySuperFancyViewModel
{
    myProps = properties;
}


text:
Q: Laplace Equation -> Boundary Conditions Given $\nabla^2 \phi=0$,
With B.C.

*

*$\Gamma_1 =-V$   (Left side of rectangle)

*$\Gamma_2 = V$   (right side of rectangle)

*$\Gamma_0 = 0$   (top and bottom sides of rectangle)
Can Separation of Variables be applied to this problem?  Will the superposition principle have to be applied to the second ODE because there are two non-zero BC?

A: Absolutely.  First write $\phi(x,y) = \phi_1(x,y)+\phi_2(x,y)$, where:
$$\nabla^2 \phi_1 = 0$$
$$\phi_1(x,0) = 0$$
$$\phi_1(x,d)=0$$
$$\phi_1(0,y) = -V$$
$$\phi_1(w,y) = 0$$
and
$$\nabla^2 \phi_2 = 0$$
$$\phi_2(x,0) = 0$$
$$\phi_2(x,d)=0$$
$$\phi_2(0,y) = 0$$
$$\phi_2(w,y) = V$$
We may write $\phi_1(x,y) = X(x) Y(y)$ to find that
$$\frac{X''}{X} = -\frac{Y''}{Y} = k^2$$
Then
$$Y(y) = A \cos{k y} + B \sin{k y}$$
The boundary conditions in $y$ imply that $A=0$ and $k = n \pi/d$.  For the $x$ equation, we may write
$$X(x) = C_n \cosh{\frac{ n \pi (w-x)}{d}} + D_n \sinh{\frac{ n \pi (w-x)}{d}}$$
I wrote the solution this way so that we can have $C=0$ from the boundary condition at $x=w$.  The general solution is then
$$\phi_1(x,y) = \sum_{n=1}^{\infty} D_n \sinh{\frac{ n \pi (w-x)}{d}} \sin{\frac{ n \pi y}{d}}$$
We find the $D_n$ from the B.C. at $x=0$.  By orthogonality, we have
$$D_n = \frac{2}{d \sinh{\frac{ n \pi w}{d}}} \int_0^d dy (-V) \sin{\frac{ n \pi y}{d}} = -\frac{2 V}{n \pi \sinh{\frac{ n \pi w}{d}}} \left ( 1-\cos{n \pi}\right )$$
We find $\phi_2$ similarly, except the expansion is now given by
$$\phi_2(x,y) = \sum_{n=1}^{\infty} C_n \sinh{\frac{ n \pi x}{d}} \sin{\frac{ n \pi y}{d}}$$
We find the $C_n$ from the B.C. at $x=w$:
$$D_n = \frac{2}{d \sinh{\frac{ n \pi w}{d}}} \int_0^d dy (V) \sin{\frac{ n \pi y}{d}} = \frac{2 V}{n \pi \sinh{\frac{ n \pi w}{d}}} \left ( 1-\cos{n \pi}\right )$$
Putting this altogether, I get as the sought-after solution:
$$\phi(x,y) = \frac{4 V}{\pi} \sum_{k=0}^{\infty} \frac{\sinh{\frac{(2 k+1) \pi x}{d}}-\sinh{\frac{(2 k+1) \pi (w-x)}{d}}}{(2 k+1) \sinh{\frac{(2 k+1) \pi w}{d}}} \sin{\frac{(2 k+1) \pi y}{d}} $$

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\on}[1]{\operatorname{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
$\ds{\underline{\tt Domain}:\ {\large\pars{0,b}\times\pars{0,h}}}$

It's always better, at the very beginning, to take advantage of:

*

*the homogeneous boundary conditions : It's
$\ds{\underline{\mbox{equivalent to}\ variable\ separation}}$ and it's less "painful".

*the problem symmetries: The solution must changes its sign when $\ds{x \mapsto b - x}$ and it's invariant when
$\ds{y \mapsto h - y}$.

*The above statements lead to
$\ds{\phi\pars{x,y} =
\sum_{n = 0}^{\infty}\on{a}_{n}\pars{x}\sin\pars{k_{n}y}}$ where $\ds{k_{n} \equiv \pars{2n + 1}\,{\pi \over h}}$ and
$\ds{\on{a}_{n}\pars{x} = -\on{a}_{n}\pars{b -x}}$.
Note that, with $\ds{m, n \in \mathbb{N}_{\,\geq\ 1}}$,
$$
\left\{\begin{array}{rcl}
\ds{\int_{0}^{h}\sin\pars{k_{m}y}\sin\pars{k_{n}y}\,\dd y}
& \ds{=} &
\ds{{1 \over 2}\,h\,\delta_{mn}}
\\
\ds{\int_{0}^{h}\sin\pars{k_{n}y}\,\dd y}
& \ds{=} &
\ds{{2 \over \pars{2n + 1}\pi}\,h\,\delta_{mn}}
\end{array}\right.
\label{1}\tag{1}
$$

*$\ds{\phi\pars{x,y}}$ must satify the differential equation:
$$
\sum_{n = 0}^{\infty}
\bracks{\pars{\totald[2]{}{x} - k_{n}^{2}}\on{a}_{n}\pars{x}}\sin\pars{k_{n}y} = 0
\label{2}\tag{2}
$$

*Use (\ref{1}) and (\ref{2}). I get
\begin{align}
&\pars{\totald[2]{}{x} - k_{n}^{2}}\on{a}_{n}\pars{x} = 0
\implies
\on{a}_{n}\pars{x} =
c_{n}\sinh\pars{k_{n}\bracks{x - {b \over 2}}}
\end{align}
The general solution is reduced to:
$$
\phi\pars{x,y} =
\sum_{n = 0}^{\infty}
c_{n}\sinh\pars{k_{n}\bracks{x - {b \over 2}}}\sin\pars{k_{n}y}
$$

*The boundary conditions yield
\begin{align}
&V = \sum_{n = 0}^{\infty}
c_{n}\sinh\pars{k_{n}\bracks{b \over 2}}\sin\pars{k_{n}y}
\\[5mm] \implies &\
\overbrace{V\,{2 \over h}\int_{0}^{h}\sin\pars{k_{n}y}
\dd y}^{\ds{4V \over \pars{2n + 1}\pi}}
\\[2mm] = &\
\sum_{m = 0}^{\infty}
c_{m}\sinh\pars{k_{m}\,{b \over 2}}\
\underbrace{\bracks{{2 \over h}
\int_{0}^{h}\sin\pars{k_{n}y}\sin\pars{k_{m}y}\dd y}}
_{\ds{\delta_{nm}}}
\\[5mm] &\ \implies
c_{n} =
{4V \over \pars{2n + 1}\pi\sinh\pars{k_{n}b/2}}
\end{align}

*Finally,
$$
\bbx{\phi\pars{x,y} =
{4V \over \pi}\sum_{n = 0}^{\infty}
{\sinh\pars{k_{n}\bracks{x - b/2}}\sin\pars{k_{n}y} \over
\pars{2n + 1}\sinh\pars{k_{n}b/2}}} \\
$$


text:
Q: What is the difference between a GUI system and Rendering System in Game Engine Design? After reading part 1 of Michael Kissner's blog article on writing a game engine from scratch, a lot of concepts became a lot clearer to me. But a question that I seem to be stuck on is, what is the difference between the system used for rendering and the system used for gui. What makes these two systems separate from one another. My thinking maybe flawed but doesn't the GUI have to be "rendered" or is this done differently than something like a sprite. Thanks for any help!

A: Actually your thinking is good!
As the GUI system usually uses the rendering system of the game. However, both systems still tend to be separated. To give an idea, the GUI system would handle the data of the buttons, layouts, police, clicks or scrolling. It will then simplify everything to a bunch of vertices, triangles and textures and give it to the rendering system.
This is how works the hud of Unreal Engine 4 or our dear imgui for example.
You can also have additional GUI systems for the game editor or game tools, but it will usually be external and contains the game engine rather than the other way around.
In this case, the rendering system will output the entire frame in some texture that you may show anywhere you like. You will see it done this way with libraries like Qt, directly as extensions for software like Maya or with proprietary editors like Unreal Editor or Unity Editor. This type of GUI will never end on the player side unless as a modding tool.


text:
Q: D3.js multi-series line chart using csv file I am trying to recreate a multi-line chart like this example: multi-series line chart
This is my initial data file:
module_category,component_category,date_repair,actual,predicted
M1,P06,2009/01,39,63
M1,P06,2009/10,3,4
M1,P06,2009/11,4,3
M1,P06,2009/12,4,2
M1,P06,2009/02,29,45
M1,P06,2009/03,29,32
M1,P06,2009/04,10,22
M1,P06,2009/05,13,15
M1,P06,2009/06,9,16
M1,P06,2009/07,7,12
M1,P06,2009/08,5,9
M1,P06,2009/09,4,5
M1,P09,2009/01,7,5
M1,P09,2009/10,3,1
M1,P09,2009/02,2,3
M1,P09,2009/03,6,2
M1,P09,2009/04,4,2
M1,P09,2009/06,1,2
M1,P09,2009/07,3,2

I want to plot the date on the x-axis and the values for "actual" and "predicted" on the y-axis as two separate lines, but with a sum of the values specific to each particular date. For example, the total number of "actual" and "predicted" repair values for "January 2009".
After modifying the code from the example I get this:
current displayed chart
The big red spheres (shown in the picture) are meant to represent repair values higher than a particular threshold, which is in my code. The final dataset generated before plotting is meant to look like this:
date_repair,Actual,Predicted
01/01/2009,11027,13250
01/02/2009,8862,12592
01/03/2009,12696,12254
01/04/2009,10666,12014
01/05/2009,10732,11776
01/06/2009,11304,16044
01/07/2009,12880,15133
01/08/2009,11582,13481
01/09/2009,9426,8314
01/10/2009,5250,6510
01/11/2009,4075,4941
01/12/2009,2789,3519

I then considered using a nesting function with the keys as the dates but that doesn't display anything on the page.

function datelineChart(){
   var margin = {top: 20, right: 90, bottom: 30, left: 60},
       width = 980 - margin.left - margin.right,
       height = 500 - margin.top - margin.bottom;

   var parseDate = d3.time.format("%Y/%m").parse;

   var x = d3.time.scale()
       .range([0, width]);

   var y = d3.scale.linear()
       .range([height, 0]);

   var color = d3.scale.category10();

   var xAxis = d3.svg.axis()
       .scale(x)
       .orient("bottom");

   var yAxis = d3.svg.axis()
       .scale(y)
       .orient("left")
       .tickFormat(d3.format(".2s"));

   var line = d3.svg.line()
       .interpolate("basis")
       .x(function(d) { return x(d.date); })
       .y(function(d) { return y(d.no_repairs); });

   var svg = d3.select("#maincontent").append("svg")
         .attr("width", width + margin.left + margin.right)
         .attr("height", height + margin.top + margin.bottom)
       .append("g")
         .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

   d3.csv("data/Consolidated_result.csv", function(error, data) {
       if (error) throw error;

       data = d3.nest()
        .key(function(d) { return d.date_repair;}).sortKeys(d3.ascending)
        .rollup(function(values){
          var counts = {}, keys = ['actual', 'predicted']
          keys.forEach(function(key){
              counts[key] = d3.sum(values, function(d){ return d[key]})
          })
        return counts
        })
      .entries(data);

      data.forEach(function(d){
        d.date = parseDate(d.key);
      })

      var repairs = data.map(function(d) {
        return { date: d.date, no_repairs: d.values};
      });

      console.log(repairs)

      x.domain(d3.extent(data, function(d) { return d.date; }));

      y.domain([
        d3.min(repairs, function(c) { return d3.min(c.no_repairs); }),
        d3.max(repairs, function(c) { return d3.max(c.no_repairs); })
      ]);

      var module = svg.selectAll(".module")
        .data(repairs)
      .enter().append("g")
        .attr("class", "module");

      var path = svg.selectAll(".module").append("path")
        .attr("class", "line")
        .attr("d", function(d) { return line(d.no_repairs); })
        .style("stroke", function(d) { return color(d.date); });

      var totalLength = [path[0][0].getTotalLength(), path[0][1].getTotalLength()];

      console.log(totalLength);

      d3.select(path[0][0])
        .attr("stroke-dasharray", totalLength[0] + " " + totalLength[0])
        .attr("stroke-dashoffset", totalLength[0])
        .transition() // Call Transition Method
            .duration(10000) // Set Duration timing (ms)
            .ease("linear") // Set Easing option
            .attr("stroke-dashoffset", 0)// Set final value of dash-offset for transition
            .each("end", function(){
                labels.transition()
                    .delay(function(d, i){ return i * 1000; })
                    .style("opacity",1);
            });

      d3.select(path[0][1])
        .attr("stroke-dasharray", totalLength[1] + " " + totalLength[1])
        .attr("stroke-dashoffset", totalLength[1])
        .transition() // Call Transition Method
            .duration(10000) // Set Duration timing (ms)
            .ease("linear") // Set Easing option
            .attr("stroke-dashoffset", 0);// Set final value of dash-offset for transition
            .each("end", function(){
                labels.transition()
                    .delay(function(d, i){ return i * 1000; })
                    .style("opacity",1);

            });

      var point = module.append("g")
          .attr("class", "line-point");

          point.selectAll('circle')
                .data(function(d){ return d.values})
            .enter().append("circle")
                .attr("cx", function(d, i) { return x(d.date)})
                .attr("cy", function(d, i) { return y(d.value)})
                .attr("r", 5)
                .style("fill", "white")
                .style("stroke", function(d) {
                    if(d.value < 14000){
                        return color(this.parentNode.__data__.name);
                        }else{
                            return d3.select(this).attr("r",15).style("fill","red").style("stroke","red");
                        }
                });
      var labels = module.append("text")
          .datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
          .attr("class","label")
          .attr("transform", function(d) { return "translate(" + x(d.key) + "," + y(d.values) + ")"; })
          .attr("x", 3)
          .attr("dy", ".35em")
          .style("opacity", 0)
          .text(function(d) { return d.name; });

Also using viewing the value of the "path" in the console shows an empty array. Please assist.

A: Just sort your data before plotting the chart.
data.sort(function(a, b) {
  return a.date - b.date
});

var margin = {
    top: 20,
    right: 90,
    bottom: 30,
    left: 60
  },
  width = 980 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

var parseDate = d3.time.format("%Y/%m").parse;

var x = d3.time.scale()
  .range([0, width]);

var y = d3.scale.linear()
  .range([height, 0]);

var color = d3.scale.category10();

var xAxis = d3.svg.axis()
  .scale(x)
  .orient("bottom");

var yAxis = d3.svg.axis()
  .scale(y)
  .orient("left")
  .tickFormat(d3.format(".2s"));

var line = d3.svg.line()
  .interpolate("basis")
  .x(function(d) {
    return x(d.date);
  })
  .y(function(d) {
    return y(d.no_repairs);
  });

var svg = d3.select("#maincontent").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var data = [{
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/01",
  "actual": 39,
  "predicted": 63
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/10",
  "actual": 3,
  "predicted": 4
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/11",
  "actual": 4,
  "predicted": 3
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/12",
  "actual": 4,
  "predicted": 2
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/02",
  "actual": 29,
  "predicted": 45
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/03",
  "actual": 29,
  "predicted": 32
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/04",
  "actual": 10,
  "predicted": 22
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/05",
  "actual": 13,
  "predicted": 15
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/06",
  "actual": 9,
  "predicted": 16
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/07",
  "actual": 7,
  "predicted": 12
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/08",
  "actual": 5,
  "predicted": 9
}, {
  "module_category": "M1",
  "component_category": "P06",
  "date_repair": "2009/09",
  "actual": 4,
  "predicted": 5
}, {
  "module_category": "M1",
  "component_category": "P09",
  "date_repair": "2009/01",
  "actual": 7,
  "predicted": 5
}, {
  "module_category": "M1",
  "component_category": "P09",
  "date_repair": "2009/10",
  "actual": 3,
  "predicted": 1
}, {
  "module_category": "M1",
  "component_category": "P09",
  "date_repair": "2009/02",
  "actual": 2,
  "predicted": 3
}, {
  "module_category": "M1",
  "component_category": "P09",
  "date_repair": "2009/03",
  "actual": 6,
  "predicted": 2
}, {
  "module_category": "M1",
  "component_category": "P09",
  "date_repair": "2009/04",
  "actual": 4,
  "predicted": 2
}, {
  "module_category": "M1",
  "component_category": "P09",
  "date_repair": "2009/06",
  "actual": 1,
  "predicted": 2
}, {
  "module_category": "M1",
  "component_category": "P09",
  "date_repair": "2009/07",
  "actual": 3,
  "predicted": 2
}];

color.domain(d3.keys(data[0]).filter(function(key) {
  return key !== "date_repair"
}));

data.forEach(function(d) {
  d.date = parseDate(d.date_repair);
});

data.sort(function(a, b) {
  return a.date - b.date
});
console.log(data);

var repairs = color.domain().map(function(name) {
  return {
    name: name,
    values: data.map(function(d) {
      return {
        date: d.date,
        no_repairs: +d[name]
      };
    })
  };
});

console.log(repairs);

x.domain(d3.extent(data, function(d) {
  return d.date;
}));

y.domain([
  d3.min(repairs, function(c) {
    return d3.min(c.values, function(v) {
      return v.no_repairs;
    });
  }),
  d3.max(repairs, function(c) {
    return d3.max(c.values, function(v) {
      return v.no_repairs;
    });
  })
]);
console.log("comment1");

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .append("text")
  .attr("transform", "rotate(-90)")
  .attr("y", 0 - margin.left)
  .attr("x", 0 - (height / 2))
  .attr("dy", "1em")
  .style("text-anchor", "middle")
  .text("Number of Repairs");
console.log("comment2");

var module = svg.selectAll(".module")
  .data(repairs)
  .enter().append("g")
  .attr("class", "module");

var path = svg.selectAll(".module").append("path")
  .attr("class", "line")
  .attr("d", function(d) {
    return line(d.values);
  })
  .style("stroke", function(d) {
    return color(d.name);
  });

console.log("comment3");
var totalLength = [path[0][0].getTotalLength(), path[0][1].getTotalLength()];

console.log(totalLength);

d3.select(path[0][0])
  .attr("stroke-dasharray", totalLength[0] + " " + totalLength[0])
  .attr("stroke-dashoffset", totalLength[0])
  .transition() // Call Transition Method
  .duration(10000) // Set Duration timing (ms)
  .ease("linear") // Set Easing option
  .attr("stroke-dashoffset", 0) // Set final value of dash-offset for transition
  .each("end", function() {
    labels.transition()
      .delay(function(d, i) {
        return i * 1000;
      })
      .style("opacity", 1);
  });

console.log("comment4");

d3.select(path[0][1])
  .attr("stroke-dasharray", totalLength[1] + " " + totalLength[1])
  .attr("stroke-dashoffset", totalLength[1])
  .transition() // Call Transition Method
  .duration(10000) // Set Duration timing (ms)
  .ease("linear") // Set Easing option
  .attr("stroke-dashoffset", 0) // Set final value of dash-offset for transition
  .each("end", function() {
    labels.transition()
      .delay(function(d, i) {
        return i * 1000;
      })
      .style("opacity", 1);
  });

var point = module.append("g")
  .attr("class", "line-point");
console.log("comment5");

point.selectAll('circle')
  .data(function(d) {
    return d.values
  })
  .enter().append("circle")
  .attr("cx", function(d, i) {
    return x(d.date)
  })
  .attr("cy", function(d, i) {
    return y(d.no_repairs)
  })
  .attr("r", 5)
  .style("fill", "white")
  .style("stroke", function(d) {
    if (d.no_repairs < 14000) {
      return color(this.parentNode.__data__.name);
    } else {
      return d3.select(this).attr("r", 15).style("fill", "red").style("stroke", "red");
    }
  });

var labels = module.append("text")
  .datum(function(d) {
    return {
      name: d.name,
      value: d.values[d.values.length - 1]
    };
  })
  .attr("class", "label")
  .attr("transform", function(d) {
    return "translate(" + x(d.value.date) + "," + y(d.value.no_repairs) + ")";
  })
  .attr("x", 3)
  .attr("dy", ".35em")
  .style("opacity", 0)
  .text(function(d) {
    return d.name;
  });
path {
  fill: none;
}


text:
Q: What should I be studying if I want to calculate correlation between data sets? I'm building an app that brings in data from multiple API's (Stripe, Google Analytics, Github). I'd want to be able to analyze the different sets of data against each other if at all possible and draw meaningful conclusions based on correlations.
For example, I'd like to analyze monthly pageviews of  against revenue for those months and to find how strongly said page relates to my revenue. I want to  train a model to detect based on previous data when there are significant fluctuations in that data. Such that if suddenly my website dipped 40% in revenue, I can analyze all my analytics and revenue data to find the strongest correlation.
What kind of math should I be looking into? The last I studied math was in high school many years ago. I'm not sure what I should even look for.


text:
Q: merge two columns from two different dataframes in conditions, python input:
df1:
name, msg_time, age
adam,22-00-11, Nan
susam,23-00-14,Nan

df2:
name, age
adam, 23

i want to add msg_time from df1 to df['age'] for specific name
output:
df2:
name, age
adam, 23,22-00-11

my code:
df2=df2.assign(age=lambda x: x.age +','+df1.msg_time)

my problem is, that i am receiving :
df2:
name, age
adam, 23,22-00-11,22-00-11,22-00-11,22-00-11

A: You could merge on name and join the fields of interest separated by ,:
(df1.merge(df2, on='name')
    .set_index('name')[['age_y', 'msg_time']]
    .astype(str)
    .apply(','.join, axis=1)
    .rename('age')
    .reset_index())

   name          age
0  adam  23,22-00-11

A: I am using combine_first
df2.set_index('name').combine_first(df1.set_index('name')).dropna().astype(str).apply(' '.join,1).to_frame('age')
                age
name
adam  23.0 22-00-11

A: you could do it using series.map() and converting to string before concatenating them using astype(str):
df2.age=df2.age.astype(str)+','+df2.name.map(df1.set_index('name')['msg_time']).astype(str)
print(df2)

   name          age
0  adam  23,22-00-11