text:
Q: Why use var instead of the class name?
Possible Duplicate:
What's the point of the var keyword?
What advantages does using var have over the explicit type in C#?

I always see other people producing code like:

var smtp = new SmtpClient();

But why use var instead of SmtpClient in this case? I ALWAYS use

SmtpClient smtp = new SmtpClient();

Is var more efficient? Why use var instead of the actual variable type? Am I missing something?

A: No it isn't more efficient. It's the same thing of write explicitly the type. Infact it is good programming write the type of the variable instead of use var because it makes the code more readable.
So:
var smtp = new SmtpClient();

And:
SmtpClient smtp = new SmtpClient();

Are the same thing wrote in two different ways.

A: Imagine this.
Dictionary<Dictionary<String, String>, String> items = new Dictionary<Dictionary<String, String>, String>();

var is useful for things like that.
var items = new Dictionary<Dictionary<String, String>, String>();

Much simpler. The point of var is the same as auto in C++ 11, the compiler knows the type so why must we repeat ourselves so much. I personally use var rarely, but only for lengthly declarations. It's just syntactic sugar.

A: It's syntactic sugar:
var smtp = new SmtpClient();

is equal to:
SmtpClient smtp = new SmtpClient();

It's a new feature in C# 3.0, called type inference.

A: No, it's not about efficency, it's only about code-writing style.
Considering that it's about a style, this rule could not be applied always.
Immagine following snipplet:
var myVar = Some3dPartFunction() , what is the type of myVar?
It's not absolutely clear, and not good, from code-style point of view, to write in this way.
In short, choose appropriate writing in a clever way.


text:
Q: Minecraft: Issues concerning chunk refreshing I'm playing Minecraft: Java Edition version 1.11 on PC. I was designing a flying machine with observers and pistons when I observed this bug.
Whenever the flying machine sets off, it creates randomly, some observers and pistons, throughout its path. These components can be broken but will not drop as an item.
Is this problem related to some issues in chunk loading/refreshing?
Reloading the save removes all these randomly created components.
I've uploaded some screenshots of these instances

Is there a solution to fix this issue?

A: These aren't actual blocks, these are only visual bugs, so-called "ghost blocks". To test, you can for example try to place a block on them and you'll see that it instead places the block where the ghost block was. A lot of bugs that caused ghost blocks were fixed since 1.11, so I recommended playing a more recent version.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SystemC - Can I retrieve clock period from sc_in_clk port? Can I retrieve the clock period through sc_port?
The following code doesn't work. I'd like to call method period() defined in sc_clock.
sc_in_clk clk;

*clk.get_interface()->period();

A: You could use dynamic_cast<> to cast the sc_interface returned by get_interface() as an sc_clock:
#include <iostream>
#include <systemc>

using namespace std;
using namespace sc_core;

SC_MODULE(A) {
    sc_in_clk clk;

    SC_CTOR(A) {}

    void start_of_simulation() {
        sc_clock *channel = dynamic_cast<sc_clock *>(clk.get_interface());
        cout << name() << ": period is "
             << (channel ? channel->period() : SC_ZERO_TIME) << endl;
    }
};

int sc_main(int argc, char *argv[]) {
    A a1("a1");
    A a2("a2");

    sc_clock clk("clk", 3.0, SC_NS);
    sc_signal<bool> fake_clk("fake_clk");

    a1.clk(clk);
    a2.clk(fake_clk);

    sc_start(10, SC_NS);

    return EXIT_SUCCESS;
}

This works because sc_clock is a subclass of sc_interface.
If dynamic_cast<> succeeds, then a valid sc_clock pointer is returned. If it fails, NULL is returned.


text:
Q: Current is same everywhere in the circuit Why don't charges pile up at the vicinity  of resistor as charge flowing out of resistor is slow at one side of resistor but on the other side charge starts to pile up to enter resistor?

A: Yes, when electric charge flows in a closed circuit, the current remain same everywhere in it.
The electric charge leaving one end of a conductor is equal to the charge entering the other end of the conductor. Thus no charge stores or piles up in a conductor when an electric current flows through it. This also satisfies the Law of Conservation of Charge for a circuit assuming it as an isolated system.

A: Because the current flowing out is not faster than the current flowing in.
If charges moved faster when exiting the resistor, then they will soon deplete. They will all soon have left that end of the resistor. Then we'll have to wait until a new charge has flown through before we see another one moving fast away from the resistor. In other words, we will have a queuing up of charges flowing in but no of charges flowing out.

*

*Those charges flowing in are moving slower, but they are also many, many more.

*Those charges flowing out are moving faster, but they are also much fewer.

These two effects will have to balance out. The current is the total charge moving past a point per second and with faster but fewer charges we can still reach the same current as with more but slower charges.
We know that the current must be the same at all points along a non-split wire because of Kirchhoff's current law. It simply says that if there is no building up of charges, no accumulation, anywhere then in-going current per second must equal all out-going current per second. (If more flows in than out, then we have a built-up - if more flows out than in, then soon there will be no more to flow out and it.)

A: They actually do pile up
But it is not because charges move slowly at one end and faster at the other. current remains same throughout
even before electrons start moving and making a current, something called electric Force (its actually electric field but not sure you know that) propogates from one end of battery to the other end at a very high speed. It is only after this Force reaching a point, the charges at that point start to move. If the speed at which this force travelled was small, we would see current slowly building up from the ends and finally, all charges moving with same speed. (ie:same current) So, for a smal time, current is not. constant throughout. But in reality the speed with which this force travels is the speed of light and hence, the small time for which current is different is negligibly small. So current is constant throughout
why charges accumulate?
It is becuse there exist a voltage across a Resistor. A voltage across the resistor can only be generated by charge differences across its ends.


text:
Q: principal ideal notation Let $I = \{f(X) = \mathbb{C}[X] | f(0) = f(1) = f(−1) = 0\}$. Then $I$ is an ideal of $\mathbb{C}[X]$.
Deduce that $I = (X^3 −X)$ is the principal ideal generated by $X^3 −X$.
Can someone write $(X^3 −X)$ in set notation because I have no idea what it actually is.

A: $$\langle X^3 - X\rangle = \{p(X)\dot\, (X^3 - X); p(X) \in \mathbb K[X]\}$$ is  the ideal generated by $X^3 - X \in \mathbb K[X]$.


text:
Q: Ошибка 500 при переносе сайта. на зеркале все работает без проблем Есть сайт на wordpress, которому необходим перенос на другой хостинг c домена на латинице на домен на кириллице.
На 2ом хостинге создан и привязан домен с кириллическим доменным именем и создана соответствующая папка (на латинице). Перенес сайт, бд, настроил переконвертацию доменного имени с помощью сервиса. Как итог: в админку пускает, стандартную тему отображает, а вот в созданной вызывает 500 ошибку - в логах:

[24-Nov-2016 07:37:39] PHP Parse error: syntax error, unexpected '[', expecting ')' in /home/name/wp-content/themes/themes-name/front-page.php on line 116
  [24-Nov-2016 07:38:57] PHP Parse error: syntax error, unexpected '[', expecting ')' in /home/name/wp-content/themes/themes-name/front-page.php on line 116

в этом месте - 116 строка <?php $section_gates = new WP_Query([:
<?php $section_gates = new WP_Query([
                        'post_type'     => 'section_gates',
            'name'     => 'sektsionnye-vorota',
                        'post_status'   => 'publish',
                        'posts_per_page'=> -1,
                        'order'         => 'ASC'
                    ]);
                while($section_gates->have_posts()):
                     $section_gates->the_post();

На латинском зеркале все работает без проблем и ошибок при этом.
В чем причина, как найти и устранить ошибку?

A: На латинском зеркале у вас версия PHP 5.4+ а на "проблемном" версия ниже. Проблема возникает из-за того, что только начниная с версии 5.4 стали поддерживаться литералы массивов. То есть теперь можно писать так:
$arr = [1, 2, 3, 4];

На более ранних версиях нужно писать так:
$arr = array(1, 2, 3, 4);

Решить проблему можно так (в порядке сложности):

*

*Сменить версию PHP (многие хостеры это позволяют);

*Сменить хостера;

*Поменять все упоминания литеральной записи массива на array(...).


text:
Q: How would i go about having a fixed header with a horizontally scrolling body? Problem
I want to create a header which is fixed which i can do using CSS
#Header{
        position:fixed;
       }

However i can't seem to get the rest of the page to scroll horizontally!
This is my markup so far.

Bass Clef Photography

Passion 4 Live Music & Passion 4 Photography

Home

Music Gallery

About

Clients

Contact

Members

It's the div photoframe i wish to scroll horizontally. The tricky thing is the "photoframe" contains images that don't have a fixed width. so i don't want to set its CSS property with a fixed width, like so.
#photoframe
{
Width:1000px;
}

Any help would be greatly appreciated!

A: #photoframe {
    overflow-x: auto;
}

Put up a jsfiddle with what I think you were trying to achieve.


text:
Q: How do you allow multiple file uploads on an internal windows-authentication intranet? I have a couple of solutions, but none of them work perfectly.
Platform

*

*ASP.NET / VB.NET / .NET 2.0

*IIS 6

*IE6 (primarily), with some IE7; Firefox not necessary, but useful

Allowed 3rd Party Options

*

*Flash

*ActiveX (would like to avoid)

*Java (would like to avoid)

Current Attempts
Gmail Style: You can use javascript to add new Upload elements (input type='file'), then upload them all at once with the click of a button. This works, but still requires a lot of clicks. (I was able to use an invisible ActiveX control to detect things like File Size, which would be useful.)
Flash Uploader: I discovered a couple of Flash Upload controls that use a 1x1 flash file to act as the uploader, callable by javascript. (One such control is FancyUpload, another is Dojo's Multiple File Uploader, yet another is one by darick_c at CodeProject.) These excited me, but I quickly ran into two issues:

*

*Flash 10 will break the functionality that is used to call the multiple file upload dialogue box. The workaround is to use a transparent flash frame, or just use a flash button to call the dialogue box. That's not a huge deal.

*The integrated windows authentication used on our intranet is not used when the Flash file attempts to upload the files, prompting the user for credentials. The workaround for this is to use cookieless sessions, which would be a nightmare for our project due to several other reasons.

Java Uploader: I noticed several Java-based multiple-file uploaders, but most of the appear to cost money. If I found one that worked really well, I could arrange to purchase it. I'd just rather not. I also don't like the look of most of them. I liked FancyUpload because it interacted with html/javascript so that I could easily style and manage it any way I want.
ActiveX Uploader: I found an ActiveX solution as well. It appears that ActiveX will work. I would just write my own instead of buying that one. This will be my last resort, I think.
Resolution
I would love to be able to use something like FancyUpload. If I can just get by the credentials prompt some way, it would be perfect. But, from my research, it appears that the only real workaround is cookieless sessions, which I just can't do.
So, the question is: Is there a way to resolve the issues presented above OR is there a different solution that I have not listed which accomplishes the same goal?

A: I don't think there is any work around for the integrated windows authentication.  What you could possibly do is save the files to a generic unprotected folder and, in the case of swfupload, use a handler to move the file when its fully uploaded

A: You could try SWFUpload as well - it would fit in your Flash Uploader "category".

A: Our company uses https://ajaxuploader.com which supports this feature.

A: In Internet Explorer, FileReference.upload (flash upload) will send cookies along as well.
This behavior breaks only when running in other browsers.

A: @davidinbcn.myopenid.co: That's basically how I solved this issue. But, in an effort to provide a more detailed answer, I'm posting my solution here.
The Solution!
Create two web applications, or websites, or whatever.
Application A is a simple web application.  The purpose of this application is to receive file uploads and save them to the proper place. Set this up as an anonymous access allowed. Then make a single ASPX page that accepts posted files and saves them to a given location. (I'm doing this on an intranet. Internet sites may be exposing themselves to security issues by doing this. Take extra precautions if that is the case.) The code behind for this page would look something like this:
Dim uploads As HttpFileCollection = HttpContext.Current.Request.Files
If uploads.Count > 0 Then
    UploadFiles(uploads)
Else
    result = "error"
    err = "File Not Uploaded"
End If

Application B is your primary site that will allow file uploads. Set this up as an authenticated web application that does not allow anonymous access. Then, place the FancyUpload (or similar solution) on a page on this site. Configure it to post its files to Application A's upload ASPX page.


text:
Q: Хочу чтобы при добовления какой либо статьи в Django они шли не в низ друг за другом а в право потом в низ ну на блоки раздел Если че использую Jinja, bootstrap3, python(Djnago), css , html, Jquery

wrapper.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="witdh=device, initial-scale=1.0">

    <title>Rapter</title>
      {% load staticfiles %}

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">

    <link rel="stylesheet" href="{% static 'css/main.css' %}"type="text/css">

    <link rel="stylesheet" href="css/font-awesome.min.css">

          <button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

          </button>

Главная

Игры

Товары

О нас

<button class="btn btn-success btn-lg" data-toggle="modal" data-target="#Enter">Войти</button>
          <button class="btn btn-info btn-lg" data-toggle="modal" data-target="#Register">Зарегестрироваться</button>

            {% block content %}

            {% endblock %}

          <button class="close" data-dismiss="modal">X</button>

Войти

Введите Логин или E-mail

          <input type="text" class="form-control centered" placeholder="Email or Login">

Введите Пороль

          <input type="password" class="form-control centered" placeholder="password" >

          <button class="btn btn-info btn-lg" id="EnterButton">Войти</button>

           Забыли пароль

      <button class="close" data-dismiss="modal">X</button>

Регестрация

Введите Логин или E-mail

      <input type="text" class="form-control centered" placeholder="Email or Login">

Введите Пороль

      <input type="password" class="form-control centered" placeholder="password" >

Повторите пороль Пороль

      <input type="password" class="form-control centered" placeholder="password" >
      <button class="btn btn-info btn-lg" id="RegisterButton">Зарегестрироваться</button>

products.html (сюда надо блоки добовлять)
{% extends "ShapeHtml/wrapper.html" %}

{% block content %}

    {% for product in object_list  %}

 {{product.title}}

{{products.date|date:"d-m-Y"}}

    {% endfor %}

{% endblock %}

main.css
@import url('https://fonts.googleapis.com/css?family=Lato|Raleway&display=swap');
@import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');

body {
  background-color: #77C4C4;
  font-family: "Lato" ;
  font-weight: 300;
  font-size: 16px;
  color: #555;

  -webkit-font-soothing: antialiased;
  -webkit-overflow-scrolling: touch;

  margin-top: 70px;

}

h2,h4,h5,h6{
  font-family: "Lato";
  font-weight: 300;
  color:#333;
}

h3{
  font-family: 'Ramabhadra', sans-serif;
  font-weight: 400;

}

h1{
  font-family: 'Oswald', sans-serif;
  font-weight: 500;
  color:#333;
}

p{
  line-height: 28px;
  margin-bottom: 25px;
}

.centered{
  text-align: center;
}

a{
  font-family: "Oswald";
  font-size: 30px;
}

a:hover , a:focus{
  color:#7b7b7b;
  text-decoration: none;
  outline: 0;
}

hr {
  height: 1px;
  border: 0;
  border-top:1px solid #ccc;
  margin: 1em 0;
  padding:0;
}

li {
  margin-top:60px;
  margin-left: 10px;
}

.li:active, .li:hover{
  background-color: #ff7878 ;

}

.navbar{
  margin-top: -80px;
  font-weight:800;
  font-size:14px;
  padding-top:15px;
  padding-bottom: 15px;
}

.navbar-inverse{
  background:#005367;
  border-color: #2d2d2d;
}

.navbar-inverse .navbar-brand{
  color: #999 ;
  font-weight: bolder;
  font-size: 22px;
  letter-spacing: 1px;
}

#headrwrap{

  margin: 300px ;

}

#Buttons{
  margin-left: 100px
}

.form-control{
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius:4px;
  box-shadow: 0 1px 1px rgba(0,0,0,0.075) inset;
  color: #555 ;
  display: block;
  font-size: 14px;
  height: 34px;
  line-height: 1.42857;
  padding: 6px 12px;
  width: 50%;
  margin-top: 20px;
  margin-left: 25%;
}

#Entered{
  height: 500px;
}

#EnterButton{
  margin-top: 50px;
  margin-left: 250px;
}

#enterVK{
  margin-left: 160px;
}

#ForgetPasswords{
  margin-left:240px;
}

#ForgetPasswords:hover{
  color: #DE4E5F;
  text-decoration:underline;
}

#containerEMail{
  margin-left: 25%;

}

.EnterText{
  margin-left: 150px;
}

.close{
  margin-right: 10px;
  margin-top: 10px;
}

#RegisterButton{
  margin-left: 180px;
  margin-top: 30px;
}

#H1changeColor{
    color:white;
}

#next-block{
  width: 300px;
  height: 60px;
  background:#f1f1f1;
  float:left;
  margin-left: 400px;
  padding-top:10px
  text-align:center;
}

A: Я СМОГГГГГГГГГГГ
products.html
{% extends "ShapeHtml/wrapper.html" %}

{% block content %}

    {% for product in object_list  %}

 {{product.title}}

    {% endfor %}

{% endblock %}

и это добавить ваш css
#next-block{
    width:300px;
    height:400px;
    margin-left:30px;
    float:left;
}


text:
Q: Find the Subextensions of $\Bbb Q(\sqrt2, \sqrt3, \sqrt5)/\Bbb Q$ As an exercise for myself I want to find the subextensions of $\Bbb Q(\sqrt2, \sqrt3, \sqrt5)/\Bbb Q$.
I know that it has Galois group $\Bbb Z/2\Bbb Z$x$\Bbb Z/2\Bbb Z$x$\Bbb Z/2\Bbb Z$, and this has 8 subgroups (since $2^3=8$).
This means that $\Bbb Q(\sqrt2, \sqrt3, \sqrt5)/\Bbb Q$ must have exactly 8 extensions, but I find more, so I must assume that some are equivalent.  The possibilities I consider are:
$\Bbb Q$, $\Bbb Q(\sqrt2)$, $\Bbb Q(\sqrt3)$,$\Bbb Q(\sqrt5)$, $\Bbb Q(\sqrt6)$, $\Bbb Q(\sqrt{10})$, $\Bbb Q(\sqrt{15})$, $\Bbb Q(\sqrt{30})$, $\Bbb Q(\sqrt2, \sqrt3)$, $\Bbb Q(\sqrt2, \sqrt5)$, $\Bbb Q(\sqrt3, \sqrt5)$, which makes 11 different subfields.  I assume I have to show that some fields are equivalent, but how would one approach that?  Thanks in advance!


text:
Q: Unable to use sum function inside dplyr::mutate I am trying to create a new variable that, for each row, sums the values of previous variables. Generically:
dataset %>%
select(var1, var2, var3) %>%
mutate(var4 = sum(var1:var3))

I get the error "numerical expression has x elements: only the first used", where x is the number of observations in the dataset. Initially I thought the error was related to the size of my dataset, which contains observations in the low thousands. But I get the same error when I adapted the above code to the built-in mtcars dataset. I also verified that all the values of the variables I want to sum are of class / mode numeric, and that there are no NAs. I appreciate any insight.


text:
Q: How does an optical mouse detect movement?

Can anyone explain it ?

A: The optical mouse has a chip that has a lo-res camera in it, with a DSP. The DSP picks off certain high-contrast bits of the image in one frame, and looks at how they've tracked across the field of view in the next image. From this it infers X and Y motion, and reports the position change to the computer through a USB interface. The LED provides illumination to increase contrast on the surface, so there will be more bright spots the DSP can pick off.


text:
Q: Google Maps V3 Authentication & Duplication Issue I am trying to implement google maps onto our website.
The website baiscally has a page with sections on the page that can load dynamically via jquery.load().
In one of these sections another page loads via the jQuery.Load() function  which fills the content for a popup window (a div with fancy styling)
Now in the div i am making use of the JqueryUI tab control and one of the tabs contain the google maps map.
Please see my code:
<script type="text/javascript"
            src="http://maps.googleapis.com/maps/api/js?key=xxxxxxxxxx..&sensor=false&v=3&callback=initialize">
</script>

 <script>
        document.domain = '<?php echo $_SERVER["HTTP_HOST"]; ?>';

        $(function() {
            $("#tabs").tabs();
        });

        function initialize() {
            var mapOptions = {
                zoom: 8,
                center: new google.maps.LatLng(-34.397, 150.644)
            };

            var map = new google.maps.Map(document.getElementById('map-canvas'),
                    mapOptions);
        }

        function loadScript() {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = 'http://maps.googleapis.com/maps/api/js?key=..........&sensor=false&v=3&callback=initialize';
            document.body.appendChild(script);
        }

        window.onload = loadScript;

    </script>

The map loads successfully but I get the following errors:
 1. Warning: you have included the Google Maps API multiple times on this page. This may cause unexpected errors.
 2. Exceeding connection limit - which is impossible
Any help?

A: Just remove first script tag.
i.e.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/jskey=xxxxxxxxxx..&sensor=false&v=3&callback=initialize">

Because "loadScript()" is already loading google map api.


text:
Q: Can relative path be changed? If open some file using my program it seems, that the current relative path is set by shell not to the executable folder but to the file's folder.
It is uncomfortable for me, because I need to specify paths to program's icons or something else stuff absolutely, i.e. module path + icon_name.
Can it be done?

A: Just invoke GetModuleFileName and pass NULL as the first parameter to get the path to your EXE.  Then do the appropriate string parsing or use Shell APIs to convert that to the path to your module.
wchar_t szPathToMyExe[MAX_PATH];
GetModuleFileName(nullptr, szPathToMyExe, MAX_PATH);
wstring path = szPathToMyExe;            // "C:\Path\To\My\Program.exe"
auto pos = strPath.find_last_of("\\");
wstring directory = path.substr(pos);    // "C:\Path\To\My"


text:
Q: COUNTIFS Formula with Criteria to match current year and month I'm trying to only count cells based on a date value being equal to the current month and year. Does an operator for this exisit? I tired to replace the ">=" below to "=" but it returned no values. In contrast he ">=" operator is returning more values that it should. Does anyone know how i can revise the formula below to only count the cell range if values in Cells P21:P502 are equal to the current Month and Year? The last two criteria in the formula below is all I cant seem to get working right
=COUNTIFS('CSAT Risk Register'!$O$21:$O$502,"*",'CSAT Risk Register'!$L$21:$L$502,B6,'CSAT Risk Register'!$I$21:$I$502,"*",'CSAT Risk Register'!$P$21:$P$502,">43831",'CSAT Risk Register'!$P$21:$P$502,"=="&YEAR(TODAY()),'CSAT Risk Register'!$P$21:$P$502,"=="&MONTH(TODAY()))

A: *

*Excel does not use == just one will suffice.

*You need to bookend the dates, use EOMONTH().

=COUNTIFS('CSAT Risk Register'!$O$21:$O$502,"*",'CSAT Risk Register'!$L$21:$L$502,B6,'CSAT Risk Register'!$I$21:$I$502,"*",'CSAT Risk Register'!$P$21:$P$502,">="&EOMONTH(TODAY(),-1)+1,'CSAT Risk Register'!$P$21:$P$502,"<"&EOMONTH(TODAY(),0)+1)


text:
Q: can't create startup disk in ubuntu when selecting fedora iso I can't select a fedora image to create a bootable usb stick. It works with ubutu and gnome ubuntu but not with fedora. Does the ubuntu startup creator only work with ubuntu isos?

A: Ubuntu Startup disk maker able to create Debian based OS like Lubuntu,Xubuntu,Kubuntu,Kali,Debian and Ubuntu and others similar "Debian bases distros". Not support distros like fedora,Cent OS and Open SUSE.
Reason described well here

A: Have you tried another app to do it? UNetBootIn is a good one (and does not require any installation, just download, unpack, launch and go). I remember the same issue when I'm tried to create a Live USB with a non-Ubuntu distro.


text:
Q: How to use a key generated by KeyGenerator at a later time? I'm writing a program which does both encryption and decryption in DES. The same key used during the encryption process should be used while decrypting too right? My problem is encryption and decryption are run on different machines.  This is how the key is generated during the encryption process.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();

So ,I thought I'll write the key to a file. But looks like I can typecast a SecretKey object to a String but not vice-versa! So, how do I extract the key contained in a text file? And pass as an input to this statement?
 decipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

Or else is it possible to take the key as an input from the user during both the encryption and decryption process?

A: Do this:
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
byte[] encoded = key.getEncoded();
// save this somewhere

Then later:
byte[] encoded = // load it again
SecretKey key = new SecretKeySpec(encoded, "DES");

But please remember that DES is unsecure today (it can be relatively easily bruteforced). Strongly consider using AES instead (just replace "DES" with "AES).


text:
Q: Can't run IPython-Parallel in Jupyter Notebook I'm trying to follow these instructions on using ipyparallel in order to speed up some Python scripts in Jupyter Notebook. When doing
import ipyparallel as ipp
IPPC = ipp.Client()

I get the following error:
Using matplotlib backend: TkAgg

Waiting for connection file: ~/.ipython/profile_default/security/ipcontroller-client.json

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-11-bf8e572b63bc> in <module>()
     18 display(HTML("<style>.container {width:100% !important;}</style>"))
     19
---> 20 IPPC = ipp.Client()
     21
     22

/home/guest/.local/lib/python3.7/site-packages/ipyparallel/client/client.py in __init__(self, url_file, profile, profile_dir, ipython_dir, context, debug, sshserver, sshkey, password, paramiko, timeout, cluster_id, **extra_args)
    415                         no_file_msg,
    416                     ])
--> 417                     raise IOError(msg)
    418         if url_file is None:
    419             raise IOError(no_file_msg)

OSError: Connection file '~/.ipython/profile_default/security/ipcontroller-client.json' not found.
You have attempted to connect to an IPython Cluster but no Controller could be found.
Please double-check your configuration and ensure that a cluster is running.

The file ~/.ipython/profile_default/security/ipcontroller-client.json does not exist (folder is empty!!) and doing sudo find / -name ipcontroller-client doesn't return any results.
Furthermore, when trying to start ipcluster in the terminal, I get
user@laptop:~$ ipcluster start -n 2
ipcluster: command not found

and the "Clusters" tab in Jupyter Notebook is empty: Screenshot
However, ipyparallel is definitely installed:
user@laptop:~$ pip3 install ipyparallel
Requirement already satisfied: ipyparallel in ./.local/lib/python3.7/site-packages (6.3.0)
Requirement already satisfied: jupyter-client in /usr/lib/python3/dist-packages (from ipyparallel) (5.2.3)
Requirement already satisfied: traitlets>=4.3 in /usr/lib/python3/dist-packages (from ipyparallel) (4.3.2)
Requirement already satisfied: tornado>=4 in /usr/lib/python3/dist-packages (from ipyparallel) (5.1.1)
Requirement already satisfied: pyzmq>=13 in /usr/lib/python3/dist-packages (from ipyparallel) (17.1.2)
Requirement already satisfied: ipykernel>=4.4 in /usr/lib/python3/dist-packages (from ipyparallel) (4.9.0)
Requirement already satisfied: ipython-genutils in /usr/lib/python3/dist-packages (from ipyparallel) (0.2.0)
Requirement already satisfied: decorator in /usr/lib/python3/dist-packages (from ipyparallel) (4.3.0)
Requirement already satisfied: ipython>=4 in /usr/lib/python3/dist-packages (from ipyparallel) (5.8.0)
Requirement already satisfied: python-dateutil>=2.1 in /usr/lib/python3/dist-packages (from ipyparallel) (2.7.3)
Requirement already satisfied: pexpect in /usr/lib/python3/dist-packages (from ipython>=4->ipyparallel) (4.6.0)

and there are three file ipcluster, ipcontroller, and ipengine in /home/user/.local/bin which are Python scripts.
What could be the problem?

A: Sarah.Connr, I recently had a similar initial experience with ipyparallel, where the symptoms were much the same. After installing it, the folders, files, and Jupyter Notebook "clusters" tab contents you mention were missing.
The issue was that although it looked like ipyparallel was installed, it was either installed incorrectly, or configuration, permissions or owners (user vs. root) were messed up.
But first, you reported:
user@laptop:~$ ipcluster start -n 2
ipcluster: command not found

and "there are three files: ipcluster, ipcontroller, and ipengine in /home/user/.local/bin which are Python scripts."
On my ubuntu system, those programs installed in /usr/local/bin, not
~/.local/bin.
In any case, ipcluster: command not found means that ipcluster is not in
your execution path.
You can run it by entering the full path to the program or
first cd-ing to its folder.
This might solve your problem, or it might reveal more issues.
OK, now for my story and its solution...
I first installed ipyparallel:
$ pip3 install ipyparallel

There were problems, so subsequently,
$ pip3 install --user ipyparallel

Problems remained, so,
$ sudo pip3 install ipyparallel

I saw the "Requirement already satisfied:..." messages, too, but they were
preceded by this warning:
WARNING: The directory '/home/(user name here)/.cache/pip' or its parent
directory is not owned or is not writable by the current user. The cache
has been disabled. Check the permissions and owner of that directory.
If executing pip with sudo, you may want sudo's -H flag.

Things still didn't work!
So I ran
$ sudo -H pip3 install ipyparallel

At this point, all the folders and files showed up, the appropriate items appeared under the Jupyter Notebook "clusters" tab, and the problems disappeared.
Now I'll admit that I don't understand all of this, and I do tend to tinker by instinct and experience until things eventually work (or not).
So I'm not saying that you need to (or should) do this, but I hope my comments
provide a starting point and some helpful hints.


text:
Q: R - load multiple csv files and drop .csv from name I have some files in a base directory that I use to house all my .csv files
base_dir <- file.path(path)
file_list <- list.files(path = base_dir, pattern = "*.csv")

I would like to load all of them at once:
for (i in 1:length(file_list)){
  assign(file_list[i],
  read.csv(paste(base_dir, file_list[i], sep = ""))

)}

However, this produces files with ".csv" in the names in R.
What I would like to do is load all the files but drop the ".csv" from the name once they are loaded.
I have tried the following:
 for (i in 1:length(file_list)){ assign(file_list[i],
 read.csv(substr(paste(base_dir, file_list[i], sep = ""), 1,
 nchar(file_list[i]) -4))

 )}

But I received an error:  No such file or directory
Is there a way to do this somewhat efficiently?

A: Normally one reads them into a list rather than having them as free objects floating around in the workspace.  Use dir or Sys.glob to generate the full path names and then use read.csv to read each one in.   L's names will be pathnames so reduce them to the basename and remove .csv .
# paths <- dir(path = path, pattern = "\\.csv$", full = TRUE)
paths <- Sys.glob(sprintf("%s/*.csv", path))
L <- Map(read.csv, paths)
names(L) <- sub("\\.csv$", "", basename(names(L)))

If you really want them as free floating objects anyways then add this:
list2env(L, .GlobalEnv)

A: We can use sub to remove the .csv at the end
for (i in 1:length(file_list)){
  assign(sub("\\.csv$", "", basename(file_list[i])),
       read.csv(paste(base_dir, file_list[i], sep = ""))

    )}

Or another option is file_path_sans_ext
for (i in 1:length(file_list)){
  assign(tools::file_path_sans_ext(basename(file_list[i])),
       read.csv(paste(base_dir, file_list[i], sep = ""))

    )}

The error produced in OP's code is because the substr is applied on the 'value' part i.e. the one goes into reading the file instead of the 'x' i.e. the corrected code would be
for(i in 1:length(file_list)){
     assign(substr(paste(base_dir, file_list[i], sep = ""),
           1, nchar(file_list[i]) -4),
         read.csv(file_list[i])

 )}

Also, if the working directory is different, it may be better to specify full.names = TRUE
file_list <- list.files(path = base_dir, pattern = "*\\.csv$", full.names = TRUE)


text:
Q: How to Call the Copy Activity Dynamically Single Pipeline We are executing pipeline one by one in sequence manager and load the data on premise SQL.
but we would want to load the data all the copy activity in single trigger. which means we have to load the 15 tables data into on premise DB. if tomorrow, we have to add one more table, we should not change in pipeline. we would like dynamic table insert. kindly advise.
thanks to all

A: I reproduced the above scenario and got the below results.
Use two lookups one for your source database and one for on-prem SQL.
Here I have used Azure SQL database for both source and target. You can use your database with SQL Server linked service in lookup.
Use the below query in both lookups to get the list of tables.
SELECT TABLE_NAME
FROM
information_schema.tables;

lookup list of of source tables:

Give the same query in second lookup.
List of target tables with another lookup:

Use filter activity to get the list of new tables which are not copied to target.
Items: @activity('sql source lookup').output.value
Condition: @not(contains(activity('on-prem lookup').output.value,item()))

Filter result:

Give this Value array to a ForEach activity and use copy activity inside ForEach.

Copy Source:

Copy sink:

You can see new tables are copied to my target. Schedule this pipeline everyday so that your every new table gets copied to target.


text:
Q: gunicorn с flask через функцию, деплой на Heroku Мне необходимо создать Flask сервер из функции (на самом деле это будет метод в классе) Локально все работает(без gunicorn), но на сервере через gunicorn не работает.
Пробовал много разных вариантов, вот один из них.
Модуль test.py
def serv():
    from flask import Flask
    app = Flask(__name__)

    @app.route("/")
    def hello():
        return "
Hello world!
"

    if __name__ == "__main__":
        app.run()

    return app

wsgi.py
from test import serv

if __name__ == "__main__":
    serv().run()

Локально без gunicorn все работает. Однако, на heroku через gunicorn возвращает 503 ошибку. Если убрать функцию и импортировать без функции, все начинает работать даже с более простым кодом.
К сожалению, не хватает опыта разобраться. Как мне добиться запуска Flask через функцию при работе с gunicorn.
Procfile
web: gunicorn wsgi:app

A: Разобрался.
Для вызова flask из функции, необходимо указывать об этом в явном виде при запуске gunicorn.
Например с Heroku в Procfile указать название функции
web: gunicorn "wsgi:servflask()"

При указании функции ковычки являются обязательными.
file wsgi.py
from test import servflask

if __name__ == "__main__":
    servflask().run()

test.py
def servflask():
    from flask import Flask
    app = Flask(__name__)

    @app.route("/")
    def hello():
        return "
Hello There!
"

    return app

A: Project structure:
test_app
├── app.py
└── __init__.py

__init__.py is empty
app.py:
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "
Hello world!
"

if __name__ == "__main__":
    app.run()

cmd to run:
gunicorn --bind=0.0.0.0:5000 --access-logfile=- "test_app.app:app"


text:
Q: Smoothing of absolute value and sign functions for numerical integration I'm doing Numerical integration of ODEs. for a special system that has an always positive coordinate s and a conjugated momentum ps.
At some point the equations become so stiff that s becomes negative and if I improve tolerances of the numerical integrator, it crashes. To solve this problem, I'd like to approximate the ODEs with s_new=abs(s) and ps_new=-ps around the critical region (for example if(s<1.0e-8)).
The problem is that these are not smooth. Numerical integrators (I use BDF) break down.
One solution that I came across is to use arctan for abs and erf for sign.
It was hard for me to find anything in literature on it. If you know of a better approach, please let me know.
Note, there is conservation of energy, so there exist f(s,ps) such that df/dt=0

A: You can use:  $2\Phi(x/\sigma) - 1$   as a good approximation to the signum function, where $\sigma$ is small relative to $x$.

A: Are you sure that the failure of the integrator is due to lack of smoothness? It is quite possible to integrate over non-smooth conditions with standard techniques, depending on the character of the system.
If you say that you have a stiff problem, I would imagine that that would be the cause more than anything. Have you tried using a multi-step method instead of a BDF? An Adams-Moulton implicit linear multistep method might be more suitable, and you might be able to avoid this problem altogether. It would help if you posted your system in detail.


text:
Q: How to use ToolTip for DataGrid? I'm trying to create a popup that appears when the user overlaps the mouse in a cell. I've seen some online tutorials and I created a ToolTip this:
<DataGrid>
   <DataGrid.CellStyle>
       <Style>
         <Setter Property="DataGridCell.ToolTip">
               <Setter.Value>bb</Setter.Value>
         </Setter>
       </Style>
    </DataGrid.CellStyle>
    <DataGrid.Columns>
      <DataGridTextColumn Binding="{Binding Path = 'position'}" ClipboardContentBinding="{x:Null}" Header="Pos." Width="*"/>
      <DataGridTextColumn Binding="{Binding Path = 'teamName'}" ClipboardContentBinding="{x:Null}" Header="Squadra" Width="*" />
      <DataGridTextColumn Binding="{Binding Path = 'points'}" ClipboardContentBinding="{x:Null}" Header="Punti"  Width="*"/>
      <DataGridTextColumn Binding="{Binding Path = 'playedGames'}" ClipboardContentBinding="{x:Null}" Header="Giocate"  Width="*"/>
      <DataGridTextColumn Binding="{Binding Path = 'goals'}" ClipboardContentBinding="{x:Null}" Header="Goal fatti" Width="*"/>
      <DataGridTextColumn Binding="{Binding Path = 'goalsAgainst'}" ClipboardContentBinding="{x:Null}" Header="Goal subiti" Width="*"/>
      <DataGridTextColumn Binding="{Binding Path = 'goalDifference'}" ClipboardContentBinding="{x:Null}" Header="Differenza reti" Width="*"/>
     </DataGrid.Columns>
</DataGrid>

the only problem is that I do not understand how to show the full text of a single cell when the user overlaps with the mouse on it. Particularly when the DataGrid is minimum resolution of the header cells are not shown completely, and that is a problem, to avoid this I would make sure that if it is the user overlaps the mouse on "pos", then it is the showed the complete header as tooltip is "position". How can I do this?

A: For DataGrid Cells:
If you want a ToolTip that shows the full content of a particular DataGrid cell when the mouse is over it, you can modify your DataGridTextColumn and use the same Binding for the ToolTip:
<DataGridTextColumn Binding="{Binding Path = 'position'}" ClipboardContentBinding="{x:Null}" Header="Pos." Width="*">
    <DataGridTextColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Setter Property="ToolTip" Value="{Binding Path = 'position'}" />
        </Style>
    </DataGridTextColumn.CellStyle>
</DataGridTextColumn>

Or, if you want to set it once for all the columns, you can bind to the Text property of the DataGridTextColumn's content:
<DataGrid.CellStyle>
    <Style TargetType="DataGridCell">
        <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=Content.Text}" />
    </Style>
</DataGrid.CellStyle>

For DataGrid Column Headers:
<DataGrid.ColumnHeaderStyle>
    <Style TargetType="DataGridColumnHeader">
        <Setter Property="ToolTip" Value="{Binding}" />
    </Style>
</DataGrid.ColumnHeaderStyle>


text:
Q: sql query to return single value based on column it matches I've a requirement where in if the query string matches column1 , return me 1. If it matches column 2 return 2 else if it matches column 3 return 3.
Table strunctre:
col1   col2    col3

11      12       13
22      23       24

If my query string is 23, then i'm expecting a return value of 2 as it matches col2.
Something like below:
select 1
from table1
where col1=querystring
      and orderid=xxx
      or select 2 from table1
         where col2=querystring
               and orderid=xxx
               or select 3 from table1
                  where col3=querystring  and orderid=xxx

Basically i'm expecting one query which return single value based on the column it matches.
Is it something doable in SQL as i'm not very good in DB skills.
Any help is highly appreciated.

A: There are a couple of approaches. If there is a guarantee that no more than one column will match at a time, a UNION will work:
SELECT 1 AS SomeCol
FROM   table1
WHERE  col1 = querystring
       AND orderid = xxx
UNION
SELECT 2
FROM   table1
WHERE  col2 = querystring
       AND orderid = xxx
UNION
SELECT 3
FROM   table1
WHERE  col3 = querystring
       AND orderid = xxx;

If more than one match can happen, another approach is this (note the order of precedence is now col1, col2, col3 etc):
SELECT CASE
         WHEN col1 = querystring THEN 1
         WHEN col2 = querystring THEN 2
         WHEN col3 = querystring THEN 3
       END AS SomeCol
FROM   table1
WHERE  orderid = xxx;

A: Please try using case
declare @var int
set @var=23

select
    case @var when col1 then 1
            when col2 then 2
            when col3 then 3 end
from YourTable
where
    col1=@var OR
    col2=@var OR
    col3=@var

A: Try using IF-ELSE condition in your query and check with passed parameter.


text:
Q: bluebird throws unhandled rejection When I write promise in variable, I am getting unhandled rejection:
'use strict';

const Promise = require('bluebird');

const p = Promise.reject(new Error('qwerty'));

Unhandled rejection Error: qwerty
          at Object.

but when I'm doing the same thing with q, error is not thrown:
'use strict';

const q = require('q');

const p = q.reject(new Error('qwerty'));

Why does Promise.reject in bluebird work this way? I can't find information in documentation about this behavior.


text:
Q: how to target component styles from host component angular 2 I have this :
@Component({
    selector: 'host-element',
    template: `<elementA></elementA>`,
    styles:[''] //styles here
})

export class hostElement {}

How do I target the styles of elementA component from host-element?
Thanks in advance!!

A: :host elementA {
  // style here
}

A: Angular has a special css operator /deep/, you can read about it here.
To make a style go beyond your component, put in your css (sass, less):
/deep/ .elemet-a-class {
   ... your style;
}

Or if you want to put it locally, just
styles: ['/deep/ .element-a-class { ... }']


text:
Q: Character falsely walking in the air? I am trying to make a horse run across a road in Unity. But, after putting every stuff in place, horse is unable to consider the road presence while crossing it (in the game mode). I mean it should walk/run over the road. What did I missed here?

For making roads , I am using EasyRoad3D.

A: I fixed this problem by setting the road material shader to standard.


text:
Q: SQL Server - Como establecer un día para un listado de fechas Cordial saludo,
Acudo a ustedes ya que tengo un listado de fechas como el siguiente

#
fecha

1316
2022-03-01

1316
2022-04-03

1316
2022-05-27

necesito establecer ejemplo el día 14 a cada una de las fechas anteriores, pero hasta el momento no he podido encontrar como realizar lo que requiero con SQL.
Muchas gracias y quedo muy al pendiente.
Cordialmente.

A: Perfecto con los dos comentarios anteriores puede realizar lo que necesitaba dejo el codigo para mejor comprensión
declare @fechInicial date
declare @fechFinal date
declare @id_spot int
declare @dia int

SET @fechInicial = '2022-03-02'
SET @fechFinal = '2022-07-02'
SET @id_spot = 1316
SET @dia = 14

BEGIN
    SELECT @fechInicial, @fechFinal;
        WITH FECHAS(fecha) AS (
            SELECT @fechInicial fecha
                UNION ALL
                SELECT DATEADD(month,3, fecha) fecha
                    FROM FECHAS
                    WHERE fecha < @fechFinal
            )
            select @id_spot AS '#', DATEFROMPARTS (YEAR(fecha), Month(fecha), @dia) fecha from FECHAS
        OPTION (MaxRecursion 0)

END

Muchas gracias


text:
Q: Debian won't reconnect ethernet after physical disconnection
Linux 4.9.0-8-amd64 #1 SMP Debian 4.9.130-2 (2018-10-27)
  x86_64 GNU/Linux

/etc/network/interfaces
   source /etc/network/interfaces.d/*

    auto lo
    iface lo inet loopback

    allow-hotplug eno1
    iface eno1 inet static
         address 192.168.1.249
         netmask 255.255.255.0
         network 192.168.1.0
         gateway 192.168.1.1
         dns 192.168.1.1

/etc/network/interfaces.d/setup
auto lo
iface lo inet loopback

#auto eth0
#iface eth0 inet dhcp

/etc/NetworkManager/NetworkManager.conf
[main]
plugins=ifupdown,keyfile

[ifupdown]
managed=false

Why the event of disconnection and reconnection of the ethernet port is not detected?

A: You may want to add auto eno1 right before iface eno1 inet static.


text: Q: Xubuntu did not show up after installation So I made a bootatble live usb with Xubuntu on it and installed it. I followed the guided process and partitioned my disk to install Xubuntu alongside Windows 11. Then, when I restarted, nothing happened, Windows 11 booted up as always but I just had a partition in my disk. I proceeded to delete the Xubuntu partition and extended Windows' one to bring everything back to normal. Why didn't GRUB bootloader show up and what should I do to properly install Xubuntu?


text:
Q: Using tmpfs + a very large swap partition for /tmp instead of a regular filesystem? I have Linux server and I have a spare 500GB disk partition. I wanted to format it and use it for /tmp. The server occasionally runs some large data processing tasks so it can happen that /tmp will hold GBs of temporary data.
Then I got an idea that instead I could add it as a swap partition instead and mount /tmp to tmpfs. Is this idea reasonable?
The server has 6GB of RAM, so in most cases data on /tmp would be only in RAM, with the obvious speed advantage. The question is, what if there will be let's say 10-20GB of data on /tmp, how will the system perform? What would be the performance compared to having simply /tmp mounted to an ext4 partition? Thanks for help.
Edit: It is clear that the system will start swapping out memory when the usage of tmpfs hits the RAM limit. But is Linux smart enough to swap out tmpfs data and keep "regular" data in RAM? If yes, then I suppose it could behave reasonably. If not, then the whole system will be severely affected.

A: This could be a reasonable idea.
Putting an actual filesystem on /tmp does incur overheads, because filesystems go through great lengths to make sure that the data on disk is not corrupted in case of system failure. For a /tmp that is cleaned at boot time, that is obviously just overhead. Using a tmpfs would avoid that overhead.
On the other hand, filesystems also make sure that files are organised on the disk in a way that optimises access time - i.e., they will avoid fragmentation. Typical sequential file accesses will (mostly) result in sequential disk accesses, which are more efficient than random accesses. This effect is more pronounced on spinning harddisks than on SSD. The swap+tmpfs combination can't easily do this, because swap is not aware of which piece of memory belongs to which file and tmpfs isn't aware of how pages are mapped to physical memory or to the disk. For large files, however, it should work well, since both tmpfs and swap try to keep things contiguous in that case. At least, as long as there is a lot of free space on swap (otherwise fragmentation kicks in), and writes happen slowly enough that they get a chance of being swapped out.
So the bottom line is: it depends, you should try both options to see which one works best.
When you mount the tmpfs, do remember to set the size explicitly. The default is half the physical RAM, so just 3GB.

A: This is actually a good idea when you usually don't have much data in /tmp, but occasionally consume endless gigabytes for limited duration.  The problem is the linux swap system doesn't know enough about your use case to do it right.  It will generally prioritize dumping or swapping cache over program pages, but that doesn't really help.  It may be possible to use cgroups to achieve your goal, it is when the scratch data is held in program memory, but I'm not sure how to configure cgroups in this case (I suppose you could use a FUSE tmpfs...). Fortunately, that's not required.  You can get the desired behaviour with zram and a backing device.
zram-init is the program that automates setting up zram, which is a compressed ram block device.  There is usually an example in the zram-init config for mounting /tmp as zram.  It'll be something like the following
type0=/tmp
flag0=
size0=524288 # 500G of logical space
mlim0=2G # 2G of memory
back0=/dev/loop0 # (or /dev/sdxN, your large slow drive)
notr0=
maxs0=4 # maximum number of parallel processes for this device
algo0=zstd
labl0=tmp # the label name
uuid0=
args0=

This will compress and store in memory anything written to /tmp.  Usual compression is somewhere around 50%.  It will consume at most 2G of physical memory.  If it runs low on physical memory, it will take the oldest files and push them into the backing device, still compressed.  Note that it does incur some CPU overhead to compress and decompress the files, but this is usually offset by the reduced IO.
A similar setup can be used in conjunction with cgroups to let certain processes swap without adversely affecting overall system performance.

A: This is NOT A Good IdeaTM.
You'll be fine with a large /tmp partition, mounted like this (from your /etc/fstab)
tmpfs  /dev/tmp  tmpfs  defaults,nosuid,nodev,noexec,noatime,nodiratime,size=6000M 0 0

And you could add your external drive as a giant swap partition
/dev/sdb1  swap  swap  defaults  0 0

When that hits its limit, your machine will start to swap the pages from RAM to disk - at which point, load averages will go through the roof and the machine will grind to a halt.
Its a bad idea to rely on SWAP in any way, you'd be better off selling your 500GB drive and simply buying more RAM - its cheap.
In summary
If you really want to use your 500GB disk, you could mount your 500GB disk on /tmp with a non-journaled filesystem with atime and diratime disabled (eg. ext2). That would be substantially faster than dealing with a machine that is SWAPing


text:
Q: Chart Control Label Parentheses I am having a problem labeling a chart axis in C# with the Microsoft Chart control. My label is the following string: "Elevation (m)". It works perfectly fine when labeling the x-axis. However, when I put the label on the y-axis, it displays as follows: "Elevation (m|".  For some reason the ) displays as a |. Is this a bug or am I doing something wrong?
EDIT:
Here is my code:
DataTable dt1 = curve.GetCurveDataTableFromDatabase(); //Gets a datatable with columns Elevation and Storage
string seriesName = "Raw Data";
string xaxislabel = "Storage (m3)";
string yaxislabel = "Elevation (m)";
chartPlotArea.Series.Clear();
chartPlotArea.DataSource = dt1;
chartPlotArea.Series.Add(seriesName);
chartPlotArea.Series[seriesName].XValueMember = "Storage";
chartPlotArea.Series[seriesName].YValueMembers = "Elevation";
chartPlotArea.Series[seriesName].ChartType = SeriesChartType.Line;
chartPlotArea.ChartAreas[0].AxisX.Title = xaxislabel;
chartPlotArea.ChartAreas[0].AxisY.Title = yaxislabel;
chartPlotArea.Titles.Clear();
chartPlotArea.Titles.Add(new Title("Storage vs Elevation Plot"));

And here is what the chart looks like:
enter image description here

A: It has something to do with the font.  I can duplicate the issue when I use the default font for the chart axis titles.  Setting the font to size 10 fixed the issue for me.
Through the gui:

Programmatically:
chart1.ChartAreas[0].AxisX.TitleFont = new Font("Microsoft Sans Serif", 10, FontStyle.Regular);
chart1.ChartAreas[0].AxisY.TitleFont = new Font("Microsoft Sans Serif", 10, FontStyle.Regular);

A: I was having this same issue. I changed one of my chart axis title font sizes to 9 and I don't see the problem. It seems that some font sizes cause this and some don't. I believe it has to do with the fact that this text is printed vertically.
Here is how I changed the font size:
MeasurementResultsChart.ChartAreas[0].Axes[0].TitleFont = new Font("Microsoft San Serif", 9, FontStyle.Regular);
MeasurementResultsChart.ChartAreas[0].Axes[0].Title = "Reference Concentration (%)";
MeasurementResultsChart.ChartAreas[0].Axes[1].TitleFont = new Font("Microsoft San Serif", 9, FontStyle.Regular);
MeasurementResultsChart.ChartAreas[0].Axes[1].Title = "Measured Concentration (%)";


text:
Q: How to implement setEncoding in my own Node.JS readable Stream? In my program, I have a readable Stream source which emits data events from a shared stream of byte data. I then interpret the data to extract Buffer objects, and then pass them to the appropriate function. The most elegant way of passing the Buffers to the rest of my program seems to be using a readable Stream object. That way my functions can read the stream the same way as if it were standalone stream.
Here is my current code:
var stream = new stream.Stream()
stream.readable = true
stream.pause = function () {
    source.pause()
}
stream.resume = function () {
    source.resume()
}
stream.readable = true
// in a loop, read the data from source stream, dissect the parts we want,
// and emit Buffer objects to the stream's data event.

How can I implement setEncoding?
 Edit: I think the answer is related to this line in the stream.js source code
Stream.Readable = require('_stream_readable');

Furthermore, the correct answer may be to

*

*replace new stream.Stream with new stream.Readable and to

*replace stream.emit('data', buffer) with
either stream.onread(buffer) or stream.push(buffer). The thing is, I don't know which one.

Edit: stream.Readable is not available in version 0.8. It is available in 0.9 beta, and will be avilable in v0.10 stable when that comes out. The ideal answer to this question will describe both the 0.8- solution and the 0.9+ solution.

A: use streams2. for 0.8, there's: https://github.com/isaacs/readable-stream


text:
Q: Multisite on single wordpress I've got single site on instance of wordpress. Now I want to add second blog so second site (separate domain) under the same hosting so the same wordpress instance.
Is it possible to achieve it having sweparate not related domains?
I'm new in wordpress area and most of tutorials I saw are about multidomain with having subdomain or subdirectories so not my case.

A: You absolutely can have a single WordPress Multisite installation serve up more than one domain.

*

*Set up Multisite. For this site, it won't matter if you use subdirectory or subdomain. (If you plan to add other sites to this Multisite network, choose the option you'd prefer to use for those other sites.)

*Create your new site.

*Go to the new site's Dashboard, and mouse over its name in the admin bar at the top of the page. Select Edit Site from the dropdown menu.

*Change the Site Address (URL) to what you want it to be, and save the changes.

Note: You'll need to make sure that your new domain name is registered, and that its DNS entry points to the appropriate IP address. You'll also need to make sure that your WordPress server's configuration is set to accept requests for the new domain name. This is something you'll either need to handle yourself, or take up with your hosting provider.

A: As long as you're not talking about Using two domains with the same wordpress install IE you use the same site with two different names.
If you are using two DIFFERENT wordpress installations, this is super simple. Its all about associating that second domain with your webhost, i suggest you look into using your second domain as an addon domain. Given that you've just got started I imagine you're in a shared hosting solution like godaddy.
Godaddy would have you add an addon domain, or you could use a subdomain and point that to a given folder on your server.
You will ofcourse need a seperate database, and to install wordpress in that folder but you should have no issues.
IF you used something like softalicious or some hosting provided installer you are a in for a little headache as at this point you need to understand how to put files on your server. That would involve ftp etc.
I hope this helps. But really your question isn't a wordpress question its a hosting question one specific to your hosting providers pattern for using multiple domains with their servers.


text:
Q: Objective C: NSNumber from Array to float I have an array:
SomeArray =[[NSMutableArray alloc]initWithObjects:[NSNumber numberWithFloat:50.0],[NSNumber numberWithFloat:120.0],[NSNumber numberWithFloat:200.0],nil];

When I retrieve it:
NSNumber* Target = [SomeArray objectAtIndex:0];

When I NSLog it:
NSLog(@"Target %d",Target);

it return something funky like
2013-06-26 01:47:58.940 KKK[1027:c07] Target 121016880

What is the proper way to do this?? I just need the number in the array to be used as float.

A: You are retrieving a NSNumber, which is an object.
%d is for logging decimals, which is not your case.
Either you log it with
NSLog(@"Target %@", target);

or you convert it to a float and use %f
NSLog(@"Target %f", [target floatValue]);

And PLEASE don't use capitalized identifiers for variables!

A: You are asking for a decimal %d in the log and also a primitive type. NSNumber is an object that wraps a primitive type numbers. So you can do like that
NSLog(@"target %f",[Target floatValue]) or NSLog(@"target %@",Target). With the first you are sending a message to the object to unwrap the float value with the latter you are asking for the object description that in this case is the number


text:
Q: Refactor react code to improve performance I am new in coding in React and I have just joined a new organization where I need to send my code for review .The functionality is working fine but it seems to me that code in my component has become very lengthy ,also my submithandler method is making me iterate the array a couple of times,I don't know how to do it other way.Is there any way I can shorten my code to make it look better and increase the performance??Currently its taking a long time to show the data after i click submit ,looks like iteration oof array is taking time.
Also,If i close the browser after clicking the submit button, the ajax pending request is still in progress.I want to end the request and stop loading once i close the browser or navigate to other page.myRequestor is a third party library of my organization that can be used to send a request.Please help me shorten the code and fix the pending ajax request issue.Below is the code that I have tried to do.
const propTypes = {
  name: PropTypes.string,
  tenant: PropTypes.arrayOf(PropTypes.any),
  myRequestor: PropTypes.object, // eslint-disable-line react/forbid-prop-types
  };

let myRequestor = null;

const CallerUtil = () => {
myRequestor = React.useContext(MyRequestorContext);
return <ApplicationLoadingOverlay isOpen backgroundStyle="clear" />;
}

class ReadinessComponent extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        body: '',
        tenant: null,
        error: null,
        errorMsg: '',
        isOpen: false,
        showTable: false,
        isInvalid: false,
        isLoading: false,
        tenantId: '',
        items: [],
        tenantItems : null
    };

    this.onChangeTenantDropDown = this.onChangeTenantDropDown.bind(this);
    this.onSubmitHandler = this.onSubmitHandler.bind(this);
    this.onChangeHandler = this.onChangeHandler.bind(this);
    this.tenantIdHandler = this.tenantIdHandler.bind(this);
    this.onClose = this.onClose.bind(this);
    this.addNewTenant = this.addNewTenant.bind(this);
    this.fetchInitial = this.fetchInitial.bind(this);
   }

componentDidMount() {
  this.mounted = true;
  this.setState({ isLoading: true });
  this.fetchInitial();

  }
componentWillUnmount(){

    this.mounted = false;

  }

onChangeTenantDropDown(value) {
    this.setState({
        tenant: value,
    });

  const info = this.state.tenantItems.find(function (t) { return t.name == value })
  this.setState({
    tenantId: info.id,
  });

}

  onSubmitHandler() {
    if (this.state.body == '') {
      this.setState({ isInvalid: true });
      return;
    }
    this.setState({ isLoading: true });
    const params = {
      "tenantId": this.state.tenantId,
      "tenantShortName": this.state.tenant,
      "contactName": this.state.body
    }

    const { request } = myRequestor.get({
      url: '/getReadinessCheck',
      params: params,
    });

   // request.then(async ({ data }) => {
      request.then(({ data }) => {
      console.log(this.mounted);
      if (!this.mounted) {
        this.setState({ isLoading: false });
        return;
      }

      console.log(data);

      let abc = data.find(vrsn => vrsn.name === 'TENANT_ERROR');
      if (abc === undefined) {
        this.setState({ error: 'Failure', errorMsg:'Invalid Tenant',isLoading: false, isOpen: true, showTable: false, body: '', tenantId: ''});
        return;
      }
      let readinessResp = data.map(version => (version.latest === true ? { ...version, name: version.name.concat('_LATEST') } : version))
      readinessResp.sort(function (a, b) {
        var textA = a.name.toUpperCase();
        var textB = b.name.toUpperCase();
        return textA.localeCompare(textB);
      });

      this.setState({ items: readinessResp, error: 'Success', showTable: true, isLoading: false });
    }).catch(error => {
        this.setState({ error: 'Failure', errorMsg:'Failure', isLoading: false, isOpen: true, showTable: false ,body: '', tenantId: '' });
      });

  }

onChangeHandler(event) {
    this.setState({
        body: event.target.value,
    });
}

tenantIdHandler(event) {
  this.setState({
    tenantId: event.target.value,
  });
}

onClose() {
    this.setState(prevState => ({
        isOpen: !prevState.isOpen,
    }));
}

addNewTenant(shortName,tenantId){
  const newTenantShortName = shortName;
  const newTenantId = tenantId;
  const newTenant = {'name':newTenantShortName, 'id':newTenantId};
  this.setState({
    tenantItems: [...this.state.tenantItems, newTenant]
});

}

fetchInitial() {
  this.setState({ isLoading: true });
  const { request } = myRequestor.get({
    url: '/tenants'
  });

  request
  .then(({ data }) => {
    if(data[0].hasOwnProperty("error")){
      this.setState({ error: 'Failure', errorMsg:data[0]['error'], isOpen: true, isLoading:
   false,tenantItems: [{'name':'Default', 'id':'Default'}]});
      return;
    }

    let tenantsList = data;
    let tenants =[];
    tenantsList.map(tenant => ( tenants.push({'name':tenant.shortName, 'id':tenant.key})))

  this.setState({
    tenantItems: tenants,isLoading: false
  });
  })
  .catch((error) => {
    this.setState({ error: 'Failure', isOpen: true, isLoading: false});
  });
  }

  render() {
      const {
   error, isOpen, body,showTable
       } = this.state;

if (this.state.tenantItems === null) {
  return <CallerUtil />;
  }

if(this.state.isLoading){
    return <ApplicationLoadingOverlay isOpen backgroundStyle="clear" />;
}

if (showTable) {
    return (

Readiness Status

    <ReadinessComponentView readinessInfo={this.state.items} />
);
}

return (

    <Grid>
      <Grid.Row>
        <Grid.Column>
          <Heading level={1}>Readiness Check</Heading>
        </Grid.Column>
      </Grid.Row>
      <Grid.Row>
        <Grid.Column className="ruleSupportEvaluation" large={3} medium={3}>

            <Heading className="info" level={3}>About</Heading>
            <Divider />
            <Text className="description" fontSize={18}>
              Readiness Check
            </Text>

        </Grid.Column>
        <Grid.Column className="ruleSupportEvaluation" large={8} medium={8}>

            <Tenant
              tenant={this.state.tenantItems}
              change={this.onChangeTenantDropDown}
            />
            <ModalManagerExample addNewTenant={this.addNewTenant} />

            <InputField type="text" label="Tenant-Id" value={this.state.tenantId} placeholder="Tenant Id" onChange={this.tenantIdHandler}/>
            <InputElement isInvalid ={this.state.isInvalid} change={this.onChangeHandler} value={body} />
            <Submit click={this.onSubmitHandler} />

            {error === 'Failure' &&
              (
                <Notification
                  errorMessage={this.state.errorMsg}
                  close={this.onClose}
                  isOpen={isOpen}
                />
              )
             }

        </Grid.Column>
      </Grid.Row>
    </Grid>

);
     }
 }

ReadinessComponent.propTypes = propTypes;

export default ReadinessComponent;

A: as @charlietfl mentioned - codereview.stackoverflow.com is probably your best bet, however:
First quick win is take all of the .bind(this) stuff from your constructor and for those methods, define them in your class like this:
BEFORE:
onChangeTenantDropDown(value) {
    this.setState({
        tenant: value,
    });

  const info = this.state.tenantItems.find(function (t) { return t.name == value })
  this.setState({
    tenantId: info.id,
  });

}

AFTER:
onChangeTenantDropDown = (value) => {
    this.setState({
        tenant: value,
    });

  const info = this.state.tenantItems.find(function (t) { return t.name == value })
  this.setState({
    tenantId: info.id,
  });

}

Note the arrow function.

You can also set state directly as a class property, so remove this. from where you define your state and move it outside of the constructor, i.e.:
class ReadinessComponent extends Component {
  state = {
        body: '',
        tenant: null,
        error: null,
        errorMsg: '',
        isOpen: false,
        showTable: false,
        isInvalid: false,
        isLoading: false,
        tenantId: '',
        items: [],
        tenantItems : null
    };
    ...
}

Now you can totally remove the constructor too :)
Hopefully that gets you at least part of the way there

Totally recommend learning Hooks if you're new, it will really help clean up components like this - here's some links:

*

*https://reactjs.org/docs/hooks-intro.html

*https://blog.bitsrc.io/fetching-data-in-react-using-hooks-c6fdd71cb24a

*https://www.smashingmagazine.com/2020/06/introduction-swr-react-hooks-remote-data-fetching/
EDIT
In response to your comment:
onSubmitHandler = async () => {
    const { body, tenantId, tenant: tenantShortName, body: contactName } = this.state;
    if (!body) {
        this.setState({ isInvalid: true });
        return;
    }

    this.setState({ isLoading: true });

    const params = {
        tenantId,
        tenantShortName,
        contactName,
    };

    try {
        const { request } = myRequestor.get({
            url: '/getReadinessCheck',
            params,
        });

        const { data } = await request;

        if (!this.mounted) {
            this.setState({ isLoading: false });
            return;
        }

        let abc = data.find((vrsn) => vrsn.name === 'TENANT_ERROR');
        if (abc === undefined) {
            this.setState({
                error: 'Failure',
                errorMsg: 'Invalid Tenant',
                isLoading: false,
                isOpen: true,
                showTable: false,
                body: '',
                tenantId: '',
            });
            return;
        }
        let readinessResp = data.map((version) =>
            version.latest === true ? { ...version, name: version.name.concat('_LATEST') } : version,
        );
        readinessResp.sort(function (a, b) {
            var textA = a.name.toUpperCase();
            var textB = b.name.toUpperCase();
            return textA.localeCompare(textB);
        });

        this.setState({ items: readinessResp, error: 'Success', showTable: true, isLoading: false });

    } catch (err) {
        this.setState({
                error: 'Failure',
                errorMsg: 'Failure',
                isLoading: false,
                isOpen: true,
                showTable: false,
                body: '',
                tenantId: '',
            });
    }
};


text:
Q: how can i set tokeninput parameter on condition as dynamic I am using tokeninput jquery for autocomplete with asp.net.
http://loopj.com/jquery-tokeninput/
i have one textbox and searching parameter is conditional. this jquery is render on loadtime. there is a checkbox, if checkbox is checked searching parameter wouldbe change and if checkbox is unchecked searching parameter is default parameter. i have called this on ready state.the issue is that when checkbox is checked searching parameter not changed. it search on only one condition as default condition.On ckeckbox click IsPastClass change as true  or false.
  $(document).ready(function() {
        $("#txtStudentTokenSearch").tokenInput("../Handlers/TestAutoCompleteHandler.ashx?SearchType=Patient&IsPastClass=false", {
            theme: "facebook",
            tokenDelimiter: "|",
            preventDuplicates: true,
            onAdd: function(item) { removeTokenDuplicate('#txtStudentTokenSearch', item); btnLoadStudent.Focus(); }
        });
});

Can any one tell me how can i set tokeninput parameter on condition.
Thanks.

A: Try
$(document).ready(function() {
    $('.checkbox').change(function(){
        var IsPastClass = this.checked;
        $("#txtStudentTokenSearch").tokenInput("clear");
        $("#txtStudentTokenSearch").tokenInput("../Handlers/TestAutoCompleteHandler.ashx?SearchType=Patient&IsPastClass="+IsPastClass , {
            theme: "facebook",
            tokenDelimiter: "|",
            preventDuplicates: true,
            onAdd: function(item) { removeTokenDuplicate('#txtStudentTokenSearch', item); btnLoadStudent.Focus(); }
        });
    });
    $('.checkbox').trigger('change');
});

Hope it helps.

A: you can use tokenInput with ajax and handler very easly
you can download example from github
https://github.com/yanivsuzana/jquery-tokeninput-ajax-asp.net-vb


text:
Q: Route from Incoming ASPX url to an ASP.NET MVC Controller Action I have a url Review.aspx?reviewId=3 and I'd like to have this url be routed to an MVC controller/action Review/3. Any ideas?

A: Never mind, a simple route like this worked:
        routes.MapRoute(
          "Reviews_Old", // Route name
          "LOreview.aspx", // URL with parameters
          new { controller = "LOReview", action = "Review", id = UrlParameter.Optional } // Parameter defaults
        );

And the query string parameters are model bound on the controller action parameters


text:
Q: Is it correct to use quotes before a comma when not representing spoken text? In another question I asked, I used quotes to demark specific terms, but after I posted the question, I wondered if I'm doing it right.
Usually, when quoting something a person says, the quotation mark goes after the comma or period, like so:

"This is my opinion," she said.

However, I sometimes use quotes not to represent something said by anyone, but instead for delineating a set term or phrase to make it clear that those words go together and none of them should be mistaken for a part of the rest of the sentence. Like this:

Should I say "stand up", "standup", or "stand-up"?

This looks weird to me:

Should I say "stand up," "standup," or "stand-up"?

... but maybe I'm wrong about the rules.
Is it correct to use quotes in this way? And if so, are the quotes positioned correctly relative to the other punctuation marks?
Are there other alternatives for delineating terms without the use of quotes?

A: Quotation marks are sometime used:

- to draw attention to a word;
- to indicate an unusual use of a word;
- to suggest that the writer want to be distanced from word.

The comma and the question mark come after the quotation marks in such cases.
In this light, the sentence

Should I say "stand up", "standup", or "stand-up"?

is perfectly valid.
Instead, the sentence

Should I say "stand up," "standup," or "stand-up"?

is not valid because, although the question mark came after the quotation marks (... or "stand-up"?), the comma does not allow the rule I have mentioned.¹
¹ For more explanations and examples see Collins Easy Learning - Grammar and Punctuation, to which I am referred to for answering the question you have asked.

A: It depends from which language you are using to write. For example, in American English the comma following the quoted part is written inside the quotes, as reported from Comma Sense—A fun-damental guide to punctuation (by Richard Leederer, and John Shore), which says:

In U.S. punctuation, periods and commas always—and we do mean always—go inside the quotation marks.

Some of the examples found in the book are the following ones:

In "Confessions of an Alliteration Addict," the lead article in the August 2005 issue of Neurosis Today, Edema Edington recounts a childhood in which she was force-fed storied and rhymes about Jack and Jill, Simple Simon, Miss Muffet, King Cole, Boy Blue, Red Riding Hood, Peter Peter Pumpkin Eater, and Georgie Porgie Pudding and Pie.

"I really zapped Aloysius," boated Edema.

The word "politics" derives from two ancient roots: "poly," meaning "many," and "tics," which are blood-sucking parasites.

The comma is placed inside the quotation marks, whatever you are using them to report what has been said from somebody, or you are using quotation marks to distinguish words-as-words.
In the latter case, you could write the sentence as follows:

The word "politics" derives from two ancient roots: poly, meaning "many," and tics, which are blood-sucking parasites.

As a side note, the comma is not used inside the quotation marks, if the quotation ends with a question mark, or an exclamation point.

"You lie!" answered Edema.
  "No I don't" risposted Aloysius.

"What happened to Aloysius?" she asked.


text:
Q: S3 bucket and object access As per my understanding with out giving access, any IAM user can not access the S3 bucket/object. But in my use case I am able to access it.
Am I misunderstood the security policy in S3.
Here is my use case I have root account in AWS, say root user. And this user created two IAM users,say Admin and Test users. And root user given S3FullAccess permission to both IAM users.
Now I logged in as  Admin and created one Bucket( say Test). And enabled "Block all public access ".
Now with another IAM user still I am able to access Test bucket, even though  " Block all public access " enabled.
Ideally it should not right. The Test user should get access denied permission while accessing Test bucket.
Am I missing anything, any help would be highly appreciated
Thanks
AWS learner

A:
And root user given S3FullAccess permission to both IAM users

This is the reason why your both the users are able to see the bucket as they have the below policy attached with the user :
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "*"
        }
    ]
}

You remove this policy from the user and you'll see below error :

A: The "block all public access" to the bucket is referring to outside your organization, not with the IAM users.
In other words, if your bucket is accessible to the public, then anyone who has access to the objects S3 URL can directly access that object.
You may restrict access to the bucket by using a bucket policy, but it would make more sense to remove the S3FullAdminAccess from the test user in IAM.


text:
Q: group_by combined with frq() is excluding NAs from group variables, but I want to keep them I'm outputting summary statistics using frq() because my dataset has haven labels that I want displayed. I found that when I used group_by and run this, however, the output excludes groups with missing values. Reproducible example:
library(dplyr)
library(sjmisc)

look<-cars
    look<-look %>% mutate(color=case_when(
      speed > 10 ~ 'red',
      TRUE ~ 'blue'
    ))
 temp<-data.frame(speed=12,dist=12)
 look<-bind_rows(look,temp)
 rm(temp)

 look<-look %>% group_by(color) %>% frq(speed)
 look<-as.data.frame(look)
 sum(look$frq)

[1] 50

Here we see that only 50 rows are summarized and the one with is.na(color) is excluded.
Is there any way to get groups with NA to show?
Thanks!


text:
Q: DownloadFileAsync in loop with CompletedEvent gets only the last file I'm getting several file links from a file into a loop statement and for each link , I have to download the file , when the download was completed I have to do something with each file.
Here is my code,
      foreach(//condition ) {
            Descarcare = new WebClient();
                                Descarcare.DownloadProgressChanged += Descarcare_DownloadProgressChanged;
                                Descarcare.DownloadFileAsync(new Uri(nod.SelectSingleNode("DownloadLink").InnerText), Directory.GetCurrentDirectory()+);
                                Descarcare.DownloadFileCompleted +=Descarcare_DownloadFileCompleted;
}

    void Descarcare_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
       //extract the file
    }

But somehow , the webclient downloads the files but the DownloadFileCompleted event fires only for the last downloaded file instead of doing it for each file.
What can cause this?

A: You are creating a new WebClient in every iteration of your foreach-loop. The best approach is to create a Queue with all files and start a new download in each DownloadFileCompleted until you got all the files you want.
var _downloadQueue = new Queue<Uri>();
var _webClient = new WebClient();

//in your constructor:
_webClient.DownloadProgressChanged += Descarcare_DownloadProgressChanged;
_webClient.DownloadFileCompleted += Descarcare_DownloadFileCompleted;

private void Foo()
{
    //...

    foreach(/* condition */)
    {
        _downloadQueue.Enqueue(
            new Uri(nod.SelectSingleNode("DownloadLink").InnerText)
        );
    }

    DownloadNext();
}

private void DownloadNext()
{
    if(_downloadQeue.Count> 0)
    {
        _webClient.DownloadFileAsync(
            _downloadQueue.Dequeue(), Directory.GetCurrentDirectory()
        );
    }
}

void Descarcare_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    DownloadNext();

    //extract the file
    //...
}


text:
Q: Sort by price low to high and high to low in product listing magento2 I am new in Magento 2. I am using Magento 2.1.1
I want to add custom price low to high and price high to low in Sort By dropdown in product listing page.
I didn't get toolbar.phtml page. Also I didn't get any stuff regarding this in google.

A: Step 1: Create plugins in

app/code/Vendor/Module/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="Magento\Catalog\Block\Product\ProductList\Toolbar">
        <plugin name="custom_custom_block_toolbar" type="Vendor\Module\Plugin\Catalog\Block\Toolbar" />
    </type>

    <type name="Magento\Catalog\Model\Config">
        <plugin name="custom_catalog_model_config" type="Vendor\Module\Plugin\Catalog\Model\Config" />
    </type>

</config>

Step 2: Create Config.php in

app/code/Vendor/Module/Plugin/Catalog/Model/Config.php

<?php

namespace Vendor\Module\Plugin\Catalog\Model;

class Config
{
    public function afterGetAttributeUsedForSortByArray(
    \Magento\Catalog\Model\Config $catalogConfig,
    $options
    ) {

        $options['low_to_high'] = __('Price - Low To High');
        $options['high_to_low'] = __('Price - High To Low');
        return $options;

    }

}

Step 3: Create Toolbar.php in

app/code/Vendor/Module/Plugin/Catalog/Block/Toolbar.php

<?php
namespace Vendor\Module\Plugin\Catalog\Block;

class Toolbar
{

    /**
    * Plugin
    *
    * @param \Magento\Catalog\Block\Product\ProductList\Toolbar $subject
    * @param \Closure $proceed
    * @param \Magento\Framework\Data\Collection $collection
    * @return \Magento\Catalog\Block\Product\ProductList\Toolbar
    */
    public function aroundSetCollection(
    \Magento\Catalog\Block\Product\ProductList\Toolbar $subject,
    \Closure $proceed,
    $collection
    ) {
    $currentOrder = $subject->getCurrentOrder();
    $result = $proceed($collection);

    if ($currentOrder) {
        if ($currentOrder == 'high_to_low') {
            $subject->getCollection()->setOrder('price', 'desc');
        } elseif ($currentOrder == 'low_to_high') {
            $subject->getCollection()->setOrder('price', 'asc');
        }
    }

    return $result;
    }

}


text:
Q: Can't create foreign key with laravel database migration I have a problem with my Laravel migrations :(
when i'm running php artisan migrate, it stops on a foreign key.
first migration
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::enableForeignKeyConstraints();
    Schema::create('fichefrais', function (Blueprint $table) {
        $table->char('idVisiteur', 4);
        $table->foreign('idVisiteur')->references('id')->on('visiteur');
        $table->char('mois',6);
        $table->primary(['idVisiteur', 'mois']);
        $table->integer('nbJustificatifs');
        $table->decimal('montantValide', 10, 2);
        $table->date('dateModif');
        $table->char('idEtat', 2);
        $table->foreign('idEtat')->references('id')->on('etat');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('fichefrais');
}

and the second
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::enableForeignKeyConstraints();
    Schema::create('lignefraishorsforfait', function (Blueprint $table) {
        $table->integer('id');
        $table->primary('id');
        $table->char('idVisiteur', 4);
        $table->char('mois',6);
        $table->foreign('idVisiteur')->references('idVisiteur')->on('fichefrais');
        $table->foreign('mois')->references('mois')->on('fichefrais');
        $table->char('libelle', 100);
        $table->date('date');
        $table->decimal('montant', 10, 2);
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('lignefraishorsforfait');
}

After running the command, I got this error :

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table
gsb_larave.#sql-176_b9 (errno: 150 "Foreign key constraint is
incorrectly formed") (SQL: alter table lignefraishors     forfait
add constraint lignefraishorsforfait_mois_foreign foreign key
(mois) references fichefrais (mois) on delete cascade on update
cascade)
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table
gsb_laravel.#sql-176_b9 (errno: 150 "Foreign key constraint is
incorrectly formed")

A: Does your visiteur table has an id as a primary key? If yes, does it have a data type has char and a length of 4. The idVisiteur in ** lignefraishorsforfait** table has a data type of char which must be the same as the primary key in the visiteur table.

A: The problem is that the foreign key you are declaring doesn't refer to a primary key. If you want to create a foreign key to a non-primary key, the column 'mois' in your 'fichefrais' table must be a column with a unique constraint on it

A: First of all your foreign keys must refer to a primary key (which most of the time is 'id' column).
Also you should create the tables in this order:
1- 'etat' table(which i dont see bcs you did not posted the migration code,),
2- 'fichefrais' table,
3- 'lignefraishorsforfait' table.
Just change the dates on database/migrations like this (example):
    2020_09_11_150331_create_etat_table.php
    2020_09_12_000000_create_fichefrais_table.php
    2020_09_13_000000_create_lignefraishorsforfait_table.php

You cannot create first the table which contains foreign key because will not have a key in which to refer.

A: Use this migrations:
First migration (fichefrais):
public function up()
{
    Schema::create('fichefrais', function (Blueprint $table) {
        $table->integer('idVisiteur')->unsigned()->nullable();
        $table->foreign('idVisiteur')->references('id')->on('visiteur');
        $table->char('mois',6);
        $table->primary(['idVisiteur', 'mois']);
        $table->integer('nbJustificatifs');
        $table->decimal('montantValide', 10, 2);
        $table->date('dateModif');
        $table->integer('idEtat')->unsigned()->nullable();
        $table->foreign('idEtat')->references('id')->on('etat');
    });
}

Second migration (lignefraishorsforfait):
public function up()
{
    Schema::create('lignefraishorsforfait', function (Blueprint $table) {
        $table->integer('id');
        $table->primary('id');
        $table->integer('mois')->unsigned()->nullable();
        $table->foreign('mois')->references('mois')->on('fichefrais');
        $table->integer('idVisiteur')->unsigned()->nullable();
        $table->foreign('idVisiteur')->references('idVisiteur')->on('fichefrais');
        $table->char('libelle', 100);
        $table->date('date');
        $table->decimal('montant', 10, 2);
    });
}

A: You are using MySQL, so Are your tables defined in InnoDB engine? MyISAM doesn't accept foreign key...


text:
Q: Fabric and Digits pods failing workspace in Xcode 7 and Swift 2.0 I updated to Xcode 7 and fixed the necessary code (syntax) changes for Swift 2.0. I updated my Podfile with these 2 entries:
  pod 'Fabric'
  pod 'Digits'

and now see many build errors (pasted below). Any ideas?
I ran sudo gem install cocoapods to update my Cocoapods, and then ran pod install and pod update in order to install 'Fabric' and 'Digits' pods.
Note: Prior to updating to Xcode 7, my project, which uses Digits, was building and working correctly!
Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_FABJLObjectDeserializer", referenced from:
      objc-class-ref in DigitsKit(DGTUserNetworking.o)
      objc-class-ref in DigitsKit(DGTAuthNetworking.o)
  "_OBJC_CLASS_$_FABJLObjectSerializer", referenced from:
      objc-class-ref in DigitsKit(DGTAuthNetworking.o)
  "_OBJC_CLASS_$_TFSScribe", referenced from:
      objc-class-ref in DigitsKit(Digits.o)
  "_OBJC_CLASS_$_TWTRAPIResponseValidator", referenced from:
      objc-class-ref in DigitsKit(DGTNetworkingHelper.o)
  "_OBJC_CLASS_$_TWTRAuthConfig", referenced from:
      objc-class-ref in DigitsKit(Digits.o)
  "_OBJC_CLASS_$_TWTRColorUtil", referenced from:
      objc-class-ref in DigitsKit(DGTAppearance.o)
  "_OBJC_CLASS_$_TWTRCoreLanguage", referenced from:
      objc-class-ref in DigitsKit(DGTAuthNetworking.o)
  "_OBJC_CLASS_$_TWTRDictUtil", referenced from:
      objc-class-ref in DigitsKit(DGTLogInAuthConfiguration.o)
      objc-class-ref in DigitsKit(DGTDeviceRegisterConfiguration.o)
  "_OBJC_CLASS_$_TWTRGuestSessionRefreshStrategy", referenced from:
      objc-class-ref in DigitsKit(Digits.o)
  "_OBJC_CLASS_$_TWTRKeychainWrapper", referenced from:
      objc-class-ref in DigitsKit(DGTSessionMigrator.o)
  "_OBJC_CLASS_$_TWTRNetworkingPipeline", referenced from:
      objc-class-ref in DigitsKit(DGTNetworkingHelper.o)
  "_OBJC_CLASS_$_TWTRResourcesUtil", referenced from:
      objc-class-ref in DigitsKit(DGTURLSessionConfig.o)
      objc-class-ref in DigitsKit(DGTResourcesUtil.o)
  "_OBJC_CLASS_$_TWTRScribeClientEventNamespace", referenced from:
      objc-class-ref in DigitsKit(DGTScribeEventLogger.o)
  "_OBJC_CLASS_$_TWTRScribeEvent", referenced from:
      objc-class-ref in DigitsKit(DGTScribeEventLogger.o)
  "_OBJC_CLASS_$_TWTRScribeService", referenced from:
      objc-class-ref in DigitsKit(Digits.o)
  "_OBJC_CLASS_$_TWTRSessionStore", referenced from:
      objc-class-ref in DigitsKit(Digits.o)
  "_OBJC_CLASS_$_TWTRURLSessionDelegate", referenced from:
      objc-class-ref in DigitsKit(DGTNetworkingHelper.o)
  "_OBJC_CLASS_$_TWTRUserSessionVerifier", referenced from:
      objc-class-ref in DigitsKit(DGTSessionVerifier.o)
  "_OBJC_CLASS_$_TWTRUtils", referenced from:
      objc-class-ref in DigitsKit(DGTAuthViewController.o)
      objc-class-ref in DigitsKit(DGTConfirmSignUpViewController.o)
      objc-class-ref in DigitsKit(DGTConfirmLogInViewController.o)
      objc-class-ref in DigitsKit(DGTUploadContactsViewController.o)
      objc-class-ref in DigitsKit(Digits.o)
      objc-class-ref in DigitsKit(DGTConfirmViewController.o)
      objc-class-ref in DigitsKit(DGTContacts.o)
      ...
  "_OBJC_CLASS_$_TwitterNetworking", referenced from:
      objc-class-ref in DigitsKit(DGTUserNetworking.o)
      objc-class-ref in DigitsKit(DGTContactsNetworking.o)
      objc-class-ref in DigitsKit(DGTAuthNetworking.o)
  "_TWTRAPIURLWithPath", referenced from:
      -[DGTUserNetworking verifyUser:completion:] in DigitsKit(DGTUserNetworking.o)
      -[DGTOAuthSigning OAuthEchoHeadersToVerifyCredentialsWithParams:] in DigitsKit(DGTOAuthSigning.o)
      -[DGTContactsNetworking uploadContactVCards:completion:] in DigitsKit(DGTContactsNetworking.o)
      -[DGTContactsNetworking lookupContactMatchesWithCursor:completion:] in DigitsKit(DGTContactsNetworking.o)
      -[DGTContactsNetworking destroyAllContactsWithCompletion:] in DigitsKit(DGTContactsNetworking.o)
      -[DGTAuthNetworking registerDeviceWithPhoneNumber:withVerificationType:completion:] in DigitsKit(DGTAuthNetworking.o)
      -[DGTAuthNetworking confirmAccountWithPhoneNumber:confirmationNumber:completion:] in DigitsKit(DGTAuthNetworking.o)
      ...
  "_TWTRCoreOAuthSigningOAuthEchoHeaders", referenced from:
      -[DGTOAuthSigning OAuthEchoHeadersForRequestMethod:URLString:parameters:error:] in DigitsKit(DGTOAuthSigning.o)
  "_TWTRCoreVersion", referenced from:
      +[Digits assertValidTwitterCoreVersion] in DigitsKit(Digits.o)
  "_TWTRNetworkingErrorDomain", referenced from:
      -[DGTAuthViewController startLogInProcessWithVerificationType:] in DigitsKit(DGTAuthViewController.o)
      -[DGTConfirmSignUpViewController startSignUpProcess] in DigitsKit(DGTConfirmSignUpViewController.o)
      -[DGTConfirmLogInViewController startLogInProcess] in DigitsKit(DGTConfirmLogInViewController.o)
      -[DGTPinCodeFormViewController startVerifyPINCode] in DigitsKit(DGTPinCodeFormViewController.o)
  "_TWTRNetworkingUserAgentHeaderKey", referenced from:
      +[DGTURLSessionConfig defaultAdditionalHeaders] in DigitsKit(DGTURLSessionConfig.o)
  "_TWTRScribeClientEventNamespaceEmptyValue", referenced from:
      -[DGTScribeViewEventLogger viewDidShow] in DigitsKit(DGTScribeViewEventLogger.o)
      -[DGTScribeViewEventLogger viewDidSucceed] in DigitsKit(DGTScribeViewEventLogger.o)
      -[DGTScribeViewEventLogger didShowFailureView] in DigitsKit(DGTScribeViewEventLogger.o)
      -[DGTScribeViewEventLogger errorDidOccurWithCode:] in DigitsKit(DGTScribeViewEventLogger.o)
      +[DGTScribeViewEventLogger scribeViewNameWithScribeView:] in DigitsKit(DGTScribeViewEventLogger.o)
      +[DGTScribeEventLogger digitsUniquesImpressionNamespace] in DigitsKit(DGTScribeEventLogger.o)
      +[DGTScribeEventLogger digitsImpressionNamespace] in DigitsKit(DGTScribeEventLogger.o)
      ...
  "_TWTRScribeEventImpressionClient", referenced from:
      +[DGTScribeEventLogger digitsEventNamespaceWithComponent:element:action:] in DigitsKit(DGTScribeEventLogger.o)
  "_TWTRScribeEventImpressionPage", referenced from:
      +[DGTScribeEventLogger digitsEventNamespaceWithComponent:element:action:] in DigitsKit(DGTScribeEventLogger.o)
  "_TWTRScribeEventUniquesClient", referenced from:
      +[DGTScribeEventLogger digitsUniquesImpressionNamespace] in DigitsKit(DGTScribeEventLogger.o)
  "_TWTRUserSessionVerifierDefaultDelay", referenced from:
      -[DGTSessionVerifier startVerification] in DigitsKit(DGTSessionVerifier.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

A: I think the problem is that you haven't included 'TwitterCore' into the pod file:
pod 'Fabric'
pod 'Digits'
pod 'TwitterCore'


text:
Q: How to change IP address to point to localhost? A sandbox enviroment of a web app is reachable directly by an IP address: http://<my_ip_address> without a login name.
Is there a way to make a virtual host in my local machine, named as <my_ip_address>, and change /etc/hosts so it will "redirect" to my localhost?
127.0.0.1 <my_ip_address>

So when I load the url http://<my_ip_address> the browser will point to my localhost? The way I can already redirect domain names.

A: Hosts file can only be used to associate a domain name with an IP; it cannot map IP to IP.
Altering IPs can be done by a firewall. On Linux, the default firewall is controlled by iptables commands. "man iptables" is the documentation. Google "explain iptables" for introductory explanations.
Some links:
http://linux.die.net/man/8/iptables
http://www.linuxnix.com/2009/12/iptables-in-linux-explained.html
http://blog.adityapatawari.com/2011/12/ip-packet-filtering-iptables-explained.html
Specifically, you want to change OUTGOING requests from your PC to an IP address (<my_ip_address>), so that they instead go to a different IP address, in this case 127.0.0.1. You want to perform NAT (Network Address Translation), given the "destination IP" (<my_ip_address>; e.g. 123.45.67.89), changing it to a different "destination IP" (127.0.0.1).
Try this (in place of 123.45.67.89, put the ip_address that needs to be altered):
iptables -t nat -A OUTPUT -p all -d 123.45.67.89 -j DNAT --to-destination 127.0.0.1

Details:
-t nat = table for translating one address to another
-A OUTPUT = append to the list of rules for locally-generated, outgoing, packets.  SECURITY WARNING: Make sure the rule includes this OUTPUT directive. If you don't, the rule would create a possible security hole, because matching Incoming packets from remote locations would also be directed to localhost.
-p all = apply to all protocols (tcp, udp, and icmp).
-d 123.45.67.89 = the original IP address that the packet was going to (its destination).
-j DNAT = if the rule matches (in this case, if an outgoing packet has destination IP 123.45.67.89), then handle it with DNAT, which alters the destination.
--to-destination 127.0.0.1 = tells DNAT what to do; replace the original destination with "127.0.0.1".
(NOTE: If you had a more complex situation, such as intercepting requests for specific web pages, an alternative solution might be to use "proxy" software.)


text:
Q: Express cookie-parser is not written on browser I am using express and cookie-parser on my nodejs rest server.
After the cookie was sent, I can see in the network:
Set-Cookie:xxxx=xxxxxxxxxxx; Path=/; Expires=Tue, 29 Dec 2015 18:14:06 GMT; HttpOnly
But there is nothing in my Browser cookie.
Is it because I'm using localhost?
```
const app = express();

app.use(cookieParser());

app.post('/login', (req, res) => {
  let email = req.body.email;
  let pass = req.body.password;
  (new User()).login(email, pass)
  .then(response => {
    if (response) {
      res.cookie('mid', email, { expires: new Date(Date.now() + 900000), httpOnly: true })
      .send('ok');
    } else {
      res.status(503).end();
    }
  });
});

```

A: I was using React + Relay and I need to add a
Relay.injectNetworkLayer(
  new Relay.DefaultNetworkLayer('/graphql', {
    credentials: 'same-origin',
  })
);

To make it work.