Q: Call a controller method without loading a blank view I'm trying to call a controller method to delete a record in my database and I am using an actionlink to do this but whenever I hit the delete button, it will delete the record in the database, but it redirects me to a blank page. What I am trying to do is have it not redirect to anything but I can't seem to get that to work.
HTML/Razor
@Html.ActionLink(" ", "DeleteRecord", new { id = item.JPAppId }, new { @class = "fa fa-trash"})

Controller Method
public void DeleteRecord(Guid id)
    {
        JPApplication jPApplication = db.JPApplications.Find(id);
        db.JPApplications.Remove(jPApplication);
        db.SaveChanges();
    }


Q: webservice REST método GET com token em navegador externo Estou desenvolvendo um cliente que consome um webservice, todos os métodos POST estão ok.
Tem um método GET que deve retornar uma página em HTML para cadastro de cliente.
nesse método, é necessário definir o header:

 content-type:"application/json"
 api-token: {token}

eu consigo chamar o método e abrir a página em um webbrowser, porém com um monte de erros CSS e JS, a formatação da página fica errada e os botões não funcionam.
Gostaria de abrir essa página em um browser externo (chrome, firefox, até mesmo iexplorer) porém, ao chamar a URL, sempre me retorna que o token não foi informado.
É possível mudar algo no C# para abrir corretamente a página no WebBrowser?
É possível abrir o navegador externo, passando além da URL, o token que deve ir no header?
UPDATE:
O que já fiz:
1-
 string html = LinkedFarma.CadastrarCliente(); //Retorna o HTML do método GET
 webBrowser1.DocumentText = html;

Resultado: Não carrega CSS e JS (óbvio)
2-
string headers = "api-token: "+Configuracao.Token+"\r\n";
headers += "content-type: application/json";
webBrowser1.Navigate(Configuracao.UrlCadastrarCliente, null, null, headers);

Resultado: Funciona, porém o a página fica com erros, os botões não funcionam o CSS não é carregado completamente.
3-
Já criei uma página em PHP, que receberia o Token como um parâmetro e faria a solicitação redirecionando a página, porém, sem sucesso também. (Me aventurei no PHP pois não tenho prática)

A: Pensei que era sua API que estava com problemas para fornecer as paginas estáticas dela, seria um simples ajuste;
Agora que você falou que é um aplicativo desktop, infelizmente nunca trabalhei com Windows Form, sei que tem como abrir a pagina em outro Browser e passar o token, da uma olhada :
https://stackoverflow.com/questions/6293549/setting-authentication-header-for-webbrowser-control-asp-net
https://stackoverflow.com/questions/18035579/how-to-open-a-link-in-webbrowser-control-in-external-browser

A: Resolvido:
O desenvolvedor da outra empresa, me enviou um exemplo em Delphi e pesquisei como fazer em C#
Ele utiliza um objto OLE que abre o internet explorer.
em C# ficou assim:
            SHDocVw.InternetExplorer IE = new SHDocVw.InternetExplorer();
            object Empty = 0;
            object URL = Configuracao.UrlCadastrarCliente;
            IE.Visible = true;

            IE.Navigate2(ref URL, ref Empty, ref Empty, ref Empty, "api-token: "+ Configuracao.Token);

obs. Tive que adicionar a referência Microsoft Internet Controls de nome: Interop.SHDocVw
obrigado a todos pela colaboração.

A: Existe uma maneira legal de fazer isso no próprio app. Usando o component web, não o nativo da microsoft, mas um de terceiros. Eu utilizo o awessomium.
Usando a api do mercado livre, segue o exemplo do código que utilizo:
    private void formWebControl_Load(object sender, EventArgs e)
    {
        //navega o site da api com os parametros assim que o formulario abrir
        webLogin.Source = new Uri(https://apisite.com);
    }

    private void Awesomium_Windows_Forms_WebControl_TargetURLChanged(object sender, Awesomium.Core.UrlEventArgs e)
    {
        //evento que ocorre quando a url muda no navegador component, daí é só manipular.
        //logo após chama o evento close;
        Close();
    }

    private void formWebControl_FormClosing(object sender, FormClosingEventArgs e)
    {
        //limpa o component da memória
        webLogin.Dispose();
    }

Creio que isso acima possa te ajudar. Pois ter que ir a um navegador externo, ao meu ver, é muita mão de obra, e esse não é o objetivo de um software.
Espero que seja isso. Qualquer coisa posso colocar o exemplo completo que uso no mercado livre ou até mesmo te ajudar.


Q: Multiple VU in Jmeter-Only one user able to insert data Test Plan:-
-User logs in.
-Enter details in a form and save it(Which is stored in DB).
-Logs out.

When ran with 2 Virtual Users :-
-Number Of Threads(users) = 2
-Ramp Up Period = 1
-Loop Count = 1

Only 1 user is able to successfully store the details in DB.
2nd Thread/user give some URLs in response instead of JSON Data.
When one thread is used and the script is run many times, it is successfully storing data in DB.
Elements used in the Test Plan:-
-HTTP Cookie Manager

-View Result Tree

Am I missing some elements ?
What mistake I am doing ?

A: I suppose you are replaying the recorded plan for 1 user.
Most probably your issue is due to not variabilizing (Regexp Post-Processor or CSS/Jquery Post Processor to extract and variable to inject) some dynamic data that is needed for the additionnal users.
So when you put 1, it works because IDs correspond to recorded user, but when you put more, at some step you have the second users using the IDs of the first one.
Google "correlation with jmeter" to understand and fix your issue.

A: In case you have the correct script then check the business of your application. As I have experienced some applications don't allow many users submit the form at the same time. It will lock the form for the first user and the second user cannot submit, the second user will receive the response data with messages like "This form is being used by another user..." or "The data on this form is out of date, please refresh...". In that case, I use a Logic Controller, called "Critical Section Controller". It will handle the users to make sure the transaction will be executed by only one user at a time.


Q: Migrate pinnacle cart customers data to magento1.x version I came back on stackoverflow after long time.I really need a help in migrating the pinnacle cart to magento1.x.I am migrating the customer data but I want customer can login in magento site with same credentials without reset the password.
Is it possible that customer can use the same credentials of pinnacle cart to Magento after migration.
any quick help will be appreciated.


Q: Get distinct pattern match results (substrings) from PyMongo What is the most efficient way to query a MongoDB collection for unique/distinct substrings in a given field?
Example documents:
{"_id": "1234.abc.test1", "some_key": "some_value"}
{"_id": "1234.abc.test2", "some_key": "some_value"}
{"_id": "0420.def.test3", "some_key": "some_value"}

The document IDs above follow an internal namespacing convention. I need to know what all of the distinct first elements of that namespacing are.
The desired output of the query on the above collection:
1234
0420

I am trying to avoid getting the entire dataset back only to do row['_id'].split('.')[0] on each row afterwards. Ideally, the query should return only the distinct list of those substrings.

A: The idea is actually the same as yours(i.e. splitting by . and get the first element), then $group them to get distinct records.
db.collection.aggregate([
  {
    $project: {
      first: {
        "$arrayElemAt": [
          {
            "$split": [
              "$_id",
              "."
            ]
          },
          0
        ]
      }
    }
  },
  {
    "$group": {
      "_id": "$first"
    }
  }
])

Here is the Mongo playground for your reference.
Here is the PyMongo implementation of the above query:
pipeline = [
    {"$project": {"first": {"$arrayElemAt": [{"$split": ["$_id", "."]}, 0]}}},
    {"$group": {"_id": "$first"}}
]
result = self.collection.aggregate(pipeline=pipeline, allowDiskUse=False)


Q: ajax get image from folder debug   function ajax_json(folder){
      var thumbnailbox = $('#thumbnailbox');
      $.ajax({
        url:"json_data.php",
        dataType:"json",
        type:"POST",
        data: {folder: JSON.stringify(folder)},
        contentType: "application/json; charset=utf-8",
        success:function(d){
          var temp = '';
            for (var o in d) {
                 if (d.hasOwnProperty(o) && d[o].hasOwnProperty('src') && d[o].src !== '') {
                     //create image
                     temp += "

";
                 }
            }
          }, error: function (jqXHR, textStatus, errorThrown){
            console.log("textStatus = " + textStatus + "\terrorThrown = " + errorThrown);
            alert(XMLHttpRequest.status);
            alert(XMLHttpRequest.readyState);
            alert(textStatus);
        }
      });
    }

php
<?php
header("Content-Type: application/json");
$folder = $_POST["folder"];
$jsonData = '{';
$dir = $folder."/";
$dirHandle = opendir($dir);
$i = 0;
while ($file = readdir($dirHandle)) {
    if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
        $i++;
        $src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
    }
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>

error
textStatus = parsererror    errorThrown = SyntaxError: Unexpected token <

my intention is the get image from my folder using ajax ,it got error and i cant find what i am missing to have error , can anyone help me take a look? i cant debug it.


Q: Get Index of a Set in Swift let setOfStrings: Set<String> = ["ONE", "TWO", "THREE"];

It doesn't behave like and array, so setOfStrings[0] does not work.
Any ideas?

A: You might want to access the first element of the set as follows:
if let first = setOfStrings.first {
    print(first)
}

Assuming that you are already familiar with: Set is unordered data structure, i.e: first value is not guaranteed to be "ONE".
You cannot access an element in a set via index as an integer (setOfStrings[0]), however, since Set represents a Collection (adopted by sets), SetIndex is probably what are you looking for, by using Set.Index of your current set, as follows:
let setOfStrings: Set<String> = ["ONE", "TWO", "THREE"]
// for me, it sorted as: {"THREE", "TWO", "ONE"}

let mySetIndex = setOfStrings.index(setOfStrings.startIndex, offsetBy: 1)

let secondElemnet = setOfStrings[mySetIndex] // "TWO"

Note that:

*

*By using subscript(_:), you should be able to get e specific element.

*index(_:offsetBy:):

Returns an index that is the specified distance from the given index.

*

*mySetIndex data type is SetIndex<String>.


Q: How to build server streaming via grpc and nest.js? Need to create some "channel" to which the client can subscribe and periodically receive messages.
Within the current technology stack, I'm trying to organize something like this:
proto file:
syntax = "proto3";

package testtime;

service TimeService {
    rpc GetTimeStream(Empty) returns (stream TimeStreamResponse);
}

message Empty {
}

message TimeStreamResponse {
    string result = 1;
}

controller:
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';
import moment from 'moment';
import { Observable, Subject } from 'rxjs';

const timeSubject = new Subject<{ result: string }>();
setInterval(() => {
    const result = moment().format('hh:mm');
    timeSubject.next({ result });
}, 5000);

@Controller()
export class TestTimeController {
    @GrpcMethod('testtime.TimeService', 'GetTimeStream')
    public getTimeStream(): Observable<{ result: string }> {
        return timeSubject.asObservable();
    }
}

when I try to call the method, I get an error:
/project/node_modules/@nestjs/microservices/server/server-grpc.js:141
             this.transformToObservable(await handler).subscribe(data => callback(null, data), (err) => callback(err));
                                                                         ^
 TypeError: callback is not a function
     at SafeSubscriber._next (/project/node_modules/@nestjs/microservices/server/server-grpc.js:141:73)
     at SafeSubscriber.__tryOrUnsub (/project/node_modules/rxjs/src/internal/Subscriber.ts:265:10)
     at SafeSubscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:207:14)
     at Subscriber._next (/project/node_modules/rxjs/src/internal/Subscriber.ts:139:22)
     at Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
     at CatchSubscriber.Subscriber._next (/project/node_modules/rxjs/src/internal/Subscriber.ts:139:22)
     at CatchSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
     at TapSubscriber._next (/project/node_modules/rxjs/src/internal/operators/tap.ts:125:22)
     at TapSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
     at MergeMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/mergeMap.ts:162:22)
     at SimpleInnerSubscriber._next (/project/node_modules/rxjs/src/internal/innerSubscribe.ts:30:17)
     at SimpleInnerSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
     at MergeMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/mergeMap.ts:162:22)
     at SimpleInnerSubscriber._next (/project/node_modules/rxjs/src/internal/innerSubscribe.ts:30:17)
     at SimpleInnerSubscriber.Subscriber.next (/project/node_modules/rxjs/src/internal/Subscriber.ts:99:12)
     at SwitchMapSubscriber.notifyNext (/project/node_modules/rxjs/src/internal/operators/switchMap.ts:166:24)

What am I doing wrong?


Q: Azure function app, service bus and return service bus I have an azure function with a service bus input attribute and service bus output attribute set.
This means that whatever I return from this function will be returned to the ‘return’ queue.
However,  i want to manually handle some messages as there is no point retrying them I just want to put them straight on the LDQ and carry on.
So i added MessageReceiver as a parameter with lockToken.
All good.
But now, if i handle the message and send to DLQ i have no way ending the function execution gracefully as it is expecting a return.  So i throw an exception.  But now i have numerous error logs in the output like ‘lock is invalid’.
I tried to set autocomplete to false but then i have a different issue; how do i ensure i can return the message AND log it in a transaction and handle rollback?
Any guidance??
Example:
  public static class Function1
    {
        [FunctionName("Function1")]
        [return: ServiceBus("returnQueueName", Connection = "myConnectionString")]
        public static async System.Threading.Tasks.Task<ReturnMessage> RunAsync([ServiceBusTrigger("mytopic", "mysubscription", Connection = "myConnectionString")]
        string mySbMsg, ILogger log,
            MessageReceiver messageReceiver, string lockToken)
        {
            log.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");

            await messageReceiver.DeadLetterAsync(lockToken);

            return new ReturnMessage();
        }
    }

    public class ReturnMessage
    {
        public string Payload { get; set; }
    }

Hopefully you can see that the input queue and output queue are handled by the hosting system - Azure.  I like this because it will look after atomcity for me.
But if I include the line:
await messageReceiver.DeadLetterAsync(lockToken);

This will move the current message to the DLQ.
GREAT!!! That's what I want.
But I am now forced to return something OR throw an exception.  Is there any way out of this as seeing the error messages is misleading as there is no error to follow.

A: As far as I can see it appears that you shouldn't use an automatic return service bus binding.  Instead, you should manually connect to the return topic/queue and handle the message logistics manually.


Q: objective-C - other methods to convert a float to string I know that you can convert a float into a string using
NSString *myString = [NSString stringWithFormat:@"%f", myFloat];

My question is what OTHER methods exist in Objective-C that can do that same?
thanks.

A: You can create your own category method.  Something like
@interface NSString (Utilities)

+ (NSString *)stringWithFloat:(CGFloat)float

@end

@implementation NSString (Utilities)

+ (NSString *)stringWithFloat:(CGFloat)float
{
    NSString *string = [NSString stringWithFormat:@"%f", float];
    return string;
}

@end

Edit
Changed this to a class method and also changed the type from float to CGFloat.
You can use it as:
NSString *myFloat = [NSString stringWithFloat:2.1f];

A: You could use NSNumber
NSString *myString = [[NSNumber numberWithFloat:myFloat] stringValue];

But there's no problem doing it the way you are, in fact the way you have in your question is better.

A: float someVal = 22.3422f;
NSNumber* value = [NSNumber numberWithFloat:someVal];
NSLog(@"%@",[value stringValue]);

A: in a simple way
NSString *floatString = @(myFloat).stringValue;


Q: How to change layers in pretrained model in Mxnet I have a pre-trained Mxnet model. I need to change last two layers and add new two layers for testing. Basically, I need to create a probability map of the image.
How can i do that ?

A: There is a tutorial on fine-tuning with MXNet. Did you check this out?
http://mxnet.incubator.apache.org/faq/finetune.html


Q: Determining the execution time of all statements in process of FPGA I'm beginner studying FPGA. I'm confusing a problem.
I have code and the data type I use is fixed-point:
process(clk)
  begin
   if(clk'EVENT and clk ='1') then
      r_amp := to_sfixed (amp,amp'HIGH,amp'LOW);
    r_Va  := resize (r_amp * to_sfixed(Va,0,-31),r_Va);
    r_Vb  := resize (r_amp * to_sfixed(Vb,0,-31),r_Vb);
    r_Vc  := resize (r_amp * to_sfixed(Vc,0,-31),r_Vc);
    V_alpha := resize(r_Va/(to_sfixed (2/3,4,-27)*Udc),V_alpha);
    V_beta  := resize(to_sfixed(0.57735026919,4,-27)*(r_Vb-r_Vc)/(to_sfixed (2/3,4,-27)*Udc),V_beta);
    tmp := resize(to_sfixed(0.57735026919,4,-27)*V_beta,tmp);
    z1x := resize(V_alpha - tmp,z1x);
    z1y := resize(to_sfixed (2,4,-27)*tmp,z1y);
    z2x := resize(z1x+z1y,z2x);
    z2y := resize(to_sfixed (-1,4,-27)*z1x,z2y);
    z3x := resize(z1y,z3x);
    z3y := resize(to_sfixed (-1,4,-27),z3y);
   end if;
   end process;

How to caculate the execution time of all statements in process? if all statements don't finish in 1 clock period, what will happen?
Thank for watching.

A: You define the clock period in ns and the synt/PR-tools tries to place the logic so this time constraint is fulfilled. If it fails you will get a timing error.
If it is not finished within 1 clk the result is undefined.


Q: How to make separate REST controllers for nested resources? Spring Boot I have a REST controller. It processes the resource "messages". And each message can contain comments inside itself.
/api/v1/messages/1
/api/v1/messages/2

/api/v1/messages/1/comments/1
/api/v1/messages/1/comments/2

Here is a code:
@RestController
@RequestMapping("/api/v1/messages/")
public class RestControllerV1 {

    @RequestMapping(value = "{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Message> getMessage(@PathVariable("id") Long messageId) {

    }

    @RequestMapping(value = "{messageId}/comments/{commentId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Comment> getComment(@PathVariable("messageId") Long messageId, @PathVariable("commentId") Long commentId) {

    }
}

It works fine.
But I think that it is not very good to have one big controller for two resources. So I want different controllers (SOLID, S-principle).
MessageControllerV1

and
CommentControllerV1

Is it possible to divide controllers in Spring Boot application?

A: You could have something like:
@RestController
@RequestMapping("/api/v1/messages")
public class MessageController {

    @RequestMapping(value = "{messageId}",
                    method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Message> getMessage(@PathVariable("messageId") Long messageId) {
        ...
    }
}

@RestController
@RequestMapping("/api/v1/messages/{messageId}/comments")
public class CommentController {

    @RequestMapping(value = "{commentId}",
                    method = RequestMethod.GET,
                    produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<Comment> getComment(@PathVariable("messageId") Long messageId,
                                              @PathVariable("commentId") Long commentId) {
        ...
    }
}


Q: I need some help detecting if a browser has access to the internet
Possible Duplicate:
Check if Internet Connection Exists with Javascript?

I have been working on a manual to be sent via CD to a customer.  The owner of my company requires that the manual be split into many subsections as .doc and .docx files.  The table of contents for this manual will be an HTML page, to be run by autorun when the CD is put into the computer.
I can be fairly sure that the computer is a windows computer, but that's about it.  My current thinking is to use this script to take advantage of google to display the word file, but only if the computer is actually connected to the internet.  That way I don't have to rely on the customer having a particular version of word (or having a compatibility pack installed).
From the research I've done, relying on a computer to correctly recognize that a link to a word document should be opened with word is problematic, and has to be resolved at the user end.

A: Have a look at window.navigator.onLine

A: You could try an ajax request to a reliable site.
// THIS IS OUR PAGE LOADER EVENT!
window.onload = function() {
    testConnection();
};

function testConnection(){
    var xmlhttp;

    if (window.XMLHttpRequest){
        xmlhttp=new XMLHttpRequest();
    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            alert(xmlhttp.responseText);
        } else if (xmlhttp.readyState==4){
            alert("NO INTERNET DETECTED!");
        }
    }

    xmlhttp.open("GET","http://www.w3schools.com/ajax/ajax_info.txt",true);
    xmlhttp.send();
}

Now you will have to play around with it for a way to use the response because it is asynchronous, but this will work to test a connection.

A: Previously discussed here: Check if Internet Connection Exists with Javascript? and here: How to know if the network is (dis)connected?.

A: GM_xmlhttpRequest({
  method: "GET",
  url: "http://www.google.com/",
  onload: function(response) {
    if(response.responseText != null) {
       alert("OK");
    } else {
      alert("not connected");
    }
  }
});

*

*second alternative
var HaveConnection = navigator.onLine;


Q: laravel artisan error while clearing config cache when I run php artisan cache:config the command throw the following error
PHP Warning:  require(): Filename cannot be empty in /home/****/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php on line 71
PHP Fatal error:  require(): Failed opening required '' (include_path='.:/usr/share/php') in /home/****/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/LoadConfiguration.php on line 71

I have no idea what causing this and how to fix it.

A: it turns out that there is one suspicious file inside config folder, once it's deleted the artisan command works just fine again.


Q: How can you prove that $1+ 5+ 9 + \cdots +(4n-3) = 2n^{2} - n$ without using induction? Using mathematical induction, I have proved that
$$1+ 5+ 9 + \cdots +(4n-3) = 2n^{2} - n$$
for every integer $n > 0$.
I would like to know if there is another way of proving this result without using PMI. Is there any geometric solution to prove this problem? Also, are there examples of problems where only PMI is our only option?
Here is the way I have solved this using PMI.
Base Case: since $1 = 2 · 1^2 − 1$, the formula holds for $n = 1$.
Assuming that the
formula holds for some integer $k ≥ 1$, that is,
$$1 + 5 + 9 + \dots + (4k − 3) = 2k^2 − k$$
I show that
$$1 + 5 + 9 + \dots + [4(k + 1) − 3] = 2(k + 1)^2 − (k + 1).$$
Now if I use hypothesis I observe.
$$
\begin{align}
1 + 5 + 9 + \dots + [4(k + 1) − 3]
& = [1 + 5 + 9 + \dots + (4k − 3)] + 4(k + 1) −3 \\
& = (2k^2 − k) + (4k + 1) \\
& = 2k^2 + 3k + 1 \\
& = 2(k + 1)^2 − (k + 1)
\end{align}
$$
$\diamond$

A: My favorite proof makes use of a telescoping sum. Let's recall how that works: given a sequence $a_k$ then:
$$
\sum_{k=1}^n (a_{k+1}-a_k)=a_{n+1}-a_1,
$$
because intermediate terms cancel out pairwise.
Just take now $a_k=k^2$ and you have:
$$
\sum_{k=1}^n [(k+1)^2-k^2]=(n+1)^2-1=n^2+2n.
$$
But, on the other hand:
$$
\sum_{k=1}^n [(k+1)^2-k^2]=\sum_{k=1}^n (2k+1)=
\sum_{k=1}^n 2k+\sum_{k=1}^n 1=\sum_{k=1}^n 2k+n.
$$
By equating you get then
$$
\sum_{k=1}^n 2k+n=n^2+2n,
\quad\hbox{that is}\quad
\sum_{k=1}^n 2k=n^2+n
\quad\hbox{and}\quad
\sum_{k=1}^n 4k=2n^2+2n,
$$
so that:
$$
\sum_{k=1}^n (4k-3)=2n^2+2n-3n=2n^2-n
$$

A: If you know the expression for the sum of an arithmetic sequence (or can prove it, it's not too hard, see below) then that's another way. For an arithmetic series with first term $a$ and common difference $d$, the sum to $n$ terms, $S_n$ is given by:
$$S_n = \frac{n}{2}\left(2a+(n-1)d\right)$$ or alternatively, if the last term is $l$ then
$$S_n = \frac{n(a+l)}{2}$$
For your question, we have $a=1$ and $d=4$ so
$$S_n = \frac{n}{2}\left(2+4(n-1)\right) = n(2n-1) = 2n^2-n$$

To get the first expression for $S_n$, write the sum out twice, in opposite orders, and then take their sum:
$$S_n = a + (a+d) + (a+2d) + ... + [a+(n-2)d] + [a+(n-1)d]$$
$$S_n = [a+(n-1)d] + [a+(n-2)d] + ... + (a+2d) + (a+d) + a$$
$\implies$
$$2S_n = [2a+(n-1)d] + [2a+(n-1)d] + ...+[2a+(n-1)d] + [2a+(n-1)d]$$
where there are $n$ terms, so that
$$2S_n = n [2a+(n-1)d] $$
i.e.
$$S_n = \frac{n}{2}\left(2a+(n-1)d\right)$$

A: Let
$$a_k := 4 k - 3 \qquad \qquad \qquad b_k := k - 1$$
Using summation by parts,
$$\begin{array}{rl} \displaystyle\sum_{k=1}^n a_k &= \displaystyle\sum_{k=1}^n a_k (b_{k+1} - b_k)\\ &= \left(a_k \, b_k \,\bigg|_1^{n+1}\right) - \displaystyle\sum_{k=1}^n (a_{k+1} - a_k) \, b_{k+1}\\ &= a_{n+1} \, b_{n+1} - a_1 \, b_1 - \displaystyle\sum_{k=1}^n 4 k\\ &= a_{n+1} \, b_{n+1} - \left(\displaystyle\sum_{k=1}^n (4 k - 3)\right) - 3n\\ &= (4 n + 1) n - 3 n - \displaystyle\sum_{k=1}^n a_k\\ &= 4 n^2 - 2n - \displaystyle\sum_{k=1}^n a_k\end{array}$$
Hence,
$$\displaystyle\sum_{k=1}^n a_k = 2 n^2 - n$$

A: The most straightforward way is of course
$$\frac n2(a+\ell))=\frac n2 \big(1+(4n-3)\big)=\color{red}{2n^2-n}\qquad\blacksquare$$

Another method:
The well-known result of the sum of the first $n$ integers:
$$1+2+3+4+\cdots+n=\frac{n(n+1)}2$$
Subtract $1$ from each term ($n$ in total):
$$0+1+2+3+\cdots+(n-1)=\frac{n(n-1)}2$$
Multiply by $4$:
$$0+4+8+12+\cdots+4(n-1)=2n(n-1)$$
Add $1$ to each term ($n$ in total):
$$1+5+9+13+\cdots+(4n-3)=\color{red}{2n^2-n}\quad\blacksquare$$

A: Below we show how to give a rigorous interpretation of some of the other "proof by picture" answers. Namely, we describe how a $2$-dimensional form of telescopy allows us to view a sequence of rectangles as being built-up layer-by-layer from successive differences of prior rectangles - as if built by a $2$-D printer. Further, applying a simple product rule for differences allows us to simplify these differences into a form more amenable to geometric visualization. This yields a simple and purely mechanical way to generate such pictorial proofs. Moreover, it provides a rigorous interpretation of such proofs using standard techniques for telescopic sums. Finally we mention an analogy with calculus: such telescopic summation is a discrete analog of the Fundamental Theorem of Calculus (but you don't need to know any calculus to understand the much simpler discrete analog that we describe below).
Let $\,f_n,\, g_n\,$ be sequences of naturals and  $\bar R_n$ a sequence of $f_n\times g_n$ rectangles of area $ R_n = f_n g_n.$ Below we recall the product rule for the difference operator $\,\Delta h_n := h_{n+1} - h_n$ then we apply the rule to the special case $\,f_n = n,\ g_n = 2n\!-\!1\,$ in Lynn's picture below.
$$ \large  \color{PaleVioletRed}1 + \color{DarkViolet}5 + \color{DodgerBlue}9 + \dots + \color{LightCoral}{(4n-3)}\, =\, n(2n-1) = 2n^2-n$$

Note: below we give related objects the same color (not related to the coloring above).
$ \begin{eqnarray}{\bf Product\ Rule}\qquad\ \: &&\Delta(f_n g_n ) &=&\ f_{n+1}\ \ \ \Delta g_n &+&\qquad\  \Delta f_n\cdot  g_n\\[.3em]
{\bf Proof}\quad\ \ \,f_{n+1}\ g_{n+1}\ \ &-&\ \ f_n\ g_n &=&\ f_{n+1}(g_{n+1}\!-g_n) &+&\, (f_{n+1}\!-f_n)\, g_n \\[.5em]
{\rm e.g.}\quad\, \smash[b]{\underbrace{(n\!+\!1)(2n\!+\!1)}_{\large R_{\,\Large{n+1}}}}&-&\smash[b]{\underbrace{n(2n\!-\!1)}_{\large R_{\,\Large{n}}}} &=&\ \smash[b]{\underbrace{(\color{#c00}{n\!+\!1})\cdot 2}_{\large \rm arch\ \color{#c00}{sides}}} &+&\quad\ \smash[b]{\underbrace{1\,\cdot\, (\color{#0a0}{2n\!-\!1})}_{\large\rm arch\ \color{#0a0}{top}}}\ \ \ {\rm in\ picture}\\[.2em]
\phantom{} \end{eqnarray}$
So to increment an $\,n\!\times\! (2n\!-\!1)$ rectangle $\bar R_n$ to its successor $\bar R_{n+1}$ of size $\,(n\!+\!1)\!\times\!(2n\!+\!1)$ we can add $\,\color{#c00}{n\!+\!1}$ squares on each $\rm\color{#c00}{side}$ of $\bar R_n$ and $\,\color{#0a0}{2n\!-\!1}\,$ on  $\rm\color{#0a0}{top}$ of $\bar R_n.\,$ For example, let $\,n=3.\,$ In the picture, to increment the $3\times 5$ blue $\bar R_3$ to the $4\times7$ green $\bar R_4$ rectangle, the rule says we can append $\,\color{#c00}{n\!+\!1} = 4$ green squares to each side of blue $\bar R_3,\,$ plus $\color{#0a0}{2n\!-\!1} = 5$ green squares on top of blue $\bar R_3$ yielding the $\,7\times 4$ green arch - which constitutes the (area) difference between the green $4\times7\ (\bar R_4)$ and blue $3\times 5\ (\bar R_3)$ rectangles. Thus the $\rm\color{#c00}{sides}$ and $\rm\color{#0a0}{top}$ of the arch are precisely the summands in the product rule, so the rule shows how to construct  successive differences of $2$-D rectangles $f_n\times g_n$ via differences $\,\Delta f_n,\, \Delta g_n$ of their $1$-D sides.
Thus we can view each rectangle as being built-up layer-by-layer from the differences (= arches) of successive prior rectangles (the separately colorered arches in the picture). Dynamically, we can think of a $2$-D printer building the rectangle arch-layer-by-layer (similar to a $3$-D printer).
The sought equality follows by computing the  $n(2n\!-\!1)$ area of rectangle $\bar R_n$ a second way, using said layer-by-layer inductive construction of $\bar R_n.$ By the rule, the difference arches have area $\,R_{k+1}\!-R_k = 2(\color{#c00}{k\!+\!1)} + \color{#0a0}{2k\!-\!1} = 4k\!+\!1.\,$ Adding these to initial area $= 1_{\phantom{\frac{i}i}}\!\!\!$ of $\,1\!\times\! 1$ $\,\bar R_1$
$\qquad\qquad\qquad\begin{eqnarray} {\underbrace{1}_{\color{#c0f}{\large R_{\Large1}}} +\!\!\! \underbrace{5}_{\large{\color{#48f}{R_{\Large 2}}-\color{#c0f}{R_{\Large 1}}}}\!\! +\! \underbrace{9}_{\large{R_{\Large 3}-\color{#48f}{R_{\Large 2}}}}\!\! +\, \cdots + \!\!\underbrace{4n\!-\!3}_{\large{R_{\Large n}-R_{\Large{n-1}}}} \!=\, \smash{\sum_{\large k\,=\,0}^{\large{{n-1}}}\,(4k\!+\!1)}}\\[-.2em] \end{eqnarray}$
is an equal value for the area of $\,n\!\times\!(2n\!-\!1)\,$ rectangle $\,\bar R_n$. This is the sought equality.
The above LHS sums to $ R_n$ since it is a telescoping sum so $\rm\color{#c0f}{successive}\ \color{#48f}{terms}$ cancel out, which becomes clearer if we reorder the sum by rewriting $\,R_{k+1}-R_k\,$ as $\ {-}R_k\! + R_{k+1}$ yielding
$\qquad \begin{eqnarray}{\underbrace{\color{#c0f}{R_1}\! + (\color{#c0f}{-R_1}}_{\large =\ 0}\! + \underbrace{\color{#48f}{R_2}) + (\color{#48f}{-R_2}}_{\large =\ 0}\! +\underbrace{ R_3) + (-R_3}_{\large =\ 0}\! +\cdots +\underbrace{R_{n-1}) +(-R_{n-1}}_{\large =\ 0}\! + R_n)\, =\, R_n}\\[-.1em]
\end{eqnarray} $
Here lies the hidden use of induction. Though such telescopic cancellation may seem "obvious", it does require rigorous proof. But the inductive step is easy: adding $\, -R_n\! + R_{n+1}$ to both sides of the above statement $P(n)\,$ yields $P(n\!+\!1)\ $ so $\:P(n)\,\Rightarrow\,P(n\!+\!1)\,$ [to be completely rigorous we should also eliminate the ellipses, replacing them by a more precise summation operator].
Many inductive proofs have a very natural telescopic form, and expressing them in this format often leads to great simplification. You can find many examples of telescopy in my prior answers (both in additive and multiplicative form).
Finally we briefly mention that analogy with calculus. The above remarks on telescopic sums show that $\,f(n)\,$ is the sum of its differences. This is the difference analog of the Fundamental Theorem of Differential Calculus, i.e. we have the analogous theorems
$$\begin{eqnarray}
\sum_{k=0}^{n-1}\ \Delta_k f(k)\ \,   &=&\ f(n)-f(0)\\[.2em]
\int_0^x\! D_t f(t)\, dt &=&\ f(x) - f(0)
\end{eqnarray}$$
This is but one small part of the calculus of finite differences, a discrete analog of differential calculus. Many things familiar from calculus have discrete difference analogs, and their proofs are often much simpler (such as the difference product rule above). For example, to verify that  $F(n) = \sum_{k=0}^{n-1} f(k)$
 it suffices to show that they have the same difference and same initial condition, i.e $\,F(n\!+\!1)-F(n) = f(n)\,$ and $F(0) = 0$. When, as in the OP, both $F$ and $f$ are polynomials this reduces to simply checking the equality of two polynomials, which can be done purely mechanically (so no intuition or visual analogies are needed). E.g. for the OP we have $\,F(n) = n(2n\!-\!1)$ so the proof reduces to verifying $\,F(n\!+\!1)-F(n) = 4n\!+1,\,$ and $\,F(n)= 0,\,$ which is trivial polynomial arithmetic - so trivial we can program calculators to perform all such proofs. In fact there are general summation algorithms due to Karr, Gosper and others that are discrete analogs of the Risch-Bronstein integration algorithms implemented in computer algebra systems such as Macsyma, Maple and Mathematica.
Therefore such difference calculus proofs remain completely mechanical even for higher degree polynomials, but generalizing the geometrical picture-based proofs to higher dimensions will prove much more difficult because we typically lack (real-world) intuition for high dimensional spaces.  So difference calculus serves to algebraicize these geometrical proofs in a "calculus" that is so mechanical that it can be performed by a computer - freeing our intuition to work on less trivial matters.

A: $$\sum\limits_{k = 1}^n {\left( {4k - 3} \right)}  = 4\sum\limits_{k = 1}^n k  - 3 \cdot \sum\limits_{k = 1}^n 1  = 4\frac{{n\left( {n + 1} \right)}}{2} - 3 \cdot n = 2n^2  - n$$

A: Hint:
Let $$\begin{alignat}{10}S_n&=&1+&&5+&&9+&\cdots+&(4n-3)\\&=&(4n-3)+&&(4n-7)+&&(4n-11)+&\cdots+&1.\end{alignat}$$
Thus $$2S_n=(4n-2)+(4n-2)+(4n-2)+\cdots+(4n-2).$$

Additional:

As pointed out in the comments, the proof above relies on mathematical induction. So I want to explain what role induction plays in the proof.
For a given number $n$, say $10000$, the proof is valid, though it involves ellipsis, since one can write down all numbers omitted.
Now we claim that the proposition is true for all natural numbers. This would be difficult to prove without using mathematical induction, although I have no idea whether this is possible. Intuitively, we can see that this proof is valid for all natural numbers, but how do we prove that
$$\mathbb{Z}_+=\{n\in\mathbb{N}:S_n=2n^2-n\}?$$
One can start from Peano axioms or axiom of infinity, or other equivalent assumptions, and prove that the set on the right-handed side is $\mathbb{Z}_+$ easily.
I don't think that there exists any proposition we can prove without mathematical induction that it is true for every natural numbers, since when we talk about natural numbers, we are using mathematical induction.

A: Follow the rainbow!
$$ \Large \color{PaleVioletRed}1 + \color{DarkViolet}5 + \color{DodgerBlue}9 + \dots + \color{LightCoral}{(4n-3)} = n(2n-1) = 2n^2-n$$

A: A geometrical proof. A rectangle formed by a sum of gnomons.

A: You can use the “trick” attributed to Gauss for finding the sum of the first $n$ integers. Call your sum $S_n$, and consider this.
$$\begin{align}
&\quad S_n=+1&+ 5 +& \quad\cdots&+(4n-7)&+(4n-3)\\
+&\quad S_n=+(4n-3)&+(4n-7)+&\quad\cdots&+5&+1
\\ &\hline\\
 \quad&2S_n\quad =+\underbrace{(4n-2)}_{1^{st}} &+\underbrace{(4n-2)}_{2^{nd} }+&\quad\underbrace{\cdots}_{3^{rd}\mbox{ to }{(n-2)}^{nd}}&+\underbrace{(4n-2)}_{(n-1)^{st}}&+\underbrace{(4n-2)}_{n^{th}}\\\end{align}$$
Thus $2S_n$ equals $n(4n-2)$, and $S_n=2n^2-n$.

A: Here is a method based upon formal power series. We encode thereby sequences  $\left(a_n\right)_{n\geq 0}$ by formal power series $\sum_{n=0}^\infty a_nx^n$ and show equality of sequences by showing equality of corresponding power series.
Using the summation symbol $\sum$ we claim

The following is valid
  \begin{align*}
\sum_{j=1}^{n}\left(4j-3\right)=2n^2-n\qquad\qquad    n\geq 1
\end{align*}

We encode the sequence
\begin{align*}
\left(\sum_{j=1}^{n}\left(4j-3\right)\right)_{n\geq 1}=\left(1,6,15,\cdots\right)\quad\rightarrow\quad
\sum_{n=1}^\infty\left(\sum_{j=1}^n\left(4j-3\right)\right)x^n=\color{blue}{1}x+\color{blue}{6}x^2+\color{blue}{15}x^3+\cdots
\end{align*}
by the   power series and in the same way we encode
\begin{align*}
\left(2n^2-n\right)_{n\geq 1}=\left(1,6,15,\cdots\right) \quad\rightarrow\quad\sum_{n=1}^{\infty}\left(2n^2-n\right)x^n=\color{blue}{1}x+\color{blue}{6}x^2+\color{blue}{15}x^3+\cdots
\end{align*}
and show the equality of the corresponding power series.

We obtain
  \begin{align*}
\sum_{n=1}^\infty\left(\sum_{j=1}^n\left(4j-3\right)\right)x^n
&=\sum_{n=1}^\infty\left(\sum_{j=0}^{n-1}\left(4j+1\right)\right)x^n\tag{1} \\
&=\sum_{n=0}^\infty\left(\sum_{j=0}^n\left(4j+1\right)\right)x^{n+1} \tag{2}\\
&=\frac{x}{1-x}\sum_{n=0}^\infty\left(4n+1\right)x^n\tag{3}\\
&=\frac{x}{1-x}\left(4\sum_{n=0}^\infty nx^n+\sum_{n=0}^\infty x^n\right)\tag{4}\\
&=\frac{x}{1-x}\left(4(xD_x)\sum_{n=0}^\infty x^n+\frac{1}{1-x}\right)\tag{5}\\
&=\frac{4x^2}{1-x}D_x\left(\frac{1}{1-x}\right)+\frac{x}{(1-x)^2}\tag{6}\\
&=\frac{x(3x+1)}{(1-x)^3}\tag{7}\\
\end{align*}

Comment:

*

*In (1) we shift the index $j$ by one to start with $j=0$

*In (2) we shift the index $n$ by one to start with $n=0$

*In (3) we use the nice fact that summing up elements is encoded in formal power series by multiplication with $\frac{1}{1-x}$. This is due to the Cauchy product formula.

*In (4) we do some rearrangement to be prepared for further steps

*In (5) we use the formula for the geometric power series and also that differentiating a power series and multiplication with $x$ results in
\begin{align*}
xD_x \sum_{n=0}^\infty a_n x^n = \sum_{n=0}^\infty na_nx^n
\end{align*}
Here we denote with  $D_x:=\frac{d}{dx}$ the differential operator.

*In (6) we use the formula for the geometric power series again and multiply out

*In (7) we perform the differentiation and simplify the expression

on the other hand we obtain with similar reasoning
  \begin{align*}
\sum_{n=1}^\infty\left(2n^2-n\right)x^n
&=2\sum_{n=1}^\infty n^2x^n-\sum_{n=1}^\infty nx^n\\
&=2(xD_x)^2\sum_{n=1}^\infty x^n-(xD_x)\sum_{n=1}^\infty x^n\\
&=2(xD_x)^2\frac{x}{1-x}-(xD_x)\frac{x}{1-x}\\
&=\frac{2x(1+x)}{(1-x)^3}-\frac{x}{(1-x)^2}\\
&=\frac{x(3x+1)}{(1-x)^3}\\
\end{align*}
  and the claim follows.

Note: Of course applying this method here is to take a sledgehammer to crack a nut. But these techniques are useful also in more difficult context. See e.g. this answer.

A: By counting dots (of Hexagonal number) in two ways.

On the left: there are four "outer" sides of each hexagon $j = 2, \dots, n$, where each side has $j$ dots but 3 of them are shared, in addition the trivial hexagon $j=1$ is one dot. Therefore, in total there are $\sum_{j=1}^n4j-3$ dots.
On the right: there are $2n-1$ rows (since a hexagon has both top and bottom sides, except the trivial case), and each row adds $n$ dots. Hence $n(2n-1) = 2n^2-n$ dots.
*Despite being geometric, induction may well be needed to justify the counting arguments, as Bill Dubuque noted.

A: There are some very clever answers here, but what if you don't spot the clever trick? It would be nice to be able to mechanically grind out the answer, and in order to do that, you can use the discrete calculus.
So here the problem is to evaluate $ \sum_{1\le i\le n}{4i-3} $. First, expand all powers of the summation variable (here, $i$) into sums of falling powers (by inspection in simple cases, or using Stirling cycle numbers). This is trivial here, since $i = i^{\underline 1}$, so $$ \sum_{1\le i\le n}{4i-3} = \sum_{1\le i\le n}{4i^{\underline 1}-3}. $$ Now, summation of falling powers is just like integration of ordinary powers, except for the upper evaluation limit: $$ \sum_{1\le i\le n}{4i^{\underline 1}-3} = \bigg({4\over2}i^{\underline 2}-3i^{\underline 1}\bigg)\bigg\rvert^{n+1}_1. $$ Expand the falling powers and apply the evaluation limits, getting $$ \bigg({4 \over 2}(n+1)(n) - 3(n+1)\bigg) - \bigg({4 \over 2}(1)(0) - 3(1)\bigg) $$ which can be simplified to $ 2n^2 - n $.
No insight required, just turn the handle and compute!

A: Induction is fundamental to the structure of mathematics. The $``\cdots"$ in the expression $1+ 5+ 9 + \cdots +(4n-3)$ cannot be explained rigorously without using some form of induction. All of the picture proofs here have an implied $``\cdots"$ in them. Similarly, $\text{$\Sigma$-notation}$ and telescoping sums cannot be defined without some form of induction.
Putting that aside, I have always been curious about the process of converting sums to integrals, so I offer the following flawed solution.
Note that
$\int_\limits k^{k+1}(4x-5)\,dx
 = \left. (2x^2-5x) \right|_k^{k+1}
 = (2k^2+4k+2-5k-5)-(2k^2-5k)
 = 4k-3$.
So
\begin{align}
    \sum\limits_{k = 1}^n (4k - 3)
    &= \sum\limits_{k = 1}^n \left( \int_\limits k^{k+1}(4x-5)\,dx \right) \\
    &= \int_\limits 1^{n+1}(4x-5)\,dx
        &\text{(This step requires induction.)} \\
    &= \left. (2x^2-5x) \right|_1^{n+1} \\
    &= (2n^2 + 4n+2 -5n - 5) - (2 - 5) \\
    &= 2n^2-n
\end{align}
Addendum
I got the integrand by solving
$4k - 3 = \int_\limits k^{k+1}(2ax+b)\,dx = 2ak + (a+b)$
The implication is that
\begin{align}
    1 &= u_2 - u_1 \\
    5 &= u_3 - u_2 \\
    9 &= u_4 - u_3 \\
    &\vdots \\
    4k-3 &= u_{k+1} - u_k \\
    &\vdots
\end{align}
where $u_k = 2k^2 - 5k$.
Which converts the sum to the sum of a collapsing series.
This implies Lynn's graphical proof shown below and, though it still requires induction, I thought it shows an interesting way to compute sums.


Q: Select two columns from the sqlite which got unique column and ordered by Date, Time I have two tables which got same columns, examples
TableA

ID, Image, Date ,  Time
0 , 0    , 12/03,  12:33
0 , 1    , 12/03,  12:34
1 , 2    , 12/03,  12:34
1 , 3    , 12/03,  12:35

TableB

ID, Image, Date ,  Time
0 , 4    , 12/03,  12:33
0 , 5    , 12/03,  12:35
2 , 6    , 12/03,  12:34
2 , 7    , 12/03,  12:35

The results I need are
ID, Image, Date ,  Time
0 , 5    , 12/03,  12:35
1 , 3    , 12/03,  12:35
2 , 7    , 12/03,  12:35

This is easy to be done if it was one table
SELECT DISTINCT ID, Image FROM TableA GROUP BY ID ORDER BY Date DESC, Time DESC LIMIT 5

But how could I select from two tables?

A: You can use union all.  This returns the most recent image from the two tables combined for each id:
with ab as (
      select a.* from TableA a union all
      select b.* from TableB b
     )
SELECT ID, Image
FROM (SELECT ab.*,
             ROW_NUMBER() OVER (PARTITION BY id ORDER BY DATE DESC, TIME DESC) as seqnum
      FROM ab
     ) ab
WHERE seqnum = 1;
ORDER BY Date DESC, Time DESC
LIMIT 5;

A: If what you need is the rows with the latest date and time (as your expected results):
with cte as (
  select * from Tablea
  union all
  select * from Tableb
)
select * from cte
where Date || Time = (select max(Date || Time) from cte)
order by id

I assume the dates are always in the format MM/YY and the times hh:mm.
See the demo.
Results:
| ID  | Image | Date  | Time  |
| --- | ----- | ----- | ----- |
| 0   | 5     | 12/03 | 12:35 |
| 1   | 3     | 12/03 | 12:35 |
| 2   | 7     | 12/03 | 12:35 |


Q: pip and multiple python version issues in ubuntu 16.04 I'm deploying a flask server with gulp, and after the gulp command is launched, everything goes fine until the following line:
import flask

as I get the error
ImportError: No module named flask

. Adding the lines before the import command
import sys
print(sys.executable)

I get printed
/usr/bin/python

which, launched on console, corresponds to a python 2.7.12 interpreter, and the command 'import flask' within the console doesn't give any error!!
I can find many python interpreters (2, 3 and virtenvs on my machine) but it seems each of them has flask installed.


Q: take minimum between column value and constant global value I would like create new column for given dataframe where I calculate minimum between the column value and some global value (in this example 7). so my df has the columns session and note and my desired output column is minValue :
session     note     minValue
1       0.726841     0.726841
2       3.163402     3.163402
3       2.844161     2.844161
4       NaN          NaN

I'm using the built in Python method min :
df['minValue']=min(7, df['note'])

and I have this error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: Use np.minimum:
In [341]:
df['MinNote'] = np.minimum(1,df['note'])
df

Out[341]:
   session      note  minValue   MinNote
0        1  0.726841  0.726841  0.726841
1        2  3.163402  3.163402  1.000000
2        3  2.844161  2.844161  1.000000
3        4       NaN       NaN       NaN

Also min doesn't understand array-like comparisons hence your error

A: The preferred way to do this in pandas is to use the Series.clip() method.
In your example:
import pandas

df = pandas.DataFrame({'session': [1, 2, 3, 4],
                       'note': [0.726841, 3.163402, 2.844161, float('NaN')]})

df['minVaue'] = df['note'].clip(upper=1.)
df

Will return:
       note  session   minVaue
0  0.726841        1  0.726841
1  3.163402        2  1.000000
2  2.844161        3  1.000000
3       NaN        4       NaN

numpy.minimum will also work, but .clip() has some advantages:

*

*It is more readable

*You can apply simultaneously lower and upper bounds: df['note'].clip(lower=0., upper=10.)

*You can pipe it with other methods: df['note'].abs().clip(upper=1.).round()


Q: Is there a development environment 'checklist' I can run through before starting to code? I am following Michael Hartl's Rails Tutorial, and have gone through setting up my Development Environment.
I want to quickly check I have everything in order i.e. RVM, Ruby, Rails, Git, etc. all installed in the right place and correctly configured.
If you were picking up a beginner's computer and wanted to understand their development environment and spot anything missing (before running into errors later on), is there a hygiene checklist you go through?
How can I do this?
Thank you!

A: Michael hartls tutorial explains well what you need, but for a short list:

Curl

is needed to get RVM and to test HTTP requests. You will need it to install some requirements also.

Git:

You need it during the tutorial, and to get some gems directly from github.

Any JS platform:

I've choosen NODEJS because it's the easiest one to install, but you can use any of your like: rubyracer, v8...

Ruby interpreter:

Then Install a ruby version. I've always install the last one as default and then install the ones needed in the project.
The gems:

If you are using Ruby > 2.0 install byebug if not install debugger. And rails, the last version as well. If you are following a tutorial install other version.
Any editor:
If you want to learn I recommend you VIM, as you will get used to develop and will learn a nice editor. Learning a nice command line editor is allways payed. So don't be afraid. You can learn sublime or gedit at any moment, but learning VIM is hardest, so start now.
Then databases.

Install whichever you want:
MySQL.
PostgreSQL
SQlite
Or mongo, just to practice.

that should be enough to start the tutorial.


Q: How do I use jQuery sortable for elements in a specific table column only? I am trying to use jQuery's draggable and sortable to sort elements listed inside of a specific column of a table.
The reason is that I essentially want to fit people into timeslots.
I have a table as such:

    1:00 PM

Person 1

    2:00 PM

Person 2

    3:00 PM

Person 3

    4:00 PM

Person 4

I want to make all the divs with the class 'personSortable' sortable into the avaliable time slots. I have looked for an answer but the closest thing i could find was to make the entire row sortable (by making the table the sortable container) - which is not ideal because I can't have the time slots change.
Another idea I had was to create two div wrappers: one with the time slots, and one containing sortable divs for the people, and using the CSS 'float' property to have them line up. Would that be a more ideal approach?

A: Found this and it seems to do the trick if anyone else was interested:
http://www.redips.net/javascript/drag-and-drop-table-content/


Q: How to send any structure as parameter to a method and return the structure? I'm new to Go and I'm seeing if there's a way to have a method that receives any structure as parameter.
I have something like this in my code that is a function that does exactly the same for 5 structures and returns the same structure,  but I don't know if I can do that. I'm wondering if I can do something like this:
type Car struct {
     Model   string `yaml:"Model"`
     Color   string `yaml:"Color"`
     Wheels  int    `yaml:Wheels"`
     Windows int    `yaml:"Windows"`
}

type Motorcycle struct {
     Model    string `yaml:"Model"`
     Color    string `yaml:"Color"`
     Wheels   int      `yaml:Wheels"`
}

type Bus struct {
     Model      string `yaml:"Model"`
     Color      string `yaml:"Color"`
     Wheels     int    `yaml:Wheels"`
     Passengers int    `yaml:"Passengers"`
}

func main () {

    car := GetYamlData(Car)
    motorcycle := GetYamlData(Motorcycle)
    Bus := GetYamlData(Bus)
}

func GetYamlData(struct anyStructure) (ReturnAnyStruct struct){

       yaml.Unmarshal(yamlFile, &anyStructure)

       return anyStructure
}

Is possible to do something like the code above? Actually what I have is something like this:
func main(){
   car, _, _ := GetYamlData("car")
    _,motorcycle,_ := GetYamlData("motorcycle")
    _,_,bus := GetYamlData("bus")
 }

func GetYamlData(structureType string) (car *Car, motorcycle *Motorcycle, bus *Bus){

 switch structureType{

        case "car":
                yaml.Unmarshal(Filepath, car)
        case "motorcycle":
                yaml.Unmarshal(Filepath, motorcycle)
        case "bus":
                yaml.Unmarshal(Filepath, bus)
 }

 return car, motorcycle, bus

}

With the time this will be increasing and it will return a lot of values and I don't want a lot of return values, is there a way to do it with the first code that I posted?

A: You can do it the exact same way yaml.Unmarshal does it, by taking in a value to unmarshal into:
func GetYamlData(i interface{}) {
    yaml.Unmarshal(Filepath, i)
}

Example usage:
func main () {
    var car Car
    var motorcycle Motorcycle
    var bus Bus
    GetYamlData(&car)
    GetYamlData(&motorcycle)
    GetYamlData(&bus)
}


Q: PHP/MYSQL query ranking using secondary tables Working with a ranking algorithm, but I'm getting frustrated with the multiple database calls and data gyrations i'm having to go through to calculate the rank of a specific item, output it in to an array, and then sort by the rank value. Is it possible in MySQL to calculate the rank of a given row based on the data found in other tables?
SELECT key_value FROM table;

Now with the result set I need to rank each item based on various other tables information about those items. So if the output was -
|key_value|
|abcd1    |
|abcd2    |
|abcd3    |

Then based on 'abcd1' values in 3 other tables, I need to rank each entry based on the value divided by total and return the rank and then output it. Is there a way to do all this in a single SQL statement? I've thought about setting up some sql variables and storing different calls and then doing the calculation, but I'm still not sure how you would assign that to the SELECT statements output and rank it accordingly. I'm good with PHP, but i'm kind of a MySQL n00b.
This is probably confusing the way I'm describing it - I can answer more questions to help better explain what I'm trying to do.
Basically each row returned in the original statement is really only relevant to each user based on information stored about that object in 3 other tables. Need to know the best way to use the data in the 3 other tables to rank the relevancy of the data from the first table.

A: The key here is that you need to JOIN your other tables, then ORDER BY some expression on their fields.
SELECT key_value
FROM table
LEFT JOIN table_b on table_b.field = table.key_value
LEFT JOIN table_c on table_c.field = table.key_value
LEFT JOIN table_d on table_d.field = table.key_value
ORDER BY table_b.some_field DESC, (table_c.another_field / table_d.something_else) ASC
;

Depending on the join conditions, you may need to GROUP BY table.key_value or even use subqueries to attain the appropriate effect.


Q: Keras custom loss function causes TypeError
*

*Why when I am trying to create my own loss function using Keras backend

def my_loss(y_true, y_pred):
    return K.mean(K.max(y_true, y_pred) / K.min(y_true, y_pred))

and pass to the Keras neural network, I get
TypeError: Value passed to parameter 'reduction_indices' has DataType float32 not in list of allowed values: int32, int64

*As far as I know, we should use Keras backend functions in custom loss because keras have to differentiate the loss function, but how do they differentiate Max and Min functions that have no derivative?


Q: convert serveral image files to a single djvu file Suppose I have serveral BMP image file, say 001.bmp, 002.bmp,..., 100.bmp.
I want to convert these files to a single djvu file, whose first page is the content of 001.bmp, the second page is the content of 002.bmp...etc.
What is the best way (software) to do this task? I don't want to upload those image file to a server, since it takes too much time. On the other hand, I am not restricted to use BMP files, I can also work with PNG or JPG files.

A: Assuming you are on Linux. Install the djvulibre packages (on Debian/Ubuntu, it's apt install djvulibre-bin), cd to the path where you have your images and run the following:
for x in *.jpg; do c44 -dpi 300 $x; done
djvm -c ../result.djvu *.djvu
ddjvu -format=pdf myfile.djvu myfile.pdf

Sources:

*

*http://www.vitki.net/book/page/converting-jpeg-scans-or-djvu-files-pdf

*http://commons.wikimedia.org/wiki/Help:Creating_a_DjVu_file
On Windows you could follow these steps on cygwin, WSL or similar.

A: For color pages:
pages=pg1.djvu
c44 -dpi 300 pg1.jpg pg1.djvu

For black/white:
for (( i = 2; i <= $N; i++ )); do
  echo $i
  convert pg$i.jpg pg$i.pbm
  cjb2 pg$i.pbm pg$i.djvu
  pages="$pages pg$i.djvu"
done

Join all pages:
djvm -c book.djvu  $pages


Q: Iterate over a directory and filter results based on file extensions I have a function that cycles through a directory and, for each folder within that directory, returns the most recent file. The problem is that the folders contain files of different formats, such as .xlsx and .csv. The file extensions may change per request, so I need to pass them as a parameter to the function, instead of hard-coding the values. How can I pass a list of file extensions as a parameter and select the file according to its extension? Here's what I'm trying to do:
  var extensions = new string[] { ".xlsx", ".csv" };
  var filename = FileSystemService.GetRecentFile(path,  extensions.ToList<string>);

A: If you need the most recent file having one of the extensions required, then this could be a solution:
public FileInfo GetRecent(string path, params string[] extensions)
{
    var list = new List<FileInfo>();

    // Getting all files having required extensions
    // Note that extension is case insensitive with this code
    foreach (var ext in extensions)
        list.AddRange(
          new DirectoryInfo(path)
            .EnumerateFiles("*" + ext, SearchOption.AllDirectories)
            .Where(p =>
              p.Extension.Equals(ext,StringComparison.CurrentCultureIgnoreCase))
              .ToArray());

    return list.Any()
        // If list has somm file then return the newest one
        ? list.OrderByDescending(i => i.LastWriteTime)
              .FirstOrDefault()
        // else return what you please, it could be null
        : null;
}

If you need the most recent file for each extension, then this could be a solution:
public Dictionary<string, FileInfo> GetRecents(string path, params string[] extensions)
{
    var ret = new Dictionary<string, FileInfo>();

    // Getting all files having required extensions
    // Note that extension is case insensitive with this code
    foreach (var ext in extensions)
    {
        var files = new DirectoryInfo(path)
            .EnumerateFiles("*" + ext, SearchOption.AllDirectories)
            .Where(p =>
                p.Extension.Equals(ext, StringComparison.CurrentCultureIgnoreCase))
            .ToArray();

        ret.Add(ext, files.Any()
        ? files.OrderByDescending(i => i.LastWriteTime).FirstOrDefault()
        : null);
    }

    return ret;
}

A: You could first enumerate the Sub-Directories in the provided path, using Directory.EnumerateDirectories. This enumeration excludes the root, so we can add it back to the Enumerable, if required, using the Prepend()1 or Append()1 methods.
Then iterate the collection of extensions, call DirectoryInfo.EnumerateFiles to get Date/Time information about the files in each Directory and filter using the FileInfo.LastWriteTime value and finally order by the most recent and yield return the first result.
I've used a public methods that calls a private worker method, so the public method can be used to provide some more filters or it could be more easily overloaded. Here it's used to provide an option to return the most recent file of all.
It can be called as:
string[] extensions = { ".png", ".jpg", "*.txt" };
var mostRecentFiles = GetMostRecentFilesByExtension(@"[RootPath]", extensions, false);

Specify false to get all the files by type and directory, or true to get the most recent file among all files that matched the criteria.
public IEnumerable<FileInfo> GetMostRecentFilesByExtension(string path, IEnumerable<string> extensions, bool returnSingle)
{
    var mostRecent = MostRecentFileByExtension(path, extensions).Where(fi => fi != null);
    if (returnSingle) {
        return mostRecent.OrderByDescending(fi => fi.LastWriteTime).Take(1);
    }
    else {
        return mostRecent;
    }
}

private IEnumerable<FileInfo> MostRecentFileByExtension(string path, IEnumerable<string> exts)
{
    foreach (string dir in Directory.EnumerateDirectories(path, "*", SearchOption.AllDirectories).Prepend(path))
    foreach (string ext in exts) {
        yield return new DirectoryInfo(dir)
                        .EnumerateFiles($"*{ext}")
                        .Where(fi => fi.Extension.Equals(ext, StringComparison.InvariantCultureIgnoreCase))
                        .OrderByDescending(fi => fi.LastWriteTime).FirstOrDefault();
    }
}

(1) Both Prepend() and Append() require .Net Framework 4.7.1.
  Core/Standard Frameworks all have them.


Q: best backup strategy for laptop I have the following backup strategies(use one or combine multiples): I want to know if there are easier and more robust solutions.  are there additonal strategy I can use?

1. create a image dump onto an external disk.
2. windows built-in recovery and restore function
3. manual&automatic backup of important files onto external disk/cloud.

A: I would advise you to use option 1.
I personally use Acronis Backup and Recovery. Just image the entire contents of your system partition and these of your second one (if you have one).
You will even be able to boot from the external disk seeing your system as you left it when backing-up.


Q: Where should I cp oc binary to on MacOS? In this documentation it says

unpack the archive and move the oc binary to a directory on your PATH

I tried echo $PATH and it returns:

bin:/Library/Frameworks/Python.framework/Versions/3.4/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin

Clearly there are multiple path here, which one should I move cp oc binary to?

A: /usr/local/bin would be the usual choice for user or third-party executables. That way it won't get wiped out when you update the OS.
See also: Where do you keep your own scripts on OSX? - the question is about scripts rather than binaries, but the same logic applies.


Q: Recovering Very Important Lost Data From external hard drive when copying it I was trying to copy back up documents file on my external HD and something didn't work.  When I went back to the external hd to retry the copy, the file was gone.  How can I recover a file on an external hard drive that was deleted by accident?

A: You can use testdisk
install
sudo apt-get install testdisk
attach external drive and run
sudo testdisk
select >[no log]
select external drive from options press >[proceed] >[intel]
and use >[analyze] >[quick search] >[deeper search]
it will analyze drive and give list of files deleted files will be red
you can then copy them to desired place.


Q: in iOS7 how do you stop the First viewcontroller autorotating? I have an app that just needs one screen to autorotate, the first and last screens should be portrait. I can get the last screen to stop rotating using:
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

But this does not work on the first screen, I am using a storyboard with a UINavigationController (I'm thinking that may have something to do with it?)
Any help would be gratefully received. Thanks

A: you may need to subset the UINavigationController and you should use it instead of the standard UINavigationController.
I have done this in my projects, so this cares of the individual UIViewController classes' custom orientations:
.h
#import <UIKit/UIKit.h>

@interface UIOrientationController : UINavigationController { }
@end

.m
@implementation UIOrientationController

- (BOOL)shouldAutorotate {
    return [self.topViewController shouldAutorotate];
}

- (NSUInteger)supportedInterfaceOrientations {
    return [self.topViewController supportedInterfaceOrientations];
}

@end

NOTE: you can extended this class with overriding more methods, if it becomes a requirement in your final code.


Q: Get a clean extract from Wikipedia page I am currently exploring the Wikipedia API and am trying to understand it a bit more.
So I am starting with a Wikidata ID and can find my Wikipedia Title there. I extract the title and am then able to query Wikipedia like e.g. so:
https://en.wikipedia.org/w/api.php?action=query&format=json&titles=Los_Angeles&prop=extracts&exsentences=2&explaintext&exintro

The result would be something like the following:

Los Angeles (US:  (listen) lawss AN-jəl-əs; Tongva: Tovaangar; Spanish: Los Ángeles; Spanish for "The Angels"), often spoken and written as its initialism, L.A., is the largest city in California. With a 2020 population of 3,898,747, it is the second-largest city in the United States, after New York City, and the third-largest city in North America, after Mexico City and New York City.

That way I get the extract as a plain string. Good! The problem is, that it still contains "links" or "strange things", because some links/infos are removed. E.g. the pronunciation of the text ist now gone but the link to (listen) to it is still there as plain text.
I would like to display the text of the page in an iOS App as plain text somehow. Is there a way to get that from the wikipedia API or will I have to do my own magic?


Q: Nested Json using retrofit i want to read sub_category > id, name from json using retrofit
But below code give failed response.

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
  BEGIN_ARRAY at line 2 column 2 path $

My Json....
[
{
    "id": "1",
    "name": "Invamore",
    "sub_category": [
        {
            "id": "101",
            "name": "Banner"
        },
        {
            "id": "102",
            "name": "3 sided Dangler"
        },
        {
            "id": "103",
            "name": "Leaflet"
        }
    ]
},
{
    "id": "2",
    "name": "HUPS",
    "sub_category": [
        {
            "id": "103",
            "name": "Leaflet"
        },
        {
            "id": "104",
            "name": "Posters"
        },
        {
            "id": "105",
            "name": "Sunpack"
        }
    ]
},
{
    "id": "3",
    "name": "Xplore",
    "sub_category": [
        {
            "id": "101",
            "name": "Banner"
        },
        {
            "id": "103",
            "name": "Leaflet"
        },
        {
            "id": "106",
            "name": "Dangler"
        },
        {
            "id": "107",
            "name": "Vertical Streamer"
        }
    ]
},
{
    "id": "4",
    "name": "Xpress",
    "sub_category": [
        {
            "id": "101",
            "name": "Banner"
        },
        {
            "id": "103",
            "name": "Leaflet"
        },
        {
            "id": "108",
            "name": "Streamer"
        }
    ]
},
{
    "id": "5",
    "name": "Matrix",
    "sub_category": [
        {
            "id": "103",
            "name": "Leaflet"
        }
    ]
},
{
    "id": "6",
    "name": "Instabrite",
    "sub_category": [
        {
            "id": "103",
            "name": "Leaflet"
        }
    ]
},
{
    "id": "7",
    "name": "Mileage",
    "sub_category": [
        {
            "id": "107",
            "name": "Vertical Streamer"
        }
    ]
},
{
    "id": "8",
    "name": "Onam Posm",
    "sub_category": [
        {
            "id": "101",
            "name": "Banner"
        },
        {
            "id": "106",
            "name": "Dangler"
        }
    ]
}]

Backend.java
public void pos_func(String user_id) {

    ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

    Call call = apiService.POS_MODEL_CALL(user_id);
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {

        }

        @Override
        public void onFailure(Call call, Throwable t) {
            Log.d("sk_log", "Failed! Error = " + t.getMessage());

        }
    });

}

ApiInterface.java
 @FormUrlEncoded
@POST("pos_distributed.php")
Call<ValuesPos> POS_MODEL_CALL(@Field("user_id") String user_id);

Model : from pojoschema2pojo.com for above JSON
ValuesPos.java
package com.example.shkhan.myapp.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by shkhan on 14/11/16.
 */
public class ValuesPos {
    @SerializedName("id")
    @Expose
    public String id;
    @SerializedName("name")
    @Expose
    public String name;
    @SerializedName("sub_category")
    @Expose
    public List<SubCategory> subCategory = new ArrayList<SubCategory>();

    /**
     *
     * @return
     * The id
     */
    public String getId() {
        return id;
    }

    /**
     *
     * @param id
     * The id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     *
     * @return
     * The name
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @param name
     * The name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *
     * @return
     * The subCategory
     */
    public List<SubCategory> getSubCategory() {
        return subCategory;
    }

    /**
     *
     * @param subCategory
     * The sub_category
     */
    public void setSubCategory(List<SubCategory> subCategory) {
        this.subCategory = subCategory;
    }

}

SubCategory.json
package com.example.shkhan.myapp.model;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Created by shkhan on 14/11/16.
 */

public class SubCategory {

    @SerializedName("id")
    @Expose
    public String id;
    @SerializedName("name")
    @Expose
    public String name;

    /**
     *
     * @return
     * The id
     */
    public String getId() {
        return id;
    }

    /**
     *
     * @param id
     * The id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     *
     * @return
     * The name
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @param name
     * The name
     */
    public void setName(String name) {
        this.name = name;
    }

}

A: The Json contains a list of ValuesPos
The ApiInterface.java call for a single ValuesPos

EDIT
Change the ApiInterface.java to call for a list of ValuesPos
@FormUrlEncoded
@POST("pos_distributed.php")
Call<List<ValuesPos>> POS_MODEL_CALL(@Field("user_id") String user_id);

A: Here is the entire code which work for me... ( Thanks for the help )
Modified two class
ApiInterface.java
@FormUrlEncoded
@POST("pos_distributed.php")
Call<List<ValuesPos>> POS_MODEL_CALL(@Field("user_id") String user_id);

Backend.java
public void pos_func(String user_id) {
        dataArrayList1 = new ArrayList<>();
        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

        Call <List<ValuesPos>> call = apiService.POS_MODEL_CALL(user_id);

        call.enqueue(new Callback<List<ValuesPos>>() {
            @Override
            public void onResponse(Call<List<ValuesPos>> call, Response<List<ValuesPos>> response) {
                Log.d("sk_log", "Status POS Code = successsss");
                dataArrayList1 = response.body();

                //ValuesPos valuesPos = (ValuesPos) response.body();
                Log.d("sk_log", "name==="+dataArrayList1.get(0).getName());
                Log.d("sk_log", "name==="+dataArrayList1.get(0).getSubCategory().get(0).getName());
                CustomerCollection.spinner_pos(dataArrayList1);

            }
            @Override
            public void onFailure(Call<List<ValuesPos>> call, Throwable t) {
                Log.d("sk_log", "Failed! Error = " + t.getMessage());

            }
        });
    }

:)


Q: Toogle slide on a tag and css proprety I'm trying to toggle box shadow property for a tag within #bj-pagination. I would like to achieve effect where box shadow slides from page 1 link to page 2 link when link for page 2 is clicked. Is this complicated?

PREV
1
2
3
4
NEXT

Here I am positioned on page 1. CSS for current page is...
#bj-pagination .current {
    -moz-box-shadow: inset 0 -4px 0 #F6E128;
    -webkit-box-shadow: inset 0 -4px 0 #F6E128;
    box-shadow: inset 0 -4px 0 #F6E128;
    background: #FFF;
    border:1px solid #E4E4E4;
    border-right:none;
}

I would like to when page 2 is clicked animate slide of boxshadow from page 1 link on to page 2 link


Q: A strange result in a simple pthread code I wrote the following code:
#include <pthread.h>
#include <stdio.h>

void* sayHello (void *x){
    printf ("Hello, this is %d\n", (int)pthread_self());
    return NULL;
}

int main (){
    pthread_t thread;
    pthread_create (&thread, NULL, &sayHello, NULL);
    printf("HERE\n");
    return 0;
}

After compiling and running I saw 3 different types of outputs.

*

*Only "Here" was printed.

*"Here" and 1 'sayHello' message.

*"Here" and 2 'sayHello' messages.

Of course I'm OK with the second option, but I don't understand why the 'sayHello' massege can be printed 0 or 2 times if I created only one thread?

A: You can't say when the thread starts to run, it might not start until
after you return from main which means the process will end and the thread with it.
You have to wait for the thread to finish, with pthread_join, before leaving main.
The third case, with the message from the thread printed twice, might be because the thread executes, and the buffer is written to stdout as part of the end-of-line flush, but then the thread is preempted before the flush is finished, and then the process exist which means all file streams (like stdout) are flushed so the text is printed again.

A: For output 1:
your main function only create a pthread, and let it run without waiting for it to finish.
When your main function return, Operating system will collect back all the resources assigned to the pprocess. However the newly created pthread might have not run.
That is why you only got HERE.
For output 2:
your newly created thread finished before main function return. Therefore you can see both the main thread, and the created thread's output.
For output 3
This should be a bug in glibc. Please refer to Unexpected output in a multithreaded program  for details.
To make the program always has the same output
pthread_join is needed after pthread_create


Q: Passing component as a function argument I have a function that take a component as argument, and return another, enhanced component:
import React from 'react';
import { compose } from 'recompose';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { Layout, DarkBar } from 'SharedComponents/Layouts';

const myCreationFunction = ({
  component,
}) => {
  const Route = (props) => {
    // Some code here
    return (
      <Layout>

<Link to={props.path}>LinkTitleHere</Link>

          {React.createElement(component, {
            ...props,
            ...someOtherPropsHere,
          })}
      </Layout>
    );
  }; // The error points here

  const mapStateToProps = () => ({});
  const enhance = compose(
    connect(mapStateToProps, someActionsHere),
  )(Route);

  return enhance;
};

I invoke that function in this way:
import MyComponent from './MyComponent';
import myCreationFunction from './HOC/myCreationFunction';

const Route = myCreationFunction({
  component: MyComponent,
});

When I run it in the development mode, it runs smoothly. But when trying to build the app using npm run build and going through webpack, I get:
Module parse failed: Unexpected token (35:47)
You may need an appropriate loader to handle this file type.
| function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
> var createListRoute = function myCreationFunction((_temp = _ref, _ref2 = <_Layouts.DarkBar>
|           <_Breadcrumbs2.default />
|           <_Layouts.RoundAddButton path={addPath} color="white" />

What am I doing wrong?
Edit #1
It seems that the <Link> is causing the problem. Removing it fixed the problem. Also, when trying to replace it with a tag, I get the same issue. Weird.
Edit #2
I have not resolved this issue because of lack of time. I was trying for 1 hour without any progress and decided to go with button tag and onClick method that uses history to push the new url.
It was and is really weird to me, that a Link or  tag can break something during the build process itself. I will definitely jump deeper into it in some free time.


Q: Restrict product quantity drop down value In all my product have 100 inventory, i want to display drop down in view page. I used below mention code
    <?php echo $this->__('Quantity') ?>
    <select class="input-text qty" name="qty" id="qty">
<?php $i = 1 ?>
<?php do { ?>
<option value="<?php echo $i?>">
<?php echo $i?>
<?php $i++ ?>
</option>
<?php } while ($i <= (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()) ?>
</select>

But problem is it showing all 100 i need only 10 product in that drop down

A: It's not a good practise to calculate the product qty in each loop iteration.
Better query the qty for the product once:
<?php echo $this->__('Quantity') ?>
<select class="input-text qty" name="qty" id="qty">
  <?php $i = 1 ?>
  <?php $productQty = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); ?>
  <?php do { ?>
  <option value="<?php echo $i?>">
    <?php echo $i?>
    <?php $i++ ?>
    </option>
<?php } while ($i <= $productQty && $i <= 10) ?>
</select>

See also "Conquer the 5 Most Common Magento Coding Issues to Optimize Your Site for Performance" on page 7 for more information about how to avoid loading models in a loop.

A: Replace your code with below
    <?php echo $this->__('Quantity') ?>
    <select class="input-text qty" name="qty" id="qty">

        <?php $i = 1 ?>
        <?php $productQty = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); ?>
        <?php do { ?>
            <option value="<?php echo $i ?>">
                <?php echo $i ?>
                <?php $i++ ?>
            </option>
            <?php if ($i == 11) {
                break;
            } ?>
    <?php } while ($i <= $productQty) ?></select>


Q: Why does my PartialView render outside the form tag? I have a view that displays an HTML table of "Room" objects.  Each Room is a row (which is a PartialView) in the table.
The view contains this code:

    @foreach (var item in Model)
    {
        using (Html.BeginForm())
        {
            @Html.Partial("_roomPartial", item)
        }
    }

Model is an IEnumerable<Room>, and _roomPartial is an HTML row containing the properties of a Room.
For some reason, the HTML of the Partial renders after the closing form tag (despite being inside the using block):
<form action="/Room/Index" method="post"></form>

    ...some boring markup...

Other things I tried to make this work:

*

*Used Html.RenderPartial("_roomPartial", item); instead of @Html.Partial.

*Moved the using (Html.BeginForm()) block inside the PartialView

I got the same HTML results each time.
Why does the Partial render outside the form tag?  And how can I get it to render properly?

View:
@model IEnumerable<PatientAssigner.Models.Room>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Index

            @Html.DisplayNameFor(model => model.ID)

            @Html.DisplayNameFor(model => model.isOccupied)

            @Html.DisplayNameFor(model => model.patientComplexityLevel)

@foreach (var item in Model)
{
    using (Html.BeginForm())
    {
        @Html.Partial("_roomPartial", item)
    }
}

_roomPartial:
@model PatientAssigner.Models.Room

        @Html.DisplayFor(room => room.ID)
        @Html.HiddenFor(room => room.ID)

        @Html.EditorFor(room => room.isOccupied)
        @Html.ValidationMessageFor(room => room.isOccupied)

        @Html.DropDownListFor(room => room.patientComplexityLevel,
                                    new SelectList(Enum.GetValues(typeof(PatientAssigner.Models.PatientComplexityLevel)),
                                                    Model.patientComplexityLevel),
                                                    "")
        @Html.ValidationMessageFor(room => room.patientComplexityLevel)

        <input type="submit" value="Save" class="btn btn-default" id="saveBtn" />

A: form tags are not valid between table and tr tags. I suggest changing your view to not have the tr or td tags and do this outside:

    @foreach (var item in Model)
    {

        @using (Html.BeginForm())
        {
            @Html.Partial("_roomPartial", item)
        }

    }

If you need to have a form for every row but want your inputs spread across cells, your only option is to have nested tables like this:

      <form>

            cell1
            cell2
            cell3

      </form>

      <form>

            cell1
            cell2
            cell3

      </form>


Q: python webserver socket programming error # Import socket module
from socket import *

#from socket import AF_INET, SOCK_STREAM, socket
import sys  # In order to terminate the program

# Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)

ipadress=socket.gethostbyname(socket.gethostname())
subnetAdress = '.'.join(ipadress.split('.')[:3]) + '.0'

print(f"ipadress : {ipaddress}")
print(f"subnetAdress : {subnetAdress}")

file = open("permit.txt", 'r', encoding="UTF-8")
permitList = file.readlines()

#

serverSocket = socket(AF_INET, SOCK_STREAM)
# Assign a port number
serverPort = 6789
# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))
# Listen to at most 1 connection at a time
serverSocket.listen(1)
# Server should be up and running and listening to the incoming connections

while True:
    print('The server is ready to receive')
    # Set up a new connection from the client
    connectionSocket, addr = serverSocket.accept()
    # If an exception occurs during the execution of try clause
    # # the rest of the clause is skipped
    # # If the exception type matches the word after except
    # # the except clause is execute
    if subnetAdress+'\n' in permitList:
        print("Warning!!\n it's not permitted")
        continue
    try:
        # Receives the request message from the client
        message = connectionSocket.recv(1024).decode()
        print(message)

        # Extract the path of the requested object from the message
        # # # The path is the second part of HTTP header, identified by [1]
        # filename = message.split()[1]

        print(filename)
        # Because the extracted path of the HTTP request includes
        # # # a character '\', we read the path from the second character
        file = open(filename[1:], 'rb')
        # Store the entire contenet of the requested file in a temporary buffer
        # outputdata = file.read()
        # # Send the HTTP response header line to the connection socket
        header = 'HTTP/1.1 200 OK\n'
        if(filename.endswith(".jpg")):
            filetype = 'image/jpg'
        elif(filename.endswith(".mp4")):
            filetype = 'video/mp4'
        elif(filename.endswith(".wmv")):
            filetype = 'video/wmv'
        elif(filename.endswith(".gif")):
            filetype = 'video/gif'
        elif(filename.endswith(".html")):
            filetype = 'text/html'
        else:
            raise IOError
        header += 'Content-Type: '+str(filetype)+'\n\n'
        print(header)
        connectionSocket.send(header.encode())
        # Send the content of the requested file to the connection socket
        # # # for i in range(0, len(outputdata)):
        # # # #     connectionSocket.send(outputdata[i].encode())
        # # # connectionSocket.send(outputdata)
        connectionSocket.send("\r\n".encode())
        # Close the client connection socket
        # connectionSocket.close()
    except IOError:
        # Send HTTP response message for file not found
        header = 'HTTP/1.1 404 Not Found \n\n'
        connectionSocket.send(header.encode())
        connectionSocket.send(
        "
404 Not Found
\r\n".encode())
        # Close the client connection socket
        connectionSocket.close()
        serverSocket.close()
        sys.exit()
        #Terminate the program after sending the corresponding data

I did this for socket programming
it's hard to explain but I had this error. and I put from socket import
please help me out. I don't know why
I will be dying ..

AttributeError                            Traceback (most recent call last)
c:\Users\taek\python\탐색\네트워크\과제3\IPwebServer.py in <module>
      9 #(SOCK_STREAM is used for TCP)
     10
---> 11 ipadress=socket.gethostbyname(socket.gethostname())
     12 subnetAdress = '.'.join(ipadress.split('.')[:3]) + '.0'
     13

AttributeError: type object 'socket' has no attribute 'gethostbyname'
                                                                                **                                        **

ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ

A: If you use
from socket import *

then you have to use without socket.
gethostbyname(...)
gethostname()
socket(AF_INET, SOCK_STREAM)

If you use
import socket

then you have to use with socket.
socket.gethostbyname(...)
socket.gethostname()
socket.socket(AF_INET, SOCK_STREAM)

BTW: import * is not preferred - see PEP 8 -- Style Guide for Python Code


Q: problems with opening vegan I Installed the package "vegan" but cant seem to run it. When I use the command library(vegan) I get this message
.
Any ideas? I normally just use R cmdr so excuse me if this is a silly question.
Also: Is there any plugin to cmdr for NMDS ordination that I can use instead?

A: That wasn't a "problem". It was only a "message" and not even a particularly dangerous message. It was telling you that the vegan package had a function of the same name as another function in the pls package. If you know that you will be using the scores function with the syntax of the pls::scores function at a later time, then you will need to use it with that form. If you just use scores you will get the function as it exists in pkg:vegan.
I'm being mute about the second part (although it may be premised incorrectly on your anxiety about the message, in which case the question is moot). Multipart questions are discouraged on SO.

A: To answer your question about Rcmdr  plugin for NMDS: check BiodiversityR package that provides an Rcmdr GUI to a part of vegan (plus more).


Q: Приходят крикозябры с Википедии. Как указать кодировку данных которые приходят с этого сайта? Я использую API wikimedia, для формирования запроса на парсинг раздела:https://ru.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Ключевая%20ставка%20в%20России&rvprop=content&rvsection=1&format=xml
Но в Qt приходят крикозябры:
<?xml version=\"1.0\"?><api batchcomplete=\"\"><warnings><main xml:space=\"preserve\">Unrecognized parameter: utf8.</main></warnings><query><pages><page _idx=\"5056059\" pageid=\"5056059\" ns=\"0\" title=\"РљР»СЋС‡РµРІР°СЏ СЃС‚Р°РІРєР° РІ Р РѕСЃСЃРёРё\"><revisions><rev contentformat=\"text/x-wiki\" contentmodel=\"wikitext\" xml:space=\"preserve\">== Р—РЅР°С‡РµРЅРёСЏ РєР»СЋС‡РµРІРѕР№ СЃС‚Р°РІРєРё РІ Р РѕСЃСЃРёРё ==\n{| class="wikitable" style="text-align:center"\n! РџРµСЂРёРѕРґ РґРµР№СЃС‚РІРёСЏ\n! align="center"| % РіРѕРґРѕРІС‹С…\n! РџСЂРёРјРµС‡Р°РЅРёСЏ\n|-\n| 03.02.2013 вЂ” 02.03.2014 || 5,5 || <ref name=cb14all>[http://www.cbr.ru/DKP/keyrate/rates_table_14/ РџСЂРѕС†РµРЅС‚РЅС‹Рµ СЃС‚Р°РІРєРё РїРѕ РѕРїРµСЂР°С†РёСЏРј Р‘Р°РЅРєР° Р РѕСЃСЃРёРё 2014] / РЎР°Р№С‚ Р¦Р‘ Р Р¤.</ref>\n|-\n| 03.03.2014 вЂ” 27.04.2014 || 7,0 || <ref name=cb14all/>\n|-\n| 28.04.2014В вЂ” 27.07.2014В || 7,5 || <ref name=cb14all/>\n|-\n| 28.07.2014В вЂ” 04.11.2014В || 8,0 || <ref name=cb14all/>\n|-\n| 05.11.2014В вЂ” 11.12.2014В || 9,5 || <ref name=cb14all/>\n|-\n| 12.12.2014В вЂ” 15.12.2014В || 10,5В || <ref name=cb14all/>\n|-\n| 16.12.2014В вЂ” 01.02.2015В || 17,0В || <ref name=cb14all/>\n|-\n| 02.02.2015В вЂ” 15.03.2015В || 15,0В || <ref name=cb15all>[http://www.cbr.ru/DKP/keyrate/rates_table_15/ РџСЂРѕС†РµРЅС‚РЅС‹Рµ СЃС‚Р°РІРєРё РїРѕ РѕРїРµСЂР°С†РёСЏРј Р‘Р°РЅРєР° Р РѕСЃСЃРёРё 2015] / РЎР°Р№С‚ Р¦Р‘ Р Р¤.</ref><ref>[http://www.dp.ru/a/2015/01/30/CB_snizhaet_kljuchevuju_stavk/ Р¦Р‘ СЃРЅРёР¶Р°РµС‚ РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ РґРѕ 15В % СЃ РЅР°С‡Р°Р»Р° С„РµРІСЂР°Р»СЏ<!-- Р—Р°РіРѕР»РѕРІРѕРє РґРѕР±Р°РІР»РµРЅ Р±РѕС‚РѕРј -->]</ref>\n|-\n| 16.03.2015В вЂ” 04.05.2015В || 14,0В || <ref name=cb15all/><ref>{{Cite web|url = http://russian.rt.com/article/79319|title = Р¦Р‘ Р Р¤ РїРѕРЅРёР·РёР» РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ РґРѕ 14%|author = |work = |date = 13.03.2015|publisher = RT РЅР° СЂСѓСЃСЃРєРѕРј}}</ref>\n|-\n| 05.05.2015В вЂ” 15.06.2015В || 12,5В || <ref name=cb15all/><ref>{{Cite web|url = http://www.cbr.ru/press/pr.aspx?file=30042015_133103dkp2015-04-30T13_05_21.htm|title = Рћ РєР»СЋС‡РµРІРѕР№ СЃС‚Р°РІРєРµ Р‘Р°РЅРєР° Р РѕСЃСЃРёРё (РїРѕРЅРёР¶РµРЅРёРµ 30 Р°РїСЂРµР»СЏ 2015 c 14,00% РґРѕ 12,50%)|author = |work = |date = |publisher = РЎР°Р№С‚ Р¦Р‘ Р Р¤ }}</ref>\n|-\n| 16.06.2015В вЂ” 02.08.2015В || 11,5В || <ref name=cb15all/><ref>{{Cite web|url = http://www.cbr.ru/press/pr.aspx?file=15062015_133028keyrate2015-06-15T13_25_44.htm|title = РЎР°Р№С‚ Р¦Р‘ Р Р¤. Рћ РєР»СЋС‡РµРІРѕР№ СЃС‚Р°РІРєРµ Р‘Р°РЅРєР° Р РѕСЃСЃРёРё (РїРѕРЅРёР¶РµРЅРёРµ СЃ 16.06.2015 РґРѕ 11,5% РіРѕРґРѕРІС‹С…).|author = |work = |date = |publisher = }}</ref>\n|-\n| 03.08.2015В вЂ” 13.06.2016В || 11,0В || <ref name=cb15all/><ref>{{cite web|url=http://www.cbr.ru/press/PR.aspx?file=31072015_133033keyrate2015-07-31T13_03_35.htm|title=Рћ РєР»СЋС‡РµРІРѕР№ СЃС‚Р°РІРєРµ Р‘Р°РЅРєР° Р РѕСЃСЃРёРё|date=2015-07-31|publisher=Р¦Р‘ Р Р¤}}</ref><ref>[http://www.cbr.ru/press/keypr.aspx Р‘Р°РЅРє Р РѕСЃСЃРёРё СЃРѕС…СЂР°РЅРёР» РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ РЅР° СѓСЂРѕРІРЅРµ 11,00В % РіРѕРґРѕРІС‹С…] / РџСЂРµСЃСЃ-СЃР»СѓР¶Р±Р° Р‘Р°РЅРєР° Р РѕСЃСЃРёРё, 11 РґРµРєР°Р±СЂСЏ 2015 РіРѕРґР° </ref>\n|-\n| 14.06.2016В вЂ” 18.09.2016В || 10,5В || <ref name="cb16all">[http://www.cbr.ru/DKP/keyrate/rates_table_16/ РџСЂРѕС†РµРЅС‚РЅС‹Рµ СЃС‚Р°РІРєРё РїРѕ РѕРїРµСЂР°С†РёСЏРј Р‘Р°РЅРєР° Р РѕСЃСЃРёРё 2016] / РЎР°Р№С‚ Р¦Р‘ Р Р¤.</ref>\n|-\n| 19.09.2016В вЂ” 26.03.2017В || 10,0В || <ref name="cb16all"/><ref name="cb17all"/>\n|-\n| 27.03.2017В вЂ” 01.05.2017В || 9,75 || <ref name="cb17all">[http://www.cbr.ru/DKP/keyrate/rates_table_17/ РџСЂРѕС†РµРЅС‚РЅС‹Рµ СЃС‚Р°РІРєРё РїРѕ РѕРїРµСЂР°С†РёСЏРј Р‘Р°РЅРєР° Р РѕСЃСЃРёРё 2017] / РЎР°Р№С‚ Р¦Р‘ Р Р¤.</ref><ref>{{cite web|url=http://www.cbr.ru/press/PR.aspx?file=24032017_132958keyrate2017-03-24T13_25_44.htm |ti
tle=Р‘Р°РЅРє Р РѕСЃСЃРёРё РїСЂРёРЅСЏР» СЂРµС€РµРЅРёРµ СЃРЅРёР·РёС‚СЊ РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ РґРѕ 9,75% РіРѕРґРѕРІС‹С… |date=2017-03-24 |publisher=Р¦Р‘ Р Р¤ |accessdate=2017-03-27}}</ref>\n|-\n| 02.05.2017 вЂ” 18.06.2017 || 9,25 || <ref name="cb17all"/><ref>{{Cite web|url=http://www.cbr.ru/press/pr.aspx?file=28042017_132959keyrate2017-04-28T13_17_20.htm|title=Р‘Р°РЅРє Р РѕСЃСЃРёРё РїСЂРёРЅСЏР» СЂРµС€РµРЅРёРµ СЃРЅРёР·РёС‚СЊ РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ РґРѕ 9,25% РіРѕРґРѕРІС‹С…|publisher=www.cbr.ru|accessdate=2017-04-28}}</ref>\n|-\n|19.06.2017 вЂ” 17.09.2017 || 9,0 ||<ref name="cb17all"/><ref>{{Cite web|url=http://www.cbr.ru/press/pr.aspx?file=16062017_133001keyrate2017-06-16T13_21_27.htm|title=Р‘Р°РЅРє Р РѕСЃСЃРёРё РїСЂРёРЅСЏР» СЂРµС€РµРЅРёРµ СЃРЅРёР·РёС‚СЊ РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ РґРѕ 9,00% РіРѕРґРѕРІС‹С…|publisher=www.cbr.ru|accessdate=2017-06-16}}</ref>\n|-\n|18.09.2017 вЂ” 29.10.2017 || 8,5 || <ref name="cb17all"/><ref>[http://www.rbc.ru/finances/15/09/2017/59bb99d49a7947fc3cfbf75f Р¦Р‘ СЃРЅРёР·РёР» РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ С‡РµС‚РІРµСЂС‚С‹Р№ СЂР°Р· Р·Р° РіРѕРґ вЂ” Р Р‘Рљ]</ref>\n|-\n|30.10.2017 вЂ” 17.12.2017 || 8,25 || <ref name="cb17all"/><ref>{{Cite news|title=Р¦РµРЅС‚СЂРѕР±Р°РЅРє СЃРЅРёР·РёР» РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ РІ РїСЏС‚С‹Р№ СЂР°Р· Р·Р° РіРѕРґ|url=http://www.rbc.ru/finances/27/10/2017/59f2f7c59a794718d5968f1b|work=Р Р‘Рљ|accessdate=2017-10-27}}</ref>\n|-\n|18.12.2017 вЂ” 11.02.2018 || 7,75 || <ref>[http://www.cbr.ru/press/keypr/?Prev=Y Р‘Р°РЅРє Р РѕСЃСЃРёРё РїСЂРёРЅСЏР» СЂРµС€РµРЅРёРµ СЃРЅРёР·РёС‚СЊ РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ РЅР° 50 Р±.Рї., РґРѕ 7,75% РіРѕРґРѕРІС‹С…]</ref>\n|-\n|12.02.2018 вЂ” 25.03.2018\n|7,5\n|<ref>[http://www.cbr.ru/press/PR/?file=09022018_133031keyrate2018-02-09T13_29_29.htm Р‘Р°РЅРє Р РѕСЃСЃРёРё РїСЂРёРЅСЏР» СЂРµС€РµРЅРёРµ СЃРЅРёР·РёС‚СЊ РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ РЅР° 25 Р±.Рї., РґРѕ 7,50% РіРѕРґРѕРІС‹С…]</ref>\n|-\n|26.03.2018 вЂ” РЅ.РІ.\n|7,25\n|<ref>[http://www.cbr.ru/press/PR/?file=23032018_133000keyrate2018-03-23T13_20_35.htm Р‘Р°РЅРє Р РѕСЃСЃРёРё РїСЂРёРЅСЏР» СЂРµС€РµРЅРёРµ СЃРЅРёР·РёС‚СЊ РєР»СЋС‡РµРІСѓСЋ СЃС‚Р°РІРєСѓ РЅР° 25 Р±.Рї., РґРѕ 7,25% РіРѕРґРѕРІС‹С…]</ref>\n|}</rev></revisions></page></pages></query></api>

Как мне указать кодировку и какую? Чтоб кириллица отобразилась нормально. И где надо указать эту кодировку в ссылки или самой программе?
Сам код парсинга с Википедии:
...
connect(&theLoader, SIGNAL(dataReadyRead(QTextStream*)),this,SLOT(dataUploader(QTextStream*)));
...
void MainWindow::on_pushButton_4_clicked()
{
    theLoader.makeRequest("https://ru.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Ключевая%20ставка%20в%20России&rvprop=content&rvsection=1&format=xml");
}
...

loader.h
#ifndef LOADER_H
#define LOADER_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
class Loader : public QObject
{
    Q_OBJECT
public:
    explicit Loader(QObject *parent = nullptr);
    void makeRequest(QString endPointRequest);
signals:
    void dataReadyRead(QTextStream *data);
public slots:
    void ReadRead(QNetworkReply *reply);
private:
    QNetworkAccessManager *m_manager =new QNetworkAccessManager(this);
};

#endif // LOADER_H

loader.cpp
#include "loader.h"

#include <QDebug>
#include <QTextStream>
#include <QSslError>
#include <QRegExp>

Loader::Loader(QObject *parent) : QObject(parent)
{
    connect(m_manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(ReadRead(QNetworkReply*)));
}

void Loader::makeRequest(QString endPointRequest)
{
    m_manager->get(QNetworkRequest(QUrl(endPointRequest)));
}

void Loader::ReadRead(QNetworkReply *wikirep)
{
    QTextStream repStream(wikirep);
    //QString str = repStream.readAll();
    qDebug() << "Response Received:\n" << repStream.readAll();
    //wikirep->deleteLater();

    //QRegExp rx("([\d]{2}\.[\d]{2}\.[\d]{4}...[\d]{2}\.[\d]{2}\.[\d]{4}).{4}([\d,]{2,4})/gm");
    QRegExp rx("cbr");
    int pos = rx.indexIn(repStream.readAll());
    QStringList list = rx.capturedTexts();

    //emit dataReadyRead(&repStream);
}

Кто будет тестировать код ,для того чтоб спарсить данные с Википедии, надо выполнить указания по ссылки и скопировать две библиотеки из установленной программы лежащие в папке bin, после чего подключить их в pro файле LIBS += -Llibeay32 -Lssleay32

A: Для определения кодировки скачиваемой страницы можно воспользоваться вот этим ресурсом. Теперь мы знаем кодировку скачиваемой страницы  - utf-8.
Далее, в методе ReadRead я бы не стал создавать QtextStream, а читал бы массив байт из ответа, а потом преобразовал его в строку с кодировкой utf-8(для QtextStream тоже можно указать кодировку с помощью метода setCodec, но я не вижу здесь смысл его использовать)
void Loader::ReadRead(QNetworkReply *wikirep)
{
    QByteArray byteStr = wikirep->readAll();
    QString str = QString::fromUtf8(byteStr);
    qDebug() << "Response Received:\n" << str;
    //wikirep->deleteLater();

    //QRegExp rx("([\d]{2}\.[\d]{2}\.[\d]{4}...[\d]{2}\.[\d]{2}\.[\d]{4}).{4}([\d,]{2,4})/gm");
    QRegExp rx("cbr");
    int pos = rx.indexIn(str);
    QStringList list = rx.capturedTexts();

    //emit dataReadyRead(&repStream);
}

Также для вас думаю может быть полезен ответ на похожий вопрос.