text:
Q: Error while loading a sentence transformer model I'm trying to load transformer model from SentenceTransformer. Below is the code
# Now we create a SentenceTransformer model from scratch

word_emb = models.Transformer('paraphrase-mpnet-base-v2')
pooling = models.Pooling(word_emb.get_word_embedding_dimension())
model = SentenceTransformer(modules=[word_emb, pooling])

Below is the error
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_2948\3254427654.py in <module>
      1 # Now we create a SentenceTransformer model from scratch
----> 2 word_emb = models.Transformer('paraphrase-mpnet-base-v2')
      3 pooling = models.Pooling(word_emb.get_word_embedding_dimension())
      4 model = SentenceTransformer(modules=[word_emb, pooling])

~\miniconda3\envs\atoti\lib\site-packages\sentence_transformers\models\Transformer.py in __init__(self, model_name_or_path, max_seq_length, model_args, cache_dir, tokenizer_args, do_lower_case, tokenizer_name_or_path)
     27
     28         config = AutoConfig.from_pretrained(model_name_or_path, **model_args, cache_dir=cache_dir)
---> 29         self._load_model(model_name_or_path, config, cache_dir)
     30
     31         self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name_or_path if tokenizer_name_or_path is not None else model_name_or_path, cache_dir=cache_dir, **tokenizer_args)

~\miniconda3\envs\atoti\lib\site-packages\sentence_transformers\models\Transformer.py in _load_model(self, model_name_or_path, config, cache_dir)
     47             self._load_t5_model(model_name_or_path, config, cache_dir)
     48         else:
---> 49             self.auto_model = AutoModel.from_pretrained(model_name_or_path, config=config, cache_dir=cache_dir)
     50
     51     def _load_t5_model(self, model_name_or_path, config, cache_dir):

~\miniconda3\envs\atoti\lib\site-packages\transformers\models\auto\auto_factory.py in from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs)
    445         elif type(config) in cls._model_mapping.keys():
    446             model_class = _get_model_class(config, cls._model_mapping)
--> 447             return model_class.from_pretrained(pretrained_model_name_or_path, *model_args, config=config, **kwargs)
    448         raise ValueError(
    449             f"Unrecognized configuration class {config.__class__} for this kind of AutoModel: {cls.__name__}.\n"

~\miniconda3\envs\atoti\lib\site-packages\transformers\modeling_utils.py in from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs)
   1310                 elif os.path.join(pretrained_model_name_or_path, FLAX_WEIGHTS_NAME):
   1311                     raise EnvironmentError(
-> 1312                         f"Error no file named {WEIGHTS_NAME} found in directory {pretrained_model_name_or_path} but "
   1313                         "there is a file for Flax weights. Use `from_flax=True` to load this model from those "
   1314                         "weights."

OSError: Error no file named pytorch_model.bin found in directory paraphrase-mpnet-base-v2 but there is a file for Flax weights. Use `from_flax=True` to load this model from those weights.

I'm using below versions
transformers==4.16.2
torch==1.11.0+cu113
torchaudio==0.11.0+cu113
torchvision==0.12.0+cu113
sentence-transformers==2.2.0
faiss-cpu==1.7.2
sentencepiece==0.1.96

It's been 2 months i ran this. All of a sudden, it's returning an error. I'm using FAISS-CPU as well.

A: The error is telling you that "I can't find the weights of the model you are trying to load."
Based on the error trace, I guess you are using models object from Sentence-Transformers library (correct me if I am wrong). One thing to note is that Sentence-Transformers only has the following paraphrase models as its pretrained models:

*

*paraphrase-multilingual-mpnet-base-v2

*paraphrase-albert-small-v2

*paraphrase-multilingual-MiniLM-L12-v2

*paraphrase-MiniLM-L3-v2
hence the one you wanted to load is not one of Sentence-Transformers pretrained models.

That brings me to think that you are trying to load a model from your local machine.
I would suggest you to create a Sentence-Transformers model like this:
from sentence_transformers import SentenceTransformer

model_path_or_name = "path/to/model" # A folder that contains model config files, including pytorch_model.bin
model = SentenceTransformer(model_path_or_name)

There was also a possibility that the pytorch_model.bin file was downloaded with another filename, as mentioned in the SO thread here.
Let me know if this solves your problem. Cheers.


text:
Q: Dependent Variable Loop C# I'd like to ask a question about how to deal with dependent variables.
C1=MA(X,10)
C2=MA(C1,10)
C3=C2.Minus(C1)
C4=MA(C3,10)
Final=C4.Minus(C3)

An illustration:Final=C4.Minus(C3), I save its two parameters C4,C3.
  C4(MA ok and firstTime in MA)--> C3(MA NotOK,not fstTime)---> C2(MA ok)--->C1(MA ok)
                       0------------------->  10-------------->  10+10---->10+10+10=30

I created a class at first to get all the informtion of each line
    public class IndicatorInform
    {
        char[] parenthesis = new []{'(',')'};
        char[] equal = new char[] { '=' };
        char[] comma = new char[] { ';' };
        char[] all = new char [] { '.','<'};

        string text=null;
        string funcname=null;
        string[] args=null;

        public void IndicatorInform (string expression, out string text,out string funcName,out string [] args)
        {
           string [] parts= expression.Split(equal);
           text = parts[0];
           if( parts[1].Contains(";"))
           {
               string[] subparts = parts[1].Split(parenthesis);
               funcname = subparts[0];
               args = subparts[1].Split(comma);
               if(args.Count.equal(2))
               {
                   funcarg = args[0];
                   period = Convert.ToDouble(args[1]);
               }
           }
           else
           {
               if (parts[1].Contains("Plus"))
                   funcname = "Plus";
               if (parts[1].Contains("Minus"))
                   funcname = "Minus";
               if (parts[1].Contains("Multi"))
                   funcname = "Multi";
               if (parts[1].Contains("Div"))
                   funcname = "Div";
               parts[1] = parts[1].Replace(funcname, "");
               args=parts[1].Split(all);
           }
        }
        public double Shifts {get; set;}
        public double period { get; set; }
        public string Funcname { get; set; }
        public string text { get; set; }
        public string funcarg { get; set; }
    }

And then I created a Dictonary and begin to deal with dependant variables
   Dictionary<string,SubIndicator> Dico=new Dictionary<string,SubIndicator> ;
        foreach (var line in richTextBox1.Lines)
        {
            SubIndicator SubInc = new SubIndicator();
            Dico.Add(SubInc.text,SubInc);
        }
        int incre=0;
        double tempvalue=0;
        foreach( string element in Dico.Keys)
        {
            string[] tempo=null;
            if(Dico[element].text.Contains("Final"))
            {
                tempo=Dico[element].args;
            }
            else
            {
                if(tempo.Contains(Dico[element].text))
                {
                    if(Dico[element].Funcname.Contains("MA") )
                    {
                        if (incre.Equals(0))
                        {tempvalue=Dico[element].period;
                        incre++;}
                        else
                        {
                            Dico[element].Shifts=tempvalue+Dico[element].period;
                            tempvalue =Dico[element].Shifts;
                        }
                    }
                    else
                    {
                        Dico[element].Shifts=tempvalue;
                    }
                }
            }

My algorithm works for the case above.But how to deal a more complicated case such as
  C1=MA(X,10)
  C2=MA(X,20)
  C3=MA(C1,5)
  C4=MA(C2,10)
  C5=MA(C3,15)
  C6=MA(C4,10)
  Final=C6.Minus(C5)
 C6(fst Time)---->C4--->C2         C5(fst Time)--->C3--> C1
            0-->10+10-->10+10+20              0--> 15+5-->15+5+10

Thanks for your help.

A: I think I need to write a longer answer.  Math functions need to have a binary tree with element/nodes which is a class that contains a left node, right node, value, and math operator.  The element is usually a class object and can be the value in a dictionary.  Leafs nodes will contain the values while non leafs nodes will have operators with either a left node, a right node, or both a left and right node.
Math function are associated so any function can divided into a left and right component like a = b + (c + d + e + f).  b is the left component and (c + d + e + f) is the right component.  The right component can further by separated into a left and right.
You code need two pieces.  The first is to parse the input into elements.  The second part is to calculate the results.  The recursive function will perform the calculations.  The recursive checks to see if an element contains a left, and or right nodes and keeps calling the recursive function until a leaf is found that contains a value.  Then moves back up the stack of function calls replacing the math operators with value returned from left and right components.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing data from Silverlight Out of Browser When Silverlight runs in Out of Browser mode and off line, can it get the Sql Server Data from a DataBase located in the local disk by means of an ADO Entity Data Model?

A: I don't think Entity Framework can run in Silverlight due to restrictions imposed by the Silverlight security model (and AFAIK System.Data.dll not available in Silverlight). Typically people use  WCF data services client in Silverlight to connect to a data service that exposes your database.


text:
Q: Extract a specific section of a string depending on an input I have a very large .json converted into a string, containing numerous cities/countries.
I'd like to extract the information of the city depending on the user's choice of country (London is just an example).
For example, if the Country the user inputed was: UK, the following information would be extracted from the string:
I'm not too sure on how I could possibly achieve this due to my inexperience, but am aware that it would require an if statement. My progress so far:
Country = raw_input('Country: ')
if 'UK' in string:
    ???

A: The initial response wasn't great because a few of us overlooked the raw JSON. However, you did provide it so in future it would be better to make it more obvious that the snippet you showed had a more complete (and valid) counterpart.
That said, I would load the data into a dictionary and do something like:
import json

json_string = """{
  "response": {
  "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
  "features": {
  "conditions": 1
  }
        , "results": [
        {
        "name": "London",
        "city": "London",
        "state": "AR",
        "country": "US",
        "country_iso3166":"US",
        "country_name":"USA",
        "zmw": "72847.1.99999",
        "l": "/q/zmw:72847.1.99999"
        }
        ,
        {
        "name": "London",
        "city": "London",
        "state": "KY",
        "country": "US",
        "country_iso3166":"US",
        "country_name":"USA",
        "zmw": "40741.1.99999",
        "l": "/q/zmw:40741.1.99999"
        }
        ,
        {
        "name": "London",
        "city": "London",
        "state": "MN",
        "country": "US",
        "country_iso3166":"US",
        "country_name":"USA",
        "zmw": "56036.3.99999",
        "l": "/q/zmw:56036.3.99999"
        }
        ,
        {
        "name": "London",
        "city": "London",
        "state": "OH",
        "country": "US",
        "country_iso3166":"US",
        "country_name":"USA",
        "zmw": "43140.1.99999",
        "l": "/q/zmw:43140.1.99999"
        }
        ,
        {
        "name": "London",
        "city": "London",
        "state": "ON",
        "country": "CA",
        "country_iso3166":"CA",
        "country_name":"Canada",
        "zmw": "00000.1.71623",
        "l": "/q/zmw:00000.1.71623"
        }
        ,
        {
        "name": "London",
        "city": "London",
        "state": "TX",
        "country": "US",
        "country_iso3166":"US",
        "country_name":"USA",
        "zmw": "76854.1.99999",
        "l": "/q/zmw:76854.1.99999"
        }
        ,
        {
        "name": "London",
        "city": "London",
        "state": "",
        "country": "UK",
        "country_iso3166":"GB",
        "country_name":"United Kingdom",
        "zmw": "00000.1.03772",
        "l": "/q/zmw:00000.1.03772"
        }
        ,
        {
        "name": "London",
        "city": "London",
        "state": "WV",
        "country": "US",
        "country_iso3166":"US",
        "country_name":"USA",
        "zmw": "25126.1.99999",
        "l": "/q/zmw:25126.1.99999"
        }
        ]
    }
}"""

json_object = json.loads(json_string)

world_dict = {}
for item in json_object['response']['results']:
    item_country = item['country']
    in_dict = world_dict.get(item_country)
    if in_dict:
        world_dict[item_country].extend([item])
    else:
        world_dict[item_country] = [item]

country = raw_input('Country: ')

response = world_dict.get(country)
if response:
    for item in response:
        print item
else:
    print "Not a valid country"

EDIT:
Based on comment to use URL rather than a JSON string.
import requests

url = 'http://api.wunderground.com/api/a8c3e5ce8970ae66/conditions/q/London.json'

data = requests.get(url).json()

world_dict = {}
for item in data['response']['results']:
    item_country = item['country']
    in_dict = world_dict.get(item_country)
    if in_dict:
        world_dict[item_country].extend([item])
    else:
        world_dict[item_country] = [item]

country = raw_input('Country: ')

response = world_dict.get(country)
if response:
    for item in response:
        print item
else:
    print "Not a valid country"

A: import json

country = raw_input('Country: ')

jsondata = "the large json string mentioned in your post"

info = json.loads(jsondata)

for item in info:
    if item['country'] == country:
        print item

A: You can try this. Might still want to consider some user input errors in your code. For example, str.strip() and capital sensitive.
import json
input_country = raw_input('Please enter country:')
with open('London.json') as fp:
    london_json = fp.read()
    london = json.loads(london_json)
    for item in london["response"]["results"]:
        if item['country'] == input_country:
            print json.dumps(item, indent = 2)


text:
Q: Faster creation of small numpy arrays I have a code where I need to do some operation on a small number of inputs and return the result in a numpy array. The problem is that the actual creation of the numpy array takes much longer than the operation itself. My question is whether it is possible to somehow speed up the creation of the new array.
As an example, consider the following:
def return_list(x1, x2, x3):
     return [x1**2, x2**2, x3**2]

def return_array(x1, x2, x3):
    return np.array([x1**2, x2**2, x3**2])

Profiling the code:
%prun for i in range(1000000): z = return_list(2, 3, 4)
%prun for i in range(1000000): z = return_array(2, 3, 4)

The first one is executed in 0.32 seconds while the second one in 1.23 seconds. This tells me that it's the conversion of the list to a numpy array what takes most of the time. Is there a way to speed up this process? My return arrays are always small, 1x3, but I need to return an array, not a list.


text:
Q: Compute $m ( \angle ACD $).
Let $\triangle ABC $ s.t $m (\angle A)=100^{°}, m (\angle B)=20^{°} $. Let $D\in Int (\triangle ABC) $ s.t. $m (\angle BAD)=30^{°} $ and $[BD $ is the bisector of $\angle B $.

Compute $m ( \angle ACD $).

I need a construction to solve it. I take $M\in [AB] $ s.t. $m (\angle ACM)=40^{°} $ and $P\in [CM]$ s.t. $m (\angle MAP=30^{°} $ I need to prove that $[BP $ is the bisector of $\angle B $. Then $P=D $.

A: We can use the Ceva's theorem also by the following way.
Let $\measuredangle ACD=x$. So $\measuredangle DCB=60^{\circ}-x$ and we obtain:
$$\sin{x}\sin10^{\circ}\sin30^{\circ}=\sin(60^{\circ}-x)\sin10^{\circ}\sin70^{\circ}$$ or
$$\frac{1}{2\sin70^{\circ}}=\sin60^{\circ}\cot{x}-\frac{1}{2}$$ or
$$\cot{x}=\frac{1+\sin70^{\circ}}{\sqrt3\sin70^{\circ}},$$
which gives $x=40^{\circ}.$
Indeed, $$\frac{1+\sin70^{\circ}}{\sqrt3\sin70^{\circ}}=\frac{1+\cos20^{\circ}}{2\cos30^{\circ}\cos20^{\circ}}=\frac{2\cos50^{\circ}+\cos30^{\circ}+\cos70^{\circ}}{4\cos50^{\circ}\cos30^{\circ}\cos20^{\circ}}=$$
$$=\frac{\cos50^{\circ}+\cos30^{\circ}+\cos10^{\circ}}{4\sin40^{\circ}\cos30^{\circ}\cos20^{\circ}}=\frac{2\cos30^{\circ}\cos20^{\circ}+\cos30^{\circ}}{4\sin40^{\circ}\cos30^{\circ}\cos20^{\circ}}=$$
$$=\frac{2\cos20^{\circ}+1}{4\sin40^{\circ}\cos20^{\circ}}=\frac{\cos20^{\circ}+\cos60^{\circ}}{2\sin40^{\circ}\cos20^{\circ}}=\frac{2\cos40^{\circ}\cos20^{\circ}}{2\sin40^{\circ}\cos20^{\circ}}=\cot40^{\circ}.$$

A: Let $D'$ be such that $\angle BAD' = 30^{\circ}$ and  $\angle BCD' = 20^{\circ}$ and let us prove $D'=D$.
We see that now $\angle ACD' = 40^{\circ}$ so $\angle CD'A = 70^{\circ}$ and thus $CA = CD'$.

Rotate $C$ around $D'$ for $60^{\circ}$ to a new point $E$.
Then $\angle ACE = 20^{\circ}$
and $CE = CD' = CA$ so $\angle AEC = \angle EAC = 80^{\circ}$ and thus $E,A,B$ are collinear.
Now we see also that $\angle ECB = 80^{\circ}$ and $\angle EAB = 20^{\circ}$ so $\angle BEC = 80^{\circ}$ which means $BE = BC$.
So triangles $EBD'$ and $CBD'$ are congruent (sss), so $BD'$ is angle bisector of angle $\angle ABC$ which means $D'=D$.
So the angle we are looking for is $\angle ACD = 40^{\circ}$.

A: You can use the trigonometric form of Ceva's theorem (in your second setting):
$$\frac{\sin\angle PAB}{\sin\angle PBA}\cdot\frac{\sin\angle PBC}{\sin\angle PCB}\cdot\frac{\sin\angle PCA}{\sin\angle PAC}=1,$$
i.e. $$\frac{\sin 30^\circ}{\sin x}\cdot\frac{\sin (20^\circ-x)}{\sin 20^\circ}\cdot\frac{\sin 40^\circ}{\sin 70^\circ}=1,$$
where $x=\angle PBA$.
By writing $\sin 30^\circ=1/2$, $\sin 70^\circ=\cos 20^\circ$ and $\sin 40^\circ=2\sin 20^\circ\cos 20^\circ$, we get $\sin(20^\circ-x)=\sin x$ which has solutions $x=10^\circ+k\pi$, and since $x$ is an angle we have $x=10^\circ$.


text:
Q: Insert ubuntu OS next of the windows7 in boot order I usually work with windows 7 and just using Ubuntu for work with some special software I want to insert Ubuntu OS next of the windows 7 entry to have auto boot with windows 7 if I do not choose one of them . is it possible?

A: There is a program for windows called easy bcd.
Install it when running windows and the proceed a described in the following link:
Download Easy BCD for window
How to Use BCD
I think this will help you to Insert ubuntu OS next of the windows7 in boot order.


text:
Q: Showing that S is a ring. I have an exercise asking me to show that a set $S$ with two operations $(\oplus_S,\otimes_S)$ is a ring.
I think I've completed all the requirements but want to make sure:
Is it enough to show that

*

*S is commutative under $\oplus_S$.

*Multiplication $\otimes_S$ is associative.

*That the distributive property holds.

I have proved all these already but are there any more that are required?

A: You still need to show that:

*

*$\oplus_S$ has a neutral element.

*$\oplus_S$ is associative.

*If $0_S$ is the aforementioned additive neutral element, that $\oplus_S$ has opposites, id est, that for all $a$ there is $b$ such that $a\oplus_S b= 0_S$ and $b\oplus_S a=0_S$.

*If your definition of ring requires it (most of them do), that $\otimes_S$ has a neutral element as well.
Some would say that you also need to check "closedness under operations", which would technically mean showing that $$\forall a,b\in S,\ (a\oplus_S b\in S\wedge a\otimes_S b\in S)$$
This is reminescent of one of the verifications that you need to do when you check that something is a subring of something else. In this case, it would be an abuse of terminology, because clearly $\oplus_S$ and $\otimes_S$ should already be functions with codomain $S$. What should be checked beforehand in this case is that $\oplus_S$ and $\otimes_S$ are two well-defined functions $S\times S\to S$.
What does that mean? Describing it in general is a bit abstract, but somewhere you have a predicate which describes what property, say, $a\oplus_S b$ is meant to satisfy with repsect to $a,b\in S$. Call that property $P(a,b;y)$ (and the definition somehow goes like "$a\oplus_S b$ is the one element satisfying $P(a,b; a\oplus_Sb)$" ).  Then you must prove that, for any $a,b\in S$ there is exactly one element $y$ in $S$ such that $P(a,b;y)$ is true. Id est: $$\forall a,b\in S,((\exists y\in S,\ P(a,b;y))\wedge (\forall w,y\in S, (P(a,b;w)\wedge P(a,b;y)\longrightarrow w=y)))$$


text:
Q: I am trying to scrape a website for my project but I am stuck with an error. Take a look and let me know if anyone have suggestion for this html_text = requests.get('https://www.trustpilot.com/categories/restaurants_bars?
numberofreviews=0&status=claimed&timeperiod=0').text
soup = BeautifulSoup(html_text, 'lxml')
restaurants = soup.find_all('a', class_ = 'internal___1jK0Z wrapper___26yB4')
for index, restaurant in enumerate(restaurants):
    name = restaurant.find('div', class_ = 'businessTitle___152-c').text
    rating = restaurant.find('div', class_ = 'textRating___3F1NO').text
    with open('{index}.csv', 'a') as f:
        f.write(name)
        f.write(',')
        f.write(rating)
        f.write('\n')

    print('File saved')

This is the code throwing an error.
Traceback (most recent call last):
File "main.py", line 8, in
name = restaurant.find('div', class_ = 'businessTitle___152-c').text
AttributeError: 'NoneType' object has no attribute 'text'

A: Ran your code and printed out the relevant bits. The set of classes you are targeting, the internal___1jK0Z wrapper___26yB4is not only used for restaurant websites, but also for the about link in the footer of the page. I think that set of classes is used for every link, rather than just the links of restaurant websites.

A: You are trying to access an attribute of an object of type None, probably one of your queries is returning None.


text:
Q: Converting a mmm-yy date in string format to date format I have an excel document that lists dates in mmm-yy format as a string (they've been copied in from a pdf). I need to be able to determine the number of days between these dates, however excel misunderstands them as mmm-dd format.
For example: I need to find the number of days between Jun-11 and Jun-13. Say they are in A1 and B1 respectively. In the next cell I type "=B1-A1". Number of days should be 730, but excel puts out 2. It calculates June 13th, 2014 - June 11th, 2014.
When I try to change the format to date it will give me something like Jun-11 -> Jun-14 (still reading it as June 11th, 2014).
I've tried to concatenate the dates to make a full date ("Jun"+"-1-"+"11") = Jun-1-11, but it still comes out as a string and I cannot perform the necessary operations with it.
Is there a way to easily correct the format of these dates? I could do this manually with Replace but there are several hundred.

A: First suggestion:
Highlight the Excel column holding your date strings, and Format the cells to be "General" instead of "Text".  Excel should then figure out they are dates, and will probably convert them properly.
Second suggestion (more directly answering the question):
You can use MID, LEFT and/or RIGHT to manually pick apart the date string, and then use DATE to convert it to an actual date type.
Reference (see Option #3)
DATE Syntax: DATE(year, month, day)
So say A1 contains "JUN-13"...
=DATE(CONCATENATE("20",RIGHT(A1,2)),MONTH(1&LEFT(A1,3)),1)
CONCATENATE is used to join the string "20" to the string representing the year, to ensure it doesn't think "13" is "1913" during conversion.
The MONTH function is used to get the number of the month based on the provided text string.  the 1& bit is to force MONTH to join the 1 to the first three characters of the cell (say "1Jun"). Excel recognises that as a date format and treats it like a date for the MONTH function to then extract the month number.
Reference
Once those are done, DATE is used to combine the bits into a final date (using a "Day" of 1).
Using your example data and the above formula to convert them and put the results in new cells, and then performing the subtraction on the cells with the results gives me 731 (leap year? :) ).


text:
Q: linker command failed with exit code 1 when link object files I'm trying to test SinglyLinked List example in "Data Structure and Algorithm in c++" by Micheal T. Goodrich and etc. I added some details omitted by the author in order to make it runnable.
Here's the code:
#ifndef S_LINKED_LIST
#define S_LINKED_LIST

template <typename E>
class SLinkedList;

template <typename E>
class SNode
{
    private:
        E elem;
        SNode<E> * next;
        friend class SLinkedList<E>;
};
template <typename E>
class SLinkedList
{
    private:
        SNode<E> * head;
    public:
        SLinkedList();
        ~SLinkedList();
        bool empty() const;
        const E& front() const;
        void addFront(const E& e);
        void removeFront();
};
#endif /*SLinkedList.h*/

Implementation:
#include "SLinkedList.h"
#include <iostream>

template <typename E>
SLinkedList<E>::SLinkedList():head(NULL){}

template <typename E>
SLinkedList<E>::~SLinkedList()
{while(!empty()) removeFront();}

template <typename E>
bool SLinkedList<E>::empty() const
{return head == NULL;}

template <typename E>
const E& SLinkedList<E>::front() const
{return head->elem;}

template <typename E>
void SLinkedList<E>::addFront(const E& e)
{
    SNode<E> * newNode = new SNode<E>;
    newNode->elem = e;
    newNode->next = head;
    head = newNode;
}

template <typename E>
void SLinkedList<E>::removeFront()
{
    SNode<E> * old = head;
    head = old->next;
    delete old;
}/*SLinkedList.cpp*/

test file:
#include <iostream>
#include "SLinkedList.h"

int main()
{
    SLinkedList<std::string> newlist;
    newlist.addFront("MSP");
    std::cout << newlist.front();
    return 0;
}/*test_slinkedlist.cpp*/

After running g++ -c SLinkedList.cpp and g++ -c test_slinkedlist.cpp
I got object files SLinkedList.o and test_slinkedlist.o without error.
but when I run g++ -o result test_slinkedlist.o SLinkedList.o, I got linker errors:
Undefined symbols for architecture x86_64:
...
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I spend a day debugging this linker issue but can't find. I suspect it's obvious.
Operating System: OS X

full error message:
Undefined symbols for architecture x86_64:
  "SLinkedList<std::__1::basic_string<char,     std::__1::char_traits<char>, std::__1::allocator<char> >     >::addFront(std::__1::basic_string<char, std::__1::char_traits<char>,     std::__1::allocator<char> > const&)", referenced from:
      _main in test_slinkedlist.o
  "SLinkedList<std::__1::basic_string<char,     std::__1::char_traits<char>, std::__1::allocator<char> > >::SLinkedList()",     referenced from:
      _main in test_slinkedlist.o
  "SLinkedList<std::__1::basic_string<char,     std::__1::char_traits<char>, std::__1::allocator<char> >     >::~SLinkedList()", referenced from:
      _main in test_slinkedlist.o
  "SLinkedList<std::__1::basic_string<char,     std::__1::char_traits<char>, std::__1::allocator<char> > >::front() const",     referenced from:
      _main in test_slinkedlist.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

A:
Implementation:

You didn't say it, but we can assume that implementation is in SLinkedList.cpp.

Undefined symbols for architecture x86_64:
...

In the ..., you've omitted the most important part of the error message. However, we can guess that SLinkedList<std::string>::addFront(...) is among the unresolved symbols.
Your problem is that the body of the template method (i.e. the implementation) must be present in every compilation unit in which it is used, and you've violated that rule by putting this body into a separate .cpp file, which is not visible to the compiler when it compiles test_slinkedlist.cpp.
This is why template bodies are most often included in the SLinkedList.h (note the .h, not the .cpp). See also this answer.
P.S. Technically, the "must" above is incorrect: you could also use explicit instantiation to make the compiler produce template method bodies that you need. But that's a bit more advanced solution than putting the implementation into .h file.

A: In C++, you can't compile and link uninstantiated templates as a separate compilation unit.
SLinkedList.cpp has no instantiated templates, so it will compile into essentially nothing.
This is why template-only libraries are always header-only.
You have a couple of choices.
Either instantiate your SLinkedList within
SLinkedList.cpp's compilation unit to let the compiler generate actual code for the template instance, or combine your header and cpp into one file.


text:
Q: XML attribute not removing using XML.modify My XML is like below.
 <TDBUIData xmlns="http://www.somedomain.com/pace/r2.4/v1">
  <FileCreationDate>2014-07-18T13:21:48.507</FileCreationDate>
  <TDBUIDataList xmlns="">
    <PaceJobNumber>3898646894</PaceJobNumber>
    <TaskData>
      <TaskCode>Secon</TaskCode>
      <TaskAssigneeForecastFinishDate>07/16/2014</TaskAssigneeForecastFinishDate>
      <ActualFinishDate>01/01/2000</ActualFinishDate>
    </TaskData>
  </TDBUIDataList>
<TDBUIDataList xmlns="">
    <PaceJobNumber>11331313232</PaceJobNumber>
    <TaskData>
      <TaskCode>Secod</TaskCode>
      <TaskAssigneeForecastFinishDate>07/16/2014</TaskAssigneeForecastFinishDate>
      <ActualFinishDate>01/21/2000</ActualFinishDate>
    </TaskData>
  </TDBUIDataList>
</TDBUIData>

I need to remove xmlns="" attribute from all TDBUIDataList tags.
I am using this query, But its just not working.
DECLARE @XML XML
;WITH XMLNAMESPACES (DEFAULT 'http://www.somedomain.com/pace/r2.4/v1' )
Select @XML=(SELECT  GETDATE() AS FileCreationDate, CONVERT(XML,@paceXML)
FOR XML PATH('TDBUIData'))

SET @XML.modify('delete (/TDBUIData/TDBUIDataList/@xmlns[.=""])[1]')
SELECT @XML


text:
Q: java is not recognized even after setting the path I installed Java JDK then set the path of system environment in advanced setting but still java is not recognized in command prompt..
Here is the screenshot

A: There are multiple possibilities

*

*You tried to execute jawa ....
In this case, you made a spelling mistake. It is java and not jawa.

*the directory of java (or java.exe) is not in your PATH. If you use windows try running set PATH=<C:\Path\to\Java\bin> and if you use Unix-like systems, try PATH=/<Path/to/Java/bin>.


text:
Q: in js on page refresh its takes me to primary page With AJAX, as all functions are loaded on a dynamic page without the page being reloaded or more importantly a URL being changed (except for a hash symbol maybe), clicking the back or refresh button would take you to an entirely different web page or to the beginning of what your dynamic web page was processing basically, I want it should remain on the same page
on index page main div #content is placed.

home

about

A: Ajax Content is persistent till the point you refresh the page, if you want to retain the values:
You can do that once you send ajax request to page to be rendered store this date in session once you refresh the page you can render this partial from session if it was set before.
User following content for save your page data which you have retrieve during ajax load.
session_start();
$page_data = 'set value in this variable during your ajax call';
//save data in $_SESSION
$_SESSION['page_data'] = $page_data;

below code use for render data on html:
if(isset($_SESSION['page_data']))
    {  $html = $_SESSION['page_data'];}


text:
Q: Editing the Top.phtml First off I just want to say thank you to who ever can help me, I'm currently using the MT Cosmetic Theme, but if I go to /app/design/frontend/base/default/template/catalog/navigation/top.phtml and edit that, nothing changes I've recached the site as well, can anyone help?
Thanks! :)

A: The chances our the package/theme will have it's own version of this file. Try looking in the following places.
app/design/frontend/{MT Cosmetic}/default/template/catalog/navigation/top.phtml

But to find out exactly which templates are used you can turn on template hints via the admin section. Under System->Configuration you need to set current configuration scope to your Store and then then select Developer->Debug to find these settings.


text:
Q: deleting micropost in ruby on rails tutorial I've been working through Hartl's tutorial and almost finished chapter 10 when I hit this error:
1) MicropostPages micropost destruction as correct user should delete a micropost
 Failure/Error: expect { click_link "delete" }.to change(Micropost, :count).by(-1)
   count should have been changed by -1, but was changed by 0
 # ./spec/requests/micropost_pages_spec.rb:38:in `block (4 levels) in <top (required)>'

When I click the "delete" link in the app itself, it redirects without deleting the micropost. I've gone back and forth comparing my code to his, and searching online, but I can't seem to find the problem.  I am hoping that one of you with more experienced eyes than mine can help.
spec/requests/micropost_pages_spec.rb:
describe "micropost destruction" do
 before { FactoryGirl.create(:micropost, user: user) }

 describe "as correct user" do
   before { visit root_path }

   it "should delete a micropost" do
     expect { click_link "delete" }.to change(Micropost, :count).by(-1)
   end
  end
end

microposts_controller.rb:
class MicropostsController < ApplicationController
  before_action :signed_in_user, only: [:create, :destroy]
  before_action :correct_user, only: [:destroy]

  def create
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save
      flash[:success] = "Micropost created!"
      redirect_to root_url
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

  def destroy
    @micropost.destroy
    redirect_to root_url
  end

  private

    def micropost_params
      params.require(:micropost).permit(:content)
    end

    def correct_user
      @micropost = current_user.microposts.find_by(id: params[:id])
      redirect_to root_url if @microposts.nil?
    end
end

app/views/microposts/_micropost.html.erb:

  <%= micropost.content %>

    Posted <%= time_ago_in_words(micropost.created_at) %> ago.

  <% if current_user?(micropost.user) %>
    <%= link_to "delete", micropost, method: :delete,
    data: { confirm: "You sure?" },
    title: micropost.content %>
  <% end %>

app/views/shared/_feed_item.html.erb:
<li id="<%= feed_item.id %>">
  <%= link_to gravatar_for(feed_item.user), feed_item.user%>

    <%= link_to feed_item.user.name, feed_item.user %>

  <%= feed_item.content %>

    Posted <%= time_ago_in_words(feed_item.created_at)%> ago.

  <% if current_user?(feed_item.user) %>
    <%= link_to "delete", feed_item, method: :delete,
    data: { confirm: "You sure" },
    title: feed_item.content %>
  <% end %>

config/routes.rb:
SampleApp::Application.routes.draw do
  resources :users
  resources :sessions, only: [:new, :create, :destroy]
  resources :microposts, only: [:create, :destroy]
  root 'static_pages#home'
  match '/signup', to: 'users#new', via: 'get'
  match '/signin', to: 'sessions#new', via: 'get'
  match '/signout', to: 'sessions#destroy', via: 'delete'
  match '/help', to: 'static_pages#help', via: 'get'
  match '/about', to: 'static_pages#about', via: 'get'
  match '/contact', to: 'static_pages#contact', via: 'get'

I get this when I click the "delete" link
Started DELETE "/microposts/295" for 127.0.0.1 at 2014-07-01 16:02:34 -0400
Processing by MicropostsController#destroy as HTML
Parameters: {"authenticity_token"=>"mQUxCMrrNfelpeXmxqO0+GmznKS7BGQeFL5upFgp0Tc=", "id"=>"295"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."remember_token" = '99409d871e582f2e3251d83f33751645707c72bc' LIMIT 1
  Micropost Load (0.6ms)  SELECT "microposts".* FROM "microposts" WHERE "microposts"."user_id" = ? AND "microposts"."id" = 295 ORDER BY created_at DESC LIMIT 1  [["user_id", 1]]
Redirected to http://localhost:3000/
Filter chain halted as :correct_user rendered or redirected
Completed 302 Found in 14ms (ActiveRecord: 0.9ms)

A: It almost looks like the user doesn't have a Micropost to delete? Make sure there is one setup before you execute the spec. You could add this: expect(user.microposts.count).to_not eq(0) as shown below to confirm there is a post belonging to the user.
describe "micropost destruction" do
 before { FactoryGirl.create(:micropost, user: user) }

 describe "as correct user" do
   before { visit root_path }

   it "should delete a micropost" do
     expect(user.microposts.count).to_not eq(0)
     expect { click_link "delete" }.to change(Micropost, :count).by(-1)
   end
  end
end

A: I figured it out.  A simple typo in the microposts_controller.
the line:
redirect_to root_url if @microposts.nil?

should be
redirect_to root_url if @micropost.nil?


text:
Q: EF Core - Map property collection of same type I am trying to define an (EF Core, code first) entity that has a list of associates of the same type
public class Entity
{
    public int Id { get; set; }
    public HashSet<Entity> Associates { get; set; }
}

The associates have no knowledge of the entity to which it belongs.
I am struggling to figure out how to map this (fluently)


text:
Q: How to bind a multipart/form-data file without filename to IFormFile in ASP.NET Core In a simple controller action in ASP.NET Core 3.1 that accepts multipart/form-data parameters:
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication
{
    public class Controller : ControllerBase
    {
        [HttpPost("length")]
        public IActionResult Post([FromForm] Input input)
        {
            if (!ModelState.IsValid)
                return new BadRequestObjectResult(ModelState);

            return Ok(input.File.Length);
        }

        public class Input
        {
            [Required]
            public IFormFile File { get; set; }
        }
    }
}

When I send a multipart/form-data with a File with no filename (which is acceptable under RFC 7578) it is not recognized as an IFormFile. For example:
using System;
using System.IO;
using System.Threading.Tasks;
using System.Net.Http;

namespace ConsoleApp4
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await Test(withFilename: true);
            await Test(withFilename: false);
        }

        static async Task Test(bool withFilename)
        {
            HttpClient client = new HttpClient();

            var fileContent = new StreamContent(new FileStream("/Users/cucho/Desktop/36KB.pdf", FileMode.Open, FileAccess.Read));

            var message = new HttpRequestMessage(
                HttpMethod.Post,
                "http://localhost:5000/length"
            );

            var content = new MultipartFormDataContent();

            if (withFilename)
            {
                content.Add(fileContent, "File", "36KB.pdf");
            }
            else
            {
                content.Add(fileContent, "File");
            }

            message.Content = content;

            var response1 = await client.SendAsync(message);

            var withString = withFilename ? "With" : "Without";

            Console.WriteLine($"{withString} filename: {(int)response1.StatusCode}");
        }
    }
}

results in:
With filename: 200
Without filename: 400

How can I bind that File without filename to the IFormFile object?
Edit:
I found in the ContentDispositionHeaderValueIdentityExtensions the following method:
public static class ContentDispositionHeaderValueIdentityExtensions
{
    /// <summary>
    /// Checks if the content disposition header is a file disposition
    /// </summary>
    /// <param name="header">The header to check</param>
    /// <returns>True if the header is file disposition, false otherwise</returns>
    public static bool IsFileDisposition(this ContentDispositionHeaderValue header)
    {
        if (header == null)
        {
            throw new ArgumentNullException(nameof(header));
        }

        return header.DispositionType.Equals("form-data")
            && (!StringSegment.IsNullOrEmpty(header.FileName) || !StringSegment.IsNullOrEmpty(header.FileNameStar));
    }

And a similar code in FormFeature, which I think is how it decides whether the part is a file or not.

A: Just iterating what @Tieson T. mentioned in the comments, model binder requires files to have filenames regardless of their value.
I am sending a request using HttpClient, and this is working. If I omit filename, it won't work.
var formContent = new MultipartFormDataContent();
var streamContent = new StreamContent(request.Stream);
formContent.Add(streamContent, "Photo", "any filename is accepted");

https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/Mvc.Core/src/ModelBinding/Binders/FormFileModelBinder.cs#L142


text:
Q: How to assign a long variable in a Url I have an object as a variable ,so I want to assign this object as an Id my link.
I wrote the below code but it does not work.
here is my code :

$(".rooms").each(function(index, element) {
  var policy = $(".policy").val();
  alert(policy)
 $('.search-box2').load('page.html?id=+policy+&debug=true');

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<div class="rooms">
<input type="text" value="{ "id" : { "provider" : { "provider_id" : "10", "dmnid" : 2452 }, "NonRefundable" : "false", "id" : "#1#c2ce302a2032435c96a0b80b8dadc5b2@63a517cd8bca4b318ae398e329509f68" } }" class="policy">
</div>

A: You can use Blob like this:
var obj ='{ "id" : { "provider" : { "provider_id" : "10", "dmnid" : 2452 }, "NonRefundable" : "false", "id" : "#1#c2ce302a2032435c96a0b80b8dadc5b2@63a517cd8bca4b318ae398e329509f68" } }',
    b = new Blob([obj], {type: "application/json"}),
    url = URL.createObjectURL(b);

Online demo (jsFiddle)


text:
Q: Why does casting object's address to same class as this points to results in another object value? I have an object of the class RTSG::XML3D::OpenGLMeshMA. When stopped at the breakpoint in its method RTSG::XML3D::OpenGLMeshMA::onXflowStateChanged I add the following expressions into the Watch window:

How can it be that the raw address of the object casted into the same pointer type as this results in a different object (object and uniqieId members have different values in the first and second rows)?
System info: VS 2008 3.5 SP1, Win 7 64-bit.

A: The only reasonable explanation (other than a debugger bug) is that you're using multiple inheritance. The start of the object is not 0x0a72d4e4, it's somewhere else (probably a pointer higher or lower). The line with the cast is forcing the debugger to treat that address as the start of the object, and accordingly it's reading bad values.
With multiple inheritance, the value of 'this' can be different from the address of the start of the object, and the compiler inserts adjustments as necessary. It's discussed in e.g. here, here.


text:
Q: Using arrays with a for loop in C I am using C and I have an array t[]
I wrote a for loop but the answer is wrong.
Please help me catch the error. My code is:
for(j = 0; j < tags; j++)
{
    for(k = j; k < nb_of_subscribers*tags; k = k+tags)
    {
        avr[j] = (float)(avr[j]+t[k]);
    }
    printf("avr[j]:%f", avr[j]);
}

Actually , the values of t[] are read incorrectly in the for loop i don't know why . If i use a for loop only to printf the values of the array t the response is correct otherwise(in the for loop)it is incorrect
Thank you.

A: You should set avr[j] to 0 before starting your iterative sum:
for(j = 0; j < tags; j++)
{
    avr[j] = 0; // <-----
    for(k = j; k < nb_of_subscribers*tags; k = k+tags)
    {
        avr[j] = (float)(avr[j]+t[k]);
    }
    printf("avr[j]:%f", avr[j]);
}

A: So I assume that t is an array of size nb_of_subscribers*tags and avr is an array of size tags.
If I'm not mistaken, what you intend to do is the following:
for(int j = 0; j < tags; j++)
{
    for(int k = 0; k < nb_of_subscribers; k++)
    {
        avr[j] += (float)(t[j + k*tags]);
    }
    printf("avr[j]:%f", avr[j]);
}

Which is to say, assuming tags were 2 and nb_of_subscribers were 3, with the array t[6] = {0, 5, 1, 6, 2, 7}, then array avr[2] would be {3, 18}.  Am I correct in that this is what you wanted to do?


text:
Q: Whirl effect with HLSL, starting from Microsoft SpriteEffects sample The sample
If you watch the code, I'm interested in refraction.fx, and in void DrawRefractGlacier(GameTime gameTime) function. Here you can notice that the function uses a texture to render water distortion on an image (waterfall.jpg as "distorter image", and glacier.jpg as distorted image).
If you read inside refraction.fx, at the beginning it says:
// Effect uses a scrolling displacement texture to offset the position of the main
// texture. Depending on the contents of the displacement texture, this can give a
// wide range of refraction, rippling, warping, and swirling type effects.

It seems that would be easy to achieve another effect by changing the image. I tried that with an image like this:

I want to achieve the effect of distorting everything around as a rotating whirl, or a spiral. How can I do that?
Some simple sequential screen of how it looks with my texture:

Refraction shader:
// Effect uses a scrolling displacement texture to offset the position of the main
// texture. Depending on the contents of the displacement texture, this can give a
// wide range of refraction, rippling, warping, and swirling type effects.

float2 DisplacementScroll;
float2 angle;

sampler TextureSampler : register(s0);
sampler DisplacementSampler : register(s1);

float2x2 RotationMatrix(float rotation)
{
    float c = cos(rotation);
    float s = sin(rotation);

    return float2x2(c, -s, s ,c);
}

float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
   float2 rotated_texcoord = texCoord;
        rotated_texcoord -= float2(0.25, 0.25);
        rotated_texcoord = mul(rotated_texcoord, RotationMatrix(angle));
        rotated_texcoord += float2(0.25, 0.25);

    float2 DispScroll = DisplacementScroll;

    // Look up the displacement amount.
    float2 displacement = tex2D(DisplacementSampler, DispScroll+ texCoord / 3);

    // Offset the main texture coordinates.
    texCoord += displacement * 0.2 - 0.15;

    // Look up into the main texture.
    return tex2D(TextureSampler, texCoord) * color;
}

technique Refraction
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 main();
    }
}

Its draw call:
void DrawRefractGlacier(GameTime gameTime)
{
    // Set an effect parameter to make the
    // displacement texture scroll in a giant circle.
    refractionEffect.Parameters["DisplacementScroll"].SetValue(
                                                MoveInCircle(gameTime, 0.2f));

    // Set the displacement texture.
    graphics.GraphicsDevice.Textures[1] = waterfallTexture;

    // Begin the sprite batch.
    spriteBatch.Begin(0, null, null, null, null, refractionEffect);

    // Because the effect will displace the texture coordinates before
    // sampling the main texture, the coordinates could sometimes go right
    // off the edges of the texture, which looks ugly. To prevent this, we
    // adjust our sprite source region to leave a little border around the
    // edge of the texture. The displacement effect will then just move the
    // texture coordinates into this border region, without ever hitting
    // the edge of the texture.

    Rectangle croppedGlacier = new Rectangle(32, 32,
                                             glacierTexture.Width - 64,
                                             glacierTexture.Height - 64);

    spriteBatch.Draw(glacierTexture,
                     GraphicsDevice.Viewport.Bounds,
                     croppedGlacier,
                     Color.White);

    // End the sprite batch.
    spriteBatch.End();
}


text:
Q: In python how do I assign a series of commands to one variable? I'm self teaching myself python by delving right in. I'm not sure if a function does this if you leave it empty:
#My first section that pulls a value from a random shuffle of codes
print "\n"
print "-"*10
print 'This is a test of the %s system'% codes[0]
print "-"*10
print "\n"

#My second section that pulls a value from a random shuffle of codes
print "\n"
print "-"*10
print 'This is not a test of the %s system and all is good'% codes[1]
print "-"*10
print "\n"

My question is, is there a way to make it nicer looking and with fewer lines of code? Or am I stuck with having 10 lines of print?

A: You can use a function:
def print_stuff(what,addendum=''):
    print "\n"
    print "-"*10
    print 'This is a test of the %s system%s' % (what,addendum)
    print "-"*10
    print "\n"

print_stuff(codes[0])
print_stuff(codes[1],addendum = " and all is good")

A: Python has quite awesome multiline strings:
def print_it(somethig):
    print """
----------
This is a test of the {} system.
----------
""".format(something)

print_it(0)
print_it(1)

A: Create a function with the index number:
def print_codes(i):
    #My first section that pulls a value from a random shuffle of codes
    print "\n"
    print "-"*10
    print 'This is a test of the %s system'% codes[i]
    print "-"*10
    print "\n"

print_codes(0)
print_codes(1)

Also read this documentation

A: If you want to show different messages, you can define a function that receives the message to be printed:
def print_message(message):
    print "\n"
    print "-"*10
    print message
    print "-"*10
    print "\n"

print_message('This is a test of the %s system' % codes[0])
print_message('This is not a test of the %s system and all is good'% codes[1])


text:
Q: Laravel insert dynamic input values with radio button I am a beginner at Laravel, I want to insert a more dynamic address field to the database and I want to select one primary address using the radio button. I can able to add more address fields, but, I am unable to select one primary address because it's selecting all radio button values. I have given below using my code
This is My Blade File

          <form action="{{ route('register.post') }}" enctype="multipart/form-data" accept-charset="utf-8" method="POST" >
               @csrf

                  Address

                         <button type="button" name="add" id="add-btn" class="btn btn-success">Add More Details</button>

                    <button type="submit" class="btn btn-primary">
                            Save
                     </button>

                </form>

This is My Controller File
 public function postRegistration(Request $request)
{
    $id = DB::getPdo()->lastInsertId();
    foreach ($request->moreFields as $key => $value) {

        Address::create([
            'user_id'=>$id,
            'house_no'=>$value['house_no'],
            'street_name'=>$value['street_name'],
            'area'=>$value['area'],
            'pincode'=>$value['pincode'],
            'primary_address'=>$value['primary_address'],

        ]);
    }

A: You dont need to make different name radio buttons use same name for all radio buttons so that user can not select other radio button after selecting one
<input type="radio" class="form-check-input" name="moreFields" value="'+i+'">

A: Laravel 8 Dynamic Radio Button Edit Page
This worked for me
@foreach($lease_stores as $lease_store)

                <input class="form-check-input" type="radio" name="lease_store_id" id="inlineRadio1" @if($general_details->lease_store_id==$lease_store->id) checked value="{{$lease_store->id}}"
                @else value="{{$lease_store->id}}"
                @endif>
               {{$lease_store->name}}

              @endforeach

Controller master fetch
$lease_stores=Leasestore::all();


text:
Q: best layout for my android application I am building a twitter client android application.Say i am now on "timeline" page of my app.
A typical timeline page shows the recent tweets with additional info like location of the tweet,application name etc.
So my question is how to design a layout for such an application.provide me some samples.
thanks

A: I will assume you know about basic android widgets etc in the answer, if not, just ask...
My suggestion would be to follow the conventions set out by the android team, for example have an action bar at the top, with buttons such as to create a new tweet/search tweets and then have a list view below it. If you choose to use a list view, then the list row and list adapter will be the things to customise for showing photos, and other info about tweets.
Or, you could use a view flipper (or similar, but slightly more challenging to implement technique) to slide between tweets, where a single tweet takes up the whole screen at any one time.
I hope that's helpful.


text:
Q: Package not found - add libav to PKG_CONFIG_PATH environment variable I am attempting to build the Parrot SDK and when running the command it continuously fails due to multiple libav package variants not being found. Below is the error message.
    user@TheMysteriousMachine:~/WORKING_DIRECTORY$ ./build.sh -p arsdk-native -t build-sdk -j
    [I] Starting task 'build-sdk'
    [I] In '/home/user/WORKING_DIRECTORY':   ALCHEMY_TARGET_CONFIG_DIR="/home/user/WORKING_DIRECTORY/products/arsdk  /native/config" ALCHEMY_TARGET_OUT="/home/user/WORKING_DIRECTORY/out/arsdk-native" ALCHEMY_TARGET_PRODUCT="arsdk" ALCHEMY_TARGET_PRODUCT_VARIANT="native" ALCHEMY_TARGET_SCAN_ADD_DIRS=" /home/user/WORKING_DIRECTORY/packages" ALCHEMY_TARGET_SCAN_PRUNE_DIRS=" /home/user/WORKING_DIRECTORY" ALCHEMY_USE_COLORS="1" ALCHEMY_WORKSPACE_DIR="/home/user/WORKING_DIRECTORY" PARROT_BUILD_PROP_GROUP="drones" PARROT_BUILD_PROP_PRODUCT="arsdk" PARROT_BUILD_PROP_PROJECT="arsdk" PARROT_BUILD_PROP_UID="arsdk-native-20190316-1404-0.0.0" PARROT_BUILD_PROP_VARIANT="native" PARROT_BUILD_PROP_VERSION="0.0.0" /home/user/WORKING_DIRECTORY/build/alchemy/scripts/alchemake -j 8 all
    ----------------------------------------------------------------------
    + ALCHEMY_WORKSPACE_DIR = /home/user /WORKING_DIRECTORY
    + TARGET_PRODUCT = arsdk
    + TARGET_PRODUCT_VARIANT = native
    + TARGET_OS = linux
    + TARGET_OS_FLAVOUR = native
    + TARGET_LIBC = native
    + TARGET_ARCH = x64
    + TARGET_CPU =
    + TARGET_OUT = /home/user/WORKING_DIRECTORY/out/arsdk-native
    + TARGET_CONFIG_DIR = /home/user/WORKING_DIRECTORY /products/arsdk/native/config
    + TARGET_CC_PATH = /usr/bin/cc
    + TARGET_CC_VERSION = 7
    ----------------------------------------------------------------------
    Scanning /home/user/WORKING_DIRECTORY/packages for makefiles...
    Found 44 makefiles
    Prebuilt module ncurses marked as overriden
    Prebuilt module ncurses marked as overriden
    Package libavcodec was not found in the pkg-config search path.
    Perhaps you should add the directory containing libavcodec.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libavcodec' found
    Package libavformat was not found in the pkg-config search path.
    Perhaps you should add the directory containinglibavformat.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libavformat' found
    Package libswscale was not found in the pkg-config search path.
    Perhaps you should add the directory containing libswscale.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libswscale' found
    Package libavutil was not found in the pkg-config search path.
    Perhaps you should add the directory containinglibavutil.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libavutil' found
    Package libavcodec was not found in the pkg-config search path.
    Perhaps you should add the directory containing libavcodec.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libavcodec' found
    Package libavformat was not found in the pkg-config search path.
    Perhaps you should add the directory containinglibavformat.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libavformat' found
    Package libswscale was not found in the pkg-config search path.
    Perhaps you should add the directory containing libswscale.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libswscale' found
    Package libavutil was not found in the pkg-config search path.
    Perhaps you should add the directory containinglibavutil.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libavutil' found
    Found 96 modules
    Computing modules dependencies...
    Checking modules dependencies...
    /home/user/WORKING_DIRECTORY/build/alchemy/main.mk:360: *** /home/user    /WORKING_DIRECTORY/packages/libARDiscovery: module 'libARDiscovery'     depends on unknown module 'avahi'.  Stop.
    [E] Task 'build-sdk' failed (Command     failed (returncode=2))

As I understand it libav has been replaced by ffmpeg but the build should     still be able to reference the packages as libav. I've tried adding different paths to PKG_CONFIG_PATH using `export PKG_CONFIG_PATH=...' but with no success. It is possible I'm not adding the correct path, I used 'dpkg -L ffmpeg' to locate the package. The output of that is:
    user@TheMysteriousMachine:~$ dpkg -L ffmpeg
    /.
    /etc
    /etc/ffserver.conf
    /usr
    /usr/bin
    /usr/bin/ffmpeg
    /usr/bin/ffplay
    /usr/bin/ffprobe
    /usr/bin/ffserver
    /usr/bin/qt-faststart
    /usr/share
    /usr/share/doc
    /usr/share/doc/ffmpeg
    /usr/share/doc/ffmpeg/RELEASE_NOTES
    /usr/share/doc/ffmpeg/copyright
    /usr/share/ffmpeg
    /usr/share/ffmpeg/libvpx-1080p.ffpreset
    /usr/share/ffmpeg/libvpx-1080p50_60.ffpreset
    /usr/share/ffmpeg/libvpx-360p.ffpreset
    /usr/share/ffmpeg/libvpx-720p.ffpreset
    /usr/share/ffmpeg/libvpx-720p50_60.ffpreset
    /usr/share/lintian
    /usr/share/lintian/overrides
    /usr/share/lintian/overrides/ffmpeg
    /usr/share/man
    /usr/share/man/man1
    /usr/share/man/man1/ffmpeg-all.1.gz
    /usr/share/man/man1/ffmpeg-bitstream-filters.1.gz
    /usr/share/man/man1/ffmpeg-codecs.1.gz
    /usr/share/man/man1/ffmpeg-devices.1.gz
    /usr/share/man/man1/ffmpeg-filters.1.gz
    /usr/share/man/man1/ffmpeg-formats.1.gz
    /usr/share/man/man1/ffmpeg-protocols.1.gz
    /usr/share/man/man1/ffmpeg-resampler.1.gz
    /usr/share/man/man1/ffmpeg-scaler.1.gz
    /usr/share/man/man1/ffmpeg-utils.1.gz
    /usr/share/man/man1/ffmpeg.1.gz
    /usr/share/man/man1/ffplay-all.1.gz
    /usr/share/man/man1/ffplay.1.gz
    /usr/share/man/man1/ffprobe-all.1.gz
    /usr/share/man/man1/ffprobe.1.gz
    /usr/share/man/man1/ffserver-all.1.gz
    /usr/share/man/man1/ffserver.1.gz
    /usr/share/man/man1/qt-faststart.1.gz
    /usr/share/doc/ffmpeg/changelog.Debian.gz

...of which I can assume the useful part is '/usr/bin' which i added to my PKG_CONFIG_PATH and still the same error when building. I am running Ubuntu 18.04 LTS. I'm at a loss and have been grinding at this for the past 2 days, any help would be  GREATLY  appreciated. Thank you and I'm happy to provide more needed information. As a small request, I am pretty new to Linux so if you could include as many details in command line operations as possible it would help alot.

A: Assuming you followed FFmpeg Ubuntu compilation guidelines here:https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu
The path you looking for must be here: PKG_CONFIG_PATH="$HOME/ffmpeg_build/lib/pkgconfig


text:
Q: Crash on startup after intalling Roller Coaster Tycoon in Wine in Ubuntu 11.04 After a seemingly successful install of Roller Coaster Tycoon (the super old one, from the old disk I had from my family's first PC) using Wine 1.2.2 (and Wine 1.3.15) on Ubuntu 11.04, the program will not launch and nothing appears in the command terminal when I attempt to launch it. The game's initial menu does appear, from which I select to play the game, then it disappears and nothing happens.
I thought it might be DirectX because some other forums suggested this, but I installed DirectX 9 under Wine and during the Roller Coaster Tycoon install, it said that the version of DirectX was fine.
Can anyone help me understand why this refuses to launch in Wine or even just how to get more information when I try to launch it?

A: You are using an old version of Wine. Wine changes very rapidly. Programs that work with one version of Wine may not work in a later version. Then they get fixed in an even later version.
Try updating wine. There is an Ubuntu PPA maintained by the Wine developers that is kept up to date. You will need to install the wine1.3 package instead of just upgrading since you are using the wine1.2 package.

A: On the Wine App DB, someone recommended a patch for Rollercoaster Tycoon that is supposed to help with startup issues.
Maybe RollerCoaster Tycoon does not like the version of Windows you are emulating. Run winecfg and change the "Windows Version" setting on the "Applications" tab to the version of Windows the game was released for. You should be able to set this option for RollerCoaster Tycoon only.


text:
Q: Issues deploying .NET VSTO Excel addins, what is the best way to do it? When publishing an Excel Addin made in VS2010 using ClickOnce everything works out as it should. However when I update the code and do another publish. I encounter an error when opening Excel (see attached). Apparently the addin will not automatically update to the newest version, which is kind of the point of publishing this way. How can I get around this? And is there a better way to do it?
Note that if I manually run the setup.exe or vsto file from the publish dir, and then open Excel there is no problem, it's the automatic update that fails.
Error message (partial):

The customization cannot be installed because another version is already installed and cannot be upgraded from this location...

A: The issue emerged as a result of having an installation of the add-in installed, and at the same time debugging another version of the same add-in. The solution was uninstalling the deprecated version, doing a clean in Visual Studio.After that debugging worked fine again.


text:
Q: New Task Button on Account Need a way to put 'New Task' button on the compact layout of account . I added it to page layout but the action is now appearing in activity composer.
We cannot use this because we have many record types, also there's no cancel button to close/collapse the component once the button is clicked.(I have seen an idea to bring the cancel/Close button to activity composer actions)
I saw this answer advising to add one more quick action, but I would like to know if there's no other way before I go ahead with this approach(Or Code).
What I would love to see is a 'New Task' button which pops up a nice little modal asking the user to select the record type user wants, you know, the standard salesforce way.
Thank you.

A: I think the way to go for your scenario, and since it sounds like you do not want to have the button in activity composer would be to create a Flow Action (or a Lightning Component action if you prefer the with code approach).
Flow Action Docs


text:
Q: how to fix operator + undefined for the arguments type(s) int, object i have source code call as PhpArray Class from JavaBridge
public final class PhpArray extends AbstractMap
{
    private TreeMap t;
    private HashMap m;

    public PhpArray() {
        this.t = new TreeMap(Request.PHP_ARRAY_KEY_COMPARATOR);
        this.m = null;
    }

    @Override
    public Object put(final Object key, final Object value) {
        if (this.m != null) {
            return this.m.put(key, value);
        }
        try {
            return this.t.put(key, value);
        }
        catch (ClassCastException e) {
            this.m = new HashMap(this.t);
            this.t = null;
            return this.m.put(key, value);
        }
    }

    @Override
    public Set entrySet() {
        if (this.t != null) {
            return this.t.entrySet();
        }
        return this.m.entrySet();
    }

    public int arraySize() {
        if (this.t == null) {
            throw new IllegalArgumentException("The passed PHP \"array\" is not a sequence but a dictionary");
        }
        if (this.t.size() == 0) {
            return 0;
        }
        return 1 + this.t.lastKey();
    }
}

i got an error in this code
public int arraySize() {
            if (this.t == null) {
                throw new IllegalArgumentException("The passed PHP \"array\" is not a sequence but a dictionary");
            }
            if (this.t.size() == 0) {
                return 0;
            }
            return 1 + this.t.lastKey();
        }

error which i got are
operator + undefined for the arguments type(s) int, object
from my lastKey() we call this methods
public K lastKey() {
        return key(getLastEntry());
    }

and here for getLastEntry
final Entry<K,V> getLastEntry() {
        Entry<K,V> p = root;
        if (p != null)
            while (p.right != null)
                p = p.right;
        return p;
    }

i want to know how to fix it ? i have try add after TreeMap like this TreeMap<String,String> i got still error. so i want to know how to fix it
from this call i see this is for return int
protected static final IntegerComparator PHP_ARRAY_KEY_COMPARATOR;

after i change my code as like this  return 1 + (Integer)this.t.lastKey(); this code not get error again... i want to know suggestion from this forum is it ok for this code ?


text:
Q: ServiceStack Ormlite Object column is not populated Using ServiceStack Ormlite 5.12.0.
I have a model looks like the following, saving the object is perfectly fine.
public string DescriptionAlias { get; set; }
    /// <summary>
    /// Applying PLUs (Price Lookup Code)
    /// Default is all
    /// </summary>
    [CustomField("LONGTEXT")]
    public Applying<string> ApplyingPlus { get; set; }
    /// <summary>
    /// Applying User Tags
    /// Default is all
    /// </summary>
    [CustomField("LONGTEXT")]
    public Applying<string> ApplyingUserTags { get; set; }
    /// <summary>
    /// Applying User Groups
    /// Default is all
    /// </summary>
    [CustomField("LONGTEXT")]
    public Applying<int> ApplyingUserGroups { get; set; }

When LoadSelect or Select the object, all Complex object Applying Columns are not populated.


text:
Q: Unpinned messages stay starred I just ran across a bug in chat.  If you are the room owner, you have the ability to pin/unpin messages.  However, recently I ran a test (in my own private chat-room, don't worry! :) ) to see how many messages I could pin and what happens if I ran over the limit.  However, I ran across a bug which we verified in another room.  When you remove the pin from the message, it remains starred, even if the pinner was the poster of the message.

A friend tried the same thing, but with a single message in a chatroom he owns, and it appears that it is a reproducable bug.  Would appreciate some help on it!


text:
Q: After Windows 10 upgrade (from Windows 8 Home), error "The file '' could not be found." when Eclipse is default editor for a file type After Windows 10 upgrade (from Windows 8 Home), I'm getting an error "The file '' could not be found." when trying to open a file by doulble-clicking in File Explorer with default editor set as Eclipse. This is happening once the workspace is loaded.
If Eclipse is closed, double-clicking on the file prompts for workspace first, and then the file loads correctly in Eclipse editor. However after Eclipse is running, the above error is observed.
Steps tried: removed Eclipse and set up again; changed default editor for file types with issue (.java, .jsp), and set to Eclipse again.
This issue did not exist in Windows 8.


text:
Q: How to evaluate only arguments, but leave topmost expression unevaluated? I want to represent expressions mostly in unevaluated form, but being able to evaluate it's subparts.
For example, how to evaluate only arguments, but leave topmost expression unevaluated?
For example, so that
1 + Cos[0]

give
1 + 1

UPDATE
I want Mathematica to act something like follows.
If I write
<something> 1 + Cos[0]

it should respond with
<something> 1 + Cos[0]

i.e. having expression as is, unevaluated
Then if I enter something
<something> 1 + Evaluate[Cos[0]]

it should respond with
<something> 1 + 1

I.e. I want to CONTROL evaluation, not allowing Mathematica to evaluate what it wants. Only what I want.
Imagine gradual scholar math text where expression is converted gradually portion by portion and presented at intermediate stages.
Since I don't know how it can be implemented, I am not describing this with much detail. It can be some combination of holding heads or some global modes turnable on and off.
The goal is not to loose my work done while entering long expressions, which Mathematica tends to throw out by evaluating.
The solution should not be complex like in referred answer, it should be some simple built-in feature.


text:
Q: Is every k-traceable d-regular oriented graph of order 2k traceable? This problem is a special case of the traceability conjecture for oriented graphs.
For more information on this conjecture see the paper: "Progress on the Traceability Conjecture for Oriented Graphs" at http://www.dmtcs.org/dmtcs-ojs/index.php/dmtcs/article/view/965  or "Traceability of k-traceable oriented graphs" at http://www.sciencedirect.com/science/article/pii/S0012365X09006438.
Definitions
A graph is oriented if each edge has only one direction. A graph is traceable if it contains a Hamiltonian path. A graph is $k$-traceable if each of its subgraphs of order $k$ is traceable. An oriented graph is d-regular if each vertex has $d$ out-neighbours and $d$ in-neighbours.
Notes
Note that for a graph of order $2k$ to be $k$-traceable, we must have $2d \geq k+1 $, otherwise we can select $k$ non-traceable vertices by selecting any vertex $v$ and $k-1$ of its non-neighbours.
It is for example, easy to show that a $k$-traceable $d$-regular graph $G$ of order $2k-1$ is traceable: Select any vertex $v$. Partition the remaining vertices in two sets $I$ and $O$ with $k-1$ vertices each such that $I$ contains only in-neighbours and non-neighbours of $v$, and $O$ contains only out-neighbours and non-neighbours of $v$. Then the subgraph with vertices $I \cup v$ has a Hamilton path ending in $v$, and the subgraph with vertices $O \cup v$ has a Hamilton path starting with $v$, making $G$ traceable.
I am sure there must be a clever trick somewhere to show the special case for order $2k$ is also true.


text:
Q: How to search files by label As title, I'd like to list all the files with a given label under a directory. Which clearcase command can help me to do that ?

A: There is also a graphical way to find objects with a certain label called Report Builder (also known in ClearCase Explorer as Report Wizard).  In Report Builder you can navigate to Elements/Labels which has the "Elements with Labels" and "Versions with Labels" reports. After the report runs you have the option to save the results as HTML, XML, or CSV.

A: cleartool find is a good start.
You can execute those anywhere within your (snapshot or dynamic) view

To generate the list of those elements which contain a version with a predetermined label (REL1) attached, use the following syntax of the cleartool find command:

UNIX and Linux:
% cleartool find -all -element '{lbtype_sub(REL1)}' -print

Windows:
cleartool find -all -element "{lbtype_sub(REL1)}" -print


text:
Q: Decoding nested objects in JSON I'm trying to fetch some data using YouTube JSON API, JSON looks like this:
{
  "kind": "youtube#channelListResponse",
  "etag": "AVEF8yG4pQMKfzZjMyy1rfVtFXA",
  "pageInfo": {
    "resultsPerPage": 1
  },
  "items": [
    {
      "kind": "youtube#channel",
      "etag": "LpEHq7VFVl1gDbt97Gf4ObyFn0U",
      "id": "UCBJycsmduvYEL83R_U4JriQ",
      "statistics": {
        "viewCount": "2084223845",
        "commentCount": "0",
        "subscriberCount": "12100000",
        "hiddenSubscriberCount": false,
        "videoCount": "1272"
      }
    }
  ]
}

And here is my code:
import Foundation
struct StatResponse: Decodable {
    let items: Items
}
struct Items: Decodable {
    var statistics: Stats
}
struct Stats: Decodable {
    let subscriberCount: Double
}
enum APIError: Error {
    case wrongURL
    case decodingError
    case noData
}
extension URL {
    static func url() -> URL? {
        guard let url = URL(string: "https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCBJycsmduvYEL83R_U4JriQ&key=API_KEY") else {
            return nil
        }
        return url
    }
}
class StatService {
    func getStats(completion: @escaping (Result<Items?,APIError>) -> Void) {
        guard let url =  URL.url() else {
             return completion(.failure(.wrongURL))
        }
          URLSession.shared.dataTask(with: url) {
            data, response, error in
            guard let data = data, error == nil else {
                return completion(.failure(.noData))
            }
            let statResponse = try? JSONDecoder().decode(StatResponse.self, from: data)
            if let statResponse = statResponse {
                completion(.success(statResponse.items))
                } else {
                    return completion(.failure(.decodingError))
            }
        }.resume()
    }
}
class StatsViewModel: ObservableObject {
    @Published private var items: Items?
    var subCount: Double {
        guard let subscriberCount = items?.statistics.subscriberCount else {
            return 0
        }
        return subscriberCount
    }
    func fetchStats() {
        StatService().getStats {
            result in switch result {
            case .success(let Items):
                DispatchQueue.main.async {
                    self.items = Items
                }
            case .failure(_ ):
                print("fail")
            }
        }
    }
}

I have no idea what is going wrong, it gives 0 as the result. I tried various things like self.items?.statistics = Items.statistics instead of self.items = Items because I'm trying to get the data I'm trying to fetch is under statistics but it also didn't work and got an error saying "Value of optional type 'Stats?' must be unwrapped to a value of type 'Stats'" and I don't know what to do, I can fetch non-nested objects pretty easily in Swift but I can't nested ones. I'm kind of a beginner to both Swift and programming in general so if that's a stupid question sorry for taking your time.

A: You have an error on your model classes, the items property is an array, and you are trying to decode it as an object, change StatResponse to:
struct StatResponse: Decodable {
    let items: [Items]
}

Also change the subscriberCount to String on the Stats struct:
struct Stats: Decodable {
    let subscriberCount: String
}

Then you will have to change the way you are accessing the data, because now you're accessing an array. You can use the first property of an array which will return the first element of and array like this:
if let item = statResponse.items.first {
    completion(.success(item))
} else {
    return completion(.failure(.decodingError))
}


text:
Q: Get the dropdown list value into mvc controller to View thru Ajax call as new in MVC, I am trying to get the dropdown list value into mvc controller thru Ajax call here is the Views code:

@using (Html.BeginForm("Details", "Employee", FormMethod.Get, new { enctype = "multipart/form-data", id="myForm"}))
{
    @Html.DropDownList("SeTime", new List<SelectListItem>
    {
        new SelectListItem{ Text="1 Min", Value = "60" },
        new SelectListItem{ Text="2 Min", Value = "120" },
        new SelectListItem{ Text="3 Min", Value = "180" },
    }, "Select Time")
    <input type="submit" value="Set Time "  />
}

@Model.SetTime
 //to show the selected value thru controller to view

Here is Model:
        public class Time
    {
        public string SetTime { get; set; }
    }
Here is the controller:
public ActionResult Details(string selectedtTime)
    {
        Time time = new Time();
        if (selectedtTime == null)
        {
            time.SetTime = "Hello";
        }
        else
        {
            time.SetTime = selectedtTime;
        }
        return View(time);
    }
}

I am getting the right value in alert box but not in the controller (getting 'Hello' for each selection). I have also tried with POST method but didn't work. May I get some advice how to get the selected dropdown value thru controller

A: Here is how you do it.  Please let me know if you need anything more.
View:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index59</title>

    @Html.DropDownList("SeTime", new List<SelectListItem>
    {
        new SelectListItem{ Text="1 Min", Value = "60" },
        new SelectListItem{ Text="2 Min", Value = "120" },
        new SelectListItem{ Text="3 Min", Value = "180" },
    }, "Select Time")
    @*ajax is a button click not a submit*@
    <input type="button" value="Set Time" id="btn" />

Controller:
public class HomeController : Controller
{
    [HttpPost]
    public ActionResult PostTime(string selectedtTime )
    {
        //put a checkpoint here and interrogate selectedTime and work with it
        return Json(new
        {
            aValue = "aValueRet"
        }
               , @"application/json");
    }

A: You can use url: '@Url.Action("Details","Home")' + "/" + select to send select parameter to controller. I added .Netfiddle. It works here
public ActionResult Details(string selectedtTime)
{
    var time = selectedtTime;
    return Json(new { data = time}, JsonRequestBehavior.AllowGet);
}

$(function () {
    $('#myForm').submit(function () {
      var select = $("#SeTime option:selected").val();
      $.ajax({
        url: '@Url.Action("Details","Home")' + "/" + select,
        type: this.method,
        data: {'selectedtTime' : select},
        success: function(result) {
          alert("Selected value: " + result.data);
        }
      });
      return false;
    });
});

A: Change the following:
var select = $("#SeTime option:selected").val();

to:
var select = $("#SetTime option:selected").val();

Also change:
@Html.DropDownList("SeTime", new List<SelectListItem>

to:
@Html.DropDownList("SetTime", new List<SelectListItem>


text:
Q: How to split querySelectorAll result? I have been able to querySelectorAll the correct className, a tag, and href. I am trying to split my result so I only have the SKU #.
HTML

   Product 1

   Product 2

JS
    function GetCartProducts() {

    var URL = document.querySelectorAll(".mini-cart-product-name a[href*='/product/']");
     for (var i = 0; i < URL.length; i++) {

    console.log(URL.item(i));

    Product 1

   Product 2

    // Split result/href to only have the SKU # //
    // Push to array
    // Desired result
    // var array ["12345","67890"]
     }

     }

A: You can use a simple regular expression to match the SKU #

function GetCartProducts() {
    var SKUs = [];
    var URL = document.querySelectorAll(".mini-cart-product-name a[href*='/product/']");
    for (var i = 0; i < URL.length; i++) {
        SKUs[i] = URL[i].href.match(/\/(\d+)\.html/)[1];
    }
console.log(SKUs);
}
GetCartProducts();

   Product 1

   Product 2

A:  //Since you revised your criteria, you can do this with a simple string substring and replace
const skuNum = URL.item(i).substring(URL.item(i).lastIndexOf('/') + 1).replace('.html', '');

//Don't use this if you have something other than numbers in the capture string, see above
//Declare your regular expression, this could be declared before your loop
const reg = /(\d+)\.html/g;
//These next two go inside your loop
//Get the match collection of captures from your regular expression
const matches = reg.exec(URL.item(i));
//Get your sku # from the match colletion
const skuNum = matches[1];

A: Both of the answer's mentioned before are correct, but such approach seems painfull.
If you can modify your html code i would suggest you to pass these SKU's as data attribute.

    Product 1

   Product 2

Then you need to modify your selector a bit so it doesn't 'cut' these attributes.
function GetCartProducts() {
    var SKUs = [];
    var URL = document.querySelectorAll(".mini-cart-product-name a");
    for (var i = 0; i < URL.length; i++) {
        SKUs[i] = URL[i].dataset.sku;
    }
    console.log(SKUs);
}
GetCartProducts();

A: The function can be a single line like this.

function GetCartProducts() {
  return Array.from(document.querySelectorAll(".mini-cart-product-name a[href*='/product/']"))
    .map(el => el.href.replace(/^.+product\/(.+?)\.html.*?/i, '$1'))
}
console.log(GetCartProducts());

  Product 1

  Product 2

Some explanations of /^.+product\/(.+?)\.html/i.
/whatever/ is Regular Expression
^ start of input
. any character + repeated one or more times
\. dot itself
(.+?) capturing pattern. +? one or more non-greedy
$1 - captured text.


text:
Q: right-hand-side of clause doesn't agree with function result type [literal] I am trying to compute binomial coefficients using Dynamic Programming. I keep getting this error
fun binomial(m:int, n:int, DP) =
if n = m orelse n = 0 then
    Array2.update(DP, m, n, 1)
else if Array2.sub(DP, m, n) = ~1 then (
    if Array2.sub(DP, m-1, n) = ~1 then
        Array2.update(DP, m-1, n, binomial(m-1, n, DP))
    else
        Array2.update(DP, m-1, n, Array2.sub(DP, m-1, n));
    if Array2.sub(DP, m-1, n-1) = ~1 then
        Array2.update(DP, m-1, n-1, binomial(m-1, n-1, DP))
    else
        Array2.update(DP, m-1, n-1, Array2.sub(DP, m-1, n-1));
    let
        val k = Array2.sub(DP, m-1, n) + Array2.sub(DP, m-1, n-1);
    in
        Array2.update(DP, m, n, k)
    end
)
else
    Array2.update(DP, m, n, Array2.sub(DP, m, n));
Array2.sub(DP, m, n)

I am don't understand what this error is trying to say.
6.5-25.48 Error: right-hand-side of clause doesn't agree with function result type     [literal]
expression:  unit
result type:  int
in declaration:
binomial =
  (fn (<pat> : int,<pat> : int,DP) =>
        if <exp> orelse <exp>
        then Array2.update <exp>
        else if <exp> then <exp> else <exp>)

Can anyone help me?

A: Your function binomial returns the result of Array2.update, which is a unit. But you're passing this return value in to Array2.update as the last argument, which is expecting an int.
EDIT: Oh, now I see... Your only problem is that the last line (Array2.sub(DP,m,n)) isn't part of your function - if you want to build a list of expressions, you need to surround it with brackets. So instead of
fun binomial (m,n,DP) = <update logic>; Array2.sub(DP,m,n)

you want
fun binomial (m,n,DP) = (<update logic>; Array2.sub(DP,m,n))


text:
Q: How to draw stroke on custom shape on android canvas I am trying to add a stroke to a custom shape I have added.
Here is the code
    private void drawBackground(Canvas canvas) {

          float height = getHeight();
          float width = getWidth();

          canvas.drawRoundRect(0, 0, width, height, 5, 5, canvasPaint);
          canvas.drawRoundRect(0, 0, getTextWidth(), getHeight(), 5, 5, canvasStrokePaint);//to draw black stroke

          canvas.drawText(name, width / 2 - getTextWidth() / 2, getBitmapHeight() + 20, textPaint);
          Path path = new Path();

          path.moveTo((width / 3), height);
          path.lineTo((width / 2), (height + height / 3));
          path.lineTo((width - width / 3), height);
          path.lineTo((width / 3), height);

          path.close();

          canvas.drawPath(path, canvasPaint);
          canvas.drawPath(path, canvasStrokePaint);//to draw black stroke
}

The output

Here you can see there is a closed edge for rectangle and triangle.
But the stroke should be outside of the shape.

Requirement

Thanks in advance

A: You can try to draw this particular shape in black, and then you can write on the top of it another shape (a bit smaller) in green color. The result should be as you would expected.

A: Try this code:
private void drawStroke(Canvas canvas) {
    int rectangleWidth = 20;
    int rectangleHeight = 10;
    float height = getHeight();
    float width = getWidth();

    // start
    canvasStrokePath.reset();
    canvasStrokePath.moveTo(0, 5);

    // first arc
    arcRect.set(0, 0, 10, 10);
    canvasStrokePath.arcTo(arcRect, 180, -90, true);

    // going right
    canvasStrokePath.lineTo(width - 10, 0);

    // second arc
    arcRect.set(width - 10, 0, width, 10);
    canvasStrokePath.arcTo(arcRect, 90, -90, true);

    // going bottom
    canvasStrokePath.lineTo(width, height - rectangleHeight - 10);

    // third arc
    arcRect.set(width - 10, height - rectangleHeight - 10, width, height - rectangleHeight);
    canvasStrokePath.arcTo(arcRect, 0, -90, true);

    // going to rectangle (right edge)
    canvasStrokePath.lineTo(width / 2 + rectangleWidth / 2, height - rectangleHeight);

    // going to rectangle center
    canvasStrokePath.lineTo(width / 2, height);

    // going to rectangle (left edge)
    canvasStrokePath.lineTo(width / 2 - rectangleWidth / 2, height - rectangleHeight);

    // going to left
    canvasStrokePath.lineTo(5, height - rectangleHeight);

    // fourth arc
    arcRect.set(0, height - rectangleHeight - 10, 10, height - rectangleHeight);
    canvasStrokePath.arcTo(arcRect, 270, -90, true);

    // going to top
    canvasStrokePath.lineTo(0, 5);

    canvasStrokePath.close();

    canvas.drawPath(canvasStrokePath, canvasStrokePaint);
}

I didn't build it, I hope there will be no mistakes


text:
Q: r - dedupe the rows with value in dataframe How to subset only the rows with values in a particular column among the duplicates based on another column.
Example:
df

A B  C D
1 NA 8 7
1 5  8 9
2 6  5 8
2 NA 5 6
3 NA  8 5

So in the above dataset, first 4 rows are duplicate based on column A and C, so among them, I want to choose only the rows which has value in column B.
Desired output,
A B C D
1 5 8 9
2 6 5 8
3 NA 8 5

Thanks.

A: Duplicates back or forwards and not missing on B; or not a duplicate:
anydup <- duplicated(df[c("A","C")]) | duplicated(df[c("A","C")], fromLast=TRUE)
df[(anydup & (!is.na(df$B))) | (!anydup),]

#  A  B C D
#2 1  5 8 9
#3 2  6 5 8
#5 3 NA 8 5

Or use ave to check the length per group as per @HubertL's dplyr answer:
df[!is.na(df$B) | ave(df$B, df[c("A","C")], FUN=length)==1,]
#  A  B C D
#2 1  5 8 9
#3 2  6 5 8
#5 3 NA 8 5

A: Using dplyr:
df <- read.table(text="A B  C D
1 NA 8 7
1 5  8 9
2 6  5 8
2 NA 5 6
3 NA  8 5", header=T)

df %>%
  group_by(A,C) %>%
  filter(n()==1|!is.na(B))

      A     B     C     D
  <int> <int> <int> <int>
1     1     5     8     9
2     2     6     5     8
3     3    NA     8     5

A: Here is one option with data.table
library(data.table)
setDT(df)[df[, .I[.N==1 | complete.cases(B)] , .(A, C)]$V1]
#    A  B C D
#1: 1  5 8 9
#2: 2  6 5 8
#3: 3 NA 8 5


text:
Q: Insert missing values in categorized style In QGIS Bonn, when styling my layer to use the categorize option, I want to have all values within a range, for instance, 0 to 50000.
I am using the data from a CSV that has information about population density and I am using a grayscale to categorize it.
But the values are so different that 0 is white, 2000 is medium gray and 50000 is black.
This does not reflect the true differences between population per area and I do not want to add the missing integer values by hand, how do I do it?

A: If you take 'graduated' instead of 'categorized', you can choose the number of classes.  Eg 5 classes gives you
0-10000
10000-20000
20000-30000
etc.

A: A way to overcome this kind of problem is to use a non-linear reclassification of the data (for exemple using the square root of the value for representation, or log or exp or... depending of the actual distribution of the data).
By reclassifying you could differentiate more at one end of the scale (for exemple square root will let you discriminate between low value by lowering more the high value than the low one)


text:
Q: API for resizing images in laravel 5.4 i am working on a marketing website with laravel 5.4
i need to upload and load lots of images on the website, if i load the original image every time, it will going slow. so i need your suggestions
*

*

*should i store the image with two quality? (original and
resized)

*store the original images, resize them when they loaded
on the screen? (need an API)

share some ideas and the solutions please!
if you have such an API, please share!

A: Laravel does not have a default resize of image. But most laravel developers use 'Image intervention' in handling the image. (Easy to use)
To install (Image intervention):
STEP 1 Run
 composer require intervention/image

STEP 2 On your config/app.php:
In the $providers array, add the following:
  Intervention\Image\ImageServiceProvider::class

In the $aliases array,add the following:
 'Image' => Intervention\Image\Facades\Image::class

If you have problems your GD librabry is missing, intall it
 PHP5: sudo apt-get install php5-gd
 PHP7: sudo apt-get install php7.0-gd

~~ To use on your controller ~~
STEP 3 On top of your controller
use Intervention\Image\ImageManagerStatic as Image;

STEP 4 On your method (there are several ways but this will give you an idea)
 if($request->hasFile('image')) {

   $image       = $request->file('image');
   $filename    = $image->getClientOriginalName();

   $image_resize = Image::make($image->getRealPath());
   $image_resize->resize(300, 300);
   $image_resize->save(public_path('images/ServiceImages/'
  .$filename));

}


text:
Q: How to empty cache in Qt QMake: No such slot, repeated errors So basically, I'm writing a Qt app. It used to work fine, but ever since I reconfigured some of the file names (specifically, a long time ago, I had files called mainwindow.h and .cpp. I renamed them net.h and .cpp, respectively, and recently changed back to mainwindow.h and .cpp), it fails with several errors (at runtime):
Object::connect: No such slot QWidget::slotName()
Object::disconnect: No such signal QWidget::iconSizeChanged(QSize)
Object::disconnect: No such signal QWidget::toolButtonStyleChanged(Qt::ToolButtonStyle)
Object::connect: No such signal QWidget::iconSizeChanged(QSize)
Object::connect: No such signal QWidget::toolButtonStyleChanged(Qt::ToolButtonStyle)

The only slot I have registered within my class is the first one, slotName. I'm not sure why it's being listed as a member of QWidget instead of my class (which subclasses QWidget). I know I have it declared right, because I found it inside the moc_mainwindow.cpp file. And yes, I have Q_OBJECT in my class definition.
Another error also occurs, once per second while running:
QWidget::metric: Invalid metric command
QPainter::begin: Paint device returned engine == 0, type: 143256176

Like I said, all of this used to work perfectly, which is why I'm not going to post huge walls of code unless asked. I'm thinking it's more of a cache issue with QMake. I've tried deleting all the moc files, deleting the project file, emptying the project file and generating a new, empty Makefile, etc. Anyone have any ideas?

A: You should not develop code without version control, period. Leverage your version control system to clean up your working copy, or check out to a new location and recompile there. Then you won't be blaming who knows what.
In absence of version control, copy your project manually, file-by-file, to a new location, commit that to a new version control repository of your choice (a local one!) and compile there.
Note that Qt Creator has been defaulting to shadow builds -- i.e. builds that are not within your source folders. Wiping a shadow build is trivial: go one directory up above your source folder, and look for a folder with long name, starting with the name of your project. Wipe that and you're guaranteed that there is no "caches" of any sort.
Also note that QMake has no caches at all. It re-reads all files given in its input (.pro and its includes) and recreates all the Makefiles from scratch. You can run qmake && make clean to clean up, but this won't take care of files from a differently configured project. Alas, such files should not interfere anyway.


text:
Q: Calling a variables function on click I am trying to trigger an items effect in an adventure game I am building and I can't seem to figure out how to do it. Basically when clicked I would like whichever item it is to run their effect function. I'm getting quite confused.
    function showItems() {
      for (var i = 0; i < items.length; i++) {
        playerUi.innerHTML += '
' + items[i].name + '

' + items[i].description + '
Value: ' +
    items[i].price + '

';
      }
    }

    // Shows the inventory interface.
    $('#inv-btn').on('click', function() {
      playerUi.innerHTML = '
Your Inventory:
';
      showItems();
      playerUi.innerHTML += '

Gold: ' +
    player.gold + '
';
    });

The below is the code I have for my items at the minute:
    // I  T  E  M  S
    function invItem(name, type, desc, price, eff) {
      this.name = name;
      this.type = type;
      this.description = desc;
      this.price = price;
      this.effect = eff;
    };

    var weakPotion = new invItem('Weak Potion', 'Consumable', 'A weak health
    potion.', 10, healSelf(20));
    var brewersPotion = new invItem('Brewers Potion', 'Consumable', 'A
    standard health potion.', 23, healSelf(45));

    function healSelf(amt) {
      if (player.currentHealth < player.maxHealth) {
        player.currentHealth += amt;
        if (player.currentHealth >= player.maxHealth) {
          player.currentHealth = player.maxHealth;
        }
      }
    }

To see what I currently have so far on this click here.
Below is my player object.
    // Create our player object.
    var player = new Object();
    player.gold = 0;
    player.level = 1;
    player.strength = 5;
    player.intellect = 5;
    player.endurance = 5;
    player.agility = 5;
    player.currentExp = 0;
    player.reqExp = 100;
    player.skillPoints = 0;
    player.attPoints = 2;
    player.maxHealth = 0;
    player.currentHealth = 0;
    player.maxMana = 0;
    player.currentMana = 0;

A: Lets start at the beginning here. This line
var weakPotion
     = new invItem('Weak Potion', 'Consumable', 'A weak health potion.', 10, healSelf(20));

Already does not do what you think it does! It will immediately execute the function - which is not what you're trying to do. Instead you should be storing a reference to the function to execute. Fix it by returning a new function to be called later
function healSelf(amt) {
  return function(){
    if (player.currentHealth < player.maxHealth) {
      player.currentHealth += amt;
      if (player.currentHealth >= player.maxHealth) {
        player.currentHealth = player.maxHealth;
      }
    }
  }
}

Next, when you pass a reference to a function, to later execute that function use parentheses:
onclick="items[i].effect()"

But this still wont work - items[i] only exists in the loop - not when the page is running. One way to solve this is to not attach an onclick directly (especially when using jQuery) and instead attach a click handler to those links using index() to find the right item
function showItems() {
  for (var i = 0; i < items.length; i++) {
    playerUi.innerHTML += '
' + items[i].name + '

' + items[i].description + '
Value: ' + items[i].price + '

';
  }
}

and elsewhere
$(document).on('click','.item-name',function(){
   var index = $(this).index();
   items[index].effect();
});

A: Items should have unique IDs so you can easily access them, remove from item list etc. So, ended up with something like that.

let playerUi = $('#inv');

let player = {
  currentHealth: 100,
  maxHealth: 100
};

let items = [];

function showItems() {
  for (var i = 0; i < items.length; i++) {

    let item = '
' + items[i].name + '
Description: ' + items[i].description + '
';

    playerUi.append(item);

  }
}

function makeid() {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 5; i++) // Change 5 to higher number for more unique IDs
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

function invItem(name, type, desc, price, eff) {
  this.id = makeid();
  this.name = name;
  this.type = type;
  this.description = desc;
  this.price = price;
  this.effect = eff;
};

function healSelf(amt) {
  return function() {
    console.log("Before heal:" + player.currentHealth);
    player.currentHealth = Math.min(player.currentHealth+amt, player.maxHealth);
    console.log("After heal:" + player.currentHealth);
  }
}

items[0] = new invItem('Weak Potion', 'Consumable', 'A weak health potion.', 10, healSelf(20));
items[1] = new invItem('Brewers Potion', 'Consumable', 'A standard health potion.', 23, healSelf(45));
items[2] = new invItem('Strongest Potion', 'Consumable', 'This potion is too strong.', 100, healSelf(80));

showItems();

$('li').on('click', function(e) {

  let id = e.target.dataset.itemid;
  let item = $.grep(items, function(e) {return e.id == id;})[0];
  console.log("Using: " + item.name);
  player.currentHealth -= 40;
  item.effect();

});