Codeigniter query

Question: My Query :
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where("`pos_item_sales`.`transaction_id` =  '$transaction_id' AND (`pos_item_sales`.`item_barcode` =  '$term' OR `pos_batch_infos`.`item_mbarcode` =  '$term' OR `pos_item_infos`.`item_id` =  '$term')");
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();

its solve my prob but i need like this query :
$term = $this->input->get('term',TRUE);
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where('pos_item_sales.transaction_id',$transaction_id);
$this->db->where('pos_item_sales.item_barcode',$term);
$this->db->or_where('pos_batch_infos.item_mbarcode',$term);
$this->db->or_where('pos_item_infos.item_id',$term);
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();

But I need a Query like :
SELECT *
FROM (`pos_item_infos`)
JOIN `pos_item_sales` ON `pos_item_sales`.`item_id` = `pos_item_infos`.`item_id`
JOIN `pos_batch_infos` ON `pos_batch_infos`.`item_id` = `pos_item_infos`.`item_id`
WHERE `pos_item_sales`.`transaction_id` =  '11355822927'
AND (`pos_item_sales`.`item_barcode` =  '8801962686156'
OR `pos_batch_infos`.`item_mbarcode` =  '8801962686156'
OR `pos_item_infos`.`item_id` =  '8801962686156')

how i solve this prob pls help because its not include ( ) in my or condition.
Comment: so what is wrong with your first code??? that should work..
Answer: if you go through the codeigniter userguide.. you can see that there are 4 ways to call where clause...
All of these does the same things... and your first code is codeigniter style (if incase you are worried that is not) that is the 4th method by codeigniter userguide where you can write your own clauses manually... there is no difference in calling the where function in anyways...
so i would go with your first query
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where("`pos_item_sales`.`transaction_id` =  '$transaction_id' AND (`pos_item_sales`.`item_barcode` =  '$term' OR `pos_batch_infos`.`item_mbarcode` =  '$term' OR `pos_item_infos`.`item_id` =  '$term')");
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();

which is perfectly fine...
Answer: In cases of complex queries i find it easier to just send raw query like this :
$query = "your query";
$result = $this->db->query($query);
Don't forget to escape variables before inserting them to the query like this :
$var = $this->db->escape($var);
Comment: my first query works fine but its a manual query . i need codeigniter style .
Comment: `$query="SELECT *
FROM (`pos_item_infos`)
JOIN `pos_item_sales` ON `pos_item_sales`.`item_id` = `pos_item_infos`.`item_id`
JOIN `pos_batch_infos` ON `pos_batch_infos`.`item_id` = `pos_item_infos`.`item_id`
WHERE `pos_item_sales`.`transaction_id` =  '11355822927'
AND (`pos_item_sales`.`item_barcode` =  '8801962686156'
OR `pos_batch_infos`.`item_mbarcode` =  '8801962686156'
OR `pos_item_infos`.`item_id` =  '8801962686156')"`

this is codeigniter style.
Answer: $query="SELECT *
FROM pos_item_infos
JOIN pos_item_sales ON pos_item_sales.item_id = pos_item_infos.item_id
JOIN pos_batch_infos ON pos_batch_infos.item_id = pos_item_infos.item_id
WHERE pos_item_sales.transaction_id =  ?
AND (pos_item_sales.item_barcode =  ?
OR pos_batch_infos.item_mbarcode =  ?
OR pos_item_infos.item_id =  ?)";
$params=array();
$params[]='11355822927';
$params[]='8801962686156';
$params[]='8801962686156';
$params[]='8801962686156';

$result=$this->db->query($query,$params);
$result=$result->result_array();
print_r($result);

Also, simplify your syntax with USING.
SELECT *
FROM pos_item_infos
JOIN pos_item_sales USING (item_id)
JOIN pos_batch_infos USING (item_id)
WHERE pos_item_sales.transaction_id =  ?
AND (pos_item_sales.item_barcode =  ?
OR pos_batch_infos.item_mbarcode =  ?
OR pos_item_infos.item_id =  ?)

Codeigniter query


How to read a column type SPUser, DateTime, Currency with EcmaScript?

Question: I have a list in SharePoint 2010 with some columns. All are default types. So I have
"Single line of text"
"Multiple line of text"
"Date and Time"
"Choice"
"Number"
"Currency"
"Person or Group"
My aim is to have a custom ribbon tab or group where I can perform some action on this list. As a starting point I created an Empty Element in my Visual Studio solution and put inside Elements.xml my buttons. This works so far. I also figured out how to do a postback to react on pressed button. This postback refers to a JavaScript file.
Before performing some action I tried first to read the given contents and return them using alert('first field: ' + field1). In first called function I have
function calledPostbackFunction(string button) {
    var context = SP.ClientContext.get_current();
    this.site = context.get_site();
    this.web = context.get_web();
    context.load(this.site);
    context.load(this.web);
    context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceded(button), Function.createDelegate(this, this.onQueryFailed));

How can I get the content from listed column types? I remember that I was able to read single text line and choice, but the rest crashed. So I guess I have to convert it any way. But how? IntelliSense doesn't helps a lot.
SUBQUESTION: I would skip using EcmaScript if you can tell me how to doPostBack to a .cs file where I can use Client Object Model. I found something but didn't work/ understand.
Yes, I though this will be easy, but it was not. At least because I only know C# a bit, no EcmaScript.
Thanks.
Answer: Okay, I got a solution Sharepoint.Stackoverflow.com from user Vardhaman Deshpande. This works.
Here is How to get the value of each type of field:
Title – SP.ListItem.get_item('Title');

ID – SP.ListItem.get_id();

Url -SP.ListItem.get_item('urlfieldname').get_url()

Description – SP.ListItem.get_item('descriptionfieldname').get_description();

Current Version – SP.ListItem.get_item("_UIVersionString");

Lookup field – SP.ListItem.get_item('LookupFieldName').get_lookupValue();

Choice Field – SP.ListItem.get_item('ChoiceFieldName');

Created Date – SP.ListItem.get_item("Created");

Modified Date – SP.ListItem.get_item("Modified"); -> case sensitive does not work with 'modified'

Created By – SP.ListItem.get_item("Author").get_lookupValue());

Modified by – SP.ListItem.get_item("Editor").get_lookupValue());

File  – SP.ListItem.get_file();

File Versions -  File.get_versions();.

Content Type – SP.ListItem.get_contentType();

Parent List – SP.ListItem.get_parentList();

from:
http://www.learningsharepoint.com/2011/07/06/how-to-get-various-item-fields-using-client-object-model-ecmascript-sharepoint-2010/
UPDATE: The following code is working and tested.
var item;
function getItemById(itemId){

    var clientContext = new SP.ClientContext.get_current();

    var web = clientContext.get_web();

    var list = web.get_lists().getByTitle('myList');

    item = list.getItemById(itemId);

    clientContext.load(item);

    clientContext.executeQueryAsync(onSuccess, onFailure);
}
function onSuccess(){

    alert(item.get_item("My User column").get_lookupValue());
}
function onFailure(){

    alert('Failure!');
}

Comment: how do you get the user id from lookup value ?


Ext JS, change grid column configs default values globally

Question: Ext.grid.column.Column class has following configs:

draggable (Defaults to: true)
sortable (Defaults to: true)
menuDisabled (Defaults to: false)

Is it possible to change default values of this configs globally for all grid columns in my application ?
Any help appreciated.
Answer: Given that the accepted answer is for ExtJS 5.x, I thought it would be useful to have an answer for ExtJS 4.x too.
Something like the following should do it:
<code>  Ext.define('Ext.my.grid.column.Column', {
    override : 'Ext.grid.column.Column',
    draggable : false,
    sortable : false,
    menuDisabled : true
  });
</code>
Now every time you use a column in a grid, it will take these as defaults.
Answer: yes, using Ext.override......
http://docs.sencha.com/extjs/5.1/5.1.0-apidocs/#!/api/Ext-method-override
example...
<code>Ext.override(Ext.grid.column.Column, {
 draggable: true,
 sortable: true,
 menuDisabled: false
});
</code>
Comment: draggable, sortable, menuDisabled are configs of 'Ext.grid.column.Column' class, not configs of 'Ext.grid.Panel' class.

Here you can see working example: https://jsfiddle.net/Yoh0xFF/dd7huux5/1/


Goblin Battle Standard doesn't summon the goblin army

Question: I'm on iOS edition (iPad mini) and I've just reached hardmode and made my Goblin Battle Standard. I have full health and really good weapons and armour my world is Crimson but for some reason it has no Crimson hearts in it which is annoying.
When I try use the Goblin Battle Standard all it does is show me holding it for a second and then doesn't consume. Can someone please help I really need the goblin tinkerer.
Answer: Per the Terraria Wiki on the Goblin Invasion:

The criteria for a Goblin Invasion to occur at all is as follows:
You must have smashed at least one Shadow Orb or Crimson Heart.
At least one player must have 200 HP or more.
If the player has not met both of these requirements, they will be unable to use a Goblin Battle Standard to manually summon the event.

If you haven't found a Heart to smash in your Crimson world, then you won't be able to run the invasion, either by chance or by using the Battle Standard.  If your world actually doesn't have any (I would try harder to find one first - I've not heard of that bug before, but anything's possible), then that world would never be able to run that Invasion event and you would have to generate a new world to be able to use the summoning item.


I can't save images to folder the app directory directly

Question: I have a method that calls the camera and save the image to the folder in the application directory
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File mFolder = new File(context.getFilesDir() + "/confirmation");
        File file = new File(mFolder.getAbsolutePath() + "/test.jpg");
        if (!mFolder.exists()) {
            mFolder.mkdir();
        }

        Uri outputFileUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        startActivityForResult(intent, 10);

Method context.getFilesDir() returns: "/data/user/0/com.example.kos/files"
confirmation is the folder in which i want to save the image
But it doesn't work, the file is not saved, what did I do wrong?
Comment: ` mFolder.mkdir();` Checkk the return value for false. It might not have created the directory. Then display a Toast and do not continue but return. Did you check if the directory is created?
Answer: But... the MediaStore will not save to getFilesDir().
Try getExternalFilesDir() instead.
Ohhh you are not saving to the MediaStore. But... the Camera app cannot store to your apps private direction too so use getExternalFilesDir().
After that you will have a FileUriExposedException.
After that you will use a FileProvider.
And after that you can use getFilesDir() again.


Desktop envivornment switching from unity to gnome resulted in blank background with side panel

Question: I tried to switch from unity desktop envivornment to gnome using the following commands
sudo apt-get install gnome-shell
sudo apt-get install ubuntu-gnome-desktop

And the result is a blank background and side panel as shown in the image
How do I remove this panel?
Answer: I think the image failed to come through...
Try this in the terminal:
sudo apt-get update; sudo apt-get install gnome-session-fallback

as suggested in this tutorial:
http://www.howtogeek.com/189912/how-to-install-the-gnome-classic-desktop-in-ubuntu-14.04/


Firebase Firestore nested collection in Cloud Functions

Question: I am trying to implement the nested query with Firestore in Cloud Functions but stumbled upon issues with reading values in a for loop. Are there ways to adjust the following code so I could do some operations after reading all records from a collection?
const firestore = admin.firestore();
        const today = new Date();

        const snap = await firestore
            .collection('places')
            .where('endDate', '<', today)
            .get()

        const userIds = [...new Set(snap.docs.map((doc: any) => doc.data().owner))];

        const updatePromises = snap.docs.map((d: any) => {
            return d.ref.update({
                isPaid: false,
                isActive: false
            })
        })

        await Promise.all(updatePromises);

        const userCol = firestore.collection('users');
        const userDocs = await Promise.all(userIds.map(uid => userCol.doc(uid).get()));
        const userData = userDocs.reduce((acc, doc) => ({
            ...acc,
            [doc.id]: doc.data()
        }), {})

        snap.docs.forEach((l: any) => {
            const ownerData = userData[l.owner];
            const { email, displayName } = ownerData;

            console.log(email, displayName);

            const message = {
                // Some values
            }

            return sendGrid.send(message);
        })

        return null;

{ owner: '<firebaseUid'>, address: 'Royal Cr. Road 234' }

{ email: 'email@example.com' }

<firebase_uid>: {
  displayName: '',
  email: '',
  phoneNumber: ''
}

Comment: Can you explain what do you mean by "some operations after reading all records"?
Answer: The userIds.push(owner); will keep adding duplicate values in that array and if a single user is owner of multiple locations, you'll end up querying same data multiple times. If you are trying to read owner's data along with a location, then try refactoring the code as shown below:
const firestore = admin.firestore();
const today = new Date();

const snap = await firestore
  .collection('locations')
  .where('isActive', '==', true)
  .get()

const userIds = [...new Set(snap.docs.map(doc => doc.data().owner))];

const updatePromises = snap.docs.map((d) => {
  return d.ref.update({
    isPaid: false,
    isActive: false
  })
})

// update documents
await Promise.all(updatePromises);

const userCol = firestore.collection("users")
const userDocs = await Promise.all(userIds.map(uid => userCol.doc(uid).get()))
const userData = userDocs.reduce((acc, doc) => ({
  ...acc,
  [doc.id]: doc.data()
}), {})

// To get data of a location's owner
// console.log(userData[ownerId])

snap.docs.forEach((l) => {
  const ownerData = userData[l.owner]
  // run more logic for each user
})

return null;

Comment: So if the user record has the `email` field, this shall now be available with `const { email } = userData;`, correct?
Comment: @Aleksandrs `userData` is an object where keys are user IDs and value is the data of that user. So you can use `const {email} = userData[userId]` where `userId` some owner ID from the `locations` documents.
Comment: do i have to make another loop to access it?
Comment: @Aleksandrs can you explain what are you trying to do? I assume you have a location's owner's ID and want to get that user's email or data? How are you rendering all the locations at first place? You must be mapping the data somewhere? I updated the answer if that's what you are looking for?
Comment: i am trying to hide unpaid locations and then notify users by email with SendGrid. the location has owner, which references the userID in users table. the users table in turn stores records with emails, so i want function to find the collection, get users through the reference, and then send out emails
Comment: @Aleksandrs there's no context about that in your question. We don't know how you figure out if a location is unpaid or no. If that's a field you can just use a query `where("unpaid", "==", false)` so something similar. For your original question, you can iterate over the array and call your sendgrid service. Updated answer
Comment: something is wrong with the code. do you refer to querySnapshot as snap?
Comment: the values in `locations` also don't get updated
Comment: so can i now access the email with `const ownerData = userData[l.owner]            const { email } = ownerData;`?
Comment: @Aleksandrs yes. that's correct. Also that `querySnapshot` is supposed to be `snap` yes.
Comment: Cannot destructure property 'email' of 'ownerData' as it is undefined.
Comment: could you please help in adjusting this?
Comment: @Aleksandrs that means the value is undefined. My best guess is there is no document with ID as owner's UID. Also please update the code that you are running now in your question if that's not the case.
Comment: Updated the code. You are right. owner does not have the ID field, it should be the document ID
Comment: The document ID must be user's Firebase Auth UID in users collection. @Aleksandrs
Comment: yes, but it still undefined, or do you mean i have to change something?
Comment: @Aleksandrs the code seems fine. Do you mind `console.log(userData)` and share a screenshot of that? Also a screenshot of your users collection document might help to verify that the document actually exists
Comment: @Aleksandrs doesn't include a screenshot from Firestore. Your data is missing but the code seems to be correct then.
Comment: can i point to the document id so i don't have to include in a users record?


Coins displaying as popsicles?

Question: All of my Temple Run coins are being displaying as little popsicles. Is this a bug in the game? Should I reinstall Temple Run? I just don't want to lose all of my progress.
Comment: My guess is that it is some sort of summer themed update or something, but I don't play the game myself.
Comment: Have you connected the game to Game Center (iOS) or Play Store (Android)? If so, your progress will be saved and restored if you reinstall the game.
Answer: It is a themed update for the summer. They regularly change the standard coins to other shapes in Temple Run 2 for special occasions, for example ghosts for Halloween or shamrocks for St Patrick's Day.
Answer: Coin skins can be changed at the main menu screen

Coins displaying as popsicles?


How can I add a level to a MultiIndex?

Question: index = [np.array(['foo', 'foo', 'qux']),
         np.array(['a', 'b', 'a'])]
data = np.random.randn(3, 2)
columns = ["X", "Y"]
df = pd.DataFrame(data, index=index, columns=columns)
df.index.names = ["Level0", "Level1"]
print df

                      X         Y
Level0 Level1
foo    a       0.418549  0.252685
       b      -1.307099  0.202833
qux    a       0.046095 -0.968976

New level
I want to take the index of df and create a new MultiIndex that now has an additional level.
new_level_name = "New level"
new_level_labels = ['p', 'q']
# new_multi-index

Desired MultiIndex
Level0 Level1 Level2
foo    a      p
              q
       b      p
              q
qux    a      p
              q

Answer: The simpliest is use stack with new DataFrame with columns by new level values:
df1 = pd.DataFrame(data=1,index=df.index, columns=new_level_labels).stack()
df1.index.names = ['Level0','Level1',new_level_name]
print (df1)
Level0  Level1  New level
foo     a       p            1
                q            1
        b       p            1
                q            1
qux     a       p            1
                q            1
dtype: int64

print (df1.index)
MultiIndex(levels=[['foo', 'qux'], ['a', 'b'], ['p', 'q']],
           labels=[[0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 1]],
           names=['Level0', 'Level1', 'New level'])

Comment: Yes, I try it too, but if not `1` there are default `NaN`  and all rows are removed.
Comment: ah brill! I had tried almost the exact same thing, but didn't include data=1!
Comment: The result is actually a pd.Series, not DataFrame (?). Can't believe there is no better method...
Comment: @n1000 - Do you think `print (df.reindex(df1.index))` ?
Answer: Not exactly sure what data should be in your desired DataFrame, but for a similar problem I used melt():
df1 = df.reset_index()
pd.melt(df1, id_vars=['Level0', 'Level1'])

    Level0  Level1  variable    value
0   foo a   X   0.678564
1   foo b   X   -0.609134
2   qux a   X   0.505178
3   foo a   Y   -2.593380
4   foo b   Y   -0.232796
5   qux a   Y   -1.420875

How can I add a level to a MultiIndex?


Air conditional protection in winter

Question: My house has a air conditioner,I am not sure I should call it furnace or air conditioner. it works as a air conditioner in summer but work as a heater in winter.
Today I found the condensing unit (the part outside the house) actually doesn't spin during heating process, so I am thinking about if we need to add some plastic to protect snow/rain into it.
But I am not sure weather the heating process need the condensing unit air or not.Should I just cover a plastic bag onto condensing unit in winter?
Comment: It is called a heat pump.  It does use the condenser unit during the heating phase (it gets the heat from outside via the condenser), I haven't had contact with one that didn't spin the fan, but limiting its access to outside air would seem to decrease its efficiency.
Comment: Well, that's if it *is* a heat pump and not just a standard condenser that's part of a split system. As the OP has to deal with snow, I wouldn't think it is, but I've never even seen one. You have, but not one that didn't spin the fan, so there's that too. Regardless, don't cover it...
Answer: Personally, I've never known of anyone to cover their outdoor a/c equipment. A quick Google found most saying no and a few saying yes...conditionally. This page summarizes their opinion as:

Should you cover your air conditioner in the winter?  Probably not,
  but it's worth a thought during hails and heavy winter storms.  Your
  air conditioner is one of your most expensive investments, so take
  care of it and service it properly.  I will say, one last time, that
  covering your air conditioner in the winter is not a necessary
  precaution in most cases.

It's worth pointing out, however, that they seem to be a heating and air company in California.
This page, which is a company in Wisconsin notes:

In my opinion, it's best to leave the A/C unit uncovered. In the
  spring, our company handles more repairs for units that were covered
  during the winter.

..that's a compelling thought.
But you do have a valid concern with respect to seasonal maintenance. It would be wise to do some research on seasonal maintenance for outside compressors going into the Spring, prior to their return to use after a winter hiatus. I imagine checking for and cleaning away any debris at the least.

Air conditional protection in winter


KineticJS. Drag shape and move all group

Question: I am new to KineticJS.
I want to make something similar to this example: http://www.html5canvastutorials.com/kineticjs/html5-canvas-drag-and-drop-a-group-with-kineticjs/
My problem is that I only want the purple rectangle to be draggable, not all the group, but I want that the rest of the rectangles move together with the purple rectangle when I drag it.
Thanks for your help.
Answer: In other words, you want only the purple rectangle to be "listening" for events? Then disable it for every other rectangle, e.g. if (colors[i] != 'purple') box.listening(false);


What is the actual meaning of runs in terms of coin tossing?

Question: I am not able to understand the concept of runs in terms of coin tossing. As per my question, suppose a coin is tossed x times, then we have to find the expected number of runs.
But, what is a run? Can anybody give a detailed example?
As per the question, the sequence of tosses HHHHTTHTTTHHHTHH has 7 runs. How? I am really not able to understand. I researched and found somewhere that a run is when the previous outcome is different from current, so for this case, how will it apply?
Can somebody please explain in layman terms?
Thanks
Comment: A run is a sequence of consecutive H or T that cannot be extended forwards or backwards.
Comment: a run is a string of h or t
Comment: so in your case, hhhh, tt, h, ttt, hhh, t, hh are you runs
Comment: Why will h and t will be the runs? they are not with the same result? Should not the concept of run apply to more that one value of h/t?
Comment: HTHT has 4 runs (short ones!).
Comment: Runs are very useful. Sometimes (indeed more than sometimes) experimental results are invented, or improved on. Badly done invented data tend to have too many runs. This is easily detected.  But it is possible to cheat well.
Comment: @AndréNicolas:Thanks, this is very helpful.
Comment: You are welcome.
Answer: Take the full sequence and cut it at each point where there is a transition (next value is different from the previous one). Each part is a run.
<code> HHHHTTHTTTHHHTHH  =>  HHHH TT H TTT HHH T HH   => 7 runs
</code>
In other words, elaborating on Peter's answer, a run is a maximum-length subsequence of equal values.
Comment: Thanks a lot, it is clear now. :)
Answer: A run is a sequence of equal outcomes (4 times heads , 7 times tails , etc.), so
 if you have n changes from head to tail or vice versa, you have n+1 runs.
Comment: In the case of HHHHTTHTTTHHHTHH, i can understand that the following will be the cases of runs: HHHH, TT, TTT, HHH, HH. But why H and T will be also in runs? They are not sequences right?
Comment: @user3097157 they are part of the run, not a run themselves unless there is a change directly after H or T
Comment: @Rustyn, Can you please elaborate little more?
Comment: For example in this sequence: HTHHTHTHTHT. The runs are: H,T,HH,T,H,T,H,T,H,T. The runs are the chunks of tails or the chunks of heads right before there's a change.
Comment: A sequence of length 1 is still a sequence, though it is not commonly referred to as a run.


problems with sign out, cookies and devise on rails

Question: I have been trying to sign in after signing out on my application using devise but I am having an issue with the cookies I think because I have to refresh my web page in order to sign in again. I tried using activerecord-session_store gem and I follow the steps to configure it. I mean, I installed the gem, I generated the recommended migration on the gem documentation and generated the table using rake db:migrate command, I also changes the session_store.rb file but I feel that I am missing something to make it work since I tried it and the same happens. Please help me if you feel I am missing something or if you have other solution for this problem. Many thanks in advance
Answer: You are probably getting a "Can't verify CSRF token authenticity" error. Can you check your server logs?
In your ApplicationController please add the following and check if you get an error.
protect_from_forgery with: :exception
Comment: Hi Eelco, it cant be a CSRF error because I have that line-code from the beginning "protect_from_forgery with: :exception" and no error is reported


Does $BA = CA$ imply $B = C$?

Question: I know this is too simple of a question, but I haven't been able to prove it by myself so here we are.
If $A, B^T, C^T \in \mathbb{R}^{D \times d}$ (with $D \ge d$) are full rank matrices, does $BA = CA$ imply $B = C$?
Comment: If $A$ is full rank, then the linear map $x \mapsto Ax$ is surjective. Hence $By=Cy$ for every $y \in \Bbb R^{d \times 1}$.
Comment: Maybe look at some examples for $d = 1$?
Answer: No. In the case D = d, A = O is a good example.
In the D > d case, zero matrix is still a contradiction example for you guess.
Do you wanna consider full ranked matrices? I just tell a simple case which B = wC where w is a real non-zero scaler. A similar full-ranked A can make both sides 0 (prove: BA = 0 & BA = CA so BA = CA = 0. On the other hand, B = wC so BA = wCA = 0. w is not equal to zero, so CA is equal to zero. You can conclude in a briefer way).
This discussion can be continued. You need to consider boundary situations & trying to make a stronger conjecture.
Comment: I see, I was confused about what you were saying since you started off by taking $A$ to be the zero matrix, and didn't explicitly give any other matrix as an example.
Comment: @MishaLavrov Please check the 2nd paragraph. For making a matrix multiplication to be 0, being 0 isn't needed (like what we see in 0 dividers, in advanced algebra).
Comment: @MishaLavrov Please check this & if there's any mistake let me know. A = [2,-12;-4,0;2,4], B = [1,2,3;4,5,6]. Both of them are full rank matrices which is equal to 2, since max rank = min (d,D). Simply consider w=2 to create C (I wrote B = wC in my answer). Calculation for C isn't needed because scaler can be factored.
Comment: That example doesn't quite work: I get $-24$ in the bottom right entry of $BA$. Here is an example with $d=2$ and $D=4$: $A = \begin{bmatrix}1 & 0 \\ -2 & 1 \\ 1 & -2 \\ 0 & 1\end{bmatrix}$ and $B = \begin{bmatrix}1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 8\end{bmatrix}$.
Comment: (To get $BA = 0$ when $A$ and $B$ are full-rank matrices, we need $D \ge 2d$. To have $BA=0$, we want the column space of $A$ to be in the null space of $B$, but the column space of $A$ has dimension $d$ and the null space of $B$ has dimension $D-d$, so we want $d \le D-d$ or $D\ge 2d$. But the implication $BA = CA \implies B=C$ stops holding in general once $D > d$, just for other reasons.)

Does $BA = CA$ imply $B = C$?


Diagnose 125v 20a receptacle voltage

Question: I am replacing a 20A 250V receptacle with a NEMA 5-20 and am seeing voltages I can't explain.

Hot-ground: 122v
Neutral-ground: 20v
Hot-neutral: 95v

What could be the problem here?
Details

Turned off main
Removed 2 pole circuit breaker
Capped red wire
Installed 1 pole breaker and connected black wire
Turned on main
Remove old receptacle, discover there are only 3 wires - white, black, ground (this receptacle is labeled 20A 250V)
Installed NEMA 5-20 receptacle - black to brass, white to silver, ground to green as per instructions.
Read above voltages

Where did my red wire go?
I am certain I replaced the correct breaker. No voltage when I turn the breaker off.
The wire appears to be 12 gauge.
My outlet tester is inconclusive because all three lights appear to be lit.
Comment: How many poles are on the existing breaker?
Comment: What happens to the white wire at the breaker panel end?
Comment: Removed breaker had 2 poles. Installed breaker has 1 pole.
Comment: Plug a lamp into the outlet, turn it on, then measure all voltages again. This will remove any doubt about phantom voltages, whether the lamp lights or not.
Answer: So in the breaker box, you have black, red and ground but in the outlet box you have black, white and ground.
Odds are that you have a junction box somewhere where the red wire is connected to the white wire. Since you capped the red wire in the breaker box, the white wire is not connected, just floating.
I'm also assuming you checked the voltages with a digital voltmeter. In this case, you're seeing a phantom voltage, induced from other wires. The voltmeter provides very little load.
To test this, plug an outlet tester into the outlet, it should show "open neutral". You can also measure the voltage with the tester plugged in. You should now see 120 volts (or nearly that) on the white, conducted through the tester.
Assuming all of that proves true, you need to land the red wire onto the neutral bus in the breaker box. I'd also suggest marking the end of the red wire as white, either with paint or tape.
Comment: I'll give that a try. When I plug an outlet tester in all three lights are on, which means nothing. 20v across the neutral-ground is pretty high. Could that be a phantom load?
Comment: Also, I think my neutral bus is full. Can I land the red wire onto the neutral bus somehow, or can I install a longer bus?
Comment: I'm concerned that you are getting three lights on your tester. I wouldn't think the phantom voltage would light it. I'd still try connecting the red to neutral.
Comment: You can try connecting the red to the ground bus **as a test only. Don't leave it there! It's against code and potentially dangerous**. If this solves the problem, you do need to move it to the neutral bus. You could add a second one and connect them together. Be sure to remove the grounding screw on the new one.
Answer: More than likely you have a junction box, receptacle or switch between there and the panel that drops the neutral and passes the "red" hot over the white wire.

Diagnose 125v 20a receptacle voltage


Is there a command to count how many mobs have passed a certain area?

Question: I want to test a mob farm I'm making, and can't currently install things like carpet mod, I tried using:
execute
  if @e[type=zombified_piglin]
  positioned x y z
 run give @s diorite 1

on a repeating command block, but it just gave me diorite even if it was not in the right position. I also think that this command probably wouldn't work for a farm because not every entity would be at the specified block at any given time.
Answer: You could use a dummy scoreboard to count the amount.
scoreboard objectives add Counter dummy

Then add a player or an invaluable armor stand with a custom name like Zombified Pinglings.
scoreboard players add SemlanBakelsen Counter 1

or
scoreboard players add @e[type=armor_stand,name="Custom name"] Counter 1

You can then display the score on the screen with:
scoreboard objectives setdisplay sidebar Counter

Then using the x y z and dx dy dz in the target selector:
@e[x=...,y=...,z=...,dx=...,dy=...,dz=...]

You can specify a cube/rectangle area.
Then set up a repeating command block followed by 2 chain command blocks with the code.
This block finds any zombified piglings in the area of 40 56 -1 with a distance of up to 2 blocks, and then adds a tag to the entity:
execute if entity @e[type=minecraft:zombified_piglin,x=40,y=56,z=-1,distance=..2,tag=!1,tag=!2]
run execute as @e[type=minecraft:zombified_piglin,x=40,y=56,z=-1,distance=..2,tag=!1,tag=!2]
run tag @s add 1

2:nd block; executes all enteties that got the last tag and adds a point to the dummy scoreboard that was set up earlier:
execute if entity @e[type=minecraft:zombified_piglin,x=40,y=56,z=-1,distance=..2,tag=1,tag=!2]
run scoreboard players add SemlanBakelsen Counter 1

The last block; adds an additional tag to the entity so that the previous blocks don't add more than 1 point to the score:
execute as @e[tag=1,tag=!2] run tag @s add 2

This will make sure the counter only goes up by 1 for every unique entity.
If this will be used at a mob farm, you could specify the whole spawn area and the mobs would get counted when they spawn. And naming an invaluable armor stand different mob names you could count any mob separately. Remember that if the armor stand/player that the dummy scoreboard is added to would die the score would reset, i.e. the score will set to null.
If you want to specify a cube/rectangle area remove distance=... and add dx=...,dy=...,dz=...
If you want to use the 'give diorite' system you could replace the scoreboard part scoreboard players add SemlanBakelsen Counter 1 with give SemlanBakelsen minecraft:diorite 1, of course replacing my name with whoever should get the item.
This site can be useful for custom armor stands:
https://haselkern.com/Minecraft-ArmorStand/
Answer: What your sample command is really doing:
execute
  if @e[type=zombified_piglin] # If a zombified piglin exists anywhere,
  positioned x y z             # run the following at (x,y,z)
run give @s diorite 1          # Give a diorite block.

What you need to change to make it work:
execute
  if @e[type=zombified_piglin,x=...,y=...,z=...,distance=..1] # If a zombified piglin exists within 1 block of (x,y,z),
run give @s diorite 1          # Give a diorite block.


Why are all elements replaced in stack after new one added?

Question: Simple stack implementation in C:
struct Stack {
  char* data;
  Stack* prev;
};

void push(char* data, Stack** stack) {
  Stack* node = (Stack*)malloc(sizeof(Stack));
  node->data = data;
  node->prev = *stack;
  *stack = node;
}

int main() {
  Stack* top = NULL;
  push("1", &top);
  push("2", &top);
  push("3", &top);
}

then top->prev->prev->data results into 3 same as top->prev->data and top->data.
Can anybody explain why?
Comment: @unwind: It's likely that kassie is using a c++ compiler to compile this code. Otherwise there would be a number of other errors.
Comment: [Please don't cast the return value of `malloc()` in C](http://stackoverflow.com/a/605858/28169).
Comment: you have passed to `push` the buffer(pointer) of probably identical. I think that it is necessary to copy the contents by securing a new area.
Answer: So, it appears to work correctly.
#include <stdlib.h>
#include <stdio.h>

struct Stack {
    char* data;
    struct Stack* prev;
};

void push(char *data, struct Stack** stack) {
    struct Stack* node = malloc(sizeof(struct Stack));
    node->data = data;
    node->prev = *stack;
    *stack = node;
}

int main() {
    struct Stack* top = NULL;
    push("1", &top);
    push("2", &top);
    push("3", &top);

    printf("top->data: %s\n", top->data);
    printf("top->prev->data: %s\n", top->prev->data);
    printf("top->prev->prev->data: %s\n", top->prev->prev->data);
}

The output is:
top->data: 3
top->prev->data: 2
top->prev->prev->data: 1

Comment: Yes, be sure to always call your new `struct`-type with this keyword before it. You can avoid that by doing a `typedef struct MY_STRUCT { ... } MY_STRUCT;`


Baseboard heat - Installed and then drywall around

Question: I'm in a 1980s house that has baseboard heat. The baseboards are pretty beat up so was going to use a product like neatheat or baseboarder to cover.
When I started looking at the way that they were installed, the heating units themselves are 'sunk' into the wall... like they were installed, and then drywall was hung around them.
Have others seen this? (end caps are not able to be removed...the front piece can be removed on some units, but not others).
Will I be able to use any of these retrofit covers given how the drywall was installed?
Comment: Model #s (if you can find any - possibly under the front piece) and pictures would help.
Comment: @isherwood how to make it look great!
Answer: I do not think that you will be able to use any of the products you mentioned since they both fit over the whole wall mounted baseboard enclosure. Your enclosure is installed as you said, with the drywall set on top of the enclosure so you do not have access to the back of the enclosure. I have only seen this type of installation done once before. I do not know the company that installed them that way but "what a mistake". You will probably be limited to either painting what you have or trying to buy new enclosures from the same manufacturer as those installed. Good luck in your search for a fix.


Prove that if $f'(c)>0$ (strictly positive) for all $c\in(a,b)$ then $f(x)$ is strictly increasing on $(a,b)$

Question: Prove that if $f'(c)>0$ (strictly positive) for all $c\in(a,b)$
then $f(x)$ is strictly increasing on $(a,b)$
It is true that if $f(x)$ is strictly increasing on $(a,b)$ then
$f'(c)>0$ (strictly positive) for all $c\in(a,b)$? If it is true,
prove it. If it is not, find a counter example.
Let $c \in (a,b)$ be arbitrary we will show $f'(c)>0$. Consider a sequence $x_n \rightarrow c$. Since $f$ is differentiable at $c$ we have that $\frac{f(x_n)-f(c)}{x_n-c} \rightarrow f'(c)$. Now since $f$ is strictly increasing and $x_n \rightarrow c$ we have that $f(x_n)>f(c)$.($f(x_n) \not = f(c)$ since $f$ is continuously getting larger). Thus $\frac{f(x_n)-f(c)}{x_n-c}>0$ and therefore $f'(c)>0$.
I feel the second is also true but not sure what to add.
Comment: Maybe you should add as a hypothesis that $f\in C^1(a,b)$
Comment: @StanislasHildebrandt $C^1$ is not needed.
Answer: The second part, that if $f(x)$ is strictly increasing on $(a, b)$ then $f'(c) > 0$ for all $c \in (a, b)$, is not necessarily true. Consider $f: (-1, 1) \to \mathbb  R$ where $f(x) = x^3$ as a counterexample. Your proof is flawed in that you assume
$$ (\forall n)\ \frac{f(x_n) - f(c)}{x_n - c} > 0 \implies f'(c) = \lim_{n \to \infty} \frac{f(x_n) - f(c)}{x_n - c} > 0$$
Limits do not preserve strict inequalities, just weak ones. Hence your proof does show that $f'(c) \geq 0$, which is true. But $f'(c) > 0$ is too strong a result.
A big hint to prove the first part, that if $f'(c) > 0$ for all $c \in (a, b)$ then $f$ is strictly increasing, is to use the mean value theorem.
Answer: Assume $f$ is differentiable on the open interval $(a,b)$ (so that $f'(c)$ makes sense for any $c\in (a,b)$) then $f$ is differentiable on any open subinterval $(x,y)\subseteq (a,b)$. By the mean value theorem there exists $c\in (x,y)$ such that
$$\frac{f(y)-f(x)}{y-x}=f'(c)\Rightarrow f(y)-f(x)=f'(c)(y-x)>0\Rightarrow f(y)>f(x)$$
since by assumption $f'(c)>0$ (and also $y>x$). Therefore $f$ is strictly increasing on the interval $(a,b)$ since $(x,y)$ was arbitrary.
Also for the second question: if $f$ is strictly increasing then $f(y)>f(x)$ whenever $y>x$. Then by definition of the derivative $$f'(x)=\lim_{y\to x}\frac{f(y)-f(x)}{y-x}\geq 0.$$
Edit: Counterexample to strict inequality as provided by @bitesizebo.
Comment: The second one is wrong; you show that $f'(c)>0$ for *some* $c$ between $x$ and $y$, but that doesn't mean that it's true for *all* $c$.
Comment: Even after your edit, your answer to second question is still wrong (same mistake a the OP): if a function is $>0$, its limit can be $0.$ See also @bitesizebo's counterexample.


How can I repair a washed out asphalt driveway culvert area?

Question: Asphalt driveway washed out up to the edge of the asphalt due to heavy rains. Previously put 2 to 4 inch rocks and hard red clay soil at road edge and around top and sides of 36" covert but all of it washed away with the rain and water. How can I repair this myself.
Comment: Step one - more pipe. That needs to exit (and if the same on the other side enter) considerably further from the edge of the road so it does not wash out.
Comment: Thank you for suggestion. I do need to extend the culvert at least another 5-6 feet.
Answer: I suspect your problem is not the stone you used, but the fact that the water is draining through and undermining the soil underneath, allowing the rocks to wash away.
I don't know what area of the country you are in, but in the Pacific NW I used to see large rocks encased in wire cages used for drainage.  The cages are called gabions and make sure that the drain rock stays in place during floods.
What I would do is this:

Excavate about 1-2 ft around the sides and 3-4 feet out from the end of your culvert.

Place heavy landscape fabric on top of the excavated soil.  Secure it with wire staples. The landscape fabric will serve two purposes.  First, it will keep the rock from sinking down and mixing with the soil when everything gets wet and soft.  Second, it will allow some water to infiltrate so you don't just push all of the flooding somewhere else.

On top of that, build your gabions. You can use cattle panel, chicken wire, or even chain link fencing depending on the size of your drain rock.  The gabion can be square, rectangular, etc.  The idea is to fully line the culvert area as well as up to the road bed, almost like giant porous bricks.

Fill with your drain rock.  I would suggest rip-rap.  It's usually inexpensive because it isn't super pretty and the pieces are anywhere from tennis-ball to basketball sized.

Fold the gabion casing up around the sides and over the top of the rock.  Secure with wire ties to keep the wire mesh from opening.

If you really want to make sure it stays in place, drive some metal T-posts through the gabion into the ground to lock it in.
Comment: Thank you for explaining in such detail. Your suggestion will save me money. I had planned to use bigger size, more expensive 10" rock around the culvert but using chicken wire casing I can apply 4"-6" riprap (1"-2" bigger than my previous rocks) and not run the risk of loosing them during the next NE Texas deluge. This was a 1 in 50 year storm, with 6" of rain in less than an hour; so hopefully I won't have to worry about washouts for many years.
Answer: Obviously small rocks don't cut it. In my region you often see layers of small boulders in situations like that--both around the pipe exit and as a splash buffer downstream a bit.
I suggest that strategy. To go all-out you'd embed the boulders in concrete.
Comment: Thank you for your suggestion. I plan to extend the culvert, then use Chris O's suggestion to use chicken wire to case riprap. Bigger rock is definitely a must also.


How to add an xml element and wrap the data (inner-text) in CDATA tags using ElementTree

Question: I'm struggling to find a good example of how one would add an XML Element to an XML Document and also add the data (inner-text) to this same element, but wrap the data in CDATA tags?
Here is an example of what I need.  I have the following document.
<data>
     <config>
          <documentation>This is my documentation<documentation>
     </config>
</data>

I then want to add a  element and CDATA as the inner-text.  So it would look something like this.  The data that I need to wrap in CDATA tags can be fairly large and will need to be read/referenced from file.
<data>
     <config>
              <documentation>This is my documentation<documentation>

     </config>
</data>

I then need to write the changes out to a new document... (so that I have the original and the additions.
Comment: Possible duplicate of http://stackoverflow.com/questions/174890/how-to-output-cdata-using-elementtree and http://stackoverflow.com/questions/4474754/how-to-keep-comments-while-parsing-xml-using-python-elementtree?rq=1
Answer: You should be able to use the .CDATA() method provided by lxml.
http://lxml.de/api.html#cdata
Just create a SubElement as normal
some_var = root.find('config')
another_var = etree.SubElement(some_var, 'script')
another_var.text = etree.CDATA(another_var.text)

Then you can write the data out as normal.


Live USB doesnt recognize any bootable file on usb. Booting from usb gives disc error

Question: Windows is screwed up and I cannot register it on my computer (product on HD doesn't match product previously on motherboard). So I decided to just run Ubuntu instead. I put the Ubuntu .iso file I downloaded off this site on a USB and tried to boot it from there but is gave me a disc error and never showed Ubuntu as an option.
I must be doing something wrong. It probably isn't as simple as Im hoping
Answer: check USB is bootable or not. if not then follows this step to make USB bootable .
Afterwards you can boot from the USB as if you booted from a CD and proceed to install Ubuntu on your hard disk.
more information visit here


Evaluate $ \int_0^1 \sqrt{x}\sin(x)dx $ to accuracy 0.001.

Question: Evaluate
$$
\int_0^1 \sqrt{x}\sin(x)dx
$$
to accuracy 0.001.
By definition, there exists an N such that for n > N,
$$
\left| \int_0^1 \sqrt{x}\sin(x)dx - \sum\limits_{i=1}^n \sqrt{x^{*}_i}\sin(x^{*}_i) \Delta x\right| <0.001.
$$
But from there I do not know how to proceed.  Are there any theories regaurding approximation that would be helpful?
Answer: Hint
Use the Taylor series expansion of $\sin x$ and do term wise integration.
$$\sqrt{x}\sin x = \sum_{k=0}^{\infty} (-1)^k\frac{x^{2k+\frac{3}{2}}}{(2k+1)!}.$$
To get the desired accuracy you will need to adjust the number of terms you want to use.
Answer: $\text{Hints: }$
$$\sqrt x \sin x = \sqrt x\sum_{n=0}^{\infty} \frac{(-1)^n x^{2n+1}}{(2n+1)!} = x^{1.5} - \frac{x^{3.5}}{3!} + \frac{x^{5.5}}{5!} - \frac{x^{7.5}}{7!} + \dots$$
$$| \text{error} | \le |\text{First unused term}|$$
$\text{Your integral is then simple to evaluate using }$
$$\int_a^b x^kdx = \left[ \frac{x^{k+1}}{k+1} \right]_a^b$$
Comment: How could you justify that the error is less than the absolute value of the first unused term?
Comment: @WhiteRice Alternating Series Estimation Theorem. The limit that the series converges to ($L$) lies between the successive partial sums $s_n$ and $s_{n+1}$ and hence differs from $s_n$ by an amount less than $u_{n+1}$ where $\{u\}$ is the sequence of terms in the series. So, $|L - s_n| < u_{n+1}$, which means that $|\text{error}| < u_{n+1} \implies |\text{error}| < |\text{First unusued term}|$
Answer: Using @Mohammad Ali Baydoun: ideea, the integral lies between the increasing sequence
$$ \int_0^1  \sqrt{x}\cdot (x - \frac{x^3}{6}) dx, \int_0^1  \sqrt{x}\cdot (x - \frac{x^3}{6}+ \frac{x^5}{120} - \frac{x^7}{7!})\,dx, \ldots $$
and the decreasing sequence
$$ \int_0^1  \sqrt{x}\cdot x\,  dx, \int_0^1  \sqrt{x}\cdot ( x- \frac{x^3}{6}+ \frac{x^5}{120})\,dx, \ldots $$
These are sequences of rational numbers, easy to evaluate,  that converge to the same limit $\int_0^1 \sqrt{x} \sin x dx$.
Note that the inequalities between $\sin x$ and its odd and even order Taylor approximations are valid for all positive $x$, something that does not follow right away from Leibniz estimate for alternating series with decreasing absolute values of terms. See the picture below:

The fifth and the seventh order Taylor approximation already give the correct fourth  decimal :
$$\frac{608527}{1670760} < \int_0^1 \sqrt{x} \sin x dx< \frac{2557}{7020}$$
The approximation on both sides
$$\sqrt{x}\cdot (x - \frac{x^3}{6}+ \frac{x^5}{120} - \frac{x^7}{7!})\le \sqrt{x} \sin x \le \sqrt{x}\cdot (x - \frac{x^3}{6}+ \frac{x^5}{120} )$$ on $[0,1]$ has an error less than $\frac{1}{7!} = \frac{1}{5040}< \frac{1}{5000} = 0.0002$ so the estimates for the integrals are apriori better than $0.0002$ since the interval has length $1$. It turns out that the estimates are better than $0.0001$, as we see from evaluating both of the fractions.
Comment: Nothing more convincing than a pretty graph


LTE network connection with USB stick

Question: I am running 15.10 on a Lenovo ThinkPad R61 and have been running Ubuntu since 8.04 on this machine. Since upgrading to 15.04 I have serious trouble with mobile broadband connections via USB modems.
While nm-applet says that a connection was established, there is actually no connection. One needs to repeat the 'connect to...' action several times until eventually a working connection becomes established. Once the connection is established, it remains stable as long as the current user is in an active session.
I have no clue where to start looking for system messages that could help further. On booting I occasionally see 'Internal Errors detected' messages mostly showing crashes of a package. Right now it says the urfkill package has crashed. Could there be a connection to the network connection issues?
I am happy to provide you any logfile output that could help. However, I did not want to flood my posting with potentially useless logfile copies. What can be done to enable mobile broadband to connect reliable and on the first trial?
Answer: I was lucky enough to get access to a Linux Pro during Chemnitzer Linuxtage 2016 where an open workshop took place to support folks with their Linux problems. After two hours of fiddling he finally identified the reason for my LTE stick issue and solved it. I am happy to share the solution with you. So hopefully it helps others, too.
Obviously, Ubuntu network manager sometimes fails to add standard route 0.0.0.0 for device ppp0 (the LTE stick in my case). This causes name server issues and prevents your system from reaching any external resources, while nm-applet still displays the 'connected' icon.
Problem gets solved by manually adding this route 0.0.0.0 via shell script when ppp0 gets connected. The script goes to <code>/etc/network/if-up.d/</code> and looks like this:
<code>#!/bin/bash

if [ "$IFACE" == "ppp0" ]; then
  /sbin/ip route add to 0/0 via 0.0.0.0 dev ppp0 metric 750
fi
</code>
That's it.

LTE network connection with USB stick


How should I update my wi-fi driver?

Question: I use Ubuntu16.04 and my laptop model is Asus-n552vw. My wi-fi network doesn't work properly. I thought maybe the problem solved if I update my wi-fi driver. I searched for that but couldn't find how should I do it?
EDIT: My problem is very strange and stupid!
If I connect to my wi-fi network at home that has 512kbps speed, I should disconnect and reconnect for every access to internet! I mean I must disconnect/reconnect to open a new site, then I must do it again for another site, or refreshing the other apps data.
But, If I use a VPN like windscribe and connecting to it, my network works well untill I am connected to it!!!
Also when I use other network connections with 2mbps or upper speeds, it seems my network works well again!
Comment: "I update my wi-fi driver" That's not how Linux works. We have 1 generic driver that is updated and when your system updates so does the driver. And we might have 1 closed source driver. This one also gets updated as your system gets updated. You probably have another problem. 16.04 gets the hardware support from 16.10/17.04/17.10 has when 16.04 goes up a point release (16.04.1, 16.04.2 etc). So you will have the latest/newest version of your driver.
Comment: @Rinzwind: I updated my question
Comment: Does this answer your question? [How do I get a Ralink RT3290 wireless card working?](https://askubuntu.com/questions/253632/how-do-i-get-a-ralink-rt3290-wireless-card-working)
Comment: I'm still having same issue on my 18.04 ubuntu. I'm using a Ralink card on hp 4540. The symptom is exactly as you described it. I found this guide that helped me resolve the issue, please see this post https://askubuntu.com/questions/253632/how-do-i-get-a-ralink-rt3290-wireless-card-working/253660#253660
Answer: Ubuntu 16.04 is very stable so i don't think the driver is you problem. maybe the problem is DNS(you can change it in /etc/resolve.conf) or ISP(if other devices have same problem) or hardware
by the way if you sure the problem is your driver, the drivers is in the Linux (i mean the kernel) you must upgrade your Linux and because you use Ubuntu 16.04 i don't think you can upgrade your Linux in a safely way
you can upgrade your Ubuntu to 17.10 or 18.04(it is not stable yet)
Comment: I updated my question

How should I update my wi-fi driver?


JavaFX and IntelliJ no errors althought the documentation says I should have some

Question: I'm currently following this tutorial: https://openjfx.io/openjfx-docs/ (JavaFX and IntelliJ IDEA). I use Intellij 2021.3.2.
I have created a project (1. Create a JavaFX project), which worked out great and didn't need to 2. Set JDK 16 because it was already set to 17 (which I guess is fine).

But here begin the weird stuff (and I'm very new to programming so I'm sorry if it sounds silly). "You can also set the language level to 11 or greater." I don't have this option. Because it's "can" I felt like it wasn't a big deal but if someone can explain what this is all about? Just out of curiosity, because I'm at the very beginning of the tutorial and I kinda only understand half of it.
Then 3. Create a library, and I don't have what they have, and my stuff is red:

So when they said "add the JavaFX 17 SDK as a library to the project" I didn't know what to do. I also didn't know what to do to fix the red stuff.
And finally, they say "Warning: If you run now the project it will compile but you will get this error: ..." but if I click on this button

everything works! which you know i'm not complaining about but I would like to understand a bit more what is happening.
And then they suggest I should 4. Add VM options to fix the problem that I don't have. So I figured maybe my computer set the VM options correctly without me knowing it but there is currently no VM option (and it works). Should I add them nonetheless?

Thank you for your help, I'm very lost and feel like I don't really understand anything.
Comment: If you click on the Maven tab on the right hand side of the screen, there will be a download symbol which has a drop down menu. Choose "Download Sources and Documentation".
Comment: As to the module path, I think Intellij might have improved their template.
Comment: What error were you expecting, and what VM options did they suggest to fix it? The "red stuff" isn't important, it just means that you can't view the javafx source or javadoc (being able to read the Javadoc *is* important when you're stuck, but not for running your program)
Comment: I mean StackOverflow is usually not the place to explain multiple steps in complete tutorials, usually it is more focused, with code, and questions like this are often closed as requiring more focus.  It is just the way it often works.  One key is seeing multiple question marks in the question and comments (perhaps they could be separate questions).  My comment was just meant as an FYI and to set expectations for this and future questions you may have.
Comment: hi thank you for your answer, I was expecting this error (https://i.imgur.com/Z1GDAiX.png) because the tutorial said so.
Comment: And how can I view the javafx source or javadoc, I guess it's better to fix it out than to wait for it to be important?
Comment: There are a bunch of questions here and usually StackOverflow is one question per question, but in this case everything is so closely related, so it might be ok.
Comment: @jewelsea not sure what you mean? were you answering someone who deleted their comment?
Comment: @tgdavies thanks it worked with "download sources and documentations"!
Comment: any ideas for the part:
""You can also set the language level to 11 or greater." I don't have this option. Because it's "can" I felt like it wasn't a big deal but if someone can explain what this is all about? Just out of curiosity, because I'm at the very beginning of the tutorial and I kinda only understand half of it." ?
Answer: The current documentation in the openjfx tutorial for getting started with JavaFX using Idea is incorrect, at least for recent Idea releases (2021.3 +).
The tutorial is written as though a new Java project was created, rather than a new JavaFX project. Once a new JavaFX project has been created, most of the rest of the steps in the tutorial are either redundant or wrong.
Step 1, "Create a JavaFX project", does a lot more than just "Create a Java project", which is why everything else is different from the tutorial.
A better tutorial for getting started with JavaFX with Idea, is the official Idea documentation:

Create a new JavaFX project.

Differences between creating a new Java project and creating a new JavaFX project
The new JavaFX project:

Provides a build script for Maven (pom.xml) or Gradle (build.gradle).

Adds the appropriate dependencies for JavaFX base, graphics, controls and fxml.

Provides an example application and controller code that you can run immediately.

The example project is modular and provides a module-info.java

Because the program is modular and dependencies are downloaded via maven and recognized by the IDE, you don't need to manually configure VM runtime options for the module path and adding modules.

Idea will recognize the Maven or Gradle projects and automatically synchronize the initial transitive dependent libraries with the Idea project.

There are options in the Idea Maven tool window which will allow you to synchronize further changes to dependent libraries or javadoc and source code in libraries.

Selects a JDK and attaches it to the project, automatically downloading the  selected JDK version if not already present.

Sets an appropriate language level for the project.

When you just use the create new Java Project option, it doesn't do any of those things, so you need to do things manually instead, which is what the rest of that tutorial is about:

Manually download the JDK and configure it in the SDK.

Manually download the JavaFX SDK and add the libraries from it to your project.

Manually configure VM modular arguments.

Manually maintain any other dependencies.

Manually associate javadoc and source code.

Manually write the code for a basic application.

Manually set the project language level.

Doing all this stuff manually is more work and more error prone.  The manual work usually leads to a worse outcome and a project that is more difficult to maintain for many people getting started with JavaFX, so I do not recommend it.
Versions
In terms of the versions to use, I recommend using the most recent stable (non-beta) releases of both JDK and JavaFX, regardless of what versions may be referenced in any tutorials you may be using.
You can set JavaFX versions in the Maven file generated by the new JavaFX project wizard, then press the button in the Maven Tool window to synchronize the Maven project with the Idea project.
Language level settings
These are important later on, but pretty irrelevant when just getting started.
The language level settings:

Tell the compiler what version of the java byte code to compile the application to.

Tell the IDE what language syntax rules to enforce and provide help with.

If you use Java 17 only features, the app won't run on a Java 11 VM.
You can define the settings in Idea manually:

language setting level.

But it is better to set them in the compiler section of the maven project and synchronize the project with Idea, which will also configure the settings in the IDE.
IMO, set it to the most recent stable version and have a requirement that your application be run with that Java version as a minimum (you can enforce that by using jlink or jpackage to bundle the JRE version you choose with your packaged app).
Comment: Hi, it looks to me that they do want me to make a JavaFX project and not a Java one like you mention: https://i.imgur.com/Jhzo23Y.png ? Or maybe i'm mistaken?
Comment: Oh ok, so they said create a new "JavaFX project" when they wanted me to create a "Java project" (which you mentioned is not a good idea)???? Well I am happy I posted here because I was assuming they couldn't been wrong and just thought I was genuinely lost. I learned a lot of stuff. Thank you!
Comment: Updated answer to note that the openjfx documentation is currently wrong, which created your confusion.


Disadvantages of super nested functions?

Question: On xDebug they limit how many times a function can be nested, are there any disadvantages of nesting functions for so many times?
Comment: Doesn't it say it right there? To prevent infinite recursion? And if you're nesting those functions manually, and you need to nest more than 100 times, then you're doing it wrong.
Answer: Yes.
Each time you call a function from within another function, you add one level to the stack.
The past function calls have not yet returned, so the memory they claimed for local variables cannot be deallocated; it remains resident until the whole stack is unwound.
Imagine you were to throw an exception from inside a function 1,000 calls deep. In order to generate a stack trace, it would have to walk upward through 1,000 function calls, putting them all into the exception object.
There's nothing you can do with recursion that deep which you couldn't do instead with a well-written loop, and the loop would be both more memory-efficient (as it doesn't have to have the stack frame overhead for each function invocation) and time-efficient (as it doesn't have the overhead of actually performing the function calls you removed).
It is exceedingly unlikely that a program which reaches a recursion level of 1,000 is behaving as intended. More likely, it's stuck in infinite recursion and will eventually exhaust all the system's RAM. Better to kill it earlier.


using pl/sql to update sequences

Question: We have a sql script to update a set of sequences after seed data populated our tables. The code below would not work:
declare
cursor c1 is
    select
      'select nvl(max(id),0) from '||uc.table_name sql_text,
      uc.table_name||'_SEQ' sequence_name
    from
      user_constraints uc,
      user_cons_columns ucc
    where uc.constraint_type='P'
      and ucc.constraint_name = uc.constraint_name
      and ucc.column_name='ID'
      and uc.owner='ME';

alter_sequence_text varchar2(1024);
TYPE generic_cursor_type IS REF CURSOR;
max_id number;
c2 generic_cursor_type;
begin
for r1 in c1 loop
    open c2 for r1.sql_text;
    fetch c2 into max_id;
    close c2;

    if( max_id != 0 ) then
        dbms_output.put_line( 'seq name = '||r1.sequence_name );
        execute immediate 'alter sequence '||r1.sequence_name||' increment by '||to_char(max_id);
        dbms_output.put_line( 'max_id = '||to_char(max_id) );
        execute immediate 'select '||r1.sequence_name||'.nextval from dual';
        dbms_output.put_line( 'sequence value = '||to_char(next_id) );
        execute immediate 'alter sequence '||r1.sequence_name||' increment by 1';
        dbms_output.put_line( 'sequence: '||r1.sequence_name||' is at '||to_char(max_id+1) );
    end if;
end loop;
end;

After searching I found a reference that stated I needed to change the line:
execute immediate 'select '||r1.sequence_name||'.nextval from dual'

and add 'into next_id;' (of course declaring next_id appropriately) so the result would be:
execute immediate 'select '||r1.sequence_name||'.nextval from dual into next_id;

I've only dealt lightly with pl/sql and sql in general and am interested to know why this change was necessary to make the script work correctly.
Thanks.
Answer: When you are using select inside PL/SQL block you have to place data returned by that select statement somewhere. So you have to declare a variable of appropriate data type and use select into clause to put data select returns into that variable even if select statement is executed by execute immediate statement.
Examples
declare
  x number;
begin
  select count(*)
    into x
    from all_objects;
end;

declare
  x number;
begin
  execute immediate 'select count(*)from all_objects' into x;
end;

So your execute immediate statement would be
execute immediate 'select '||sequence_name||'.nextval from dual' into newseqval;

If you are using Oracle 11g onward you can assign sequence's value directly to a variable, there is no need of using select into clause.
 declare
   x number;
 begin
   x := Sequence_Name.nextval;
 end;

Comment: In this case, dynamic SQL is required so he can't use the `x := Sequence_Name.nextval;` syntax.
Comment: @JeffreyKemp In his particular case yes, he cannot use that syntax. But he was also asking about why we should use `select into` clause. And I thought that information might be useful.
Answer: select seq_name.nextval from dual implies the implicit cursor creation and the results of the cursor should be fetched somewhere so you need fetch it into any externally declared bind variable.
Comment: I'm not able to conceptualize why the select needs to be assigned to an externally declared variable. What's going on behind the scenes that simply assigning a select into a variable causes the value to actually be stored? Because the 'newseqval' is not used again to assign to the sequence's current value. I'm new at this and curious.

using pl/sql to update sequences


Flutter custom package not loading fonts and images | Flutter

Question: I am creating a package. I've added two directories, fonts and images, consecutive to the lib directory. I've also added the required code in pubspec.yaml file to use those fonts and images in the package. I created an example directory in the package directory in order to test the package I'm creating, but the test app won't pick the fonts and images from the package and gives the exception:
FlutterError (Unable to load asset: images/abc.png)
Screenshot of directories [1]: https://i.stack.imgur.com/po8oT.png
pubspec.yaml:
name: customtestingpackage
description: A new Flutter package project.
version: 0.0.1
author:
homepage:

environment:
  sdk: ">=2.7.0 <3.0.0"
  flutter: ">=1.17.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons:

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true
  assets:
    - images/

  fonts:
    - family: Comfortaa
      fonts:
        - asset: fonts/comfortaa/Comfortaa-Regular.ttf
          weight: 400
        - asset: fonts/comfortaa/Comfortaa-Medium.ttf
          weight: 500
    - family: Poppins
      fonts:
        - asset: fonts/poppins/Poppins-Regular.ttf
          weight: 400
        - asset: fonts/poppins/Poppins-Medium.ttf
          weight: 500

main.dart: implementation of fonts
style: TextStyle(
    fontSize: 24,
    fontWeight: FontWeight.w500,
    color: Colors.white,
    fontFamily: 'Poppins',
    letterSpacing: 1.25,
),

Comment: did you stop the main.dart than run it again (not hot-reload) ?
Comment: did you make sure you did flutter pub get after modifying your pubspec.yaml? And you should also check if your indentation is correct.
Comment: any update here? I'm experiencing the same behaviour. Strangely it only fails to load the assets inside a flutter package project while it works in a "normal" flutter project.
Answer: From https://flutter.dev/docs/development/ui/assets-and-images#from-packages:

To load an image from a package dependency, the package argument must be provided to AssetImage.

Assets used by the package itself should also be fetched using the package argument as above.

So in your case you should be able to load an image by something like this:
  Image.asset(
    'images/image_a.png',
    package: 'customtestingpackage',
  ),

The same seems to apply to fonts as well.
From: https://api.flutter.dev/flutter/painting/TextStyle-class.html

To use a font family defined in a package, the package argument must be provided

If the package internally uses the font it defines, it should still specify the package argument when creating the text style as in the example above.
Comment: No problem! Would you mind marking my answer as accepted?
Comment: I have a base app with images under lib/assets/images and a whitelabel app with a dependency to the base app. When I use package: "baseapp" for images, they don't work anymore for the base app but they work for the whitelabel. Since they are under lib folder I have nothing specified in pubspec.yaml. Any clue?


Sharing Wifi connection over ethernet, Still no internet access

Question: I am trying to share my laptops (16.04) wifi connection with a beagle bone (14.04 no gui) through ethernet. I've done this process before on a raspberry pi and an odroid-xu4 but the same process does not seem to be working for the beagle bone.
ping www.google.com
hangs for awhile until finally saying unknown host
sudo apt-get update hangs on 0% connecting to ports.ubuntu.com until eventually having many failed connections and errors.
Here is my network settings on my laptop:

And here are the settings for my beagle bone:

Those are all the settings that I can think of that are relevant (ifconfigs are posted below because I don't have rep to post more than 2 links...)
Comment: [link](http://i.stack.imgur.com/LYqNq.png) Laptop ifconfig
[link](http://i.stack.imgur.com/oJvft.png) beagle bone ifconfig
Comment: Could you please post text files and program output listings as text, not as images (see [How do I save terminal output to a file?](//askubuntu.com/q/420981/175814))? Thanks.
Comment: will do in the future.
Answer: I have now fixed my problem.
I added
nameserver 10.42.0.1
to my resolv.conf file on the beagle bone and can now ping and run apt-get update.


Kernel compiling - cross platform

Question: Just a small clarification about compiling kernels (not that I'm doing any :P).
What I know about compiling is that it is machine specific, although you can use a cross compiler to compile your work to run on different machine (or compile to byte-code to run under virtual machines), but cross compiling needs some basics/requirements necessary to run the program you compiled (like C++/C libs or Java VM...).
But what about kernels? they compile them once and magically run on every* machine (* didn't check that), I searched the web and I found some guide how to cross compile kernels, but didn't say why or how does it work! how does different CPUs with different instruction set run the same binary successfully?!
If you have some refs to answer my question I'll be very thankful for that, and maybe something to get me started learning more about kernels will be superb :D
Answer: They don't. A kernel compiled for, say, an ARM v6 won't run on any other kind of CPU. It's the same for every binary, kernels aren't magic. And cross compiling only means that the resulting binary is specific to an architecture which is different from the architecture the compiler runs on. For example, on my x86 desktop, I can compile binaries that will run on x86, or I can cross-compile binaries that will run on, for example, PowerPC. But neither will run on the other's target platform.
Comment: So when I install linux, it detects my arch and installs the appropriate kernel for my system?
Comment: Depends on the installer/distro. The distros I use don't do anything like that, you have to choose the right installer yourself.

Kernel compiling - cross platform


get angular ui router $location.search() to use Basic URL Parameters

Question: I have ui-router set up as follows
.state('root.event', {
    url : '/event/:id',
    templateUrl : 'templates/event.html'
})

(the controller is initiated in the template)
which gives nice looking Basic URL Parameters like:
www.mysite.com/event/1234
When a user navigates directly to my www.mysite.com/event path (ie param is missing) the template controller looks the most recent id parameter from either:
- a js variable stored in a value
- localstorage / cookie etc
I then return this to my state using $location.search('id', 1234)
...however, this results in URLs which have Query URL Parameters like:
www.mysite.com/event/?id=1234
Is there a technique to ensure that $stateparams updates present the url in basic format on update ?
...or is it possible to get the URL parameter & update the $state before the state change  ?
(I looked at Resolve but this seems mostly to be about passing parameters to controllers)
I've had a look here, here and here - but most of the questions relate to how to avoid reload on update of $state params
Answer: $location.search does exactly that. It adds query URL parameter. I think what you're looking for is
$state.go('root.event', {id: 1234})

Comment: won't that reload the template rather than just updating the parameters ?


Unique Haar measure on quotient is pushforward

Question: Let $G$ be an abelian locally compact Hausdorff group with discrete subgroup $H$. Let $\mu$ be a Haar measure on $G$ and $\lambda$ the usual counting measure on $H$. Then we obtain a unique Haar measure on $G/H$ satisfying
$$\int_{G/H}\left(\int_{H}f(gh)\mathrm{d}\lambda(h)\right)\mathrm{d}\nu(gH)=\int_{G}f(g)\mathrm{d}\mu(g).$$
Since another natural way to obtain a Haar measure on $G/H$ is by considering the pushforward measure $\nu:=\mu\circ f^{-1}$, where $f$ is the quotient map, I wondered whether the two measures obtained coincide. What I tried is just showing that the pushforward measure satisfies the integral formula, but I failed doing so.
By definition of the pushforward measure we have for each measurable $M\subset G/H$, and corresponding characteristic function $\chi_{M}$, that
$$\int_{G/H}\chi_{M}(gH)\mathrm{d}\nu(gH)=\int_{G}\chi_{f^{-1}(M)}(g)\mathrm{d}\mu(g).$$
This already looks a lot like the desired integral formula, nevertheless we would like to implement the measure on H in an appropiate way. But I don't see how, or if this is even possible. Or is there any additional condition needed, for instance $G/H$ being compact? Any help would be appreciated!
Answer: I guess I found my own counterexample, which maybe is the most natural one to consider at first. Namely, pick $G=\mathbb{R}$ and $H=\mathbb{Z}$. In this case the quotient is endowed with the natural Lebesgue measure induced by the lebesgue measure on $[0,1)$ (by the pushforward of the canonical isomorphism). This clearly doesn't equal the pushforward measure of the quotient map between $H$ and $G$.
Comment: Of course what is true is that the pushforward of haar on $G$ restricted to a fundamental domain is (proportional to) the haaron $G/H$; see https://math.stackexchange.com/q/4343890/169085 , https://math.stackexchange.com/q/4340095/169085 .


Append numbers in C

Question: How can I read six digits separately, and then append them?
For example:
I want to enter the following digits: 2 3 6 , 7 5
And the expected output would be: "236,75".
I have to do it with only one loop (to read the numbers), and I have to read the numbers with the type char.
Here's what I have so far:
#include <stdio.h>

int main()
{
    char c;
    char string [6];

    printf("Introduce a number\n");

    int i = 0;
    while (i <=5) {
        scanf("%c", &c);
        string[i] = c;
        i++;
    }

    printf("%c\n",string);

}

Comment: add string[i] = c before i++
Comment: Your last printf shows only a character, you must use `%s` to see the whole number stored in array.
Comment: First, it would help if you said what happens when you try your program. What errors have you encountered? Second, near the end of the code you show, you aren't printing out an item where the `%c` format fits. You're (trying) to print a string, so you want `printf("%s\n", string);`. Finally, is this homework? You appear not to know C very well, but you say you "have to" do certain things.
Comment: @dcarou: I've removed some unnecessary whitespace from your code and added indentation to make it more readable.
Comment: @ZachStark: Some countries use the comma to mark decimals. [See wikipedia](https://en.wikipedia.org/wiki/Decimal_mark#Countries_using_Arabic_numerals_with_decimal_comma).
Comment: @sharth: Regardless of whether it is used to mark decimals, a comma still isn't a digit.
Comment: @ZachStark i want to the read 3 numbers, then a comma, and the 2 more numbers
Comment: @Telemachus this isn't homework, it's just an exercise i'm trying to do. I'm new to the language, i managed to do it in java, but i'm struggling to do it in C.
Answer: Try something like this:
char string [7];

printf("Introduce a number\n");

int i = 0;

while(i <=5){

    scanf("%c", &c);
    string[i] = c;
    i++;
}

string[i] = '\0';

//printf("%s", string);

I added the '\0' character at string[6], just in case you need that for printing the values for example.
Also, I recommend you to read about cleaning the input buffer when obtaining input from stdin. Hope it helps.
Comment: with the imput i entered above, it does not print what it's supposed to
Comment: read about [cleaning the input buffer](http://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c). That is your problem now.
Answer: For starters ensure that your int main() is actually returning an integer.
#include <stdio.h>

int main()
{
    char c;
    char string[7];
    char* stringy = string;

    printf("Introduce a number\n");

    int i = 0;
    while (i <=5) {
        scanf("%c", &c);
        string[i] = c;
        i++;
    }
    string[i] = '\0';

    printf("%s\n",stringy);

    return 0;

}

Also you want to print your entire string out with a %s format specifier. This also means that you'll need to null terminate your string which can be done by setting the last character in your array to \0.
Also make sure your array has 7 indexes instead of 6, so everything can fit.
Answer: #include <stdio.h>

int main()
{
    char c;
    char string [7];

    printf("Introduce a number\n");

    int i = 0;
    while (i <=5) {
        scanf("%c\n", &c);
        string[i] = c;
        i++;
    }
    string[i] = '\0';

    printf("result: %s\n",string);
    return 0;
}

C strings end with a null character, that is '\0'. Therefore you should always append the null character to a character string as the last character since it determines the end of the string. Therefore the line string[i] = '\0'; is necessary (at the end of the while loop, the value of i will be 6, thus pointing to the last element of the character array).
Another correction to your code is the final printf(). You specified the format to be character format ("%c"), which will only output the first character of the string. You should change it to "%s" for printing the whole string.
This program should work since it is a valid C code. If you are having troubles with this code, then it is platform specific. I couldn't run this code on VS2012, but managed to run it on a GNU C Compiler. Try running the code on an online C compiler, it should work just fine.

Append numbers in C


How to have both vertical and horizontal mousewheel scroll in the webpage?

Question: Out webpage has a vertical scroll until it reaches the bottom, at that point we want it to start scrolling horizontally.
It should also work in reverse, so when the user reaches the end of the horizontal scroll, the user can go back using the mouse wheel to the top, following the same path.
To make it clearer, the webpage wrapper is like an "L". It's the same movement as this website as it gets to: "We've taken on at least 300%".
I've seen useful advice about horizontal scroll, but i can't implement it to the vertical one.
Comment: You should post example HTML, CSS and Javascript so we can try and help.  Please read [ask]
Answer: Under normal circumstances, I'd give the normal shpeal about "what have you tried, show stuff", which you should definitely follow on Stack Overflow: How do I ask a good question?
That said, this was a particularly interesting problem, so I decided to take a stab.
I recommend checking out the example in full page mode after hitting "Run code snippet":

const root = document.getElementById('root');
const content = document.getElementById('content');

root.addEventListener('wheel', e => {
  e.preventDefault();
  e.stopPropagation();

  const delta = e.deltaY;

  const maxScrollY = content.offsetHeight - root.offsetHeight;
  const maxScrollX = content.offsetWidth - root.offsetWidth;

  let scrollY = root.scrollTop;
  let scrollX = root.scrollLeft;

  if (scrollX > 0) {
    scrollX += delta;

    if (scrollX < 0) {
      scrollY -= scrollX;
      scrollX = 0;
    }
  } else {
    scrollY += delta;

    const overflow = scrollY - maxScrollY;
    if (overflow > 0) {
      scrollX += overflow;
      scrollY = maxScrollY;
    } else {
      scrollX = 0;
    }
  }

  root.scrollTo(scrollX, scrollY);
});
#root {
  width: 500px;
  height: 500px;
  overflow: hidden;
}

#content {
  width: 5000px;
  height: 1000px;
}

/* This is just to have something in content so we can see it moving */
#content {
  border: 50px solid #F00;
  background-image:
    linear-gradient(0deg, rgba(0, 0, 255, .5) 0%, rgba(0, 0, 255, .5) 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%),
    linear-gradient(90deg, #000 0%, #000 50%, #FFF 50%, #FFF 100%);
  background-repeat: repeat;
  background-size: 1% 5%;
}

This solution requires that you have two elements, an outer "root" and an inner "content". The window should be to be the "root" element (just switch it to const root = window;).
Basically, we then hijack the wheel event on the root element. Any time it happens, we need to add it to either scrollLeft or scrollTop.
If our scrollX/scrollLeft is 0, then we'll add it to scrollY/scrollTop. We then check for any extra scroll when we hit the bottom. If we have any, we'll add that to scrollX.
If our scrollX is not zero, then we'll just add any scroll directly to it. If it becomes less than zero, we'll set it to zero and give the extra to scrollY so it can go back up.
Since deltaY will be negative or positive, we don't have to do any special math to be able to deal with it.
For the CSS, the only important bit is that the root element has overflow hidden. If you are using window, set html to overflow: hidden. The "content" then needs to have some width. You don't necessarily have to explicitly set it, because your content will give it a size.


What power and type of in-line bathroom extractor fans should I be looking for?

Question: We had some mould appear in our bathroom and I suspected that our inline extractor fan was underpowered. As it happens the extractor just stopped working, so I'm in the market for a replacement.
I have a few questions:

What is better - centrifugal or induct? It looks like the centrifugal ones have best throughput but are they as reliable etc?
What rate is good? I can't find info on my old induct 23W fan's rate, but I assume it was in the range 80-100 m^3/hr - does that sound about right? Would going up to a 220 m^3/hr be excessive?
Does power affect anything other than the rate?

A few notes:

The inlet in the bathroom is in the ceiling
I don't really want to take out the old ducting & fittings, so if it was a round, 125mm fan that would be great. Also 100mm would work I guess as I could still make the ducting fit.
Fan needs to have an adjustable timer on it so it stays on after the light is turned off - there is a permanent live circuit available.
Bathroom is approx 1.6m x 2.5m x 2.2m (i.e. 8.8 m^3) Using some recommendations from another answer, this would mean 70 m^3/hr would be fine... but it's not worked out that way before. Perhaps the timer wasn't on for long enough? Or perhaps I can double the throughput and halve the time?
Comment: the other thing you need to take into account is how long the duct run is and how many bends are in it. Longer runs/more bends means you need a higher powered fan.  Also make sure its not blocked!
Comment: How big is your bathroom?
Comment: [This answer](http://diy.stackexchange.com/a/16618/33) might help you determine what size fan you need.
Comment: Whatever you do, pay close attention to the noise level.  A fan that is too loud will not be used.  Unfortunately, silence is golden. Which means it costs lots of gold.
Comment: @NiallC - have added the info.
Comment: @Tester101 - thanks, have taken that into account
Comment: @ChrisCudmore - it'll be on a timer, so no option about using it or not. No windows in the room either, so it's shower in the pitch black or use the fan :)
Answer: In the end I went for a mixed flow (which I think is both cetrifugal & radial or something), has about double the throughput that is recommended for the size of room (240 m^3/hr vs 110 m^3/hr). Doesn't have a timer on it, but it seems to be keeping the steam down when we shower anyway.
Here's a link to the fan I bought in the end.
Thanks for the pointers.


How determinate number of rounds in TFF context

Question: In TFF, It is necessary to determinate number of rounds. So, to obtain optimal performance of our model, How we can know the optimal number of rounds?
Answer: TFF does not necessarily need you to specify the number of rounds for federated training beforehand. TFF is more about specifying the federated aspect of your computation (which you can essentially think of as specifying the communication), and considers actually "running" the rounds to be at the system level.
When you write TFF, generally you are writing at three levels (explanation of this statement here); the question you are asking (and every concern TFF considers a "system concern") is at the Python level. Since Python controls the actual invocation of your computation written in TFF, you can stop training with any criterion expressible in Python. E.g. if you want to monitor performance on a validation set and use that as a stopping criteria, this is entirely doable. If you have a tff.utils.IterativeProcess ip, and evaluation function eval_fn (see here for an example), this could be implemented as something like:
while True:
  data = sample_client_data()
  state, metrics = ip.next(state, data)
  eval_metrics = eval_fn(state)
  if condition(eval_metrics):
    break

Abstractly: since the Python drives the experiment process, you can stop whenever you want to, based on any observable characteristic of the training procedure. Therefore you do not in fact need to know how many rounds you will be running beforehand.
A more direct answer to the original question is, I think at this point in the history of FL, not quite achievable for the general case; nobody (as far as I am aware) knows of reliable system-level settings for FL at this point. This is not surprising; it is somewhat akin to knowing beforehand how many epochs one should specify in datacenter training, which I think tends to be quite problem-dependent. FL is similar in this regard. Practically speaking, my advice tends to be: monitor performance on a validation set, run for as long as you can, and keep the state of your highest-performing model on the val set around. I think a more general answer than this may be quite difficult.
Comment: Thank you very much, it was an important answer, to monitor performance on a validation set ( evaluation was invoked on the latest state we arrived at during training. In order to extract the latest trained model from the server state, you simply access the `.model` member, as follows.:                                   `train_metrics = evaluation(state.model, federated_train_data)`. I understand from here that the latest state of model is provided after a predeterminated number_of_round.. what do you think about this


How can I remove CRLF line terminators from wget'ed file?

Question: I want to download a pastebin a raw file, and I tried:
wget http://pastebin.com/raw.php?i=LBVNiRXa -O somefile

My only problem is that the file arrives with CRLF line terminators.
Can I remove the line terminators with only one command line?
Answer: Use tr to remove them:
wget http://pastebin.com/raw.php?i=LBVNiRXa -O- | tr -d '\r' >somefile

Comment: Million Thanks!! My head was about to explode, wasted almost an hour on this trivial issue!


Regex between, from the last to specific end

Question: Today my wish is to take text form the string.
This string must be, between last slash and .partX.rar or .rar
First I tried to find edge's end of the word and then the beginning. After I get that two elements I merged them but I got empty results.
String:
http://hosting.xyz/1234/15-game.part4.rar.html

http://hosting.xyz/1234/16-game.rar.html

Regex:
Begin:(([^/]*)$) -  start from last /
End:(.*(?=.part[0-9]+.rar|.rar)) stop before .partX.rar or .rar
As you see, if I merge that codes I won't get any result.
What is more, "end" select me only .partX instead of .partX.rar
All what I want is:
15-game.part4.rar and 16-game.rar

What i tried:
(([^/]*)$)(.*(?=.part[0-9]+.rar|.rar))

(([^/]*)$)

(.*(?=.part[0-9]+.rar|.rar))

I tried also
/[a-zA-Z0-9]+

but I do not know how select symbols.. This could be the easiest way. But this select only letters and numbers, not - or _.
If I could select symbols..
Comment: He posted (at least) something that he tried.
Comment: as I said `(([^/]*)$)(.*(?=.part[0-9]+.rar|.rar))` this I tried, I tried also `(([^/]*)$)` and `(.*(?=.part[0-9]+.rar|.rar))`, I tried also `/[a-zA-Z0-9]+` but I do not know how select symbols.. This could be the easiest way. But this select only letters and numbers, not `-` - do  you know how to select till `.` dot?
Comment: What language are you working within? Java/Javascript/C#?
Answer: Nothing could be simpler! :-)
Use this:
new Regex("^.*\/(.*)\.html$")

You'll find your filename in the first captured group (don't have a c# compiler at hand, so can't give you working sample, but you have a working regex now! :-) )
See a demo here: http://rubular.com/r/UxFNtJenyF
Comment: Ah. C# guy :-) Then put this into a Regex constructor: `^.*\/(.*)$`. Leading and trailing slashes are part of regex literal in some languages.
Comment: Yeah, I see but doesn't on C#, and `.html` is no need.
C# gives me all source of link.
Answer: You don't really need a regex for this as you can merely split the url on / and then grab the part of the file name that you need.  Since you didn't mention a language, here's an implementation in Perl:
use strict;
use warnings;

my $str1="http://hosting.xyz/1234/15-game.part4.rar.html";

my $str2="http://hosting.xyz/1234/16-game.rar.html";

my $file1=(split(/\//,$str1))[-1]; #last element of the resulting array from splitting on slash

my $file2=(split(/\//,$str2))[-1];

foreach($file1,$file2)
{
  s/\.html$//; #for each file name, if it ends in ".html", get rid of that ending.
  print "$_\n";
}

The output is:
15-game.part4.rar
16-game.rar

Comment: He's using c#, apparently :-)
Comment: Yes, sorry forget about code language. I though that regex is universal. Btw. your code helped me a lot. I forgot about rule **KISS**! :) However it is not regex, doh! :P
Answer: I'm not a C# coder so can't write full code here but I think you'll need support of negative lookahead here like this:
new Regex("/(?!.*/)(.+?)\.html$");

Matched Group # 1 will have your string i.e. "16-game.rar" OR "15-game.part4.rar"
Comment: Sure I will try. This regex basically has a negative lookahead `/(?!.*/)` which means match a `/` which is **NOT followed** by some text and another `/`. This basically makes sure that we **match only last /**. Rest is straight forward where `(.+?)\.html` matches a text that has `.html` in the end.
Comment: could I ask you to explain me this regex command, I would appreciate for this. Thanks in advance!
Answer: Use two regexes:

start to substitute .*/ with nothing;
then substitute \.html with nothing.

Job done!


Sorting numerically but not alphabetically when numbers are equal

Question: I have a file like this:
A 0.77
C 0.98
B 0.77
Z 0.77
G 0.65

I want to sort the file numerically in descending order. I used this code:
sort -gr -k2,2 file.txt

I obtain this:
C 0.98
Z 0.77
B 0.77
A 0.77
G 0.65

In my real file I have several columns with the same number and they are ordered alphabetically. What I want is to sort numerically but not alphabetically when the numbers are equal, I want to obtain those columns unsorted alphabetically:
C 0.98
B 0.77
Z 0.77
A 0.77
G 0.65

But any random order is fine.
Answer: You can use this sort:
sort -k2rn -k1R file

C 0.98
B 0.77
Z 0.77
A 0.77
G 0.65

There are 2 sort options used:

-k2rn: First sort key is column 2; numerical, reverse
-k1R: Second sort key is column 1; random
Comment: I obtained the same result, the file is ordered alphabetically in reverse order.
Comment: Done. What I want is apply `sort -R` maintaining the numerical sort.
Answer: One in GNU awk that preserves the order of the first field (random in, equally random out):
$ awk ' {
    a[$2]=a[$2] (a[$2]==""?"":FS) $1       # append $1 values to hash, indexed on $1
}
END {
    PROCINFO["sorted_in"]="@ind_num_desc"  # set for traverse order for index order...
    for(i in a) {                          # ... and use it here
        n=split(a[i],b)
        for(j=1;j<=n;j++)                  # preserve the input order
            print b[j],i                   # output
    }
}' file
C 0.98
A 0.77
B 0.77
Z 0.77
G 0.65

Testing reverse order:
$ tac file | awk '# above awk script'
C 0.98
Z 0.77
B 0.77
A 0.77
G 0.65


After root changes table name, root gets error when trying to revoke permissions from end user on a non existent table name

Question: I am currently using the root account
I have a table - user1_db.table1 and user1 has the following permissions -
SHOW GRANTS FOR user1@localhost;
GRANT SELECT, INSERT, UPDATE, DELETE, INDEX, ALTER ON `user1_db`.`table1` TO `user1`@`localhost`

Now, I rename table1 to table2 but I forgot to revoke the permissions from user1 on table1 first
I now grant the same permissions on table2 to user1
Now I have the permissions as -
SHOW GRANTS FOR user1@localhost;
GRANT SELECT, INSERT, UPDATE, DELETE, INDEX, ALTER ON `user1_db`.`table1` TO `user1`@`localhost`
GRANT SELECT, INSERT, UPDATE, DELETE, INDEX, ALTER ON `user1_db`.`table2` TO `user1`@`localhost`

So now there is permissions granted on a non-existent table name - table1
I try to revoke the permission.
REVOKE ALL PRIVILEGES ON `user1_db`.`table1` FROM `user1`;

But, I get the error -
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

I tried the following to decrease password complexity requirement -
SET GLOBAL VALIDATE_PASSWORD.POLICY = LOW;
SET GLOBAL VALIDATE_PASSWORD.LENGTH = 2;
SET GLOBAL VALIDATE_PASSWORD.MIXED_CASE_COUNT = 0;
SET GLOBAL VALIDATE_PASSWORD.NUMBER_COUNT = 0;
SET GLOBAL VALIDATE_PASSWORD.SPECIAL_CHAR_COUNT = 0;

But still the problem persists. So how can I revoke permissions from user1 on a non-existent table - table1
Answer: I came across this workaround.
From root account I create a table user1_db.table1
CREATE TABLE table1 (col1 INT);

Then I logged out, restarted mysql server and again logged in.
Now the query -
REVOKE ALL PRIVILEGES ON `user1_db`.`table1` FROM `user1`;

runs without any error.
Now, user1 permissions are -
SHOW GRANTS FOR user1@localhost;
GRANT SELECT, INSERT, UPDATE, DELETE, INDEX, ALTER ON `user1_db`.`table2` TO `user1`@`localhost`

Then I deleted table table1
DROP TABLE user1_db.table1;