text:
Q: How does ARC determine whether to use retain or copy? As LLVM compiler with ARC option add retain, copy,release and autorelease for us automatically, but how does ARC determine whether to use retain or copy?
Thanks in advance:)

A: ARC doesn't add copy, that's still your responsibility if you need copies. It only manages retain and release for you. If you manually copy something though it knows that you get a new object that it will have to release at some time.

A: As mentioned in following docs (http://clang.llvm.org/docs/AutomaticReferenceCounting.html#meta)

Automatic Reference Counting implements automatic memory management
  for Objective-C objects and blocks, freeing the programmer from the
  need to explicitly insert retains and releases. It does not provide a
  cycle collector; users must explicitly manage the lifetime of their
  objects, breaking cycles manually or with weak or unsafe references.

Also you can go through the discussion of this thread - How does the new automatic reference counting mechanism work?


text:
Q: Постепенная подгрузка изображений в слайдере Добрый день.
Хочу реализовать простой слайдер картинок на Jquery но так, чтобы при инициализации загружались только первые 2 изображения. Третье должно загружаться в том случае, если человек перешёл на второе. И так далее - загрузка следующего только при условии просмотра предыдущего.
Прошу направить меня на путь истинный, можно без готовой реализации (хотя и не откажусь от таковой).
A: Когда показываете N-ое изображение - загружайте N+1 таким способом:
 nextImg= new Image();
 nextImg.src= '%имя файла N+1%';

а дальше зависит от вашего слайдера, либо создаете новый '<img />', либо меняете атрибут на старом:

$('#imgid').attr('src', nextImg.src);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jackson, how to transform json to Java class using raw type? I am developing a library to be able to query a public api in a more fluent way for a personal project. And I have some difficulty with Jackson to transform the API answers into my java objects.
There is my problem :
I call this API using jdk 11 HttpClient and using a BodyHandlers.ofString(). So far, nothing very complicated. But the format of the answer gives me difficulties when I want to transform the json into a java object.
Here is an answer in Json :
{
    "data": {
        "iso": "2021-02-04T20:35:21Z",
        "epoch": 1612470921
    }
}

But the "data" type can also be in other answers with different fields. For example :
{
    "data": {
        "base": "BTC",
        "currency": "USD",
        "amount": "37721.43"
    }
}

So I decided to create a generic data type like this :
public class DataDto<T> {

  T data;

  @JsonCreator
  public DataDto(@JsonProperty(value = "data") T data) {
    this.data = data;
  }
}

So, Let's take the example of the first answer.
I have an other object called Time :
public class TimeDto {

  private LocalDateTime iso;
  private long epoch;

  @JsonCreator
  public TimeDto(
      @JsonProperty(value = "iso") LocalDateTime iso, @JsonProperty(value = "epoch") long epoch){
    this.iso = iso;
    this.epoch = epoch;
  }
}

And there is my function where I want to transform the answer into my java object :
public static Time getTime(final MyClient client) {
    var request =
        HttpRequest.newBuilder()
            .GET()
            .uri(
                URI.create(
                    client.getProperties().getApiUrl() + client.getProperties().getTimePath()))
            .header(ACCEPT, ACCEPT_VALUE)
            .build();

    try {
      var response = client.getClient().send(request, HttpResponse.BodyHandlers.ofString());

      var dataDtoType = client.getObjectMapper().getTypeFactory().constructType(DataDto.class);

      var timeDtoType =
          client
              .getObjectMapper()
              .getTypeFactory()
              .constructParametricType(TimeDto.class, dataDtoType);

      var toto = client.getJsonDeserializer().readValue(response.body(), timeDtoType);
      return null;
    } catch (Exception e) {
      log.error("An error occured while getting time", e);
      throw new MyException("An error occured while getting time", e);
    }
  }

As you can see, I tried to create a specific Jackson JavaType to be able to transform data in a generic way... But in my case, when I test this code, this exception appends :
java.lang.IllegalArgumentException: Cannot create TypeBindings for class com.github.badpop.mylib.client.dto.TimeDto with 1 type parameter: class expects 0
    at com.fasterxml.jackson.databind.type.TypeBindings.create(TypeBindings.java:126)
    at com.fasterxml.jackson.databind.type.TypeBindings.create(TypeBindings.java:96)
    at com.fasterxml.jackson.databind.type.TypeFactory.constructParametricType(TypeFactory.java:1109)
    at com.github.badpop.mylib.client.PublicResourcesService.getTime(PublicResourcesService.java:42)
    at com.github.badpop.mylib.client.MyClient.getTime(MyClient.java:70)
    at com.github.badpop.mylib.Main.main(Main.java:20)

If you have an idea that could help me solve my problem, thank you in advance!

A: The easiest is to use a TypeReference, e.g.
String json = "{\r\n" +
              "    \"data\": {\r\n" +
              "        \"iso\": \"2021-02-04T20:35:21Z\",\r\n" +
              "        \"epoch\": 1612470921\r\n" +
              "    }\r\n" +
              "}";
ObjectMapper mapper = new ObjectMapper()
        .registerModule(new JavaTimeModule());

DataDto<TimeDto> data = mapper.readValue(json, new TypeReference<DataDto<TimeDto>>() {});

System.out.println("iso: " + data.getData().getIso());
System.out.println("epoch: " + data.getData().getEpoch());

You can even "skip" the DataDto part:
TimeDto time = mapper.readValue(json, new TypeReference<DataDto<TimeDto>>() {}).getData();

System.out.println("iso: " + time.getIso());
System.out.println("epoch: " + time.getEpoch());

Output
iso: 2021-02-04T20:35:21Z
epoch: 1612470921

DTOs
class DataDto<T> {
    private final T data;

    @JsonCreator
    public DataDto(@JsonProperty(value = "data") T data) {
        this.data = data;
    }

    public T getData() {
        return this.data;
    }
}

class TimeDto {
    private final Instant iso;
    private final long epoch;

    @JsonCreator
    public TimeDto(@JsonProperty(value = "iso") Instant iso,
                   @JsonProperty(value = "epoch") long epoch){
        this.iso = iso;
        this.epoch = epoch;
    }

    public Instant getIso() {
        return this.iso;
    }

    public long getEpoch() {
        return this.epoch;
    }
}


text:
Q: VSS's 'Projects Sharing File' option in Git I am working on the VSS to Azure DevOps Git migration.
In VSS, I noticed there is an option (right click on the file --> Properties --> Links) which shows the list of other projects using the same file (not reference, but same file copied in all other projects folders).
In the below example, frmOrderList.frm exists in Logistics, Order Administrator and Planning project folders.

With this option, when developer makes any changes to the frmOrderList.frm in Logistics application, similar changes will be done in other 2 project files.
May I know, is there a similar feature available in Azure DevOps GIT Repo ?
Note:- I know, this is not at all a good option to have a same file in multiple folders (instead - common files can be maintained in the centralized folder and all other solutions can refer from there). Due to time constraints, I am looking for the similar feature in GIT.
Appreciate your response, thank you


text:
Q: How to change default indentation for JavaScript Babel and JavaScript React in VS Code? Writing the following piece of code in settings.json file in VS Code, I was able to override the default 4-space indentation for JavaScript:
"[javascript]": {
    "editor.tabSize": 2
},

For some reason, this does not apply to JavaScript React and JavaScript Babel in VS Code. How can I change their default indentation in VS Code?

A: press ctrl+, to open editor settings then in search input write 'indentation'.
It offers you related settings:


text:
Q: RPY2 RuntimeError: "No environment variable R_HOME could be found, calling the command 'R RHOME' does not return anything..." I am running Python 2.7 on Windows 7. First, I installed R and RTools, and changed the following environment variables:
RHOME: C:\Program Files\R\R-2.15.2
R_HOME: C:\Program Files\R\R-2.15.2
R_USER: C:\Users\username\Documents

And appended the following directories to PATH:
C:\Program Files\R\R-2.15.\bin\i386; C:\Rtools\bin

Next, I installed RPy2 through a binary executable here.
When running RPY2 through Python I get the following error:
Traceback (most recent call last):
  File "<string>", line 254, in run_nodebug
  File "C:\Python27\blaise automation.py", line 14, in <module>
    import rpy2.robjects as robjects
  File "C:\Python27\lib\site-packages\rpy2\robjects\__init__.py", line 14, in <module>
    import rpy2.rinterface as rinterface
  File "C:\Python27\lib\site-packages\rpy2\rinterface\__init__.py", line 28, in <module>
    "or install the win32 package.")
RuntimeError: No environment variable R_HOME could be found, calling the command 'R RHOME' does not return anything, and unable to import win32api or win32con, both of which being needed to retrieve where is R from the registry. You should either specify R_HOME or install the win32 package.

I've been working on this for HOURS.  Does anybody have any idea how to resolve it?
My code:
import rpy2.robjects as robjects
import pywin

def main():
     robjects.r("require(foreign)")


text:
Q: ¿Como obtener el valor de un select por medio de su clase? Actualmente quisiera saber como puedo tomar el valor de un selecta ya sea numerico o cadena a travez de su clase, ya lo eh conseguido pero es por medio de su id, no tienen nada de malo con cualquiera es posible realizar la operacion, solo que primordialmente lo quise hacer con su clase y el valor lo puse una alerta, pero me salia en blanco la sintaxis que utilizaba era la siguiente:
alert($(".textLBL").val());

Quisiera saber si para aquirir el valor de un select mediante su clase es de forma diferente a la que se usa por medio de su id. la sintaxis que use con el id es la siguiente.
 alert($("#chkDireccion1").val());

tambien verifique si era un error de dedo al escribir la clase, pero todo estaba correcto. alguien sabe a que se pueda deber.
Lo que quiero es el value no su cadena de texto.

A: En jQuery no debería haber ningún problema a la hora de leer el valor usando como selector la clase o el ID. El problema lo puedes encontrar si tienes varios select con la misma clase.

*

*Cuando seleccionas por ID, ese ID es único (o debería serlo) y te devolverá el valor de ese select en particular.

*Cuando seleccionas por clase, esa clase puede no ser única, en cuyo caso se devolverá una lista con todos los elementos que tengan esa clase; Entonces al hacer el val() sólo te devuelve el valor del primero (que seguramente no está seleccionado y por eso sólo ves una cadena vacía en el alert) lo cual puede llevar a confusiones si lo que querías leer es el valor del segundo/tercero/etc.

A: El problema no tiene que ver con como seleccionas el select, y es más sobre que estas seleccionando realmente. Como algunos mencionan los ID deberían ser únicos, y por lo mismo es lo más adecuado usarlos. Mas si la clase que tienes asignada a tu select también es única no tiene ningún problema que selecciones el elemento por medio de esta.
El problema viene cuando varios elementos tienen la misma clase (ya que estas estas como lo dice su nombre designan una clase/tipo y es correcto usarlas más de una vez en un mismo documento), y cuando los selecciones con jQuery tendrás tantos elementos como elementos tengan asignada la clase por la que estas seleccionando. Y si llamas al método .val() este te retornara el valor del primero de los elementos seleccionados, que no necesariamente puede ser el que tu deseas.
Como solución se me ocurren dos cosas:

*

*Lo más recomendado es que lo selecciones por su ID.

*Si necesitas hacerlo por su clase, y varios select tienen esa clase, puedes acceder a uno concreto anexando el selector :eq(indice), donde indice es la posición del elemento que te interesa, y el primero tiene el indice 0.

Por ejemplo:

var $el = $('.i-am-select:eq(2)');
alert($el.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select class="i-am-select">
    <option>one</option>
</select>

<select class="i-am-select">
    <option>two</option>
</select>

<select class="i-am-select">
    <option>three</option>
</select>

Si cambias el indice en el selector :eq() veras como cambia el select seleccionado.
Suerte y Saludos!

A: Quiero dejarte un ejemplo como te puede ser útil usando el $(this)1 selector, cuando tienes varios select con la misma clase (aunque tampoco es necesario que tengan una clase asignada) y quieras sacar el valor (value) de cada uno:

$(function(){

  $('.select').on('change', function() {

    console.log( $(this).prop('value') );
  });
});
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<select class="select">
  <option value="01">Selecciona</option>
  <option value="01_valor">select 1</option>
</select>
<select class="select">
  <option value="02">Selecciona</option>
  <option value="02_valor">select 2</option>
</select>
<select class="select">
  <option value="03">Selecciona</option>
  <option value="03_valor">select 3</option>
</select>

1$(this) - Se refiere o representa el objeto seleccionado actualmente en un bucle o evento.


text:
Q: sort rss news by date with angular js I am referring a stack overflow answer in JavaScript but I unable to work on it in angular js.
The javascript answer to sort the rss feeds according to the date(latest on top) is as below
data.query.results.rss.sort(function(item1, item2) {
    var d1 = new Date(item1.channel.item.pubDate)
    var d2 = new Date(item2.channel.item.pubDate)
    return d2.getTime() - d1.getTime()
})

My angular js (ionic framework) is as below:
            $webServicesFactory.get(
                  "https://www.google.com/finance/company_news",
                  {},
                  {
                    output: "rss",
                    q:  stock.e +":"+ stock.t
                  }
                ).then(
                  function success(xmlData) {
                    var x2js = new X2JS();

                    $globalFactory.personalStockNews = x2js.xml_str2json(xmlData).rss.channel.item;

   $globalFactory.personalStockNews.sort(function(item1, item2) {
       var d1 = new Date(item1.channel.item.pubDate);
       var d2 = new Date(item2.channel.item.pubDate);
       return d2.getTime() - d1.getTime();
})
                    console.info($globalFactory.personalStockNews);
                    $ionicLoading.hide();
                    $state.go("app.home");
                  },
                  function error(error) {
                    $globalFactory.personalStockNews = null;

                    $ionicLoading.hide();
                    $state.go("app.home");
                  }
                );

              },
              function error(error) {
                $ionicLoading.hide();
              }
            );

However, it did not sort as expected.
How shall I modified the javascript to angular js?
You can use the rss feeds below
'https://www.google.com/finance/company_news?q=SGX:533&ei=EeiDWaGGMpXUuATxloPgAw&output=rss' to sort the rss base on date.
In html, the code is as below:

{{item.title}}

{{item.pubDate}}

    <p {{story.description | htmlToPlaintext}}

A: I think your sort function should look something like:
function(item1, item2) {
    var d1 = new Date(item1.channel.item.pubDate)
    var d2 = new Date(item2.channel.item.pubDate)

    if (d1>d2) return -1
    if (d2>d1) return 1
    return 0
}

Of course it would help if you stated what the desired outcome is in the question. :)
Also remove the orderby on your ng-repeat. That's overriding the array sorting you're doing in the controller.


text:
Q: how to find the coordinates of a searched string using regex in the file? Actually my aim is to find a string in a file in python, I used regex to find it, I found it also but don't know how to calculate the coordinates of the position of that string in the file? I have no idea about it how to progress further

A: You can use result.start() and result.end() to find out coordinates of regex match:
import re  # regex module

content = open('file.txt', 'r').read()  # read file
regex = r'regular expression here'

result = re.match(regex, content)  # find match

print(result.start(), result.end())  # print coordinates

Also, you can use result.span() to get tuple of start and end of match (thanks @JennevanderMeer for complement)


text:
Q: IntelliJ IDEA does not expand environment variables in Program arguments in Run Configuration
Same in Using environment variables in "VM options" and "Program arguments", the environment variables cannot be used in Program arguments in the Run configuration. If I put $VARIABLE in the Program arguments (VARIABLE is configured in Environment variables in the Run configurations.
None works.

*

*$VARIABLE

*${VARIABLE}

*$VARAIBLE$

Is this a bug?
Environment
$ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.2 LTS (Bionic Beaver)"
ID=ubuntu

A: It's a bug affecting user environment variables defined in the same configuration, it works for the system environment variables.


text:
Q: Combine 2 columns in a new table and remove duplicates Hi I would like to combine 2 columns from a table and create a list of unique values in a new table.
example:
dataset = DT
Source    Destination
A          B
A          C
B          C

New table (DT_New)
Unique names
A
B
C

I already tried to use the following code:
DT_New <- unlist(DT)
DT_New<- data.table(DT_New)
DT_New = DT_New[!duplicated(DT_New), ]

When I use this code it returns the folowing result:
New table (DT_New)
Unique names
A
B
B
C

It seems that the code above can distinct the "B" from the column Source and the column destination. How can I avoid this issue and get the table with unique values?
Unique names
A
B
C

A: Just unlist and select unique values
data.table::data.table(unique_col = unique(unlist(DT)))

#   unique_col
#1:          A
#2:          B
#3:          C

OR with your duplicated approach it would be
DT_New <- unlist(DT)
data.table(unique_col = DT_New[!duplicated(DT_New)])

A: For larger datasets, union is a good route.
data.table(unique_col = union(DT[['Source']], DT[['Destination']]))

#   unique_col
#1:          A
#2:          B
#3:          C

identical(data.table(unique_col = union(DT[['Source']], DT[['Destination']]))
          , data.table(unique_col = unique(unlist(DT))))
#[1] TRUE

Here's an example with a million records in each column:
set.seed(1)
DT <- data.table(Source = sample(1:1E6, 1E6, replace = T)
                 , Destination = sample(1:1E6 + 500000, 1E6, replace = T))

Unit: milliseconds
      expr       min        lq      mean    median        uq       max neval
  dt_union  173.2102  179.4019  281.2719  222.8879  395.7681  535.6448    20
 dt_unique 1271.1621 1487.0988 1581.3864 1582.5068 1682.7661 1842.5898    20

A: You could use a graph to store the data (with the igraph package) and then these names will be associated with each node/vertex:
library(igraph)
g = with(DT, graph_from_edgelist(cbind(Source, Destination)))
names(V(g))
# [1] "A" "B" "C"

You can see that the Source->Destination links are retained in the edges:
E(g)
# + 3/3 edges from 440136f (vertex names):
# [1] A->B A->C B->C

A: thanks for all your input. All your answers were correct, but not solving my particular problem. Therefore, I realized the problem should be in the data prep code ... Apparently, there was a whitespace at the end of each value of the source column, which doesn't show in the table view of Rstudio. Silly mistake ...
Thanks to Franks answer I saw the whitespace.


text:
Q: _utf8 POST parameter on gmail login contains a snowman character
Possible Duplicate:
What is the _snowman param in Ruby on Rails 3 forms for?

If you inspect the POST parameters of Gmail login with Firebug or Chrome developer tools, you'll see a _utf8 parameter with a value of ☃:
_utf8:☃

(See the attached image in case your browser doesn't render the value. It's a snowman, U+2603, http://www.utf8-character.info/#!%E2%98%83.)
Why do they do this? Is it possible that they somehow test for browser compatibility to UTF-8?

A: The _utf8 header along with a Unicode character is to ensure that

*

*At least one Unicode character is submitted to the server

*Force certain non-compliant browsers to respect the form's character encoding

In some cases, the _utf8 header is given a value of a ☃ and sometimes it is a ✓. What it is doesn't really matter and may have arbitrarily been chosen for fun.


text:
Q: Query optimalization - how create proper composite index I have mysql 5.5 and table item have around 1-3 milions rows.
CREATE TABLE `item` (
  `Id_item` int(11) NOT NULL DEFAULT '0',
  `item_Kod` varchar(15) DEFAULT NULL,
  `Date1` datetime DEFAULT NULL,
  `Date2` datetime DEFAULT NULL,
  `Date3` datetime DEFAULT NULL,
  `Person1` int(11) DEFAULT NULL,
  `Person2` int(11) DEFAULT NULL,
  `Person3` int(11) DEFAULT NULL,
  `Deleted` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`Id_item`),
  UNIQUE KEY `Index_item_Kod` (`item_Kod`),
  KEY `Index_Date1` (`Date1`),
  KEY `FK_item_Person2` (`Person2`),
  KEY `Person1` (`Person1`),
  KEY `FK_item_Person3` (`Person3`),
  CONSTRAINT `FK_item_Person2` FOREIGN KEY (`Person2`) REFERENCES `persons` (`Id_Person`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `FK_item_Person1` FOREIGN KEY (`Person1`) REFERENCES `persons` (`Id_Person`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=cp1250;

CREATE TABLE `persons` (
  `Id_Person` int(11) NOT NULL DEFAULT '0',
  `Code` int(11) DEFAULT '0',
  `Title` varchar(50) NOT NULL DEFAULT '',
  PRIMARY KEY (`Id_Person`)
) ENGINE=InnoDB DEFAULT CHARSET=cp1250;

and I want optmalize this query...result is about 100-500 rows and query run about 3-4seconds
SELECT
  *
FROM
  `item` AS `item`
WHERE
  (
    `item`.`Deleted` = 0
    AND (
      (
        `item`.`Date1` >= '2020-01-20 00:00:00'
        AND `item`.`Date1` <= '2021-01-29 23:59:59'
      )
      OR (
        `item`.`Date3` >= '2020-01-20 00:00:00'
        AND `item`.`Date3` <= '2021-01-29 23:59:59'
      )
      OR (
        `item`.`Date2` >= '2020-01-20 00:00:00'
        AND `item`.`Date2` <= '2021-01-29 23:59:59'
      )
    )
    AND (
      `item`.`Person1` IN (15, 167, 192, 198, 398, 662)
      OR `item`.`Person2` IN (15, 167, 192, 198, 398, 662)
      OR `item`.`Person3` IN (15, 167, 192, 198, 398, 662)
      OR (
        `item`.`Person1` IS NULL
        AND `item`.`Person3` IS NULL
      )
    )
  )
ORDER BY
  `item`.`Date1` DESC

Explain return:
id:1
select_type: SIMPLE
table: item
partitions: NULL
type: ALL
possible_keys: Index_Date1,FK_item_Person2,Person1,FK_item_Person3
key: null
key_len: NULL
ref: null
rows: 1198601
extra: Using where; Using filesort

I tried create composition index for Date1-3 or for Person1-3 but with the index query run around 30 seconds.
How I can optimalize query to run fast as possible? Ideal max.5 seconds.


text:
Q: Best technology for web-to-application video chat? I'm starting to look into technologies to support a project that involves video chat between one party using a web browser and another party using a fat client (technology TBD, per below).
I see three components that need to be identified (and I'd prefer to avoid reinventing any wheels): the web client (video recording & playback), fat client (video recording & playback), and a server to act as interchange between them.
When I last did similar work years ago Flash seemed to be the only game in town, but I suspect there are other viable options now. What set of technologies for the above components (or suggest an alternate architecture) fit my wishlist below?

*

*Web-client side can be embedded in a web page and will have access to a local camera.

*Fat client side must be so simple as to be automatic (i.e. no complex camera configuration)

*

*Launching this side from a browser (e.g. WebStart) is legit

*If there are different technologies used for the two clients, use a standard interchange technology between them.

*My team is most comfortable in the Java ecosystem and would prefer technologies that are easily embeddable. But, this last point is negotiable (e.g. if Silverlight is a perfect fit, then perhaps we could go with C# instead for the fat client).

Thanks for any pointers!

A: Silverlight, with IIS7(.5).
Silverlight supports streaming video and it supports webcams. It was also used for the olympics for videostreaming. And with the out-of-browser-support, you fit bot the web client, and the think client

A: This question was asked 5 years ago, WebRTC was released later, but now I think it's best we can use for web video streaming. You can have both clients are using web, don't need to install client application.
PS. Just take into attention that WebRTC in near future will be replaced by ORTC, proposed by Microsoft.

A: HTML5 offers better video support (than HTML used to) - including streaming, the downside is that cross-browser support will probably be hit-and-miss.
Failing that, I'd go with Vidar's suggestion for Silverlight.

*

*How to Ditch Flash and Stream Video with HTML5

*HTML 5 and Web video: freeing rich media from plugin prison
If you were in the .Net world there's a control you can use in a thick-client which is bascially a browser window - I assume there's an eqvialent in the Java world (?); this would allow you to hopefully re-use more code.


text:
Q: Dynamic Control names in C# I'm trying the following code:
for (int i = 0; i < students.Length; i++)
{
    "student" + i.ToString().Text = students[i];
}

I already have many labels which each one has name like:
student1
student2
student3
.
.
But I got this error:
Error   1   'string' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)   F:\Homework\Homework\Form1.cs   161 46  Homework
Any help please??!

A: You can't have dynamic variable names, in just about any language.
Looks like you are looking to have a collection or array of controls.
Something like:
var studentControls = new List<Control>();
studentControls.Add(student1);
studentControls.Add(student2);
...
for (int i = 0; i < students.Length; i++)
{
    studentControls[i].Text = students[i];
}

A: Use Controls.Find("student" + i.ToString())

A: this may help
Controls.Find(string.Format("student{0}", i));

A better solution:
Set the Tag property of you Labels as follow:
Student1.Tag = 1;
Student2.Tag = 2;
Student3.Tag = 3;

I assume that your Labels are in a container control named container. use this code:
foreach(var item in container.Children) //based on your container type this line may change
{
    if(item is Label)
    {
        Label temp = ((Label)item);
        temp.Text = students[int.Parse(temp.Tag.ToString())]
    }
}

A: By doing i.ToString() you are given a string, which does not have the property Text :). That is what is causing your exception.
If Students is a list of controls that have the property .Text then use that and remove the ToString() else, remove the .Text.


text:
Q: Infinite series with binomials and a hypergeometric function I've been struggling for days with Mathematica to sum this, but no luck, any ideas?
$$ \sum_{k=0}^\infty \frac{(-1)^k}{2k+1} \sum_{j=0}^\infty (-x)^j \sum_{r=0}^\infty (xw)^r \binom{k+2}{r} \binom{j+2r-4}{2k} \, {}_2F_1\left(-2k,-r ; 4-j-2r ; \frac{2}{w}\right)$$
No need to worry about convergence, consider $x$ and $w$ as formal parameters. I just want it in closed form and I have reasons to believe that it should exist and I expect it to be relatively simple.


text:
Q: cycle through a list while skipping elements (python) I'm trying to find a way of going through a loop of a single list skipping the first element each time.
so for example, if I have a list:
lst = [0,1,2,3,4,5,6]

and wish to use a for loop to cycle through all but the first element and stop at an arbitrary point. So if I wish to start at index 1 of lst and advance through a cycle of each element (excluding the first) I can use the following:
scd = [1,2,3,4,5,6]
out = []
for i in range (1,14+1):
    if (i%len(lst)) not in scd:
        continue
    else:
        out.append(lst[i%len(lst)])
print(out)

it returns a list with only 12 elements:
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]

The output that I'm trying to get is:
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2]

I know the issue is in using the continue in the for loop, but I'm struggling with a workaround that gets me the desired output.
Any help would be greatly appreciated. also if there's a more pythonic way of going about this problem, I'm all ears.
Thanks so much.

A: IIUC, you simply want to repeat the same list, right? How about this where you could concatenate lists using divmod:
num = 14
i,j = divmod(num, len(lst)-1)
out = lst[1:] * i + lst[1:1+j]

Output:
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2]


text:
Q: Wake-on-LAN not sending magic-packet I've had setup my CentOS 7 box to wake up my Windows PC a couple of years ago and it was working fine, until for whatever reason it stopped working one day and I just couldn't figure out what the problem was and let it go.
Today I gave it another try and finally found out why. Somehow my CentOS is not sending any WOL packets to the L2 network. I checked this both with tcpdump from the CentOS box and from a MikroTik router between both machines and no UDP WOL packets are ever generated.
In the WOL client it apparently says the packet is generated successfully, like so, even though no packets are actually detected:
[root@CentOS 02:32:50 ~]# ether-wake 00:22:11:33:22:33 -D
The target station address is 0:22:11:33:22:33.
Packet is  00 22 11 33 22 33 00 22 11 33 22 33 08 42 ff ff ff ff ff ff 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33 00 22 11 33 22 33.
Sendto worked ! 116.
Sendto worked ! 116.
Sendto worked ! 116.
Sendto worked ! 116.
Sendto worked ! 116.

The reason there are multiple instances is because there are multiple IPs configured in it, but even when specifying a single interface the result is still the same.
I already tried disabling the firewall in CentOS to see if that was the problem but to no avail.
Does anyone have any idea of what the culprit may be?

A: While not exactly a solution to the underlying problem, I found a workaround.
I installed a different WOL client from a RHEL 6 RPM package (wol-0.7.1-4.el6.x86_64.rpm) and this one worked just fine.
After confirming my PC was actually receiving the packets, it still wasn't working but I quickly found out Fast Boot was enabled in Windows power options (even though I'm quite sure I had disabled it back in the day, some updated must've re-enabled it) and after disabling it everything worked as expected.


text:
Q: How to create a pandas DataFrame column based on the existence of values in a subset of columns, by row? I have a pandas DataFrame as follows:
import pandas as pd
data1 = {"column1": ["A", "B", "C", "D", "E", "F", "G"],
         "column2": [338, 519, 871, 1731, 2693, 2963, 3379],
         "column3": [5, 1, 8, 3, 731, 189, 9],
         "columnA" : [5, 0, 75, 150, 0, 0, 0],
         "columnB" : [0, 32, 0, 96, 0, 51, 0],
         "columnC" : [0, 42, 0, 42, 0, 42, 42]}

df = pd.DataFrame(data1)

df
>>>     column1   column2   column3   columnA   columnB   columnC
0         A       338         5         5         0         0
1         B       519         1         0        32        42
2         C       871         8        75         0         0
3         D      1731         3       150        96        42
4         E      2693       731         0         0         0
5         F      2963       189         0        51        42
6         G      3379         9         0         0        42

The values in columnA, columnB, and columnC are either an integer or zero. I would like to check values in columnA, columnB, and columnC such that if there is a integer in columnC and zeros in columns columnA and columnB.
If there is a value in columnC and zeros in columnA and columnB, I would like 1 to be in new column newcolumn. Otherwise, the values in newcolumn should be 0.
The resulting dataframe should be:
>>>     column1   column2   column3   columnA   columnB   columnC     newcolumn
0         A       338         5         5         0         0          0
1         B       519         1         0        32        42          0
2         C       871         8        75         0         0          0
3         D      1731         3       150        96        42          0
4         E      2693       731         0         0         0          0
5         F      2963       189         0        51        42          0
6         G      3379         9         0         0        42          1
....                 .....                         ...........

I'm aware of how to check values by column (e.g. using df.columnA == 0) and creating a new column is quite straightforward. However, how does one check this "by row"?

A: you can use boolean & operator on multiple conditions as shown below
df['new column'] = (df['columnA'] == 0) & (df['columnB'] == 0) & (df['columnC'] != 0)
df['new column'] = df['new column'].astype(int)
df

results in
 column1  column2  column3  columnA  columnB  columnC  new column
0       A      338        5        5        0        0           0
1       B      519        1        0       32       42           0
2       C      871        8       75        0        0           0
3       D     1731        3      150       96       42           0
4       E     2693      731        0        0        0           0
5       F     2963      189        0       51       42           0
6       G     3379        9        0        0       42           1

A: You can use np.where
df['newcolumn'] = np.where((df.columnA ==0) & (df.columnB == 0) & (df.columnC!= 0), 1, 0)

    column1 column2 column3 columnA columnB columnC newcolumn
0   A       338     5       5       0       0       0
1   B       519     1       0       32      42      0
2   C       871     8       75      0       0       0
3   D       1731    3       150     96      42      0
4   E       2693    731     0       0       0       0
5   F       2963    189     0       51      42      0
6   G       3379    9       0       0       42      1

A: You can use DataFrame.eval method:
In [146]: df['newcolumn'] = df.eval("columnA == 0 and columnB == 0 and columnC != 0") \
                              .astype(np.uint8)

In [147]: df
Out[147]:
  column1  column2  column3  columnA  columnB  columnC  newcolumn
0       A      338        5        5        0        0          0
1       B      519        1        0       32       42          0
2       C      871        8       75        0        0          0
3       D     1731        3      150       96       42          0
4       E     2693      731        0        0        0          0
5       F     2963      189        0       51       42          0
6       G     3379        9        0        0       42          1

A: # clever regex... might even make good screen name
# might want to use this instead
# v = df.reindex_axis(['columnA', 'columnB', 'columnC'], 1)).values == 0
v = df.filter(regex='[A-Za-z]$').values == 0
v[:, -1] = ~v[:, -1]  # negate the last column
df.assign(New=v.all(1).astype(np.uint8))

  column1  column2  column3  columnA  columnB  columnC  New
0       A      338        5        5        0        0    0
1       B      519        1        0       32       42    0
2       C      871        8       75        0        0    0
3       D     1731        3      150       96       42    0
4       E     2693      731        0        0        0    0
5       F     2963      189        0       51       42    0
6       G     3379        9        0        0       42    1

Its also pretty fast
time test


text:
Q: Send events from background task to UI I have implemented an application in windows phone 10.
In my background task, while the application is working some jobs, it wants to call to the main project and update UI real time.
Is there any mechanism to send event from background task to the main project  for updating UI ?

A:          //backTask
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () =>
            {
                //update ui
                UIAction.?Invoke();
            });

A:
Is there any mechanism to send event from background task to the main project for updating UI ?

You can register the Completed event of the background task and update the UI in the Completed event:
Register the complete event:
var registration= taskBuilder.Register();
registration.Completed += Registration_Completed;

private async void Registration_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
    var settings = ApplicationData.Current.LocalSettings;
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
    {
        tbResult.Text=settings.Values["BackgroundResult"].ToString();
    });
}

Xaml:
<StackPanel VerticalAlignment="Center">
        <Button Name="btnRegister" Click="btnRegister_Click">
            Click Me to register BT
        </Button>
        <TextBlock Name="tbResult">
            Here will show the result
        </TextBlock>
</StackPanel>

And here is the complete demo: BackgroundTaskSample.


text:
Q: Cannot read property 'emit' of undefined "Socket + Angular + Node " I created this event in my node server :
socket.on('hello' , function (data) {console.log('hello from the other side');})

on my chat component i have put :
constructor(private authService:AuthService,private router : Router) {
const socket=io('http://localhost:4000');
console.log(socket);}

onSendMessage(){
console.log('yep yep');
console.log(this.socket);
this.socket.emit('hello');
}

And on my chat component.html :

            <form (ngSubmit)="onSendMessage()">

                        Enter Message
                        <textarea class="form control" id="message"></textarea>

                        <input type="submit" class="btn btn-primary" value="Send Message"/>

            </form>

And the result is this :

Cannot read property 'emit' of undefined
      at ChatComponent.push../src/app/components/chat/chat.component.ts.ChatComponent.onSendMessage

Here is an image of the web console :
PS : whenever i click send message the socket always disconnect and reconnect

A: I think the problem is that socket is not a member of your char component you should declare it first as a member of your component to user this.socket , or if it's a service you use directly Inject it in the constructor then it becomes a member of your class and you can use (this.socket)


text:
Q: Getting Null Pointer in PreparedStatement.close() im trying to insert values from textfield to mySql using jdbc but my problem is im having a null pointer error when closing my prepared statement. here's my code
 private Connection con;
 private Statement stm;
 private ResultSet rs;
 private PreparedStatement ps ;

public void dbConnect(){
    try{
        Class.forName("com.mysql.jdbc.Driver");
        this.con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbTestDrive"
                + "", "root", "password");

    }
    catch(ClassNotFoundException ex){}
    catch(SQLException ex){}
}

 public boolean insert(Member member)throws SQLException{
    this.dbConnect();
    boolean success = false;
    String query = "INSERT INTO try VALUES(?, ?)";
            try {
        this.ps = this.con.prepareStatement(query);
        this.ps.setString(1, member.getMemberId());
        this.ps.setString(2, member.getFirstName());

       int rows = this.ps.executeUpdate();
        if(rows>0){
            success = true;
        }

    } catch (SQLException ex) {
        ex.printStackTrace();
        throw ex;
    } finally{
        this.ps.close(); // this is my line: 56 (im getting null pointer here)
        this.con.close();
    }

    return success;
}

here's the stacktrace:
   Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at rtu.tomis.dao.MemberDao.insert(MemberDao.java:56)
at rtu.tomis.gui.AddMemberView.btnSaveActionPerformed(AddMemberView.java:993)
at rtu.tomis.gui.AddMemberView.access$800(AddMemberView.java:21)
at rtu.tomis.gui.AddMemberView$9.actionPerformed(AddMemberView.java:476)

thank u for your help

A: You are getting an exception inside the try block, somewhere before or while this line executes:
this.ps = this.con.prepareStatement(query);

After the catch block rethrows the exception, the finally block executes. Unfortunately, because ps is null, you get another exception, which is then thrown, hiding the original exception.
You need to code more defensively, closing ps and con only if they are not null, and catching any exceptions that the close() calls might themselves raise. This will allow you to propagate any exceptions thrown by the body of the try.
You should also not silently ignore exceptions thrown in the try block of dbConnect(). I suspect that an exception there is the root of your problem.

A: You should write your code like this :
finally{
  if(ps != null)
        try{
            this.ps.close();
        }catch(Exception e){
            System.out.println("PreparedStatement close problem");
        }
  if(con != null)
        try{
            this.con.close();
        }catch(Exception e){
            System.out.println("Database Connection close problem");
        }
}

This will avoid null pointer exception if any of the con or ps were not initialized due to some error.
Also you can remove this keyword from all your code because you don't have any local variables of your method with the same name as your class variables , so there won't be any ambiguity

A: You need to check for null in the finally clause
finally{
  if(ps != null)
        this.ps.close();
   //
}

but the underlying problem may be when you open your connection, after it fails it will not initialize your prepared statement:
this.ps = this.con.prepareStatement(query);

In other words, before calling prepareStatement make sure con is not null. You should change your method dbConnect and print the exceptions, this will help you take care of the cause of the problem.
 try{
        Class.forName("com.mysql.jdbc.Driver");
        this.con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbTestDrive"
                + "", "root", "password");

    }
    catch(ClassNotFoundException ex){
     ex.printStackTrace();
    }
    catch(SQLException ex){
     ex.printStackTrace();
    }

A: I do think that there was an exception thrown in your dbConnect() method that's why the jvm reads directly to the finally before reading the instantiation of your prepared statement.

A: You are not getting Prepared Statement object in your insert method and invoking anything on null give you Null Pointer Exception.


text:
Q: How format special character in formData in nodeJS? I have a problem with encoding on special characters, let me show my code :
I have a node which post request directly on website, so i use FormData object to build form data.
The request did by a browser (got the CURL) :
In all example, it's a sample of my data where i have the problem.
  $'-----------------------------1755811723502268269588155\r\n
Content-Disposition: form-data; name="pageId"\r\n\r\n212403390500\r\n-----------------------------1755811723502268269588155\r\n
Content-Disposition: form-data; name="CL_TEXT_CLOT"\r\n\r\nLa t\xe2che \xe9tait bloqu\xe9\r\n-----------------------------1755811723502268269588155\r\n

the code is :
const form = new FormData();
  form.append('pageId', pageId),
  form.append('pageId', pageId),
  form.append('CL_TEXT_CLOT',el.CL_TEXT_CLOT)
...

let configPost = {
method: 'POST',
headers : {'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,/*;q=0.8",
'Content-Type': 'multipart/form-data; boundary='+form._boundary,
'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.9 Safari/537.36'},
url: 'http://localhost:7000/test',
data : form,
validateStatus: function (status) {
  return status >= 200 && status < 300 || status == 302; // default
}

When i sent :
'----------------------------397600554882409697883429\r\nContent-Disposition: form-data; name="CL_TEXT_CLOT"\r\ntype: text/plain; charset=UTF-8\r\n\r\n',
 'La tâche était bloqué.',

If i use escapeUnicode function :
let escapeUnicode = function (str) {
  return str.replace(/[^\0-~]/g, function(ch) {
      let tmp = "\\u" + ("000" + ch.charCodeAt().toString(16)).slice(-4);
      return tmp.replace('\\u00','\\x')
  });
}

in the formData, same code but with this line :
form.append('CL_TEXT_CLOT', escapeUnicode(el.CL_TEXT_CLOT))

and the result is :
   '----------------------------882802935214785196311782\r\nContent-Disposition: form-data; name="CL_TEXT_CLOT"\r\ntype: text/plain; charset=UTF-8\r\n\r\n',
     'La t\\xe2che \\xe9tait bloqu\\xe9.',

formData encapsulate the \xe2 by \ so result is \xe2....
and the final code is this (with or without the escapeUnicode) :
 const form = new FormData();
 form.append('CL_TEXT_CLOT', escapeUnicode(el.CL_TEXT_CLOT),{ header: { type:  'text/plain; charset=UTF-8' } })

Do you have an idea ?
Maybe i am in the wrong way....
EDIT: I have the same program in Python, and i had this in data :

So how should i do to have special character escaped in the formData in nodeJS ???

A: I changed by :
     form.append('CL_TEXT_CLOT',el.CL_TEXT_CLOT)

It send that  :
   [Function: bound ],
 '----------------------------075700443350966081023154\r\nContent-Disposition: form-data; name="CL_TEXT_CLOT"\r\n\r\n',
 'C\'est corrigé.  ',

I have this :
  C'est corrigé.

A: the following code can work:
     let form = new FormData()
     form.append(
        "prop",
        "some utf strings:你好",
        {
          contentType: "text/plain;charset=utf-8"
        }
     );


text:
Q: Error using for loop (objects inside array) I am trying to populate a table with an array (products). My data works however it's currently putting all of the information in one row:
const products = [{
            username: JSON.stringify(data, ['from']),
            content: JSON.stringify(data, ['content']),
            date: JSON.stringify(data, ['updatedAt'])
            }]

However, I'm trying to create a for loop to make a new object for every data item. I thought I had the right concept but this isn't working at all:
const products = [
            for (let i = 0; i < data.length; i++) {
            username: JSON.stringify(data[i], ['from']),
            content: JSON.stringify(data[i], ['content']),
            date: JSON.stringify(data[i], ['updatedAt'])
            }]

Can anyone point me in the right direction?

A: You can simply use map.
const products = data.map(item => ({
                username: JSON.stringify(item, ['from']),
                content: JSON.stringify(item, ['content']),
                date: JSON.stringify(item, ['updatedAt'])
               }))

or using for loop.
let products = [];
            for (let i = 0; i < data.length; i++) {
                products.push({
                username: JSON.stringify(data[i], ['from']),
                content: JSON.stringify(data[i], ['content']),
                date: JSON.stringify(data[i], ['updatedAt'])
                })
            }

You can avoid stringify if not needed.

const products = data.map(item => ({
                username: item.from,
                content: item.content,
                date: item.updatedAt,
               }))


text:
Q: Automatically include ID from datastore in Go I'm using Go on App Engine. I'm loading struct data from App Engine datastore. Currently I have to get the object ID from the key after the object is loaded from the datastore and then assign it to the object. In App Engine admin panel I can see the key and ID value when I'm using the datastore viewer.
Can I automatically include the key OR the numerical ID as a property from the datastore to the loaded object? (with or without using PropertyLoader interface).
That way I wouldn't have to include it always after the query by parsing it from the given key.

A: I believe the short answer is "no", there's nothing provided in appengine/datastore to have that happen automatically. See this groups topic.


text:
Q: NavigationView with multiple group hide & show group based on Condition I have NavigationView with multiple Groups which is based on some condition I  need to hide & show the group. How I can achieve this.
My Sample NavigationView menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

 <group android:checkableBehavior="single"
        android:id="@+id/grp_employee"
        >

        <item
            android:id="@+id/help"
            android:checked="false"
            android:icon="@drawable/ic_help"
            android:title="@string/app_name" />

.......
</group>

<group android:checkableBehavior="single"
        android:id="@+id/grp_admin"
        >

        <item
            android:id="@+id/admin_help"
            android:checked="false"
            android:icon="@drawable/ic_help"
            android:title="@string/app_name" />

.......
</group>

<group> ... </group>

</menu>

This is the my NavigationView file. I just want to show only one group view at a time hide all others group.

A: Well, you can use Menu.setGroupVisible (int group, boolean visible) to hide or show menu group.
navigationView.getMenu().setGroupVisible(R.id.group_id,false);//to hide
navigationView.getMenu().setGroupVisible(R.id.group_id,true);//to show

A: You can check visibility for one of the items in group, and the result is equal to group visibility.
For example, check admin_help visibility by this line:
navigationView.getMenu().findItem(R.id.admin_help).isVisible()

and the results is same to check grp_admin visibility


text:
Q: How get `Class`? For reflection, I need a Class<Long> as argument to getDeclaredMethod:
it.javaClass.getDeclaredMethod("myMethodName", Long.javaClass)

But in Kotlin, Long.javaClass gives a Class<Long.companion>. How do I get the correct type?

A: You can use Long::class to get a KClass representing Long, and then from there, the .java extension property to get a Java Class instance. So altogether:
val longClass: Class<Long> = Long::class.java


text:
Q: Search format in rails not as per expected? here is the code in my (poappcontroller.rb)
 def index
    @poapps =  Poapp.where(action: 'approve').pluck(:from, :invoice)
 end

code in the index.html.erb

    <% @poapps.each do |poapp| %>

        <%= poapp %>

     <% end %>

output
  ["Snehpandya", "fegd620"]
  ["Snehpandya", "bvnp1442"]

Expected  output

Database

A: .pluck(:from, :invoice) returns an array of arrays.
So, @poapps looks something like :
[["Snehpandya", "fegd620"],["Snehpandya", "bvnp1442"]]

which is why when you do <%= poapp %>, you get output as an array ["Snehpandya", "fegd620"]
To display it in snehpandya fegd62 format, change index.html.erb as below:

    <% @poapps.each do |poapp| %>

        <%= poapp.join(" ") %>

     <% end %>

UPDATE
To get the changed output as shown in the image attached in the question. You can do something like this:
As suggested by MrYoshiji

    <% @poapps.each do |from, invoice| %>

        <%= from %>

        <%= invoice %>

     <% end %>

A: Pluck returns an array, if selecting multiple items it'll return an array of arrays.  So you'll need to loop through them

     Invoice
     From

   <% @poapps.each do |poapp| %>

     <%= poapp.each do |poapp_content| %>

         <%= poapp_content %>

     <% end %>

 <% end %>

A: Try
<%= poapp.join(" ") %>


text:
Q: Let $f(x) = \frac{x(x−1)(x−2)\cdots(x−n)}{(x + 1)(x + 2)\cdots(x + n)}$ It's my first time asking questions on this community. Could you guys help me?
Let $$f(x) = \frac{x(x−1)(x−2)\cdots(x−n)}{(x + 1)(x + 2)\cdots(x + n)}$$
a) Find $f '(0)$
b) Suppose that the function $f: \mathbb{R}\to\mathbb{R}$ satisfies $f(x+y) = f(x)f(y)$ for all $x, y \in\mathbb{R}$.
If $k:=f '(0)$, show that $f '(x)= k f(x)$.
(Consider the cases $f (0) = 0$ and $f(0)$ is not the same as $0$ separately.)
Thank you so much
( I've been attempting to solve the problem (A) by multiplying and dividing the function in order to simplify the function and looking for the "logic" of this problem and yet I still don't know how to solve the problem. Sorry if you guys feel that way! I'll try to solve it again, I'm so sorry :) )
Update:
For problem A, I've tried and found the answer by using an internet calculator (wolfram alpha) So, here it is:
if n is an odd number, the answer will be=-1
if n is an even number, the answer will be=1.
But I am not too sure about it and therefore, I need strong proof that can prove my answer and I really hope that you guys could help me.

A: For part a let us go to the limit definition of a derivative. That is, the derivative of a function at point a is:
$$\frac{df}{dx_a}=\lim\limits_{h\to0}\frac{f(a+h)-f(a)}{h}$$
Consequently, the function becomes:
$$\lim\limits_{h\to 0}\frac{\frac{0+h(0+h−1)(0+h−2)\cdots(0+h−n)}{(0+h + 1)(0 +h+ 2)\cdots(0+h + n)}-\frac{0(0−1)(0−2)\cdots(0−n)}{(0 + 1)(0 + 2)\cdots(0 + n)}}{h}$$
$$\lim\limits_{h\to 0}\frac{\frac{h(h−1)(h−2)\cdots(h−n)}{(h + 1)(h+ 2)\cdots(h + n)}-\frac{0}{(1)( 2)\cdots( n)}}{h}$$
$$\lim\limits_{h\to 0}\frac{\frac{h(h−1)(h−2)\cdots(h−n)}{(h + 1)(h+ 2)\cdots(h + n)}-0}{h}$$
$$\lim\limits_{h\to 0}\frac{\frac{h(h−1)(h−2)\cdots(h−n)}{(h + 1)(h+ 2)\cdots(h + n)}}{h}$$
After simplifying the rational we get:
$$\lim\limits_{h\to 0}\frac{h(h−1)(h−2)\cdots(h−n)}{h(h + 1)(h+ 2)\cdots(h + n)}$$
Cancelling out $h$, we get:
$$\lim\limits_{h\to 0}\frac{(h−1)(h−2)\cdots(h−n)}{(h + 1)(h+ 2)\cdots(h + n)}$$
After letting the limit go to zero:
$$\lim\limits_{h\to 0}\frac{(h−1)(h−2)\cdots(h−n)}{(h + 1)(h+ 2)\cdots(h + n)}=\frac{(-1)(-2)\cdots (-n)}{(1)(2)\cdots (n)}=-1$$
Therefore, the derivative at $0$ is -1.
Part b is very similar to part one, you just have to use the limit definition of derivative, and then plug-in the disjunctive values given.


text:
Q: How to cancel a local notification trigger in Swift I have a trigger to show a notification to the user:
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Body"
content.sound = UNNotificationSound.default

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 20, repeats: false)

let request = UNNotificationRequest(identifier: "TestIdentifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

Is there a way for me to cancel that trigger once it has been set?
How do I cancel the notification before the timeInterval runs out and call the notification?

A: You can cancel or remove notifications by calling:
let center = UNUserNotificationCenter.current()

Remove pending notifications with given identifier
center.removePendingNotificationRequests(withIdentifiers: ["givenIdentifier"])

And remove delivered notifications with given identifier
center.removeDeliveredNotifications(withIdentifiers: ["givenIdentifier"])

A: To build on top of Mannopson's answer:
This removes all pending Notifications (Swift 5)
func cancelNotifications() -> Void {
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}


text:
Q: SQL Table with two relations or table with one relation and repeated rows This is an example, the names are fictitious.
On the one hand, we have suppliers who provide products to shops:
Suppliers
id name

1  GreatSupplier
2  SuperSupplier

On the other hand, we have shops that sell products to consumers:
Shops
id name          supplier

1  NiceShop      null
2  ShopShop      null
3  Soop          1
4  CheapShop     1
5  MyShop        1
6  Shopping      2

There are shops that have their own prices like NiceShop or ShopShop, so they don't have suppliers. But there are shops that use the prices set by the supplier like Soop, CheapShop, MyShop or Shopping.
Then I want to show all the prices of the products that the shops show to their customers. Something like this:
NiceShop  - Tomate: 1.23      // shop price
ShopShop  - Tomate: 1.26      // shop price
Soop      - Tomate: 1.21      // supplier 1 price
CheapShop - Tomate: 1.21      // supplier 1 price
MyShop    - Tomate: 1.21      // supplier 1 price
Shopping  - Tomate: 1.19      // supplier 2 price

Two options come to mind:
Option 1:
Products
id id_product   id_shop   id_supplier   price
1  34           1         null         1.23
2  34           2         null         1.26
3  34           null      1            1.21
4  34           null      2            1.19

When displaying prices, if it is a row with id_shop I show it as is, but if it is a row with id_supplier I join the supplier and the shops.
Here I can't make a unique index between id_product-id_store-id_supplier and things like this could happen:
id id_product   id_shop   id_supplier   price
5  34           3         null          1.21 // wrong

This should not happen as shop 3 has supplier 1 and this is already inserted in id 3.
Option 2:
Another option would be:

*

*If we insert a price from a shop that does not have a supplier, it is inserted as is.

*If we insert a price from a supplier, a join is made between the supplier and the shops and the same price is inserted several times. (same for updates)

Products
id id_product   id_shop   price

1  34           1         1.23      // shop price
2  34           2         1.26      // shop price
3  34           3         1.21      // supplier 1 price
4  34           4         1.21      // supplier 1 price
5  34           5         1.21      // supplier 1 price
5  34           6         1.19      // supplier 2 price

This option is a bit cleaner and allows me to create a single id_product-id_shop index but I am creating a lot of records with repeated prices, in this example it is duplicated 3 times but in my real environment it can be duplicated 50 times, and that translates into several extra gigabytes of database space.
Is there a better way to do this?

A: Most of the issues described can be solved by creating a common associated table for both shops and suppliers that is used to associate prices. In my example, I'll call this the price_setters table.
A Shop's Price-Setter is either itself or its supplier. This is enforced by the constraint on price_setters that the record has either a unique shop_id or a unique supplier_id, but not both.
prices has a FK to price_setters rather than shops or suppliers.
The only "anomaly" remaining is that there is no requirement in the schema for a shop or supplier to have a price_setter; however, that would just prevent you from assigning prices to the entity.
Edit: I moved the FKs between price_setters, shops, and suppliers into price_setters
-- Retrieve all prices by shop by going through the price_setter

select
  shops.name,
  products.name,
  prices.price
from shops
left join suppliers
  on shops.supplier_id = suppliers.id
join price_setters
  on shops.id = price_setters.shop_id
  or suppliers.id = price_setters.supplier_id
join prices
  on prices.price_setter_id = price_setters.id
join products
  on prices.product_id = products.id
;

create table suppliers (
  id unsigned bigint primary key,
  name varchar(255) not null
);

create table shops (
  id unsigned bigint primary key,
  name varchar(255) not null,
  supplier_id unsigned bigint,
  FOREIGN KEY (supplier_id) REFERENCES suppliers(id)
);

create table products (
  id unsigned bigint primary key,
  name varchar(255) not null
);

-- A shop's price setter is either itself or its supplier
create table price_setters (
  id unsigned bigint primary key,
  shop_id unsigned bigint ,
  supplier_id unsigned bigint,
  FOREIGN KEY (shop_id) REFERENCES shops(id),
  FOREIGN KEY (supplier_id) REFERENCES suppliers(id),
  unique(shop_id),
  unique(supplier_id),
  CONSTRAINT chk_shop_xor_supplier CHECK (
    (shop_id IS NOT NULL AND supplier_id IS NULL)
        OR (shop_id IS NULL AND supplier_id IS NOT NULL)
  )
);

create table prices (
  id unsigned bigint primary key,
  product_id unsigned bigint not null,
  price_setter_id unsigned bigint not null,
  price float not null,
  unique(product_id, price_setter_id),
  FOREIGN KEY (price_setter_id) REFERENCES price_setters(id),
  FOREIGN KEY (product_id) REFERENCES products(id)
);

A: If you want to have it clean you will need 3 entities (apart from shops and suppliers):
Products (PK = id_product)
id_product   name (and other attributes)
34           Tomate

Shop prices (PK = id_product + id_shop)
id_product   id_shop   price
34           1         1.23
34           2         1.26

Supplier prices (PK = id_product + id_supplier)
id_product   id_supplier   price
34           1             1.21
34           2             1.19

In both shop prices and supplier prices product/shop/supplier ids are not null and foreign keys to corresponding tables.
To display a list you will need to union both price tables:
SELECT s.id as id_shop, shp.id_product, shp.price
  FROM shops s
  JOIN shop_prices shp ON (shp.id_shop = s.id AND s.supplier_id IS NULL)
 UNION ALL
SELECT s.id as id_shop, sup.id_product, sup.price
  FROM shops s
  JOIN supplier_prices sup ON (sup.id_supplier = s.id_supplier)

(+extra joins with products if you need to display product attributes like name...)
This structure can't prevent eg. adding a record to shop prices for a shop that has a supplier, as in your example:
id_product   id_shop   price
34           3         1.21

But if you're careful such record wouldn't even show, for example in query above it is filtered out with s.supplier_id IS NULL in join condition. If it's mandatory, such case can be caught in a trigger or just at application level.

A: Can you just add shops without suppliers to the suppliers table?
Also - this phrase scares me:

bit complicated to maintain in the updates

I would use views to display the prices - not new tables.
I would also consider adding some form of versioning to your product/price table. Two ways to do this: add  begin_ts and end_ts where end_ts = '9999-12-31' means the record is still active. Or alternatively, have a trigger that automatically tracks when a record changes and writes the record to an archive table. Bottom line is you will probably want something that tracks the price history so you can show what the prices where X days, weeks, months, years ago.


text:
Q: When I use WebStorm open the vue project, there is Import decralations are not supported error
Import decralations are not supported by current JavaScript version

When I use WebStorm open the vue project.
My code is bellow:
import Vue from 'vue'
import App from './App.vue'

new Vue({
  el: '#app',
  render: h => h(App)
})

The snapshot:

A: import xxx from xxx is a new feature in ECMAScript6, you can find in there.
In the WebStorm you should change the JavaScript language version to ECMAScript6.
WebStorm -> Preferences -> Languages & Frameworks -> Javascript:

EDIT
Thanks @lena:
There is a easy way to realize it:

hit Alt+Enter on the error message, choose Change Javascript language version to ECMAScript 6 from the popup


text:
Q: How to enable responsiveness on fixed-width site built on Bootstrap? I have a problem with bootstrap. I needed a fixed-width layout, so i added div.wrap wrapper to whole page with width:1170px attribute and got what I want. But later I figured out that this trick disables responsive in Bootstrap.
Is it possible to built responsive website with fixed-width layout on Bootstrap? How do I enable responsive now?
Thank you.

A: Have you tried max-width: 1170px; instead of width: 1170px?


text:
Q: Defining routes for all my actions and controllers in ASP.NET MVC route collection I am bit new to Routing in ASP.NET MVC. I am building a project with multiple controllers and multiple actions. However, I wonder if I have to define a new route to the route collection for each action of each controller?.
Thanks.

A:
I wonder if I have to define a new route to the route collection for
  each action of each controller?

No, You do not have to define a new route for each action.

What is the main reason for defining routes for my actions and
  controller in there if in any case I can request the action and
  controller via the url even there are not routes defined?

The default route serve the purpose in most of the cases however you will find instances where adding a custom specific route make sense.
Custom routes gives you lot of power especially if you add route constraints.
Refer this article for in depth details and example.


text:
Q: Public IPv4 subnet: ping result in "Destination Host Prohibited" I got a new FTTC connection few days ago, along with 8 additional IPv4 addresses, say 89.89.233.104/29 (don't test them, they're fake). The ISP modem has 89.89.233.110 (which is the default gateway), so available for use are from .105 to .109.
I attach my linux computer to the modem LAN, configure with
ifconfig eth0 89.89.233.108 netmask 255.255.255.248
route add default gw 89.89.233.110

From outside I can ping 110 and 108, but from my desktop if I ping outside I get the following:
# ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
From 89.89.233.110 icmp_seq=1 Destination Host Prohibited
From 89.89.233.110 icmp_seq=2 Destination Host Prohibited
From 89.89.233.110 icmp_seq=3 Destination Host Prohibited

How is this possible? Why from outside I can be pinged (and so my host is replying to the outside world), but from inside I cannot access internet? I disabled every firewall or whatever enhanced feature I could find on the ISP modem. I tried pinging and tracerouting even ISP's DNS, thinking I could have some DNS restrictions but nothing changed.
I made every possible test, using Linux, Windows 7, pfSense (FreeBSD), they all give the same result. I called the ISP and they're coming to make some test themselves, buf if any suggestion can come from the community I'll be happy to test.
Oh, on a side note, we also have a single Point-to-Point IP on the modem, and internet works perfectly from there (that is: getting DHCP from the modem itself). The modem is connected in Bridged + Routed mode, so apparently it's routing but not correctly bridging.

A: It was as supposed a modem problem. After 3h the ISP technician replaced it nd magically everything started to work


text:
Q: Transforming String variable into JSTL I want to create a dynamic form.
For now I decided to add some options as a String variable (I know, horror code, but if you have any other sugestion, leave as a comment) that is "pasted" into the JSP.
I got the "pasting" part ok, but I can't use JSTL expressions, such as a forEach loop, which would make the code less horrific (say I want to make a multiple checkbox). In the above example I get only one option with a ${loopvariable} inside.
Take a peek (the string I'm passing as parameter):
String extraHtml = "<select name='HarmonicDecomposition' multiple><c:forEach begin='1' end='15' varStatus='loop'><option value='${loop.index}'>${loop.index}</option></c:forEach>"

In the JSP I have the following (ignore the way I named the variables):
<c:if test="${type.extraHtml != null}">

            ${type.extraHtml}

</c:if>

Can I make that forEach loop work? If not, why? What Options do I have?


text:
Q: Using split function to split LHS and RHS and store in each of variable accordingly May i know why the "a" and "b" variables only store the last element of the for loop data instead of the full for loop data?
listofinfo = ["a=1","b=2","c=3","d=4","e=5"]

for line in listofinfo:
    a,b = line.split("=")

print ("LHS:"+a)
print ("RHS:"+b)

output--> LHS:e # Expected output LHS:a,b,c,d,e
output--> RHS:5 # Expected output RHS:1,2,3,4,5
The purpose of this code is to split the "=" between the alphabet & the number. after that, all the alphabet will store inside the variable "a" which is LHS and number will store in the variable "b" which is RHS. May i know what mistake i have made in above code?
Update:
I try to play around and modify the code below like that:
myDictionary = {}
for line in listofinfo:
    a, b = line.split("=")
    myDictionary['a'] = b

for element in myDictionary:
    print (element, myDictionary[element])

Surprisingly, it only print out something like this --> ('a', '5')
In my understanding, within the for loop, just like what list do, it will append the content into the dictionary right?

A: a and b are assigned each element in succession. You only print the last values. If you moved your print statements into the loop you'd see each output:
for line in listofinfo:
    a, b = line.split("=")

    print "LHS:" + a
    print "RHS:" + b

If you wanted to create two separate lists of values, then do so explicitly:
a_list = []
b_list = []
for line in listofinfo:
    a, b = line.split("=")
    a_list.append(a)
    b_list.append(b)

print "LHS:", ','.join(a_list)
print "RHS:", ','.join(b_list)


text:
Q: How to connect build agent to PostgreSQL database My integration tests for my asp.net core application require a connection to a PostgreSQL database.  In my deployment pipeline I only want to deploy if my integration tests pass.
How do I supply a working connection string inside the Microsoft build agent?
I looked under service connections and couldn't see anything related to a database.

A: I would recommend you to use runsettings which you can override in task. In that way you will keep your connection string away of source control. Please check this link. And in terms of service connection, you don't need any service connection, only what you need is proper connection string.
Since I don't know how you connect to your DB in details I can't give you more info. If you provide example how you already connect to database I can try to provide a better answer.

A: If you are using Microsoft hosted agent, then your database need to be accessible from internet.
Otherwise, you need to it on self-hosted agent that can access your database.
I assume the default connectionstring is in appsettings.json, you could store the actual database connectionstring to a secret variable, then update appsettings.json file with that variable value through some task (e.g. Set Json Property) or do it programming (e.g. powershell script) before running web app and starting test during build.
If you can use any PostgreSQL database, you can use service container with a docker image that has PostgreSQL database (e.g. postgres).
For classical pipeline, you could call docker command run the image.


text:
Q: How to use select statement in join condition in Impala sql I am learning Impala sql and need to convert a sql query into impala equivalent which is something like this:
select distinct t1.c1, t1.c2
  from table1 t1
       join table2 t2
       on t2.c1=t1.c1 and (t2.c2 is null
                           or t2.c2 in (select c1 from table3
                                                 where 'some conditions')
                          )

When I am executing this query in impala I am getting error as "Could not resolve table reference table3". Although this table3 is present in the database which I am using.
Can anyone please guide what is happening and why am I getting this table not found error.
Also please suggest how to implement this sql code into Impala equivalent.

A: It does not support queries in ON join condition, rewrite query like this:
select distinct t1.c1, t1.c2
  from table1 t1
       join table2 t2 on t2.c1=t1.c1
       left join (--prevent unintended duplication by join if c1 is not unique
                  select distinct c1 from
                  table3 where 'some conditions') t3 on t2.c2=c3.c1
 where t2.c2 is null --not joined with c3 because of null
    or t3.c1 is not null --or joined with c3


text:
Q: YARN ContainerIDs from Client Is it possible to get the various container IDs and hostnames from the YARN client after the client has submitted the appContext ?  I suppose that would mean after the containers have been allocated can the information be communicated back to the client?
If this is not possible does the RM Web Interface provide this info ?

A: YARN CLI has an option to get the list of containers from the Application Attempt ID. You can get the list of containers, by following the steps below.

*

*Step 1: Get the list of Application Attempts from the Application ID
From the YARN application ID, you can get a list of application attempts, using the following command:
yarn applicationattempt -list <Application ID>

The description of this command reads:
-list <Application ID>    List application attempts for application.

For e.g.
yarn applicationattempt -list application_1452267331813_0009

*Step 2: Get the containers using Application Attempt ID
After you get list of application attempts, for each application attempt, you can get a list of containers, using following command:
yarn container -list <Application Attempt ID>

The description of this command reads:
-list <Application Attempt ID>    List containers for application attempt.

For e.g.:
yarn container -list appattempt_1452267331813_0009_000001

A: Rather ugly but can be done through a series URL requests to the ResourceManager, NodeManager, and various ContainerLog urls:
# Resource Manager Info for Given Application
curl http://RM:PORT/ws/v1/cluster/apps/<app_id>

amHostHttpAddress = data['app']['amHostHttpAddress']

# List containers with id, nodeId, containerLogsLink, etc
curl http://<amHostHttpAddress>/ws/v1/node/containers

# stdout/stderr for a specific container
curl http://<containerLogsLink>/stdout/?start=0"
curl http://<containerLogsLink>/stderr/?start=0"

This method works but there should probably be a cleaner way of doing this in YARN JAVA API


text:
Q: remotewebdriver - how to get logs from node I am running tests using the selenium grid and remote web driver (Using testNG).
The nodes run on VMWare.
How can I get during the run the log that appear on the node ?
I create new driver per class so I want the log to be saved for each class.
How it can be done ?
I want also to record in video the run in the vmware.
Is it possible to record the vmware when the screen is not open?
Thanks

A: This might be a partial answer of your question. We have done some extensive research on how to handle selenium log. So far came out that Log4j is one of the best options to use. Its allows you to log your result in different levels. Such as 'Fatal','Debug','Info' etc and different targets such as 'database, txt and console'. With a simple try catch  wrapper you can simply log every bit of of information you may want from each test.


text:
Q: For Each file doesn't go beyond 1000 files? I'm trying to get a CSV output for a Blender render job duration estimation. I like to input file time stamps into an Excel, so I wrote below VBScript (it's not 100% ready, but the echo should work). However, it won't iterate beyond the 1000th png file. It ends at file 9999.
Currently I got 35432 png files.
Why won't VBScript go beyond 1000 files?
Option Explicit 'force all variables to be declared
Const ForWriting = 2
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objTS 'Text Stream Object
Set objTS = objFSO.OpenTextFile("C:\tmp\output.txt", ForWriting, True)

Recurse objFSO.GetFolder("C:\tmp")
objTS.Close()

Sub Recurse(objFolder)
    Dim objFile, objSubFolder
    For Each objFile In objFolder.Files
        If LCase(objFSO.GetExtensionName(objFile.Name)) = "png" Then
            WScript.Echo objFSO.GetBaseName(objFile.Name) & vbTab & _
                CDate(objFile.DateLastModified) & vbTab & _
                CDate(objFile.DateCreated)
            objTS.WriteLine(objfile.Path)
        End If
    Next
    'unmark to make it recursive
    'For Each objSubFolder In objFolder.SubFolders
    '    Recurse objSubFolder
    'Next
End Sub


text: Q: How do I "stub" a child ember component in an integration test? Say I have a component A that contains component B. I'm writing an integration test for component A, but component B is an addon which I don't want to include with the tests (mainly because it makes xhr requests that I'd rather keep out of my integration test). Is there any documentation on how to do this? Or does anyone have a best practice?


text:
Q: QR code to image I've done a lot of searching around for this but to no avail.
I have a system where users purchase event tickets. On each event ticket is a code, which is used to generate a QR code (users need to be checked into the venue with this using a scanner).
Generating the QR code on the site is not a problem, but I need to get this into an email. I'm using http://davidshimjs.github.io/qrcodejs/ and obviously emails can't generate the QR code from this. so essentially I need to create an image, save it on the server, and then have the email link to it.
How can I create an image from the Javascript generated QR code?
Thank you

A: You can generate the qr code and save the image using this php code:
http://joserobinson.com/blog/como-generar-qr-codes-con-php/
Then, send the email with the attached image.


text:
Q: Google+ API redirect uri I want get OAuth from Google+. I'm doing
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL
URLWithString:@"https://accounts.google.com/o/oauth2/auth?client_id=952790678356&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=https://www.googleapis.com/auth/plus.me&response_type=token"]]];

I know that problem in the redirect URI, but I haven't got the redirect uri, it's http:// localhost. I try with redirect URI http:// localhost and it doesn't work. Maybe somebody know what I must write in redirect URI?

A: The Google+ iOS SDK and sample application demonstrates how you can use the installed application OAuth flow (with the Sign in with Google+ button). With this SDK, you will be able to register your Bundle ID instead.
https://developers.google.com/+/mobile/ios/


text:
Q: Code a SQL projection and mapping at the same time? This works to carve out a DDL object from an Address object from our database:
public class DDL {
    public int?   id   { get; set; }
    public string name { get; set; }
}

List<DDL> mylist = Addresses
    .Select( q => new DDL { id = q.id, name = q.name })
    .ToList();

However, we'd like to keep our POCO to ViewModel mappings in a single place outside of our MVC controller code.  We'd like to do something like this:
List<DDL> mylist = Addresses
    .Select( q => new DDL(q))  // <-- constructor maps POCO to VM
    .ToList();

But SQL cannot use the constructor function.  The object initializer above doesn't use functions to map fields.  Of course you could do .AsEnumerable().Select( q => new DDL(q)), but this selects all the fields in SQL (including the data), sends it to C#, then C# carves out the fields we need (terribly inefficient to transfer data we don't need.)
Any suggestions?  We happen to be using Entity Framework 6 to pull data.

A: You can use anonymous types to restrict what to select from the DB and then use those fields to construct your object :
List<DDL> mylist = Addresses
    .Select( q => new { id, name })
    .AsEnumerable()
    .Select(i => new DDL(i.id, i.name) // <- On the Enumerable and not on the Queryable
    .ToList();

A: All you need is to define the expression somewhere and use it. For example, in your ViewModel as a static read-only field.
public class SomeViewModel
{
    public static readonly Expression<Func<SomeEntity, SomeViewModel>> Map = (o) => new SomeViewModel
    {
        id = o.id,
        name = o.name
    }

    public int id { get; set; }
    public string name { get; set; }
}

// Somewhere in your controller
var mappedAddresses = Addresses.Select(SomeViewModel.Map);

I personally made myself a little static Mapper that keeps all the maps and use them for me. The maps are declared in a static initializer in all my ViewModels. The result gives me something that feels like AutoMapper, yet doesn't require the lib or the complicated mapping code (but also won't do any magic for you).
I can write something like this:
MyCustomMapper.Map<Entity, ViewModel>(entity);

and it's overloaded to accept IEnumerables, IQueryables and a single ViewModel. I also added overloads with only 1 generic type (the entity) that accept a type parameter. This was a requirement for me.

A: Are you against using 3rd party libraries? Automapper's QueryableExtensions does exactly what you want.
List<DDL> mylist = Addresses
    .Project().To<DDL>()
    .ToList();

It even has nice features like being able to filter on the transformed object and that filter being performed server side.
List<DDL> mylist = Addresses
    .Project().To<DDL>()
    .Where(d => d.name = "Smith") //This gets translated to SQL even though it was performed on DDL.
    .ToList();


text:
Q: Resume file uploading using Tus protocol I am developing a website using Laravel, and I am using tus-js-client to upload files directly to Vimeo without going through my server. The uploading works perfect.
But, lets say the uploading reached 44%, and then the user refreshed the browser... as I understand It should continue uploading from 44% when the user start uploading the same file again.. but that doesn't happen and it start from the beginning.
I think this is happening because when I send an API request to Vimeo to get the upload_link ( step 1 ) It will give me a new upload_link every time the user refresh the page..
 // Upload process start
  var self = this;

  // Send request to server to get (upload.upload_link) from Vimeo API (Step 1)
  var uploadEndPoint = self.getUploadEndPoint();

  // Start uploading ( Step 2 )
  self.uploader = new tus.Upload(file, {
    uploadUrl: uploadEndPoint,
    retryDelays: [0, 1000, 3000, 5000],
    metadata: {
      filename: file.name,
      filetype: file.type
    },
    resume: true,
    uploadSize: file.size,
    onError: function(error) {
      console.log("Failed because: " + error);
    },
    onProgress: function(bytesUploaded, bytesTotal) {
      var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2);
      console.log(bytesUploaded, bytesTotal, percentage + "%");
    },
    onSuccess: function() {
      console.log(
        "Download %s from %s",
        self.uploader.file.name,
        self.uploader.url
      );
    }
  });

What is the best way to handle this, so the user can resume the upload?

A: What i did:

*

*set Laravel backend endpoint to get download link

*for the first endpoint request make request from your backend to Vimeo and save uploadlink on backend

*for further requests check if client is going to download same file (by name and size, or by hash) and if yes return saved uploadlink, if not request new one

by doing that i solve two problems:

*

*keep record of the upload link until the file is not fully uploaded

*keep my permanent Vimeo access token uncompromised on server, sending on client only upload link


text:
Q: Science Fiction Novel with the Word Diamond in the Title This is a book that is probably more than 20 years old. It would be pre-2000 (most likely).
It has diamond in the title (I believe). I also think of the word satellite or space station.
It has two political groups that are against each other or at least at odds with each other.
There is an arranged marriage.
The girl that is sent to be married has an operation that covers her clitoris with some type of plastic or material that keeps her from enjoying certain adult activities.
The family that she is married into removes this so that her and her husband can bond better. He is young. They are both young. Perhaps 17 to 19.
That's about all that I remember. Adult themes for sure. Political.
They end up developing feelings for each other. There's a really adult scene with oral sex.

A: I think that's probably City of Diamond by Doris Egan (who went on to be a TV producer on House rather then continuing her writing career). It was first published in 1996 under the pseudonym Jane Emerson.

Adrian Mercati is thrown into the role of Protector of the City of
  Diamond, one of the Three Cities vast interstellar spaceships with
  whole religious cultures based on a murky past and an alien
  intervention. Not that he doesn't want the job, and not that he's not
  the man for it, but at twenty, he's a tad on the young side. He
  immediately makes arrangements for a political marriage to Iolanthe of
  the City of Opal, a seventeen-year-old who makes him seem worldly and
  wise.


text:
Q: MS Access Form Cascade Combo Box Let me preface this by acknowledging I'm a database, SQL and VBA newb. I've been tasked with hacking together something for which there is not external budget.
I'm having issues setting up a simple combobox based on a simple 2 column query called "Immeubles" (buildings in French).
The query features 2 columns that look for data in 2 different tables. One's called "Immeuble" (building in French), the other is called "Adresse" (address in French).
In a form, I've set up the first Combo box to only show distinct results from the "Immeuble" column. This combobox's name is "cboListe_Immeuble".
I'd like for the second combo box to only show the address that corresponds to the "Immeuble" value in the first combo box. I've named this second combobox "cboListe_Adresse".
For this example, the "Immeuble" is called "ROM 1", which has 3 corresponding adresses.
I've tried 2 different ways:
1st way.
Using a simple query builder on the second combo box :
SELECT DISTINCT Immeubles.Adresse
FROM Immeubles
WHERE (((Immeubles.Adresse)=[Forms]![SELECTION]![cboListe_Immeuble]))
ORDER BY Immeubles.Adresse;

2nd way.
Coding in visual basic code.
Me.cboListe_adresse.RowSource = "SELECT Immeubles.Adresse " & _
                          "FROM qryImmeubles " & _
                          "WHERE Immeubles.Immeuble = " & (Me.cboListe_Immeuble) & _
                          "ORDER BY Immeubles.Adresse"

The first way doesn't work at all.
The second way generates an error
Syntax error (missing operator) in query expression 'Immeuble = ROM 1ORDER BY Adresse'

At the end of the sub, I've added a requery line

"Me.cboListe_adresse.Requery"

What am I doing wrong?

A: Try using the correct spacing and quoting:
Me.cboListe_adresse.RowSource = "SELECT Immeubles.Adresse " & _
    "FROM qryImmeubles " & _
    "WHERE Immeubles.Immeuble = '" & Me.cboListe_Immeuble & "' " & _
    "ORDER BY Immeubles.Adresse"

A: I had added a "qry" that broke the code.
This is the working code for my example :
Me.cboListe_adresse.RowSource = "SELECT Immeubles.Adresse " & _
    "FROM Immeubles " & _
    "WHERE Immeubles.Immeuble = '" & Me.cboListe_Immeuble & "' " & _
    "ORDER BY Immeubles.Adresse"

Thank you @HansUp for your time and effort!


text:
Q: LoadError: MethodError: convert(::Type{Union{}}, ::LinearAlgebra.Adjoint{Float64,Array{Float64,1}}) is ambiguous While I'm using julia to compile a .jl file
pixelscale=4e-4
psfsize=4191.00

span = (2*pixelscale * floor(psfsize/2))/(psfsize-1)
temx = [-pixelscale * floor(psfsize/2)]
for i in psfsize
    b=-pixelscale * floor(psfsize/2) + i*span
    push!(temx,b)
end

meshtheta = temx
meshphi = temx'
R_pup = sqrt(meshphi^2 + meshtheta^2)

temx is a one dimensional array and temx' is transposed from temx
and error occurs:

LoadError: MethodError: convert(::Type{Union{}}, ::LinearAlgebra.Adjoint{Float64,Array{Float64,1}}) is ambiguous.

I can't see why it's wrong.Does anyone have any idea?

A: The error you're seeing comes from this:
julia> a = rand(2);

julia> a'
1×2 adjoint(::Vector{Float64}) with eltype Float64:
 0.985248  0.651835

julia> (a')^2
ERROR: MethodError: convert(::Type{Union{}}, ::LinearAlgebra.Adjoint{Float64, Vector{Float64}}) is ambiguous. Candidates:

This is essentially because squaring a row or column vector doesn't make mathematical sense thus is undefined in Julia.
If you want element-wise sqaure, do a' .^ 2 instead.


text:
Q: how to mock a service so as to inject it properly I'm trying to mock a service within a functional test, which is used by another service:
    $client = static::createClient();

    $stub = $this->createMock(MailService::class);
    $stub->method('sendMailToUser')->willReturn(9);
    $client->getContainer()->set('belka.auth_bundle.mail_service', $stub);
    // the *real* test should start here

if I try to put a die command inside the original sendMailToUser, what I get is the code stop running, although I tried to mock it by returning 9. What's wrong with it? The service I'm testing has the following declaration, then I guessed the injected service was the one wrote above:
belka.auth_bundle.user_handler:
    class: Belka\AuthBundle\Handler\UserHandler
    arguments:
        - '@belka.auth_bundle.user_repository'
        - '@belka.auth_bundle.mail_service'
    calls:
        - [setRequest, ["@request_stack"]]
        - [setSettings, ["@belka.auth_bundle.setting_handler"]]
        - [setBodyJsonHandler, ["@belka.container_support_bundle.body_json_handler"]]
        - [setQuantityHandler, ["@belka.container_support_bundle.quantityhandler"]]

A: I trust Symfony to create services correctly, and so I won't usually get services to then test within them (I do have a smoke-test that tries to create almost every service though).
So, if you are trying to get a 'belka.auth_bundle.user_handler', I would manually create the Belka\AuthBundle\Handler\UserHandler instance, with your mock as one of the arguments.
For services that are required deeper within the services, there aren't easy ways to mock them (or to get the mock into place), but you can use the service container environments to override them.
For example, I have a service that tests if a Request has come from a bot - but while running functional tests I replace it entirely with a service that always says 'not a bot', by overriding my 'app.bot_detect.detector' service in /config/services_test.yml
# set the default bot detector to a simple fake, always return false
app.bot_detect.detector:
    class: App\Services\BotDetectorNeverBot

In the main config/services.yml, the class would really perform the check, but the method in the test environment's BotDetectorNeverBot class always says false.
In the same way, you could override belka.auth_bundle.mail_service in services_test.yml (or config_test.yml) to not send email, and store something instead. You just have to make sure you are including '*_test.yml' files appropriately.


text:
Q: WPF WindowsFormsHost VS2008 Toolbox has grayed out all the Windows Forms controls I'm trying to use WindowsFormsHost in a WPF app so I can use some Windows Forms components.
<Grid>
    <WindowsFormsHost>

    </WindowsFormsHost>
</Grid>

This all works ok with no errors, but when I go to drag a Windows Forms component from the toolbox in VS2008, they're all grayed out. In a way this makes sense as only the WPF components are available. But how do you drop a Windows Forms component onto a WindowsFormsHost if they're all grayed out and unavailable?

A: I don't think WPF designer supports Windows Forms components. You need to specify these in the XAML or in code. A simple example of how to add a WinForms button into a WPF application. Note that the button isn't visible on the design surface.
<Window x:Class="DataTemplateBind.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:forms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    Title="Window1" Height="300" Width="300">

    <WindowsFormsHost Height="200" Name="windowsFormsHost1" Width="258" >
        <forms:Button Text="Waaa :("></forms:Button>
    </WindowsFormsHost>
</Window>

Note the added xmlns:forms namespace which isn't there by default.


text:
Q: Unable to extract details from an XML column of MSSQL I am new to extracting data from XML column using SQL, I did try with other simple format but this one is a bit tricky.
XML column name is "Data" and below is the value.
<SpecificationDataDto
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://schemas.datacontract.org/2004/07/Dummy.Sample.API.TransferObjects.Dto">
    <Narratives>
        <AnswerDto>
            <AddressData />
            <AddressResponseType i:nil="true" />
            <Answers
                xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
                <d4p1:string>Loose Print</d4p1:string>
            </Answers>
            <ComponentOrderNumber>3</ComponentOrderNumber>
            <Index>0</Index>
            <IsQuantity>false</IsQuantity>
            <MasterQuestionId i:nil="true" />
            <MasterQuestionTitle i:nil="true" />
            <MasterQuestionTitleResourceKey i:nil="true" />
            <ParentQuestionGroupId i:nil="true" />
            <ParentQuestionGroupIndex i:nil="true" />
            <ParentQuestionGroupTitle i:nil="true" />
            <PermutationId>65922bf8-6468-40f2-967c-27547412ba2b</PermutationId>
            <PermutationOrder>0</PermutationOrder>
            <ProductSpecificationLabel />
            <ProductSpecificationLabelResourceKey>65A4E3D8-9FF7-48D9-B3F8-0E2D4D23A1B8</ProductSpecificationLabelResourceKey>
            <QuestionGroupId i:nil="true" />
            <QuestionGroupIndex i:nil="true" />
            <QuestionGroupOrderNumber i:nil="true" />
            <QuestionGroupTitle i:nil="true" />
            <QuestionId>e575d4ac-5dfb-4170-c5c0-08da85c9a9ed</QuestionId>
            <QuestionOrderNumber>1</QuestionOrderNumber>
            <QuestionTitle>Product category</QuestionTitle>
            <QuestionTitleResourceKey>81B4FFBC-4503-4E48-83C0-17FBB227384B</QuestionTitleResourceKey>
            <ResponseIds
                xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
                <d4p1:guid>c4ed5170-6634-4aad-c054-08da7f653c36</d4p1:guid>
            </ResponseIds>
            <UpdateDate i:nil="true" />
        </AnswerDto>
    </Narratives>
</SpecificationDataDto>

I tried below but no luck
WITH XMLNAMESPACES ('http://schemas.microsoft.com/2003/10/Serialization/Arrays' AS d4p1)
    , CTE as (
    SELECT Order
    ,t.c.value('(*/QuestionTitle)[1]', 'Varchar(250)') AS Question
    ,t.c.value('(*/d4p1:string)[1]', 'Varchar(250)') AS Answer
    FROM SchemaName.DatabaseName.TableName
    CROSS APPLY Data.nodes('*/SpecificationDataDto/Narratives/AnswerDto') t(c)
    WHERE Order = '737B4994'
    )
    select * from CTE

I am expecting the below values to come out for this order in 2 columns,
QuestionTitle = Product category

d4p1:string = Loose Print


text:
Q: Order students by highest grade and then order grades for each student

Student
Grade
Course

JOHN
10
Algebra

JOHN
7
Computer science

ANNA
10
Algebra

ANNA
10
Data structures

JACOB
10
Data structures

GEORGE
6
Computer science

GEORGE
10
Algebra

GEORGE
9
Data structures

I have the above table and what I want to do is to order the students by their highest course grade (a student with 10 & 10 comes first compared to someone with a 10 or 10 & 9 or even someone with 10 & 9 & 9) and then order the courses by grade for each student. The result should look like the table below:

Student
Grade
Course

ANNA
10
Data structures

ANNA
10
Computer science

GEORGE
10
Algebra

GEORGE
9
Data structures

GEORGE
6
Algebra

JOHN
10
Algebra

JOHN
7
Computer science

JACOB
10
Data structures

Is there a way to achieve this result?

A: You can use window functions in the ORDER BY clause.  So:
order by max(grade) over (partition by student) desc,
         student,
         grade desc

A: With this query:
SELECT Student, GROUP_CONCAT(LPAD(Grade, 2, '0') ORDER BY Grade DESC) grades
FROM tablename
GROUP BY Student

you get for each student all grades left padded with 0 in a comma separated list:

Student
grades

ANNA
10,10

GEORGE
10,09,06

JACOB
10

JOHN
10,07

You can join the above query to the table and sort by that list of grades descending:
SELECT t.*
FROM tablename t
INNER JOIN (
  SELECT Student, GROUP_CONCAT(LPAD(Grade, 2, '0') ORDER BY Grade DESC) grades
  FROM tablename
  GROUP BY Student
) g ON g.Student = t.Student
ORDER BY grades DESC, Grade DESC

See the demo.
Results:

Student
Grade
Course

ANNA
10
Algebra

ANNA
10
Data structures

GEORGE
10
Algebra

GEORGE
9
Data structures

GEORGE
6
Computer science

JOHN
10
Algebra

JOHN
7
Computer science

JACOB
10
Data structures