text:
Q: How do I get a FlatList to show correct items when I open the screen? The idea is to have a toggle switch that switches from To Watch and Watched bookings. When I update a movie in the To Watch list, I want it to rerender the FlatList without that booking because it's now in the Watched list. And so when I press the toggle to see the Watched list I would now see the booking there. Same for reverse.
I have to press the toggle twice to see the change. Even when I open the screen for the first time it shows all the movies without the filter - this is the main thing I'm having trouble with. How can I get around this? This is the code I have:
const WatchList = () => {

  const uid = auth.currentUser.uid;
  const docRef = doc(db, 'users', uid);
  const [user, setUser] = useState({});
  const [watched, setWatched] = useState(true);
  const [text, setText] = useState('To watch');
  const [filteredBookings, setFilteredBookings] = useState(bookings);

  const bookingsRef = collection(db, "booking"); // imamo ref ka bazi

  const [bookings, setBookings] = useState({});
   useEffect(() => {
    getUser();
    getBookings();
  },[])

  const getUser = async () => {
    const snap = await getDoc(docRef)
    setUser({user, ...snap.data()})
  }

  const getBookings = async () =>{
    const q = query(bookingsRef, where("users","array-contains",auth.currentUser.uid));
      const unsubscribe = onSnapshot(q, (querySnapshot) => {
        const a = [];
        querySnapshot.forEach((doc) => {
        a.push(doc.data());
      });
      setBookings(querySnapshot.docs);
    });
  }

  const toggleSwitch = () =>{
    if(!watched){
      setFilteredBookings(bookings.filter(function(item){
        return item.data().watched == true;
      }))
      setText('Watched');
    } else {
      setText('To watch');
      setFilteredBookings(bookings.filter(function(item){
        return item.data().watched == false;
      }))
    }
    setWatched(previousState => !previousState);
  }

  const updateBooking = async(id) => {
    try {
      await setDoc(doc(db, 'booking', id), {
        watched: true
      }, {merge: true})
    }
    catch(e) {
      console.log(e)
    }
  }

  const updateBooking1 = async(id) => {
    try {
      await setDoc(doc(db, 'booking', id), {
        watched: false
      }, {merge: true})
    }
    catch(e) {
      console.log(e)
    }
  }

  const deleteBooking = async(id) => {
    try {
      await deleteDoc(doc(db, 'booking', id));
    }
    catch(e) {
      console.log(e)
    }
  }

  useEffect(() => {
    const resultOfFiltering = bookings
    setFilteredBookings(resultOfFiltering)
  }, [bookings])

  return (
    <View>
      <View>
        <Text>{text}</Text>
        <Switch
          value = {watched}
        />
      </View>

  <FlatList
    data = {filteredBookings}
    extraData = {watched}

    renderItem  = {({item}) => (
      <View>
      <View>
        <Text>{item.data().movie}</Text>
        <Text>{item.data().day} - {item.data().showtime}</Text>
      </View>
      <View>
        {item.data().watched == true ? (
            <TouchableOpacity style = {styles.delete} onPress = {() => {updateBookings(item.id); setFilteredBookings();}}>
            <Image source={require('../assets/watched.png')}/>
            </TouchableOpacity>
        ) : (
        <TouchableOpacity onPress = {() => {updateBookings1(item.id); setFilteredBookings();}}>
        <Image source={require('../assets/towatch.png')}/>
        </TouchableOpacity>)}

        <TouchableOpacity onPress = {() => {deleteBooking(item.id); setFilteredBookings();}}>
          <Image source={require('../assets/remove.png')}/>
        </TouchableOpacity>
      </View>
      </View>
    )}
  />
      </View>
  )
}

export default WatchList

It's not really working properly at the moment and I'm not sure what I'm doing wrong so I'm kind of stuck. If I could get some help, I'd really appreciate it. Thank you!


text:
Q: simplifying a MYSQL query, and fixing I've been trying to get this complex MYSQL query to work exactly right over the last few days, of course because it's got so many aspects to it that effect it it's difficult to surely know that it's 100% working correctly, and I'm not at all good with more complex MYSQL queries. also this query that I have now is quite messy, so the data it returns is a little scattered, and I'm not exactly sure how to address this issue. I've read through MYSQL Join and everything and I sort of understand it, but I'm not sure which to use in my case, and how to use them properly.
Here's my current query that works as it should. (just needs cleaning up, I think, so I don't have to have redundant values)
$notificationsq = mysql_query("SELECT
N.*,
N.fromID,
N.date,
N.id AS ID,   //I have to do this because if I don't it doesn't return anything,
              ///I guess because it joins 3 tables with the id column. not sure
              ///how to call the correct data.
MIN(N.state) AS State,
MAX(N.date) AS newDate,
P.*,
C.*,
P.id AS uniqueID
FROM notifications N
LEFT JOIN comments C ON N.action = 2 AND N.uniqueID = C.id AND C.state=0
LEFT JOIN posts P ON N.action = 1 AND P.id = N.uniqueID
OR N.action = 2 AND P.id = C.postID
WHERE N.userID = '$session'
AND (N.action = 1 AND N.state IN (0, 1) OR N.action = 2)
AND P.state = 0

GROUP BY P.id
ORDER BY
State ASC,
newDate DESC

 ") or die(mysql_error());

My table structure:
Table: notifications

id  UserID  FromID  UniqueID    Action  State   Read_Date   Date
1   1       2       1           1       0       0           1325993600
2   1       6       2           1       0       0           1325993615
3   1       2       1           2       0       0           1325993622
4   1       6       2           2       0       0           1325993661
5   2       6       2           2       0       0           1325993661

Action = 1 means UniqueID identifies a column in Posts;
Action = 2 means UniqueID identifies a column in Comments.
Table: posts

id  ToID    FromID  Post        State   Date
1   1       2       Hey         0       1325993600
2   1       6       okay yeah   0       1325993615

Table: comments

ID  PostID  FromID  Comment     State   Date
1   1       2       lol         0       1325993622
2   1       6       ohh         0       1325993661

So, in the Notifications table where action is 2, the UniqueID's are for the 'id' in the Comments table.
What I want to return is the PostID, so in the query it would just be as if the UniqueID was this instead:
1
2
1
1
1

A: If your state = 0 filter limits the connection to the comments, then the inner join on the posts could filter out the result, try making that a left join as well to test.
You should have a prefix on your ORDER BY clause (either ORDER BY P.State or N.State).
The reason you're having an error with the N.id is that the id is already selected with the N.*
You're better to use an ENUM type to deal with multiple states.  This leads to more readable SQL with the same performance (ie. N.action = 'add', instead of 2)
Avoid any select *, it's error prone and the performance isn't as good as the manual alternative.
As far as cleaning up, I find it much easier to read with clean whitespace and names:
SELECT notifications.*
     , notifications.fromID
     , notifications.date
     , MIN(notifications.state) AS State
     , MAX(notifications.date) AS newDate
     , posts.*
     , comments.*
     , posts.id AS uniqueID
FROM notifications
LEFT JOIN comments ON notifications.action = 2
                  AND notifications.uniqueID = C.id
                  AND comments.state = 0
LEFT JOIN posts ON (notifications.action = 1 AND posts.id = notifications.uniqueID)
                OR (notifications.action = 2 AND posts.id = comments.postID)
WHERE notifications.userID = '$session'
  AND (notifications.action = 1 AND notifications.state IN (0, 1) OR notifications.action = 2)
  AND posts.state = 0
GROUP BY posts.id
ORDER BY notifications.State ASC
       , newDate DESC

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to save a list of functions as an object in Python3 I'm working on a filter. For each case, I have a list of functions to process the input data, which differs from case to case.
I want to serialize and save such list of function, so that I can load and use functions for each case. I tried to use pickle to dump the list as a pkl file, but it cannot be load if I delete the definition of functions.
To deliver it more explicitly, it runs like this
def a1(obj):
    pass

def a2(obj):
    pass

def b1(obj):
    pass

def b2(obj):
    pass

a_func = [a1, a2]
b_func = [b1, b2]

if obj.flag == 1:
    for fun in a_func:
        fun(obj)
elif obj.flag == 2:
    for fun in b_func:
        fun(obj)

and I want to save such a_func and b_func as pkl file or so.
I don't know how to save them as py. I need to deal with more than 100 cases, and each case may need about 10 functions, most of which are in common. I don't want type them manually.

A: Here you can try like this, using exec() and store string names of the functions in lists:
class obj:
  def __init__(self):
    self.flag = 1

def a1(obj):
    pass

def a2(obj):
    pass

def b1(obj):
    pass

def b2(obj):
    pass

a_func = ['a1', 'a2']
b_func = ['b1', 'b2']
objg = obj()

if objg.flag == 1:
    for fun in a_func:
        exec('{x}(objg)'.format(x=fun))
elif objg.flag == 2:
    for fun in b_func:
        exec('{x}(objg)'.format(x=fun))

A: You can define functions that use functions such as:
def a1(obj):
    result = obj+1
    return result

def a2(obj):
    result = obj*3
    return result

def a1_a2(obj):
   result1 = a1(obj)
   result2 = a2(result1)
   return result2

then calling a1_a2 will do a1 first and apply a2 to the result of a1.
If you save the code to say filters.py you can do in any other programm in the same directory:
from filters import a1_a2


text:
Q: Is there an easy common gis abstraction available in .Net Is there an easy common gis abstraction available in the .Net programming world that cuts the dependency to a concrete gis implementation, e.g. to the esri silverlight/wpf sdk.
... for example OpenLayers is such a library for several map providers in JavaScript. By using an IoC container (like Spring.Net) the dependency could be hidden. I noticed the GeoAPI buth this seems too complex for an easy abstraction level, I think.


text:
Q: jQuery javascript regex Replace  with \n How do i write a regex to replace
 or
  with \n. I'm trying to move text from div to textarea, but don't want
's to show in the textarea, so i want to replace then with \n.

A: True jQuery way if you want to change directly the DOM without messing with inner HTML:
$('#text').find('br').prepend(document.createTextNode('\n')).remove();
Prepend inserts inside the element, before() is the method we need here:
$('#text').find('br').before(document.createTextNode('\n')).remove();

Code will find any
 elements, insert raw text with new line character and then remove the
 elements.
This should be faster if you work with long texts since there are no string operations here.
To display the new lines:
$('#text').css('white-space', 'pre-line');

A: a cheap and nasty would be:

jQuery("#myDiv").html().replace("
", "\n").replace("
", "\n")

EDIT
jQuery("#myTextArea").val(
    jQuery("#myDiv").html()
        .replace(/\
/g, "\n")
        .replace(/\
/g, "\n")
);

Also created a jsfiddle if needed: http://jsfiddle.net/2D3xx/

A: var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/
/gi, "\n");

or using jQuery:
var str = $("#mydiv").html();
var regex = /
/gi;
$("#mydiv").html(str.replace(regex, "\n"));

example
edit: added i flag
edit2: you can use /
]*>/gi which will match anything  between the br and slash if you have for example

A: Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:
<textarea id="ta0"></textarea>
<button onclick="
  var ta = document.getElementById('ta0');
  var text = 'some
text
to
replace';
  var re = /
/gi;
  ta.value = text.replace(re, '\n');
">Add stuff to text area</button>

A: myString.replace(/
/g, "\n")


text:
Q: Fast switching between fragments crush my app, how can I avoid that? I'm newbie in programming.
I'am adding entries to spinner with data from firebase, everything is ok, but when im fast switching between fragments, error occurs.
I know the problem is that im using "getActivity" while using fragment, and the code is still excecuting, while the fragment is not attached anymore. And thats the problem.
Is there any posibility to attach adapter to spinner from an activity instead of from fragment?
Imo that could avoid that problem, but i dont know how to do that?
Here is some code.

                ArrayAdapter dania = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, menulist);  //I KNOW THAT THE PROBLEM IS HERE getActivity()

                ArrayAdapter adodatki = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, menudodatkilist); //I KNOW THAT THE PROBLEM IS HERE getActivity()

                dania.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                adodatki.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                danie1spinner.setAdapter(dania);
                danie2spinner.setAdapter(adodatki);

I'm open for all suggestions.
Thanks for all answers :)

A: Thanks @SteveM,
For me it worked to use
if (getActivity() != null)
{
 ArrayAdapter dania = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, menulist);  //I KNOW THAT THE PROBLEM IS HERE getActivity()

                ArrayAdapter adodatki = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, menudodatkilist); //I KNOW THAT THE PROBLEM IS HERE getActivity()

                dania.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                adodatki.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                danie1spinner.setAdapter(dania);
                danie2spinner.setAdapter(adodatki);
}

thanks one more time for an easy idea :D

A: ArrayAdapter requires a Context as the first parameter. Simply pass the Context of the Fragment instead. (I think it's GetView())


text:
Q: How reusable Android libraries operate (development, deployment etc) I am trying to create reusable library for my Android project. The library will include resources. Unfortunately, I can't find any decent explanation on how Android libraries operate.
Android reference just says how to set up Eclipse project and Ant project. I am using Maven and IntelliJ. And I would figure how to set them up if I could find any suitable description on how all pieces work together.
So I wonder if someone wants to take a pick and try to explain it. And here are some of my open questions.
Lets say I have project AndroidApp which has AndroidManifest.xml with package app.foo and produces AndroidApp.apk.
I also have project AndroidLib with package app.bar. What do I need in the AndroidManifest.xml for AndroidLib? Is just declaring package sufficient or there should be something else?
Now, I want to have resources in both and refer to resources in AndroidLib from AndroidApp. Do I just call lib.bar.R? Some posts suggest that there will be no id conflicts. True or false?
What is deliverable artifact for AndroidLib? Is it also apk? How do I deploy both? Or more importantly, can I produce single apk that would include AndroidApp and AndroidLib?
How do projects relate to each other in development environment? For example, in IntelliJ I tried to just include module with AndroidLib in AndroidApp but it just compiled resources into AndroidApp. (Possibly I missed uses-libary). If I would use javac and Android tools, what would be the sequence?
Anything else worth knowing?
Anyway. I'd appreciate if someone could share there knowledge base on that matter.

A: I have written a detailed post about this: Android Application, Android Libraries and Jar Libraries.
If you want to mimic the way original Android build system behaves, then the best way is to run
ant debug -d

on a project that uses Android Library ( or Android libraries ).
This will give you all command lines ant runs to create R.java files, compile code and package the final .apk file. This is basically the best reference you can find right now. Though note that Android's build system is evolving and you'll need to keep your build system in sync with the original one.

A: Ok, I'm no expert in this, but these are my thoughts (which could be wrong):
As far as I can say, there is strictly speaking not really such a thing as "Libraries" on Android. There are basically three options:

*

*Let the "Lib" project be a "normal" Java project and add that project to the build path of the "App" project. The "Lib" can then only contain Java code, which is compiled and added normally to the "App"s APK. Since an app running on a device can't access another app's code, if you'd want to reuse the "Lib" in second Android app, it would have to include a copy of the (compiled) lib code in its APK. This also means the lib cannot contain any resources, because they need to be in the corresponding directories in the "App" project.

*Similar to #1, but you have the Lib code compile into a regular Java library (jar), which you copy/compile into the lib directory of the "App" project. Other than that it would have the same limitations as #1, so that any app you reate would have to include a copy of the JAR in it's APK.

*Have the "Lib" project be a full grown stand alone app and define an API using custom Intents have have all communication between "Lib" and "App" run over them. This requires the "Lib" and "App" to be distributed separately, so that a user will need to manually install both. However this allows you to create additional apps that can reuse the functionality of the "Lib" app without including duplicate code.

A: I have recently merged in the library projects support in the samples project for the Maven Android Plugin. Just see how it all works by checking out how they are set up.
https://github.com/jayway/maven-android-plugin-samples


text:
Q: Validity of a functional formula of the Riemann Zeta function across the whole complex plane? Could someone confirm me the validity of the following formula:
$$\zeta\left(z\right)=2^{z}\pi^{z-1}\sin\left(\frac{\pi z}{2}\right)\left(\frac{e^{-\gamma \left(1-z\right)}}{1-z}\prod_{n=1}^{\infty}\frac{e^{\frac{1-z}{n}}}{1+\frac{1-z}{n}}\right)\zeta\left(1-z\right)$$
for the Riemann Zeta function accross the entire complex plane ?
EDIT: another non-related question: is the notation without parenthesis ambiguous for a mathematician?
$$\zeta\left(z\right)=2^{z}\pi^{z-1}\sin\left(\frac{\pi z}{2}\right)\frac{e^{-\gamma \left(1-z\right)}}{1-z}\prod_{n=1}^{\infty}\frac{e^{\frac{1-z}{n}}}{1+\frac{1-z}{n}}\zeta\left(1-z\right)$$


text:
Q: Is there a mutual folder where I can save and load data using a simulator or my device? I'm currently saving my data in Document Directory, using this code :
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

let archiveURL = documentsDirectory.appendingPathComponent("myData").appendingPathExtension("plist")

let pListEncoder = PropertyListEncoder()
        if let encodedTableArray = try? pListEncoder.encode(myData) {
            try? encodedTableArray.write(to: archiveURL, options: .noFileProtection)
        }

When I print documentsDirectory, whether my app is running on a simulator or my device (plugged to my computer), paths are not similar :
file:///Users/userName/Library/Developer/CoreSimulator/Devices/E80B48AB-C269-48ED-9AF4-AC55C34C911E/data/Containers/Data/Application/D3C87E08-DC0E-4F53-ABC7-C930DFAC4EF8/Documents/
file:///var/mobile/Containers/Data/Application/F5BE0EB0-F2C7-4842-B039-01D5F8CCA4A2/Documents/ ,
respectively.
Is there a path that can be accessed by both simulators and devices ?
PS : I'm using this path just because I read that it's supposed to be the most appropriate path when saving my kind of data (something like a list of tables), I'm still learning about persistency so I'm not fully understanding why however.
Thank you for your help !


text:
Q: How to make google map marker in center with proper alignment i am using google maps for my project in rails 4, ruby 2, and gmaps4rails '1.5.6'
but the problem is i am not getting marker at center of the map as well as the zoom in zoom out side bar is also not coming.
If any one have any idea about this problem please reply?
Model Action
acts_as_gmappable
def gmaps4rails_address
    html = full_address(city_id,state_id,country_id)
    self.location = (location + html)
    location
end
def full_address(city_id,state_id,country_id)
      city_name = MdmCity.get_city_name(city_id)
      state_name = MdmState.get_state_name(state_id)
      country_name = MdmCountry.get_country_name(country_id)
      html = "#{city_name} #{state_name} #{country_name}"
      html
 end
Controller Action
def edit_content
  @location_json = SeoContent.where(:id => params[:id]).first.to_gmaps4rails
end
VIEW

  <%= gmaps4rails(@location_json) %>

Issues for me.
1) Zoom In and Zoom out bar is not coming.
2) Marker is not coming at center.
3) How to give Info window.
4) How to raise that address is Invalid, which is not present on google map (Eg:kdjfkdfhdkfhd)
5) Why this action (def gmaps4rails_address) is calling automatically.
6) I want to call def gmaps4rails_address from update action too how ?
7) Map is coming only one forth ?why
8) Can i show directions on map ?
Thanks


text:
Q: How to find the roots in the field $\mathbb Z_p$? Considering the field $\mathbb Z_p$ in which $p$ is a prime; how many of roots satisfying $$x^2+1=0$$
I tried to look into $p=2,3,5,7$, but didn't find a rule for that. Is it that the number of roots depends on the value of $p$?  Or there's a pattern that I didn't see. Thanks you.

A: Yes, the answer depends on $p$:

*

*If $p \equiv 1 \mod 4$, then there are two distinct roots of $x^2 + 1$,

*If $p \equiv 3 \mod 4$, then there are no roots,

*If $p = 2$, then $1$ is a double root of $x^2 + 1$.
To see the first case, remember that the multiplicative group of $\mathbb{Z}/(p)$ is cyclic of order $p-1$. Let $g$ be a generator of the cyclic group; then $(p-1)/4$ is an integer and $g^{(p-1)/4}$ will be a primitive fourth root of $1$, i.e., a square root of $-1$. In the second case, where $4$ does not divide $p-1$, there can be no primitive fourth root (i.e., an element "$i$" of order $4$).

A: Taking a cue directly from Wikipedia, we have the result "$x^2+1\equiv 0\mod p\text { is solveable }\iff p\equiv 1\mod 4.$"  This has the additional constraint that $p\gt 2$ since that case has the double root $x=1$ while $2\equiv 2\ne 1\mod 4.$

A: Is $\mathbb{Z}_p$ the $p$-adic numbers, or the finite field with $p$ elements? $\mathbb{F}_p$ is an unambiguous notation for the latter. (both will have the same answer, though)
Let's solve:
$$ x^2 + 1 \equiv 0 $$
$$ x^2 \equiv -1 $$
$$ x \equiv \pm \sqrt{-1} $$
So, we need $-1$ to have a square root in $\mathbb{Z}_p$ for this to work.
There are simpleways to approach this:

*

*Use the standard tool to compute whether some number is a square modulo $p$

*Use what you know about the group of units to determine if $\mathbb{Z}_p$ has a fourth root of unity.


text:
Q: Pass user to SharePoint 2013 when integrating document from BizTalk 2013 SharePoint adapter I'm able to create a user specifically for integrations and enter the corresponding credentials when configuring my WSS send port. This works fine, however, as expected, when I view the document in SharePoint, the "Modified By" user on the document is the integration user.
Is there a way that I can set the modified by field in SharePoint dynamically? That is, the user that actually initiates the integration? (I have the user's information available when the adapter sends the document to SharePoint, I'm just unsure of how to tell SharePoint to impersonate the integration as a specific user).


text:
Q: Simple software for mapping residential address in Singapore I am new to GIS and I recently have a project where we will like to map clinic addresses vs patients' address, to show the distance between these locations.
In addition, at each clinic address, a number of patients would have visited for either chronic or acute visit. I will like to be able to illustrate the different type (acute or chronic) of visits, as well as the number of visits (9 acute vs 5 chronic for Clinic XXX).
Lastly, we will need to do this on a regular basis (meaning we will have a continuous feed of address that we will key in periodically), and also to layer the different maps (options to select, unselect layers).
Is there any simple freeware or software out there that can readily do this? My colleague has recently learnt ArcGIS, but I feel that it's an overkill.


text:
Q: if product is in cart add class to add to cart button in woocommerce I'm working on woocommerce project and I want to add a new class on Add to Cart button if product is already added in cart, Can you help me to find out with this.
I'm changing right now using this code
add_filter( 'woocommerce_product_single_add_to_cart_text', 'bbloomer_custom_add_cart_button_single_product' );
function bbloomer_custom_add_cart_button_single_product( $label ) {

foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
    $product = $values['data'];
    if( get_the_ID() == $product->get_id() ) {
        $label = __('Added', 'woocommerce');
    }
}

return $label; }

text is changing but I want add class so I can add my css style
please help Thank You

A: The add to cart template which is in woocommerce/templates/loop/add-to-cart.php has a filter. So we can also over write the class using add_filter function in functions.php.
function woocommerce_custom_add_to_cart_class ( $html, $product, $args ) {
    // Define the classes to be added
    $class_to_append = "this_guys_in_cart";

    // Check if product is in cart
    $in_cart = WC()->cart->find_product_in_cart( WC()->cart->generate_cart_id( $product->get_id() ) );

    if ( $in_cart != '' ) {
        // Append the extra class
        $args['class'] = $args['class']." {$class_to_append}";

        $html = sprintf( '%s',
            esc_url( $product->add_to_cart_url() ),
            esc_attr( isset( $args['quantity'] ) ? $args['quantity'] : 1 ),
            esc_attr( isset( $args['class'] ) ? $args['class'] : 'button' ),
            isset( $args['attributes'] ) ? wc_implode_html_attributes( $args['attributes'] ) : '',
            esc_html( $product->add_to_cart_text() )
        );
    }

    // Return Add to cart button
    return $html;
}

add_filter( "woocommerce_loop_add_to_cart_link", "woocommerce_custom_add_to_cart_class", 10, 3 );

Note: This method is not recommended if add-to-cart.php filte is modified in theme templates


text:
Q: Python: Type error: method receives more arguments than the ones given I have created this class to determine the normalisation function of a distribution.
Here is the class with relative main:
class Normaliser(object):

    def funcN(f, xIni, xFin, yIni, yFin):

        return sym.integrate(f, (x, xIni,
        xFin), (y, yIni, yFin))

def main():
    f = (1+sym.cos(x)**2)*sym.exp(-y/t)
    g = (3*sym.sin(x)**2)*sym.exp(-y/t)
    xIni = 0.
    xFin = 2*pi
    yIni = 0.
    yFin = 10.
    tau1 = 1.
    tau2 = 2.
    *funcN1 = Normaliser().funcN(f, xIni,
    xFin, yIni, yFin)*
    *funcN2 = Normaliser().funcN(g, xIni,
    xFin, yIni, yFin)*

When I run the tester I get the following error in the emphasised lines:
TypeError: funcN() takes exactly 5
arguments (6 given)

I really don't understand where this error is arising from considering that there is no self in the method. If anybody has any idea of a possible reason and possibly for a solution as well, I would be very grateful. Thanks in advance!

A: As  regular member function of the Normaliser class, funcN is passed the Normaliser object it is being invoked on (canonically named self) as the first parameter.  This implicit parameter is added before any explicit parameters.
Since you defined the function to take five parameters and passed five explicit parameters, the function is called with six parameters - one implicit, and five explicit.
If funcN doesn't use any (instance or class) member variables of Normaliser, it could be defined outside any class or marked with the @staticmethod decorator to avoid the implicit self being added.


text:
Q: SYSTEMPATH/CodeIgniter.php at line 219 CodeIgniter show this problem: SYSTEMPATH/CodeIgniter.php at line 219.
I already added extension=intl to php.ini file. But the error still.
Error :
The framework needs the following extension(s) installed and loaded:
intl.
1. SYSTEMPATH/CodeIgniter.php : 219  -CodeIgniter\Exceptions\FrameworkException::forMissingExtension ( arguments )
212         foreach ($requiredExtensions as $extension) {
213             if (! extension_loaded($extension)) {
214                 $missingExtensions[] = $extension;
215             }
216         }
217
218         if ($missingExtensions !== []) {
219             throw FrameworkException::forMissingExtension(implode(', ', $missingExtensions));
220         }
221     }
222
223     /**
224      * Initializes Kint
225      */
226     protected function initializeKint()

2. SYSTEMPATH/CodeIgniter.php : 177   —  CodeIgniter\CodeIgniter->resolvePlatformExtensions ()
170         $this->bootstrapEnvironment();
171
172         // Setup Exception Handling
173         Services::exceptions()->initialize();
174
175         // Run this check for manual installations
176         if (! is_file(COMPOSER_PATH)) {
177             $this->resolvePlatformExtensions(); // @codeCoverageIgnore
178         }
179
180         // Set default locale on the server
181         locale_set_default($this->config->defaultLocale ?? 'en');
182
183         // Set default timezone on the server
184         date_default_timezone_set($this->config->appTimezone ?? 'UTC');

3. SYSTEMPATH/bootstrap.php : 146   —  CodeIgniter\CodeIgniter->initialize ()
139  *
140  * The CodeIgniter class contains the core functionality to make
141  * the application run, and does all of the dirty work to get
142  * the pieces all working together.
143  */
144
145 $app = Services::codeigniter();
146 $app->initialize();
147
148 return $app;
149

4. require FCPATH/index.php   —   require()
I already add the extension in php.ini :
extension=php_intl.dll

But it still does not work.

A: Locate php.ini and then just remove ";" in the extension=intl line

A: Locate php.ini and then just remove ";" in the extension=intl line.
Then go to the XAMPP control panel and clicking on Stop, then Restart, on the Apache line Service.

A: I solved that error by install php-xml module
ubuntu : #apt-get install php-xml
env php 8.1.6 / CI 4.1.9


text:
Q: Ordering dictionary ascending and descending both I have a
Dictionary<int, float>frequencies

Of numbers (int) and their frequencies.
I need to order them by frequency descending, so i put
frequencies.OrderByDescending(key => key.Value).

The problem is that it orders the keys ascending. That is correct but I only need the first n keys to be ordered descending and the others ascending.
What is the best way to achieve that?
Example:
Now i have:

*

*frequencies: 7  7  6  5 4 4  4  4  4  4 3 3 3

*numbers:     7 36 26 35 1 5 22 23 31 34 2 4 6

My dictionary needs to look like this:

*

*frequencies:  7 7  6  5  4 and then like the upper one.

*numbers:     36 7 26 35  3

Just the first five numbers need to be descending and the others ascending.


text:
Q: Windows 8.1 Offline Folder from NAS on home network? On my home network I have a NAS device. It's an old IOmega StorCenter iX2 that runs SAMBA. I have it configured with mirrored drives. It's old, but it has served me well.
I have a new Windows 8.1 laptop. Here is what I want to do.

*

*On the laptop, set the My Documents folder to point to a shared folder on the NAS

*Set this folder so Offline Files are enabled so when the laptop is out of my home, the my documents files are still available.

Now, I'm pretty sure this was straightforward in XP, Vista and Windows 7. But, I am stuck in 8.1.
For #1, I can browse to "This PC", then right click on "Documents", select Properties, go the Location tab and then specify the path to my NAS folder. This seems to work fine.
For #2, I'm stuck. When I view the folder I do not see Sync options or Always Available on the ribbon. If I go to Control Panel->Sync Center, the Manage Offline files link doesn't seem to launch anything and "Set up new Sync partnerships" doesn't seem to let me set up sync to the NAS.
Any suggestions? Can I do this in Windows 8.1 or is my thinking to too old fashioned.
I've seen similar questions posted like http://www.networksteve.com/windows/topic.php/NAS_files,_Offline,_Sync_Centre_and_windows_8.1/?TopicId=61609&Posts=4

A: Right click on network folder, select option Always Available Offline. Work on folder on network location.

A: Sounds like you are looking for something like called Work Folders. I am not sure if you can set up a host for this using SAMBA.
Kind regards,
Erik


text:
Q: ElasticSearch: Querying if today is between and series of start and end dates in list If I have some data with a field with multiple sets of start/end dates.. for example:
{
     id: 1,
     title: "My Title",
     availability[{start: 01-01-2020, end: 01-05-2020},{start: 02-01-2020, end: 02-22-2020}]
}

Is it possible in elasticsearch to build a query to check if today (or any given date) falls within any of the start/end date combinations in the list?
Or would I need to structure my data differently to make this work?
Previously, I was dealing with just one start and one end date and could store them as their own fields and do a gte, lte combination to check.
Update:
if I add them as nested fields. e.g.:
"avails" : {
    "type" : "nested",
    "properties" : {
        "availStart" : { "type" : "date" },
        "availEnd" : { "type" : "date" }
    }
}

If I do my search like this:
{
    "query": {
        "nested" : {
            "path" : "avails",
            "query" : {
                "term" : {
                    { "range" : {"avails.start" : {"lte": "now"}}},
                    { "range" : {"avails.end" : {"gt" : "now"}}}
                }
            }
        }
    }
}

will it evaluate this for each nested record and return any parent record with a child record that matches?

A: It's good that you've chosen nested fields. Now you just need to make sure the mappings, field names, and the query are all consistent.

*

*The date mapping including the format:

PUT myindex
{
  "mappings": {
    "properties": {
      "avails": {
        "type": "nested",
        "properties": {
          "start": { "type": "date", "format": "MM-dd-yyyy" },
          "end": { "type": "date", "format": "MM-dd-yyyy" }
        }
      }
    }
  }
}

*Syncing your doc

POST myindex/_doc
{
  "id": 1,
  "title": "My Title",
  "avails": [
    {
      "start":"01-01-2020",
      "end": "01-05-2020"
    },
    {
      "start": "02-01-2020",
      "end": "02-22-2020"
    }
  ]
}

*And finally the query. Yours was malformed -- if you want a logical AND, you'll need to wrap the range queries in a bool + must:

POST myindex/_search
{
  "query": {
    "nested": {
      "path": "avails",
      "query": {
        "bool": {
          "must": [
            { "range" : {"avails.start" : {"lte": "now"}}},
            { "range" : {"avails.end" : {"gt" : "02-01-2020"}}}
          ]
        }
      }
    }
  }
}


text:
Q: lightning:isUrlAddressable parameter disappears after reload I see some strange behavior with lightning:isUrlAddressable tab.
When I try to enter the parameter after loading the page immediately parameter is removed from the URL and component is not able to find the param value.
Simple Cmp:
<aura:component  implements="lightning:isUrlAddressable,force:appHostable" access="global">
    <aura:attribute name="urlParam" type="string"/>

        If you implements "lightning:isUrlAddressable" interface, then by
        using v.pageReference,you can get URL params.

            Account name from URL parameter: {!v.pageReference.state.accname}

</aura:component>

Screenshots:

param is disappeared after pressing the ENTER button

A: Here I found it in the document that we should add default namespace C__ to the parameters.
lightning/n/Test_Cmp?c__accname=ajay

This worked for me.

A: Well this is some fun stuff.
Although the documentation says you have to add "c__" to component name, I had the same issue when I didn't add "c__" to the param names.
For example:
https://<Instance>.lightning.force.com/lightning/cmp/c__CheckInCheckOut?step=123

Was loading the page without any parameter in the state variable.
See below the console.log of the pageReference:
{"type":"standard__component","attributes":{"componentName":"c__CheckInCheckOut"},"state":{}}

And the parameters after the "?" were not there anymore after load:
https://<Instance>.lightning.force.com/lightning/cmp/c__CheckInCheckOut

So I tried with both
https://<instance>.lightning.force.com/lightning/cmp/c__CheckInCheckOut?c__step=123

And that Worked.
{"type":"standard__component","attributes":{"componentName":"c__CheckInCheckOut"},"state":{"c__step":"123"}}

If anyone has an idea why it only works like that for me and seems to work another way for others i'd be curious to know.


text:
Q: Запросы по семантическому ядру Ребят собираю ядро для продвижения задаюсь вопросом как правильно поступить, подскажите пожалуйста.
Кей коллектор собрал мне запросы (дизайн сайта, дизайн сайтов, дизайн сайту, дизайн сайты) как правильно выделить их в кластер?
Нужно все оставлять или выбрать 1, а остальные поисковик сам будет методом склонения подтягивать?
Как лучше размещать выбранный запрос в текст точным вхождением или разбавляя дополнительным словом?

A: 1) Для поисковика все эти запросы синонимы, в текст нужно вставить один из них, иначе высока вероятность применения фильтра "переоптимизация" за заспамленость!
2) По поводу кластера - лучше использовать программу 'Key Assort' - она автоматически разбивает слова на кластеры.
3) В вашем случае, для анализа эффективности ключей нужно снять частотность"!" (это частотность строгая, включая склонения) и если по ключевикам: (дизайн сайта, дизайн сайтов, дизайн сайту, дизайн сайты) есть высокая частотность"!" (выше 20 в мес) то лучше их оставить!)))
PS.: Если помог, плз примите ответ (галочка над ответом).

A: Я думаю, что в вопросе слиты в едино разные задачи:

*

*Найти запросы и составить семантическое ядро (список слов для
оптимизации).  Это у вас готово

*Распределить эти поисковые запросы по страницам сайта.

*Для выбранных страниц сделать техническое задание на тексты.
Отсюда следующее:

*

*Для семантического ядра лучше собирать точные вхождения.

*Для выбранных страниц составить задание на тексты, где присутствуют прямые и непрямые вхождения.


text:
Q: curl in windows - how do i put a space in the json? so i have this curl request (running on a windows cmd prompt):
curl --insecure -g -X POST -H "Content-Type: application/json" -d {\"from\":\"someName\",\"message\":\"this is a message\"} https://some/website/here

When i run this, i get an error:
curl: (6) Could not resolve host: is; Host not found
curl: (6) Could not resolve host: a; Host not found
curl: (6) Could not resolve host: message; Host not found

Which seems to be because the json is munged up - the spaces are not working!
How would i send this message, if  i wanted spaces to be in the, uh, message?

A: Use double quotes " and use %20 in url
Just tried on my windows command prompt now. You were missing escape on the DATA part
Your code
curl --insecure -g -X POST -H "Content-Type: application/json" -d {\"from\":\"someName\",\"message\":\"this is a message\"} https://some/website/here

should be escaped like this
curl --insecure -g -X POST -H "Content-Type: application/json" -d "{\"from\":\"someName\",\"message\":\"this is a message\"}" https://some/website/here

A: You just need to quote your JSON as a string literal:
curl --insecure -g -X POST -H "Content-Type: application/json" -d "{\"from\":\"someName\",\"message\":\"this is a message\"}" https://some/website/here

also, use the -V for more info on what is happening (it threw this error "parse error near `}'").

A: try this (instead of -d ), e.g.:
--data-raw "{"blah":"a string with spaces"}"


text:
Q: EntityFramework, Dates and UTC I have an entity with a DateTimeOffset (since .NET doesn't have a Date class) that is supposed to store a date (no time).
The problem is that, when I set the date to, for example, "2017-9-1" in the database it's saved as "2017-08-31 22:00:00+00" (2 hours less)
I think it applies the offset of my time zone to UTC.
I would like to store like to store "2017-9-1" in the database. The first thing I thought is to add 2 hours to every DateTimeOffet, but it feels bogus.
Is there a better way to work with dates than this?

A: I'm not quite sure, but add "0:" before the date on the format string, I think that should put it to your current time, otherwise it will default to UTC.
Like this:
[DisplayFormat(DataFormatString = "{0:yyyy/dd/MM}")]

A: If you are using MS Sql, you can use the Date variable to store just date. You can annotate the entities DateTimeOffset property database type.
[Column(TypeName="date")]


text:
Q: Maven aggregation module serving as a bulk dependency Is it possible to use an aggregating module (pom that aggregates modules for building purposes) as a dependency that transitively includes its modules as dependencies? Considering  it must declare those dependencies that correspond to its submodules, otherwise if you declare it as a dependency, it hasn't own dependencies, so that no transitive deps are included.
I already tried it but I got a cyclic dependency error.
Otherwise I would have to create an extra module (say my_module_deps) that just declares all those dependencies, so I could use it as a dependency that transitively includes its dependencies. I don't like having maven modules that do not have any specific purpose except for being a dependency bulk.
This is the desired state, so I can use it for both module aggregation and a dependency to be used for getting its transitive dependencies :
<project>
    <artifactId>aggregationModule</artifactId>
    <modules>
        <module>a</module>
        <module>b</module>
        <module>c</module>
    </modules>
    <dependencies>
        <dependency>
            <artifactId>a</artifactId>
        </dependency>
        <dependency>
            <artifactId>b</artifactId>
        </dependency>
        <dependency>
            <artifactId>c</artifactId>
        </dependency>
    </dependencies>
</project>

A: Do any of the sub-modules have that aggregating project defined as its parent?
If so, this cannot work, since for being parent the project must be build first.
But if the parent itself defines the modules as dependencies at the same time, the modules must be build first, so you created your cyclic dependency error.

A: You cannot declare a dependency to a project with packaging type "pom". If you do so maven will show the same error as when you declare a dependency to a jar module which does not exists in your local repository and could not be downloaded from your repository list.
Maybe some of the alternatives proposed to this question could help you.


text:
Q: обращение к переменным объекта JavaScript скажите почему след код не выводит измененое имя и возраст?

 var person = (function (name, age) {
     var
         $name = name,
         $age = age;

     return {
         name: $name,
         age: $age,
         setName: function (name) { $name = name;},
         setAge: function (age) { $age = age;}
     };

})('Gregory', 42);

person.setName('Miller');
person.setAge(30);

console.log(person.name);
console.log(person.age);

Выхлоп:
Gregory
42

A: Проблема в том, что сеттеры меняют локальные переменные, которые дальше нигде не получаются.
Значения полей name и age устанавливаются один раз и затем не изменяются.
Для исправления, вместо полей можно использовать геттеры

var person = (function(name, age) {
  var   $name = name,
        $age = age;
  return {
    get name() {
      return $name
    },
      get age() {
      return $age
    },
       setName: function(name) {
      $name = name;
    },
        setAge: function(age) {
      $age = age;
    }
  };
})('Gregory', 42);
person.setName('Miller');
person.setAge(30);
console.log(person.name);
console.log(person.age);

Либо менять непосредственно поля объекта

var person = (function(name, age) {
  return {
    name: name,
    age: age,
    setName: function(name) {
      this.name = name;
    },
    setAge: function(age) {
      this.age = age;
    }
  };
})('Gregory', 42);
person.setName('Miller');
person.setAge(30);
console.log(person.name);
console.log(person.age);

но в этом случае стоит следить за возможной потерей контекста вызова

A: Решение через класс, на мой взгляд, нагляднее и большая возможность есть к расширению
class Person {
    constructor (name, age) {
        this.name = name;
        this.age = age;
    };
    setName (name) {
        this.name = name;
    };
    setAge (age) {
        this.age = age;
    };
}
let person = new Person ('Gregory', 42);
person.setName('Miller');
person.setAge(30);
console.log(person.name);
console.log(person.age);

A:

var person = (function (name, age) {
     var
         $name = name,
         $age = age;

     return {
         name: $name,
         age: $age,
         setName: function (name) { this.name = name;},
         setAge: function (age) { this.age = age;}
     };

})('Gregory', 42);

person.setName('Miller');
person.setAge(30);

console.log(person.name);
console.log(person.age);


text:
Q: Setting up Resource bundles in a Maven project Spring MVC (4.1.6) I am using Netbeans 7 and Maven project using Spring MVC framework. I am trying to access the messages stored in messages.properties under src/main/resources but getting the below error:

ResourceBundle [classpath:\resources\resources\messages] not found for MessageSource: Can't find bundle for base name classpath:\resources\resources\messages, locale en_US

I have the following configuration inside dispatcher-servlet.xml
<bean id="messageSource"
          class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="classpath:\resources\messages" />
</bean>

I also tried to place the properties file under WEB-INF, src/java/package, also tried changing the path but nothing worked.
Please help me fixing the issue.


text:
Q: PHP PDO Multiple Prepare Statement This Code did not work. I am new in php pdo.
This statement works only for first stmp then other does not work.
Code:
try {
    $db->beginTransaction();

    $stmp = $db->prepare("UPDATE jeslot_customer SET cust_outstinding=:totaloutstanding WHERE cust_name=:custname");
    $stmp->execute(array(':totaloutstanding' => $tout,':custname' => $custname));

    $stmp1 = $db->prepare("UPDATE jeslot_products SET opening_stock=:clstock WHERE product_name=:name1");
    $stmp1->execute(array(':clstock' => $clstock,':name1' => $name1));

    $stmt2 = $db->prepare('INSERT INTO jeslot_sales (username, sell_date, invoiceid, product_name, product_weight, sell_price, sell_qty, sell_freeqty, totalqty, sell_amount, customerid, customer_name, subtotal, discount, dis_amount, grandtotal, payment, balance, due_date, payment_mode, cheque_no, cheque_bank, description, countid, profitloss) VALUES (:uname, :selldate, :invoice ,:sname, :pkg, :srate, :sqty, :sfreeqty, :totalqty, :samount, :custid, :custname, :subtotal, :discount, :dis_amount, :payable, :payment, :balance, :duedate, :payment_mode, :cno, :bname, :description, :countid, :profit)');

    $stmt2->execute(array(
    ':uname' => $username,
    ':selldate' => $selldate,
    ':invoice' => $bill_no,
    ':sname' => $name1,
    ':pkg' => $pkg,
    ':srate' => $rate,
    ':sqty' => $quantity,
    ':sfreeqty' => $freequantity,
    ':totalqty' => $totalqty,
    ':samount' => $total,
    ':custid' => $custid,
    ':custname' => $custname,
    ':subtotal' => $subtotal,
    ':discount' => $discount,
    ':dis_amount' => $dis_amount,
    ':payable' => $grandtotal,
    ':payment' => $payment,
    ':balance' => $balance,
    ':duedate' => $duedate,
    ':payment_mode' => $mode,
    ':cno' => $cno,
    ':bname' => $bname,
    ':description' => $description,
    ':countid' => ($i+1),
    ':profit' => $profit
    ));

    $db->commit();
    $db->rollback();

} catch(PDOException $e) {

    $error[] = $e->getMessage();
}

A: Should not this statement
$stmp1->execute(array(':clstock' => $clstock,':name1' => $name1));

be
$stmp1->execute(array(':clstock' => $clstock,':product_name' => $name1));

A: Maybe try
$db->beginTransaction();

try {
    $stmp = $db->prepare("UPDATE jeslot_customer SET cust_outstinding=:totaloutstanding WHERE cust_name=:custname");
    $stmp->execute(array(':totaloutstanding' => $tout,':custname' => $custname));

    try {
        $stmp = $db->prepare("UPDATE jeslot_products SET opening_stock=:clstock WHERE product_name=:name1");
        $stmp->execute(array(':clstock' => $clstock,':name1' => $name1));

        try {
            $stmt = $db->prepare('INSERT INTO jeslot_sales (username, sell_date, invoiceid, product_name, product_weight, sell_price, sell_qty, sell_freeqty, totalqty, sell_amount, customerid, customer_name, subtotal, discount, dis_amount, grandtotal, payment, balance, due_date, payment_mode, cheque_no, cheque_bank, description, countid, profitloss) VALUES (:uname, :selldate, :invoice ,:sname, :pkg, :srate, :sqty, :sfreeqty, :totalqty, :samount, :custid, :custname, :subtotal, :discount, :dis_amount, :payable, :payment, :balance, :duedate, :payment_mode, :cno, :bname, :description, :countid, :profit)');

            $stmt->execute(array(
            ':uname' => $username,
            ':selldate' => $selldate,
            ':invoice' => $bill_no,
            ':sname' => $name1,
            ':pkg' => $pkg,
            ':srate' => $rate,
            ':sqty' => $quantity,
            ':sfreeqty' => $freequantity,
            ':totalqty' => $totalqty,
            ':samount' => $total,
            ':custid' => $custid,
            ':custname' => $custname,
            ':subtotal' => $subtotal,
            ':discount' => $discount,
            ':dis_amount' => $dis_amount,
            ':payable' => $grandtotal,
            ':payment' => $payment,
            ':balance' => $balance,
            ':duedate' => $duedate,
            ':payment_mode' => $mode,
            ':cno' => $cno,
            ':bname' => $bname,
            ':description' => $description,
            ':countid' => ($i+1),
            ':profit' => $profit
            ));

            $db->commit();
        }
        catch(PDOException $e) {

            $db->rollback();
            $error[] = $e->getMessage();
        }
    }
    catch(PDOException $e) {

        $db->rollback();
        $error[] = $e->getMessage();
    }
}
catch(PDOException $e) {

    $db->rollback();
    $error[] = $e->getMessage();
}


text:
Q: Compute an addrow function not working javascript php I could not solve the issue whenever I execute my addrow() function, the computation sudden stop working.Once I addrow(), the computation not working.  Here is my code:

$('#addrow').click(function() {
  var length = $('.sl').length;
  var i = parseInt(length) + parseInt(1);
  var newrow = $('#next').append('

Sl No:<input type="text" class="form-control sl" name="slno[]" value="' + i + '" readonly="">

BL NO:<input type="text" class="form-control" name="bl_no[]" id="bl_no' + i + '" placeholder="Enter BL NO">

CONTAINER:<input type="text" class="form-control" name="container[]" id="container' + i + '" placeholder="Enter container">

DELIVERY ADDRESS:<input type="text" class="form-control" name="delivery_address[]" id="delivery_address' + i + '" placeholder="Enter Address">

ITEM DESCRIPTION:<input type="text" class="form-control" id="item_description' + i + '" name="item_description[]" placeholder="Enter item_description">

DELIVERY DATE:<input type="date" id="delivery_date' + i + '" name="delivery_date[]" class="form-control"/>

SHIPPING LINE COST:<input type="number" id="shipping_line_cost' + i + '" name="shipping_line_cost[]" class="form-control" onkeyup="sum()"/>

BASE TAX COST:<input type="number" id="base_tax_cost' + i + '" name="base_tax_cost[]" class="form-control" onkeyup="sum()"/>

ADDITIONAL CHARGES:<input type="number" id="additional_charges' + i + '" name="additional_charges[]" class="form-control"/>

DELIVERY CHARGE:<input type="number" id="delivery_charge' + i + '" name="delivery_charge[]" class="form-control"/>

MANO CHARGE:<input type="number" id="mano_charge' + i + '" name="mano_charge[]" class="form-control"/>

COLLECTIBLE AMOUNT:<input type="number" id="collectible_amount' + i + '" name="collectible_amount[]" class="form-control" readonly/>
  <input type="button" class="btnRemove btn-danger" value="Remove"/>

');

});
// Removing event here
$('body').on('click', '.btnRemove', function() {
  $(this).closest('div').remove()

});

function sum() {
  var shipping_line_cost = document.getElementById('shipping_line_cost').value;
  var base_tax_cost = document.getElementById('base_tax_cost').value;
  var result = parseInt(shipping_line_cost) + parseInt(base_tax_cost);
  if (!isNaN(result)) {
    document.getElementById('collectible_amount').value = result;
  }
}

  SHIPPING LINE COST:

  <input type="number" id="shipping_line_cost" name="shipping_line_cost[]" class="form-control" onkeyup="sum()" />

  BASE TAX COST:

  <input type="number" id="base_tax_cost" name="base_tax_cost[]" class="form-control" onkeyup="sum()" />

  COLLECTIBLE AMOUNT:

  <input type="number" id="collectible_amount" name="collectible_amount[]" class="form-control" readonly/>

<button type="button" name="addrow" id="addrow" class="btn btn-success pull-right">Add New Row
</button>

<button type="submit" name="submit" class="btn btn-info pull-left">Submit
</button>

A: The main issue with your code is because you're dynamically creating multiple incremental id attributes on the elements you create in each row, yet your JS logic expects there to only ever be 1 of each id.
To fix the issue you need to loop through the new content which you dynamically create and sum up each value as you go.
There's also several other issues with your code which need to be addressed:

*

*You're using multiple versions of jQuery. Reference a single version and use that one only.

*Remove id attributes from dynamic content and replace them with class attributes. You can then use DOM traversal methods to relate the elements together when required.This makes the code more DRY and easier to maintain.

*Use a <template /> element to store the dynamic HTML. You should avoid having HTML in your JS as much as possible, otherwise the JS becomes an unmaintainable mess.

*Wrap the label elements around the input. This way you don't need to use any id attributes.

*Use unobtrusive delegated event handlers on dynamic content. Do not use onclick, or any other onX event attribute in your HTML. They are no longer good practice.

*Use the input event instead of keyup, keypress etc. It also covers cases where the user pastes content using the mouse, and is generally better for accessibility.

With all those changes applied, your code should look and work something like this:

const rowTemplateHtml = $('#row-template').html();
const $container = $('#next');
const setIndexValues = () => $container.find('.sl').val(i => i + 1);

$('#addrow').on('click', e => {
  $container.append(rowTemplateHtml);
  setIndexValues();
});

$container.on('input', '.sum', e => {
  const $row = $(e.target).closest('.row');
  var result = $row.find('.sum').get().reduce((acc, el) => acc + parseInt(el.value || 0, 10), 0);
  $row.find('.collectible_amount').val(result);
});

$container.on('click', '.btnRemove', e => {
  $(e.target).closest('div').remove();
  setIndexValues();
});
#next {
  margin: 20px;
}
.row {
  margin-bottom: 20px;
}

  <form>

        SHIPPING LINE COST:
        <input type="number" id="shipping_line_cost" name="shipping_line_cost[]" class="form-control" onkeyup="sum()" />

        BASE TAX COST:
        <input type="number" id="base_tax_cost" name="base_tax_cost[]" class="form-control" onkeyup="sum()" />

        COLLECTIBLE AMOUNT:
        <input type="number" id="collectible_amount" name="collectible_amount[]" class="form-control" readonly/>

    <button type="button" name="addrow" id="addrow" class="btn btn-success pull-right">Add New Row</button>
    <button type="submit" name="submit" class="btn btn-info pull-left">Submit</button>
  </form>

<template id="row-template">

        Sl No:
        <input type="text" name="slno[]" class="form-control sl" readonly>

        BL NO:
        <input type="text" name="bl_no[]" class="form-control" placeholder="Enter BL NO">

        CONTAINER:
        <input type="text" name="container[]" class="form-control" placeholder="Enter container">

        DELIVERY ADDRESS:
        <input type="text" name="delivery_address[]" class="form-control" placeholder="Enter Address">

        ITEM DESCRIPTION:
        <input type="text" name="item_description[]" class="form-control" placeholder="Enter item_description">

        DELIVERY DATE:
        <input type="date" name="delivery_date[]" class="form-control" />

        SHIPPING LINE COST:
        <input type="number" name="shipping_line_cost[]" class="form-control sum" />

        BASE TAX COST:
        <input type="number" name="base_tax_cost[]" class="form-control sum" />

        ADDITIONAL CHARGES:
        <input type="number" name="additional_charges[]" class="form-control" />

        DELIVERY CHARGE:
        <input type="number" name="delivery_charge[]" class="form-control" />

        MANO CHARGE:
        <input type="number" name="mano_charge[]" class="form-control" />

        COLLECTIBLE AMOUNT:
        <input type="number" name="collectible_amount[]" class="form-control collectible_amount" value="0" readonly/>

    <button type="button" class="btnRemove btn-danger">Remove</button>

</template>

As an aside, you seem to be working with monetary values, so the use of parseInt() may not be a good choice. I'd suggest parseFloat() instead.


text:
Q: Skolem sequence of quadrupets? I recently read that there are solutions for Langford sequences of quadruplets (four of each number evenly spaced) when n=24.
I'm curious if anyone has found Skolem sequences of quadruplets?
Many thanks,
Erik


text:
Q: I cannot get my php session to recall my stored variable I have php creating new files that are generated by input by a user (I know not great) I want all documents to be created by the initial input that way theres no variance. I set the varible in the first php script like so
session_start();
$_SESSION["FirstName"] = $_POST['FName'];

I know that the FName variable works because the first document creates correctly with the correct title
but then on following documents the php does not name the document properly and just leave it blank, here is how I am creating the the file name for other documents
session_start();
$my_file = $_SESSION["FirstName"] . 'History.txt';

I am unsure as to why it is not working

A: So I have no idea why but it just started working.
I have not touched the php scripts as I moved on to other things but it all started working now.


text:
Q: Is $\sum_{k=1}^{n} k^k / \sum_{k=1}^{n} k \in \mathbb{N}$ for some $n > 1$? Let $ A = \sum_{k=1}^{n} k^k $ and $ B = \sum_{k=1}^{n} k$, where $n >1 $ is a positive integer.
Is $A/B$ ever an integer?

A: Write $\sum n = \frac 1 2 n(n+1)$, and note that $n \mid n^n$ but $n+1 \nmid n^n$. For coprime $a$ and $b$ (nb. $n$ and $n+1$ are coprime):

$ab \mid n \iff a \mid n \wedge b\mid n$

and

$a\mid q\times a+r \iff a \mid r$

we can write:

$\frac {n(n+1)}{2}  \mid \sum_{i=1}^n i^i \iff \{k_{n+1} \mid \sum_{i=1}^n i^i\} \wedge \{k_n \mid \sum_{i=1}^{n-1} i^i\}$

Where $k_n = \begin{cases} \frac n 2 & n \text{ is even} \\ n & \text{ otherwise} \end{cases}$
This reduces the problem to working out:

$\text{When does } k_n \text{ divide } \sum_{i=1}^{n-1} i^i \text{ ?} \quad*$

I tested every number up to 132,000 (using a script I've appended at the bottom) and the numbers satisfying $n\mid \sum_{i=0}^n i^i$ are:
1
3     =3
7     =7
16    =2*2*2*2
18    =2*3*3
33    =3*11
49    =7*7
147   =3*7*7
161   =7*23
183   =3*61
487   =487
647   =647
1549  =1549
1576  =2*2*2*197
3563  =7*509
4049  =4049
4387  =41*107
5872  =2*2*2*2*367
6638  =2*3319
8578  =2*4289
8805  =3*5*587
9549  =3*3*1061
59453 =59453
62499 =3*83*251

I am interested that these numbers have very few prime factors and I think that it might might be possible to prove that:

*

*there are infinitely many such numbers

*there are no pairs of such numbers

using a combination of interesting modular arithmetic and some fun prime number manipulation.


text:
Q: How can I group and name the incoming values in the request according to the standards in the config-repo with Springboot? In the request, I will receive a Solr-name field of type List. I need to group by solr-name name. For example, gender_s, age_f and job_s came. If these three come, I have to assign them as demographics. But I don't want to do this with an ugly if else code block. How can I group this information cleanly? My second question is that I want to parse the fields containing subrules in the same way and show them with view name. How can I do it with a clean code?
My config-repo :
project.search.categories:
  sms:
    view-name: Sms
    rules:
      sms:
        view-name: operator tarafindan atilan aylik atilan sms sayisi
        solr-name: sms_count_f
        view-type: NUMERIC
        solr-type: BIGINT
        min-value: 0
        max-value: 150
        max-range: 50
  demography:
    view-name: Demografi
    rules:
      gender:
        view-name: Cinsiyet
        solr-name: gender_s
        view-type: SINGLE_SELECT
        solr-type: STRING
      age:
        view-name: Yas
        solr-name: age_f
        view-type: NUMERIC
        solr-type: BIGINT
        min-value: 0
        max-value: 150
        max-range: 50
      job:
        view-name: Meslek
        solr-name: job_s
        view-type: MULTI_SELECT
        solr-type: STRING
        values: JOBS
      citizenship:
        view-name: Uyruk
        solr-name: citizenship_s
        view-type: MULTI_SELECT
        solr-type: STRING
        values: ROAMING_COUNTRY
  interest:
    view-name: Ilgi Alanlari
    rules:
      betting:
        view-name: Spor Bahisleri ile ilgilenen
        solr-name: betting__sports_interest_f
        view-type: SINGLE_SELECT
        solr-type: TINYINT
        values: 1@Evet, 0@Hay\u0131r
      career:
        view-name: Kariyer
        solr-name: career_interest_f
        view-type: SINGLE_SELECT
        solr-type: TINYINT
        values: 1@Evet, 0@Hay\u0131r
      coupons:
        view-name: \u0130ndirimler ile ilgilenen
        solr-name: coupons__discount_interest_f
        view-type: SINGLE_SELECT
        solr-type: TINYINT
        values: 1@Evet, 0@Hay\u0131r
      device_site:
        view-name: Teknoloji ile ilgilenen
        solr-name: device_site__technology_interest_f
        view-type: SINGLE_SELECT
        solr-type: TINYINT
        values: 1@Evet, 0@Hay\u0131r
      e-commerce:
        view-name: E-ticaret ile ilgilenen
        solr-name: ecommerce_interest_f
        view-type: MULTISELECT_TINYINT
        solr-type: TINYINT
        values: 1@Evet, 0@Hay\u0131r
        subrules:
          home_furniture:
            view-name: Ev dekorasyonu ile ilgilenen
            solr-name: ecommerce__home_furniture_interest_f
            view-type: SINGLE_SELECT
            solr-type: TINYINT
            values: 1@Evet, 0@Hay\u0131r
          clothing:
            view-name: Tekstil ile ilgilenen
            solr-name: ecommerce__clothing_interest_f
            view-type: SINGLE_SELECT
            solr-type: TINYINT
            values: 1@Evet, 0@Hay\u0131r
          automobiles:
            view-name: Otomobil ile ilgilenen
            solr-name: ecommerce__automobiles_interest_f
            view-type: SINGLE_SELECT
            solr-type: TINYINT
            values: 1@Evet, 0@Hay\u0131r
          market_place:
            view-name: Online Market Place Al\u0131sveris ile ilgilenen
            solr-name: ecommerce__market_place_interest_f
            view-type: SINGLE_SELECT
            solr-type: TINYINT
            values: 1@Evet, 0@Hay\u0131r
          sports:
            view-name: Spor Al\u0131\u015fveri\u015fi ile ilgilenen
            solr-name: ecommerce__sports_interest_f
            view-type: SINGLE_SELECT
            solr-type: TINYINT
            values: 1@Evet, 0@Hay\u0131r
          technology:
            view-name: Teknoloji Al\u0131\u015fveri\u015fi ile ilgilenen
            solr-name: ecommerce__technology_interest_f
            view-type: SINGLE_SELECT
            solr-type: TINYINT
            values: 1@Evet, 0@Hay\u0131r
          books:
            view-name: Kitap Al\u0131\u015fverisi ile ilgilenen
            solr-name: ecommerce__books_interest_f
            view-type: SINGLE_SELECT
            solr-type: TINYINT
            values: 1@Evet, 0@Hay\u0131r
          kids:
            view-name: \u00c7ocuk i\u00e7in Al\u0131\u015fveri\u015f yapan
            solr-name: ecommerce__kids_interest_f
            view-type: SINGLE_SELECT
            solr-type: TINYINT
            values: 1@Evet, 0@Hay\u0131r
          comparison:
            view-name: Fiyat Kar\u015f\u0131la\u015ft\u0131rma # convert
            solr-name: ecommerce__comparison_interest_f
            view-type: SINGLE_SELECT
            solr-type: TINYINT
            values: 1@Evet, 0@Hay\u0131r

I defined and assigned it in the config repo, and use my microservices @Value("${project.....) annotation but there is too much data and I think there may be a better solution that I can show with view-name without using if else. I really need your help, thank you.


text:
Q: How to use Flexjson JSONDeserializer? I have a string:
 [{"product_id":"2","name":'stack"'},{"product_id":"2","name":"overflow"}]"

How can I use Flexjson's JSONDeserializer to obtain all product_ids from the above string?
I have a class called productinformation which has fields like product_id and name.

A: You could use the JSONDeserializer.use() methods to tell it how to deserialize the array and each object in the array, in this case of class ProductInformation . The product_id attribute does not match up with the standard naming that flexjson expects, so your properties on the object will need to have an underscore in them.
String products= "[{\"product_id\": \"123\",\"name\":\"stack\"},{\"product_id\": \"456\",\"name\":\"overflow\"}]";
List<ProductInformation> productInfoList = new JSONDeserializer<List<ProductInformation> >()
    .use(null, ArrayList.class)
    .use("values",ProductInformation.class)
    .deserialize(products);

for(ProductInformation productInformation : productInfoList){
    System.out.println(productInformation.getProduct_id();
}

The section on "Deserialization Without the Training Wheels" in Deserialization section of the docs goes into additional details on the other cases to consider if the type information is not included in the JSON string.


text:
Q: Android - comparing string to arrays Is it possible to compare strings to arrays in android? This is for the dictionary application using the Porter Stemmer that i am developing for my thesis.
For example the input word is PROCESSES (placed inside a char array), and I'd like to scan if the input contains "s","es" or "sses" then delete them.
I thought of comparing letter by letter but it would be a tedious coding I believe.
Is there an easier way to just compare the input word like so:
If ( inputWord has string "es" )
 {
   delete "es
 }

example input: PROCESSES
example output: PROCESS

A: You can use the String.contains and String.replaceAll functionality:
//if (inputWord.contains("es")) {
    inputWord.replaceAll("es", "");
//}

You don't need the if statement, you can also do directly a replace. If the string is not found it won't do anything.

A: if(inputWord.contains(checkWord))
{
    int i = inputWord.indexOf(checkWord);
    StringBuilder sb = new StringBuilder(inputWord);
    sb = sb.delete(i, i+(checkWord.length()));
    inputWord = sb.toString();
}

Store your values in String. It will be more easier. Hope this code will help you. If you have to check multiple words, store all words in a array, and put this snippet inside a for loop.

A: Perhaps I don't understand your question, but you can convert between String and char[] using
char[] data = {'a', 'b', 'c'};
String str = new String(data);

and
String str = "abc";
char[] data = toCharArray();

You can check whether a substring is contained using indexOf(String) or contains(String).


text:
Q: jQuery Children length of an ol I am trying to count the child elements of an OL
jQuery :
$(document).ready(function(){

$("#my_select").change(function(){
    alert($("#ol3").children.length);
                                     });});

HTML:

Location 1-1

Location 2-1

Location 2-2

Location 3-1

Location 3-2

Location 3-3

I always get the number 2 no matter how many li are there under the ol.
Know what's going on..?

A: Try children() instead of children.
For a belt-and-suspenders approach, try children('li').

A: you can also use .size() instead of .length()
either one works, though .length() is supposedly faster.

A: try
$("#ol3").children().length \\ you missed () in children...

when you do $("#ol3").children.length it returns the number of arguments in the .children() function...
try alerting $("#ol3").children and you will get this...
function (d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}

where d and f are the two arguments... that's why you are always getting 2 in your code when you alert..


text:
Q: Community Hide Built in Component from Guest User I am wondering if it is possible to conditionally show or hide a built in lightning component on a communities page. We are using the napili theme.
One idea I had was to create a custom component, and then put the built in component inside of that component with a user access check, but I have no idea how to include a built in community component into my own component.  I feel like this should be possible, but I don't know how to access it, I don't see any components in the developer console which correspond to the napili components.


text:
Q: Eigen: Flat view of Matrix in Templated Function For 1D resizing, the Eigen documentation suggests I use the following method to resize an array:
using Eigen;

MatrixXf X(2,2) << 1,2,3,4;
Map<RowVectorXf> v1(X.data(), X.size());

Except I have a templated vector, and can't use RowVectorXf
using Eigen;
template<class num>
void my_func(){

  Matrix<num,Dynamic,Dynamic> X(2,2) << 1,2,3,4;

  Map<Matrix<num,Dynamic,Dynamic>> unraveled(X.data(),X.size());
}

The example above fails with the following message:

error: static assertion faild: YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX

How do I obtain a flat view of an eigen matrix in a templated function?

A: The issue is that the Map is 2D and not 1D as you really want:
Map<Matrix<num,Dynamic,1>> unraveled(X.data(),X.size());

Then now it's a vector operation on your original X matrix.


text:
Q: Issue in overriding the Price block I was trying to override the price block for custom product type and I tried the below code, which is working fine but in base or some theme does not work.
    <reference name="catalog_product_price_template">
        <action method="addPriceBlockType">
            <type>packet</type>
            <block>packetprice/catalog_product_price</block>
            <template>packetprice/product/price.phtml</template>
        </action>
</reference>

Please advise.

A: If I have such problem, I firstly check existing such product type in config, create object of the block anywhere and check if template exists.
If everything is allright - you should check the method Mage_Catalog_Block_Product_Abstract::addPriceBlockType (put there some breakpoins or Mage::log()). Also look for any rewrites of this method (Better using xdebug)
As your reference exist inside some handle:
<layout version="0.1.0">
<some_of_your_handles>
...
</some_of_your_handles>

check if this handle is using on current page (put something like <remove name="head" /> inside this handle)
upd.1
By default magento render price here:
app/design/frontend/base/default/template/catalog/product/list.phtml
<?php echo $this->getPriceHtml($_product, true) ?> (You can start your debug from here). Also check in method getPriceHtml if you use correct product_type.
The method where magento set price template is:
Mage_Catalog_Block_Product_Abstract::_getPriceBlockTemplate

    protected function _getPriceBlockTemplate($productTypeId)
    {
        if (isset($this->_priceBlockTypes[$productTypeId])) {
            if ($this->_priceBlockTypes[$productTypeId]['template'] != '') {
                return $this->_priceBlockTypes[$productTypeId]['template'];
            }
        }
        return $this->_priceBlockDefaultTemplate;
    }

check which template magento try to render
upd.2
If you don't use xdebug, better use Mage::log($param, false, 'somelog.log', true)
Inside method Mage_Catalog_Block_Product_Abstract::getPriceHtml
put following:
Mage::log(get_class($this), false, 'somelog.log', true);
Mage::log($this->getTemplate(), false, 'somelog.log', true);
Also don't forget that on your page magento can call this method many times (for regular price, for tier price)


text:
Q: Not able to navigate to desired folder on remote Linux machine, how do i do that using paramiko? I am Using Python paramiko and
My website server has folder structure like this-
1]dir1
      --dirP
      --dirQ
2]dir2
      --dirA
          --file.sh
      --dirB
3]dir3

where i want to access file.sh from dirA inside dir2 folder
I tried this-
import paramiko
client.connect('mysite.com', username='something', password='something')
stdin, stdout, stderr = client.exec_command('cd dir2')
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
    print('... ' + line.strip('\n'))

but i get output-
  ...dir1
  ...dir2
  ...dir3

expected output is-
...dirA
...dirB

and also suggest how can i execute file.sh too?

A: client.exec_command("cmd ...") is just like the command ssh user@host "cmd ..." so
client.exec_command('cd dir2')
client.exec_command('ls')

are just like
ssh user@host 'cd dir2' # this would not affect the following `ls'
ssh user@host 'ls'

. So you need to do like this:
client.exec_command('cd dir2; ls')

which is just like
ssh user@host 'cd dir2; ls'

A: Or if you use variables need to add + for example
client.exec_command('str(var1)+str(var2))


text:
Q: tableview delete row problem I have an tableview in my uiviewcontroller classes.. I have deleted row in tableview.
In the debugger console it shows an error is
0x939fe688  <+0024>  mov    0x20(%edx),%edi
My application terminated..
Can anyone help me?
Thanks in advance..

A: This messaege is displayed in log console
Assertion failed: (cache->size >= g->size), function evict_glyph_entry_from_cache, file Fonts/CGFontCache.c, line 836


text:
Q: Wait until jquery plugin on another plugin init i'm using iziModal jquery plugin and ion range slider. Basically I have a table with records and each record has edit button that shows an iziModal with sliders inside it.
I have in a js file called "slidersInit.js" ion range sliders plugin initialization
$(document).ready(function () {

$("#NumTurnos").ionRangeSlider({
    skin: "big",
    type: "single",
    min: 1,
    max: 3,
    from: 3
});

$("#NumPAB").ionRangeSlider({
    skin: "big",
    type: "single",
    min: 0,
    max: 50,
    from: 6
});

$("#AlcanceAbastecimento").ionRangeSlider({
    skin: "big",
    type: "single",
    min: 0,
    max: 20,
    from: 3
});

$("#QtdMin").ionRangeSlider({
    skin: "big",
    type: "single",
    min: 0,
    max: 20,
    from: 4
});

$("#QtdMax").ionRangeSlider({
    skin: "big",
    type: "single",
    min: 0,
    max: 50,
    from: 12
});

$("#NumDias").ionRangeSlider({
    skin: "big",
    type: "single",
    min: 0,
    max: 5,
    from: 5
});

})
Now on my actual page I call the script
   <script src="~/lib/vue/vue.js"></script>
    <script src="~/lib/axios/axios.js"></script>
    <script src="~/lib/ion-rangeslider/js/ion.rangeSlider.js"></script>
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <script src="~/lib/font-awesome/js/all.js"></script>
    <script src="~/lib/izimodal/js/iziModal.js"></script>
    <script src="~/js/slidersInit.js"></script>

notice that it's at bottom before ion rangeslider and izimodal.
So on that page I also have iziModal configurations
  $(document).ready(function () {

        $("#modal").iziModal({
            zindex: 3000,
            width: 900,
            onOpening: function (modal) {

                modal.startLoading();
                //ajax call
                //update ion range sliders with new values
            }
        });
  });

problem is for some reason when i open the iziModal, all sliders appear at 0 which means they haven't been initialized before iziModal opens and it only works if I initialize them inside the Modal open function.
Problem is that i want to do this outside iziModal because it won't work if i call the sliders initialize everytime i click on a record edit button to call modal, it keeps previous values and won't update.
So is there a way where i can just wait for sliders to be initialized before modal is?

A: Nevermind, it seems the issue was something else. I tried everything, destory modal, sliders and reinitialize. It seems what worked was resetting iziModal on closing.
I just added this method to iziModal initialize
 onClosed: function (modal) {
                $('#modal').iziModal('resetContent');
            }

I hope someone with same problem sees this to save some headaches...


text:
Q: What is the difference when concatenating a String as a variable with a Character vs concatenating with an other String? When i see something (pseudo 1-liner) like this:
str1 + "a" + str2

Is it much worse (or better/equal) than the following (pseudo 1-liner)?
str1 + 'a' + str2

Update: Better example (by @QPaysTaxes) to reduce confusion regarding my original example.
What i tried:
Various stuff for the past 10 years programming Java but i never managed to realy see whats under the hood - e.g. i would assume the second is slightly "faster/better" because there is no String-Object(s) created for the slash-sign and/or the garbage collector of Java has to handle less.
I once prepared for the Java Certificates and might would have been able to argue better back in that time but it seems even thus its my daily business the "theory" about Java must be keept up to date as well... I know without any better explanation than my assumptation that indexOf('c') should be used rather than indexOf("C") and i wondered if the same counts for String-concatenation.
I also googled a bit but as my title might imply i am not quite good to describe what i am looking for without a example. I am sorry for this and the possibility this handicap just produced a duplicate.
What i will try:
Based on the accepted answer here String concatenation: concat() vs "+" operator i hope to be able to have a start to see whats under the hood and one day be able to argue/ answer such questions that profund.

A: If you construct a filename you sure will use it afterwards. That in most cases involves access to a physical media which is magnitudes slower than anything you can do wrong with concatenating your Strings. So, do what is maintable and don't worry about performance in this particular case.
My advice when building filenames is to use the File class or Path that will automatically make sure to get path separators right.
EDIT: As you point out in your comment, your question is about the general case. Just look at the source. StringBuilder.append(String) ends up doing a System.arraycopy() in String.getChars() whilst StringBuilder.append(char) directly copies a single character. So in theory, StringBuilder.append(char) will be faster.
However, you'd have to benchmark this to see if it makes any difference in practice.

A: I'm not sure if either of the options is better in terms of performance, but I can think of another issue to consider, that would prefer the first snippet.
The compiler can better protect you against typos if you append primitives instead of the String representation of those primitives.
Consider:
String plus10 = "plus" + 10;

If you type by mistake
String plus10 =  "plus" + 1O;

The compiler will give you an error.
If, on the other hand, you type
String plus10 =  "plus" + "1O";

The compiler will have no problem with that.
The same goes for appending chars
String plus = "x" + '++' + "y";

will not compile while
String plus = "x" + "++" +  "y";

will pass compilation.
Of course it would be better to use constants and not hard coded values (and to append to a StringBuilder instead of using String concatenation), but even for the constants I would prefer primitive types over Strings, as they give you one more level of protection against errors.

A: There is no any significant difference in performance actually. An average it will take the same time to do string concatenation.
However, internally Java compiler replaces + operator with StringBuilder at compile time.
So when using + operator with char, compiler will convert it into a StringBuilder internally and use .append(char).  The same will happen with a string, with a difference that it will use .append(String).
And as I mentioned above, there is no difference an average. Simple test will show that time difference is close to 0. So this is really matter of readability. And from readability perspective, if you are concentrating strings, it's better to keep the type same, and use String even for single characters, rather than char

A: Looking at the source code often helps to understand what is happening.
String s = s1 + s2

Will execute:
String s = new StringBuilder(s1).append(s2).toString();

Now look into the source code for append(char) and append(string) of the class StringBuilder:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.append%28char%29
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/AbstractStringBuilder.java#AbstractStringBuilder.append%28java.lang.String%29
You will see that append(string) performs more checks to see if the string is null or empty. However, you probably will not notice any difference.

A: This is what's under the hood: String str = s1 + "/"; essentially creates 2 new separate String objects (str and new String("/")).
This is no problem for small software, but think about it memory-wise if you were to create 2 String objects (keep in mind: objects reserve 1 entry in the Stack plus contents kept in the Heap) for n > 500.000 database entries.
Using single quotes, like String str = s1 + '/', will result in another process entirely. '/' stands for the numeric ASCii character representation value of whatever single character is written between the quotes. This operation has a constant (O(1)) runtime (think instant array access) and will naturally be faster than creating and referencing objects.
As lots of people have suggested already, using a StringBuilder object for String concatenation is much easier on memory than building strings with the + operator.

A:
Based on the accepted answer here I hope to be able to have a start to
  see whats under the hood.

Let's have a look at the generated bytecode when concatenating a String with a Character:
String str1 = "a" + "test";
String str2 = 'a' + "test";

0: ldc           #2                  // String atest
2: astore_1
3: ldc           #2                  // String atest
5: astore_2

as you can see, there is no difference, the compiler will convert it to the same bytecode.
Now let's have a look at the generated bytecode when concatenating a Character to a String variable.
String str1 = "a" + str3; //str3 is a String
String str2 = 'a' + str3;

 7: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
10: ldc           #5                  // String a
12: invokevirtual #6                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: aload_1
16: invokevirtual #6                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
19: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
22: astore_2
23: new           #3                  // class java/lang/StringBuilder
26: dup
27: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
30: bipush        97
32: invokevirtual #8                  // Method java/lang/StringBuilder.append:(C)Ljava/lang/StringBuilder;
35: aload_1
36: invokevirtual #6                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
39: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;

As you can see, there is a little difference.
10: ldc           #5                  // String a

ldc push a constant #index from a constant pool (String, int or float) onto the stack.
Therefore, if you are concatenating directly with a variable, concatenating a Character will generate less bytecode, that is what is under the hood.
Now for the performance issue, this wont represent any signifiant performance difference as the JIT compiler optimize most of the temporary objects, unless you specified when running your program to disable the JIT compiler using -Djava.compiler=NONE.

A: I prefer to use "a" instead of 'a' to make sure the result is a String.
Consider this:
public static void main(String... args) {
    String s = "foo";
    int i = 1;
    Object arg = s + '/' + i;
    log(arg);
}

private static void log(Object... args) {
    MessageFormat format = new MessageFormat("bar {0}");
    String message = format.format(args);
    System.out.println(message); // or write to a log or something
}

Assume you decide you don't need s in the message anymore and change the third line in the main method to:
Object arg = '/' + i;

Then arg will contain just a number, because char + int does not concatenate, but add the values.


text:
Q: How to use a variable in SELECT AS in MySQL, to specify the displayed column name? I have here assigned "test123" to the variable @searchstring.
I would like the name of the display column to be the value of the variable (ie. test123 in this case).
This is what I issued in MySQL console:
SET @searchstring="test123";  #SET the searchstring you want to search
SELECT DISTINCT(caselist.casenumber1) AS "@searchstring"    FROM caselist LIMIT 1;

This is what I got returned on screen:
+---------------+
| @searchstring |
+---------------+
|             0 |
+---------------+
1 row in set (0.00 sec)

The desired result is this:
+---------------+
| test123       |
+---------------+
|             0 |
+---------------+

My actual query issued will be more complex, and refers to  the @searchstring multiple times.
The content of @searchstring changes, depending on what I want to search.
That is why I decided to assign a value to it upfront once. When I want to search other things, I just need to change that variable once upfront.
QUESTION:
How do I have the column title to display the content of the variable @searchstring (ie. test123 in this case), rather than the actual name of the variable?
Thank you.
If I do this (ie. remove the quotation marks around the variable name after AS):
SET @searchstring="test123";  #SET the searchstring you want to search
SELECT DISTINCT(caselist.casenumber1) AS @searchstring  FROM caselist ;

Then I get this error message:
mysql> SELECT DISTINCT(caselist.casenumber1) AS @searchstring FROM caselist ;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@searchstring FROM caselist' at line 1
mysql>

A: One option is using dynamic querying for this problem:
SET @searchstring = "test123";  #SET the searchstring you want to search

SET @sql = CONCAT('SELECT DISTINCT casenumber1 AS ',
                  @searchstring,
                  ' FROM caselist LIMIT 1');

PREPARE stmt FROM @sql;
EXECUTE stmt;

DEALLOCATE PREPARE stmt;

Check the demo here.


text:
Q: Does the square root of $i$ necessitate quaternions? The square root of i is $\frac{\sqrt{2} + i \sqrt{2}}{2}$. But how is it valid to use a number in expressing the square root of that number?

A: The set of complex numbers form an algebraically closed field. Hence, there exists solutions to $z^2=i$. You may want to look up the fundamental theorem of algebra. This guarantees that there are no rabbit holes, i.e., you do not need to move away from complex numbers. The problem of solving for square-roots, cube-roots and in general any polynomial equation is solved once and for all by the complex numbers.
In your case, you want to find a $z$ such that $z^2 = i$. If $z=x+iy$, where $x,y \in \mathbb{R}$, we get that
$$z^2 = (x^2-y^2) + i(2xy) = i \implies x = \pm y \text{ and } xy = \dfrac12 \implies x=y=\dfrac1{\sqrt{2}} \text{ or } x=y= - \dfrac1{\sqrt2}$$
Hence, we get that
$$i^{1/2} = \pm \left(\dfrac{\sqrt2 + i \sqrt2}{2}\right)$$ (Note that one of your solution is incorrect.)

A: Square it and see.  It works fine.  In the complex field, you can take the square root of any number.  If we use the polar representation $z=re^{i\theta}$ ($r, \theta$ real), the square roots will be $\sqrt r e^{\frac {i \theta}{2}}$ and $\sqrt r e^{\frac {i \theta}{2}+i\pi}$
This extends to $n^{\text {th}}$ roots.  The $n^{\text {th}}$ root of $z=re^{i\theta}$ is $r^{\frac 1n}e^{i(\frac \theta n+\frac {2k\pi}n)}$ for $k=0,1,2,\ldots n-1$


text:
Q: Matplotlib Chart border/colouring on x Axis values Is there a way to add lines/boxes on a matplotlib chart on the x Axis values?
See the image below, this is what I'm trying to do.
If that isn't possible, then is it possible to shade color the box between a specific range? example: Jan - Dec 2020 would be grey, 2021 black, 2022 green.
This would hopefully make it much easier to distinguish the years. Thankyou

df_orders.set_index('Date').plot.bar()

plt.title('Customer Orders: Discounted Vs Full Price', pad = 10, Fontsize =16)
plt.ylabel("Order Count", labelpad = 10, fontsize=14)
plt.xlabel("Year-Month", labelpad = 20, fontsize=14)

plt.tight_layout()

plt.legend(facecolor='white', fontsize =13,  framealpha=1)

plt.show()


text:
Q: php foreach as variable I'd like to use foreach to loop though an array list and add an element to each array.
$tom = array('aa','bb','cc');
$sally = array('xx','yy','zz');

$myArrays = array('tom','sally');

 foreach($myArrays as $arrayName) {
     ${$arrayName}[] = 'newElement';
 }

Is the use of ${$arrayName}[] the best way to do this?  Is there another option rather than using curly braces?  It currently works but I'm just wondering if there is a better alternative.
Thanks

A: Use references.
$myArrays = array(&$tom, &$sally);

foreach($myArrays as &$arr) {
  $arr[] = 'newElement';
}

A: If you're stuck to that structure, I would say stick to what you're doing there. But a comment might be nice.
If you can rearrange things, why not nest them?
$tom = array('aa','bb','cc');
$sally = array('xx','yy','zz');

$myArrays = array(&$tom, &$sally); // store the actual arrays, not names

// note the & for reference, this lets you modify the original array inside the loop
foreach($myArrays as &$array) {
    $array[] = 'newElement';
}

A: No curly braces needed.
$$arrayName[]

The original line is maybe a bug in PHP?
Although I wonder why you would ever need to do this anyway...

A: Some people will scold you for using variable variables.  You could do something like this:
$tom = array('aa','bb','cc');
$sally = array('xx','yy','zz');

$myArrays = array(&$tom, &$sally);

for($i=0; $i<sizeof($myArrays); ++$i) {
    $myArrays[$i][] = 'newElement';
}

A: Not tried, but should work, too:
$tom = array('aa','bb','cc');
$sally = array('xx','yy','zz');

$myArrays = array('tom','sally');

foreach($myArrays as $key => $value) {
    $$value[] = 'newElement';
}


text: Q: Using Kleene Star to define set of all tuples? How is a set $S$ of all the ordered tuples with elements from universe $\mathbb U$ defined?  For instance, $S = \{(), (x), (x,y), (x, (x,y))...\} \land x,y \in \mathbb U$.  Is the Kleene Star function composed $n$ times and summed $S =\cup_{i=1}^\infty \star^{(i)} (\mathbb U)$ the solution?  If not, what is?


text:
Q: turn off WooCommerce for a site in a multi site environment I've just installed P3 (Plugin Performance Profiler) and it shows that WooCommerce & WooCommerce Subscriptions are active on every one of my subdomain multi sites.
How do I turn plugins off on on a site by site basis?

A: Plugins are not like Themes were you need to network activate them to make them available on each site.
If you network activate a plugin, it will be switched ON for all network sites.
If you wish to allow each site to decide if they wish to activate or deactivate the plugin, then network deactivate the plugin in network admin.


text:
Q: GUI behaves differently in IDE vs command line I'm writing a GUI application in Java, and using Eclipse. However, the result of the code behaves differently when I compile and run using command line vs in the IDE itself. Here's the code:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.PasswordField;

public class MainGUI extends Application
{
    public static void main (String args[])
    {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception
    {
     primaryStage.setTitle("Citation Machine");
     GridPane grid1 = new GridPane();
     grid1.setAlignment(Pos.CENTER);
     grid1.setHgap(10);
     grid1.setVgap(10);
     grid1.setPadding(new Insets(20, 0, 0, 0));
     Label l = new Label("Welcome. Please enter your URL.");
     grid1.add(l, 0, 0);
     TextField urlField = new TextField();
     grid1.add(urlField, 0, 1);
     Button submit = new Button("OK");
     submit.setOnAction(e -> System.out.println(urlField.getText()));
     grid1.add(submit, 1, 1);

     GridPane grid = new GridPane();
     grid.setAlignment(Pos.TOP_CENTER);
     grid.setHgap(10);
     grid.setVgap(10);
     grid.setPadding(new Insets(20, 0, 0, 0));
     Text scenetitle = new Text("Welcome");
     scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
     grid.add(scenetitle, 0, 0, 2, 1);

     Label titleLabel = new Label("Article Title:");
     grid.add(titleLabel, 0, 1);

     TextField title = new TextField();
     grid.add(title, 1, 1);

     Label authorLabel = new Label("Author:");
     grid.add(authorLabel, 0, 2);

     TextField author = new TextField();
     grid.add(author, 1, 2);

     Label webTitleLabel = new Label("Website Title:");
     grid.add(webTitleLabel, 0, 3 );

     TextField webTitle = new TextField();
     grid.add(webTitle, 1, 3);

     Label publisherLabel = new Label("Website Publisher:");
     grid.add(publisherLabel, 0, 4);

     TextField publisher = new TextField();
     grid.add(publisher, 1, 4);

     Label urlLabel = new Label("URL:");
     grid.add(urlLabel, 0, 5);

     TextField url = new TextField();
     grid.add(url, 1, 5);

     Label monthLabel = new Label("Month of Publication:");
     grid.add(monthLabel, 0, 6);

     TextField month = new TextField();
     grid.add(month, 1, 6);

     Label dayLabel = new Label("Day of Publication");
     grid.add(dayLabel, 0, 7);

     TextField day = new TextField();
     grid.add(day, 1, 7);

     Label yearLabel = new Label("Year of Publication:");
     grid.add(yearLabel, 0, 8);

     TextField year = new TextField();
     grid.add(year, 1, 8);

   //  grid.setGridLinesVisible(true);
     Scene urlChecker = new Scene(grid1, 300, 150);
     Scene information = new Scene(grid, 400, 500);
     primaryStage.setScene(urlChecker);
     primaryStage.show();
    }

}

When I compile and run through CL, it works as expected, printing "pressed" to the CL when the button is clicked. When I run it through the IDE, nothing happens. Why does this occur?


text:
Q: How to place order in magento 2 using REST API? Preconditions
I have using REST API for placing order in PHP coding.
And then i have to set this to my android app.
Steps to reproduce
And i have following the steps of
a.) create empty cart b.) add items c.) post billing address d.) post estimate shipping methods e.) get shipping info f.) get payment info g.) place order
But Shipping Address is not set in my backend and the shipping methods returning empty array [ ].
Shipping info is also returning empty array.
billing address is generating the ID but it is not saving in my backend but it posts my address details..
Expected result
For Example:
Shipping Methods :
[
{
"carrier_code": "flatrate",
"method_code": "flatrate",
"carrier_title": "Flat Rate",
"method_title": "Fixed",
"amount": 15,
"base_amount": 15,
"available": true,
"error_message": "",
"price_excl_tax": 15,
"price_incl_tax": 15
},
{
"carrier_code": "tablerate",
"method_code": "bestway",
"carrier_title": "Best Way",
"method_title": "Table Rate",
"amount": 5,
"base_amount": 5,
"available": true,
"error_message": "",
"price_excl_tax": 5,
"price_incl_tax": 5
}
]

Actual result is attached in screenshot,
Thanks in advance