text:
Q: django selection field value I have created a selection field in the Django model, but when I try to call onchange in HTML the ajax code is not working. here is the code.
when I click on the match_recipient in this form I need the value on the ajax but now I don't get the value. There is showing undefined value
models.py
type = (
('catchall' , 'Catch All'),
('match_recipient','Match Recipient'),
('match_header','Match Header'),
)

class Routes(models.Model):
    expression_type = models.CharField(max_length=10,choices=type,default='catchall')
    actions = models.CharField(max_length=100)
    recipient = models.CharField(max_length=50)
    header_name = models.CharField(max_length=50)
    header_value = models.CharField(max_length=50)
    priority = models.IntegerField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

form.py
type = (
('catchall' , 'Catch All'),
('match_recipient','Match Recipient'),
('match_header','Match Header'),
)
class RouteForm(forms.ModelForm):
    expression_type = forms.ChoiceField(choices=type,widget=forms.Select(), required=True)
    actions = forms.CharField(help_text='Required', widget=forms.TextInput(attrs={'placeholder': 'address@example.com'}))
    recipient = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'recipient@example.com'}))
    header_name = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'X-Header-Name'}))
    header_value = forms.CharField( widget=forms.TextInput(attrs={'placeholder': 'Header Value'}))
    priority = forms.IntegerField(initial=0)

    class Meta:
        model = Routes
        fields = ('expression_type','actions','recipient','header_name','header_value','priority',)

template.html

       <form action="{% url 'route' %}" method="POST">
                {% csrf_token %}

                            Expression Type

                                {{ form.expression_type }}

                            Action

                             {{ form.actions }}

                            Recipient

                            {{ form.recipient }}

                            Header Name

                              {{ form.header_name }}

                            Header Value

                             {{ form.header_value }}

                            Priority

                              {{ form.priority }}

                            <button class="button is-info">
                                Add Route
                            </button>

  </form>


text:
Q: Stripping all but the last 2 letters of each string in a list I am trying to work out how to take a list of strings, and remove all of the letters in each string apart from the last two. Could someone please help? An example being ["Bob", "Steve", "Jeremy"], I only want the "ob", "ve", and "my". This has to work regardless of how long each string is. I only know how to do this with a specific sized string.

A: [i[-2:] for i in ["Bob", "Steve", "Jeremy"]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the center of circle $P$ and $Q$ Given that circle $P : Center(a,b)$  has a radius of $r_1$, circle $ Q : Center(c,d)$ has a radius of $r_2$. Circle $P$ and circle $Q$ intersects at point $A = (3,8)$ and $B = (3,-4)$ when $r_2=\frac{2}3r_1$.
If $$a,b,c,d \subseteq  \mathbb Z$$ when $$30 \lt 3c-2a \lt 40$$
Q : Find the center of circle $P$ and $Q$.
I have determined the pythagoras triangle between two circles;
$$a_1=6,b_1=|3-a|,c_1=r_1$$ and
$$a_2=6,b_2=|3-c|,c_2=\frac{2}3*r_1$$
Which using one of the many circle properties, I come up with
$$|3-a|=|3-c|$$ which i couldn't progress further.
Help me solve the problem anew or continue with my solution.

A:
I will not hesitate to put that into mathjax though.
For reference only.


text:
Q: ошибка при импорте vue-trix в nuxt Я пытаюсь подключить библиотеку vue-trix в nuxt, по официальной доке - https://github.com/hanhdt/vue-trix#getting-started. Делаю как сказано там через плагины, и потом пытаюсь вывести на странице компонент, но мне выбрасывает что windows in not defined, проблема не решается, помогите кто сможет, буду очень благодарен.

A: window - это окружение браузера. На сервере нет этого окружения. Если какой-либо метод, на сервере, будет обращаться к окружению браузера - будет ошибка. Что у Вас и происходит.  Не все пакеты/библиотеки расчитаны  для использования при ssr


text:
Q: Print HTML table using crystal reports in Asp.Net I am having web application which has one web page. Now I want to print that page using Crystal reports. Web page containing HTML
 tag. I am new at Asp.net.
i.e.

<form>

          Name :

          UserName1

          Address :

          INDIA

</form>

So can anyone gives some suggestions how to print HTML
 tag in crystal report directly?


text:
Q: Конвертация unsighed char в char*; Надо представить десятичное число в unsigned char и реализовать операции сложения. вычитания, умножения и деления.
Число вроде бы представил, но с операциями проблема. Выдает ошибку error C2664: 'int atoi(const char *)': cannot convert argument 1 from 'unsigned char [100]' to 'const char *' в строчках
    a = atoi(obj1.dec) + atoi(obj2.dec);
    b = atoi(obj1.dec) - atoi(obj2.dec);
    c = atoi(obj1.dec) * atoi(obj2.dec);
    d = atoi(obj1.dec) / atoi(obj2.dec);

Насколько я понял это из-за того, что у меня объекты класс типа char* а само число unsigned char. Как избавиться это этой ошибки?
#include <iostream>
#include <string>
using namespace std;

class oper;

class decimal
{
    unsigned char dec[100];
    size_t size;
    friend oper;
public:
    decimal(char*);
};

decimal::decimal(char* get)
{
    size = strlen(get);
    for (int i = size - 1; i >= 0; i--, get++)
    {
        dec[i] = *get;// или просто dec[i] = *get;
        cout << dec[i];
    }
    cout << endl;
}

class oper
{
    unsigned char *slozh;
    unsigned char *vich;
    unsigned char *del;
    unsigned char *umn;
public:
    oper(decimal, decimal);
};

oper::oper(decimal obj1, decimal obj2)
{
    char* sl;
    char* vi;
    char* de;
    char* um;
    int a, b, c, d;
    a = atoi(obj1.dec) + atoi(obj2.dec);
    b = atoi(obj1.dec) - atoi(obj2.dec);
    c = atoi(obj1.dec) * atoi(obj2.dec);
    d = atoi(obj1.dec) / atoi(obj2.dec);
    sl = itoa(a);
    vi = itoa(b);
    de = itoa(c);
    um = itoa(d);

}

int main()
{
    //cout << "Vvedite 2 chisla: " << endl;
    //char* a;
    //char* b;
    //a = b = NULL;
    //cin >> a >> b;
    //decimal d1(a);
    //decimal d2(b);
    decimal a = "123321";
    decimal b = "123456";

    oper o(a, b);

    system("pause");
    return 0;
}

само задание:

A: Можно просто пойти по пути приведения:
a = atoi((char*)obj1.dec) + atoi((char*)obj2.dec);
b = atoi((char*)obj1.dec) - atoi((char*)obj2.dec);
c = atoi((char*)obj1.dec) * atoi((char*)obj2.dec);
d = atoi((char*)obj1.dec) / atoi((char*)obj2.dec);

Но!
Зачем вам вообще unsigned char dec[100];? Почему он должен быть unsigned? Лично я не вижу ни одной для этого причины, зато сразу несколько - для char dec[100];. Вам не нужно будет выполнять приведение типов, в dec[i] = *get; будет однотипное присваивание (кстати, а завершить строку нулевым символом вы не хотите?). Так что подумайте о том, чтоб просто убрать unsigned...
Да, и itoa у вас вызывается не так, как нужно. Но это уже второй вопрос :) - как и функционирование программы (я его не смотрел).


text:
Q: Python Multindex - How can I create a hierarchical multindex in a dataframe that has time only as indexes? Say I have a Dataframe df that looks like this
       9-2021   8-2021  7-2021
Datetime
13:00:00    0.000   0.000   0.0000
13:05:00    -0.003  -0.005  0.0010
13:10:00    -0.009  -0.005  -0.0020

...

23:50:00   0.004   -0.001  0.006
23:55:00    0.006  -0.008  -.006
00:00:00    0.005   -0.001  -.003
00:05:00    0.004  -0.002 -0.008
00:10:00   -0.010   0.006  -0.001
00:15:00   0.008  0.003  -0.001

...

23:50:00  -0.001  0.005  0.009
23:55:00    0.006  -0.008  -.006
00:00:00    0.005   -0.001  -.003
00:05:00    0.004  -0.002 -0.008

I would like convert my index into a multindex in order to create a further level of segmentation to specify that I am moving to subsequent day every time I am crossing midnight. So it should look like this and so on for following days. Any ideas?
            9-2021  8-2021  7-2021
Day   Datetime

D     13:00:00  0.000   0.000   0.0000
      13:05:00  -0.003  -0.005  0.0010
      13:10:00  -0.009  -0.005  -0.0020
      ...
      23:50:00   0.004   -0.001  0.006
      23:55:00    0.006  -0.008  -.006
D+1   00:00:00    0.005   -0.001  -.003
      00:05:00    0.004  -0.002 -0.008
      00:10:00   -0.010   0.006  -0.001
      00:15:00   0.008  0.003  -0.001
      ...

      23:50:00  -0.001  0.005  0.009
      23:55:00    0.006  -0.008  -.006

D+2   00:00:00    0.005   -0.001  -.003
      00:05:00    0.004  -0.002 -0.008

A: This should work for you. You can play around with the numbering, but it was easiest to start at zero. You'll see as you go through the example.
data='''       9-2021   8-2021  7-2021
Datetime
13:00:00    0.000   0.000   0.0000
13:05:00    -0.003  -0.005  0.0010
13:10:00    -0.009  -0.005  -0.0020
23:50:00   0.004   -0.001  0.006
23:55:00    0.006  -0.008  -.006
00:00:00    0.005   -0.001  -.003
00:05:00    0.004  -0.002  -0.008
00:10:00   -0.010   0.006  -0.001
00:15:00   0.008  0.003  -0.001
23:50:00  -0.001  0.005  0.009
23:55:00    0.006  -0.008  -.006
00:00:00    0.005   -0.001  -.003
00:05:00    0.004  -0.002  -0.008 '''

import io
df = pd.read_csv(io.StringIO(data), sep=' \s+', engine='python')

# use cumcount to count values in each group
df['day_counter'] = df.groupby(df.index').cumcount()+1

# set data to np.nan for further processing
df.loc[df.index!='00:00:00', 'day_counter'] = np.nan

# forward fill
df['day_counter'] = df['day_counter'].fillna(method="ffill")
df['day_counter'] = df['day_counter'].fillna(0)
df['day_counter'] = df['day_counter'].fillna(0).astype('int')

# set multiIndex
df.set_index(['day_counter', df.index], inplace=True)

df

                      9-2021  8-2021  7-2021
day_counter Datetime
0           13:00:00   0.000   0.000   0.000
            13:05:00  -0.003  -0.005   0.001
            13:10:00  -0.009  -0.005  -0.002
            23:50:00   0.004  -0.001   0.006
            23:55:00   0.006  -0.008  -0.006
1           00:00:00   0.005  -0.001  -0.003
            00:05:00   0.004  -0.002  -0.008
            00:10:00  -0.010   0.006  -0.001
            00:15:00   0.008   0.003  -0.001
            23:50:00  -0.001   0.005   0.009
            23:55:00   0.006  -0.008  -0.006
2           00:00:00   0.005  -0.001  -0.003
            00:05:00   0.004  -0.002  -0.008


text:
Q: Environment variable set in tcsh script is not available for bash script I have a bash script and a tcsh script, my tcsh scripts sets some environment variables and those variables are not available for bash subsequent steps after tcsh script execution. Any suggestion how to make environment variables set in tcsh available for bash.
Here is sample code.
Bash script:
$Naga> cat sample_bash.sh
#!/bin/bash
export SOURCE="NO SOURCE"
./sample_tcsh.csh
echo "Source value in bash is $SOURCE"

tcsh script
$Naga> cat sample_tcsh.csh
#!/usr/bin/tcsh -fvx
echo "SOURCE initially $SOURCE"
setenv SOURCE "MY DATASOURCE"
echo "SOURCE value in tcsh is $SOURCE"
exit(0)

Results
$Naga> ./sample_bash.sh
SOURCE initially NO SOURCE
SOURCE value in tcsh is MY DATASOURCE
Source value in bash is NO SOURCE

A: There is no global environment. Each process has its own environment it can freely change. Changes in a process evironment propagate to new child processes, but0 do not affect any other exisring process.
Thus a shell cannot change its own environment by running an external program. A shell can execute a script without creating a new process though. This is called sourcing. So if a script modifies an environment variable, this affects the sourcing shell. However bash cannot source a tcsh script, and vice versa.
So if you have a tcsh script and a bash script, the only way to propagate environment changes from tcsh to bash is to have the tcsh script call the bash script. Not the other way around.


text:
Q: Possible to simulate the mySQL functionality ON DUPLICATE KEY UPDATE with SQL Server I am using SQL Server 2008, and would like to be able to take advantage of something like mySQL's ON DUPLICATE KEY UPDATE clause for INSERT statements
Current legacy code does a delete and subsequent insert that is running into concurrency issues with duplicate key inserts from separate threads:
Here is the error I see in my production environment:
Violation of PRIMARY KEY constraint 'PK_Audience'. Cannot insert duplicate key in object 'dbo.Audience'.

(sp_ContentUpdate)
Primary Key:
AudienceId, VersionId

Offending SQL:
DELETE  FROM  dbo.Audience
WHERE   VersionId = @VersionId

IF  @AudienceXml IS NOT NULL
    BEGIN
    INSERT INTO dbo.Audience (
        VersionId,
        AudienceId,
        CreatedDate,
        CreatedByPersonId,
        )
    SELECT  @VersionId,
            AudienceId,
            GETUTCDATE(),
            @PersonId
                FROM    dbo.Audience
    JOIN    @AudienceXml.nodes('/Audiences/Audience') node(c)
    ON      Audience.AudienceName = c.value('@Name', 'nvarchar(50)')
    END

Wrapping this TSQL in a transaction seems to either remove the concurrency issue or mask the issue by changing the timings.  However, I do not think wrapping in a transaction has actually solved the concurrency.
Perhaps I am going about this wrong.  Your suggestions are appreciated.

A: You should read about how to use the MERGE statement in Microsoft SQL Server 2008.  This is actually the ANSI/ISO SQL way of handling this situation (MySQL's ON DUPLICATE KEY is a proprietary MySQLism).
See docs on the MERGE statement at MSDN.

A: Well, Bill beat us all, but here's a sample of what it might look like:
Merge dbo.Audience As target
Using   (
        Select @VersionId As VersionId, AudienceId, GetUtcDate() As CreatedDate, @PersonId As CreatedByPersonId
        From dbo.Audience
            Join @AudienceXml.nodes('/Audiences/Audience') node(c)
                On Audience.AudienceName = c.value('@Name', 'nvarchar(50)')
        )
When Matched Then
    Update
    Set VersoinId = target.VersionId, Audience = target.AudienceId
        , CreatedDate = target.CreatedDate
        , CreatedByPersionId = target.CreatedByPersonId
When Not Matched Then
    Insert dbo.Audience(VersionId, AudienceId, CreatedDate, CreatedByPersonId)


text:
Q: Android non-native sip I am developing a app that uses non-native sip to signalling. I want to know how my app will be notified when a sip call arrives. I know that in general I can send braodcast with intent and catch that with a receiver. The native sip works like that. But with a non-native, how can I achieve that? I need to create a custom receiver? And how do I send the Intent? Can I serialize the intent in a json?

A: On android, application may be suspended (the device is going to deep sleep) for short periods, but it's still possible to have them running regularly.
First, your java application should implement a Service. This will allow your application to run in the background:
Implement your Service in YourSipAppService.java:
(and start it from your GUI code)
public class YourSipAppService extends Service

In Manifest:
    <service
        android:name=".YourSipAppService"
        android:icon="@drawable/ic_launcher" >
    </service>

Then, you can use startForeground, to put your service in a "foreground state" (this tells android to not kill the service)
Using the above, your application will always be active even without a GUI. Handle the native sip stack from this Service so you can access the SIP messages.
Then, you'll got to solve issue related to deep sleep. In practice, even when the device is inactive, it will still check sockets regularly and your app will receive the INVITEs. In order to maintain connectivity, your SIP application should use only connected protocol (ie: TCP, TLS, not UDP)
When doing SIP exchanges or calls, you can activate lock to ask the system to maintain power at least for the duration of the SIP transactions, or the complete SIP calls:
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
int wifi_mode = WifiManager.WIFI_MODE_FULL;
if (Build.VERSION.SDK_INT >= 12)
    wifi_mode = 3; /* WifiManager.WIFI_MODE_FULL_HIGH_PERF */
mWifiLock = mWifiManager.createWifiLock(wifi_mode, "com.yoursipapp.wifi");
if (mWifiLock != null)
    mWifiLock.setReferenceCounted(false);

Then, when you requires to have full wifi power:
mWifiLock.acquire();

And when you do not require it any more:
mWifiLock.release();

In order to announce the call, you need to turn on the device and display an activity on top of the keyguard. Various API needs to be used, this may depends on the Android version you wish to support. Here is some code showing how to setup and acquire a Screen Lock and a Keyguard Lock that can be added to your Service:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mScreenWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |
                                 PowerManager.ACQUIRE_CAUSES_WAKEUP |
                                 PowerManager.ON_AFTER_RELEASE,
                                 "YourSipAppServiceKeepScreenActive");
mScreenWakeLock.setReferenceCounted(false);
mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
mKeyguardLock = mKeyguardManager.newKeyguardLock("com.yoursipapp.unlockforincomingcall");

You will acquire this lock when receiving a call:
mScreenWakeLock.acquire();
if (mKeyguardLock != null && Build.VERSION.SDK_INT < 21) {
    mKeyguardLock.disableKeyguard();
}

Then, in the Activity which answer calls, you can also add this:
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                     WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                     WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

  ...
}

To conclude, once you've done all that, you can popup your incoming call Activity:

*

*Your Activity will appear above the keyguard.

*The phone/device will be turned on when receiving a call.

*The wifi will have full power, when needed!


text:
Q: fancybox open relative div I'm trying to figure out how to open a div in fancybox relatively from the link that was clicked.

?

This is the help text

I know I can add something like #uniqueDiv to a and then a div with id uniqueDiv, however I would prefer that when the link is clicked, it opens the closest div with class help.
I tried something like this with no luck:
$('.more-info a').click(function(e){
    $(this).parent().next().fancybox();
    e.preventDefault();
});

Any help would be much appreciated.
-Ryan

A: I thought about this problem for a few more hours and decided to approach it differently, since I was pretty much at a dead end. I was thinking that if I can't target a relative div, maybe I can then auto-assign the href and id values, so each link can then be targeted via its id.
This actually worked out beautifully and meets all my requirements:
$('.more-info a').each(function(index){
    var x = index + 1;
    $(this).attr('href', '#box' + x);
    var li = $(this).parent().parent();
    $('.help', li).attr('id', 'box' + x);
}).fancybox();

*

*$('.more-info a').each(function(index){ I target all my links and loop through them.

*var x = index + 1; The index starts at 0, but for readability, I start it at 1.

*$(this).attr('href', '#box' + x); I take the current link's href value (currently #) and replace it with #box[INDEX] where index is a unique, auto-incrementing number.

*var li = $(this).parent().parent(); I move back a view elements so I can hone in on my hidden div .help.

*$('.help', li).attr('id', 'box' + x); I now target the .help div and add an attribute called id and set it to box[INDEX]. I now have the necessary association between link and hidden div so that fancybox can do its magic.

*}).fancybox(); This lets fancybox know to open my links with it.

jQuery functions used:
.each(), .attr(), .parent()
Any suggestions or improvements are still appreciated.
-Ryan


text:
Q: VB6 POS Printer - Logo register Hy, I have a printer Star TSP100ECO [USB] and I made a program to print a ticket, but I should also add the logo on the ticket.
The problem is that I do not understand how to add a logo to the ticket with the help of ESC FS q.
Adding the logo using the printers configuration tool is not an option.
Registering the logo on page 3-98. -> http://www.starmicronics.com/support/Mannualfolder/linemode_cm_en.pdf
The picture that I wanted to print is in GIF format and is black and white.
Thank you in advance for your help.
Sorry for my bad English.

A: Loading data can be done using the commands specified in the maual, but this will require a fair bit of picture decoding to preload the logo into the printer.
If paintpicture is working other than having to disable automatic cutting, then that will be the easiest way to go.
1) disable automatic cutting
2) print what you need from vb
3) printer.print chr(27) & chr(100) & chr(0)
Part 3 will perform the cut for you (in this case a full cut) partial cut can be used if you prefer by changing the 0 to another value according to the manual.


text:
Q: What exactly does array of size N mean? Sorry if this may be a stupid question, but in my Java book I read this sentence:

Thus, when iterating over an array of size N, the enhanced for obtains
the elements in the array in index order, from 0 to N-1.

I am reading about the for-each style for loop, and suddenly the book is talking about an array of size N and an index order of 0 to N-1. The book does not explain what N means, and strangely enough I googled a lot but could not find the answer. Maybe I am thinking to literally or too difficult. What does size N mean? Can someone give more information about this?

A: The size N (or whatever it is named) is the number of items in your array or collection. Since indices are zero-based (as in other languages like C, Python, OCaml, ...), they run from 0 to N – 1.
As an example, if you have a 20-item array, N = 20 and the valid indices for this array run from 0 to 19.

A: An array is basically a fixed size list of elements. Here N refers to the size (or length) of the array. So it's the number of elements that it can store.
Elements in an array are obtained by using a zero-based index. That means the first element is at index 0, the second at index 1, and so on. Therefore, if the array has size N, the last element will be at index N-1 (because it starts with 0). Thus the index is in the interval [0, N-1].
Here is the official doc for arrays explaining the basics in detail.

A:
Java provides a data structure, the array, which stores a fixed-size
  sequential collection of elements of the same type. An array is used
  to store a collection of data, but it is often more useful to think of
  an array as a collection of variables of the same type.

N is the number of items that you can store in your array.
See this link for more information:
http://www.tutorialspoint.com/java/java_arrays.htm

A: Hi Simon when an array has size N means that has no defined dimension that can be 1 to N.
When you don't know exactly wich is the size then in "math language" you just say N size. Be careful anyway that in Java an array can be initialized with size 0
Example:
Integer[] array = new Integer[];

Creates an empty array with length = 0.
I suggest you to have a look not only at your book but also at the official java tutorials in order to have practical code examples

A: For example, an array with 5 elements means N = 5.

A: N come from Natural number https://en.wikipedia.org/wiki/Natural_number but in java think of it as an int >= 0

A: Array size of N means the size of that array is N. It is like saying...that container holds 5 gallons or 10 gallons etc. So for a array size of 5, N=5 and for a array size of 9, N=9 and so on.
If N=9, we can store 9 elements in that array and we will access these 9 elements starting from the index 0 all the way up to index 8. Remember that there is no 9th index here because we are starting from the 0th index and when we reach index 8, we will be accessing the 9th element.
This may seem a bit tough to digest for you at this stage of your programming career....you will become comfortable after a few months, after you have seen this a few more times.

A: N is just a variable, it represents the amount of items could be in the array. The array could be 5 items, it could be 10 items, it could be 1000 items, it could be N items. Arrays begin from index 0, so the loop would run 0, 1, 2, 3 ... N - 3, N - 2, N - 1 times.


text:
Q: How can you plot two lists of different 'first dimension' using matplotlib? I am trying to write some code that plots a graph whilst going through a for loop and updates the graph with each iteration using matplotlib. I am plotting the voltage_trim[0:index] in order to avoid the problem of having two lists of different size but I still get an error that x and y must have same first dimensions. Does anyone know how one plots two lists of different size to have an updating real time graph?
voltage_trim = range(16)
current_meas = []

fig1 = plt.figure()

for index, value in enumerate(voltage_trim):

    current_meas.append(random.randint(0,10))

    plt.cla()
    plt.plot(voltage_trim[:index], current_meas )

A: Your idea of trimming the x values is good. To make it work use voltage_trim[:index+1].
The index you get from enumerate starts at zero, but for the first returned element you want to already select one x value. Therefore you need to get all the values up to index+1.


text:
Q: In C#, why is String a reference type that behaves like a value type? A String is a reference type even though it has most of the characteristics of a value type such as being immutable and having == overloaded to compare the text rather than making sure they reference the same object.
Why isn't string just a value type then?

A: Not only strings are immutable reference types.
Multi-cast delegates too.
That is why it is safe to write
protected void OnMyEventHandler()
{
     delegate handler = this.MyEventHandler;
     if (null != handler)
     {
        handler(this, new EventArgs());
     }
}

I suppose that strings are immutable because this is the most safe method to work with them and allocate memory.
Why they are not Value types? Previous authors are right about stack size etc. I would also add that making strings a reference types allow to save on assembly size when you use the same constant string in the program. If you define
string s1 = "my string";
//some code here
string s2 = "my string";

Chances are that both instances of "my string" constant will be allocated in your assembly only once.
If you would like to manage strings like usual reference type, put the string inside a new StringBuilder(string s). Or use MemoryStreams.
If you are to create a library, where you expect a huge strings to be passed in your functions, either define a parameter as a StringBuilder or as a Stream.

A: In a very simple words any value which has a definite size can be treated as a value type.

A: It is not a value type because performance (space and time!) would be terrible if it were a value type and its value had to be copied every time it were passed to and returned from methods, etc.
It has value semantics to keep the world sane. Can you imagine how difficult it would be to code if
string s = "hello";
string t = "hello";
bool b = (s == t);

set b to be false? Imagine how difficult coding just about any application would be.

A: Also, the way strings are implemented (different for each platform) and when you start stitching them together.  Like using a StringBuilder.  It allocats a buffer for you to copy into, once you reach the end, it allocates even more memory for you, in the hopes that if you do a large concatenation performance won't be hindered.
Maybe Jon Skeet can help up out here?

A: It is mainly a performance issue.
Having strings behave LIKE value type helps when writing code, but having it BE a value type would make a huge performance hit.
For an in-depth look, take a peek at a nice article on strings in the .net framework.

A: A string is a reference type with value semantics. This design is a tradeoff which allows certain performance optimizations.
The distinction between reference types and value types are basically a performance tradeoff in the design of the language. Reference types have some overhead on construction and destruction and garbage collection, because they are created on the heap. Value types on the other hand have overhead on assignments and method calls (if the data size is larger than a pointer), because the whole object is copied in memory rather than just a pointer. Because strings can be (and typically are) much larger than the size of a pointer, they are designed as reference types. Furthermore the size of a value type must be known at compile time, which is not always the case for strings.
But strings have value semantics which means they are immutable and compared by value (i.e. character by character for a string), not by comparing references. This allows certain optimizations:
Interning means that if multiple strings are known to be equal, the compiler can just use a single string, thereby saving memory. This optimization only works if strings are immutable, otherwise changing one string would have unpredictable results on other strings.
String literals (which are known at compile time) can be interned and stored in a special static area of memory by the compiler. This saves time at runtime since they don't need to be allocated and garbage collected.
Immutable strings does increase the cost for certain operations. For example you can't replace a single character in-place, you have to allocate a new string for any change. But this is a small cost compared to the benefit of the optimizations.
Value semantics effectively hides the distinction between reference type and value types for the user. If a type has value semantics, it doesn't matter for the user if the type is a value type or reference type - it can be considered an implementation detail.

A: Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...
(Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)

A: How can you tell string is a reference type? I'm not sure that it matters how it is implemented. Strings in C# are immutable precisely so that you don't have to worry about this issue.

A: This is a late answer to an old question, but all other answers are missing the point, which is that .NET did not have generics until .NET 2.0 in 2005.
String is a reference type instead of a value type because it was of crucial importance for Microsoft to ensure that strings could be stored in the most efficient way in non-generic collections, such as System.Collections.ArrayList.
Storing a value-type in a non-generic collection requires a special conversion to the type object which is called boxing. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap.
Reading the value from the collection requires the inverse operation which is called unboxing.
Both boxing and unboxing have non-negligible cost: boxing requires an additional allocation, unboxing requires type checking.
Some answers claim incorrectly that string could never have been implemented as a value type because its size is variable. Actually it is easy to implement string as a fixed-length data structure containing two fields: an integer for the length of the string, and a pointer to a char array. You can also use a Small String Optimization strategy on top of that.
If generics had existed from day one I guess having string as a value type would probably have been a better solution, with simpler semantics, better memory usage and better cache locality. A List<string> containing only small strings could have been a single contiguous block of memory.

A: Actually strings have very few resemblances to value types. For starters, not all value types are immutable, you can change the value of an Int32 all you want and it it would still be the same address on the stack.
Strings are immutable for a very good reason, it has nothing to do with it being a reference type, but has a lot to do with memory management. It's just more efficient to create a new object when string size changes than to shift things around on the managed heap. I think you're mixing together value/reference types and immutable objects concepts.
As far as "==": Like you said "==" is an operator overload, and again it was implemented for a very good reason to make framework more useful when working with strings.

A: The fact that many mention the stack and memory with respect to value types and primitive types is because they must fit into a register in the microprocessor. You cannot push or pop something to/from the stack if it takes more bits than a register has....the instructions are, for example "pop eax" -- because eax is 32 bits wide on a 32-bit system.
Floating-point primitive types are handled by the FPU, which is 80 bits wide.
This was all decided long before there was an OOP language to obfuscate the definition of primitive type and I assume that value type is a term that has been created specifically for OOP languages.

A: Isn't just as simple as Strings are made up of characters arrays. I look at strings as character arrays[]. Therefore they are on the heap because the reference memory location is stored on the stack and points to the beginning of the array's memory location on the heap. The string size is not known before it is allocated ...perfect for the heap.
That is why a string is really immutable because when you change it even if it is of the same size the compiler doesn't know that and has to allocate a new array and assign characters to the positions in the array. It makes sense if you think of strings as a way that languages protect you from having to allocate memory on the fly (read C like programming)


text:
Q: Overriding overloaded member functions that call each other in cpp I have designed a class which uses overloaded member functions that call each other such that functions with additional arguments modify member variables that the original function relies on. It works as expected/intended when inheritance is not involved, but I found myself reusing the code often enough to want to create an abstract class.
I did this by having the original member function exit with an error in the abstract class, but still implementing the overloaded functions that modify member variables before calling the original function. This is done with the intent of only having to override the original function in my derived classes. However, when I create a derived class from this abstract class and supposedly override the member function, the functions that are not overridden still seem to be using the abstract class's definition of the member function-- the one that exits with an error. Here is a minimal example that causes the unexpected behavior.
#include <iostream>
#include <string>
#include <cstdlib>

class Base
{
    // this class exists only to be derived from
public:
    void write_message()
    {
        std::cerr << "Base is an abstract class not intended for direct use in"
                  << " programs." << std::endl;
        exit(1);
    }

    void write_message(std::string NewMessage)
    {
        Message = NewMessage;
        write_message();
    }

protected:
    std::string Message = "This is the default message";
};

class Derived : public Base
{
public:
    using Base::write_message;
    void write_message()
    {
        std::cout << Message << std::endl;
    }
private:
    // intentionally blank
};

int main() {
    Derived MyObject;
    MyObject.write_message("Here is a modified message");

    return 0;
}

As I'm sure is clear from this example, I am already aware of the common pitfall involving inheriting overloaded member functions which is topic of other questions on this site, which is needing to have using Base::write_message in my derived class. A couple of those questions include: this and this. What those questions don't address is this issue involving the overriding of write_message not working the way I expect it to.
What is missing here? I can't reason out why Base::write_message() would be used of Derived::write_message when calling MyObject.write_message("Here is a modified message"); in the code above.
I am using cpp17 and g++12.2.1 on linux.

A: What you should use is the virtual methods. Without them, it's not the overriding, but so called hiding. That's, you may define a method within the derived class which will have the same calling semantics as in base class, but it will hide the method from the base class.
Here is rewritten your example:
#include <iostream>
#include <string>
#include <cstdlib>

class Base
{
    // this class exists only to be derived from
public:
    virtual ~Base() = default;  // It's better to have a virtual destructor if there is at least one virtual method.

    virtual void write_message() = 0;   // Pure virtual method. It defines the calling interface only and must be overridden to be used.

    void write_message(const std::string& NewMessage)   // It's better to use the const-reference in order to escape unneeded copying.
    {
        Message = NewMessage;
        write_message();    // Call the _implementation_
    }

protected:
    std::string Message = "This is the default message";
};

class Derived : public Base
{
public:
    using Base::write_message;

    void write_message() override   // 'override' key-word ensures that we are overriding 'right' method and helps against of typos etc.
    {
        std::cout << Message << std::endl;
    }
private:
    // intentionally blank
};

int main() {
    // Yes, it points to the Base, but because of virtuality...
    Base* MyObject = new Derived;
    MyObject->write_message("Here is a modified message"); // ... it invokes the Derived::write_message() here.
    delete MyObject;    // Don't forget to free the memory.

    return EXIT_SUCCESS;
}


text:
Q: Can't shutdown when logged in with an administrator account While shutting down Ubuntu 11.10 it returns to the Users menu, and remains there.
The problem is only when I am using an administrator account. I have to go back to a guest account to completely shut down the computer.
I am using a Dell Inspiron Mini 1018.

A: *

*check if any other user is logged in

*check if you have any virtual machine still running (usually kvm/qemu have this behavior)

*in the users menu you have an option at the right upper side to shutdown. Have a try at it.

A: kamil is right - you can't shut down if there are other users (even guest) logged in.  To force a shutdown even if there are other users logged in issue the command
sudo shutdown -h now

This will lose any data if there is an open application that has data that is not saved.  I haven't tested this with running VMs but I believe it will still work.


text:
Q: Mongoose bulk update/save I read that Model.collection.insert is faster than Model.create.
I have 1kk users in User.collection, I want to update them all every 1 minute:
This is my code:
const mongoose = require('mongoose');
const User = require('./models/user');
const async = require('async');

function getRandomArbitrary(min, max) {
    return Math.round(Math.random() * (max - min) + min);
}

User.find({}, (err, docs) => {
    async.mapSeries(docs, (doc, callback) => {
        doc.value = getRandomArbitrary(0,100);
        doc.save((err) => {
            callback(err, doc);
        });
    }, (err, result) => {
        if (err) return err;
        console.log('completed');
    });
});

Is it a good way to accomplish this? It takes mode than 1 minute, How do I can increase performance?

A: The way you are doing it now is to wait for one thing being saved before going to the other one. You can parallelize it (completely or partially) to make it finish faster.
You can use async.map instead of async.mapSeries to make it work in parallel.
Or you can use async.mapLimit to limit the number of operations taking place at the same time.
See:

*

*https://caolan.github.io/async/docs.html#map

*https://caolan.github.io/async/docs.html#mapLimit

*https://caolan.github.io/async/docs.html#mapSeries
Example with async.map:
User.find({}, (err, docs) => {
    async.map(docs, (doc, callback) => {
        doc.value = getRandomArbitrary(0,100);
        doc.save((err) => {
            callback(err, doc);
        });
    }, (err, result) => {
        if (err) return err;
        console.log('completed');
    });
});

Example with async.mapLimit:
const LIMIT = 10;
User.find({}, (err, docs) => {
    async.mapLimit(docs, LIMIT, (doc, callback) => {
        doc.value = getRandomArbitrary(0,100);
        doc.save((err) => {
            callback(err, doc);
        });
    }, (err, result) => {
        if (err) return err;
        console.log('completed');
    });
});

Just the LIMIT to whatever number you want.


text:
Q: Automated push notifications from list, array or database based on user settings swift iOS I'm new to coding and was wondering if anyone had experience with sending out a randomly picked push notification from a list, database, array or whatever with the user being able to control at which time they will receive it. I would preferably automate the process. Thanks for your time and help. I´m currently creating the app for IOS with Swift.

A: This could be done with UserNotifications in Swift, where the user could set a specific date and time, and then using that for the scheduled notification. I haven't done this before, but this is how I would imagine it's done.


text:
Q: PDO shown as "Not Installed" in Froxlor I am trying to install froxlor on Ubuntu 14.04 and have already installed the PHP5 MYSQL PDO Extension.
When running code:
php -i|grep PDO

It results in
PDO
PDO support => enabled
PDO drivers => mysql
PDO Driver for MySQL => enabled

But froxlor shows the PDO Extension as "Not Installed".
Curl is also installed and is shown as "Not Installed".
If it helps any here is a piccture of the install result page: Google Drive
Is there any way to fix this?

A: There are at least three different php.ini files when using php on Ubuntu.
/etc/php5/cli/php.ini
/etc/php5/apache2/php.ini
/etc/php5/cgi/php.ini

They can differ and depending on how php is invoked one or the other .ini file is used.
phpinfo() / php -i can tell you which one was used.


text:
Q: How to retrieve images from SQL Server database into WPF form?? (LINQ, Databinding, SQL) I have a cheapo window where I insert data into a database. My db-columns are the following:
col name(varchar),
col age (int),
col photo (image) (all NOT NULL)

Now I want to retrieve the info from the db into my window. I have a listbox where I retrieve the names like this (LINQ query)
public void updateListbox(){
DataClasses1DataContext dc = new DataClasses1DataContext();
var query = from s in dc.tablename select s;

_listBox1.ItemsSource = query.ToList();
}

My xaml code for binding looks like this:
<ListBox ... DisplayMemberPath="Name"/>

so the names are now being displayed in the listbox.
My next step is to display the image/photo of the representative person that is selected in the listbox on my window/form. I did it with the age property in a textblock like this:
<TextBlock ... Text="{Binding ElementName=_listBox1, Path=SelectedItem.Age}" />

but I have no idea how to retrieve the image into my wpf window.
I save the image like this
byte[] image = File.ReadAllBytes(@imagepath);
...
sqlcommandobject.Parameters.Add(new SqlParameter("@Photo", image));
...

by using openFileDialog to load the image(-path) before insterting into the db. Just retrieving is my problem now. I really would like to keep the binding as simple as it is at this moment, but I guess there is no way to retrieve the image by doing something like this:
<Image ... Source="{Binding ElementName=_listBox, Path=SelectedItem.Photo}" />

As the binary data has to be converted back to an image object(?), and I'm lost on how to do that and conbine this with the bindings. Anyone have an idea?
Thanks for reading!

A: You can create a converter to convert the value from byte[] to BitmapSource:
[ValueConversion(typeof(byte[]), typeof(BitmapSource))]
public class ByteArrayToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        byte[] bytes = (byte[]) value;
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.StreamSource = ms;
            image.EndInit();
            return image;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        BitmapSource image = (BitmapSource) value;
        BitmapEncoder encoder = new PngBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(image));
        using (MemoryStream ms = new MemoryStream())
        {
            encoder.Save(ms);
            return ms.ToArray();
        }
    }
}

(The ConvertBack method encodes to PNG, you might want to change that depending on your needs. Or you might not need ConvertBack at all...)

A: Bind the image to ObjectDataProvider  that convert the parameter to image.


text:
Q: Turning a workflow on and off via apex? I have a power user who reviews a bunch of workflow notifications. When she goes on vacation she wants to remove herself from the notifications and then add herself back. How Can I create an interface so she can do this?

A: I wouldn't do this with much Apex.  I'd use a hierarchical custom setting that you check on in the workflow formulas.  Either that or put the target of the workflow to a queue that the person has access to.
But why would this be a thing?

A: If she is the only recipient of the workflow then you can think of deactivating it during her absence but if there are other recipients as well then it has to be something on the user level.
If the prior is true , I would suggest add one Custom Label to the workflow and change it during her absence so that the workflow won't fire. If she is a power user, I believe she must have access to Custom Label which she can edit herself.
However this works in one or two scenarios. If you have similiar use cases, I would suggest design something using Metadata API or even better Tooling API


text:
Q: Why have I randomly lost two upvotes on an answer? This answer which I wrote on Jan 7 has been my most upvoted answer up till now.
Last night when I was looking at my profile, it still had 7 upvotes, but this morning it only has 5.
How can this have happened, when it hasn't been downvoted (check the vote count), and I last edited it 15 minutes after posting it?
I'm not too worried about the votes, but just interested as to why that happened?

A: I can think of a couple of cases:

*

*The users who provided those two up-votes are destroyed - all posts are deleted and all votes removed.

*The users were sock puppets of another user that also voted for that answer - so you ended up with 3 votes from the same person or 2 votes from 2 people. If the socks were discovered and merged then the duplicate votes will be removed.


text:
Q: How to use fuzzy and match phrase? I'm using elasticsearch version 7.6.2
I want to search for a sentence and get results of the same words order (like match_phrase) with sentence fuzziness
Example:
PUT demo_idx/_doc/1
{
  "content": "michael jordan and scottie pippen"
}

I want to search the following sentences (with fuzziness equals 2):

*

*"michael jordan and scottie pippen" -> get results (reason: same sentence)

*"scottie pippen and michael jordan" -> 0 results (reason: words not in the correct order)

*"ichael jordan and scottie pippen" -> get results (reason: 'm' of michael is missing, 1 fuzziness)

*"ichae jordan and scottie pippen" -> get results (reason: 'm' + 'l' of michael are missing, 2 fuzziness)

*"ichael jordan and cottie pippen" -> get results (reason: 'm' of michael and 's' of scottie are missing, 2 fuzziness)

*"ichael jordan and cottie pippe" -> 0 results (reason: 'm' of michael and 's' of scottie and 'n' of pippen are missing, 3 fuzziness)

*"ichael jordan and ottie pippen" -> 0 results (reason: 'm' of michael and 's' + 'c' of scottie are missing, 3 fuzziness)

I read and tried the solution from this post: Elasticsearch Fuzzy Phrases but I didn't get the required results.
I have tried:
"query": {
            "span_near": {
                "clauses": [
                    {"span_multi":
                     {
                         "match": {
                             "fuzzy": {
                                "content": {
                                    "value": query,
                                    "fuzziness": 2
                                }
                            }
                            }
                     }
                    }
                ],
            }
        }

but it didn't worked.
How can I right the search query in order to get the results I want ?

A: If you want to have exact matches with fuzziness you can go with keyword tokenizer when defining the index
PUT test_index
{
  "mappings": {
    "properties": {
      "content": {
      "type":"text",
      "analyzer": "custom_english"
      }
    }
  },
  "settings": {
    "analysis": {
      "analyzer": {
        "custom_english": {
          "tokenizer": "keyword",
          "filter": [
            "lowercase"
          ],
          "type":"custom"
        }
      }
    }
  }
}

Then you can use the fuzzy query to get your search results
GET test_index/_search
{
  "query": {
    "fuzzy": {
      "content": {
        "value": "ichael jordan and ottie pippen"
      }
    }
  }
}

This is working for all the test cases you mentioned in your question.


text:
Q: com.diffplug.gradle.spotless && task clean(type: Delete){} Error:Cannot add task 'clean' as a task with that name already exists This my build.gradle

buildscript {
    ext {
        ...
    }
    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$navigationVersion"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

plugins {
    id "com.diffplug.gradle.spotless" version "3.26.0"
}

allprojects {
    repositories {
        google()
        jcenter()

    }
}

spotless {
    kotlin {
        target "**/*.kt"
        ktlint(ktlintVersion).userData(['max_line_length' : '100'])
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

The original compilation was successful, but when the spotless was introduced, it caused this error:

com.diffplug.gradle.spotless && task clean(type: Delete){} Error:Cannot add task 'clean' as a task with that name already exists

So, I guess these two parts are conflicting, but I don't know the specific reasons.
plugins {
    id "com.diffplug.gradle.spotless" version "3.26.0"
}
//...
task clean(type: Delete) {
    delete rootProject.buildDir
}

A: Adding to R.Desai's answer,
actually Gradle's BasePlugin cleans only app level build directory. The doc says

clean — Delete Deletes the build directory and everything in it, i.e.
the path specified by the Project.getBuildDir() project property.

Check the docs here for more info.
However, the solution is the same. The spotless plugin is conflicting with your defined "clean" task as it has the same implementation of it under the hood, which cleans the project level build directory. This has been issues in their github repo "Duplicate clean task #521"


text:
Q: SQL Server, firewall and linked servers I have:

*

*SQL Server 2008R2 database server in my LAN and under my control (call it LOCALSQL)

*remote SQL Server, on which I have much less control (call it REMOTESQL), for which I only have IP, username, password

*Linux-Apache-PHP server, on my LAN, used to access LOCALSQL (call it PHPSERVER)

Up to now, PHPSERVER accesses LOCALSQL; I can only access REMOTESQL from a test Windows machine with SQL Server Management Studio, with the necessary firewall permission.
Now, I would like to use sp_addlinkedserver to have PHPSERVER execute query involving tables from both servers.
What should I do for the firewall? Should I allow connections:
a) between LOCALSQL and REMOTESQL
b) between PHPSERVER and REMOTESQL
c) both of the above

A:
a) between LOCALSQL and REMOTESQL

Your PHP client never connects to the REMOTESQL server. It only connects to LOCALSQL and then LOCALSQL connects to REMOTESQL.
Keep in mind that your PHP availability is now driven by the REMOTESQL availability and consider that distributed queries are notoriously problematic to perf tune. Good luck!


text:
Q: Impossible implicit move operations? As far as I understand [class.copy.ctor] and [class.copy.assign], struct A in the following code should not be move-constructible nor move-assignable:
#include <type_traits>

struct X {
  X() noexcept; // user-declared default constructor
  ~X() noexcept; // Force X not to be trivially copyable
  X(X &&) = delete; // Explicitly deleted move constructor
  X(X const &) = delete; // Explicitly deleted copy constructor
  X & operator=(X &&) = delete; // Explicitly deleted move assignment operator
  X & operator=(X const &) = delete; // Explicitly deleted copy assignment op.
};
static_assert(!std::is_copy_constructible<X>::value, "");
static_assert(!std::is_copy_assignable<X>::value, "");
static_assert(!std::is_move_assignable<X>::value, "");
static_assert(!std::is_move_constructible<X>::value, "");
static_assert(!std::is_trivially_copyable<X>::value, "");
static_assert(!std::is_trivially_copy_assignable<X>::value, "");
static_assert(!std::is_trivially_copy_constructible<X>::value, "");
static_assert(!std::is_trivially_move_assignable<X>::value, "");
static_assert(!std::is_trivially_move_constructible<X>::value, "");

struct A {
  A() noexcept; // user-declared default constructor
  A(A const &) noexcept; // user-declared copy constructor
  A & operator=(A const &) noexcept; // user-declared copy assignment operator
  X x;
};
static_assert(std::is_copy_constructible<A>::value, "");
static_assert(std::is_copy_assignable<A>::value, "");
static_assert(!std::is_move_assignable<A>::value, "");        // FAILS?!
static_assert(!std::is_move_constructible<A>::value, "");     // FAILS?!
static_assert(!std::is_trivially_copyable<A>::value, "");
static_assert(!std::is_trivially_copy_assignable<A>::value, "");
static_assert(!std::is_trivially_copy_constructible<A>::value, "");
static_assert(!std::is_trivially_move_assignable<A>::value, "");
static_assert(!std::is_trivially_move_constructible<A>::value, "");

However, two of the static assertions fail with both GCC and Clang, which mean that for some reason A is move-assignable and move-constructible.
In my reasoning this shouldn't be, because struct A:

*

*does not explicitly declare a move constructor

*does not explicitly declare a move assignment operator

*has a user-declared copy constructor

*has a user-declared copy assignment operator.

*has a field x of type X which is can not be direct-initialized with any other A::x, because all constructors of X which would participate in overload resolution for this are explicitly deleted.

Is this a compiler bug or am I misunderstanding something?

A: They're expected behaviors, because the existence of copy constructor and copy assignment operator satisfies the requirement of MoveConstructible

A class does not have to implement a move constructor to satisfy this type requirement: a copy constructor that takes a const T& argument can bind rvalue expressions.

and MoveAssignable.

The type does not have to implement move assignment operator in order to satisfy this type requirement: a copy assignment operator that takes its parameter by value or as a const Type&, will bind to rvalue argument.

Note that std::is_move_constructible and std::is_move_assignable are just checking an object of the specified type can be constructed/assigned from an rvalue argument. Even there're no move constructor/assignment operator, copy constructor/assignment operator could do the work, because an rvalue argument could be passed to an lvalue reference to const too.
EDIT
Note for the sample code you showed the move constructor/assignment operator are not implcitly declared at all (because of the existence of user-declared copy constructor and copy assignment operator), so they won't affect overload resolution and the result that copy constructor/assignment operator would be invoked. But if you explicitly declared them as delete, behavior will change because explicitly deleted functions participate into overload resolution, and they will be selected preferentially, and then std::is_move_constructible and std::is_move_assignable will return false.

A: is_move_constructible/assignable does not check if there is move constructor or move assignment operator. It check if class can be constructed/assigned from r-value reference. Classes lacking move faciities would just use copy constructor/assignment operator in this case.
Generally is_move_constructible/assignable is weaker than is_copy_constructible/assignable: later fails on move-only types, when former passes check.


text:
Q: jQuery: count input checked in a table I'm trying to get the number of machines I selected.
here we have a list of virtual machines and I would like to count the selection that is when I press an input there is the element that is checked.
i tried this but not working.
   $("table input[type=checkbox]").click(function(){
        let nbchecked = $("table input[type='checkbox']:checked").length;
        console.log(nbchecked);
        let len = nbchecked.length;

          $(".counter").html(nbchecked); //inject the number of vm checked in the div
    });

I am a beginner in javascript and jquery and I don't know how to do it.
I need your help plz

A: It work, post your html plz

$("table input[type=checkbox]").click(function(){
      let nbchecked = $("table input[type='checkbox']:checked").length;
      console.log(nbchecked);
      let len = nbchecked.length;

        $(".counter").html(nbchecked); //inject the number of vm checked in the div
  });

          <input type="checkbox" name="vms" value="12" id="id_vms_1"> vm1

          <input type="checkbox" name="vms" value="13" id="id_vms_2"> vm2

          <input type="checkbox" name="vms" value="14" id="id_vms_3"> vm3


text:
Q: Does writing onPress={onPress()} have anything to do with iife? If I write onPress below, when I click the button, the console will write test. But if I write onPress(), it writes a test on the console as the page renders. Does writing onPress() have anything to do with iife? Is that why it works without being called the moment the page is rendered?
import React from 'react';
import { Button } from 'react-native';

const Screen = () => {

    const onPress = () =>{
        console.log('test')
    }

    return (
        <Button title='button' onPress={onPress()}/>
    )
};

export default Screen;

A: No, onPress={onPress()} is not an immediately-invoked function expression (IIFE).¹ It is a function invocation: You're calling onPress and using its return value as the value of the onPress prop. So you see the console message when the component is rendered, since that function call happens during rendering, and you don't see it when pressing the button, because there's no press handler on the button (since onPress doesn't return one).
To have onPress called when the button is pressed, use onPress={onPress} (no () after it):
return (
    <Button title='button' onPress={onPress}/>
);

That assigns your onPress function to the onPress prop, telling the button to call it when the button is pressed.

¹ An IIFE is where you both create and call the function at the same time, like this:
(() => console.log("Hi"))();

The () => console.log("Hi") part creates the function, and the (...)() part calls it.

A: onPress handler expects a function which will it will execute on press event.
Since in first case, you passing the function object and not executing it,  it is working fine.
But in second case, since you executing by yourself, onPress expects that it will receive the function from the output of your onPress event.
You can change it below and it will work
<Button title='button' onPress={() => onPress()}/>

or
<Button title='button' onPress={onPress()}/>

const onPress = () => {

    return () => console.log('test');
};

A: No in JS when you want to create an arrow function it should always be pointed out, so now for example
return (
    <Button title='button' onPress={onPress()}/>
  )

will auto execute because it is an assignmentOperation so you can use
return (
    <Button title='button' onPress={() => onPress()}/>
  )


text:
Q: is this possible to extend api-gateway api's using python cdk is this possible to get a api gateway using it's arn and then add more endpoints to it ? for example I have a api gateway and it's root path is '/path-one' and more api's are attached to it like  '/path-one/one' etc  not I want to get this api gateway using it's
rest_api_root_resource_id and then add new api like '/path-one/two' to same path . is this possible ? how i can achieve using python cdk
FOR Example as the same way we access lambda function using arn
 self.my_lambda = _lambda.Function.from_function_arn(self, "my-lambda", my_lambda_arn)

in same type of thing for api gateway I am finding. any help would be highly appericiated.


text:
Q: Python, running into memory error when parsing a 30MB file(already downloaded into my local computer) Here is my download address, the file name is 'kosarak'
http://fimi.uantwerpen.be/data/

My parsing code is:
parsedDat = [line.split() for line in open('kosarak.dat').readlines()]

I need this data as a whole to run some method on it, so read one line by one line and do the operation on each line is not fit for me here.
The file is only 30 MB and my computer has at least 10G memory left and 30+G Hard drive place,So I guess there shouldn't be any resource problem
FYI: My python version is 2.7 and I am running my python inside Spyder. My OS is windows 10.
PS: You don't need to use my parsing code/method to do the job,as long as you could get the data from file to my python environment that would be perfect.

A: Perhaps this may help.
with open('kosarak.dat', 'r') as f:  # Or 'rb' for binary data.
    parsed_data = [line.split() for line in f]

The difference being that your approach reads all of the lines in the file at once and then processes each one (effectively requiring 2x memory, once for the file data and once again for the parsed data, all of which must be stored in memory at the same time), whereas this approach just reads the file line by line and only needs the memory for the resulting parsed_data.
In addition, your method did not explicitly close the file (although you may just not have shown that portion of your code).  This method uses a context manager (with expression [as variable]:) which will close the object automatically once the with block terminates, even following an error.  See PEP 343.


text:
Q: Image in Android Здравствуйте. Я забираю картинки с сайта, но при добавлении в свой лист они отображаются некорректно(сохраняя пропорции, появляются различные отступы). Возможно ли в Android studio указывать размер картинки, считая с центра, так как в Вебе???

A: Лучший вариант -  scaleType :centerCrop


text:
Q: Internal server error on repo.fusesource link I'm trying to download the below dependencies from http://repo.fusesource.com/nexus/content/groups/public/oracle/jdbc/pool/OracleDataSource/10.2.0.3/ and it gives the below error.
Internal Server Error - Read Reference #3.4618ae8c.1515079103.3708303
The dependency that I'm trying to download is

     oracle.jdbc.pool
     OracleDataSource
     ${oracle-datasource-version}

A: with http://repo.fusesource.com/nexus/content/groups/public/oracle/jdbc/pool/OracleDataSource/10.2.0.3/ I have a 404 now. I think that the "Internal Server Error" was during an outage of the repository.
The oracle JDBC datasource artefact are not on this repository (for legal reason I think).
Please have a look to https://blogs.oracle.com/dev2dev/get-oracle-jdbc-drivers-and-ucp-from-oracle-maven-repository-without-ides
regards,


text:
Q: Convert MSXML DOMDocument to be used as value for SqlDbType.Xml ADO.NET parameter I have a stored procedure that accepts an xml parameter (SqlDbType.Xml) that is being called from some .NET/ ADO.NET code. I have tested this through a test harness using a System.XML.XMLReader to read some test XML from a file;
Dim xmlParam As SqlParameter = New SqlParameter("@xml", SqlDbType.Xml)
xmlParam.Value = New SqlTypes.SqlXml(XmlReader.Create(txtXMLFile.Text))
.Parameters.Add(xmlParam)

In the application this code is going into, the actual XML is in a VB6 object, in an MSXML2.DOMDocument40 object (the VB6 project references MSXML4) I have worked out how to marshal the MSXML.DOMDocument40 across to .NET from VB6 - in fact the .NET project already references MSXML4 so that is all fine. Now all I need to do is get this converted properly so it can be passed into the stored proc.
System.XML.XMLReader has a number of overloads that take stream objects, I'm wondering if I can create a stream on top of the MSXML object? Or if I can convert the MSXML to a .NET XML type, which can then be used?
Obviously performance will be a consideration but for the moment I just need to work out how to do it any way!

A: The better idea is to not mix MSXML and .NET at all.
If you must, then get the xml string from the MSXML object, and either create an XmlReader over the string, or else load the string into an XmlDocument.

A: The MSXML DOM will save to anything the implements the COM IStream interface so if you can find an implementation of that that maps to a .NET stream you should be able to acheive this fairly efficiently.


text:
Q: React & Formik, Passing data between components I am a beginner in React. I'm trying to create my first ToDo App.
Currently, I have two components - one with input and submit button (to enter data) - created with formik, second - simply component where I want to display this data.
I'm not sure how to pass data between these components and I'm looking for tips on how to do it correctly.
Here is my code:
First component( to enter data):
import React from "react";
import { Formik } from "formik";
import { View, Button, TextInput } from "react-native";

function MyForm(props) {
  return (
    <View>
      <Formik
        initialValues={{ task: "" }}
        onSubmit={(values) => console.log(values)}
      >
        {({ handleChange, handleSubmit }) => (
          <>
            <TextInput
              onChangeText={handleChange("task")}
              placeholder="Write a task"
            />

            <Button onPress={handleSubmit} title="Click" />
          </>
        )}
      </Formik>
    </View>
  );
}

export default MyForm;

Second component( to display data):
import React from "react";
import { View, Text } from "react-native";
import MyForm from "./MyForm";

const TaskContainer = (props) => {
  return (
    <View>
      <Text>Here is your list:</Text>
    </View>
  );
};

export default TaskContainer;

Here is simple example of what I want to display in second component:
I will be grateful for any advice

A: The solution to your problem is creating the statement of your task in the Parent component. After that use the callback function (pass it through props) to change its values (I use useCallback hook to prevent useless re-rendering of child components):
Parent component
import React from 'react';

const ParentComponent = () => {
  const [tasks, setTasks] = React.useState([]);

  const addTask = React.useCallback(
    (newTask) => {
      setTasks([...tasks, newTask]);
    },
    [tasks]
  );

  return (
    <>
      <MyForm tasks={tasks} addTask={addTask} />
      <TaskContainer tasks={tasks} />
    </>
  );
};

Form component
import React from 'react';
import { Formik } from 'formik';
import { View, Button, TextInput } from 'react-native';

function MyForm({ tasks, setTasks }) {
  return (
    <View>
      <Formik
        initialValues={{ task: '' }}
        onSubmit={(values) => setTasks(values)}>
        {({ handleChange, handleSubmit }) => (
          <>
            <TextInput
              onChangeText={handleChange('task')}
              placeholder="Write a task"
            />

            <Button onPress={handleSubmit} title="Click" />
          </>
        )}
      </Formik>
    </View>
  );
}

export default MyForm;

Tasks component
import React from 'react';
import { View, Text } from 'react-native';
import MyForm from './MyForm';

const TaskContainer = ({ tasks, setTasks }) => {
  return (
    <View>
      <Text>Here is your list:</Text>
      {tasks.map((task) => (
        <Text>{task}</Text>
      ))}
    </View>
  );
};

export default TaskContainer;


text:
Q: How to use Yii2 user Identity in Codeception unit test case? I am new to unit testing. Trying to create some test cases in my Yii2 project using codeception plugin. From last 1 week i am learning it.
Now i know how to use Fixtures, Mocks and Stubs in Unit testing.
I just want to ask that can we use Yii2 user identity class in unit testing in some cases. for example there may be case when we have to check some condition for logged in user. in that case how to use user session or user identity in unit testing.


text:
Q: Logging in as another user in sharepoint I'm site collection administrator/(physical server administrator) in SharePoint (3.0), and I'm debugging other users' rights to access some of our own features. Is it possible, in any way, to log in as another user(with his/her rights) without knowing his password? I can create  my own 'dummy' user assigned to same groups, but looking in 100+ groups if user is there isn't what I want to do this evening.
Thanks.
-- y

A: I don't know if you can impersonate from UI only, but you can do it pragmatically.
I am not 100% sure, but I think you could create ASP.NET page that would handle the impersonation, thus leaving you logged in as the user you want.  You could certainly run code to determine what you have access to if you are looking for something specific.
Here is a post about how to run impersonation code:
http://blackninjasoftware.com/2009/04/09/how-to-programmatically-impersonate-users-in-sharepoint/

A: I figured it out another way (my post for serverfault):
So. The solution is following: (not clean, but working)
1) write own IHttpModule, containing:
class LoginModule {
 public void Init(HttpApplication context)
 {
    context.PreRequestHandlerExecute += new EventHandler(UglyHack);
 }

 void UglyHack(object sender, EventArgs e)
 {
     HttpCookie wannabe = (HttpContext.Current.Request.Cookies["_sp_admin_wanna_be_user"]);
     if (wannabe != null && SPContext.Current.Web.CurrentUser.IsSiteAdmin)
     {
         SPWeb cw = SPContext.Current.Web;
         typeof(SPWeb).GetField("m_CurrentUser", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(
                        SPContext.Current.Web,
                        cw.AllUsers[wannabe.Value]);
     }
 }
}

2) Sign it
3) GAC it
4)
  to web.config().
Voila! Youre the man. :) (of course i added logic to add cookie setting to menu, security, etc..)


text:
Q: I cannot bit import with --compiler option I'm having a problem.I want to import typescript compiler.
then I tried this command: bit import bit.envs/compilers/typescript --compiler
But it doesn't worked. This is the error message:
bit import [ids...]

import components into your current workspace.
  https://docs.bit.dev/docs/sourcing-components
  you can use a pattern for multiple ids, such as bit import "utils/*". (wrap the pattern with quotes to avoid collision with shell commands)

Options
  -p, --path                  import components into a specific directory  [string]
  -o, --objects               import components objects only, don't write the components to the file system. This is a default behavior for import with no id  [boolean]
  -d, --display-dependencies  display the imported dependencies  [boolean]
  -O, --override              override local changes  [boolean]
  -v, --verbose               showing verbose output for inspection  [boolean]
  -j, --json                  return the output as JSON  [boolean]
      --conf                  write the configuration file (component.json) of the component (harmony components only)  [boolean]
      --skip-npm-install      do not install packages of the imported components. (it automatically enables save-dependencies-as-components flag)  [boolean]
  -m, --merge                 merge local changes with the imported version. strategy should be "theirs", "ours" or "manual"  [string]
      --dependencies          EXPERIMENTAL. import all dependencies and write them to the workspace  [boolean]
      --dependents            EXPERIMENTAL. import component dependents to allow auto-tag updating them upon tag  [boolean]
      --skip-lane             EXPERIMENTAL. when checked out to a lane, do not import the component into the lane, save it on main  [boolean]
      --all-history           relevant for fetching all components objects. avoid optimizations, fetch all history versions, always  [boolean]

Global
  -h, --help           show help
      --token <token>  authentication token
      --log            print log messages to the screen, options are: [trace, debug, info, warn, error, fatal], the default is info
      --safe-mode      bootstrap the bare-minimum with only the CLI aspect. useful mainly for low-level commands when bit refuses to load

Unknown argument: compiler

Maybe compiler option doesn't into bit import…
This is my version info:
current (used) bvm version: 0.0.30
latest available bvm version: 0.0.30

current (used) bit version: 0.0.555
latest installed bit version: 0.0.555
latest available bit version: 0.0.555

Please help me…

A: the compiler flag was removed in 0.0.537
the best place to get bit.dev answers is their community Slack here: https://join.slack.com/t/bit-dev-community/shared_invite/zt-o2tim18y-UzwOCFdTafmFKEqm2tXE4w.

A: "compiler" is a legacy solution - Bit now has the more comprehensive "environment" property. Learn more here - https://harmony-docs.bit.dev/aspects/envs/


text:
Q: how to override email html file in magento2 I want to change following text in checkout page
You can create an account after checkout.

Actually this line is coming from following file.
app/code/Magento/Checkout/view/frontend/web/template/form/element/email.html
Can you any one give approach to override?

A: You need create [Vendor]/[ModuleName]/view/frontend/layout/checkout_index_index.xml file with content
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <referenceBlock name="checkout.root">
                <arguments>
                    <argument name="jsLayout" xsi:type="array">
                        <item name="components" xsi:type="array">
                            <item name="checkout" xsi:type="array">
                                <item name="children" xsi:type="array">
                                    <item name="steps" xsi:type="array">
                                        <item name="children" xsi:type="array">
                                            <item name="shipping-step" xsi:type="array">
                                                <item name="children" xsi:type="array">
                                                    <item name="shippingAddress" xsi:type="array">
                                                        <item name="children" xsi:type="array">
                                                            <item name="customer-email" xsi:type="array">
                                                                <item name="component" xsi:type="string">
                                                                    Magento_Checkout/js/view/form/element/email <!--  <- you can change component here -->
                                                                </item>
                                                                <item name="tooltip" xsi:type="array">
                                                                    <item name="description" xsi:type="string"
                                                                          translate="true"><!--  <- you can change text here -->
                                                                        We'll send your order
                                                                        confirmation here or you custom text.
                                                                    </item>
                                                                </item>
                                                            </item>
                                                        </item>
                                                    </item>
                                                </item>
                                            </item>
                                        </item>
                                    </item>
                                </item>
                            </item>
                        </item>
                    </argument>
                </arguments>
            </referenceBlock>
        </referenceContainer>
    </body>
</page>


text:
Q: Why does "include" behave differently in the global context than it does in a class? In the global context (main), when you include a module you can use its methods directly from the global context. In a class, including the module defines instance methods which can't be called from the same context that include was called from. Why is this?
Example:
module Foo
  def hello
    puts "Hello, world!"
  end
end

# In a class:
class Bar
  include Foo
  hello # Hello is an instance method so it won't work here.
end

# In main
include Foo
hello # Works fine. Why?

A:
In main
include Foo
hello # Works fine. Why?

What is the Ruby Top-Level? a good blog on this concept you must go thorugh first.
Because in top level you are calling the instance method #hello on the top level object main,which is an instance of Object class.On top level you are doing include Foo means you are including the module in the Object class.which is why instance method #hello of the module Foo becomes the instance method of the class object.
module Foo
  def hello
    puts "Hello, world!"
  end
end
Object.include?(Foo) # => false
include Foo
Object.include?(Foo) # => true
self # => main
self.class # => Object
self.instance_of? Object # => true
hello # => Hello, world!

On top level if you are calling the method as hello,but ruby is doing internally as self.hello. And self is there main,which I explained before.


text:
Q: Ozo Player sdk streaming 360 video through .mpd file I am using ozo player sdk plugin for playing 360 video in Unity3d. Local video is playing from the streaming assets folder in unity, it works fine. When i am playing video from server using .mpd file, sdk not able to play video please help me.
file Url :
http://35.185.12.162:1935/3S%20AWS%20Mediacache/definst/mp4:amazons3/3stagevr/sample2_TB.mp4/manifest.mpd


text:
Q: direct cmd output to variable using pipes I am trying see how many files how been updated today. So I am running:
forfiles /P C:\Directory\ /S /D %DATE:~4,10% | wc -w

now I am trying to set the result to a variable but cant' seem to get it work with:
@echo off set files=forfiles /P C:\Directory\  /S /D %DATE:~4,10% | wc -w

when I use echo "%files%" I get : %files% as output.
Anyone know what I am doing wrong. I am new to cmd coming from unix.

A: @echo off
for /f %%c in ('forfiles /P C:\Directory\  /S /D %DATE:~4,10% ^| wc -w') do set files=%%c
echo %files% found

(untested)


text:
Q: How to save and files on amazon ebs with node.js I have a node.js application using elastic beanstalk with ebs volume.
How can I save files to amazon ebs using node.js?
Does using the simple code from this answer put the file on ebs?
fs.writeFile("/tmp/test", "Hey there!", function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
});

If it does, what is the code difference between saving the file on ebs or on the disk?

A: The "disk" in your EC2 instance for your Elastic Beanstalk (EB), is just an EBS volume. There is no special other storage provided by EB for your application.
However, storing your data (e.g. images uploaded by the users) on the EB instance is a bad practice. The preferred way is to store all the date externally to your EB environment, for example in S3 or EFS filesystem.


text:
Q: Drawing an animated line in the Google Earth Plug-in Is there a way to incrementally draw a line in the Google Earth Plug-in using the JavaScript API?
If that's not possible, is there a round about method to achieve the same effect?
What I want to achieve is similar to this: http://www.wolfpil.de/v3/animated-poly_v3.html

A: Yes this is entirely possible, and to be fair it would be trivial to convert the code in the example to use the earth, rather than maps, api.  All you would need to do is to find any references to maps objects and simply use the equivalent earth api objects. The math and timing is all done for you...
If you wanted to convert it take a look at the following links, they should give you everything you need to know.
Information on Geometries and Overlays
https://developers.google.com/earth/documentation/geometries
Example of Drawing line strings
http://earth-api-samples.googlecode.com/svn/trunk/examples/linestring.html
Example of Smooth Animation with frameend
http://earth-api-samples.googlecode.com/svn/trunk/examples/event-frameend.html
Finally, you could also just add the earth plugin to the maps implementation, take a look at the following example of Maps/Earth Integration. This would just mean adding the a few lines of code to the example you posted allowing the 'earth' mode to be activated from the maps api.  If set up correctly things like polylines are available across the map/earth displays.
Earth Maps integration
http://earth-api-samples.googlecode.com/svn/trunk/examples/maps-integration.html
Beefy integration example
http://earth-api-samples.googlecode.com/svn/trunk/demos/mapsapi/beefy.html


text:
Q: Price calculation in Assembly language (TASM)
I am creating a restaurant program in assembly language which display a list of food together with its price.
When user want to make an order, the program will prompt user to enter product number and enter the quantity of food they want to buy. The program will then calculate/multiply the price and the quantity, then display the total price of the order.
My codes seems like error because it only display weird character as the output of the multiplication. It also displays the line7 string twice when I run the program.
I really appreciate it if you could help me and explain the mistakes I made. Thank you in advance!

    inputqty db 10,13 "Input quantity: $"
    line10 db 10,13, "-----Food Menu-----$"
    line7 db 10,13, "1. Pizza: $2 $"
    orderopt db 10,13, "Input product ID to make order: $"
    pizzaprice db 2
    totalprice db 10,13, "Total price: $"

foodmenu:
    mov ah,9
    lea dx,line10 ;display food menu banner
    int 21h

    mov ah,9
    lea dx,line7 ;display pizza menu with price
    int 21h

    mov ah,9
    lea dx,orderopt ;prompt user to input choice
    int 21h

    mov ah,1 ;read a character
    int 21h

    cmp al,31h
    je pizzatotal ;calculate the total price of pizza if user input is 1

pizzatotal:
    mov ah,9
    lea dx,inputqty ;prompt user to input quantity
    int 21h

    mov ah,1
    int 21h

    sub al,48
    mov bl,pizzaprice
    add bl,48
    mul bl

    mov ah,9
    lea dx,pizzatotal ;displaying the total price
    add dl,48
    int 21h

    mov ah,2
    mov dl,al ;to display result
    add dl,48
    int 21h

    cmp al,30h
    je foodmenu


text:
Q: How to turn on the Bluetooth of my laptop? This is my first question to the site.
I have a problem where I can't turn on the bluetooth on my laptop. If anybody could give help me solve this I'd be very grateful!
Laptop Details
- Dell Latitude E5510.
- Windows 7 32-bit.
Problems
- The bluetooth light is not lit (WiFi is lit).
- The bluetooth icon is not in the system tray.
- There are no settings in 'Control Panel' for bluetooth.
- There are no drivers in 'Device Manager' for bluetooth.

Troubleshooting Already Attempted
- Ensured that bluetooth was enabled in the BIOS.
- Updated BIOS to version A11.
- Downloaded and attempted to install drivers (R285455.exe, R260222.exe, R296919.exe). When I try to run R260222.exe, it tells me that it is incompatible. When I run the other two drivers, it extracts the items but then asks me to "activate bluetooth using wireless switch". The switch is already on but no light appears for the bluetooth symbol. It's a catch 22!
- Ensured that the 'Bluetooth Support Service' was started.

I've been searching for the solution for hours now and just have no idea what else to do. If I've missed out on any information, please let me know.
*EDIT* I'm beginning to think that there is no physical bluetooth adaptor in my laptop at all.
Here are the full specifications
 LATITUDE E5510 : STANDARD BASE
 SYSTEM BASE : EXPRESS CARD SLOT
 PROCESSOR : INTEL CORE I3-350M(2.26GHZ, 1
 DISPLAY : 15.6IN HD ANTI-GLARE LED DISPL
 MODULE..., PALMREST..., NFPRDR, SINGLE POINTING..., E5510
 MODULE..., BEZEL..., LIQUID CRYSTAL DISPLAY..., 15.6, MICROPHONE..., E5510
 DOCUMENTATION : ENGLISH SHIPPING DOCS
 MEMORY : 3GB(1X1GB + 1X2GB)1333MHZ DDR3
 HARD DRIVE : 250GB SERIAL ATA (7200RPM)
 WINDOWS LIVE
 MODULE..., SOFTWARE..., POWERDVD..., 8.3, DIGITAL VIDEO DISK DRIVE..., TT, FACTORY INSTALL...
 OPTICAL DRIVE : ROXIO CREATOR 10.3 SOFTW
 OPTICAL DRIVE : 8X DVD+/-RW DRIVE
 POWER SUPPLY + POWER CORD : UK/IRISH 3 W
 BATTERY : PRIMARY 4-CELL 37W/HR LI-ION
 LABELS : INTEL CORE LABEL I3
 WIRELESS : EMEA INTEL PRO WIRELESS 6200
 KEYBOARD : INTERNAL UK/IRISH QWERTY SING
 SOFTWARE DRIVER : LATITUDE E5510
 MODULE..., SOFTWARE..., W7P32, ENGLAND/ENGLISH..., EUROPEAN MANUFACTURING FACILITY...
 MODULE..., SOFTWARE..., W7P32, DIGITAL VIDEO DISK DRIVE..., MULTIPLE USER INTERFACE..., NO-E
 SOFTWARE : MICROSOFT OFFICE STARTER 2010
 OPERATING SYSTEM RECOVERY DELL BACKUP AN
 SOFTWARE..., TREND MICRO..., WF, MULTIPLE USER INTERFACE..., 15MTH
 LATITUDE ORDER - IRELAND
 BASE WARRANTY
 1YR COLLECT AND RETURN
 DECLINED PROSUPPORT
 3YR BASIC WARRANTY - NEXT BUSINESS DAY
 DECLINED COMPLETECARE
 NOTEBOOK - FREE FREIGHT SKU

A: Here's how to check for physical presence of Bluetooth in a Dell Ex510 system:

*

*In BIOS, it will say under Wireless or Radios or Networking (sorry, I don't remember the exact menu section and I don't have time to reboot my machine right now) something along the lines of "Bluetooth installed" and might list the module model.

*You can go to Dell Warranty Status and click to Original System Configuration tab. Dell Bluetooth module for Ex510 was 375. Search the page (press CTRL + F) for it.

*Checking for physical presence is tricky and you shouldn't do it unless you have experience re-assembling laptops. The procedure can be found here (Dell Support).

What you might be experiencing is that the radio switch in the front left of the palm rest is set to control both wi-fi & Bluetooth and is currently turned off. The setting is in BIOS in the same section as enabling/disabling radios. You can set it to only control wi-fi so that Bluetooth is controlled by its drivers in Windows.

A: If you're not already running this BIOS version you may want to consider upgrading as it indicates some BIOS-level fixes for Bluetooth problems.

Fixed the issue where Bluetooth is disabled after turning the wireless switch off and rebooting.


text:
Q: How to pass the path for link_to tag from controller to view. Now I'm trying to make path markup.
Assume it's up to 4th depth level directory then I made something like this for view?
How can I pass the path to view from controller with variable label???
          <% if !@FirstDirPath.nil? %>
          <%= @FirstDirPath %> /
          <% end %>

          <% if !@SecondDirPath.nil? %>
          <%= @SecondDirPath %> /
          <% end %>

          <% if !@ThirdDirPath.nil? %>
          <%= @ThirdDirPath %> /
          <% end %>

          <% if !@FourthDirPath.nil? %>
          <%= @FourthDirPath %> /
          <% end %>

A: You can access the current path with request.fullpath
If you want to get the breadcrumb then you can just split the fullpath by '/'. In the controller:
@path = request.fullpath
@breadcrumb = @path.split('/')

In the view:
<% @breadcrumb.each do |crumb| %>
  <%= crumb %>
  /
<% end %>

Untested, but I think it should work.


text:
Q: How to make scrollable list using array I am trying to make my code simple by making it into an array instead I have to write it one by one, but I do not have an idea on how to convert it into an array list. Here for what I have been done. My output is I want to generate the list in a container with scrollable to the right using axis horizontal scroll direction.
    class YearSort extends StatelessWidget {
  final String title;

  const YearSort({
    Key? key,
    required this.title,
     }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: const [
          ByYear(year: 'This year'),
          ByYear(year: '2021'),
          ByYear(year: '2020'),
          ByYear(year: '2019'),
          ByYear(year: '2018'),

        ],
      ),
      );
  }
}

class ByYear extends StatefulWidget {
  final String year;

  const ByYear({
    Key? key,
    required this.year,
    }) : super(key: key);

  @override
  State<ByYear> createState() => _ByYearState();
}

class _ByYearState extends State<ByYear> {
  bool iselected = true;

  @override
  Widget build(BuildContext context) {
    return Container(
          width: 100,
          height: 30,
          decoration: BoxDecoration(
            color: iselected
            ? Color.fromARGB(255, 215, 237, 255)
            //Colors.white
            : Color.fromARGB(255, 215, 237, 255),
            borderRadius: BorderRadius.circular(20),
          ),
          child: Center(child: Text(widget.year, style: const TextStyle(fontFamily: 'Poppins'),)),

    );
  }
}

A: Your syntax is kind of not correct for a few widgets and incorrect use of Expanded. This one will help you.
@override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: _title.length,
      scrollDirection: Axis.horizontal,
      itemBuilder: (context, index) {
        return Container(
          width: 70,
          height: 30,
          decoration: BoxDecoration(
            color: isSelected
                ? Colors.yellow
                : Colors.blue,
            borderRadius: BorderRadius.circular(20),
          ),
          child: Text(_title[index], style: TextStyle(fontFamily: 'Poppins'),),
        );
        },
      );
  }

Since you edit the question in middle of nowhere,
class YearSort extends StatefulWidget {
  final String title;
  const YearSort({
    Key? key,
    required this.title,
  }) : super(key: key);

  @override
  State<YearSort> createState() => _YearSortState();
}

class _YearSortState extends State<YearSort> {
  int selectedIndex = 0;
  static List chips = [
    DateTime.now().year,
    DateTime.now().year - 1,
    DateTime.now().year - 2,
    DateTime.now().year - 3,
    DateTime.now().year - 4
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(children: [
            for(int index = 0; index < chips.length; index++)
              Padding(
                padding: const EdgeInsets.all(8.0),
                child: GestureDetector(
                  child: ByYear(
                    year: chips[index].toString(),
                    isSelected: selectedIndex == index,
                  ),
                  onTap: () {
                    selectedIndex = index;
                    setState(() {});
                  },
                ),
              )
          ],),
        ),
        Expanded(child: Container())
      ],
    );
  }
}

class ByYear extends StatefulWidget {
  final String year;
  final bool isSelected;

  const ByYear({Key? key, required this.year, this.isSelected = false})
      : super(key: key);

  @override
  State<ByYear> createState() => _ByYearState();
}

class _ByYearState extends State<ByYear> {
  @override
  Widget build(BuildContext context) {
    Color color = widget.isSelected
        ? const Color.fromARGB(255, 25, 27, 25)
        : const Color.fromARGB(255, 215, 237, 255);
    Color textColor = !widget.isSelected
        ? const Color.fromARGB(255, 25, 27, 25)
        : const Color.fromARGB(255, 215, 237, 255);
    return Container(
      height: 30,
      width: 100,
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Center(
        child: Text(
          widget.year,
          style: TextStyle(
              fontSize: 16, color: textColor, decoration: TextDecoration.none),
        ),
      ),
    );
  }
}

Note: You can also use Listview.builder instead of singlechildscrollview

A: If you have an array to show in a scrollable widget, you can use Listview instead of SingleChildScrollView. Like this:
@override
Widget build(BuildContext context) {
return ListView(
  scrollDirection: Axis.horizontal,
  children: const [
    ByYear(year: 'This year'),
    ByYear(year: '2021'),
    ByYear(year: '2020'),
    ByYear(year: '2019'),
    ByYear(year: '2018'),
  ],
  shrinkWrap: true,
);
}

hope it helps you.


text:
Q: What makes an object to be at rest? We understand both motion and rest are relative. But me and my friends always discussing about this kind of thought experiment involving a single object (for example, a particle with mass or massless particle) with nothing else existed (no other objects, no force, no gravity, no quantum field, etc.). Because motion is relative, then someone can say the lone object is at rest. It is motionless, and someone can also say the natural state for this lone object is to be at rest. But for me, in my opinion this kind of thought experiment is actually impossible in reality and this thought experiment is purely imaginative. It is impossible and irrational because both motion and rest (motionless) are relative so this lone object with nothing else existed is actually neither moving nor not moving thus a single object universe is purely imaginative. What do you think?

A: You're right, motion is only a relative concept and without another reference body (or what we physicists would call a "reference frame") the notion of motion cannot really be defined. A fundamental but often implicit assumption in physics is that measurement can be made and reproduced. Only with measurement then we can unambiguously and meaningfully describe our physical world and talk about physics at all. But to make meaningful measurements, you unavoidably need to bring in a measurement device hence a reference body to your universe. So your question is really more a philosophical one than a physical one.


text:
Q: Laravel: passing variables from Route::get static page to view I am working with Laravel and I am not used to it. Currently I need to add description and title tags to page (that are missing from existing page already coded by someone else).
I see that there are some static pages that doesn't have any controller but are defined also in routes.php. For instnace, one of them is like this:
Route::get('feedback', function()
{
    return view('feedback');
});

It renders feedback.blade which uses home.layout. I do not understand how to pass variables from this routes.php to home.layout.
If I would understand, I would be able to define some array like
$meta['title']  and $meta['description'] and render those in layout.
It seems as basic question, but I really tried to google and no results.
I have tried like this:
Route::get('feedback', function()
{
    $meta = [
        'title' => 'About title',
        'description' => 'About description'
    ];
    return view('feedback', ['meta' => $meta]);
});

and in blade layout
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
    {{ isset($meta) ? $meta->title : 'test'  }}

But it resulted in error.

A: You can use some of the following options:
Route::get('feedback', function()
{
    return view('feedback')->with('variable', $variable);
});

Route::get('feedback', function()
{
    return view('feedback', ['variable' => $variable]);
});

Route::get('feedback', function()
{
    return view('feedback')->with(compact('variable'));
});

Then in the blade file you can use $variable as a local variable.