text:
Q: Batch Sum Fields Script using ArcPy? I have created a python script that batch summarizes all string fields within a fc table based on the concatenation of two fields.  The script loops through a list of the fields, however it stops about halfway through (same spot each time).  Why does this code not process the remaining string fields within the list?  After running it once, if I delete all the fields that it processed correctly the first time, then run it again on only the fields that it did not process, it runs ok.  Maybe my issue is with this line:
fieldname = flist.pop(0)

Ideas?
See code below
import arcpy, os
from arcpy import env

try:

    # Local variables:
    inTable = arcpy.GetParameterAsText(0)
    outWKSpace = arcpy.GetParameterAsText(1)

    # Process: Add Field
    arcpy.AddField_management(inTable, "cat", "TEXT", "", "", "200", "", "NULLABLE", "NON_REQUIRED", "")

    flist = arcpy.ListFields(inTable, '', 'String')
    fieldname = ''

    for field in flist:
        fieldname = flist.pop(0)
        arcpy.CalculateField_management(inTable, "cat", "!Sub_Batch!+\" \"+ !"+ fieldname.name +"!", "PYTHON_9.3", "")
        outTable = outWKSpace + "\SUM_" + fieldname.name
        table2 = arcpy.Frequency_analysis(inTable, outTable, "cat", "")

        intCount = arcpy.GetCount_management(outWKSpace + "\SUM_" + fieldname.name)

        arcpy.AddMessage(fieldname.name + ' records = ' + str(intCount))

except Exception, e:
  import traceback
  map(arcpy.AddError, traceback.format_exc().split("\n"))
  arcpy.AddError(str(e))

A: You're right - the problem was with fieldname.pop(0) - this actually takes the object at index 0 and removes it from the list. But you're already iterating through the list with for field in flist. Your code should be instead:
for field in flist:
    arcpy.CalculateField_management(inTable, "cat", "!Sub_Batch!+\" \"+ !"+ field.name +"!", "PYTHON_9.3", "")
    outTable = outWKSpace + "\SUM_" + field.name
    table2 = arcpy.Frequency_analysis(inTable, outTable, "cat", "")

    intCount = arcpy.GetCount_management(outWKSpace + "\SUM_" + field.name)

    arcpy.AddMessage(field.name + ' records = ' + str(intCount))


text:
Q: Automatically split (refactor) .h into header and implementation (h+cpp) When writing C++ code, I often start by writing full 'implementation' code in my header files, then later need to refactor the implementation into a .cpp file.
This is great, but I find this process laborious, but otherwise pretty easy, so I wondered about whether is there any automated way to do this?
Specifically, I want to convert all class and function definitions in the .h to declarations, and have them declared in a new .cpp file.
I'm using xcode, but I am open to any solutions.

A: There is Lazy C++ where you only write one .lzz file and it generates .h and .cpp for you.
I am really looking forward for C++ modules where you only write .cpp and the import file is generated automatically. But we will have to wait for a few years even though Clang has started to implement modules. Here are some examples.

A: You can use some tools such as Makeheaders
http://www.hwaci.com/sw/mkhdr/
but in general, these tools are not complete, especially meeting new c++11 files.

A: You may be also interested in Eclipse's function "Refactor/Toggle function". It not always work properly however.

A: C++20 modules essentially do that for us
As mentioned at: https://quuxplusone.github.io/blog/2019/11/07/modular-hello-world/ clang 2019-11 implements it along:
clang++ -std=c++2a -c helloworld.cpp -Xclang -emit-module-interface -o helloworld.pcm
clang++ -std=c++2a -c -fprebuilt-module-path=. -o helloworld.o helloworld.cpp
clang++ -std=c++2a -fprebuilt-module-path=. -o main.out main.cpp helloworld.o

where:

*

*helloworld.cpp contains the implementation

*helloworld.pcm is a precompiled module, basically an auto-extracted header from the .cpp (but in a clang internal language format) which gets used by main.cpp without an .hpp
So basically clang is the tool, and thus parsing is perfect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot create [suggestion] tag because of [discussion] tag in Android app I just tried to post a question with suggestion and discussion tags together and it's giving error message as given below:

Error message before MSE/MSO splitting
You are attempting to create the tag [suggestion]; however the tag [discussion] already exists! If you think this new tag should be allowed, raise it on http://meta.stackexchange.com

Are suggestion and personal tags same?

A: It's status-bydesign. The confusion was caused by discussion tag having suggestions tag as its synonym. SE prevents similar tag creation (e.g. singular-plural tag pairs, suggestion vs suggestions), and that's what the error message was trying to convey.
Also, it's status-norepro on v1.0.84 betaor somewhere before that. The app doesn't allow free input on tags anymore; user can only search and use  available tags from the list (excluding synonymized tags)


text:
Q: Android Studio reset my @dimen in xml I have some problem with setting params to my view in xml file with values from dimen files.
For example when i'm adding layout_height param to my EditText in laytout xml file:
    <EditText
     ....
    android:layout_height="@dimen/et_height"
     ....
    />

File dimens:
<resources>
     .........
    <dimen name="example">16dp</dimen>
    <dimen name="et_height">20dp</dimen>
     .........
</resources>

It works fine. But sometimes when i open this file again AndroidStudio replace @dimen/et_height with value 20dp in layout xml file. And i must change it again to @dimen/et_height.
How can i fix this ?
This is the normal case:

But in my case AndroidStudio replaces with value:

A: Having the same issue. Thought it is the ConstraintLayout but the issue also appears in every other layout though..
related post from me :
Android ConstraintLayout @dimens replaced with hardcoded values
Also some other user said it just shows the dp value, i am completely in your situation i know the grey text, but it does really replace the value..


text:
Q: ArrayList class separate from Java main file I have two separate files, one named WonderfulArrayList, and the other named ArrayListMain (I'm experimenting with ArrayLists, and I'm not quite sure what to do) and so I have a method in the WonderfulArrayList file, but the main file cannot see the method, which I have named booladdData, which would return true once the data is added to the array list. My WonderfulArrayList file is the following:
import java.util.*;
import java.io.*;

public class WonderfulArrayList{ //implement WonderfulArrayList
     public static int ADDNums;
     public static int index;
     public static int HEADNums;
     public static  ArrayList<Integer> arr = new ArrayList<Integer>(15);

     public static boolean booladdData(ArrayList<Integer>arr){
              arr.add(ADDNums);
              return true;
              }
    }

As you can see, I have booladdData instantiated with the ArrayList, named arr. Now, if you look at my main file:
public class ArrayListMain{

  //public ArrayList<Integer> arr = new ArrayList<Integer>(15);
  public static void main(String[]args){

          ArrayList<Integer> arr = new ArrayList<Integer>(15);
        int MenuNum = 0;
        int ADDNums = 0;
        Object Obj = new Object();

        Scanner scanner1 = new Scanner(System.in); //set up scanner for user input

        while(MenuNum != 7){ //menu loop
              Menu(MenuNum);
              MenuNum = scanner1.nextInt();

              if(MenuNum == 1){

                 arr.booladdData();
                 }

For some reason, even though I know that booladdData is created as public and they're both in the same folder, the main file doesn't have the scope to be able to see booladdData in the separate file.
Any idea what I'm doing wrong?

A: You should be calling WonderfulArrayList.booladdData(arr) instead of arr.booladdData(). The method booladdData() is defined as a class method of your WonderfulArrayList class. It's not an instance method of Java's ArrayList.
You also might want to read into object-oriented programming. Everything in your code is static.

A: You need to create your type instead of ArrayList
package com.jbirdvegas.test;

import java.util.ArrayList;

public class MainClazz {
    public static void main(String[] args) {
        // notice I'm creating my type `MyArrayList` instead of `ArrayList` type
        MyArrayList myArrayList = new MyArrayList();
        myArrayList.add("blah");
        System.out.println("My message:" + myArrayList.getSomething());
    }
}

class MyArrayList extends ArrayList {
    public String getSomething() {
        return "something";
    }
}

Prints:
My message: something


text:
Q: Linear and non-linear regression concerns I'm trying to do this polynomial regression using the scatter plot, and I have two concerns:

*

*The red line, which is the polynomial regression appears wrong to me when compared with the plots by the data values

*How can I calculate the r-square for each regression
A part of the X and Y data used (I took this data from the excel file):
The Y goes for each column that represents a specific region with total values.
x=[1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980...]

y=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.164, 0.16499999999999998, 0.16999999999999998, 0.175, 0.17200000000000001, 0.185, 0.189, 0.195, 0.201...]

#read the data
Renew = pd.read_excel('bp-stats-review-2019-all-data.xlsx', sheet_name = 'Renewables - TWh', headers = 2, skiprows=2, usecols = range(55)).dropna(axis=0,how='all').iloc[:-10]
Renew.fillna('0',inplace=True)

#Taking only the Totals
Countries_Renew = Renew[~Renew['Terawatt-hours'].str.startswith('Total')].sort_values(['Terawatt-hours'])
Countries_Renew.set_index('Terawatt-hours', inplace=True)

#build the Linear plot regression by region
df=Countries_Renew_Total.drop(['Total World']).transpose()
n=0

for j in df.columns:
    print('The region is: '+j)
    print(n)
    for i in range(1,3):
        #import the dataset
        x=df.index.values.reshape(-1,1)
        y=df.iloc[:,int(n)].values.reshape(-1,1)

        #Fit the linear regression
        lin=LinearRegression()
        lin.fit(x,y)

        #Fit the Poly regression
        poly = PolynomialFeatures(degree = i)
        x_poly = poly.fit_transform(x)
        poly.fit(x_poly,y)
        lin2=LinearRegression()
        lin2.fit(x_poly,y)

        #Plot Poly regression
        plt.scatter(x,y,color='blue')
        plt.plot(x,lin2.predict(poly.fit_transform(x)),color='red')
        plt.title('Polynomial Regression degree '+str(i))
        plt.xlabel('Year')
        plt.ylabel('Renewable Generation (TWh)')
        plt.show()
        print(lin2.predict(poly.fit_transform([[2019]])))
        print(lin2.predict(poly.fit_transform([[2020]])))
    n=n+1

A: The first graph you posted actually looks about how I would expect. The majority of the points are nearly horizontal, with a few of the rightmost points extending upwards. You have a near flat line of best fit applied which is attempting to minimize the error (which is the distance between your predictions and the actual values). Does this make sense?
It should be noted, that in order to do a linear regression on exponential data, you need to apply a log to the exponential data, which will turn it into a linear data set. Does that make sense?
Your second example is a little more confusing as I'm not familiar with the Polynomial features function, but I agree the curve does not look very accurate.


text:
Q: Why does my formula for date go away when form is submitted? I want my Google sheet that is populated from a Google form to have a column that is just a date (8/5/2019) so that it can be easily merged into a google doc through automation of Autocart.
I inserted a column next to the time stamp and populated it with the formula
=TO_DATE(A5)
=TO_DATE(A6)
=TO_DATE(A7)

and populated the whole column with this formula.
Whenever I test my form to see if it works the data is imported in but the formula in column B is taken away. Why does it take away my formula?

A: that is expected behavior. you should use instead an array formula one row above eg if your first date starts in A5 paste this in 4th row:
=ARRAYFORMULA({""; IF(LEN(A5:A), TO_DATE(A5:A), )})

=ARRAYFORMULA({"Date"; IF(LEN(A2:A), TEXT(TO_DATE(A2:A), "m/d/yyyy"), )})


text:
Q: d3.js force directed interactive coloring for groups I'm working from this example of a D3.js force-directed graph. The example colors the nodes according to their group membership for one set of groups. I have this working fine with my data. However, my data can be grouped on multiple node attributes (e.g. by gender or by party affiliation). The simple solution is to simply make separate graphs, each colored according to a different attribute.
Is there a way to have the color scheme be interactive (rather than hard coded)? Will D3 let me add a drop down or button to pick which attribute (gender, affiliation...) is used to color the nodes? This code lets a user interactively filter their data using a drop down menu, but I'm not sure how I might go from that to interactively picking attributes to use for colors.

A: You need to

*

*build some colour scales and functions for the attributes you'd want to colour on

*use them to generate a select element with appropriate options

*then call a small routine that recolours the nodes

https://jsfiddle.net/vbpqn1e6/
This is the miserables example with such stuff, it could be tidied up a bit / a lot but shows the principle:
var groupColor = d3.scaleOrdinal(d3.schemeCategory20);
var nameColor = d3.scaleLinear().domain([65,78,90]).range(["#f00", "#0f0", "#00f"]);
var madameColor = d3.scaleLinear().domain([true, false]).range(["#f00", "#aaa"]);

var colFuncs = {
    "Group": function (d) { return groupColor (d.group); },
    "Name": function (d) { return nameColor (d.id.substring(0,1).toUpperCase().charCodeAt(0)); },
    "Madame?": function(d) { return madameColor (d.id.substring(0,2) === "Mm"); }
};
var currentColFunc = colFuncs["Group"];

d3.select("body").insert("select", ":first-child")
  .on ("change", function() {
      var e = d3.event;
      if (e) {
        currentColFunc = colFuncs[e.target.value];
        updateColour();
      }
  })
    .selectAll("option")
    .data(d3.keys(colFuncs))
  .enter()
  .append("option")
  .attr("value", function(d) { return d; })
  .text (function(d) { return d; })
 ;

The .on("change") event listens to the select element and when an option is chosen uses that option's value to set the current Colour scheme (currentColFunc). If you want more choices just add more to the colFuncs object.
This is then used in updateColour:
   function updateColour () {
    node.attr("fill", function(d) {
        return currentColFunc(d);
    });
   }


text:
Q: Run React-Native UWP error I am trying to run React-Native for UWP on windows 10. I follow the instructions here https://www.microsoft.com/reallifecode/2016/05/26/creating-universal-windows-apps-with-react-native/#comment-180
When I get to last step (Running the Universal Windows App), it throws error when I run the command
react-native run-windows

The error I get is
Starting the React-Native Server
Failed to deploy: path must be a string or Buffer

I tried google this error. I don't think there is much on React-Native UWP, and this error hasn't came up before.

A: Solution
Open the Solution in Visual Studio. Set up the Build so that it works on my machine (make sure solution platform and solution configurations are correct).
From now on, running that command should work with no issues.


text:
Q: Requests and connections double on node 4.1.2 We're currently in the process of updating from node 0.10 to node 4.1.2 and we're seeing some weird patterns. The number of connections to our postgres database doubles1 and we're seeing the same pattern with requests to external services2. We are running a clustered app running the native cluster API and the number of workers is the same for both versions.
I'm failing to understand why upgrading the runtime language would apparently change application behaviour by doubling requests to external services.

A: One of the interesting things I've noticed with 0.12 and 4.x is the change in garbage collection.  I've not used the pg module before so I don't know internally how it maintains it's pools of if it would be affected by memory or garbage collection.  If you haven't defined default memory setting for node you could try giving that a shot and see if you see any other results.
node --max_old_space_size <some sane value in MB>

A: I ran into something similar, but I was getting double file writes. I don't know your exact case, but I've seen a scenario where requests could almost exactly double.
in the update to 4.1.2, process.send and child.send has gone from synchronous to asynchronous.
I found an issue like this:
var child = fork('./request.js');
var test = {};

child.send(small request);
child.send(large request);
child.on('response', function (val) {
    console.log('small request came back: ' + val);
    test = val;
});

if(!test){
   //retry request
} ...

So where as previously the blocking sends has allowed this code to work, the non-blocking version assumes an error has occurred and retries. No error actually occurred, so double the requests come in.


text:
Q: How can I add an image to all pages of my PDF? I have been trying to add an image to all pages using itextsharp. The image needs to be OVER all content of every page. I have used the following code below all the otherdoc.add()
Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 30, 1);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("~/pdf/" + fname), FileMode.Create));
doc.Open();
Image image = Image.GetInstance(Server.MapPath("~/images/draft.png"));
image.SetAbsolutePosition(12, 300);
writer.DirectContent.AddImage(image, false);
doc.Close();

The above code only inserts an image in the last page. Is there any way to insert the image in the same way in all pages?

A: It's normal that the image is only added once; after all: you're adding it only once. (Or you've left away some essential steps in your code snippet: see the edit I made.)
In any case: you can solve your problem by using a page event. There are some examples in Java here: http://itextpdf.com/sandbox/events
Or you can consult chapter 5 of my book. All examples are available in Java as well as in C#.
You should create a document in 5 steps and add an event in step 2:
// step 1
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.GetInstance(document, stream);
MyEvent event = new MyEvent();
writer.PageEvent = event;
// step 3
document.Open();
// step 4
// Add whatever content you want to add
// step 5
document.Close();

You have to write the MyEvent class yourself:
protected class MyEvent : PdfPageEventHelper {

    Image image;

    public override void OnOpenDocument(PdfWriter writer, Document document) {
        image = Image.GetInstance(Server.MapPath("~/images/draft.png"));
        image.SetAbsolutePosition(12, 300);
    }

    public override void OnEndPage(PdfWriter writer, Document document) {
        writer.DirectContent.AddImage(image);
    }
}

The OnEndPage() in class MyEvent will be triggered every time the PdfWriter has finished a page. Hence the image will be added on every page.
Caveat: it is important to create the image object outside the OnEndPage() method, otherwise the image bytes risk being added as many times as there are pages in your PDF (leading to a bloated PDF).

A: Document document = new Document();
// step 2

PdfWriter writer = PdfWriter.GetInstance(document, stream);

 final MyEvent event = new MyEvent();

    writer.setPageEvent(event);

    document.Open();

// Add whatever content you want to add

   document.Close();

//Now Create The new class and override the onEndPage()
//I have used this for footer image but you can add wherever you want
//in the whole page using setAbsolutePosition(see below the class)
//I am using palyFramework with java
 package controllers;

import java.io.IOException;
import java.nio.file.Files;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import play.Play;

public class MyEvent extends PdfPageEventHelper{

@Override
public void onEndPage(final PdfWriter writer, final Document document)
{
    final Font ffont = new Font(Font.FontFamily.TIMES_ROMAN,8,
Font.ITALIC);
    Image img;
    try {
        final Phrase footer = new Phrase("Powered By :", ffont);
img=Image.getInstance(Files.readAllBytes(Play.application().getFile("/
                                     img- path/Image.png").toPath()));
        img.scaleToFit(60f, 40f);
           img.setAbsolutePosition(510,5);
        final PdfContentByte cb = writer.getDirectContent();
        cb.addImage(img);
        ColumnText.showTextAligned(cb, Element.ALIGN_CENTER,
                footer,490, 15, 0);
    } catch (IOException | DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}}

It works fine for me; refer to this link.


text:
Q: Query to find the customer with highest amount of total purchases My relationship schema looks something like this :

Now I am trying to write a SQL query to find the customer who has the highest total amount of purchases in the year 2016. I want to know the customer name and the total amount of purchases.
Select Customer_name, TotalAmountOfAllHisPurchases from ...

I cannot think of a neat way of doing this. Anyone who can help me get started on this please?

A: I believe the following query should work to identify the customer name with the highest amount derived from all orders in the current calendar year:
SELECT CUSTOMER_NAME, Y.QNTY
FROM CUSTOMER_T CUST,
(
  SELECT X.CUSTOMER_ID, X.QNTY, MAX(X.QNTY) MAXAMT
  FROM (
        SELECT ORD.CUSTOMER_ID, SUM(OLN.QUANTITY * PRD.UNIT_PRICE) QNTY
        FROM ORDER_T ORD, ORDER_LINE_T OLN, PRODUCT_T PRD
        WHERE TRUNC(OLN.ORDER_DATE,'YEAR') = TRUNC(SYSDATE,'YEAR')
        AND ORD.ORDER_ID = OLN.ORDER_ID
        AND PRD.PRODUCT_ID = OLN.PRODUCT_ID
        GROUP BY ORD.CUSTOMER_ID
       ) X
) Y
WHERE CUST.CUSTOMER_ID = Y.CUSTOMR_ID
AND Y.QNTY = Y.MAXAMT;

The inner-most query joins the ORDER, ORDER_LINE, and PRODUCT tables grouping by the customer ID to sum the total purchases for the current year (orders by summed amount descending). The query up one level uses the inner query results and adds on the max summed total of purchases. The outer-most query joins the CUSTOMER_T table with the inner results to get the customer Name and total order amount for all customers that match the MAXAMT value.
You may modify the date condition to always restrict to 2016 (regardless of current year) as follows:
WHERE TRUNC(OLN.ORDER_DATE,'YEAR') = TRUNC(SYSDATE,'YEAR')

Write as:
WHERE TRUNC(OLN.ORDER_DATE,'YEAR') = TRUNC(TO_DATE('01/01/2016','MM/DD/YYYY'),'YEAR')

You may also pull the outer query of CUSTOMER_T inside the inner table and add it to the joins. It accomplishes the same thing, but I'm not sure which is more efficient (which is applicable if your data set is large).
Note: Written from an Oracle DB perspective, hopefully this helps and you are able to convert the syntax.
Edit: I realized my suggestion would overlook multiple customers with the same total spending amount. I've reworked it to use MAX and show multiple customers (if applicable). Hope this works for your/can be converted to MYSQL.

A: Assuming totalPurchases as total of Orders:
SELECT Customer_name, COUNT(o.order_id) as totalPurchases FROM Customer_t c
LEFT JOIN Order_t o ON o.customer_id = c.customer_id
GROUP BY c.customer_id

Edit:
SELECT Customer_name, SUM(p.unity_price*ol.quantity) as totalPurchases FROM Customer_t c
LEFT JOIN Order_t o ON o.customer_id = c.customer_id
LEFT JOIN Order_Line_t ol ON ol.order_id = o.order_id
LEFT JOIN Product_t p ON p.product_id = ol.product_id
GROUP BY c.customer_id

A: THIS ANSWER WILL BE HELPFUL FOR YOU !!!!!!!!!!!!!!!!!!!
I did not have a mysql db installed in my device so I used the ONLINE
TRY-IT-YOURSELF mysql editor at http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all
As I used the TIY editor I could not change the table names but I could find similar table structure with what you have given
select * from customers  ----->>>> YOUR Customer_t
CustomerID ||
CustomerName
.
select * from orders ----->>> YOUR Order_t
CustomerID ||
OrderID
.
select * from  orderdetails ----->>>> YOUR Order_Line_t
OrderID ||
ProductID ||
Quantity
.
select * from products ---->>>> YOUR Product_t
ProductID ||
Price
with
table1 as (select o.CustomerID, o.orderid,
(
select sum(od.Quantity * p.Price) from orderdetails od, products p
where od.ProductID = p.ProductID and od.orderid = o.orderid group by od.orderid) as total
from orders o  group by o.orderid, o.CustomerID )-- having o.CustomerID in(4,10))
select c.CustomerName,sum(t1.total) as total_purchases from table1 t1,customers c
where t1.customerid = c.customerid  group by t1.customerid having total_purchases =

(with
table1 as (select o.CustomerID, o.orderid,
(
select sum(od.Quantity * p.Price) from orderdetails od, products p
where od.ProductID = p.ProductID and od.orderid = o.orderid group by od.orderid) as total
from orders o  group by o.orderid, o.CustomerID )-- having o.CustomerID in(4,10))
select sum(t1.total) as total_purchases from table1 t1,customers c
where t1.customerid = c.customerid  group by t1.customerid order by total_purchases desc
LIMIT 1)

This Query lists all the Customer Names & Purchase Amount of All customers with the Maximum Purchase


text:
Q: Netcore: Patron Repositorio y multiples cambios en la base de datos desde hace poco que estoy desarrollando con netcore y aún hay temas que no entiendo del todo.
En el siguiente código tengo un controlador al que por Inyección de Dependencias le paso un repositorio.
En el repositorio hago una serie de acciones (entre ellas llamar a otro repositorio).
public class AppController : ControllerBase
{
    public virtual async Task<IActionResult> Put(int id, TEntity data)
    {
        //AppRepo
        await repository.Update(data);
        return NoContent();
    }

}

public class AppRepo<App, DataContext> {
    private DataContex _ctx ;

    public async Task<App> Add(App entity)
    {
        await _ctx.Apps.AddAsync(entity);
        await _ctx.SaveChangesAsync()
        return entity;
    }

    public async Task<App> Update(App data){
        _ctx.Entry(data).State = EntityState.Modified;
        App newData = await Add(data);
        var dependiente = new AppDependenciasRepo(_ctx);
        await dependiente.updateChangesApp(data.Id, data.Dependencias);
        await _ctx.SaveChangesAsync()
    }
}

public class AppDependenciasRepo<Dependencia, DataContext>
{
   public async Task updateChangesApp(int ApplicationId, List<Dependencia> nuevos){
        Dependencias old = new Dependencias () { ApplicationId = ApplicationId };
        _ctx.Dependencias.Attach(old);
        _ctx.Dependencias.Remove(old);
        await _ctx.Dependencias.AddRangeAsync(nuevos);
        await _ctx.SaveChangesAsync()
   }
}

He puesto en cada método de los repositoris _ctx.SaveChangesAsync(), para cuando se hagan llamado independiente se escriban los datos en la db.
Pero cuando hago operaciones mas complejas comienzan las dudas:
_ctx.Entry(data).State = EntityState.Modified;
App newData = await Add(data);

En las sentencias anteriores quiero modificará el estado y luego agrego un nuevo dato, entiendo que cuando termine Add(data), también se escribirá el nuevo estado de la entidad; por lo que el contexto _ctx, ya no tendrá cambios pendientes.
En el método Update de AppRepo, llamo a updateChangesApp, este primero borra datos para luego ingresar datos substitutos. Como estoy utilizando Async tengo el temor de que primero agregue los datos y luego los borre todos.
_ctx.Dependencias.Remove(old);
await _ctx.Dependencias.AddRangeAsync(nuevos);
await _ctx.SaveChangesAsync()

¿Son correctos mis suposiciones, es así como se debe trabajar o tal vez debería crear una Unidad de Trabajo para encapsular el llamado a SaveChangesAsync?.

A: Mi sugerencia es que no utilices el patron repositorio sobre Entity Framework por que estas haciendo una abstraccion sobre otra abstraccion.
Visualiza a tu controlador si en lugar de inyectar el repositorio inyectas la clase DbContext.
Si implementas este mecanismo de inyectar el DbContex en tu controlador tendras acceso a todas las tablas de tu base de datos y las consultas como las modificaciones en BD se verán enormemente simplificadas.
Hacer esto es algo totalmente valido y no rompes niguna regla de arqutiectura, sigues conservando las reglas de Patron repositorio y Unidad de trabajo (por que EF actua como un repositorio y unidad de trabajo), mantienes el codig limpio y mantenible.


text:
Q: Deserializing JSON data containing a varying number of parameters to C# (using Json.NET) I'm trying to deserialize the following JSON response:
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Yes", "1":"No"} … ]

A problem arises, however, in the fact that the number of parameters following "category" can vary from 0 to 10. Meaning all the following are possible JSON responses:
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads"} … ]
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Yes", "1":"No"} … ]
[{"pollid":"1", "question":"This is a test", "start":"2011-06-28", "end":"2012-03-21", "category":"Roads", "0":"Bad", "1":"OK", "2":"Good", "3":"Very good"} … ]

I'm deserializing responses to objects of the following form:
class Poll
    {
        public int pollid { get; set; }
        public string question { get; set; }
        public DateTime start { get; set; }
        public DateTime end { get; set; }
        public string category { get; set; }

        [JsonProperty("0")]
        public string polloption0 { get; set; }
        [JsonProperty("1")]
        public string polloption1 { get; set; }
        [JsonProperty("2")]
        public string polloption2 { get; set; }
        [JsonProperty("3")]
        public string polloption3 { get; set; }
        [JsonProperty("4")]
        public string polloption4 { get; set; }
        [JsonProperty("5")]
        public string polloption5 { get; set; }
        [JsonProperty("6")]
        public string polloption6 { get; set; }
        [JsonProperty("7")]
        public string polloption7 { get; set; }
        [JsonProperty("8")]
        public string polloption8 { get; set; }
        [JsonProperty("9")]
        public string polloption9 { get; set; }
    }

My questions is: Is there perhaps a better way to handle the storing of a varying number of parameters? Having 10 class properties which may or may not be used (depending on the response) seems like such a "hack".
Any help would be truly appreciated!
Many thanks,
Ted

A: You can either hold the variable number of properties in and Array
Have something like
List<string> ();

where you put all of polloption1, polloption2 ...
Or you could deserialize the json to a dynamic type
dynamic d = JObject.Parse(json);

And access the properties which you know exist
d.pollid, d.start, d.category ...

A:
Is there perhaps a better way to handle the storing of a varying number of parameters?

You could deserialize into an ExpandoObject or dynamic e.g.
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<dynamic>(json);
foreach (var item in result)
{
    Console.WriteLine(item["question"]);
}


text:
Q: Buffer and flush Apache Beam streaming data I have a streaming job that with initial run will have to process large amount of data. One of DoFn calls remote service that supports batch requests, so when working with bounded collections I use following approach:
  private static final class Function extends DoFn<String, Void> implements Serializable {
    private static final long serialVersionUID = 2417984990958377700L;

    private static final int LIMIT = 500;

    private transient Queue<String> buffered;

    @StartBundle
    public void startBundle(Context context) throws Exception {
      buffered = new LinkedList<>();
    }

    @ProcessElement
    public void processElement(ProcessContext context) throws Exception {
      buffered.add(context.element());

      if (buffered.size() > LIMIT) {
        flush();
      }
    }

    @FinishBundle
    public void finishBundle(Context c) throws Exception {
      // process remaining
      flush();
    }

    private void flush() {
      // build batch request
      while (!buffered.isEmpty()) {
        buffered.poll();
        // do something
      }
    }
  }

Is there a way to window data so the same approach can be used on unbounded collections?
I've tried following:
pipeline
    .apply("Read", Read.from(source))
    .apply(WithTimestamps.of(input -> Instant.now()))
    .apply(Window.into(FixedWindows.of(Duration.standardMinutes(2L))))
    .apply("Process", ParDo.of(new Function()));

but startBundle and finishBundle are called for every element. Is there a chance to have something like with RxJava (2 minute windows or 100 element bundles):
source
    .toFlowable(BackpressureStrategy.LATEST)
    .buffer(2, TimeUnit.MINUTES, 100)

A: This is a quintessential use case for the new feature of per-key-and-windows state and timers.
State is described in a Beam blog post, while for timers you'll have to rely on the Javadoc. Nevermind what the javadoc says about runners supporting them, the true status is found in Beam's capability matrix.
The pattern is very much like what you have written, but state allows it to work with windows and also across bundles, since they may be very small in streaming. Since state must be partitioned somehow to maintain parallelism, you'll need to add some sort of key. Currently there is no automatic sharding for this.
private static final class Function extends DoFn<KV<Key, String>, Void> implements Serializable {
  private static final long serialVersionUID = 2417984990958377700L;

  private static final int LIMIT = 500;

  @StateId("bufferedSize")
  private final StateSpec<Object, ValueState<Integer>> bufferedSizeSpec =
      StateSpecs.value(VarIntCoder.of());

  @StateId("buffered")
  private final StateSpec<Object, BagState<String>> bufferedSpec =
      StateSpecs.bag(StringUtf8Coder.of());

  @TimerId("expiry")
  private final TimerSpec expirySpec = TimerSpecs.timer(TimeDomain.EVENT_TIME);

  @ProcessElement
  public void processElement(
      ProcessContext context,
      BoundedWindow window,
      @StateId("bufferedSize") ValueState<Integer> bufferedSizeState,
      @StateId("buffered") BagState<String> bufferedState,
      @TimerId("expiry") Timer expiryTimer) {

    int size = firstNonNull(bufferedSizeState.read(), 0);
    bufferedState.add(context.element().getValue());
    size += 1;
    bufferedSizeState.write(size);
    expiryTimer.set(window.maxTimestamp().plus(allowedLateness));

    if (size > LIMIT) {
      flush(context, bufferedState, bufferedSizeState);
    }
  }

  @OnTimer("expiry")
  public void onExpiry(
      OnTimerContext context,
      @StateId("bufferedSize") ValueState<Integer> bufferedSizeState,
      @StateId("buffered") BagState<String> bufferedState) {
    flush(context, bufferedState, bufferedSizeState);
  }

  private void flush(
      WindowedContext context,
      BagState<String> bufferedState,
      ValueState<Integer> bufferedSizeState) {
    Iterable<String> buffered = bufferedState.read();

    // build batch request from buffered
    ...

    // clear things
    bufferedState.clear();
    bufferedSizeState.clear();
  }
}

Taking a few notes here:

*

*State replaces your DoFn's instance variables, since
instance variables have no cohesion across windows.

*The buffer and the size are just initialized as needed instead
of @StartBundle.

*The BagState supports "blind" writes, so there doesn't need to be
any read-modify-write, just committing the new elements in the same
way as when you output.

*Setting a timer repeatedly for the same time is just fine;
it should mostly be a noop.

*@OnTimer("expiry") takes the place of @FinishBundle, since
finishing a bundle is not a per-window thing but an artifact of
how a runner executes your pipeline.

All that said, if you are writing to an external system, perhaps you would want to reify the windows and re-window into the global window before just doing writes where the manner of your write depends on the window, since "the external world is globally windowed".

A: The documentation for apache beam 0.6.0 says that StateId is "Not currently supported by any runner."


text:
Q: POST with AFNetworking, error code -1001 I want to POST a json message to send to a server. I don't have access to the server itself but I know it is working and set up to return a success/failure message when a message gets through. The server requires an app id and password to connect
I am using AFNetworking for this. Here is the code I'm using:
NSURL* pushServerURL = [NSURL URLWithString: @"http://myserverurl.com/"];
AFHTTPClient* networkInstance = [[AFHTTPClient alloc] initWithBaseURL: pushServerURL];

NSDictionary *parameters =[NSDictionary dictionaryWithObjectsAndKeys:
                           @"myappid", @"app_id", @"mypassword", @"password", nil];

NSDictionary *params =[NSDictionary dictionaryWithObjectsAndKeys:
                       parameters, @"user", nil];

[networkInstance postPath: @"users/login.json"
               parameters: params
                  success:^
 (AFHTTPRequestOperation *operation, id jsonResponse)
{
    NSLog (@"SUCCESS");
}
                  failure:^
(AFHTTPRequestOperation *operation, NSError *error)
{
    NSLog(@"FAILED");
}];

It always fails with the error code -1001.
The NSError has 4 keys in the user info
NSErrorFailingURLStringKey with value @"http://myserverurl.com/,
NSErrorFailingURLKey with value <not an Objective-C object>,
NSLocalizedDescription with value "The request timed out"
NSUnderlyingError and the value has no string.

Any idea what I might be doing wrong?

A: Try this line of code. You can easily find what is the response coming from server or else, where the actual problem is?
[networkInstance postPath: @"users/login.json"
           parameters: params
              success:^(AFHTTPRequestOperation *operation, id jsonResponse) {
  NSLog (@"SUCCESS");
}
              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  NSLog(@" Error - Statistics file upload failed: \"%@\"", [request error]);
}];


text:
Q: How to fix ConstraintLayout inside ScrollView is not scolling? My App contains many buttons, which are shown under each other, two per row. I generate the buttons dynamically via Java, which are them shown in the ConstraintLayout.
<?xml version="1.0" encoding="utf-8"?>

    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/rootLayout"
            >

            </androidx.constraintlayout.widget.ConstraintLayout>

    </ScrollView>

I have tried several layouts beside the ConstraintLayout, the TableView scrolling worked, however the button are not in the correct place then.
This is how the buttons are generated:
Button b = new Button(this);
            b.setText(myClass.getTitle());
            b.setTextColor(0xFFFFFFFF);
            b.setX(buttonX);
            b.setY(buttonY);
            b.setWidth(buttonWidth);
            b.setHeight(buttonHeight);
            conLayout.addView(b);


text:
Q: Dictionary to a list How can you use a value of a dictionary to map it to a list. For example I have Dictionary<int,int> studid= new Dictionary<int,int>(); where index will be the key and id will be the value. Now I have a list of marks.
How can I point the id to the list of marks and display them?

A: You are using an incorrect data type for your needs. You need a dictionary mapping a key to a list of integers:
Dictionary<int,List<int>> studid= new Dictionary<int,List<int>>();

You would use the key in order to get the list of marks:
var marks = studid[theIndex];

A: Make it a Dictionary<int, List<int>> is the simplest way. Your key will be an int, and the value can be a list of marks.
var dict = new Dictionary<int, List<int>>();
dict.Add(1, new List<int>() { 1, 2, 3, 4 });


text:
Q: Continuous distribution from data organized in intervals in R I have the following problem. My data set is as follows:
Income              Numerosity
from 6000 to 7500       704790
from 7500 to 10000     1294784
from 10000 to 12000    1051902
from 12000 to 15000    1585132
from 15000 to 20000     704012
from 20000 to 25000     206901
from 25000 to 30000     156661

I would like to approximate these data with a continuous density function.
Is there an easy way to do this in R? I am thinking of something like an "inverse" process with respect to what is done by the function "cut".

A: I solved in this way: first I used sample(6000:7500, 704790, replace=TRUE) for each row to create a vector of generated observation. Then I applied the function density to the vector and obtained the density function I was looking for. There are certainly better and more elegant methods, but this worked.


text:
Q: Run python program from Erlang I want to read some data from a port in Python in a while true.
Then I want to grab the data from Python in Erlang on a function call.
So technically in this while true some global variables is gonna be set and on the request from erlang those variables will be return.
I am using erlport for this communication but what I found was that I can make calls and casts to the python code but not run a function in python (in this case the main) and let it run. when I tried to run it with the call function erlang doesn't work and obviously is waiting for a response.
How can I do this?
any other alternative approaches is also good if you think this is not the correct way to do it.

A: If I understand the question correctly you want to receive some data from an external port in Python, aggregate it and then transfer it to Erlang.
In case if you can use threads with your Python code you probably can do it the following way:

*

*Run external port receive loop in a thread

*Once data is aggregated push it as a message to Erlang. (Unfortunately you can't currently use threads and call Erlang functions from Python with ErlPort)
The following is an example Python module which works with ErlPort:
from time import sleep
from threading import Thread

from erlport.erlterms import Atom
from erlport import erlang

def start(receiver):
    Thread(target=receive_loop, args=[receiver]).start()
    return Atom("ok")

def receive_loop(receiver):
    while True:
        data = ""
        for chunk in ["Got ", "BIG ", "Data"]:
            data += chunk
            sleep(2)
        erlang.cast(receiver, [data])

The for loop represents some data aggregation procedure.
And in Erlang shell it works like this:
1> {ok, P} = python:start().
{ok,<0.34.0>}
2> python:call(P, external_port, start, [self()]).
ok
3> timer:sleep(6).
ok
4> flush().
Shell got [<<"Got BIG Data">>]
ok

A: Ports communicate with Erlang VM by standard input/output. Does your python program use stdin/stdout for other purposes? If yes - it may be a reason of the problem.


text:
Q: AWS DMS Exporting Bad CSV Rows When String Field Ends in Backslash I recently set up an RDS Postgres -> DMS -> S3 migration task. We are then using Snowpipe to import the CSV files from S3 into Snowflake. The issue I'm having is that DMS will automatically enclose certain string column values in double quotes when there are problematic characters, but we are getting a number of rows that have no problematic characters aside from the fact that they end with a backslash. Here is an example row:
613553630,1593721266,51801497,40223361753,Im definetly a traitor 100% confirmed  PC /  PW  Partner  -  !discord  ༼ つ ◕_◕ ༽つ --\,,2022-09-17 19:01:58.000000,2022-09-17 19:01:58.000000,true,en,archive,14671,false,2022-09-19 03:11:59.961644,2022-09-19 03:11:59.961645

Rows like this fail on import to Snowflake because the column delimiter comma is being treated as part of the string due to the trailing backslash.
Is there a way, either through the S3 destination endpoint settings, or a transformation rule, to tell DMS to always enclose every string for this column in double quotes? Is there some other way to solve this anyone can think of on the DMS side? Alternatively, does anyone know of a strategy to deal with this on the import side with the Snowflake COPY INTO?
Thanks!


text:
Q: Run Powershell script every hour on Azure I have found this great script which backs up SQL Azure database to BLOB.
I want to run many different variations of this script - e.g. DB1 goes to Customer1Blob, DB2 goes to Customer2Blob.
I have looked at Scheduler Job Collections. However I can only see options (Action settings) for HTTP(S)/ Storage Queue / Service Bus.
Is it possible to run a specific .ps1 script (with commands) scheduled?

A: You can definitely run a Powershell script as a WebJob. If you want to run a script on a schedule, you can add a settings.job file containing a chron expression with your webjob. The docs for doing so are here.

A: For this type of automation tasks, I prefer to use the Azure Automation service.  You can create runbooks using powershell and then schedule this with the use of the Azure scheduler.  You can have it run "on azure" so you do not need to use compute power that you pay for (rather you pay by the minute the job runs) or you can configure it to run with a hybrid worker.
For more information, please see the documentation

A: When exporting from SQL DB or from SQL Server, make sure you are exporting from a quiescent database. Exporting from a database with active transactions can result in data integrity issues - data being added to various tables while they are also being exported.


text:
Q: How to send multiple HTTP requests in NGRX Effects properly? I've written the Effect below for a single HTTP request:
(payload of getRequestObj is an object)
@Effect()
   indexDoc$ = this.actions$.pipe(
      ofType<IndexDocuments>(myActionTypes2.IndexDoc),
      mergeMapTo(this.store.select(getRequestObj).pipe(
         take(1)
      )),
      mergeMap((request: any) => this.myService.indexDoc(request).pipe(
         map((response: any[]) => new IndexSuccess(response)),
         catchError(error => of(new IndexFail(error)))
      ))
   );

What I want is, feeding the Effect with an array, and send an HTTP request for each item in the array. What I tried:
(payload of getRequestArray is an array of objects)
@Effect()
   indexDocs$ = this.actions$.pipe(
      ofType<indexDocs>(myActionTypes1.IndexDocs),
      concatMapTo(this.store.select(getRequestsArray)),
      concatMap((request: any[]) => {
         return zip(...request.map(item => {
            return this.myService.indexDocs(item).pipe(
               map(response => {
                  return this.store.dispatch(new IndexSuccess(response))
               }),
               catchError(error => {
                  return Observable.of(this.store.dispatch(new IndexFail(error)));
               })
            )
         }))
      })

What happens is, all of the requests return 412 Precondition Failed error. How do I make it work properly?


text:
Q: run create-react-app without installing dependencies I'm developing a template for create-react-app. To test the template i run
npx create-react-app my-app --template file:<path-to-my-template>

This also installs all the dependencies in the node_module folder, making the whole process quite slow if I make frequent changes.
Is there a way to bootstrap the application without automatically installing the dependencies?

A: To keep it simple; you may create the app and then delete the node_modules:
npx create-react-app my-app
rm -rf node_modules


text:
Q: How to format time objects in Java into the correct timezone I want to use the Java Time API to get the central Europen summer time (CEST) and format it correctly. I have the following code:
LocalDateTime localDateTime= LocalDateTime.now();
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
localDateTime.format(myFormatObj);
ZoneId europeBerlin = ZoneId.of("Europe/Berlin");
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, europeBerlin);

The command zonedDateTime.toString()leaves to the following output:
2020-09-27T08:42:33.660+02:00[Europe/Berlin]

But I would like to have an output as specified before in the DateTimeFormatter ("dd-MM-yyyy HH:mm:ss"). I have already formatted the localDateTime into this format and now I just want to get the CEST time. How can I do that? I'd appreciate every comment.

A: Please note that date-time objects from the Java Time API are immutable. Therefore, whenevery you want to modify an existing date-time instance, a new fresh copy is returned, leaving the old one untouched.
Also, a minor optimization: DateTimeFormatter is thread-safe. Thus, there is no need to construct a new instance every time, since the format is constant. You could declare it at the top like this:
private static final DateTimeFormatter FORMATTER;

static {
    FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
}

To print a formatted String, use the following:
LocalDateTime localDateTime = LocalDateTime.now();
ZoneId europeBerlin = ZoneId.of("Europe/Berlin");
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, europeBerlin);

// please note that #format has a return value
// originally, you called 'localDateTime.format(myFormatObj);' while ignoring
// the return value
String formatted = FORMATTER.format(zonedDateTime);

System.out.println(formatted); // e.g. 27-09-2020 11:44:27

Edit 1: Regarding thread-safety
Thread-safety refers to when an object can safely be used by mutliple threads concurrently, without breaking internals of the class. If a class is thread-safe, you can call it from mutliple threads at the same time (therefore you do not need to create a new instance every time, but only one). If a class is not thread-safe, a new instance is needed for each thread.

A:     DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
    ZoneId europeBerlin = ZoneId.of("Europe/Berlin");
    ZonedDateTime zonedDateTime = ZonedDateTime.now(europeBerlin);

    String formattedDateTime = zonedDateTime.format(myFormatObj);
    System.out.println(formattedDateTime);

Output when running in UTC time zone just now:

27-09-2020 20:33:53

We got the Berlin time (not the UTC time).
What went wrong in your code?
Two things:

*

*LocalDateTime.now() gives you the current time in the default time zone of the JVM. It seems that this was not Eurpoe/Berlin (perhaps it was UTC, it could be something else). Then ZonedDateTime.of(localDateTime, europeBerlin) takes that date and time of day and claims that it is Europe/Berlin time zone, which is wrong and the reason why you got an incorrect result. You don't often need the LocalDateTime class and virtually never the no-arg LocalDateTime.now() method.

*To get the time in a specific format you need to format the date and time into a string. The LocalDateTime and the ZonedDateTime objects haven't got any format.

Links

*

*Related questions:

*

*Can't rid of 'T' in LocalDateTime

*String to ZonedDateTime is changing format


text:
Q: What tools can I use to create a simple IVR system prototype I'm now doing a project on the usability of IVR systems, so I need a touch-tone based IVR system prototype/simulator on my laptop/mobile device.I'm going to ask participants to complete some tasks (such as refilling a phone account) through the prototype, and compare different designs (such as different prompts and number of options).
I'm really new to this industry, I know there's some IVR development tools, like Voxeo and Twilio, but I never used them and don't know if they are appropriate tools for creating such a prototype, after all, I don't need a real IVR system.
So any advice?
Thanks in advance.

A: I would first look into Asterisk as you can install it and set up simple IVR type menus for free - although you may need some linux experience.
Alternatively you mentioned Voxeo and Twilio - these are both good options even for a prototype since they offer free licenses for small scale prototypes. Whichever option you use though will have some sort of learning curve.

A: I recently wrote up 3 tutorials for installing and configuring Asterisk on Ubuntu 13.04.
You might be looking for something like this? I am not sure but you can easily install something like virutal box with a free copy of Ubuntu Server and have this setup and working in an hour or so.
Long as you have some experience with command line in any type of linux system this should be easy.
Setting up the IVR is nothing more then a few lines of code with some extensions and if you need custom sound files for your menus you can easily use something like SoX that is built in ubuntu and convert any sound files you do have to GSM. (File extension that IVR's play easily)
Installing Asterisk
(Can't link since I don't have 10 reputation but it is on my site)
A basic Asterisk configuration (Only works locally ex: 192.168.1.0/24 network)
http://draalin.com/basic-asterisk-confi ... in-ubuntu/
A advanced Asterisk configuration (Works globally with a Vo-IP provider setup)
http://draalin.com/advanced-asterisk-co ... in-ubuntu/

A: You mentioned Voxeo which is a great solution for a prototype because you can develop it for free.  The advantage of Voxeo over Twilio is that you can download a version of their Prophecy IVR to your laptop for free and work from there using a VoIP phone. Voxeo provides software based VoIP phone with Prophecy. Twilio is cloud based and will require you to host your application somewhere on the web. Prophecy is extremely easy to install and setup, which is not true for Asterisk.  While you can get some basic IVR functionality out of Asterisk it was meant to be a phone switch.
The other advantage to using Voxeo's product is that they have excellent customer support that is freely available. Their knowledgeable staff will provide you with quick responses even though you have not purchased anything from them.
They also have graphical development environments for developing your application that are freely available, such as Designer and CXP (formerly VoiceObjects). But Prophecy is based on an open web-based standard called VoiceXML. You can develop simple apps using your favorite web development tools. If you are familiar with ASP.NET MVC there is an open source project that makes it easy to develop VoiceXML applications called VoiceModel.
If you are just looking at the usability of the Voice User Interface (VUI) you do not have to develop an IVR application. You can use a technique that VUI designers use called "Wizard of OZ Testing".  In this type of testing you just have a person on the other end of the phone that mimics the IVR by following a written script.  You have a video camera on the caller to see how they respond to certain prompts and get an indication on whether they understand or get frustrated with the VUI design. You will also want to have a recording device on the phone for playback and analysis. This is very simple with voice applications that use speech-recognition but is a little more challenging with DTMF. Have you seen the episode of Seinfeld where Kramer plays the Moviephone guy. You will need to get a device that can translate the DTMF tones to the numbers on the keypad for the person simulating the IVR so they know how to respond.  I have seen a demonstration where someone used a Voxeo Prophecy IVR to bridge a call and listen in for DTMF and spit the results out to a screen.

A: If you can't program yourself your best bet is pry IVRDesigner.com it's for real systems, but you could certainly prototype a IVR on it.
If your actually trying learn the technology behind the systems, then yea go for Asterisk -  it requires a pretty technical level of knowledge so be ready.
Using Voxeo, Twilio, Plivo, Tropo or the like should pry be your last option. They basically make it "easier" for web technologies to work with Asterisk. The only exception to this would be if you are familiar with web technologies and not familiar with the telecom industry.


text:
Q: Date format need to be converted My date format is in m-d-y.  Now i want to convert it in y-m-d format in php
<input class="form-control form-control-inline input-medium default-date-picker"   size="16" type="text" name="from_date" id="from_date" value="" />

PHP
$from_datenew = date('Y-m-d',strtotime($_POST['from_date']));

A: Use the following code:
$originalDate = $_POST['from_date'];
$newDate = date("Y-m-d", strtotime($originalDate));

A: $from_datenew = date_format(
    date_create_from_format('m-d-Y', $_POST['from_date']),
    'Y-m-d'
);


text:
Q: Expand an expression in javascript I have the following expression (string) in javascript:
var my_expr = "(2*(A||B&&C))&&(3*D)";

How do I make to get something like this:
(2*A||2*B&&2*C)&&(3*D)

Thanks for your help.

A: You have to parse the expression into an abstract expression tree. This is not the easiest task but neither is it impossible. Next thing, you'll have to implement some algebraic properties, especially distributive property, which you are showing here. Lastly, you have to express which rules to apply on which sub-tree of the expression.
Once you've done all this for the general case, it will be TRIVIAL to apply it to this and all similar cases you may encounter.
Primer on expression trees in Javascript
EDIT: You have to go through expression trees, there is no shortcut, because it's the only way algebraic properties can be applied correctly for all cases

A: It sounds like you want to eval() the string:
> var str = "4*5";
> eval(str);
20

There's countless resources all over the internet about why eval is a dangerous thing to use. This is particularly true if you're obtaining the string from another source. If there are any alternatives to this, I would recommend using them.


text:
Q: How to Wait for windows process to finish before opening file in java I have a implemented a listener that notifies if we receive a new file in a particular directory. This is implemented by polling and using a TimerTask.
Now the program is so set up that once it receives a new file it calls another java program that opens the file and validates whether it is the correct file. My problem is that since the polling happens a specified number of seconds later there can arise a case in which a file is being copied in that directory and hence is locked by windows.
This throws an IOException since the other java program that tries to open it for validation cannot ("File is being used by another process").
Is there a way I can know when windows has finished copying and then call the second program to do the validations from java?
I will be more than happy to post code snippets if someone needs them in order to help.
Thanks

A: Thanks a lot for all the help, I was having the same problem with WatchEvent.
Unfortunately, as you said, file.canRead() and file.canWrite() both return true, even if the file still locked by Windows. So I discovered that if I try to "rename" it with the same name, I know if Windows is working on it or not. So this is what I did:
    while(!sourceFile.renameTo(sourceFile)) {
        // Cannot read from file, windows still working on it.
        Thread.sleep(10);
    }

A: This one is a bit tricky. It would have been a piece of cake if you could control or at least communicate with the program copying the file but this won't be possible with Windows I guess. I had to deal with a similar problem a while ago with SFU software, I resolved it by looping on trying to open the file for writing until it becomes available.
To avoid high CPU usage while looping, checking the file can be done at an exponential distribution rate.
EDIT A possible solution:
File fileToCopy = File(String pathname);
int sleepTime = 1000; // Sleep 1 second
while(!fileToCopy .canWrite()){
    // Cannot write to file, windows still working on it
    Sleep(sleepTime);
    sleepTime *= 2; // Multiply sleep time by 2 (not really exponential but will do the trick)
    if(sleepTime > 30000){
        // Set a maximum sleep time to ensure we are not sleeping forever :)
        sleepTime = 30000;
    }
}
// Here, we have access to the file, go process it
processFile(fileToCopy);

A: I think you can create the File object and then use canRead or canWrite to know whether file ready to be used by the other java program.
http://docs.oracle.com/javase/6/docs/api/java/io/File.html
Other option is to try to Open file on first program and if it throws the exception then dont call the other java program. But I ll recommend the above 'File option.


text:
Q: How to redirect a URL wildcard using htaccess My site was hacked not too long ago and a lot of URLs were created in the following format:
http://example.com/prematurely.asp?skin=pspfsffdproblems=nq....

is there anyway I can re-direct all these wildcard URLs based on prematurely.asp to a single page? for example:
http://example.com/newpage

.htaccess file is as follows:
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} !^nowcosmetic\.co.uk$ [NC]
RewriteRule ^(.*)$ http://nowcosmetic.co.uk/$1 [R=301,L]
RewriteCond %{REQUEST_URI} ^/questions-and-answers\.html$
RewriteRule .* http://nowcosmetic.co.uk/botox.html [R=301,L]
RewriteRule ^prematurely\.asp /botox? [R=301,L]'

A: You can do this by adding a rewrite rule
RewriteEngine on
RewriteRule ^prematurely/(.*)   /newpage [R=301,L]

A: As mentioned in comments, if these URLs are the result of a hacked site which has now been resolved then you are better off (SEO wise) serving a 404 (or 410 Gone) instead of redirecting.
However, if you still want to redirect...

re-direct all these wildcard URLs based on prematurely.asp to a single page

At the top of your .htaccess file (in your document root):
RewriteEngine on
RewriteRule ^prematurely\.asp /newpage? [R=301,L]

Note that RewriteEngine On should only appear once in your file (at the top).
This simply matches against "prematurely.asp" (ignoring the query string - as per your request). The trailing ? on the RewriteRule substitution strips the original query string from the rewritten URL.


text:
Q: SQL: Order by Tree BUT skip closed subtrees I have the following table. This is a tree structure where the path column shows the full path from the root of the tree to the particular node:
Path    | ParentName | ChildName | includeSubTree
1       | Null       | Root      | true
1.1     | Root       | RC1       | true
1.1.1   | RC1        | RC11      | true
1.2     | Root       | RC2       | false
1.2.1   | RC2        | RC21      | true
1.2.1.1 | RC21       | RC211     | true

My goal is to have a select statement which:

*

*Returns all rows

*Sorted by path

*Ignoring all rows which have a parent with includeSubTree set to false

Taking the above example, Path 1.2 has includeSubtree set to false therefore I want to ignore all of its children regardless of whether they have includeSubtree set to true or false.
My query would therefore return just the following paths:
1
1.1
1.1.1

Essentially what I am looking to do is to temporarily remove whole subtrees.
I have been stuck on this for quite some time now and wondering if anyone can give me some pointers?
I am using SQLite at the moment but happy for answers that would work with another SQL system. So far I have got as far as:
SELECT *
FROM TreeStructure
WHERE includeSubTree = true
ORDER BY Path;

The obvious problem here is that this will include 1.2.1 even though 1.2 has includeSubTree set to false.
I am at the start of this project so happy to change the schema if necessary.

A: Hmmmm . . . You can use a correlated subquery with exists to see if something should be excluded.
select t.*
from tree t
where not exists (select 1
                  from tree t2
                  where t2.includeSubTree = false and
                        t.path like concat(t2.path, '.%')
                 ) and
      t.includeSubTree = true;

Note:  Although concat() is ANSI standard, some databases spell it as +, ||, or even &.


text:
Q: Can a function be used in $(( func arg ? str1 : str2 ))? I'd like to use a statement like this:
var=$(( func arg ? str1 : str2 ))

but bash gives this syntax error message:
syntax error in expression (error token is "arg")

I've played with various forms but I can't figure out how to make it accept a function with argument.  Any ideas?

A: echo $(( $(seq 1) + 1 ))
2

You need to use the same syntax as bash expects elsewhere. As far as the conditional ? iftrue : iffalse syntax, I don't think you can do that in bash. Instead, you can do something like:
echo $(( 1 + $(true && echo 1 || echo 0) ))
2

A: I think the correct answer is that there is no way to use the statement I asked about.  The problem is that this conditional operator can only evaluate to an integer and not a string as I wanted to do.
jm666 answered the question in a comment to Steve's answer so I gave him an up vote.


text:
Q: lightbox recommendation - dont want to resample blowup image I'm looking for a lightbox type extension that can use the original image for the blow up and that also doesn't require a specific ratio or constraint that defaults for all images.
I'm presently using easy lightbox from template master, but my problem with this, is that they require you specify the max size of the popup image.
I'm using 1.7 and it doesn't have to be free.

A: I like Swipebox:
http://brutaldesign.github.io/swipebox/#dynamic
It is fast, clean and perfect on mobile too.
Also there is this extention:
http://www.magentocommerce.com/magento-connect/jquery-lightboxes-fancybox-pirobox-etc.html
..which lets you try different Lightboxes within one extention.

A: You can try colorbox, I have used in some of my projects and it works well.

A: I prefer Shadowbox (shadowbox-js.com). It can handle images, movies, external pages, etc.
You don't have to specify the dimensions of the images in the modal window. Shadowbox will work with Prototype or jQuery.
HTH, Tom


text:
Q: What is the use of Nonatomic, retain, copy? I have searched a lot but get only difference in definitions of non-atomic, retain, copy parameters. I want exact explanation which I am not getting yet.
Please explain it with example :why we are using them and how they work and role of reference counting in them?

A: In nonatomic, no guarantees are made for returning a whole value from the getter/setter, if some setter activity is going on any other thread.
Thus, nonatomic is considerably faster than atomic, and never thread-safe

In retain explicitly state that you want to maintain a reference of the object or you want to be the owner of the object, and you must release it before it will be deallocated. It will increase the reference count by 1.
-(void)setString:(NSString*)newString{

    [newString retain];

    [string release];

    string = newString;

}

The copy is often used with strings, since making a copy of the original object ensures that it is not changed whilst you are using it.
-(void)setString:(NSString*)newString{

      if(string!=newString){

          [string release];

          string = [newString copy];

     }
}

While retain simply increments the retain count of an object, copy creates a new one one with its own retain count.


text:
Q: error lnk2019 and error lnk1120. so many searches and cannot find a valid answer I do not like posting here unless it is a last resort. I enjoy trying to figure it out on my own. but I have been stuck on this for far too long and all of my google searches have ended up being useless. here is my code and the errors i get when debugging.
#include <iostream>
#include <fstream>
using namespace std;

//function prototypes
int getLowest(int[]);
int getHighest(int []);
int getSum(int []);
double getAverage(int);

//global variables
int Lowest, Highest, Sum;
double Average;

//arrays
const int ArraySize = 12;
int numbers[12];

//function main. read numbers from file into array.
//display lowest, highest, sum and average.
int main()
{

int count;
ifstream inputFile;
inputFile.open("numbers.txt");

for (count = 0; count < ArraySize; count++)
    inputFile >> numbers[count];

Lowest = getLowest(numbers);
Highest = getHighest(numbers);
Sum = getSum(numbers);
Average = getAverage(Sum);

inputFile.close();

cout << "the lowest number is " << Lowest << endl;
cout << "the highest number is " << Highest << endl;
cout << "the sum of the numbers is " << Sum << endl;
cout << "the average of the numbers is " << Average << endl;

system("pause");
return 0;

}

int getLowest()

{
int Low = numbers[1];
for (int count = 0; count < 11; count++)
    if (numbers[count] < Low)
    {
        Low = numbers[count];
    }

return Low;
}

int getHighest()

{
int High = numbers[1];
for (int count = 0; count <11; count++)
    if (numbers[count] < High)
    {
        High = numbers[count];
    }
return High;
}

int getSum()
{
int Sum = 0;

for (int count =0; count <11; count++)
    Sum = (Sum + numbers[count]);

return Sum;
}

double getAverage()
{
double Average;
Average = (Sum / 12);

return Average;
}

error when debugging

1>------ Build started: Project: Lab06-01NumberAnalysis,
  Configuration: Debug Win32 ------
1>NumbersAnalysis.obj : error LNK2019: unresolved external symbol
  "double __cdecl getAverage(int)" (?getAverage@@YANH@Z) referenced in
  function _main
1>NumbersAnalysis.obj : error LNK2019: unresolved external symbol "int
  __cdecl getSum(int * const)" (?getSum@@YAHQAH@Z) referenced in function _main
1>NumbersAnalysis.obj : error LNK2019: unresolved external symbol "int
  __cdecl getHighest(int * const)" (?getHighest@@YAHQAH@Z) referenced in function _main
1>NumbersAnalysis.obj : error LNK2019: unresolved external symbol "int
  __cdecl getLowest(int * const)" (?getLowest@@YAHQAH@Z) referenced in function _main
1>K:\School\CPET 107C Introduction to programmingwith
  C++\Labs\Lab06-Ch7\Lab06-01NumberAnalysis\Debug\Lab06-01NumberAnalysis.exe
  : fatal error LNK1120: 4 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

numbers.txt is saved in folder in the same location as the .cpp
any help would be appreciated at this point.
thanks in advance


text:
Q: Deserialize an array acts as deserializeStrict The following throws an error:
String request = '{"Id": "0036D00000H24cKQAR","FirstName": "firstName", "someArray":["obj"]}';
Contact c = (Contact)JSON.deserialize(request, Contact.class);
System.debug(c);

The error:
System.JSONException: No field name specified on column for sobject of type Contact

I'm using deserialize not deserializeStrict so ideally, the array should be ignored right?

A: Yes, you are correct that the array should be ignored [as mentioned in the apex developer guide]:
When deserializing JSON content into an Apex class in any API version, or into an object in API version 35.0 or later, no exception is thrown. When no exception is thrown, this method ignores extraneous attributes and parses the rest of the JSON content.
Infact, this issue was raised as a bug before few years and was fixed in Winter 16 release. Refer here. However, the issue was fixed only for primitive non-array types & empty arrays i.e., if you specified an empty array "someArray":[] or a string attribute  "someArray":"obj" in your JSON, then the deserialize works as mentioned in the developer guide. But doesn't work in the case of array or for deeply nested JSON elements. In your case, you would have to go with JSON.deserializeUntyped and then parse the Map<String, Object> returned.
Could you raise this as a bug with Salesforce?


text:
Q: Android12 -> configuration.setLayoutDirection(new Locale("ar")) not working It works on other android versions but below code doesn't work on android 12 devices. I use "ar" to language parameter.
val configuration: Configuration = resources.configuration
configuration.setLayoutDirection(Locale(language))
resources.updateConfiguration(configuration, resources.displayMetrics)

A: I had the same problem. Maybe a cache to recreate life cycle configuration, I use this:
val intent = activity.intent
activity.finish()
startActivity(intent)

It can take effect.

A: I had the same problem and the add this piece of code and now it works. I don't know if it's the efficient way or not.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        (context as Activity).window.decorView.layoutDirection =
            if (Locale.getDefault().language.equals("fa"))
                  View.LAYOUT_DIRECTION_RTL else View.LAYOUT_DIRECTION_LTR
}


text:
Q: Laravel how to get only relation data this is my User.php relation code
    public function activities()
    {
        return $this->hasMany(Activities::class, 'builder');
    }

and this is my query to get only relation data
return User::whereHas('activities', fn($query) => $query->where('user_id', 1))
            ->paginate();

but it returns only user data without appling any relation, and its pagination not get to use pluck
i have also tried this
User::where('username', request()->username)->has('activities')->paginate();

but i need only get relation data not user with relation, and i prefer do it with whereHas

A: You need to create reverse relation for Activities model:
class Activities extends Model
{
    // ...
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

And get all the activities using Activities builder:
$paginated = Acitivities::query()
    ->whereHas('user', static function(Builder $userQuery) {
        $userQuery->where('name', request()->username); // Think about security!
    })
    ->paginate();

Note: All the models must be named in singular (e.g. Activity, User, Product and etc.).


text:
Q: No user name/password required when exploring from live USB? A few months back when I buggered up my netbook and then booted into it to get information from it using a live USB. (Thinking that was 10.10)
When I was copy/pasting this to another USB at no time was I required to enter my user name or password to access this information. Why and how was that possible? Shouldn't that not be possible? This was information from the 'home' including documents, pictures, music, videos and some other locations.
This does not sound secure at all, is there any way that I can ensure this cannot happen again and that user name and password would be required to access information on my installed Ubuntu computer when booting on that computer from a live USB/CD/DVD?

A: This is possible because your files are on the hard disk, so anyone with full control over whatever operating system is running on the computer has full control (including full access) to your files. This is the case when running Ubuntu or another OS from a live system (live CD/DVD or live USB), and this is also the case if someone were to take the hard drive out of your computer and put it in their computer.
You can get a reasonable degree of protection from this by encrypting your home folder, making sure to only store your files in your home folder (of course back them up somewhere else besides this computer, though...and make sure the backup is secure), and using a very strong password. The password is stored, encrypted, on the hard disk, so if it's weak, the encryption can be cracked pretty easily. See this comic for a relatively accessible explanation of some of the issues relevant to password choice.
Encrypting your home folder is an option during installation, but you can also enable it on an already-installed system by following the instructions in this guide. It is recommended to encrypt your swap partition too, which that guide also explains.
The reason most users do not encrypt their home folders (besides not knowing that it is an option or not being extremely concerned about the privacy of their data) is that, often, the person trying to access your files without your password is you. This also complicates (but does not usually prevent) recovering data from the disk, even if it is mostly intact and you remember the password.
If you want to increase your protection, make sure the password you use for your Ubuntu system is not the same as or even similar to the password you use for anything else, such as any websites.

A:
No user name/password required when exploring from live USB
Why and how was that possible? Shouldn't that not be possible?

Well, you are using the OS (Ubuntu) from the live USB not OS from your installation

This does not sound secure at all, is there any way that I can ensure this cannot happen again and that user name and password would be required to access information on my installed Ubuntu computer when booting on that computer from a live USB

You could encrypt you data:
https://help.ubuntu.com/community/EncryptedFilesystems
https://wiki.archlinux.org/index.php/System_Encryption_with_LUKS

Why Use Encryption?

In the simplest terms encryption is a method for establishing privacy.


text:
Q: Select elements using Javascript So i have started some javascript and i wanted to ask that is there a way to select elements in an array. I read the querySelector, querySelectorAll and getElementsByClassName but these select the entire array but not the elements in it. Because i want to add event listener to elements so that delete button removes the list item.
If my code is like this:-

Simple Add/Remove Task

To do List

Wake up

Study

        <button>Delete</button>

        <button>Delete</button>

A: Well... What do you want to select here? In HTML, there is no such thing as an Array.
Suppose you want to add an event listener to your first button. As there is really no single feature distinguishing the two Delete buttons, you want to add some sort of identifier to them. For example:
<button id="btn-1">Delete</button>

<button id="btn-2">Delete</button>

You are then able to select the first button like this:
button1 = document.getElementById("btn-1");

...or, with more modern JavaScript (but less browser compatible):
button1 = document.querySelector("#btn-1");


text:
Q: Android: Why isn't my ArrayAdapter getting populated? For my program in Android I want to use simple ArrayAdapter, without overriding the ArraYAdapter class. The problem is that the adapter is not being showed on the activity.
    ArrayList<String> myList = generateListAndTaskText(intent);
    final ListView myListView =  (ListView) findViewById(R.id.widget_show_task_act_subtasks_listview);
    Log.d("ShowTaskAct", myList.size() + "");   //Log shows 2 items
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
                R.layout.main_child_item_lay,R.id.main_child_item_text, myList);
    myListView.setAdapter(adapter);

Am I missing something here?
EDIT: The layout (simplified):
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent">

<TextView
    android:id="@+id/widget_show_task_act_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="8dp"
    android:text="Loading..."
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginStart="8dp" />

<ListView
    android:id="@+id/widget_show_task_act_subtasks_listview"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    android:layout_marginTop="0dp"
    app:layout_constraintTop_toBottomOf="@+id/widget_show_task_act_text" />

EDIT2:
I forgot to tell you guys that the Activity is started from a screen widget. Thus should I use getApplicationContext() or getBaseContext() ?

A: You are missing the bottom constraint for the Listview, and the height is 0.
For the ListView, contraint the bottom to the bottom of parent or some other widget that is already constrained.

A: try like below:
ArrayAdapter<String> adapter = new ArrayAdapter<String> (getBaseContext(),
                android.R.layout.simple_dropdown_item_1line, myList);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
myListView.setAdapter(adapter);

A: Problem solved: static height for the listview does the job.


text:
Q: Exception in thread "main" java.lang.NullPointerException 7
(main method calling classes)
import java.io.*;

public class bob {
public static void main(String[] args){
    new bert();
  new larry();

(creates a file and copys string to it)
public class larry{
  bert bertObj = new bert();
  public larry(){
      try{
      File file = new File("text.txt");

      if(!file.exists())
          file.createNewFile();
      PrintWriter pw = new PrintWriter(file);
      for(String x: bertObj.string){
      pw.println(x);
      }
      pw.close();
  }catch(IOException e){
      e.printStackTrace();
  }
  }
}

(reads a file and copies it into a string array)
     (i havent initialised the string, i think that maybe the error, though i dont know how many values i will be storing inside it so i do not wish to do            String string[] = new String[100] for example.... what else can i do?)
public class bert {
  String string[];
  public bert(){
      BufferedReader br = null;
      try{
          br = new BufferedReader(new FileReader("C:\\Program Files\\Java\\jdk1.8.0_101\\THIRDPARTYLICENSEREADME.txt"));
          int counter = 0;
          while((string[counter] = br.readLine()) != null)
          {
              counter++;
          }
          for(int x = counter; x < 4000; x++)
              string[x] = "";
      }catch(IOException e){
          e.printStackTrace();
      }finally{
          try {
              br.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  }
}

A: In class bert, your String[] is never initialized before you try to access it in this line:
while((string[counter] = br.readLine()) != null)

Just like you initialized bert in the larry class, you need to initialize the String[] in the bert class.
Turn this line:
String [] string;

Into:
String[] string = new String[5];  // 5 is an arbitrary number I chose, you need to choose how many strings you will be holding in that array

Sorry, did not fully read your comments.  Instead of a static array, try using an arraylist.  This does not work the same as an array.
To give you a short example:
ArrayList<String> string = new ArrayList();
string.add("hello");     // string now has a string "hello"
string.add("world");     // string now has a string "hello" followed by a string "world"

for(int i = 0; i < string.size(); i++) {
    System.out.println(string.get(i));  // gets position i from the array and prints it.  Will print hello then a new line then world.
}

More on the arraylist here:
ArrayList API


text:
Q: Handling errors in lexical analysis I'm writing a lexical analyzer and I would like it to output meaningful and accurate error messages. Like the exact line and column where errors occurred. What's the appropriate way of handling errors when writing a lexical analyzer?

A: What tools are you using for lexical analysis? I know a little Flex, I'll just write it down what I know, maybe its helpful for you or someone else.
Flex is a tool used commonly for generating lexical analyzers. Instead of writing one from scratch, you only need to tell it how your tokens are (using regular expressions), and it will generate a C program which gives a stream of tokens from the input character stream.
Its easy to learn, here's a good tutorial. After learning it, you will be able to report errors easily.
Regarding line numbers, Flex defines a variable called yylineno which holds the current line number. For column numbers, this might help.


text:
Q: Amazon S3 download link for public file I have public file that was uploaded to Amazon S3 through ruby gem 'aws-sdk-s3' and presigned_post, acl is set to 'public-read'.
Now I want to use simple html download link so file can be downloaded to user computer: Save
Real sample file link for example: https://150yearssampleapp.s3.ap-northeast-2.amazonaws.com/2011-08-26+17.37.38.jpg
But when I click the link file is opened in new tab only. Tried Chrome ver. 97 and Safari ver. 15 browsers.
Read many topics but they all related to private files. It looks like public file should be easy to download. What am I doing wrong?
I can download file through server - so it get downloaded to server first and then sent to user browser but since file is public I want save time and let user download file directly from Amazon S3.
UPDATE 25.01.2022
So what I try to achieve - be able use one file for show and for download.


text:
Q: VS2017 Angular template - webapi listens on one port, angular client on another I just upgraded VS2017 to the latest, 15.8.6, today.  If I go in and create a .NET Core 2.1 project (from within the IDE, not command line), and select the Angular template, and run it without making any other changes, the app doesn't work.
What I've found is that the WebApi portion of the project is listening on port 54401:

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:54401/

while the Angular client is listening on port 54420:

ng serve --extract-css "--port" "54420"** NG Live Development Server is listening on localhost:54420, open your browser on http://localhost:54420/ **

In previous versions of VS2017, both the client and server were listening on the same port, or, at least, I didn't have to do anything special to get the application to work.
Is this new behavior normal? What do I need to do to get it to work?
Thanks


text:
Q: UI problem in LandscapeLeft mode in iPad I've create an iPad application in LandscapeLeft mode and i've set my UI according to LandscapeLeft mode. But when i run my application it is showing UI in portrait mode. I can't figure out the problem.
Please reply.....
Thanks in advance.....

A: Any application always launch in portrait mode.To launch in only landscape mode go to info.plist file and change supported orientation array accordingly
Or
In you view controller's shouldAutorotate method add following code
 if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
    return YES;
 }

 return NO;

A: Write the below code in your application delegate file.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight)
}


text:
Q: For.. in loop - why does it work? I am reading the book "JavaScript for web designers" and I've come to this example:
var fullName = {
  "first": "John",
  "last": "Smith"
};
for (var name in fullName) {
  console.log(name + ": " + fullName[name]);
}

The output is:
"first: John"
"last: Smith"

What I don't get is: where do I tell the program to get the string "first" and "last". I mean, cycling the object "fullName", I fail to see how "name" can be related to "first" and "last". I hope this is clear.
 Can you help? Many thanks!

A: It's pretty simple to learn and/or understand. You're looping through all of the properties in the object fullName. For each property, you're giving it the temporary name/alias of name
So you could change it to for (var anything in fullName) and then in the body of the for loop you would reference each property by the name anything like so:
for (var anything in fullName) {

    // anything is an alias for the current property your on of the object you're looping through
    console.log(anything + ": " + fullName[anything]);

}

A: A for..in loop will iterate through the object's keys. If you use this on an array, then it (most browser engines) will convert the array into an object behind the scenes (read more on Dictionary Mode) and iterate the keys.
You can view the keys by using

var fullName = {
  "first": "John",
  "last": "Smith"
};
console.log(Object.keys(fullName));

And essentially the result of this call is then iterated. Keep in mind that using for..in does not guarantee order of the key value pairs.

A: in the above code name represent key of the object,
first and last are both keys in the object. and can be used to access the value in the object.
like in the first run of the loop it will be something like this
for("first" in fullName) {
 console.log("first" + ": " + fullName["first"] //John);
}

A: When you loop through an object, you iterate through the keys. The keys of this object are first and last. Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in for more information.

A: for..in iterates over the keys of an object. You can then access an objects values by name using brackets.

var obj = {
  a: 1,
  b: 2,
  c: 3
};

for (var key in obj) {
  console.log('Key:', key);
  console.log('obj[key] == obj["' + key + '"] == obj.' + key);
  console.log('obj.' + key + ' == ' + obj[key]);
}


text:
Q: StaticInjectorError when using ngx-color-picker inside of MatDialog I have a color-picker component that uses ngx-color-picker directive. The component is in entryComponents of a module and is being used by MatDialog like this.
openDialog() {
    this.dialog.open(EntryComponent, {
      width: '600px',
      autoFocus: false
     },
    );
  }

When I try to utilize some functionality of the ngx-color-picker inside of the color-picker component it throws StaticInjectorError.
When I use the component without the dialog, just in a simple component that isn't in entryComponent of a module - everything is okay.
To reproduce the issue please check this Stackblitz project https://stackblitz.com/edit/angular-jxkwq2

*

*Press the Open dialog button

*Click on the black rectangle

*Check the console

Why could it happen and how do I fix it?

A: Provide MatDialog in AppComponent
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  providers : [MatDialog]
})

Forked Demo


text:
Q: How can we access an object type(not table of objects) in Oracle TABLE function? How can we access an object type(not table of objects) in TABLE function ?
The table function works on a collection of objects, but I have a need to access a single row using TABLE function.
I get the error "ORA-22905: cannot access rows from a non-nested table item" when I try to use TABLE function with an object type instead of collection of object types.
The workaround that I use is to create a table type collection on this object and place the row in the first index, and then use the table type in the function. Any other simple solutions ?
I need to query the object as if it is a row in a table.This is to have a common code base in my application to support two different use cases.
With a common code base, I can use the same SELECT query to query the records either from an actual table or from a single-row object using TABLE function. Only the FROM clause of the Dynamic SQL changes.
CASE 1:
Querying a physical table

v_select := 'SELECT a,b,c,d '
v_from   := '  FROM ' || v_actual_table
v_where  := '<where_predicate>

EXECUTE IMMEDIATE v_select || v_from  || v_where;

CASE 2:
Querying a row object using TABLE function. The row object is coming from Oracle AQ channel in the form of messages.

v_select := 'SELECT a,b,c,d '
v_from   := '  FROM TABLE(:1)'
v_where  := '<where_predicate>

EXECUTE IMMEDIATE v_select || v_from  || v_where USING v_table_type;

Hope this clarifies.


text:
Q: Restriction of $\mathcal{T}_{X / R}$ to the special fiber Let $f : X \to \operatorname{Spec}(R)$ be a flat and projective morphism of schemes over $\mathbb{C}$, where $R$ is a DVR. Assume additionally that the fibers of $f$ are Gorenstein and seminormal (in particular reduced). Let $i : X_0 \to X$ denote the closed immersion of the special fiber.
Is it then the case that the morphism of tangent sheaves $i^*\mathcal{T}_{X / R} \to \mathcal{T}_{X_0 / \mathbb{C}}$ is an isomorphism?