text:
Q: How to show visitors' country automatically in an HTML dropdown? I am a digital marketer and newbie to programming. I just want to automatically display the website visitor's country as the selected item in an html dropdown as per their ip address. I tried this code but it fails to show the country as per my concern. Please help me. Here's the url where I want to show the result : https://onlinecharterschool.org/inquire-now/
DEMO: https://coliff.github.io/geoip-db-country-select/
Here's the code which I have used.

COUNTRY*

<select name="country" id="country" class="form-control" selected="selected" autocomplete="country-name">
<option value="" disabled="" selected="">Please Select</option>
<option value="AF">Afghanistan</option><option value="AX">Åland Islands</option><option value="AL">Albania</option><option value="DZ">Algeria</option><option value="AS">American Samoa</option><option value="AD">Andorra</option><option value="AO">Angola</option><option value="AI">Anguilla</option><option value="AQ">Antarctica</option><option value="AG">Antigua & Barbuda</option><option value="AR">Argentina</option><option value="AM">Armenia</option><option value="AW">Aruba</option><option value="AC">Ascension Island</option><option value="AU">Australia</option><option value="AT">Austria</option><option value="AZ">Azerbaijan</option><option value="BS">Bahamas</option><option value="BH">Bahrain</option><option value="BD">Bangladesh</option><option value="BB">Barbados</option><option value="BY">Belarus</option><option value="BE">Belgium</option><option value="BZ">Belize</option><option value="BJ">Benin</option><option value="BM">Bermuda</option><option value="BT">Bhutan</option><option value="BO">Bolivia</option><option value="BA">Bosnia & Herzegovina</option><option value="BW">Botswana</option><option value="BR">Brazil</option><option value="IO">British Indian Ocean Territory</option><option value="VG">British Virgin Islands</option><option value="BN">Brunei</option><option value="BG">Bulgaria</option><option value="BF">Burkina Faso</option><option value="BI">Burundi</option><option value="KH">Cambodia</option><option value="CM">Cameroon</option><option value="CA">Canada</option><option value="IC">Canary Islands</option><option value="CV">Cape Verde</option><option value="BQ">Caribbean Netherlands</option><option value="KY">Cayman Islands</option><option value="CF">Central African Republic</option><option value="EA">Ceuta & Melilla</option><option value="TD">Chad</option><option value="CL">Chile</option><option value="CN">China</option><option value="CX">Christmas Island</option><option value="CC">Cocos (Keeling) Islands</option><option value="CO">Colombia</option><option value="KM">Comoros</option><option value="CG">Congo - Brazzaville</option><option value="CD">Congo - Kinshasa</option><option value="CK">Cook Islands</option><option value="CR">Costa Rica</option><option value="CI">Côte d'Ivoire</option><option value="HR">Croatia</option><option value="CU">Cuba</option><option value="CW">Curaçao</option><option value="CY">Cyprus</option><option value="CZ">Czech Republic</option><option value="DK">Denmark</option><option value="DG">Diego Garcia</option><option value="DJ">Djibouti</option><option value="DM">Dominica</option><option value="DO">Dominican Republic</option><option value="EC">Ecuador</option><option value="EG">Egypt</option><option value="SV">El Salvador</option><option value="GQ">Equatorial Guinea</option><option value="ER">Eritrea</option><option value="EE">Estonia</option><option value="ET">Ethiopia</option><option value="FK">Falkland Islands</option><option value="FO">Faroe Islands</option><option value="FJ">Fiji</option><option value="FI">Finland</option><option value="FR">France</option><option value="GF">French Guiana</option><option value="PF">French Polynesia</option><option value="TF">French Southern Territories</option><option value="GA">Gabon</option><option value="GM">Gambia</option><option value="GE">Georgia</option><option value="DE">Germany</option><option value="GH">Ghana</option><option value="GI">Gibraltar</option><option value="GR">Greece</option><option value="GL">Greenland</option><option value="GD">Grenada</option><option value="GP">Guadeloupe</option><option value="GU">Guam</option><option value="GT">Guatemala</option><option value="GG">Guernsey</option><option value="GN">Guinea</option><option value="GW">Guinea-Bissau</option><option value="GY">Guyana</option><option value="HT">Haiti</option><option value="HN">Honduras</option><option value="HK">Hong Kong SAR China</option><option value="HU">Hungary</option><option value="IS">Iceland</option><option value="IN">India</option><option value="ID">Indonesia</option><option value="IR">Iran</option><option value="IQ">Iraq</option><option value="IE">Ireland</option><option value="IM">Isle of Man</option><option value="IL">Israel</option><option value="IT">Italy</option><option value="JM">Jamaica</option><option value="JP">Japan</option><option value="JE">Jersey</option><option value="JO">Jordan</option><option value="KZ">Kazakhstan</option><option value="KE">Kenya</option><option value="KI">Kiribati</option><option value="XK">Kosovo</option><option value="KW">Kuwait</option><option value="KG">Kyrgyzstan</option><option value="LA">Laos</option><option value="LV">Latvia</option><option value="LB">Lebanon</option><option value="LS">Lesotho</option><option value="LR">Liberia</option><option value="LY">Libya</option><option value="LI">Liechtenstein</option><option value="LT">Lithuania</option><option value="LU">Luxembourg</option><option value="MO">Macau SAR China</option><option value="MK">Macedonia</option><option value="MG">Madagascar</option><option value="MW">Malawi</option><option value="MY">Malaysia</option><option value="MV">Maldives</option><option value="ML">Mali</option><option value="MT">Malta</option><option value="MH">Marshall Islands</option><option value="MQ">Martinique</option><option value="MR">Mauritania</option><option value="MU">Mauritius</option><option value="YT">Mayotte</option><option value="MX">Mexico</option><option value="FM">Micronesia</option><option value="MD">Moldova</option><option value="MC">Monaco</option><option value="MN">Mongolia</option><option value="ME">Montenegro</option><option value="MS">Montserrat</option><option value="MA">Morocco</option><option value="MZ">Mozambique</option><option value="MM">Myanmar (Burma)</option><option value="NA">Namibia</option><option value="NR">Nauru</option><option value="NP">Nepal</option><option value="NL">Netherlands</option><option value="NC">New Caledonia</option><option value="NZ">New Zealand</option><option value="NI">Nicaragua</option><option value="NE">Niger</option><option value="NG">Nigeria</option><option value="NU">Niue</option><option value="NF">Norfolk Island</option><option value="KP">North Korea</option><option value="MP">Northern Mariana Islands</option><option value="NO">Norway</option><option value="OM">Oman</option><option value="PK">Pakistan</option><option value="PW">Palau</option><option value="PS">Palestinian Territories</option><option value="PA">Panama</option><option value="PG">Papua New Guinea</option><option value="PY">Paraguay</option><option value="PE">Peru</option><option value="PH">Philippines</option><option value="PN">Pitcairn Islands</option><option value="PL">Poland</option><option value="PT">Portugal</option><option value="PR">Puerto Rico</option><option value="QA">Qatar</option><option value="RE">Réunion</option><option value="RO">Romania</option><option value="RU">Russia</option><option value="RW">Rwanda</option><option value="WS">Samoa</option><option value="SM">San Marino</option><option value="ST">São Tomé & Príncipe</option><option value="SA">Saudi Arabia</option><option value="SN">Senegal</option><option value="RS">Serbia</option><option value="SC">Seychelles</option><option value="SL">Sierra Leone</option><option value="SG">Singapore</option><option value="SX">Sint Maarten</option><option value="SK">Slovakia</option><option value="SI">Slovenia</option><option value="SB">Solomon Islands</option><option value="SO">Somalia</option><option value="ZA">South Africa</option><option value="GS">South Georgia & South Sandwich Islands</option><option value="KR">South Korea</option><option value="SS">South Sudan</option><option value="ES">Spain</option><option value="LK">Sri Lanka</option><option value="BL">St. Barthélemy</option><option value="SH">St. Helena</option><option value="KN">St. Kitts & Nevis</option><option value="LC">St. Lucia</option><option value="MF">St. Martin</option><option value="PM">St. Pierre & Miquelon</option><option value="VC">St. Vincent & Grenadines</option><option value="SD">Sudan</option><option value="SR">Suriname</option><option value="SJ">Svalbard & Jan Mayen</option><option value="SZ">Swaziland</option><option value="SE">Sweden</option><option value="CH">Switzerland</option><option value="SY">Syria</option><option value="TW">Taiwan</option><option value="TJ">Tajikistan</option><option value="TZ">Tanzania</option><option value="TH">Thailand</option><option value="TL">Timor-Leste</option><option value="TG">Togo</option><option value="TK">Tokelau</option><option value="TO">Tonga</option><option value="TT">Trinidad & Tobago</option><option value="TA">Tristan da Cunha</option><option value="TN">Tunisia</option><option value="TR">Turkey</option><option value="TM">Turkmenistan</option><option value="TC">Turks & Caicos Islands</option><option value="TV">Tuvalu</option><option value="UM">U.S. Outlying Islands</option><option value="VI">U.S. Virgin Islands</option><option value="UG">Uganda</option><option value="UA">Ukraine</option><option value="AE">United Arab Emirates</option><option value="GB">United Kingdom</option><option value="US">United States</option><option value="UY">Uruguay</option><option value="UZ">Uzbekistan</option><option value="VU">Vanuatu</option><option value="VA">Vatican City</option><option value="VE">Venezuela</option><option value="VN">Vietnam</option><option value="WF">Wallis & Futuna</option><option value="EH">Western Sahara</option><option value="YE">Yemen</option><option value="ZM">Zambia</option><option value="ZW">Zimbabwe</option
</select>

A: Use location.country_code instead of location.country_name in the AJAX response handler.
When using JavaScript to manipulate a HTML select tag, the value attribute, such as "AF", "AX" and "AL", is used for referencing, and not the inner HTML, such as "Afghanistan".
...
$.ajax({
    url: "https://geoip-db.com/jsonp",
        jsonpCallback: "callback",
        dataType: "jsonp",
        success: function( location ) {
            $('#country').val(location.country_code).attr('selected',true);
            populateStates("country", "state");
    }
});
...


text:
Q: Remote Desktop won't maximize I use a laptop and I am docking and undocking frequently.  Often when I connect to another machine using remote desktop, the screen size gets messed up when I dock again.  By "messed up" I mean that it stays the size of my lap top screen (wide screen ratio).  Clicking maximize will not get it to go full screen.
Any ideas (other than a reboot) how I can reset this?

A: The problem is that the RDP-client remembers the resolution of your last connection.
This can be remedied by adjusting the resolution in the RDP-connection dialog to "Full Screen"

Options >> Display > Remote Desktop Size: Full Screen (to the right)

Another possibility is to create a desktop shortcut for each of your frequently used resolutions. This can be done by making a shortcut to RDP and adding the following flags:

/w:[width] and /h:[height]

Examples of shortcuts would then be:

Docked: %SystemRoot%\system32\mstsc.exe /w:1600 /h:1200
Laptop: %SystemRoot%\system32\mstsc.exe /w:1920 /h:1200

A: Try KB2582172 hotfix
Maximizing will not cause it to go into full screen mode again due to a bug.  However, Microsoft released a hotfix.

A: Try hotkey
In Windows 7, clicking maximize does maximize the window, but it doesn't go full screen.
While in a remote desktop connection session, try Ctrl-Alt-Break.  That should force the RDC window to go full screen.
In case the BREAK key isn't available, try one of these key combinations:

*

*CTRL+ALT+PAUSE

*CTRL+ALT+PRTSCN

*CTRL+ALT+FN+SCRLK
Reference: Remote Desktop Services Shortcut Keys

A: I have seen this problem before.  The easiest way to fix this is to alter the display resolution from the display applet in control panel.  Set the screen to the right resolution manually and your problem should be fixed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compare 2 sets of different date which contains 2 different sets of data? I have 2 sets of Date, their 1st and last dates are the same respectively but their dates within might not be the same to each other. Both DateA and DateB contain different values on their each date, which are arrays A and B.
DateA=    '2016-01-01'
          '2016-01-02'
          '2016-01-04'
          '2016-01-05'
          '2016-01-06'
          '2016-01-07'
          '2016-01-08'
          '2016-01-09'
          '2016-01-10'
          '2016-01-12'
          '2016-01-13'
          '2016-01-14'
          '2016-01-16'
          '2016-01-17'
          '2016-01-18'
          '2016-01-19'
          '2016-01-20'

DateB=    '2016-01-01'
          '2016-01-02'
          '2016-01-03'
          '2016-01-04'
          '2016-01-05'
          '2016-01-09'
          '2016-01-10'
          '2016-01-11'
          '2016-01-12'
          '2016-01-13'
          '2016-01-15'
          '2016-01-16'
          '2016-01-17'
          '2016-01-19'
          '2016-01-20'

A = [5, 2, 3, 4, 6, 1, 7, 9, 3, 6, 1, 7, 9, 2, 1, 4, 6]

B = [4, 2, 7, 1, 8, 4, 9, 5, 3, 9, 3, 6, 7, 2, 9]

I have converted the dates into datenumber,ie
datenumberA=    736330
                736331
                736333
                736334
                736335
                736336
                736337
                736338
                736339
                736341
                736342
                736343
                736345
                736346
                736347

datenumberB=    736330
                736331
                736332
                736333
                736334
                736338
                736339
                736340
                736341
                736342
                736344
                736345
                736346
                736348
                736349

Now I want to compare the value of A on DateA(n) to that of B on DateB while DateB is the date that is closest to and before the date of DateA(n).
For example,
comparing the value of A on DateA '2016-01-12' to that of B on DateB '2016-01-11'.
Please help and thanks a lot.

A: It'll get you the desired output!
all_k=0;
out(1)=1;    % not comparing the first index as you mentioned
for n=2:size(datenumberA,1)
    j=0;
    while 1
        k=find(datenumberB+j==datenumberA(n)-1); %finding the index of DateB closest to and before DateA(n)
        if size(k,1)==1 break; end %if found, come out of the while loop
        j=j+1;         % otherwise keep adding 1 in the values of datenumberB until found
    end
    if size(find(all_k==k),2) ~=1 % to avoid if any DateB is already compared
        out(end+1)=A(n)> B(k); %Comparing Value in A with corresponding value in B
        all_k(end+1)=k; end %Storing which indices of DateB are already compared
end
out'   %Output

Output:-
ans =

 1
 0
 0
 1
 0
 0
 1
 0
 0
 1
 0
 0
 1


text:
Q: LWC - Disable submit button until all required fields have values I'm trying to disable submit button until all the required fields have value and I have something below the code but I'm not sure if this is right pattern to follow, what if; if I have 20 input fields and checkbox or dropdown the code will be messy, is there a better way to achieve what I'm trying to do?
<template>
            <lightning-input-field field-name='fieldname1' value={field1}></lightning-input-field>

            <lightning-button variant="brand" type="submit" name="save" label="Create Account" disabled={disableBtn}>
            </lightning-button>

</template>

JS:
disableBtn = true;

  field1;

 handleChange(event){
        this.field1 = event.target.value;
        if(this.field1 != null && this.field1!=''){
            this.disableBtn = false;
        }
    }

A: First of all, you can make the handler generic:
handleChange(event){
    this[event.target.dataset.name] = event.target.value;
    this.validateInputs();
}

<lightning-input-field data-name="field1" field-name='fieldname1' value={field1}></lightning-input-field>

Secondly, you can validate many values at once with some:
validateInputs() {
  this.disableBtn = [this.field1, this.field2, this.field3].some(value => !value)
}

Where ! causes a falsy value to become true, and a truthy value to become false. Array.prototype.some returns true the moment any of its inputs are true, false otherwise; this means that if all required values are present, the disableBtn property will be false and the user can save.
Note that if you're using lightning-input-field, you should also be using lightning-record-edit-form, which automatically takes care of validation for you. Also note that it is not the "Lightning" way to disable a button until you can save. Instead, you should report errors back to the user when they click on the button so they can correct their errors.


text:
Q: Static DNS servers keep defaulting windows 7 I'm using Google's DNS servers for my Wireless and LAN connections. However, every couple of hours the DNS server seems to be resetting and the static DNS server values are removed.
The below user had what seems to be the same problem, but they solved it by reformatting their computer, which is not something I'm ready to do.
Wireless Keeps Setting Manual DNS Server
Any help is appreciated!

A: Need save/restore settings GUI?:
NetSetMan 3.5.3

Are you tired of manually changing your location-based network and
  system configuration on your laptop or computer every day?
Then NetSetMan is your solution. It will do the work for you. Switch
  between configuration profiles for different locations instantly!

Free DHCP + DNS Server at Windows 7? :
Dual DHCP DNS Server


text:
Q: Passing an additional parameter with an onChange event with custom component On my component I use a custom component for displaying numbers- I need onChange to get the input value, I have tried the below but I get a type error:

Type '(event: any) => void' is not assignable to type '() =>
  void'.ts(2322)

export default function Test({param}) {

  const onChange = key => event => {
    const value = parseInt(event.target.value.replace(/[^0-9]/g, ''))
    const x = {...param.x}
    x.y[key] = value

    setX(param => ({
      ...param,
      payment: x
    }))
  }

  return (
    <>
      <NumberListItem
        label="test"
        value={(param.payment)}
        onChange={onChange('payment')}
        inputProps={{decimalScale: 0, suffix: ' %'}}
      />
    </>
  )
}

NumberListItem component:
export default function NumberListItem({
  value = '',
  onChange = () => {},
  ...rest
}) {
  return (
    <ListItem>
      <NumberField
        value={value}
        onChange={onChange}
        {...rest}
      />
    </ListItem>
  )
}

NumberField component:
export default function NumberField(props: TextFieldProps & NumberFormatProps) {
  return (
    <TextField
      {...props}
      InputProps={{
        inputComponent: NumberFormatCustom
      }}
    />
  )
}

A: You should set prop type:
export interface NumberListItemProps {
  value: string;
  onChange: (e:any) => {};
  [props: string]: any;
}
export default function NumberListItem({
  value = '',
  onChange,
  ...rest
}: NumberListItemProps) {
  return (
    <ListItem>
      <NumberField
        value={value}
        onChange={onChange}
        {...rest}
      />
    </ListItem>
  )
}


text:
Q: Histogram in Excel with bins I have an excel spreadsheet with score and frequency of scores, as such:
Score   Count
0   2297802
1   2392803
2   1258527
3   969550
4   818579
5   675646
6   591326
7   598960
8   506268
9   448232
10  414830
11  382808
...

I'm looking for a way to 'bucket' these scores in intervals of (say) 3 and plot them to show the distribution:
Score    Count
0-2      5949132
3-5      2463775
...

And so on
I'm using Excel for Mac and I tried defining a 3 interval bin in the Analysis ToolPak but that appears to work only on raw data as opposed to the counts that I already have.

A: *

*in cells D2 downwards, enter your upper (inclusive) bin limits

*in cell E2, enter =SUMIF(A:A,"<="&D2,B:B)-SUM(E$1:E1)

*copy E2 downwards

example result:


text:
Q: Getting more than one item from a database in ASP .NET MVC 3 I'm creating a database where users can enter some Error Reports and we can view them. I'm making these database with C# in the ASP MVC 3 .NET framework (as the tags imply). Each Error Report has a unique ID, dubbed ReportId, thus none of them are stored under the same Id. However, whenever a User creates a new Error, I pass their User Name and store it in with the rest of the report (I use User.Identity.Name.ToString() to get their name and store it as a string). I know how to get a single item from the data using a lambda expression, like so:
db.DBSetName.Single(g => g.Name == genre)

The above code is based on an MVC 3 tutorial (The Movie Store one) provided by ASP. This was how they taught me how to do it.
My major question is: is there a member function like the .Single one that will parse through the whole database and only output database entries whose stored User Name matches that of the currently logged in user's? Then, I can use this to restrict User's to being only able to edit their own entries, since only their entries would be passed to the User's View.
What would be the best way to implement this? Since the ReportId will not be changed, a new data structure can be created to store the user's Errors and passed through to the Index (or Home) View of that particular controller. From there they should be able to click any edit link, which will pass the stored ReportId back to the Edit Action of this particular controller, which can then search the entire database for it. Am I right in assuming this would work? And would this be ideal, given that the other items in the database are NOT passed through to the Index in this method, meaning the User does not have access to the other items' ReportId's, which the user needs to pass into the Edit Action for it to work? If this is ideal, this is the method that requires me to know how to parse through a database and grab every element that fits a particular description (stored User Name matches User's current User Name).
Or would a better approach be to pass the whole database to the Index View and only output the database entries that have User Name values that match the current logged in user's? I guess this could be done in a foreach loop with a nested if loop, like so:
@foreach(var item in db.Reports)
{
    if(item.UserName == User.Identity.Name.ToString())
    {
        ...code to output table...
    }
}

But this passes the whole database which gives the user a lot more info than they need. It also gives them potential access to info I don't want them to have. However, I don't have to make a new data structure or database, which should lower server memory usage and fetch time, right? Or are databases passed by copy? If so, this method seems kinda dumb. However, I don't know if the first method would fracture the database potentially, this one certainly would not. Also don't remember if I NEED an else statement in C#, I'm more familiar with C++, where you don't need one and you also don't need {}'s for single line if's, if I need one: please don't judge me too harshly on it!
Small note: I am using CRUD Controllers made with the Entity First Framework in order to edit my database. As such, all creation, reading, updating, and deletion code has been provided for me. I have chosen not to add such basic, common code. If it is needed, I can add it. I will add what the Edit Action looks like:
public ActionResult Edit(string id)
{
    Report report = db.Reports.Find(id);
    return View(report);
}

It accepts a string as an id, ReportId is the id used and it IS a string. It is a randomly generated GUID string made with the GUID.NewGuid().ToString() function. I will also be doing the comparison of names with:
Model.UserName == User.Identity.Name.ToString()

Which was shown earlier. Sorry if this is too much text, I wanted to provide as much info as possible and not make anyone mad. If more info is needed, it can certainly be provided. So at the end of the post, the major question actually comes down to: which of the above two methods is best? And, if it's the first one, how do I implement something like that?
Thanks for your help!

A: Unless I'm completely misunderstanding you, you just want .Where()
Like this:
var reports = db.Reports.Where(r => r.genre == inputGenre);

This would get you an IEnumerable of Report, which you could then use however you wish.


text:
Q: difference between TRC andDRC architecture? How Tuple Relaional Calculas and Domain Relational Calculas works in Database.What is the difference between these two?

A: There is a very big conceptual difference between the two.In case of tuple relational calculus ,you operate on each tuples but in case of domain relational calculus ,you deal with each column or attribute.Both methods can be used to get any result.
The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples of that relation. E.g. QUELThe domain-oriented calculus has domain variables i.e., variables that range over the underlying domains instead of over relation. E.g. ILL, DEDUCE....The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples of that relation. E

A: Basically,TRC is stands for the tuple relation calculus and DRC is stands for the domain relation calculus.Tuple contains the single row of the table where as domain contains the atomic values.


text:
Q: How can I install a third-party .deb package in an arbitrary base dir? I have a .deb which politely installs itself in /opt. For my purposes I would prefer it acted like a first-class citizen and installed itself in the regular filesystem locations.
Is there a way to do this?
This is Ubuntu 10.04.4
update
I have tried --root=/, it doesn't change the installation location.

A: This is not possible without rebuilding the Debian package--which is certainly an option if you want to create your own directory hierarchy.  The package was--presumably--built and tested based on the directory structure in /opt, and without knowing details about the package, it may not even be ABLE to be run without being in that directory.


text:
Q: linear transformation that Im(T)=Ker(T)
Let $T:\mathbb{R}^2\rightarrow \mathbb{R}^2$ such that $T(x,y)=(2x-3y,\alpha  x+\beta y)$ and $Ker(T)=Im(T)$
find $\alpha,\beta$

How should I approach this?

A: You know that $T(1,0)=(2,\alpha)$ and $T(0,1)=(-3,\beta)$ belong to $\operatorname{Im} T$. Thus they also belong to $\operatorname{Ker} T$.
What can you deduce from the fact that $T(2,\alpha)=(0,0)$? Similarly, can you say something about $\beta$ from $T(-3,\beta)=(0,0)$?


text:
Q: Adding 2 custom fields to product category and tags in WooCommerce but code giving notice with the reference of this question. Adding custom field to product category in WooCommerce
I am trying this code but its giving me notice.

Notice: Undefined variable: term_id in /home/userdir/public_html/wp-content/themes/theme-child/functions.php on line 61

here is the code i am trying with little modification. Would anyone please let me know what i am doing wrong here?
function text_domain_taxonomy_add_new_meta_field() {
    ?>

        <?php _e('Meta Title', 'text_domain'); ?>
        <textarea name="term_meta[wh_meta_title]" id="term_meta[wh_meta_title]"></textarea>

<?php _e('Enter a Text at Bottom, <= 160 character', 'text_domain'); ?>

        <?php _e('Meta Description', 'text_domain'); ?>
        <textarea name="term_meta[wh_meta_desc]" id="term_meta[wh_meta_desc]"></textarea>

<?php _e('Enter Text at Top, <= 160 character', 'text_domain'); ?>

    <?php
}
add_action('product_cat_add_form_fields', 'text_domain_taxonomy_add_new_meta_field', 10, 2);
//Product Cat Edit page
function text_domain_taxonomy_edit_meta_field($term) {
    //getting term ID
    $term_id = $term->term_id;
    // retrieve the existing value(s) for this meta field. This returns an array
    $term_meta = get_option("taxonomy_" . $term_id);
    ?>

        <?php _e('Text at Bottom', 'text_domain'); ?>

            <textarea name="term_meta[wh_meta_title]" id="term_meta[wh_meta_title]"><?php echo esc_attr($term_meta['wh_meta_title']) ? esc_attr($term_meta['wh_meta_title']) : ''; ?></textarea>

<?php _e('Text at Bottom, <= 160 character', 'text_domain'); ?>

        <?php _e('Text at Top', 'text_domain'); ?>

            <textarea name="term_meta[wh_meta_desc]" id="term_meta[wh_meta_desc]"><?php echo esc_attr($term_meta['wh_meta_desc']) ? esc_attr($term_meta['wh_meta_desc']) : ''; ?></textarea>

<?php _e('Text at Top', 'text_domain'); ?>

    <?php
}
add_action('product_cat_edit_form_fields', 'text_domain_taxonomy_edit_meta_field', 10, 2);
// Save extra taxonomy fields callback function.
function save_taxonomy_custom_meta($term_id) {
    if (isset($_POST['term_meta'])) {
        $term_meta = get_option("taxonomy_" . $term_id);
        $cat_keys = array_keys($_POST['term_meta']);
        foreach ($cat_keys as $key) {
            if (isset($_POST['term_meta'][$key])) {
                $term_meta[$key] = $_POST['term_meta'][$key];
            }
        }
        // Save the option array.
        update_option("taxonomy_" . $term_id, $term_meta);
    }
}
add_action('edited_product_cat', 'save_taxonomy_custom_meta', 10, 2);
add_action('create_product_cat', 'save_taxonomy_custom_meta', 10, 2);

$metaArray = get_option('taxonomy_' . $term_id);
echo $productCatMetaTitle = $metaArray['wh_meta_title'];
echo $productCatMetaDesc = $metaArray['wh_meta_desc'];

//Product Tag creation page
function tag_taxonomy_add_new_meta_field() {
    ?>

        <?php _e('Text at Bottom', 'text_domain'); ?>
        <textarea  name="term_meta[tg_meta_title]" id="term_meta[tg_meta_title]"></textarea>

<?php _e('Text at Bottom, <= 160 character', 'text_domain'); ?>

        <?php _e('Text at Top', 'text_domain'); ?>
        <textarea name="term_meta[tg_meta_desc]" id="term_meta[tg_meta_desc]"></textarea>

<?php _e('Text at bottom, <= 160 character', 'text_domain'); ?>

    <?php
}
add_action('product_tag_add_form_fields', 'tag_taxonomy_add_new_meta_field', 10, 2);
//Product tag Edit page
function tag_taxonomy_edit_meta_field($term) {
    //getting term ID
    $term_id = $term->term_id;
    // retrieve the existing value(s) for this meta field. This returns an array
    $term_meta = get_option("taxonomy_" . $term_id);
    ?>

        <?php _e('Text at Bottom', 'text_domain'); ?>

            <textarea name="term_meta[tg_meta_title]" id="term_meta[tg_meta_title]"><?php echo esc_attr($term_meta['tg_meta_title']) ? esc_attr($term_meta['tg_meta_title']) : ''; ?></textarea>

<?php _e('Text will show in bottom, <= 260 character', 'text_domain'); ?>

        <?php _e('Text at Top', 'text_domain'); ?>

            <textarea name="term_meta[tg_meta_desc]" id="term_meta[tg_meta_desc]"><?php echo esc_attr($term_meta['tg_meta_desc']) ? esc_attr($term_meta['tg_meta_desc']) : ''; ?></textarea>

<?php _e('Text will show at Top', 'text_domain'); ?>

<?php
}
add_action('product_tag_edit_form_fields', 'tag_taxonomy_edit_meta_field', 10, 2);
// Save extra taxonomy fields callback function.
function tag_save_taxonomy_custom_meta($term_id) {
    if (isset($_POST['term_meta'])) {
        $term_meta = get_option("taxonomy_" . $term_id);
        $tag_keys = array_keys($_POST['term_meta']);
        foreach ($tag_keys as $key) {
            if (isset($_POST['term_meta'][$key])) {
                $term_meta[$key] = $_POST['term_meta'][$key];
            }
        }
        // Save the option array.
        update_option("taxonomy_" . $term_id, $term_meta);
    }
}
add_action('edited_product_tag', 'tag_save_taxonomy_custom_meta', 10, 2);
add_action('create_product_tag', 'tag_save_taxonomy_custom_meta', 10, 2);

$metaArray = get_option('taxonomy_' . $term_id);
echo $productTagMetaTitle = $metaArray['tg_meta_title'];
echo $productTagMetaDesc = $metaArray['tg_meta_desc'];

A: Remove this code
$metaArray = get_option('taxonomy_' . $term_id);
echo $productCatMetaTitle = $metaArray['wh_meta_title'];
echo $productCatMetaDesc = $metaArray['wh_meta_desc'];

From two places in your code


text:
Q: Spring: Delete data from tables with relationships I developed a CRUD in spring using thymeleaf. Everything is working. Some tables have OneToOne and ManyToOne relationships. And every time I delete a row from the news table for example, it also deletes from the author table. How do I prevent this?
NewsServiceImplement:
@Override
public void delete(Long id) {
    repository.deleteById(id);
}

DashNewsController:
// Delete
@RequestMapping("/dashboard/noticias/deletar/{id}")
public String destroy(@PathVariable("id") Long id) {
    noticiaService.delete(id);
    return "redirect:/dashboard/noticias";
}

A: Make sure you don't have the cascade attribute where you defined the relationship (@OneToMany), if you do just remove it:
cascade = CascadeType.ALL


text:
Q: How to add description to an existing bigquery table? I'm looking for a way to add description to an existing table attributes, is there any simple command line command such as "alter table zzz add description...." to to this?

A: You can add descriptions to tables and its fields through the web UI - that would be the simplest way.
Also via the API, using this document endpoint with the PATCH() methos:
https://cloud.google.com/bigquery/docs/reference/v2/tables
description
schema.fields[].description

The bq command line tool can be used too:
bq update --description "My table" existing_dataset.existing_table

A: Google has a new API, Google.Cloud.BigQuery.V2, which is available through NuGet. Updating the table description using the new API can be done as follows:
// instantiate a client for big query
// depending on the API version, this will be either BigqueryClient or BigQueryClient
BigqueryClient bqClient = BigqueryClient.Create(projectId, credential);

// get an instance of the tables resource using the client
TablesResource resource = new TablesResource(bqClient.Service);

// get the table definition from big query
TablesResource.GetRequest get = resource.Get(projectId, datasetId, tableId);
Table tbl = get.Execute();

// set the description property
tbl.Description = "New Description";

// save the changes to the table definition
TablesResource.PatchRequest patch = resource.Patch(tbl, projectId, datasetId, tableId);
patch.Execute();


text:
Q: Outputting STDOUT To A File And Back Again I routed STDOUT to a file using this code:
STDOUT.reopen(File.open("./OUTPUT",'w+'))

Now I need to route STDOUT to the terminal again.
How would I do this?

A: You need to reopen STDOUT on file handle 1, which is the standard fd handle for stdout (0=stdin, 1=stdout, 2=stderr).
I'm not a Ruby guy, but I think this is about right:
STDOUT.reopen(IO.for_fd(1, "r"))

A: UPDATED
orig_std_out = STDOUT.clone
STDOUT.reopen(File.open('OUTPUT', 'w+'))
puts "test to file"
STDOUT.reopen(orig_std_out)
puts "test to screen"

A: Even simpler if on UNIX:
STDOUT.reopen 'OUTPUT'
puts 'text to file'

STDOUT.reopen '/dev/tty'
puts 'text to console'


text:
Q: One @SerializedName allowing for multiple datatypes I am uploading an object to a server and the "value" field accepts Strings, Ints, and Boolean values.
Here is the model with the clearly failed application of @SeralizedName.
public class InspectionFormItems {

@SerializedName("id")
private Integer id;

@SerializedName("type")
private String type;

@SerializedName("value")
private String stringValue;

@SerializedName("value")
private boolean boolValue;

@SerializedName("value")
private int intValue;

@SerializedName("name")
private String name;

@SerializedName("children")
ArrayList<ArrayList<InspectionFormItems>> subitems;
}

Most of the stackoverflow results I found were for Serializing entire objects, or De-Serializing. Some of my ideas were..

*

*Is it possible to remove @SerializedName from the three value fields and only serialize the value that isn't null?

*Can I build some sort of optional data-type-object in java that is set based on the data type that has a value?

This object is part of a larger object and the subitems object has a fair bit of depth to it it just as a note. I expect this to be a duplicate of some question, I just have been unable to find it so far.
Edit:
This is the closest question I have found though I would rather not custom serialize the entire object the way this person has as there could be 40-100 of these objects in this outgoing json
gson-same-field-name-different-types-serialize
I've also discovered I can not dynamically set the @SerializedValue attribute
is-it-possible-to-pass-method-parameter-to-annotation-on-a-method?
3rd Edit: Let me know if I should delete a bunch of this excess. I am trying to implement this method - inner serialization - this answer though is old an tough to make work right now.

A: Thanks to Andreas for their answer.
Using Object, I was able to avoid pre-defining the variable.
@SerializedName("value")
private Object value;

This allowed me to pass both String, Integer, or boolean to the same value field.


text:
Q: create dictionary from .h file with python I have problem in making dictionary from my header file, my header file contains this data
/*Some comments*/

#define INPUT1 (17.000)
#define INPUT2 (15.000)
#define MUL (255.000)
#define SUB (2.000)
#define SUM (32.000)

In my python file I am accessing this from
read = open("example_cfg.h")
a=[]
for z in read:
    a.append( z.split(" "))
dict = {}
for i in range(len(a)):
    if i == 0:
        for j in a[i]:
            dict[j] = []
    else :
        for j in range(len(a[i])):
            dict[a[0][j]].append( a[i][j])
print(dict)

I don't have any idea what to put in z.split() to access my dictionary something like this: {INPUT1 : '17', INPUT2: '15' ...}

A: I agree that Michael's comment, regex is probably the most reliable way to do this, however, there is a very simple solution to your problem (it might not generalize, tho)
read = open('example_cfg.h')
a = []
for z in read:
    # this step is important, only process lines which include a #define
    if '#define' in z:
        # it is also important to strip EOL characters
        a.append(z.replace('\n','').split(' '))

# once we have the list of lists, a one liner dict comprehension can turn our list of lists into a dict
# x[2][x[2].find("(")+1:x[2].find(")")]'s only purpose is to parse the text inside the parentheses
dictionary = {x[1]:x[2][x[2].find("(")+1:x[2].find(")")] for x in a}


text:
Q: Generación de números aleatorios sin repetición en javascript Estoy intentando generar 5 números al azar al estilo de una loteria, el problema es que ningún numero puede ser igual a otro número anterior.
Por ejemplo num1 no puede ser igual a num2, me gustaría saber si hay alguna forma de comprobar que estos nunca sean iguales.
Esto es lo que intenté:

var num1 = Math.random() * 49
if (num1 == num0) {
  var num1 = Math.random() * 49
};

A pesar de eso cada tanto hay un número que se repite

A: Genera un array con los números posibles, por ejemplo digamos que los números válidos van del 1 al 40
const n = 40;
const arr = new Array(n);
for (let i = 0; i < n; i++) {
    arr[i] = i + 1;
}

Ordénalos al azar
arr.sort(() => Math.random() > 0.5 ? 1 : -1);

Y luego toma solo 5
const loteria = arr.slice(0, 5);

Ejemplo:

const n = 40;
const arr = new Array(n);
for (let i = 0; i < n; i++) {
    arr[i] = i + 1;
}

arr.sort(() => Math.random() > 0.5 ? 1 : -1);
const loteria = arr.slice(0, 5);

document.write(loteria);

A: Este Script te puede generar 5 números aleatorios.
 <script>
 function myFunction() {
 var myArray = ['1','2','3','4','5'];

     var i,j,k;
     for (i = myArray.length; i; i--) {
         j = Math.floor(Math.random() * i);
         k = myArray[i - 1];
         myArray[i - 1] = myArray[j];
         myArray[j] = k;
     }

     document.getElementById("demo").innerHTML = myArray;
 }
 </script>

A: La idea es almacenar los números aparecidos para comprobar que no han aparecido antes.
-El sistema "sencillo" seria que, en caso de repetir número, busque otro, pero este no es un método "elegante" ya que en el caso de querer "muchos" números puede darse el caso que tenga que repetir "muchas" veces.
-El sistema "elegante" se basa en crear una matriz con las opciones posibles e ir eliminandolos a medida que aparecen.
Respondí una pregunta similar en https://es.stackoverflow.com/a/27555/3440

A: Podrías almacenar todos los números que aparecen en un String separados por algún carácter y después buscar si el nuevo número está contenido en el String.
Si está contenido en el String, que vuelva a generar otro número y si no, que introduzca el valor generado. En mi caso he preferido utilizar un bucle do-while para asegurarme de que no salga del bucle hasta que obtenga un valor que no esté repetido.
Para hacer las 5 repeticiones puedes utilizar un bucle for.
Ejemplo:
var num1;
var cadena = "";

for(var i = 0; i < 5; i++){
    do{
       num1 = Math.random() * 49;
    }while(cadena.indexOf(num1) !== -1);

    cadena += num1 + "/";
}

A:

var numbersInUse = []
var randomNumbers = []
i = 0;
while(i < 5){
 var num = Math.random() * 49;
 if(!numbersInUse.indexOf(num) > -1){
    i++;
    numbersInUse.push(num);
    randomNumbers.push(num);
 }
}
console.log(randomNumbers);

A: Prueba con
    var numeros = [];
    for(i=0;i<5;i++){
        numeros[i]= String(Math.random()).substr(2, 16);

}

La longitud es de 14 puede cambiar eso modificando el 16
hay tienes 5 números aleatorio almacenados en un array

A: Lo que yo haría, siguiendo el principio de reutilización de código, sería crear una función que admitiera como parámetro la cantidad de números aleatorios a generar, para el caso 5, y las cifras que deben tener éstos números. Por supuesto habría que comprobar luego como conviven ambos valores (no se puede pedir 200 números diferentes y pedir números de sólo 2 cifras, por ejemplo).
Internamente ésta función debería generar números, aleatoria mente, rellenando una array hasta la cantidad requerida. Seguidamente se comprueban los números del array desde el principio y en caso de encontrar un duplicado sustituirlo por un nuevo número y volver a empezar, hasta comprobar todos los números del array.


text:
Q: How to wrap more than one div around a div I have a div (Slideshow) and I want to wrap around it small divs (Items). The Slideshow div will be static and the Items will be rendered automatically using a Repeater Control.
I made this image to better illustrate what I need to achieve.

I saw this Question and I thought I could use the same logic, let the Repeater items get rendered normally and then change the markup using JavaScript and use some sort of a CSS Grid layout to style the first 4 items for example on the left and the right and the rest will be beneath them but I'm not sure how to do it plus if there's a more simple solution I thought it could be cleaner than using the concept I saw in the question I referred.
Update1: Changed the picture to show the exact desired output

A: You could generate a Masonary layout. This plug in may be helpful, https://github.com/desandro/masonry
You could do this with bootstrap columns as well. For the first row, with the slideshow, you have 3 columns. The outer left and right columns will have 2 nested rows. http://getbootstrap.com/examples/grid/. This is what Im most familiar with so I'll show you how I would implement a solution for the first row and how to implement a second row with 4 columns.

                Item

                Item

        Slide Show

                Item

                Item

        Item

        Item

        Item

        Item

Checkout the angular material layout system as well. This will be harder to implement though because it requires Angular. https://material.angularjs.org/latest/#/layout/grid

A: Check this solution out and see if you can adopt it to your project: http://jsfiddle.net/1b0hoked/.
HTML:

CSS:
*, :before, :after {
    margin: 0;
    padding: 0;
    border: 0;
    box-sizing: border-box;
}

body {
    padding: 10px;
}

#wrapper {
    counter-reset: item-counter;
    text-align: right;
    margin: 0 auto;
    display: table;
    outline: 1px solid gray;
    position: relative;
}

#slideshow {
    width: 210px;
    height: 210px;
    line-height: 210px;
    text-align: center;
    border: 2px solid red;
    position: absolute;
    top: 5px;
    left: 50%;
    margin-left: -105px;
}

#slideshow:before {
    content: "Slide Show";
    vertical-align: middle;
    font: bold 16px/1 Sans-Serif;
    color: red;
}

.item {
    height: 100px;
    width: 100px;
    text-align: center;
    line-height:  96px;
    border: 2px solid #aaa;
}

.item:before {
    counter-increment: item-counter;
    content: "item " counter(item-counter);
    vertical-align: middle;
    font: bold 12px/1 Sans-Serif;
    color: #aaa;
}

.item {
    float: left;
    margin: 5px;
}

.item:nth-of-type(4n + 1) {
    clear: left;
}

.item:nth-of-type(3) {
    float: right;
    margin-top: -105px;
}

.item:nth-of-type(4) {
    float: right;
    clear: right;
    margin-left: -105px;
}

.item:nth-of-type(2) {
    clear: left;
}

JS/jQuery:
$(function() {
    var numToAdd = 50;
    while(--numToAdd >= 0) {
        $("
").addClass("item").appendTo("#wrapper");
    }
});


text:
Q: ambiguous between the following action methods I'm trying to make a delete functionality in my program. I followed this tutorial. But when I tried deleting this error came out.

here is my class from model for delete.
        public bool deleteAccount(int Id) {
        using (SqlConnection conn = new SqlConnection(connectionString))
        using (SqlCommand comObj = new SqlCommand("", conn)) {
            comObj.CommandText = "DELETE FROM account WHERE userId = @userId";
            comObj.Parameters.AddWithValue("@userId", Id);
            conn.Open();
            int res = comObj.ExecuteNonQuery();
            if (res >= 1)
            {

                return true;

            }
            else
            {

                return false;
            }
        }
    }

My delete action controller
public ActionResult deleteAccount()
    {
        return View();
    }

    public ActionResult deleteAccount(int id)
    {

        try
        {
            var databaseModel = new database();
            if (databaseModel.deleteAccount(id)) {
                ViewBag.AlertMsg = "Employee details deleted successfully";
            }
            return RedirectToAction("GetAllEmpDetails");
        }
        catch {
            return View();
        }

full stack trace
[AmbiguousMatchException: The current request for action 'deleteAccount' on controller type 'accountController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult deleteAccount() on type directory.Controllers.accountController
System.Web.Mvc.ActionResult deleteAccount(Int32) on type directory.Controllers.accountController]
   System.Web.Mvc.ActionMethodSelectorBase.FindActionMethod(ControllerContext controllerContext, String actionName) +113
   System.Web.Mvc.Async.ReflectedAsyncControllerDescriptor.FindAction(ControllerContext controllerContext, String actionName) +54
   System.Web.Mvc.ControllerActionInvoker.FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, String actionName) +203
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +136
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
   System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
   System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
   System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Hope someone can help me.
| EDIT |
I tried other tutorials a while ago. and I also tried adding [HttpPost] but the ID being passed to the URL is always 0. so I tried displaying my userId
acc.userName = rdr["userId"].ToString();

and every ID I get is 0

A: Look at the resource below hope it helps, Also i think you should start looking at Entity Framework for your Data Access.
You can do something like in this example
// GET: /Movies/Delete/5
public ActionResult Delete(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Movie movie = db.Movies.Find(id);
    if (movie == null)
    {
        return HttpNotFound();
    }
    return View(movie);
}

// POST: /Movies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
    Movie movie = db.Movies.Find(id);
    db.Movies.Remove(movie);
    db.SaveChanges();
    return RedirectToAction("Index");
}

https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/examining-the-details-and-delete-methods

A: The second controller must have the request method like:
    public ActionResult deleteAccount()
    {
        return View();
    }
    [HttpPost]
    public ActionResult deleteAccount(int id)
    {

        try
        {
            var databaseModel = new database();
            if (databaseModel.deleteAccount(id))
            {
                ViewBag.AlertMsg = "Employee details deleted successfully";
            }
            return RedirectToAction("GetAllEmpDetails");
        }
        catch
        {
            return View();
        }
    }

A: By default the action method stands as Get if we don't explicitly specify it is Get or Post, so when you try to call either one it ends up confused on which action method was supposed to call (with parameter or without parameter), you need to specify which is for Get and which is for Post like:
[HttpGet]
public ActionResult deleteAccount()
{
    return View();
}

[HttpPost]
public ActionResult deleteAccount(int id)
{

    try
    {
        var databaseModel = new database();
        if (databaseModel.deleteAccount(id)) {
            ViewBag.AlertMsg = "Employee details deleted successfully";
        }
        return RedirectToAction("GetAllEmpDetails");
    }
    catch {
        return View();
    }
}

Hope it helps!

A: You can't have the same HTTP verb for the same action name. In other words, having HttpGet for the same action name, even an overload, isn't possible.
Change one or your action methods to a different HTTP action verb...
[HttpGet]
public ActionResult deleteAccount()
{
    //..
}

[HttpPost]
public ActionResult deleteAccount(string country)
{
    //..
}

A: if you are using WebAPI2, you can specify your route prefix and set your controller name to Delete (without the DeleteXXX)
For example,
[RoutePrefix("api/Account")]
public class AccountController : ApiController
    {

        public IHttpActionResult Delete(Guid id)
        {
        }

        public IHttpActionResult Delete()
        {
        }
   }


text:
Q: Open application window on the same screen as where It was launched I am using a dual screen setup. Ubuntu 14.10/Unity. Each screen has its own launcher/Dash. Default applictions like  Firefox, nautilus, terminal & thunderbird appears on the screen where I have used the launcher. So..when I use the launcher for Firefox on the right screen, the browser opens on the right side screen. As it should be.
I would like that behavior with other application like Google Chrome. I can't seem to find a proper solution.

A: Unity uses Compiz as composing manager, and that has all sorts of plugins for this sort of stuff. To make it easy and long story short without messing in command line , install Compiz Config Settings Manager ( with sudo apt-get install compizconfig-settings-manager or via Software Center ) , and look for Place Windows , ensure it's checked

Under that plugin there will be several options for Multi Output Mode . What you want is Use output device of focused window . Thus it will place open file window wherever your file manager is

A: Redirecting the command to run an application
Most applications open their window on the screen they were initiated from (either from Dash or the launcher). Some applications however do not, but they can be forced to, by redirecting the command to run the application through the script below. To do that, you will need to edit the corresponding .desktop file (launcher).
The setup seems a bit complicated, but if the procedure is followed ("How to use"), it should not be too difficult at all.
How it works

*

*The script reads the mouse position at the moment you click the launcher or choose the application from Dash, and determines on which screen that is (left/right).

*Subsquently, it waits for the new window to appear, owned by the application (pid) you started.

*Once the window appears, it checks if the window (screen-) position matches the mouse (screen-) initial position.

*If not, it moves the window to the screen you started the application from. In most cases, the action will be in a (very) early stage of the window's existance, so you even won't notice it.

Issue / solution
There is one downside: if you replace the .desktop file's main command by the command to call this script, the right-click "open with " will not work properly. In the case of a webbrowser like Google Chrome, that will not be too big a problem. With other applications, a simple solution would be to add the option to open a new window on the current screen as a shortcut (see further below).

How to use:

*

*The script uses both wmctrl and xautomation:
sudo apt-get install xautomation
sudo apt-get install wmctrl

*Create a directory ~/bin if it does not exist yet.

*Copy the script into an empty file, save it as open_oncurrent (no extension) in ~/bin

*Make it executable(!)

*Copy the corresponding .desktop file from /usr/share/applications to ~/.local/share/applications:
cp /usr/share/applications/google-chrome.desktop ~/.local/share/applications/google-chrome.desktop

*Open the local copy in ~/.local/share/applications:
gedit ~/.local/share/applications/google-chrome.desktop

*Edit the file (two options):

*

*To change the main command of the launcher:

*

*find the line:
Exec=/usr/bin/google-chrome-stable %U

*change it to
Exec=/bin/bash -c "open_oncurrent /usr/bin/google-chrome-stable"

*To add the option as a shortcut (like in the image above):

*

*find the line:
X-Ayatana-Desktop-Shortcuts=NewWindow;NewIncognito;

*replace it by:
X-Ayatana-Desktop-Shortcuts=NewWindow;NewIncognito;New window on this screen;

*Then add the following section to the very end of the file:
[New window on this screen Shortcut Group]
Name=New window on this screen
Exec=/bin/bash -c "open_oncurrent /usr/bin/google-chrome-stable"
TargetEnvironment=Unity

How to use with other applications:
Similarly, you can apply the solution to other applications. The syntax of the command to use in the .desktop fileis like the example:
Exec=/bin/bash -c "open_oncurrent <command>"

A small additional explanation on how to deal with exceptions is in the script.
The script
#!/usr/bin/env python3
import subprocess
import sys
import time
import getpass

t = 0; user = getpass.getuser(); application = sys.argv[1]
"""
In most cases, the command to run an application is the same as the process
name. There are however exceptions, to be listed below, if you use these appli-
cations i.c.w. this script. Just add an item to the list in the format:
["<command>", "<process_name>"],
"""
exceptions = [
    ["/usr/bin/google-chrome-stable", "chrome"],
    ]
try:
    procname = [app[1] for app in exceptions if app[0] == application][0]
except IndexError:
    procname = application

get = lambda cmd: subprocess.check_output(["/bin/bash", "-c", cmd]).decode("utf-8")
# initial position of the mouse (click position)
start_pos = int(get("xmousepos").strip().split()[0])
# x- position of right side of the screen
x_res = [int(s.split("x")[0]) for s in get("xrandr").split() if s.endswith("+0+0")][0]
# current windows
start_windows = get("wmctrl -l")
# open application
subprocess.call(["/bin/bash", "-c", application+"&"])
while t < 30:
    procs = get("ps -u "+user).splitlines()
    new = [w for w in get("wmctrl -lpG").splitlines() if not w.split()[0] in start_windows]
    match = sum([[line for line in procs if w.split()[2] in line and procname[:15] in line] for w in new], [])
    if len(match) == 1:
        data = new[0].split(); curr_pos = int(data[3]); compare = (start_pos > x_res, curr_pos > x_res)
        if compare[0] == compare[1]:
            pass
        else:
            if compare[0] == True:
                data[3] = str(int(data[3])+x_res)
            else:
                data[3] = str(int(data[3])-x_res)
            cmd1 = "wmctrl -r "+data[0]+" -b remove,maximized_vert,maximized_horz"
            cmd2 = "wmctrl -ir "+data[0]+" -e 0,"+(",").join(data[3:7])
            for cmd in [cmd1, cmd2]:
                subprocess.Popen(["/bin/bash", "-c", cmd])
        break
    t = t + 1
    time.sleep(0.5)


text:
Q: UITableView index repeats after the 14th letter i'm trying to make a table of letters with index, when i click on the first 14 letters it shows me the right letter but after that it keeps repeating itself and show me  only the 14th letter. please help.. here is my code: (the letters are not English :))
- (void)viewDidLoad
{
    [super viewDidLoad];

    _arr=[NSArray arrayWithObjects:@"א",@"ב",@"ג",@"ד",@"ה",@"ו",@"ז",@"ח",@"ט",@"י",@"כ",@"ל",@"מ",@"נ",@"ס",@"ע",@"פ",@"צ",@"ק",@"ר",@"ש",@"ת",nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_arr count];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.arr;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index {
    int position;
    switch (index) {
        case 0:
            position=0;
            break;
        case 1:
            position=1;
            break;
        case 2:
            position=2;
            break;
        case 3:
            position=3;
            break;
        case 4:
            position=4;
            break;
        case 5:
            position=5;
            break;
        case 6:
            position=6;
            break;
        case 7:
            position=7;
            break;
        case 8:
            position=8;
            break;
        case 9:
            position=9;
            break;
        case 10:
            position=10;
            break;
        case 11:
            position=11;
            break;
        case 12:
            position=12;
            break;
        case 13:
            position=13;
            break;
        case 14:
            position=14;
            break;
        case 15:
            position=15;
            break;
        case 16:
            position=16;
            break;
        case 17:
            position=17;
            break;
        case 18:
            position=18;
            break;
        case 19:
            position=19;
            break;
        case 20:
            position=20;
            break;
        case 21:
            position=21;
            break;
        case 22:
            position=22;
            break;

        default:
            position=1;
            break;
    }
    NSLog(@"scrolling to %d",position);
    [tableView reloadInputViews];
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:position inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

     return index;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self.arr objectAtIndex:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

       cell.textLabel.font = [UIFont boldSystemFontOfSize:32];
       cell.textLabel.text=[_arr objectAtIndex:indexPath.row];
    return cell;
}

A: Everything here looks right, except for your tableView:sectionForSectionIndexTitle:atIndex.
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index {
    // First of all, we can greatly simplify it by removing your case statement
    // and replacing it with this:
    int position = 1;

    if (index < 23) {  // Or even better, use [_arr count]
        position = index;
    }

    NSLog(@"scrolling to %d",position);

    // Then, the following three lines should be deleted, as the tableview
    // automatically scrolls for you when an index is tapped:

    // [tableView reloadInputViews];
    // [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
    // [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:position inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];

    // Also, you should be returning position, and not index
    return position;
}

When you are using indexes, the tableview automatically takes care of the scrolling, so you should not be doing it yourself.  Just remove all of the [tableView ...] methods in this routine, and it should work for you.
So now, the short version would be:
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index {
    if (index < [_arr count]) {
        return index;
    }

    // Default
    return 1;
}


text:
Q: Where do midi-chlorians go after their host dies? When a Jedi or a Sith die, do the midi-chlorians somehow emigrate to another person or diffuse out of body and into space?
Could somebody breathe them accidentally and gain a bond with the Force?

A: Midichlorians are not a separate life-form living freely inside a force-user's body; they're part of a life-form's cells, as much a part of you as your cells' golgi apparatus, cell nuclei, or mitochondria.
The inspiration for the midichlorians was in fact the mitochondria. These are tiny structures inside your cells that help process sugars into energy your cells can use for their metabolic processes. Mitochondria have their own DNA, and relatively recently (late 1980s) it has become widely believed that mitochondria originated as free-living bacteria that were consumed by the early cells that eventually evolved into Eurkaryotes (us), and that mitochondria are therefore symbiotes.
Midichlorians, then, are the organelles in our cells that interact with the Force. They don't create the Force, and they are not synonymous with the Force, but they are the way we perceive and interact with the Force. It's no different from how our eyes use rod and cone cells to interact with electromagnetic radiation, or our hands use skin cells to detect physical interaction. Just because I know that rods and cones are detecting the radiation, that doesn't make a sunset less beautiful.
So, what happens to a person's midichlorians when they die? Their cells die, and the midichlorians in those cells die as well. Same as any other biological structure.

A: In the original trilogy, it is said that the force is a energy field that is CREATED by all living things.
So for me the midichlorians are not the force itself but the cells (or something else) that can create the force (and therefore allows someone who has a lot of midichlorians to interract with the energy field)
So, in that way, when a person die, all his midichlorians also die and he's not able to create the force or interract wih it.
But IIRC no reference of midichlorians is done in the original trilogy and no reference to how the force works exactly is done in the prelogy... So I can't find something that could bind these both aspects of the force...
PS : I don't think that the ghost are midichlorians living without a body (like RichS said in he's comment), they are souls that have been able to let a mark so strong in the force that their spirit survive in it...


text:
Q: Access violation reading a cookie with Delphi embedded Chromium (CEF1) I using Delphi Embedding Chromium (CEF1) on my application and am having trouble reading the cookie data of an URL.
I have found this code (included below), but on XE3 I get an exception when I use it about this line:
if WaitForSingleObject(vis.pEvent.Handle, INFINITE) = WAIT_OBJECT_0 then begin

The exception is

Project guiclient.exe raised exception class EAccessViolation with
  message 'Access violation at address 00000000'. Read of address
  00000000

implying one of the objects is not created or initialised properly.
The code I am using (copied from the above forum link) is:
  TCustomVisitor = class (TCefCookieVisitorOwn)
    private
      fcookie: PCefCookie;
      function visit(const name, value, domain, path: ustring; secure, httponly,
            hasExpires: Boolean; const creation, lastAccess, expires: TDateTime;
            count, total: Integer; out deleteCookie: Boolean): Boolean; override;
    public
      pEvent: TEvent;
      function getCookies: PCefCookie;
      constructor Create; override;
  end;

constructor TCustomVisitor.Create;
begin
  inherited;
  pEvent := TEvent.Create(nil, False, False, 'ev.chromium');
  new(fcookie);
end;

function TCustomVisitor.getCookies;
begin
  Result := fcookie;
end;

function TCustomVisitor.visit(const name, value, domain, path: ustring; secure, httponly,
            hasExpires: Boolean; const creation, lastAccess, expires: TDateTime;
            count, total: Integer; out deleteCookie: Boolean): Boolean;
begin
    fcookie.name := CefString(name);
    fcookie.value := CefString(value);
    fcookie.domain := CefString(domain);
    fcookie.path := CefString(path);
    fcookie.secure := secure;
    fcookie.httponly := httponly;
    fcookie.has_expires := hasExpires;
    //fcookie.creation := DateTimeToCefTime(creation);
    //fcookie.last_access := DateTimeToCefTime(lastAccess);
    //fcookie.expires  := DateTimeToCefTime(expires);

    SetEvent(pEvent.Handle);
end;

procedure TfrmAuth.bt_okClick(Sender: TObject);
var
  vis: TCustomVisitor;
  cname, cvalue: uString;
  ccookie: PCefCookie;
begin
  if crm.Browser<>nil then begin
    vis := TCustomVisitor.Create;
    try
      CefVisitUrlCookies(ed_url.Text, true, vis);

      // !!! This line causes the access violation
      if WaitForSingleObject(vis.pEvent.Handle, INFINITE) = WAIT_OBJECT_0 then begin
        ccookie := vis.getCookies;
        cname := CefString(@ccookie.name);
        cvalue := CefString(@ccookie.value);
      end;
    finally
      vis.Free;
    end;
  end;
end;

A: it's very simple. CefVisitUrlCookies takes you object as reference-counting interface, and releases it upon return and the obejct destroys itself, so you get access violation in attempt to access fried object.
To avoid this problem you may want to either store reference to the object among local variables, or call _addref explicitly:
vis._AddRef();
CefVisitUrlCookies(ed_url.Text, true, vis);
WaitForSingleObject(...)
vis._Release();

or
ivis: ICefCookieVisitor;
...
ivis := vis;
CefVisitUrlCookies(ed_url.Text, true, ivis);
WaitForSingleObject(...)
ivis := nil;

and don't forget to remove Free call. You should never explicitly free interfaced objects with reference counting.


text:
Q: ReactJs : create html for multiple components I am referring following example for isomorphic example of react.
https://github.com/mhart/react-server-example
If I disable javascript in browser then page gets rendered from server side and add button is not working.
Another Question is in server.js file html is getting generated with React.renderToStaticMarkup . In this example only one react component is there so data is passed to that component. What if I have more than 1 component and I have to pass data to each component. How can I achieve this?


text:
Q: Can I compare a function pointer to a function for equality? Is this valid C99 code? (I guess I'm asking whether it's portable)
void test(void){
return;
}

void (*fp)(void) = test;

if (fp == test){ <--- This line
    printf("Success\n");
}

I gather only pointers of the same type can be compared with one another, so maybe my question is whether function names like 'test' are just pointer aliases? Or maybe someone can tell me what my question is better than I can :)

A: The code is valid ANSI C.
Actually what happens is, a function name such as test in your code, is automatically converted to a pointer to function.
You could change test to &test, the result is the same.

A: Yes, it is fine. The C standard is pretty self-explanatory in this case (C11 6.3.2.1/4):

A function designator is an expression that has function type. Except when it is the
  operand of the sizeof operator, or the unary & operator, a function designator with
  type ''function returning type'' is converted to an expression that has type ''pointer to function returning type''.

In your case test is an expression with function type. It gets converted to a function pointer of void(*)(void) type. This is a compatible pointer type with fp, so the == operator allows it.
Regarding the equality operator ==, the standard says (C11 6.5.9, emphasis mine):

Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function,


text:
Q: Why does it take more time for molecules to diffuse in 2D than in 3D? The formula to calculate the time for molecules to travel over a distance of r units, r being the Euclidean distance, is given by $t = \frac{r^2}{4D}$ for a 2D environment, and $t = \frac{r^2}{6D}$ for a 3D environment ($D$ is the diffusion coefficient. Not to be confused with D in 2D and 3D which stands for dimension).
From these two formulae, we can easily observe that for the same r, t will be larger in 2D than in 3D. Why? This seems a little confusing since r is the same. Is there a proper explanation for this observation?
Thanks in advance.

A: As WYSIWYG pointed out in a comment, it comes from the fact that the particule has more degrees of freedom in 3D than in 2D.
If you consider a free particle, all its space degrees of freedom are independent, which means that its motion along the $x$-axis is not affected by its motion about the $y$-axis. The diffusion equation for the density of particles $n$ is
$D \Delta n = \frac{\partial n}{\partial t}$,
where $\Delta = \frac{\partial^2}{\partial x^2} + \frac{\partial^2}{\partial y^2}$ in 2D, and $\frac{\partial^2}{\partial x^2} + \frac{\partial^2}{\partial y^2} + \frac{\partial^2}{\partial z^2}$ in 3D. A simple dimensional analysis of this equation shows that the mean squared displacement along any of the axes $x$, $y$ or $z$ is given by
$<q^2> = D t$,
where $q$ stands for $x$, $y$ or $z$.
In 2D, the mean squared displacement is
$r^2 = <x^2> + <y^2> = 2 D t$
While in 3D, you get
$r^2 = <x^2> + <y^2> + <z^2> = 3 D t$.
Your result has a factor of $2$ more which comes from the fact that you can consider the radius of diffusion instead of the diameter of diffusion.


text:
Q: I want to store the ArrayList into offline storage everytime i click on the accept button and retrieve it when the app is reopened I want to store the Arraythat is in the ArrayList and save it even if the app is closed and reopened again. And i want to retrieve the values whenever the app is opened and display the results
    This is my MainActivity

package com.example.vineeth.customlistviewmytrail;

    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.support.v7.app.AlertDialog;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ListView;
    import android.widget.TextView;
    import android.widget.Toast;

    public class MainActivity extends AppCompatActivity {

        int test;
        EditText et_period1,et_period2,et_period3,et_period4,et_period5,et_period6,et_period7,et_period8;
        EditText et_number;
        TextView tv_head;

        Button bt_submit,bt_submit2;

        //

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            et_number = (EditText) findViewById(R.id.et_number);
            bt_submit = (Button)findViewById(R.id.bt_submit);
            bt_submit2=(Button)findViewById(R.id.bt_submit2);
            tv_head = (TextView)findViewById(R.id.tv_head);

            et_period1 = (EditText) findViewById(R.id.et_period1);
            et_period2 = (EditText) findViewById(R.id.et_period2);
            et_period3 = (EditText) findViewById(R.id.et_period3);
            et_period4 = (EditText) findViewById(R.id.et_period4);
            et_period5 = (EditText) findViewById(R.id.et_period5);
            et_period6 = (EditText) findViewById(R.id.et_period6);
            et_period7 = (EditText) findViewById(R.id.et_period7);
            et_period8 = (EditText) findViewById(R.id.et_period8);

            SharedPreferences.Editor editor = getSharedPreferences("text",MODE_PRIVATE).edit();
            editor.commit();
            SharedPreferences pref = getSharedPreferences("text",MODE_PRIVATE);

            int bouncer = pref.getInt("bounce",0);
            if(bouncer==0)
            {
                tv_head.setText("Enter for Monday");

            }
            else if(bouncer==1)
            {
                tv_head.setText("Enter for Tuesday");

            }
            else  if(bouncer==2)
            {
                tv_head.setText("Enter for Wednesday");

            }
            else if(bouncer ==3)
            {
                tv_head.setText("Enter for Thursday");
            }
            else if(bouncer==4)
            {
                tv_head.setText("Enter for Friday");
            }
            else if(bouncer==5)
            {
                tv_head.setText("Enter for Saturday");
            }
            else{
                Toast.makeText(this, "Thank you for Entering all your values", Toast.LENGTH_SHORT).show();
            }

            bt_submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String value = et_number.getText().toString();
                    test = 1;

                    if(value.isEmpty())
                    {
                        Toast.makeText(MainActivity.this, "Enter something", Toast.LENGTH_SHORT).show();
                    }
                    else {

                        int number = Integer.parseInt(value);

                        if (number < 2) {
                            Toast.makeText(MainActivity.this, "Enter valid value", Toast.LENGTH_SHORT).show();
                        }

                        if (number == 2) {
                            et_period1.setVisibility(View.VISIBLE);
                            et_period2.setVisibility(View.VISIBLE);
                            et_period3.setVisibility(View.INVISIBLE);
                            et_period4.setVisibility(View.INVISIBLE);
                            et_period5.setVisibility(View.INVISIBLE);
                            et_period6.setVisibility(View.INVISIBLE);
                            et_period7.setVisibility(View.INVISIBLE);
                            et_period8.setVisibility(View.INVISIBLE);
                        }
                        if (number == 3) {
                            et_period1.setVisibility(View.VISIBLE);
                            et_period2.setVisibility(View.VISIBLE);
                            et_period3.setVisibility(View.VISIBLE);
                            et_period4.setVisibility(View.INVISIBLE);
                            et_period5.setVisibility(View.INVISIBLE);
                            et_period6.setVisibility(View.INVISIBLE);
                            et_period7.setVisibility(View.INVISIBLE);
                            et_period8.setVisibility(View.INVISIBLE);
                        }
                        if (number == 4) {
                            et_period1.setVisibility(View.VISIBLE);
                            et_period2.setVisibility(View.VISIBLE);
                            et_period3.setVisibility(View.VISIBLE);
                            et_period4.setVisibility(View.VISIBLE);
                            et_period5.setVisibility(View.INVISIBLE);
                            et_period6.setVisibility(View.INVISIBLE);
                            et_period7.setVisibility(View.INVISIBLE);
                            et_period8.setVisibility(View.INVISIBLE);
                        }
                        if (number == 5) {
                            et_period1.setVisibility(View.VISIBLE);
                            et_period2.setVisibility(View.VISIBLE);
                            et_period3.setVisibility(View.VISIBLE);
                            et_period4.setVisibility(View.VISIBLE);
                            et_period5.setVisibility(View.VISIBLE);
                            et_period6.setVisibility(View.INVISIBLE);
                            et_period7.setVisibility(View.INVISIBLE);
                            et_period8.setVisibility(View.INVISIBLE);
                        }
                        if (number == 6) {
                            et_period1.setVisibility(View.VISIBLE);
                            et_period2.setVisibility(View.VISIBLE);
                            et_period3.setVisibility(View.VISIBLE);
                            et_period4.setVisibility(View.VISIBLE);
                            et_period5.setVisibility(View.VISIBLE);
                            et_period6.setVisibility(View.VISIBLE);
                            et_period7.setVisibility(View.INVISIBLE);
                            et_period8.setVisibility(View.INVISIBLE);
                        }
                        if (number == 7) {
                            et_period1.setVisibility(View.VISIBLE);
                            et_period2.setVisibility(View.VISIBLE);
                            et_period3.setVisibility(View.VISIBLE);
                            et_period4.setVisibility(View.VISIBLE);
                            et_period5.setVisibility(View.VISIBLE);
                            et_period6.setVisibility(View.VISIBLE);
                            et_period7.setVisibility(View.VISIBLE);
                            et_period8.setVisibility(View.INVISIBLE);
                        }
                        if (number == 8) {
                            et_period1.setVisibility(View.VISIBLE);
                            et_period2.setVisibility(View.VISIBLE);
                            et_period3.setVisibility(View.VISIBLE);
                            et_period4.setVisibility(View.VISIBLE);
                            et_period5.setVisibility(View.VISIBLE);
                            et_period6.setVisibility(View.VISIBLE);
                            et_period7.setVisibility(View.VISIBLE);
                            et_period8.setVisibility(View.VISIBLE);
                        }
                    }

                }
            });

            bt_submit2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if(test==1)
                    {
                        String period1,period2,period3,period4,period5,period6,period7,period8;

                        period1 = et_period1.getText().toString();
                        period2 = et_period2.getText().toString();
                        period3 = et_period3.getText().toString();
                        period4 = et_period4.getText().toString();
                        period5 = et_period5.getText().toString();
                        period6 = et_period6.getText().toString();
                        period7 = et_period7.getText().toString();
                        period8 = et_period8.getText().toString();

                        Intent i = new Intent(MainActivity.this,Main2Activity.class);
                        i.putExtra("period1",period1);
                        i.putExtra("period2",period2);
                        i.putExtra("period3",period3);
                        i.putExtra("period4",period4);
                        i.putExtra("period5",period5);
                        i.putExtra("period6",period6);
                        i.putExtra("period7",period7);
                        i.putExtra("period8",period8);

                        startActivity(i);

                    }

                    else
                    {
                        Toast.makeText(MainActivity.this, "Enter values first", Toast.LENGTH_SHORT).show();
                    }

                }
            });

        }
    }

My SecondActivity
This is my secondactivity

package com.example.vineeth.customlistviewmytrail;

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

public class Main2Activity extends AppCompatActivity {
    ListView lv_list;
    Button bt_confirm,bt_clear;
    ArrayList<String> list = new ArrayList<String>();
int bouncer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    lv_list = (ListView)findViewById(R.id.lv_list);
    bt_confirm = (Button)findViewById(R.id.bt_confirm);
    bt_clear = (Button)findViewById(R.id.bt_clear);

    final Intent i = getIntent();
    final String value1 = i.getStringExtra("period1");
    list.add(value1);
    String value2 = i.getStringExtra("period2");
    list.add(value2);
    String value3 = i.getStringExtra("period3");
    list.add(value3);
    String value4,value5,value6,value7,value8;
    value4=i.getStringExtra("period4");
    list.add(value4);
    value5=i.getStringExtra("period5");
    list.add(value5);
    value6=i.getStringExtra("period6");
    list.add(value6);
    value7=i.getStringExtra("period7");
    list.add(value7);
    value8=i.getStringExtra("period8");
    list.add(value8);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);

    /*JSONObject json = new JSONObject();
    json.put("arrays",new JSONArray(list));
    String arrayList = json.toString();*/

    lv_list.setAdapter(adapter);

    bt_confirm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            SharedPreferences.Editor editor = getSharedPreferences("text",MODE_PRIVATE).edit();
            SharedPreferences pref = getSharedPreferences("text",MODE_PRIVATE);

            bouncer = pref.getInt("bounce",0);

            bouncer = bouncer + 1;

            Intent intent = new Intent(Main2Activity.this,MainActivity.class);

            editor.putInt("bounce",bouncer);
            editor.commit();

           // Toast.makeText(Main2Activity.this, bouncer, Toast.LENGTH_SHORT).show();

            startActivity(intent);

        }
    });

    bt_clear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            SharedPreferences.Editor editor = getSharedPreferences("text",MODE_PRIVATE).edit();
            bouncer=0;
            editor.clear();
            editor.commit();

            Intent intent = new Intent(Main2Activity.this,MainActivity.class);
            startActivity(intent);

        }
    });

}

}

A: I got a rather easy solution to my question .
I used 2 functions to convert the Array to String format separating by a comma and the other function to convert string back to array by using split.
I stored the string easily in SharedPreferences in a string format and retrieved them back when i wanted and converted them back.
converting array to string code
public String convertArrayToString(String[] array)
    {
        String str = "";
        for(int i=0;i<array.length;i++)
        {
            str = str+array[i];

            if(i<array.length-1)
            {
                str = str+strSeperator;
            }
        }
        return  str;
    }

converting String to array code
 public static String[] convertStringToArray(String str)
    {
        String[] arr = str.split(strSeperator);
        return arr;
    }

and then simply
converted the ArrayList to normal array
like this
String[] toArray = list.toArray(new String[list.size()]);

and then
I used the convertArrayTostring function and directly stored in a sharedpref file
 editor.putString("MondayList",convertArrayToString(toArray));

A: You can store it in database or shared preferences.

*

*Define your model which you can use to store some data in SharedPreferences

*Add Gson to libraries

*Get SharedPreferences
More information about SharedPreferences
final String key = "example"; // constant key to retrieve data, must be unique
final String prefName = "example2" // constant name for preference file
final SharedPreferences pref = context.getSharedPreferences(prefName, Context.MODE_PRIVATE)

final Gson gson = new Gson();

// put data
pref.edit().putString(key, gson.toJson(model)).apply();

// get data
final String serialized = pref.getString(key, null); // if there is no data in preferences yet, it returns null
if (serialized == null){
    // handle no saved data state
} else {
   final Model model = gson.fromJson(serialized, Model.class);
}

That's all. You can make separate methods for every operations, wrap into interface and implement somewhere or make simple PreferenceStorage / Helper class for easy access and keep clean architecture.

A: Please try the following code:
For Saving:
String mySavedList= new Gson().toJson(list);
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("My_SAVED_LIST", mySavedList).commit();

For Retrieving:

ArrayList<String> myList = new Gson().fromJson(PreferenceManager.getDefaultSharedPreferences(this).getString("My_SAVED_LIST", ""), new TypeToken<ArrayList<String>>() {
                }.getType());


text:
Q: Getting specific span tag text in python (BeautifulSoup) Im scraping some information off MyAnimeList using BeautifulSoup on python3 and am trying to get information about a show's 'Status', but am having trouble accessing it.
Here is the html:

Information

        Type:
        Movie

        Episodes:
        1

        Status:
        Finished Airing

All of this is also contained within another div tag but I only included the portion of the html that I want to scrape. To clarify, I want to obtain the text 'Finished Airing' contained within 'Status'.
Here's the code I have so far but I'm not really sure if this is the best approach or where to go from here:
Page_soup = soup(Page_html, "html.parser")
extra_info = Page_soup.find('td', attrs={'class': 'borderClass'})
span_html = extra_info.select('span')
for i in range(len(span_html)):
    if 'Status:' in span_html[i].getText():

Any help would be appreciated, thanks!

A: To get the text next to the  with "Status:", you can use:
from bs4 import BeautifulSoup

html_doc = """

Information

        Type:
        Movie

        Episodes:
        1

        Status:
        Finished Airing

"""

soup = BeautifulSoup(html_doc, "html.parser")
txt = soup.select_one('span:-soup-contains("Status:")').find_next_sibling(text=True)
print(txt.strip())

Prints:
Finished Airing

Or:
txt = soup.find("span", text="Status:").find_next_sibling(text=True)
print(txt.strip())

A: Another solution (maybe):
f = soup.find_all('span',attrs={'class':'dark_text'})
for i in f:
     if i.text == 'Status:':
         print(i.parent.text)

And change 'Status:' to whatever other thing you want to find.
Hope I helped!


text:
Q: Python win32com constants I'm currently wondering how to list the constants in win32com in python,
for example using excel win32com.client.Dispatch('Excel.Application')
Is there a way to display all constants using win32com.client.Constants ?
Or does someone know where i could find win32com's documentation ? Because all the links I found are dead ...

A: To find out what Com applications you can use... See http://timgolden.me.uk/pywin32-docs/html/com/win32com/HTML/QuickStartClientCom.html
Basically you can't know for sure. Sorry.
Each computer will have a different list based on the software installed, the webpage I linked suggests using pyWins ComBrowser, however I haven't ever found it that useful.
My normal approach is
'I want to interface with application X in Python... lets google "python com X" and see what comes up'
or
'I want to interface with application X in Python.. lets look through the documentation of AppX for references to COM'
Afterall you'll want to have some form of documentation to that programmes COM interface in order to be able to do anything meaningful with the program (other than opening it).

A: The answer given by @CastleH in his comment pointed me in the right direction: help() helped me a lot, but you have to use it on module-level!
For example,
import win32print
help(win32print)

gives you all constants in win32print. You can do the same for every module in win32com (for a full list of modules see the win32com documentation, section modules).
Using help(win32com)did not help me a lot since it is mainly listing the packages

A: To list available constants, you can do something like:
import win32com

for k, v in win32com.client.constants.__dicts__[0].items():
    print("{:<45}: {}".format(k, v))

#  __module__                                   : win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x9
#  xl3DBar                                      : -4099
#  xl3DEffects1                                 : 13
#  xl3DEffects2                                 : 14
#  xl3DSurface                                  : -4103
#  ...

The best resource for pywin32, even in 2020 (16+ years after its creation), is the source code1.
It turns out that win32com.client.constants is an instance of the Constants class:
class Constants:
  """A container for generated COM constants.
  """
  def __init__(self):
    self.__dicts__ = [] # A list of dictionaries
  def __getattr__(self, a):
    for d in self.__dicts__:
      if a in d:
        return d[a]
    raise AttributeError(a)

# And create an instance.
constants = Constants()

The constants are all stored in self.__dicts__ which is a list of dictionaries.  That list happens to contain only a single dictionary.
Knowing this, you can iterate through the dictionary (as done above) to see what constants are available.

1 For dead links, try The Internet Archive's Wayback Machine.  There are plugins for various browsers which make searching for archived versions of a page easy or automatic.


text:
Q: How to reduce size of string arm assembly I'm trying to make a assembly program to add two numbers, but when I type in the numbers it includes the \n at the end of the script meaning that when I do
add R3,R2,R1

it includes \n as a number
when I run strace it it shows that the program is printing two null terminators \0\0
picture of the program running and the program running with strace
the code is as follows
    .data
    keyin: .space 20
    num1: .space 2
    num2: .space 2
    num3: .space 3
    addmsg1: .ascii "enter a number: "
    addmsg2: .ascii "enter another number: "
    addmsg3: .ascii "the sum of those numbers are: "
    addcode: .ascii "add\n"

    .text
    .global _start:
_start:
    ldr R1,=addmsg1
    mov R2,#16
    bl print

    ldr R1,=num1
    mov R2,#2
    bl input

    ldr R1,=addmsg2
    mov R2,#22
    bl print

    ldr R1,=num2
    mov R2,#2
    bl input

    ldr R1,=num1
    ldr R1,[R1]
    ldr R2,=num2
    Ldr R2,[R2]
    add R3,R2,R1
    ldr R2,=num3
    str R3,[R2]
    ldr R1,=addmsg3
    mov R2,#30
    bl print

    ldr R1,=num3
    mov R2,#2
    bl print

print:
    mov R7,#4
    mov R0,#1
    SWI 0
    bx lr

input:
    ldr R1,=keyin
    mov R7,#3
    mov R0,#0
    SWI 0
    bx lr

I don't want to keep the \n when I type in the number but I have to accept it as part of the input otherwise if I typed 3 for the first number the \n would go into the second number as the input
I want to shorten the string to just one byte so that only the numbers are present
im uing rpi 4
arm V8-a
raspbian buster (for the syscalls)
any help would be welcome if you need more info just ask


text:
Q: Dealing with resources (copying) when building a ClojurScript project using leiningen I have just begun playing with ClojureScript and I'd like to collect all CSS files into a single folder (out/css).  I found leiningen-less and with the following config I get the compiled CSS files into the correct location:

  :less {:source-paths ["src/less"]
         :target-path "out/css"}

I can't find any documentation on how I can handle the ordinary CSS files (e.g. the file for resetting defaults, css/reset.css).  Basically I want the equivalent of cp css/*css out/css.
I did find lein-resource but it does a bit more than I require (pass things through stencil) and more importantly it through an UnsupportedOperationException on my with what I thought would a be a valid configuration:

  :resource {:resource-paths ["css" {:target-path "out/css"}]}

Please englighten me!

A: For your particular use case just rename reset.css to reset.less. less should be able to read CSS without problems.
For more advanced frontend tooling maybe consider adding something like make/grunt/etc. More complexity but more power & flexibility.

A: I think better and easy solution would be that you write a function that uses clojure.java.io library functions and integrate them with lein-less "compiler" fork, so this is my internal function proposal:
(defn your-fn[]
  (remove-folder "./out") ;; => you have to do how to make that fn following io lib doc
  (copy-folder "./css ./out") ;; ;; => you have to do how to make that fn following io lib doc
  (run-compiler  :javascript
                 {:project-root "your-project-root/"
                  :source-paths ["less"]
                  :target-path "out"})))

PS: note that you need to call this fn from your clojurescript compilation process, BTW I didn't know if there is a way for that :)