text:
Q: Spinner with empty default selected item I'm trying to create a spinner with default empty selected item, but it displays the first item from the choices of spinner. If I add null value to my string, which is the source of choices in spinner, then after opening spinner that empty row is displayed. How should I do it? Here's code I'm using:
  String[] ch = {"Session1", "Session2", "Session3"};
  Spinner sp = (Spinner)findViewById(R.id.spinner1);
  TextView sess_name = findViewById(R.id.sessname);
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,ch);
  sp.setAdapter(adapter);

  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

  sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener({
      @Override
      public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
          int index = arg0.getSelectedItemPosition();
          sess_name.setText(ch[index]);

          Toast.makeText(getBaseContext(), "You have selected item : " + ch[index], Toast.LENGTH_SHORT).show();
      }

A: I'm a little late to the party, but here is what I did to solve this.
If the user cancels out of selecting an initial item the spinner will retain the initial empty state. Once an initial item has been selected it works as 'normal'
Works on 2.3.3+, I have not tested on 2.2 and below
First, create an adapter class...
public class EmptyFirstItemAdapter extends ArrayAdapter<String>{
    //Track the removal of the empty item
    private boolean emptyRemoved = false;

    /** Adjust the constructor(s) to fit your purposes. */
    public EmptyFirstitemAdapter(Context context, List<String> objects) {
        super(context, android.R.layout.simple_spinner_item, objects);
        setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    }

    @Override
    public int getCount() {
        //Adjust the count based on the removal of the empty item
        if(emptyRemoved){
            return super.getCount();
        }
        return super.getCount()-1;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        if(!emptyRemoved){
            // Remove the empty item the first time the dropdown is displayed.
            emptyRemoved = true;
            // Set to false to prevent auto-selecting the first item after removal.
            setNotifyOnChange(false);
            remove(getItem(0));
            // Set it back to true for future changes.
            setNotifyOnChange(true);
        }
        return super.getDropDownView(position, convertView, parent);
    }

    @Override
    public long getItemId(int position) {
        // Adjust the id after removal to keep the id's the same as pre-removal.
        if(emptyRemoved){
            return position +1;
        }
        return position;
    }

}

Here is the string array I used in strings.xml
<string-array name="my_items">
    <item></item>
    <item>Item 1</item>
    <item>Item 2</item>
</string-array>

Next, add an OnItemSelectedListener to your Spinner...
mSpinner = (Spinner) mRootView.findViewById(R.id.spinner);
String[] opts = getResources().getStringArray(R.array.my_items);
//DO NOT set the entries in XML OR use an array directly, the adapter will get an immutable List.
List<String> vals = new ArrayList<String>(Arrays.asList(opts));
final EmptyFirstitemAdapter adapter = new EmptyFirstitemAdapter(getActivity(), vals);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
    //Track that we have updated after removing the empty item
    private boolean mInitialized = false;
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if(!mInitialized && position == 0 && id == 1){
            // User selected the 1st item after the 'empty' item was initially removed,
            // update the data set to compensate for the removed item.
            mInitialized = true;
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // Nothing to do
    }
});

It may not be a 'perfect' solution, but I hope it helps someone.

A: After some thinking, I believe I've come up with a method to achieve your goal.  It involves creating a
custom adapter and setting/maintaining a flag to determine if an item from the spinner has been selected.
Using this method you do not need to create/use false data (your empty string).
Basically, the adapters getView method sets the text for the closed spinner.  So if you override that
and set a conditional in there, you can have a blank field on startup and after you make a selection have
it appear in the closed spinner box.  The only thing is you need to remember to set the flag whenever you
need to see the value in the closed spinner.
I've created a small example program (code below).
Note that I only added the single constructor I needed for my example.  You can implement all the standard
ArrayAdapter constructors or only the one(s) you need.
SpinnerTest.java
public class SpinnerTestActivity extends Activity {
    private String[] planets = { "Mercury", "Venus", "Earth", "Mars",
            "Jupiter", "Saturn", "Uranus", "Neptune" };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Spinner spinner = (Spinner) findViewById(R.id.spinner);
        CustomAdapter adapter = new CustomAdapter(this,              // Use our custom adapter
                android.R.layout.simple_spinner_item, planets);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int pos, long id) {
                CustomAdapter.flag = true;                       // Set adapter flag that something
                has been chosen
            }
        });
    }
}

CustomAdapter.java
public class CustomAdapter extends ArrayAdapter {
    private Context context;
    private int textViewResourceId;
    private String[] objects;
    public static boolean flag = false;
    public CustomAdapter(Context context, int textViewResourceId,
            String[] objects) {
        super(context, textViewResourceId, objects);
        this.context = context;
        this.textViewResourceId = textViewResourceId;
        this.objects = objects;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null)
            convertView = View.inflate(context, textViewResourceId, null);
        if (flag != false) {
            TextView tv = (TextView) convertView;
            tv.setText(objects[position]);
        }
        return convertView;
    }
}

A: Barak's solution have a problem. When you select the first item, Spinner won't call OnItemSelectedListener's onItemSelected() and refresh the empty content because the previous position and selection position both is 0.
First put a empty string at the begin of your string array:
String[] test = {" ", "one", "two", "three"};

Second build adapter, don't modify getView(), modify getDropDownView(). Set the empty View's height to 1px.
public class MyArrayAdapter extends ArrayAdapter<String> {

    private static final int ITEM_HEIGHT = ViewGroup.LayoutParams.WRAP_CONTENT;

    private int textViewResourceId;

    public MyArrayAdapter(Context context,
                          int textViewResourceId,
                          String[] objects) {
        super(context, textViewResourceId, objects);
        this.textViewResourceId = textViewResourceId;
    }

    @Override
    public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
        TextView textView;

        if (convertView == null) {
            textView = (TextView) LayoutInflater.from(getContext())
                   .inflate(textViewResourceId, parent, false);
        } else {
            textView = (TextView) convertView;
        }

        textView.setText(getItem(position));
        if (position == 0) {
            ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
            layoutParams.height = 1;
            textView.setLayoutParams(layoutParams);
        } else {
            ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
            layoutParams.height = ITEM_HEIGHT;
            textView.setLayoutParams(layoutParams);
        }

        return textView;
    }
}

A: Here is what I use. It properly handles null (empty) selection in a generic manner. It works with any model class T, as long as class T properly implements toString(), to display the text shown in the spinner, and equals(), so that items may be selected by  reference rather than by positional index.
package com.10xdev.android.components;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * A spinner where no selection is possible, and other enhancements.
 * requires model class to properly implement Object.equals, with semantic comparaison (such as id comparaison)
 * and a proper toString(), whose result will be displayed in the spinner
 *
 * @author tony.benbrahim
 */

public class EnhancedSpinner<T> extends Spinner {
    private final EnhanceArraySpinnerAdapter<T> spinnerAdapter;
    private final List<T> items = new ArrayList<>();
    private T selected = null;

    public EnhancedSpinner(final Context context, final AttributeSet attributeSet) {
        super(context, attributeSet);
        spinnerAdapter = new EnhanceArraySpinnerAdapter<>(context, items);
        setAdapter(spinnerAdapter);
    }

    /**
     * sets the items to be displayed
     *
     * @param items
     */
    public void setItems(final List<T> items) {
        this.items.clear();
        //very iffy, but works because of type erasure
        this.items.add((T) "");
        this.items.addAll(items);
        spinnerAdapter.notifyDataSetChanged();
        updateSelected();
    }

    /**
     * set the selected item. this may be called before or after setting items
     *
     * @param item the item to select, or null to clear the selection
     */
    public void setSelected(final T item) {
        this.selected = item;
        updateSelected();
    }

    /**
     * gets the selected item, or null if no item is selected
     *
     * @return
     */
    @Override
    public T getSelectedItem() {
        return getSelectedItemPosition() != 0 ? (T) super.getSelectedItem() : null;
    }

    /**
     * set the error message for the select
     *
     * @param errorMessage
     */
    public void setError(final String errorMessage) {
        final TextView errorText = (TextView) getSelectedView();
        errorText.setError("error");
        errorText.setTextColor(Color.RED);
        errorText.setText(errorMessage);
    }

    private void updateSelected() {
        if (selected == null) {
            setSelection(0);
        } else {
            for (int i = 1; i < items.size(); ++i) {
                if (selected.equals(items.get(i))) {
                    setSelection(i);
                    break;
                }
            }
        }
    }

    private class EnhanceArraySpinnerAdapter<T> extends ArrayAdapter<T> {
        private final LayoutInflater inflater;

        public EnhanceArraySpinnerAdapter(final Context context, final List<T> objects) {
            super(context, android.R.layout.simple_spinner_item, objects);
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View getDropDownView(final int position, final View convertView, final ViewGroup parent) {
            final TextView textView = convertView != null ? (TextView) convertView
                    : (TextView) inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
            final Object item = getItem(position);
            textView.setText(item.toString());
            final ViewGroup.LayoutParams layoutParams = textView.getLayoutParams();
            layoutParams.height = position == 0 ? 1 : LayoutParams.WRAP_CONTENT;
            textView.setLayoutParams(layoutParams);
            return textView;
        }
    }
}

A: You have to put the first element of the spinner empty, or with an string indicating that nothing is selected like the following:
String[] ch= {"","Session1", "Session2", "Session3"};

or
String[] ch= {"Nothing selected", "Session1", "Session2", "Session3"};

hope to help


text:
Q: OnePair Pokerhand method java I am trying to figure out why my code isn't working. trying to create a pokerhand program for school and am trying to write the one pair method. I have to return a boolean. not sure why the count variable returns such a high value if I my array has numbers 2,2,3,4,5.
public static boolean containsPair(int [] hand)
{
  boolean pair = false;
  int count = 1;
  for(int i = 0; i < 5; i++)
  {
    for(int j = 1; j < 5; j++)
    {
      if (hand[i] == hand[j])
      count++;

    }

  }
  System.out.println(count);
  if (count == 2)
  pair = true;
  return pair;

A: In your 2 nested for loops, you are counting the cases where i == j, so that each card equals itself.  Start j from one past wherever i is:
for(int j = i + 1; j < 5; j++)

This way, you don't make comparisons twice and you don't compare the card with itself.  You are now only comparing a card with all the cards past that card.

A: You are basically comparing all the cards with all the other cards. For example both i and j will be 4 at some point.  So if (hand[i] == hand[j]) will be true when i==j.
Also, you adding up the values for all the cards, you need to reset it after each card (after each iteration of the first for loop).
for(int i = 0; i < 5; i++)
{
   count = 1;
   for(int j = 0; j < 5; j++)
   {
      if ((i != j) && (hand[i] == hand[j]))
         count++;
   }
   if (count == 2)
       pair = true;
 }

Of course this will return true if there are two pairs, so you will have to account for that too.
Edit: @rgettman's is right, you can start use his for loop to remove duplicates and get rid of the i!=j check.  You still need to reset count for each card though, and still need to do something to check for two pairs. It should be easy to make this method look for both one and two pairs in a general fashion since you will need to do that too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to sum the elements of an array list that stores objects I have a array list called Employees that stores Employee objects. Each employee has last name, first name, hour,pay pate, gross, tax, and net. I am trying to calculate the sum of each Employee's hour,pay pate, gross, tax, and net. Is there a way to extract specific element of an object from an array list?
I have tried to calculate the sum through user's input, however, it does not seem to work.
//Employee class
public Employee getinfo(Employee info )
    {
        info.LastName();
        info.FirstName();
        info.fullname();
        info.hours();//ask user to input hour
        toth += info.gethours();
        info.payrate();//ask user to input payrate
        totpr+= info.getpayrate();
        info.calcGross();
        totg+= info.getgross();
        info.calcTaxes();
        tott+= info.gettax();
        info.calcNet();
        totn+= info.getnet();
        return info;
    }

//Employees class
    Employee max=new Employee();

    public void add()
    {
        for (int i=0;i<max.maxemps();i++)
        {
            Employee emp= new Employee();
            emp.getinfo(emp);
            list.add(emp);
        }
    }

//Actual results
qwe, ewq            6.00     7.00    42.00     6.30     35.70
ttt, yyy            8.00     9.00    72.00     10.80    61.20
Total               0.00     0.00    0.00      0.00     0.00
Average             0.00     0.00    0.00      0.00     0.00

//Expecting
Total Total         14.00     16.00    114.00     17.1      96.9
Average             7.00      8.00     57.00      8.505     48.45

A: If you are sure that object is an Integer, you can use:
int i = (Integer) object;


text:
Q: Зависимость максимального значения от значения другого инпута Есть два <input type="number" min="1" max="9">. Как сделать так, чтобы значение атрибута max для второго инпута равнялось текущему val() первого инпута?

A:

$("#num1").on("change", function(){
  $("#num2").attr("max", $(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="number" id="num1" min="1" max="9">
<input type="number" id="num2" min="1" max="9">

A:

$("#1").focusout(function() {
  $("#2").attr("max", $(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
input 1:
<input id="1" type="number" min="1" max="9">
<br>input 2:
<input id="2" type="number" min="1" max="">


text:
Q: Replace hard drive in Samsung NP900X1A - Need disassembly guidance I need to clone and restore existing 64GB HDD onto a 256GB HDD, can't manage to gain access to the internals of this laptop.
I checked with Samsung, they do not make manuals available nor will they help over the phone as to how to remove the bottom cover of this Samsung NP900X1A laptop.  They did offer to sell me a manual BUT they are out of stock for another 10-15 days.
I saw the screws under the 4 rubber feet and 4 rubber grommets, all removed but the cover is still on.  Does anyone know if there are more screws to take off here?
Also, I assume this replacement HDD will work (facto

A: There should only be a couple things you need to remove to get access to the HDD, it shouldn't require major disassembly. You may have to take the battery out and open any other panels on the bottom to get access to additional screws.  There always seem to be a lot of them hidden in odd locations like that.
As for the HDD itself fitting, you'll know once you get it apart.  It's pretty common for the laptop drive to have a normal SATA connection, making a drop in replacement pretty easy. There may be a drive caddy that you'll need to take the old drive out of and put the new one back into.

A: There aren't any more screws. The cover should slide off once the screws are removed; push on the top edge. Use this video as reference.

The NP900X1A uses a mSATA SSD, shown boxed in red:

A regular 2.5" laptop SATA HDD or SSD will not fit, and you will also need a special enclosure to access it outside of the laptop; otherwise you will need to use an intermediate drive to clone.


text:
Q: Sublime 3: How to change font size on Sidebar? - Ubuntu version I'm trying to to change the size of my sidebar in sublime text 3, version for Ubuntu, but i just can't get it working, i read lots of posts about it, they said that i should have something like this:
{
    "class": "sidebar_label",
    "color": [0, 0, 0],
    "font.bold": false,
    "font.size": 14
},

on my settings - default, but nothing like it in there, for example i find there
"bold_folder_labels": true and works like a charm in my settings - user, but i try to put here the "class": "sidebar_label" with "font.size" and not results at all, maybe I'm just doing it wrong, please a little help, the text is so small that i can hardly read it.
Another thing i observed:

*

*Changing theme doesn't affects the sidebar

I don't remember if this is always true, but i think on my older laptop changing that change the colors of the sidebar and fonts, i remember use it before soda theme for getting smaller fonts on a low resolution laptop.
Thanks in advance, regards

A: Go to Preferences > Setting
In the right side pane, add this
"font_face": "Courier New",
"font_size": 10

Put the necessary commas(,) where needed. And it will change the font size.
Thank you.

A: You will need to edit the Default.sublime-theme file to do this, not your preferences. Unfortunately, in Sublime Text 3 this file is contained in a zipped .sublime-package file, so you'll need to extract that first. Install the PackageResourceViewer plugin via Package Control, then hit CtrlShiftP (⌘ShiftP on OS X) and type prv to bring up the PackageResourceViewer options. Select Open Resource, scroll down to Theme - Default, hit Enter, scroll down to Default.sublime-theme, and hit Enter again to open it.
Next, search for sidebar_label and modify the first one (on line 362) to look like this (it needs to be valid JSON):
{
    "class": "sidebar_label",
    "color": [0, 0, 0],
    "font.bold": false,
    "font.italic": false, // <-- add comma
    "font.size": 14 // <-- new line
    // , "shadow_color": [250, 250, 250], "shadow_offset": [0, 0]
},

Save the file, and you should see the sidebar font size change. You can change 14 to whatever size you want, depending on your personal preferences.

If you want to do this in Sublime Text 2, it's a bit easier, as nothing is zipped up. Select Preferences -> Browse Packages... to open up your Packages folder in your operating system's file navigator. Enter the Theme - Default subdirectory and open Default.sublime-theme as a JSON file, then edit it as above.
Good luck!


text:
Q: How to filter data from Smartsheet using a list from another sheet I am an amateur, self-taught programmer. My primary language is Python. Recently, I have started learning about the Smartsheet API and I love the potential it has. In my organization, we use Smartsheet for one of our processes.
Now, I will explain what my inputs are, and what I would like to achieve. We have a production schedule sheet with all of our raw data. That is the primary data source. Additionally, I have generated a list of SKUs for products that we produce, along with testing information. One of the columns is 'Micro Testing' and the options are 'Yes' or 'No'.
What I want to do, is filter the primary data list for any SKU which is on my item directory and has 'Micro Testing' = 'Yes' and then pull any row from the primary data sheet with a SKU that matches the item directory on the separate sheet, and has the column set to 'Yes' for micro testing.
The end result would be a sheet that pulls down all items from the primary data source which have a SKU that matches my item directory list and it does so by checking to see if the SKU has micro testing or not.
This is the current script that I have using the python-read-write-sheet.py from GitHub for Python. Please note, I have this currently set up to check a column on the primary data source called 'Micro Testing', but I can't change the primary data source at this time, so I am trying to find a work around to make it so I can just use my list of SKUs with micro testing to check against with an index match/collect call or something along those lines:
import smartsheet
import os
import logging

_dir = os.path.dirname(os.path.abspath(__file__))

column_map = {}

def get_cell_by_column_name(row, column_name):
    column_id = column_map[column_name]
    return row.get_column(column_id)

def search_rows_and_build_spreadsheet(source_row):

    # Find the cell and value we want to evaulate
    micro_testing = get_cell_by_column_name(source_row, "Micro Testing")
    micro_value = micro_testing.display_value

    if micro_value == 'Yes':

        # How can I set this up to generate a list of all products coming from production, which have micro testing as per my separate item directory?

        pass

print("Starting...")

# Initialize client using SMARTSHEET_ACCESS_TOKEN variable

smart = smartsheet.Smartsheet()
smart.errors_as_exceptions(True)

# Log all of the API calls to play it safe!

logging.basicConfig(filename='rwsheet.log', level=logging.INFO)

print("Logging in-process")

# IMPORT SHEET
production = smart.Sheets.import_xlsx_sheet(_dir + '/Production Schedule.xlsx', header_row_index=0)
sheet = smart.Sheets.get_sheet(production.data.id)

print("Loaded " + str(len(sheet.rows)) + " rows from sheet: " + sheet.name)

# BUILD COLUMN MAP

for column in sheet.columns:
    column_map[column.title] = column.id

# ACCUMULATE ROWS NEEDING UPDATE TO A LIST

rowsToUpdate = []

for row in sheet.rows:
    rowsToUpdate = search_rows_and_build_spreadsheet(row)
    if rowsToUpdate is not None:
        rowsToUpdate.append(rowsToUpdate)

# WRITE UPDATES BACK TO SMARTSHEET SHEET

if rowsToUpdate:
    print("Writing " + str(len(rowsToUpdate)) + " rows back to sheet id " + str(sheet.id))
    result = smart.Sheets.update_rows(results.data.id, rowsToUpdate)
else:
    print("No updates required")

print("Done")

A: You don't need code to do this.  Make a report in Smartsheet that has a filter on the Micro Testing column.  The report will only have the records and columns you want.  People can make changes in the report just like they can in the original sheet but they only see the records that match the filter.


text:
Q: When to remove subview from UITableViewCell? I have a UITableView with searchBar and searchDisplayController. What I wanted to do was to show a button when no results were found. So user could search server's database. I have a NSMutableArrayto store searchResults. So my delegate method looks like this:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"titulo contains [cd] %@", searchText];
    NSArray *filtroUsuario = [self.objects filteredArrayUsingPredicate:predicate];
    self.searchResults = [[NSMutableArray alloc] initWithArray:filtroUsuario];
    if (self.searchResults.count < 1) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(0, 0, 320, 50);
        btn.showsTouchWhenHighlighted = YES;
        [btn setTitle:@"Procurar no Banco de Dados" forState:UIControlStateNormal];
        btn.tag = 1;
        [self.searchResults addObject:btn];
        self.adicionar = YES;
    }
}

Basically, when there are no results, I create and add a buttonto my results array. Then, in cellForRowAtIndexPath, I have the following:
if (tableView == self.searchDisplayController.searchResultsTableView) {
        if (self.adicionar == YES) {
            cell.textLabel.text = @"";
            [cell.contentView addSubview:self.searchResults[indexPath.row]];
            self.adicionar = NO;
        }

This shows the buttonexactly the way I want, and when cancelButtonis pressed, or the buttonin question, I just remove it from searchResultsin case user searches again. [self.searchResults removeAllObjects].
The problem was that, since I'm reusing cells, the subview was still there when user searched again. I had a few options to deal with this, I could create a property for the cell and remove subview when buttonwas pressed. But I opted to include the line [[cell.contentView viewWithTag:1] removeFromSuperview];at the beginning of cellForRowAtIndexPath, so when it's called again, it deletes the subViewsbefore continue.
Everything works perfectly now. My question is if this is the best approach or if there's something more simple. Since my app is a complex app, I'm very concerned about memory and performance, besides, I would really like to learn the coolest techniques available.
Any thoughts?

A: take a look at -prepareForReuse on the UITableViewCell. Probably the best fit for the exact situation you describe. (sketched example below)
@interface CustomCellName : UITableViewCell
@property (strong, nonatomic) UIButton *someButton;
@end

@implementation
- (void)prepareForReuse
{
    _someButton.hidden = YES;
    //etc...
}
@end

Tags are also perfectly fine, although many people find that approach to be unsatisfying. (*citation needed)
An alternate approach is to subclass UITableViewCell with a UIButton as a property which you can tweak from the tableView by -cellForRowAtIndexPath.

A: Best is a flexible term - best in what regard...
What you have works, but it isn't a good allocation of responsibility. It would be better to create a custom cell subclass and have it provide an API where a custom button can be added. The cell subclass would handle cleanup of the button in prepareForReuse.
From a memory and performance point of view there is little difference. But using a cell subclass is more correct.
For performance, it's better not to create and destroy button instances. So, it would be better for your cell subclass to create a button but keep it hidden until it's needed, then show it. Now, prepareForReuse would simply hide the button. Generally this would use a little more memory on average - it's a trade off...

A: First thing, mixing controls with your app data is not a good practice. You can make it work as you already have, but in long term trie to separate UI from application data. Table view should do all the work of presenting data and controls that manipulate your data so it is probably better idea to add string "No Data" to your result array and then handle it in cellForRowAtIndexPath. Create a button on your cell and just hide/show it when you need it. Don't worry about memory consumption, the cells are reusable so you will have very small number of buttons (hidden ones).
Second thing if you really wont to create only one button then tag it, for example, when you decide you need it create it and tag it with say 1000. Then later when you reload and don't want to show it, just ask your cell if it has a view with tag == 1000 and remove it from superview. But again it is an overkill and your memory integrity wont be endangered if you create one button for every visible cell.


text:
Q: Embed a framework without module in a Pod I'm using a 3rd party library provided as a framework : Library.framework. Apparently, it can only be used in my Swift project via the Bridging Header by doing #import <Library/Library.h>. Which is fine in most cases.
However, I'm currently developing a Pod in which I want to use Library.framework. This means that I cannot rely on the Bridging Header.
I tried to link the Library.framework in my Pod target (see General > Linked Frameworks and Libraries) but then, once the Pod is installed in my app, Xcode says the Pod cannot compile because some files in Library are not found.
What would be the best strategy to adopt here ?

A: I think I made it.
The trick was to add the .h files in both source_files and public_header_files in the Pod.podspec.
Like this :
s.source_files = 'Library.framework/Headers/*.h'
s.public_header_files = 'Library.framework/Headers/*.h'

This way, all the header files appear in the Pod-umbrella.h and can now be used in my app.

A: In your pod project I assume you have a file named [PodName].h, it will look similar to the file below.
You could try to add the header in this file.
//
//  PodName.h
//  PodName
//
//  Created by John Doe on 06.04.2016.
//  Copyright © 2016 John Doe Inc. All rights reserved.
//

#import <UIKit/UIKit.h>

//! Project version number for PodName.
FOUNDATION_EXPORT double PodNameVersionNumber;

//! Project version string for PodName.
FOUNDATION_EXPORT const unsigned char PodNameVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <PodName/PublicHeader.h>

#import <Library/Library.h> // Add framework header here.


text:
Q: PhpStorm tell view which object is being used I got the following problem: In PhpStorm I made up my own little MVC framework. Now I wanted to know if there's any way I could tell the view which object/class object it gets from the controller, so it PhpStorm is able to auto-complete, give hints etc.

A: You can simply declare the variables at the top of each view, using phpDoc's @var:
<?php
$view->title = $view->controller->id;

compared to
<?php
/**
 * @var \Framework\View $view
 */

$view->title = $view->controller->id;

This form of doc can be used literally anywhere and is not limited to the top of files:
foreach ($collection as $item) {
    /* @var ItemClass $item */
    var_dump( $item->getProperty() );
}


text:
Q: Get all images of a multi-frame DICOM file I'm trying get all images in a multi-frame DICOM file. Right now I was successfully able to see and save a single image in a single-frame DICOM file, by using the pydicom and matplotlib libraries, like so:
filename = pydicom.data.data_manager.get_files(*base folder path*,*dicom filename*)[0]
ds = pydicom.dcmread(filename)

plt.imshow(ds.pixel_array, cmap=plt.cm.bone)
plt.show()

Now, I wanted to be able to see and save all images in a multi-frame DICOM image, but by using this snippet of code, it returns the following error:
TypeError: Invalid shape (150, 768, 1024, 3) for image data
I've searched a bit on the web, but couldn't seem to find anything to enlighten me. I wanted to know if someone has passed through this, and what's the best way to overcome it, and be able to get all images in a multi-frame DICOM file.
Note: The similar questions found on Stack Overflow are either outdated or do not comply with what I want.

A: DICOM is essentially a 'three-dimensional' image format: it can store lots of images or 'slices'. However, since colour images are already 3-dimensional (height, width, RGB channels), DICOM datasets can actually be 4-dimensional (apparently... I didn't know this). At least, I think that's why there are four elements in the shape of your dataset.
My guess is that the dataset contains 150 images, each of which having 768 by 1024 pixels and 3 channels.
So assuming ds.pixel_array is array-like, you should be able to see the middle slice like so:
plt.imshow(ds.pixel_array[75])

To save them all, you'd do something like this pseudocode:
for i, slice in enumerate(ds.pixel_array):
    plt.imshow(slice)
    plt.savefig(f'slice_{i:03n}.png')

Obviously, that will just re-create what you essentially already have but in a less convenient format, but you get the idea.


text:
Q: Is the tangent bundle of hyperbolic space trivial? Let $H$ be hyperbolic n-space.  Let $TH$ be the tangent bundle of $H$, endowed with its Sasaki metric.  I have two questions:

*

*Is $TH$ isometric to $H$ times a flat n-space?

*What is the group of isometries of $TH$?


text:
Q: If my pagefile is disabled on Windows, should I still be seeing Hard Faults? I am running Windows 7 with 32GB of RAM and have disabled my PageFile.
However, in Resource Monitor, the Memory tab is still showing values for Hard Faults/sec. I've read that this metric should display how many times per second a program is being read out of the PageFile on disk.
Given that I have mine disabled (and have rebooted), why am I still seeing non-zero values for this metric? Also, might this graph include Soft Faults too?

A:
I've read that this metric should display how many times per second a program is being read out of the PageFile on disk.

Then you've clearly read some bogus rubbish.  It's quite wrong to think that in a demand-paged operating system the only possible backing store for memory pages is the system page file.  Program image files containing the code and (read-only/untainted) data for running programs are another possibility.  Then there are explicitly memory mapped files.
Further reading

*

*Jonathan de Boyne Pollard (2007).  Do not throw those paging files away just yet..  Frequently Given Answers.


text:
Q: No response from Docker service I tried following the tutorial here
https://docs.docker.com/get-started/part3/.
First issue I ran into was when I called docker swarm init. It also asked for docker swarm init --advertise-addr with one of two possible IPv6 IPs.
I tried initializing the swarm on both and then starting the service. The service starts succesfully, but I can't get any response when accessing Localhost:4000. It just loads forever.
I have tried rebuilding the image, creating the swarm on both IPs, checking the logs (there was nothing there), but I kind of run out of ideas. If it helps, the computer has dual operating system, might affect the networking in ways I an unable to figure out.
How can I receive a response on my request?

A: The issue I was facing was a connection between google chrome and docker swarm, documented better here
https://forums.docker.com/t/google-chrome-and-localhost-in-swarm-mode/32229/9.
There is no apparent solution


text:
Q: Как отсортировать элементы ToolStripMenuItem Допустим у меня на ContextMenuStrip есть массив элементов ToolStripMenuItem. Есть активные элементы (Enabled=true;) и неактивные. Они расположены так - сначала все активные а потом все неактивные. И вот данные изменились, теперь некоторые неактивные стали активными, а некоторые активные - неактивными. Как теперь отсортировать их в порядке сначала все активные, потом все неактивные?

A: Попробуйте так:
ContextMenuStrip strip = ...;

var newItems = strip.Items
    .OfType<ToolStripItem>()
    .OrderByDescending(i => i.Enabled)
    .ToArray();
strip.Items = new ToolStripItemCollection(strip, newItems);


text:
Q: How to make the code scaleable? There are three divas, but I plan to increase their number, but for this, the code needs to be made scalable, which it is not now.
Inside each diva there is a button that calls another Maps component and only one Maps must be open at the same time.
Here's the code, but how can it be done so that you can easily increase the number of div ??
import React, { Component } from 'react';
import Maps from '../components/map'
import data from '../assets/data'
import './App.scss'

export default class App extends Component {

constructor(props) {
    super(props);
    this.state = { showMap1: false, showMap1Value: "Open map", showMap2: false, showMap2Value: "Open map", showMap3: false, showMap3Value: "Open map" }
    this.onClick1 = this.onClick1.bind(this)
    this.onClick2 = this.onClick2.bind(this)
    this.onClick3 = this.onClick3.bind(this)
    this.onClick = this.onClick.bind(this)

}

onClick1() {
    if (this.state.showMap1 == true) {
        this.setState({showMap1: false, showMap1Value:"Open map"})

    }

    if (this.state.showMap1 ==false) {
        this.setState({showMap1: true, showMap2: false, showMap3: false, showMap1Value:"Close map"})
    }
}

onClick2() {
    if (this.state.showMap2 == true) {
        this.setState({showMap2: false, showMap2Value:"Open map"})
    }

    if ( this.state.showMap2 ==false) {
        this.setState({showMap2: true, showMap1: false, showMap3: false, showMap2Value:"Close map"})
    }
}

onClick3() {
    if (this.state.showMap3 == true) {
        this.setState({showMap3: false, showMap3Value:"Open map"})
    }

    if (this.state.showMap3 ==false) {
        this.setState({showMap3: true, showMap1: false, showMap2: false, showMap3Value:"Close map"})
    }
}

onClick() {

}

render() {

    return (

{data[0][0]}

                    {data[0][1]}

                <input type="button" value={this.state.showMap1Value} onClick={this.onClick1} />

                    { this.state.showMap1 ? <Maps item="0"/> : null }

{data[1][0]}

                    {data[1][1]}

                <input type="button" value={this.state.showMap2Value} onClick={this.onClick2}  />

                    { this.state.showMap2 ? <Maps item="1"/> : null }

{data[2][0]}

                    {data[2][1]}

                <input type="button" value={this.state.showMap3Value} onClick={this.onClick3} />

                    { this.state.showMap3 ? <Maps item="2" /> : null }

    );
}
}

A: The trick is to store your maps in an array within state, then keep track of which map you're working using an index.
 class App extends Component {
   constructor() {
     super();
     this.state = {
       maps: [
        { showing: false, value: "Open map" },
        { showing: false, value: "Open map" },
        { showing: false, value: "Open map" }
       ]
     };
   }

   onClick(index) {
     if (this.state.maps[index].showing) {
       // Open the map at this index
     } else {
       // Close the map at this index
     }
   }

   render() {
     return (

         {this.state.maps.map((map, index) => (

{data[index][0]}

{data[index][1]}

             <input type="button" value={map.value} onClick={e => this.onClick(index)} />

{map.showing && <Maps item={index} />}

         })}

     )
   }
 }


text:
Q: How to delete index data partially in Elasticsearch I want to delete some data from my elasticsearch index and not the complete index, my question is that how can i find the document id of all the available shards. what is the query for that??
I have used the following query in order to delete a particular document, but it throws error so i think my document id is wrong. please let me know how to get the correct document id of available shards.
curl -XDELETE localhost:9200/index/type/documentID

The flow of my data is postgresql to logstash to elasticsearch to kibana. But the problem is that index size is increasing alot its going into GBs of memory whereas my postgresql data is less than 150 mb, and the index size continues to increase even if there is no data being pushed. Please help me to know the working of elasticsearch index.

A: Most likely you're using Elasticsearch version where types were discarded. In this case correct delete command by id would look like this:
curl -XDELETE localhost:9200/index/_doc/documentID

A: one more thing if
curl -XDELETE localhost:9200/index/_doc/documentID
this command is not working then try with
curl -X DELETE localhost:9200/index/_doc/documentID
because the first query was not working for me but when i gave space between X and DELETE i got the result.


text:
Q: System.ObjectDisposedException: 'The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.'2022 Im doing a MVC app but when I try to run it, it shows the following errors
System.ObjectDisposedException: 'The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.'
item.Plan.Plan_Days = 'item.Plan.Plan_Days' threw an exception of type 'System.NullReferenceException'
@model IEnumerable<POS.Models.Faculty>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Crear Nuevo", "Guardar")

            @Html.DisplayNameFor(model => model.Organization_Name)

            @Html.DisplayNameFor(model => model.First_Name)

            @Html.DisplayNameFor(model => model.Last_Name)

            @Html.DisplayNameFor(model => model.Job_Title)

            @Html.DisplayNameFor(model => model.Email)

            @Html.DisplayNameFor(model => model.Photo)

            @Html.DisplayNameFor(model => model.Address)

            @Html.DisplayNameFor(model => model.Phone_Number)

            @Html.DisplayNameFor(model => model.Meal_Plan_Status)

            @Html.DisplayNameFor(model => model.Plan.Plan_Days)

@foreach (var item in Model) {

            @Html.DisplayFor(modelItem => item.Organization_Name)

            @Html.DisplayFor(modelItem => item.First_Name)

            @Html.DisplayFor(modelItem => item.Last_Name)

            @Html.DisplayFor(modelItem => item.Job_Title)

            @Html.DisplayFor(modelItem => item.Email)

             item.Photo)" width="200" />

            @Html.DisplayFor(modelItem => item.Address)

            @Html.DisplayFor(modelItem => item.Phone_Number)

            @Html.DisplayFor(modelItem => item.Meal_Plan_Status)

        <
            @Html.DisplayFor(modelItem => item.Plan.Plan_Days)

            @Html.ActionLink("Edit", "Edit", new { id=item.Employee_ID }) |
            @Html.ActionLink("Details", "Details", new { id=item.Employee_ID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Employee_ID })

}

This is the controller:
using POS.Datos;
using POS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace POS.Controllers
{
    public class FacultyController : Controller
    {
        FacultyAdmin admin = new FacultyAdmin();

        // GET: Faculty
        public ActionResult Index()
        {
            return View(admin.Consultar());
        }

        public ActionResult Guardar()
        {
            ViewBag.mensaje = "";
            return View();
        }

        public ActionResult Nuevo(Faculty modelo)
        {
            admin.Guardar(modelo);
            ViewBag.mensaje = "Informacion Guardada";
            return View("Guardar",modelo);
        }
    }
}

Code of FacultyAdmin.cs:
using POS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace POS.Datos
{
    public class FacultyAdmin
    {
        public void Guardar(Faculty modelo)
        {
           using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
            {
                context.Faculties.Add(modelo);
                context.SaveChanges();
            }
        }

        public IEnumerable<Faculty>Consultar()
        {
            using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
            {
                return context.Faculties.AsNoTracking().ToList(); //AsNoTracking para no hacer copia en  memoria porque no se hace ningun CRUD
            }
        }
    }
}

Faculties definition:
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

namespace POS.Models
{

    public partial class Cafeteria_POSEntities : DbContext
    {
        public Cafeteria_POSEntities()
            : base("name=Cafeteria_POSEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Faculty> Faculties { get; set; }
        public virtual DbSet<KU_Students> KU_Students { get; set; }
        public virtual DbSet<Language_Students> Language_Students { get; set; }
        public virtual DbSet<Menu> Menus { get; set; }
        public virtual DbSet<Order> Orders { get; set; }
        public virtual DbSet<Plan> Plans { get; set; }
        public virtual DbSet<Station> Stations { get; set; }
        public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
    }
}

A: Use .Include() to load related entities before using the data in the view:
public IEnumerable<Faculty>Consultar()
{
    using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
    {
      return context.Faculties.Include(p => p.Plan).AsNoTracking().ToList();
    }
}

The problem here is your Entity Framework context by default configured to use the Lazy Loading. Means related data still not loaded when you tried to use in the Index view.
Therefore when the Index view is trying to query the data the context is actually does not exist.

A: You need to Eager Loading for Plan data that is related to Faculty.

FacultyAdmin.cs

public IEnumerable<Faculty>Consultar()
{
    using (Cafeteria_POSEntities context = new Cafeteria_POSEntities())
    {
        return context.Faculties
            .Include(x => x.Plan)  // Eager Load related Plan data
            .AsNoTracking()
            .ToList();
    }
}


text:
Q: ASP.Net pages hangs on white screen while CPU is almost zero I know that the answer of this question is more a "guidance tip" than a "ready-to-deploy" solution...but this scenario seems weird to me
I have a ASP.Net Web Application (framework 1.1) running under IIS 6.0. The users are complaining about performance issues, than I started monitoring the server.
The server has up to 4GB RAM and up to 4 processors...while monitoring, I noticed that the memory peaks are 2gb and the processing is 35% (not so bad). Important: This server has other websites running on it.
So, looking at IIS log files hasn't helped me...I asked the users to show me their screen, and thats what I could see:
When the users makes a request (any request, even a post-back) IE starts the request, the progress bar starts to load very slowly, IEs screen becomes white and stays like this for a while (some seconds)...after this, suddenly the page is rendered completely, the progress bar goes to the end quite fast (not like before).
During the request, I observed the server processes...the IIS process that serves the application stayed on low memory usage (over 200mb) and low CPU usage (like 2% almost all the time)...When the page has rendered, the CPU increased to 30% and the page finished its loading...
I'd like to know what more to investigate...For me it seems that the requests are being queued, and as it gets processed it works fine...
Thanks.


text:
Q: Filler in BoxLayout.yLast()? I would like to add a lead button over 2 components which are sometimes separated by an empty space as they are in a container which layout is set to BoxLayout.Y_AXIS_BOTTOM_LAST. I want to be able to trigger the button by tapping in the empty space between the component. How can I create a filler component which will take just the leftover available place, if any? I am also interested in other approaches.
Cheers

A: That's problematic as the layout literally doesn't leave anything there. You have two options I can think of:

*

*Create your own layout manager and follow the logic to place a button there if applicable

*Add a pointer released listener to the form and look at the coordinates pressed. If the form isn't scrollable (not filled yet) and the pointer event comes in a y coordinate that's larger than the absoluteY + height of the before last button yet smaller than the absoluteY of the last button then this is a click in the right location
I'm guessing that what you want is the latter. If you want to draw something there you can use a bgPainter on the parent container style that will draw information there.


text:
Q: What change in an EM field is required to create an EM wave? From here

To generate a long wavelength requires an aerial of roughly one wavelength in size.

and here

One of the difficulties posed when broadcasting in the ELF frequency
  range is antenna size, because the length of the antenna must be at
  least a substantial fraction of the length of the waves.

I gather that a charge has to be moved along a straight distance similar to the wavelength of an EM wave to generate an EM wave of that frequency.
If a straight conductor has wavelength in size, does an electron have to move from one end to the other and back  to generate the wave ?
This seems totally different than the distances involved in electron jumps between electron orbitals for generating a given wavelength.
Regardless of the above assumptions being true or false please detail:
What are the movement, speed and accelleration of a charge required to generate an EM wave of a given wavelength?
related: How do near-field EM fields change to far-field EM waves at an antenna
EDIT: Although answers here shed light on the mistakes of my assumptions, none provides a clear answer to the question in bold. I had to to ask another question to get the proper answer : a charge oscillating in space at a given frequency will generate an EM wave of the same frequency

A: You are confusing two frameworks. The classical electromagnetic wave generation , and the quantum mechanical, where electrons live and are modeled.
An antenna works mathematically well with the classical Maxwell equations which predict radiation when the fields across it change.

What are the movement, speed and accelleration of a charge required to generate an EM wave of a given wavelength?

It is the maxwell  equations that have to be solved for a speciific antenna design (boundary conditions) and will have the quantities you ask directly or one can derive them from the solutions.
Electrons in a conductor are modeled with the  quantum mechanical band theory of solids. Electrons in the conduction band over the whole metal lattice,  building up the charge distributions that are necessary for the classical theory to work, when the fields are changing. The classical emerges from the quantum mechanical , but one needs mathematical treatments in order to demonstrate this. See the complication of demonstrating how classical electromagnetic fields emerge from quantum ones here.

A: Accelerating a charge in an oscillatory fashion at a given frequency will generate electromagnetic waves regardless of the length of the path over which the charge is accelerated.
The main reason for selecting a particular antenna length is to make it resonant to the frequency it's designed to transmit or receive.  See, for example,
Wikipedia - whip antenna:

To reduce the length of a whip antenna to make it less cumbersome, an inductor (loading coil) is often added in series with it. This allows the antenna to be made much shorter than the normal length of a quarter-wavelength, and still be resonant, by cancelling out the capacitive reactance of the short antenna. The coil is added at the base of the whip (called a base-loaded whip) or occasionally in the middle (center-loaded whip). In the most widely used form, the rubber ducky antenna, the loading coil is integrated with the antenna itself by making the whip out of a narrow helix of springy wire.

A: The answers provided so far have provided some insight into the challenge of the question as posed. But it's not a challenging question. It just has to be posed properly; that is to say, it should be stated not in terms of macroscopic charge and current, but in terms of electromagnetic force.
First, to quickly define the notion of the electric and magnetic fields. Early observations in electricity showed charged objects (e.g. the famous rubbing of amber, causing the amber to pick up dust and things) attracting and repelling one-another, without being in contact, thus the electric force was defined. Magnetism was of course observed as a force between something like lodestone and iron ore. Currents produce similar force. Thus we have magnetic force. It is useful to abstract the forces, for mathematical reasons, to vector fields. The electric field is the force per charge at a point in space, and is thus represented by a force vector. The magnetic field is dependent on current, the macroscopic flow of charge we now know, and in fact the force on an object is not absolute, but depends on the movement of the object. All force is restricted to one plane of force, and the magnetic field vector defines this plane by pointing normal to it with a magnitude indicating the magnitude of the force per charge per velocity. Thus the magnetic field vector is not a force vector, but an area vector, representing the plane of forces possible.
Okay, we now have those cleared up. From Maxwell's equations in differential (point) form in free space, that is, in the absence of charge or current densities, we arrive at the Helmholtz wave equation,
$$ \nabla^2 \mathbf{E} = \frac{1}{c^2} \frac{\partial^2 \mathbf{E}}{\partial t^2} $$
Which, as has appeared at various points in mathematical physics, is a 3D wave equation. It holds any time $\rho = 0, \mathbf{J}=0$. That is there is no charge or current at a given point. An analogous equation holds for $\mathbf{H}$, the magnetic field.
That means every electromagnetic field obeys a 3D wave equation when in free space. This includes electrostatic solutions, electrodynamic solutions, everything in free space.
While understanding what the wave equation says is nice and enlightening to some extent, the point I'm hoping to make is that the idea of the electromagnetic field is almost like a pool of water. Every change causes a "wave" in that it is a solution to the wave equation. It essentially implies that changes in the electromagnetic field are not instantaneous, but propagate at speed $c$ (the speed of light). So what causes electromagnetic waves? Anything that results in electromagnetic fields in space. That is, any current or charge distribution (macroscopically speaking).
By making simplifying assumptions, most often by assuming that at any given point the direction of wave propagation is well defined, and perhaps by imposing boundary conditions, we can make a very insightful study of electromagnetic wave propagation in terms of sinusoidal waves in space and time. Combining this with Fourier analysis gives a convenient formulation of electromagnetic waves in terms of frequency content, which can be helpful. We also discover the requirements for the propagation of different propagation "modes", where a propagation mode can be considered any arrangement of the fields which produces changes in time according to the real part of $e^{j\omega t}$ at each point and changes in space according to the real part of $e^{-j\beta z}$ for propagation in the $\hat{z}$ direction with phase/propagation constant $\beta$ ($\gamma$ is the general propagation constant, with real and imaginary/phase components). This means that not only does the field at any given point change magnitude and direction cyclically, but the same thing occurs as we move in space.
With such a simplification, the wave equation above gives a number of special cases, namely transverse electromagnetic (TEM) waves, with the electric and magnetic field vectors both transverse to propagation direction, as well as transverse electric (TE) and transverse magnetic (TM) waves, which must propagate in between particular boundaries to exist. We can also look at spherical waves, which are quite common, as you can imagine. Even among these special cases there are further special cases, which allow us to calculate exact field solutions analytically (without computer calculation, numerical solutions) for some geometries. This is really the domain of radio (RF), microwave, and optical engineers and scientists.
However, it is the antenna engineers and scientists who study the radiation of electromagnetic waves. I do a lot of microwave frequency work, and I thought I had it bad with vector calculus, but the classical treatment of antennas is downright tedious.
The topic of radiation, then, focuses on what happens at an interface between e.g. a conductor and free space. Moreover, what exactly do the distant fields look like, and how efficient is the transfer of power/energy? That's a harder question. It's best tackled using the scalar and vector potentials and a lot of vector calculus. That's how it was done by Maxwell, and thats how it's taught today, there's not much getting around it. It's a difficult topic.
All this comes about in terms of classical electrodynamics, which was developed mostly in the 19th century by mathematical physicists and mathematicians including Laplace, Poisson, Green, Gauss, Hamilton, d'Alembert, and Maxwell. Experimentally, Hertz was the first to demonstrate electromagnetic waves. It's worth noting, however, that even Hertz, performing the first experiments in EM wave behavior, noticed the inability of classical electrodynamics to explain some phenomena (in this case, the photoelectric effect). So in essence, when you look closer, it's worth modifying classical electrodynamics into QED and relativistic classical electrodynamics. This is where the idea of charge falls apart, as mentioned by previous answers. Anyway, I hope this is helpful. Just remember that the true insight is in the mathematics, not the stories we tell about the mathematics.

A:
If a straight conductor has wavelength in size, does an electron have to move from one end to the other and back to generate the wave?

No, this is not the case. To explain it, let's see what happens with the emission of EM radiation in a DC circuit. (It's possible to run such a wire with a powerful DC source so that the wire glows. This is a strong evidence that the wire emits EM radiation. Of course the wire emits EM radiation even with a low power source, but this time only in the invisible range.)
The emission happens from the moving free electrons in the metal. These electrons are bouncing forth and back on the atomic structure of the wire, but in sum are moving with the drift velocity. The conclusion is that although not using an alternating current, it is an EM radiation induced. The emission happens in between the free path of the electrons. The wavelengths of the emitted EM radiation depends from the accelerations of the electrons (from the voltage, the wire material, the temperature ...).
Interrupting periodically the DC source one get nearly a square wave signal. Running the switch on high frequencies the signal becomes more and more a sine wave.

I gather that a charge has to be moved along a straight distance similar to the wavelength of an EM wave to generate an EM wave of that frequency.

The above said could be applicated to an AC device and an open circuit. Instead of moving the electrons periodically step by step along the closed circuit with a triggered AC device, the electrons move forth and back with less the drift velocity of around 0,1 mm/s and not at all with a velocity of 300,000 km/s. So again, the electrons don't travel along a straight distance similar to the wavelength.
But of course, the smaller the antenna frequency, the more electrons reach the end of the open circuit and not having the right length, the antenna is not resonant and the efficiency of the EM radiation drops down. Installing a inductive coil, we can damp the current. Or adding a capacity hat or top load we can temporarily collect the arriving on the rods end electrons in the capacitor.


text:
Q: How to use process monitor to view or log a windows login? We're having some issues with Windows 7 Roaming profiles and I was reading here that the login process can be monitored using process monitor.

"There are a couple of ways to configure Process Monitor to record
  logon operations: one is to use Sysinternals PsExec to launch it in
  the session 0 so that it survives the logoff and subsequent logon and
  another is to use the boot logging feature to capture activity from
  early in the boot, including the logon."

How does one do either of these options using process monitor to find out what is happening during a user login?

A:
"There are a couple of ways to configure Process Monitor to record logon operations: one is to use Sysinternals PsExec to launch it in the session 0 so that it survives the logoff and subsequent logon and another is to use the boot logging feature to capture activity from early in the boot, including the logon."

I don't believe that either of the above are valid for Windows 7 for the following reasons:

*

*There's no session 0 in Windows 7, as far as I know.

*User environment debug logging (which is what it sounds like they're recommending) has been replaced/supplanted with the Group Policy event log.
So, my suggestion would be to start by looking at the Group Policy event log on one of the problem machines.

A: procmon - options - enable boot logging
or
login as admin - start procmon - ctrl alt delete - switch user - login as user
switch back to admin and stop tracing


text:
Q: Setting a spinner item selected depending on an Intent Extras value I have a spinner in my activity, populated from a DB, and if the activity gets an Intent with Extras, I want to set an Item from the spinner selected according to the extra. For example - if I have an Extra "CURR_NOTE_CATEGORY" and its value is 2, I want the second item in the spinner to be selected. No extras - just the regular spinner.
So I have this code:
int curr_note_category;

ArrayAdapter<String> adapter;
NotesManager manager = new NotesManager(this);
ArrayList<Category> arrListCategories;
ArrayList<String> arrListCategoriesString = new ArrayList<String>();
Spinner spCategories;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_edit_note);

    spCategories = (Spinner) findViewById(R.id.spCategories);

    if(getIntent().getExtras()!=null){
        // Get Extras
        curr_note_category = getIntent().getExtras().getInt("CURR_NOTE_CATEGORY");

        spCategories.setSelection(curr_note_category);

    }

    manager.getAllCategories();
    arrListCategories = manager.getAllCategories();

    for (int i = 0; i < arrListCategories.size(); i++)
    {
        Category currCategory = arrListCategories.get(i);
        arrListCategoriesString.add(currCategory.getCategory_name().toString());
    }

    adapter=new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, arrListCategoriesString);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spCategories.setAdapter(adapter);
    spCategories.setOnItemSelectedListener(spinnerListener);
}

I'm getting the regular spinner, but never a selected item when there's an Intent Extra. So how can it be done?

A: Please put your spinner set selection code after setOnItemSelectedListener();
adapter=new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, arrListCategoriesString);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategories.setAdapter(adapter);
spCategories.setOnItemSelectedListener(spinnerListener);

if(getIntent().getExtras()!=null)
{
    // Get Extras
    curr_note_category = getIntent().getExtras().getInt("CURR_NOTE_CATEGORY");

    spCategories.setSelection(curr_note_category);
}


text:
Q: Routes are not properly updating its just append the previous child route in React So  was trying to set nested routing under one Layout component
and I am not unable to navigate properly its just adding up previously visited route path to the URL while visiting new route path.
I have set up my routes like this:
<BrowserRouter>
  <Routes>
    <Route path='/' element={<Layout Categorie={Categorie} />}> /*Parent Route*/
      <Route path='basket' element={<Basket />} />
      <Route path='checkout' element={<Checkout />} />
      <Route path='product/:productId' element={<ProductDetails />} />
      <Route path='categorie/:categoryId' element={<Categories />} />
    </Route> /*Parent Route end*/
  </Routes>
</BrowserRouter>

I am navigating to two components
first is to <Categories /> Component:
<Link to={`categorie/${Categorie.Data[i].id}`}>{Categorie.Data[i].title}</Link>

and second is to <ProductDetails /> component
1) <Link to={`product/${id}`}>{title}</Link>
2) <CategoryProductActionButton onClick={() => navigate(`product/${id}`) }>view
   product</CategoryProductActionButton>

now the problem is can successfully navigate to categorie/:categoryId  that is http://localhost:3000/categorie/1 url
but after that when I visit to  my product/:id route I got this http://localhost:3000/categorie/1/product/1 although I was expecting it to be http://localhost:3000/product/1

A: if you have new route and it's not child of current route then you have to pass "/" before any route.
<BrowserRouter>
<Routes>
  <Route path='/' element={<Layout Categorie={Categorie} />}> /*Parent Route*/
  <Route path='/basket' element={<Basket />}/>
  <Route path='/checkout' element={<Checkout />}/>
  <Route path='/product/:productId' element={<ProductDetails />}/>
  <Route path='/categorie/:categoryId' element={<Categories />}/>
  </Route> /*Parent Route end*/
</Routes>
</BrowserRouter>

and you link will be as
<Link to={`/categorie/${Categorie.Data[i].id}`}>{Categorie.Data[i].title}</Link>


text:
Q: Ember and HTML5 contenteditable property I just found out about the contenteditable spec in HTML5. Basically, it allows any html element to be editable when you click on it, just by setting that property to true. For example:

Editable content

would be editablewhen you clicked on it.
Unfortunately this doesn't notify Ember about the change Ember objects, so Ember doesn't know that the value has been changed.
I'm not sure how bindings work, but would this be possible to implement somehow?
Here's a fiddle to show what I'm talking about.

A: I wouldn't use the html5 contenteditable, since, like you said, you it doesn't talk with ember.
Check out this fiddle to see how I would do it in ember. It doesn't have the coolness factor of contenteditable, but at least you know it'll work on all browsers.

A: On the contrary, using contenteditable is both perfectly possible and a great approach to certain use cases in which you wish to implement input areas that resize automatically etc.
Ember.js already contains a view class for <input> elements, but none for
 elements with contenteditable set to true. The key here is to bind to the HTML content of the div and expose a value property just like Ember.TextField has it.
I've covered this in a blog post which can be found here: http://www.kaspertidemann.com/handling-contenteditable-in-ember-js-via-app-contenteditableview/
The blog post boils down to the introduction of App.ContenteditableView, the source of which can be found here: https://github.com/KasperTidemann/ember-contenteditable-view
I hope this helps!


text:
Q: Xrm.sdk and Sharepoint 2013 I need to take data from a Dynamic CRM 2013 tables using web services.
In a Console Application I used microsoft.xrm.sdk.dll and it was so easy to make query using QueryExpression.
But now I need to do the same thing and represent data on an Application Page for SharePoint 2013 Project.
And I used the same way, but there is exception:
Could not load file or assembly "Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=********" or one of its dependencies. The system cannot find the file specified.
Why is it happening?

A: In your VS project --> expand References --> click on the Microsoft.Xrm.Sdk assembly --> lock at it's properties and make sure it's set to Copy Local = true.
If that still doesn't work, try adding the Microsoft.Xrm.Sdk assembly to the SharePoint server GAC. On the server, run gacutil -i [path to assembly]


text:
Q: Ubuntu 20.04 VPN PPTP doesn't work syslog error:
May 8 09:54:21 pptpteste-VirtualBox pppd[2367]: LCP: timeout sending Config-Requests
May 8 09:54:21 pptpteste-VirtualBox NetworkManager[2367]: LCP: timeout sending Config-Requests
May 8 09:54:21 pptpteste-VirtualBox NetworkManager[2367]: Connection terminated.
May 8 09:54:21 pptpteste-VirtualBox pppd[2367]: Connection terminated.
May 8 09:54:21 pptpteste-VirtualBox pppd[2367]: Terminating on signal 15
May 8 09:54:21 pptpteste-VirtualBox pptp[2375]: nm-pptp-service-2351 warn[decaps_hdlc:pptp_gre.c:226]: short read (-1): Input/output error
May 8 09:54:21 pptpteste-VirtualBox pptp[2375]: nm-pptp-service-2351 warn[decaps_hdlc:pptp_gre.c:238]: pppd may have shutdown, see pppd log
May 8 09:54:21 pptpteste-VirtualBox pptp[2382]: nm-pptp-service-2351 log[callmgr_main:pptp_callmgr.c:245]: Closing connection (unhandled)
May 8 09:54:21 pptpteste-VirtualBox pptp[2382]: nm-pptp-service-2351 log[ctrlp_rep:pptp_ctrl.c:258]: Sent control packet type is 12 'Call-Clear-Request'
May 8 09:54:21 pptpteste-VirtualBox pptp[2382]: nm-pptp-service-2351 log[call_callback:pptp_callmgr.c:84]: Closing connection (call state)
May 8 09:54:21 pptpteste-VirtualBox NetworkManager[2367]: Terminating on signal 15
May 8 09:54:21 pptpteste-VirtualBox pppd[2367]: Child process /sbin/pptp 150.161.70.99 --nolaunchpppd --loglevel 0 --logstring nm-pptp-service-2351 (pid 2370) terminated with signal 15
May 8 09:54:21 pptpteste-VirtualBox NetworkManager[2367]: Child process /sbin/pptp 150.161.70.99 --nolaunchpppd --loglevel 0 --logstring nm-pptp-service-2351 (pid 2370) terminated with signal 15
May 8 09:54:21 pptpteste-VirtualBox pppd[2367]: Modem hangup
May 8 09:54:21 pptpteste-VirtualBox NetworkManager[2367]: Modem hangup
May 8 09:54:21 pptpteste-VirtualBox pppd[2367]: Exit.
May 8 09:54:22 pptpteste-VirtualBox NetworkManager[553]: <info> [1588942461.5657] vpn-connection[0x560f4da78590,9cfb61ed-0a2a-4e49-b47c-63ba8b5132b0,"CIN",0]: VPN service disappeared


text:
Q: How to import different classes in one class in JGRASP editor How to import different class in one class in JGRASP so that I can use the second class's code in the first one? Can someone please help..

A: If they all share the same package root directory, you don't have to do anything other than use a Java import statement. If they have different root directories or some are jar files, use "Settings" > "PATH / CLASSPATH" > "Workspace" to add jar files and directories on the "CLASSPATHS" tab.


text:
Q: Eigenvalues and bases for the eigenspaces of $A^n$ Suppose $A$ is given and I want to find corresponding eigenvalues and bases of eigenspaces of $A^n$. Then I know from $Ax = \lambda x$, $A^n x = A^{n-1} (Ax) = \lambda^n x$, so it seems $A^n$ has eigenvalues $\lambda^n$ and same eigenvector $x$
First, am I right? and second, if this is true, How one can prove this rigorously?

A: You are right and the formal proof could be written using induction. We want to show that $A^n$ has eigenvalue $\lambda^n$, if $A$ has eigenvalue $\lambda$, and that $A^n$ has the same corresponding eigenvector, say $v$. This is, $A^n v = \lambda ^n v$ for all $n$. Now the case $n = 1$ is evidently true, so assume that the statement is true for a fixed $n \in \mathbb{N}$. Then we have
$$A^{n + 1} v= A (A^n v).$$
Now, by the induction hypothesis, $A^n v = \lambda^n v$. Hence
$$A^{n + 1}v = A(\lambda^n v) = \lambda^n (Av) = \lambda^n (\lambda v) = \lambda^{n + 1} v, $$
which proves the claim.


text:
Q: How to manage a map of unsaved entities in Hibernate session? On my entity (myGroup : Group) I have a collection property (members : HashMap<Long, GroupMember>) and I want to allow the user to add multiple new (unpersisted) GroupMembers to the myGroup.members map.

*

*The reason why I am using a hashmap for the collection property is to ensure the use of the collection is performant (i.e. must be able to get a GroupMember by its ID quickly and multiple times during execution of the business logic).

*The reason why I don't want to persist them straight away is to support reversion of the additions. The user must be able to manipulate the myGroup.members map, adding and removing members until satisfied, before persisting (saving the entities in the Hibernate session and flushing).
The problem is that new GroupMembers must be assigned an ID of zero for Hibernate to detect that they're unsaved.(*) Because the members are in a map, keyed by ID, that means only one new member can be added prior to either a save or revert. The addition of a second new member with ID zero simply overrides (the reference to) the first.
My question is how can I best adapt my code solution to support the addition of multiple unsaved entities to the collection (myGroup.members) while keeping the performance advantage of using a hashmap or other map/dictionary?
Note: I have already tried a hack whereby a ID is derived from unique combination of data in a GroupMember instance and then, just before a save, the ID is set to zero in order for Hibernate to detect it needs to be persisted, but it is inelegant and I haven't found a way for it to work reliably.
* I don't fully understand Hibernate's behaviour in this regard.
Abbreviated code for the Group entity below:
@Entity
@Table (name="GROUP")
public class Group
{
    private Map<Long,GroupMember> members = new HashMap<Long,GroupMember>();

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "ownerGroup", cascade = { CascadeType.ALL })
    @MapKey(name="id")
    public Map<Long,GroupMember> getMembers() { return this.members; }

    public void setMembers(Map<Long,GroupMember> members) { this.members = members; }

    // ...other properties and methods...
}

A: I am a bit confused on what you are going to achieve.  Members that are not persisted do not have any ID.  What do you expect the "lookup" behavior for these members as you are using ID as the key?  It don't seems reasonable for me that you can lookup new members by ID, as they do not have any identity yet.
If lookup new members is not required, I will suggest you:

*

*a separate attribute storing "new members"

*have method commit() and revert() in your entity

*User will invoke commit() when it is done updating, and new entities will then be moved to the actual "mapped" map/list for actual persistence

If lookup of new members is REQUIRED, and from your passage, it seems that you are capable to generate a proven unique key yourself, will you consider NOT having hibernate to generate the ID for you?  You have the option in Hibernate to decide whether the ID is generated by Hibernate (as a surrogate key) and provided by you (kind of a natural key).  I believe a self-provided ID is more suitable in your case, as you seems not treating the ID as a surrogate key.

Edited: with respect to the comment from the OP about the reason for unable to store it separately, it can be easily solved in this approach (and I think it makes more sense too):
(pusedo code)
class Group {
  private List<Member> members;  // mapped in hibernate
  private List<Member> unsavedMembers;  // unmapped

  public Map<Long, Member> getProposedMemberMap() {
    // returned the combined "view" members and unsavedMembers
  }

  @PreUpdate  // you may consider running it it pre-update too
  public void commit() {
    members.addAll(unsavedMembers);
    unsavedMembers.clear();
  }

  public void revert() {
    unsavedMembers.clear();
  }
}

By doing so, you have a view of the "proposed members" for you to iterate, while storing the actual and unsaved members separately.


text:
Q: TypeError: add() takes exactly 2 positional arguments (3 given) Why I am getting this error Can anyone tell please
or explain me how to use it using simple example
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_33/3577035061.py in <module>
      6 # Matcher class object
      7 matcher = Matcher(nlp.vocab)
----> 8 matcher.add("matching_1", None, pattern)
      9
     10 matches = matcher(doc)

/opt/conda/lib/python3.7/site-packages/spacy/matcher/matcher.pyx in spacy.matcher.matcher.Matcher.add()

TypeError: add() takes exactly 2 positional arguments (3 given)

In Below link
https://spacy.io/api/matcher

A: The new version of spacy needs square brackets around pattern. Also, callback became an optional term.
Therefore in your case you just need:
from spacy.matcher import Matcher

matcher = Matcher(nlp.vocab)
matcher.add("matching_1", [pattern])
matches = matcher(doc)

A: What are you passing the None for? It looks like you just need:
matcher.add("matching_1", pattern)

You are getting the error because the function takes 2 unnamed arguments but you are trying to pass 3. If you want to pass a callback function as well you would need to write:
matcher.add("matching_1", pattern, on_match = my_callback_function)

A: This works for me
If you anyother answer feel free to answer
# load spaCy model
nlp = spacy.load("en_core_web_sm")
text = "GDP in developing countries such as Vietnam will continue growing at a high rate."

# create a spaCy object
doc = nlp(text)

#define the pattern
pattern = [[{'POS':'NOUN'},
           {'LOWER': 'such'},
           {'LOWER': 'as'},
           {'POS': 'PROPN'}] ]#proper noun
# Matcher class object
matcher = Matcher(nlp.vocab)
matcher.add("matching_1",patterns=pattern)

matches = matcher(doc)
span = doc[matches[0][1]:matches[0][2]]

print(span.text)

A: matcher.add("matching_1", [pattern])

This worked for me


text:
Q: how to return image url instead of file path I am facing an issue when showing uploaded image in browser.
I get error

Not allowed to load local resource:
  file:///C:/Office%20Data/dummy/AngularJSAuthentication-master/MyCars/MyCar.API/App_Data/Images/p7.jpeg%20alt=

I wrote the following line of code to store image on server under App_data.
File.Path = Url.Content(string.Format("{0}/{1}", System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Images"), fileName));

File path saved in DB as following
file:///C:/Sample%20Data/dummy/AngularJSAuthentication-master/MyCars/MyCar.API/App_Data/Images/p7.jpeg

HTML

After googling i got the reason for this error.
Basically i need to return back Image URL instead of file path.

Problem:
I am not sure how i can return image path back to angular client.
Can someone guide me on it.

A: You don't need to specify the complete physical path, when reference from the browser
File.Path = Url.Content(string.Format("~/App_Data/Images/{0}", fileName));

this should return the relative URL
Update : well this won't work since you can directly access contents of the app_data folder. you can approach this either of these ways

*

*move the images out of the app_data folder to like ~/images folder
and it should work or

*keep the file in the app_data folder but stream the file using
content/file result action on one of your controllers

bare minimum sample implementation of the second option would look like
public class UploadsController : Controller
{
    [HttpGet]
    public ActionResult Image( string fileName )
    {
        //!validate file name!
        return File( Server.MapPath( $"~/App_Data/{fileName}" ), "image/jpeg" );
    }
}

then in the HTML it can be referenced as <img src="api/uploads/image?filename=temp.jpg" ...

A: Just drop everything except the file name if all your images are in the root of Images:
//using System.IO;

File.Path = Url.Content(string.Format("{0}/{1}", System.Web.HttpContext.Current.Server.MapPath("~/App_Data/Images"), Path.GetFileName(fileName)));

Update

should have been like Sam's answer:
File.Path = Url.Content(string.Format("~/App_Data/Images/{0}",Path.GetFileName(fileName)));


text:
Q: Determinant of covariance and correlation matrix I am reading the book Network Information Theory by El Gamal and I can't understand this particular part given in the book:
Let $X \sim f(x^n)$ be a random vector with co-variance matrix $K_X = E[(X − E(X))(X − E(X))^T] \geq 0$. Then $$h(X) \leq \frac{1}{2}\log ((2\pi e)^n|K_X|) \leq \frac{1}{2}\log((2\pi e)^n|E(XX^T)|)$$
where $E(XX^T)$ is the correlation matrix of $X$. The first inequality holds with equality
if and only if X is Gaussian and the second inequality holds with equality if and only if
$E(X) = 0$.
I can't understand how the author introduced the 2nd inequality with the correlation matrix. Is there any result that determinant of correlation matrix is always greater than equal to determinant of co-variance matrix?


text:
Q: AWS STL_LOAD_ERRORS not loading, receiving error message I'm trying to look at the error messages after trying to COPY S3 files into Redshift.
Using this:
SELECT * FROM stl_load_errors;

Error message returning:
Query result is not ready, status: FINISHED (Service: AmazonRedshift; Status Code: 400; Error Code: QueryNotFinished; Request ID: 71e1d849-29ac-4e18-8746-2a25f71e67c7; Proxy: null)
Never seen this before.
Thanks.


text:
Q: Animator setFloat doesn't response C# Unity3d I'm making 3d animation for charachter movement, and Animator.SetFloat(...) doesn't response in functions that I call in if statements, code below. Interesting thing that these Debug.Log's work
properly, when I walk console has "Walk", when I run console has "Run" etc.
I think I have problem with Scope, but I'm really sure.
Screenshots: animator props console logs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float moveSpeed;
    [SerializeField] private float walkSpeed;
    [SerializeField] private float runSpeed;
    [SerializeField] private float groundCheckDistance;
    [SerializeField] private float gravity;
    [SerializeField] private bool isGrounded;
    [SerializeField] private LayerMask groundMask;
    [SerializeField] private float jumpHeight;
    private Vector3 moveDirection;
    private Vector3 velocity;
    private CharacterController controller;
    private Animator anim;
    void Start()
    {
        controller = GetComponent<CharacterController>();
        anim = GetComponentInChildren<Animator>();
    }
    void Update()
    {
        Move();
    }
    private void Move()
    {
        isGrounded = Physics.CheckSphere(transform.position, groundCheckDistance, groundMask);

        if(isGrounded && velocity.y < 0) velocity.y = -2f;

        float moveZ = Input.GetAxis("Vertical");

        moveDirection = new Vector3(0, 0, moveZ);
        moveDirection = transform.TransformDirection(moveDirection);

        if (isGrounded)
        {
            if (Input.GetKeyDown(KeyCode.Space)) Jump();

            if (moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift)) Walk();

            else if (moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift)) Run();

            Idle();

            moveDirection *= moveSpeed;
        }
        controller.Move(moveDirection * Time.deltaTime);
        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
    }
    private void Idle()
    {
        anim.SetFloat("speed", 0);
    }
    private void Walk()
    {
        anim.SetFloat("speed", 0.5f);
        moveSpeed = walkSpeed;
        Debug.Log("Walk");
    }
    private void Run()
    {
        moveSpeed = runSpeed;
        Debug.Log("Run");
        anim.SetFloat("speed", 1);
    }
    private void Jump()
    {
        velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
        isGrounded = false;
    }
}

A: Ok, I've found the solution, I missed "else", because of that Function Idle() always had control under Animator.SetFloat(...)
if (isGrounded)
        {
            if (Input.GetKeyDown(KeyCode.Space)) Jump();

            if (moveDirection != Vector3.zero && !Input.GetKey(KeyCode.LeftShift)) Walk();

            else if (moveDirection != Vector3.zero && Input.GetKey(KeyCode.LeftShift)) Run();

            else Idle(); //this how it must looks like

            moveDirection *= moveSpeed;
        }


text:
Q: Chrome extension getting selected text JavaScript I was wondering what is the easiest way to get selected text from tab and put string into a variable
My Popup html code
    <!DOCTYPE html>
<html>
    <head>

    </head>

    <body>
          <button id="clickme">click me</button>
        <canvas id="myCanvas" width="300" height="300"></canvas>
          <textarea id="output"> </textarea>
        <script src = "popup.js"></script>
    </body>

</html>

My javaScript
    chrome.tabs.executeScript( {
  code: "window.getSelection().toString();"
}, function(selection) {
  document.getElementById("output").value = selection[0];
});

I tried this but got an error
*

Error in response to tabs.executeScript: TypeError: Cannot read
  property '0' of undefined
      at Object.callback (chrome-extension://nnhcblfafgjjoolcnjckidjgjcmmgnlp/popup.js:4:54)
      at chrome-extension://nnhcblfafgjjoolcnjckidjgjcmmgnlp/popup.js:1:13

*


text:
Q: Fatal error when deploying a shiny app with Rstudio I have a shiny app (divided into ui.R, server.R and helpers.R) which works on my local machine. The app does not load any libraries besides library(shiny). I am unable to deploy it to shinyapps.io. That is what I do

*

*I log myself into shinyapps.io (via the website www.shinyapps.io)

*I run library(rsconnect) on the R console.

*I copy the Tokens code (rsconnect::setAccountInfo...) from the www.shinyapps.io page into the R console and run it.

*I run the app in Rstudio (1 warning: Warning in body(fun) : argument is not a function). The app runs as expected.

*I use the "publish" button in the app window and get a new window saying: "R session aborted. R encountered a fatal error. The session was terminated"

Sorry, I have no idea about where to look for the error. Can you give me a hint what causes the problem? Which additional information would you need to help me?
Thanks a lot!
update: I just saw that there is a second "publish"-button in Rstudio if you have one of the app-files in the editor (without running it). When I use this one, I get the same crash, but with some more information: unexpected exception: boost::filesystem::unique_path: key is not valid in specified status (sorry, that is my own translation from German).

A: One way of deploying an app to the shinyapps.io server is not to use the button in RStudio, but to do it via the console. Here the steps that are working for me now (RStudio 1.0.143):

*

*Log in on shinyapps.io (via the website www.shinyapps.io)

*Run library(rsconnect) on the R console.

*Copy the Tokens code (rsconnect::setAccountInfo...) from the www.shinyapps.io page into the R console and run it.

*Run rsconnect::deployApp('path to your app') on the R console.

Pushing the publish button in RStudio still results in a crash of R.


text:
Q: Notifications are not grouped in iOS 12 According to the WWDC 2018 Apple Keynote, iOS 12 has brought notification improvements since now message threads and notification topics are grouped together.

Nevertheless, I have noticed that, sometimes, notifications generated from the same app (e.g., from Gmail or Facebook Messenger) still appear "one under the other" and are not collectively stacked on the home screen as they should be supposed to. How should I fix this issue?


text:
Q: Why do I keep getting 'Bad Request' when I try to post a task in Java using the Google Task API? I'm building an app coded in Java/Android and using the Google Task API but I have hit a major problem.
I try to enter a Due or Completed date the Task API returns a 'Bad Request' error. I have however managed to post tasks successfully when I don't attempt to set a Due or Completed date.
I have spent hours researching this issue the closest I have found to a solution is the following thread:
http://groups.google.com/group/google-tasks-api/browse_thread/thread/1753df5bbc8e3cb8/ab66b5e675f06e6a?lnk=gst&q=problem+changing#ab66b5e675f06e6a
I have attempted to set the task's status along with a date as mentioned in the thread but that doesn't seem to work for me.
I presuming I have formatted the DateTime wrong, although I'm just using a DateTime as specified in the Google docs (com.google.api.client.util.DateTime).
This is an example of a typical DateTime value that I'm attempting to use:

2011-10-03T22:28:626

I have tried the following code...
DateTime date = new DateTime(new Date());
Task task = new Task();
task.setTitle("Hello World");
task.setDue(date);
task.setStatus("needsAction");

and ...
DateTime date = new DateTime(new Date());
Task task = new Task();
task.setTitle("Hello World");
task.setCompleted(date);
task.setStatus("completed");

I would be very grateful if anyone can help me.
Thank you.

Thank you for everyone who viewed.
After a little more digging I found the answer so here it is...
The Google Task API currently only accepts a DATETIME.
I was providing a DateTime but the format was incorrect, I had to add a Time Zone Shift Integer. e.g. com.google.api.client.util.DateTime.DateTime(long value, Integer tzShift).
I simply did the below instead and it worked.
DateTime date = new DateTime(System.currentTimeMillis(), 0);
Task task = new Task();
task.setTitle("Hello World");
task.setDue(date);
task.setStatus("needsAction");

A: What happens if you try providing the date as a String?
According to the developer docs, this should be valid. For instance, this is one of the examples provided:
Task task = new Task();
task.title = "New Task";
task.notes = "Please complete me";
task.due = "2010-10-15T12:00:00.000Z";

Task result = service.tasks.insert("@default", task).execute();
System.out.println(result.title);

[From: http://code.google.com/apis/tasks/v1/using.html#creating_task ]
If this works, it's possible that there's a bug in the client library when converting your DateTime object into a JSON string.

A: Use:
DateTime date = new DateTime(System.currentTimeMillis(),0);
task.setDue(date);

or
new DateTime(new Date(value), TimeZone.getDefault());

Don't use:
DateTime date = new DateTime(System.currentTimeMillis());

A: There are one more possibly. I use a thread to run the update.execute() coding and case the same result. (Bad request / 400 / Invaild input)


text:
Q: Find details of device based on dns name using ip command When I'm retrieving the mac address of a device
I execute following command
$ arp <dnsname> | grep "HWaddress" -A1 | awk '{print $1 "" $3}' |head -2 | tail -1

this will probably print
<dnsname> <mac address>

As I've seen from the manual of arp is that it is deprecated and alternate I have is to use 'ip' command instead of arp .

A: arp is able to take names as input and print names in output.  ip uses addresses only.
If you can deal with addresses, then modifying the output is pretty easy.
$ ip neigh show to 10.0.0.1
10.0.0.1 dev wlan0 lladdr dc:fb:02:xx:xx:xx REACHABLE

$ ip neigh show to 10.0.0.1 | awk '{print $1 " " $5}'
10.0.0.1 dc:fb:02:xx:xx:xx

I just noticed that your title specifically asks about DNS names.  If that's the requirement, then you'll want to translate the name in your script.
$ ip neigh show to `getent hosts <dnsname> | awk '{print $1}'` | awk '{print $1 " " $5}'
$ 10.0.0.1 dc:fb:02:xx:xx:xx


text:
Q: How can I get a user to subscribe to a Pusher Channel based on the group they are in? Each user is placed in a group, my site has 5 groups. I only want events in group X to be broadcast to clients who are in group X. How can I create channels like this and get the client to subscribe to them?
Pusher.logToConsole = true;

        var pusher = new Pusher('ec160cc0a1ca15e463f4', {
            cluster: 'eu',
            forceTLS: true
        });

        var channel = pusher.subscribe("{{Player::where('user_id', Auth::user()->id)->first()->group_id}}");
        channel.bind('NewPurchase', function(data){
            window.alert('successful!');
        });

I create these custom groups in my backend just fine however
public function broadcastOn()
    {
        return [Player::where('user_id', $this->product->seller_id)->first()->group_id];
    }

I keep getting a 'Class Player not found', perhaps because the php I have there doesn't seem to be read?

A: Since Player is a model, instantiate it via fully qualified name
var channel = pusher.subscribe("{{\App\Player::where('user_id', Auth::user()->id)->first()->group_id}}");

public function broadcastOn()
{
   return [App\Player::where('user_id', $this->product->seller_id)->first()->group_id];
}

A: "The broadcastOn method should return a channel or array of channels that the event should broadcast on. The channels should be instances of Channel, PrivateChannel, or PresenceChannel."
var channel = pusher.subscribe("{{Player::where('user_id', Auth::user()->id)->first()->group_id}}");

So, if you are having problems with the Class, you could add the param to the event. It should look like this:
class YourEvent implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $group_id;

    public function __construct($group_id)
    {
        $this->group_id= $group_id;
    }

    public function broadcastOn()
    {
        return new Channel($this->group_id);
    }
}

and call the event:
event(new YourEvent(Player::where('user_id', Auth::user()->id)->first()->group_id));


text:
Q: Does armor type affect stats in any way? Do armors have tiers as to what stats they can have? I see a lot of high level people running around with pristine gear and sometimes leather. Are these armors just better stat wise or are all types equal? (Chain, Mail, Leather, Plate and Pristine)

A: Armor types are exactly the same. A pristine helmet with +50 on each stat serves an identical use as a leather helm with +50 on each stat. Additionally there is no "better" armor type at a given level; leather armor with good stats has just as much of a chance to spawn as pristine armor with good stats.
Armor types exist for set bonuses. If you wear all the same armor type (e.g. all leather armor), you get a 25% bonus to all stats on low tier armor. The set bonus increases with higher tier armor, up to Ultimate gear at 40%.
Keep in mind that you cannot mix Godly and below with Mythical and above.