text:
Q: Suggestion on how to debug ComboBoxModel in my project I've several JComboBox with their custom models. Basically they are used to show values of some JTables column (therefore I decided to implement them on the relative
class extending AbstractTableModel).
public class MyTableModel1 extends AbstractTableModel{

    protected class MyTableComboBoxModel1 extends AbstractListModel implements ComboBoxModel{

        private Object selected;
        @Override
        public Object getElementAt(int index) {
            return getValueAt(index, 1);
        }

        @Override
        public int getSize() {
            return getRowCount();
        }

        @Override
        public Object getSelectedItem() {
                 return this.selected;

        }

        @Override
        public void setSelectedItem(Object anItem) {
                     this.selected = anItem;
        }

    }
}

And I have several models : MyTableModel2 with MyTableComboBoxModel2. These models all do pretty the same thing except some additional operations not related neither with the combobox nor with the table itself.
The purpose of all this stuff should be to update JComboBox's displayed values accordingly to modifications occured to the relative JTable.
All works fine for models I've implemented except in one case , and after several hours of debug I still can't solve it. The code of the bugged model is almost identical to the others. Probably it's a bug somewhere else in my code, but I can't figure out where.
The wrong case has the following behavior: when I initially created a table with some values these are correctly displayed even in the JComboBox, but when I add a new row the displayed values become all blank (the size of the displayed blank menu is right).
I found out that:

*

*the new row of the jtable is added correctly.

*the getElementAt method is called several times when clicked on the JComboBox and return all the available values (including the new ones).

*the method getSize() is called when I click the JComboBox and return the right updated value

*If JComboBox has focus I can use arrows to select the available items and all items are selectable (even the added ones).

*If I use the mouse clicking one point at random on the displayed blank menu, all the last available entry could be chosen.

Has someone any idea? Could you suggest me how could I debug in such a situation? Unfortunately I can't post an SSCCE.. I hope someone could help anyway..

A:
I know that my question is a bit vague

Which is why a SSCCE is required.

Each combo box should show all the value of a particular column of an existing JTable

I don't understand why you need a custom model. I would guess you just need to use a TabelModelListener.
Whenever a value is added/removed you updated the combo box.


text:
Q: How to change the data of a node in Linked list in C? struct:
//linked list
struct list
{
  int32_t data;
  struct list *next;
};

struct list *head;

at first, initialize linked list (every node be 0):
void initLinkedList(int size)
{
    head = (struct list*)malloc(sizeof(struct list)*size);
    struct list *current = head;

    for(int i = 0; i < size; i++)
    {
        (current+i)->data= 0;
    }
}

function:
void changeNode(int32_t element, int index)
{
    struct list *current = head;

    for (int i = 0; i < index; i++)
    {
        current = current->next;

    }

    current->data= element;
}

so basically, I want to create a linked list with size nodes, then change the data of the node through function.
But I'm getting Segmentation fault at this line in function:
current->localVar = element;
So, how can I change the data of a node without inserting a new one?

A: You must consider whether you have requested to change an index that doesn't exist in your list, but otherwise you are close. You are not iterating your initLinkedList in a traditional manner (you are treating the list like an array) As a side-note: In C, there is no need to cast the return of malloc, it is unnecessary. See: Do I cast the result of malloc?.
Let's start with your initLinkedList function. You have declared head globally (assuming) and then go to fill your list with zeros. In doing so, you never initialize any of your ->next pointers. You don't end up with a linked-list -- you have a block of allocated nodes.
You should iterate current = current->next; and set each ->next pointer, not just use the offset +i. You are able to initialize your data like that due to allocating all nodes in a continual block -- but any node added later will not be contiguous in memory and none of your ->next pointers are initialized.
Now on to your changeNode function. You must fix your initLinkedList to initialize the ->next pointers. Then you need to change the return type from void to struct list* so you can return a pointer to the changed node on success or NULL on failure. Currently, you have no way of knowing if your change succeeded or failed.
Making the changes you could do:
struct list *changeNode (int32_t element, int index)
{
    struct list *current = head;

    for (int i = 0; i < index; i++) {
        if (!current->next) {
            fputs ("error: request exceeds no. of nodes in list.\n", stderr);
            return NULL;
        }
        current = current->next;
    }
    current->data = element;

    return current;
}

Look things over and let me know if you have further questions.

A: So, here void initLinkedList(int size) you aren't creating/initializing a linked list instead you are declaring an array of type struct list dynamically with size no. of elements and then you are initializing all of them with value 0.
To initialize your linked list code this:
void initLinkedList(int size)
{
    if((head = (struct list*)malloc(sizeof(struct list)*size)) == NULL)
    {
        printf("Memory Unavailable.\n");
        exit(1);
    }
    struct list *current = head;

    for(int i = 0; i < size; i++)
    {
        current->data = 0;
        if ((current->next = (struct list*)malloc(sizeof(struct list))) == NULL)
        {
            printf("Memory Unavailable.\n");
            exit(2);
        }
        current = current->next;
    }
    current->next = NULL;
}

Then to changeNode, code this:
void changeNode(int element, int index)
{
    struct list *current = head;
    int count = 0;
    while(count != index)
    {
        if(current->next)
            current = current->next;
        count++;
    }
    current->data = element;
}

Here I'm adding another function to print the linked list:
void print(struct list *head)
{
    if(head->next)
    {
        printf("%d", head->data);
        head = head->next;
        print(head);
    }
}

main():
int main(void)
{
    initLinkedList(5);
    changeNode(5, 4);
    print(head);
    delete(head);
    printf("Memory freed.\n");
    return 0;
}

Now you can see the Sample Output:
00005
Memory freed.

One more thing, if you are confused about this:
if ((current->next = (struct list*)malloc(sizeof(struct list))) == NULL)
I can help you. In the above line of code, we're allocating memory to current->next and checking if memory is allocated successfully or not.
Freeing the memory allocated to linked list using delete() function:
void delete( struct list *head )
{
  struct list *current = head;
  struct list *next = NULL;
  while(current != NULL)
  {
    next = current->next;
    free(current);
    current = next;
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is generating real random numbers this easy in C#? I found this code using Google.
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}

Is this really all there is to generating REAL random numbers in C#? I intend to generate on a small scale between values 1-10.
Thanks

A: If you are going to use the Random class (which is fine for most things), you don't want to make a new Random Object for each call. I'd recommend making a static member of the containing class:
private static Random random = new Random();
private int RandomNumber(int min, int max)
{
    return random.Next(min, max);
}

This is because, by default, the Random class uses the system time.

MSDN: However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers. Link

For a more "real" random number you can use RNGCryptoServiceProvider (which is mentioned by Dean Harding).

A: What do you mean by "real"? They're random numbers, of course, though perhaps not cryptographically secure random numbers. For the majority of applications, though, Random.Next is definitely good enough.
If you want cryptographically secure random numbers, check out the System.Security.Cryptography.RandomNumberGenerator class.

A: You don't have to make your own class that wraps the already existing "Random" class. You can just call:
int myNumber = (new Random()).Next(1, 10);

Also, regarding "REAL random numbers"... it's random enough for 99.99% of the needs out there in the world.


text:
Q: Record each time a jailbroken iDevice power On/Off I want to record the time when an iDevice turns On/Off and then save it in a database when the device turns on.I will save both the turn-off and turn-on time when the iDevice turns-on.
I tried to do this in android using the broadcastreceiver, is this possible in iOS?
I found a list of public notifications in https://gist.github.com/hpique/7554209 and its not there.
I hope someone could help me. Thank you.


text:
Q: Javascript event on frame loaded I can't quite work out how I can get a frame being notified when another frame has changed.
<frameset rows="*,50">
    <frame id="main_frame" src="mainframe" frameborder="0" name="main_frame">
    <frame id="footer" src="footer" frameborder="0" scrolling="no" noresize="noresize" name="footer">
</frameset>

The footer frame needs to set some values in mainframe once it's loaded. If the user loads another page, this setup has to occur again. In the footer, I'd like to have an event on when the main frame has completed loading (every time it changes).
Is this possible (perhaps even with jQuery)?

A: The below is just an example; I used jQuery's load event, and this code would be placed in your main_frame frame.  It gets the parent of the frames, then the children frames as per the array.  Hopefully you can extrapolate it into what you need.
In this example, it is assumed that the yourValue variable is a global variable in either of your frames.
$(document).ready(function() {
    $(window).load(function (){
        window.parent.frames[0].yourValue = 4; // change values of main frame
        window.parent.frames[1].yourValue = 4; // change values of footer frame
    });
});


text:
Q: One method to save entity which extand abstract class in repository I am new at abstract class as Entity so for training I created abstract class
@Entity
@Inheritance(strategy = TABLE_PER_CLASS)
@Getter
@Setter
@NoArgsConstructor
public abstract class ShapeEntity {
     @Id
     @GeneratedValue(generator = "system-uuid")
     @GenericGenerator(name = "system-uuid", strategy = "uuid")
     private String id = UUID.randomUUID().toString();
}

and classes which extand Shape:
public class SquareEntity extends ShapeEntity {
    ...
}
public class CircleEntity extends ShapeEntity {
    ...
}

every entity has repostiory like that:
public interface CircleEntityRepository extends JpaRepository<CircleEntity, String> {
}

When I want to update entity I am searching it in every repository, next (if entity was found) map parameters and finnaly have to save that entity in database.
How can I easy decide which repository should be used for it? I created method save with if else which now works:
public ShapeEntity save(ShapeEntity shapeEntity) {
    if (shapeEntity.getClass().getName().contains("CircleEntity")) {
        return circleEntityRepository.save((CircleEntity) shapeEntity);
    } else if (shapeEntity.getClass().getName().contains("SquareEntity")) {
        return squareEntityRepository.save((SquareEntity) shapeEntity);
    } else {
        throw new EntityNotFoundException();
    }
}

but it is a bit uncomfortable becouse when I will have 20 entities I will have to create 20 else if loops. Can I do any interface for this or something like that?

A: If you create a ShapeEntityRepository for the ShapeEntity class you don't need if-else blocks.
public interface ShapeEntityRepository
        extends JpaRepository<ShapeEntity, String>,
        JpaSpecificationExecutor<ShapeEntity> {}

ShapeEntityRepository is useable for all classes that are extended from the ShapeEntity class.
ShapeEntity circleEntity = new CircleEntity();
ShapeEntity squareEntity = new SquareEntity();

shapeEntityRepository.save(circleEntity);
shapeEntityRepository.save(squareEntity);

Alternatively, if there must be different repositories, you can use Spring's GenericTypeResolver to get the repository of the class.
@Component
public class RepositoryHolder {

    private final List<JpaRepository> jpaRepositories;

    public RepositoryHolder(List<JpaRepository> jpaRepositories) {
        this.jpaRepositories = jpaRepositories;
    }

    public JpaRepository getRepositoryBy(Class<?> domainClass) {
        Optional<JpaRepository> optionalRepository = jpaRepositories.stream()
                .filter(repository -> GenericTypeResolver
                        .resolveTypeArguments(
                                repository.getClass(),
                                Repository.class
                        )[0]
                        .equals(domainClass))
                .findFirst();
        if (optionalRepository.isPresent()) {
            return optionalRepository.get();
        } else throw new IllegalArgumentException();
    }
}

If you want to use it, your save(...) method will be something like this:
public void save(ShapeEntity shapeEntity) {
    JpaRepository repository = repositoryHolder
            .getRepositoryBy(shapeEntity.getClass());
    repository.save(shapeEntity);
}

Note: JPA Repository allows to use default CRUD functions, you can add an intermediate repository bean like here and reduce these codes to that intermediate repository.


text:
Q: computed column based on function I would like to create computed column for profileapplication for below code.
Substring(Substring(P.propertyvaluesstring,
                            Charindex('ProfileApplication', P.propertyvaluesstring),
                            Charindex('</ProfileApplication',P.propertyvaluesstring) -
                            Charindex('ProfileApplication',P.propertyvaluesstring)),
                            Charindex('>', Substring(P.propertyvaluesstring,
                            Charindex( 'ProfileApplication',P.propertyvaluesstring),
                            Charindex('</ProfileApplication',P.propertyvaluesstring) - Charindex('ProfileApplication',P.propertyvaluesstring)))
          + 1, Len(Substring(P.propertyvaluesstring,
                            Charindex('ProfileApplication',
                            P.propertyvaluesstring),
                            Charindex('</ProfileApplication',
                            P.propertyvaluesstring) -
                            Charindex('ProfileApplication',
                            P.propertyvaluesstring))))  AS
          ProfileApplication,

Again, i would like to use ProfileApplication into other query using computed column.  I am not sure but would it be possible?
SUBSTRING
        (SUBSTRING
                (P.ProfileApplication,
                    CHARINDEX('RequisitionStartDate', P.ProfileApplication),
                    CHARINDEX('</RequisitionStartDate',P.ProfileApplication) -
                    CHARINDEX('RequisitionStartDate',P.ProfileApplication)
                    ),
                    CHARINDEX('>', SUBSTRING(P.ProfileApplication,
                    CHARINDEX('RequisitionStartDate', P.ProfileApplication),
                    CHARINDEX('</RequisitionStartDate',P.ProfileApplication) -
                    CHARINDEX('RequisitionStartDate', P.ProfileApplication))) + 1,
                    LEN(SUBSTRING(P.ProfileApplication,
                    CHARINDEX('RequisitionStartDate',P.ProfileApplication),
                    CHARINDEX('</RequisitionStartDate',P.ProfileApplication) -
                    CHARINDEX('RequisitionStartDate',P.ProfileApplication))))

A: Assuming propertyvaluesstring column exists on the same table as the calculated column.
this is what you need to do:
ALTER TABLE <your table name here>
ADD ProfileApplication AS SUBSTRING(SUBSTRING(propertyvaluesstring, CHARINDEX('ProfileApplication', propertyvaluesstring), CHARINDEX('</ProfileApplication', propertyvaluesstring)-CHARINDEX('ProfileApplication', propertyvaluesstring)), CHARINDEX('>', SUBSTRING(propertyvaluesstring, CHARINDEX('ProfileApplication', propertyvaluesstring), CHARINDEX('</ProfileApplication', propertyvaluesstring)-CHARINDEX('ProfileApplication', propertyvaluesstring)))+1, LEN(SUBSTRING(propertyvaluesstring, CHARINDEX('ProfileApplication', propertyvaluesstring), CHARINDEX('</ProfileApplication', propertyvaluesstring)-CHARINDEX('ProfileApplication', propertyvaluesstring))))

Note that calculated columns sometime adversely affect performance so I would be cautious when adding them.


text:
Q: Haskell: Iterating through material in a (complex, recursive) ADT _with context_ I have an ADT for, basically, first order logic:
data Function = Function String
data Predicate = Predicate String

data Type_ = TPoint | TSet | TFunction | TPositiveRealNumber | TSequence | TNaturalNumber | TGroup

data VariableType = VTNormal | VTDiamond | VTBullet

data Dependencies = Dependencies [Term] {-dep-} [Term] {-indep-}

data Variable = Variable String Int Type_ VariableType Dependencies

data Term = VariableTerm Variable
          | ApplyFn Function [Term]

data Formula = AtomicFormula Predicate [Term]
             | Not Formula
             | And [Formula]
             | Or [Formula]
             | Forall [Variable] Formula
             | UniversalImplies [Variable] [Formula] Formula
             | Exists [Variable] Formula

And I need to iterate through each Term (potentially deeply) nested inside a given Formula and do something to it -- said thing will depend on both the term and the 'context' in which it appears. So as a simple example we could print out the formula repeatedly, with each copy having a different term bolded.  I don't want this particular behavior wired in; I want a higher-order function with the following type signature
f :: (FormulaWithTermShapedHole -> Term -> a) -> Formula -> [a]

I  already have a function with this type signature which can do something to every term...
mapTermInFormulaM :: Monad m => (Term -> m Term) -> Formula -> m Formula

... but it can't utilise context in the way I now need. (So it could print every term that occurs somewhere inside the formula, but it couldn't print the whole formula with the term bolded.)
It feels like there should be a slick way of doing this... any suggestions would be welcome.

A: This can be done with generic programming in Haskell.
A good starting point for this is:
http://www.haskell.org/haskellwiki/Scrap_your_boilerplate
And there are some excellent papers by Simon Peyton Jones who started this, if you want to read further:
http://research.microsoft.com/en-us/um/people/simonpj/papers/hmap/


text:
Q: Можно ли вернуть результат startActivityForResult в другое активити? Всем привет!
Есть Activity1 со списком записей, из которой я нажимаю кнопку добавления записи и запускаю startActivityForResult для AddActivity. При успешном добавлении, возвращаю результат в Activity1. В Activity2 также есть кнопка для добавления. При нажатии кнопки я открываю AddActivity уже из Activity2, но после добавления записи мне нужно перейти к их списку и обновить его в Activity1. Подскажите, возможно ли стартовать из одной активити, а результат вернуть в другую?
UPD:
Без finish() не работало:
class ActivityThree extends AppCompatActivity {

    static final String EXTRA_MESSAGE  = "message";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

        setResult(RESULT_OK, new Intent().putExtra(EXTRA_MESSAGE, "Some message"));
        finish();
    }
}

A: Можно. Условно вы запускаете Activity 1 из нее Activity 2, а из Activity 2 - Activity 3.
Собственно если вы хотите из Activity 3 прокинуть result в Activity 1 вам просто нужно в Activity 2 в методе onActivityResult() получить результат, вытянуть из Intent-a данные и положить их в Activity 2 в метод setResult()
P.S. Небольшой пример:
ActivityOne:
class ActivityOne extends AppCompatActivity {

    private static final int REQUEST_CODE = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            // do something
            String message = data.getStringExtra(ActivityThree.EXTRA_MESSAGE);
        }
    }

    void startActivityTwo() {
        startActivityForResult(new Intent(this, ActivityTwo.class), REQUEST_CODE);
    }
}

ActivityTwo:
class ActivityTwo extends AppCompatActivity {

    private static final int REQUEST_CODE = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK){
            setResult(RESULT_OK, data);
        }
    }

    void startActivityThree() {
        startActivityForResult(new Intent(this, ActivityThree.class), REQUEST_CODE);
    }
}

ActivityThree:
class ActivityThree extends AppCompatActivity {

    static final String EXTRA_MESSAGE  = "message";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

        setResult(RESULT_OK, new Intent().putExtra(EXTRA_MESSAGE, "Some message"));
    }
}


text:
Q: Trying to Create Chrome Extension to present entire screen in one button | Google Meet I'm trying to make a chrome extension that allows, with one button click to present the entire screen (instead of clicking present now, entire screen, select screen, etc) in Google Meet.
I found an issue where the "Your Entire Screen" button under "Present Now" isn't of type button in the HTML.
Code Snippet of the "Your Entire Screen" button:

<svg width="24" height="24" viewBox="0 0 24 24" focusable="false" class="Hdh4hc cIGbvc NMm5M"><path d="M20 18c1.1 0 1.99-.9 1.99-2L22 6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2M4 6h16v10H4V6zm.67 13H1v2h22v-2h-3.67"></path></svg>

Your entire screen

How can I firstly get Javascript to be able to find this element (which I cannot currently get it to do) and secondly be able to click on this 'button'?


text:
Q: Scan for a range of free Ports Working on an application that uses cameras.
The camera controller has a single IP address (I can define that IP) on the network and each camera is accessed using that IP plus a Port. The controller can have up to 250 cameras.
Currently there are three cameras and I want to be able to assign Ports in lumps, as in... 6510, (Reception) 6520, (Dock) 6530 (Parking Lot) such that I can add extra cameras and assign Ports appropriate to the camera's physical location, as in...
6510 and 6511 will be physically close to each other, as would 6520, 6521 and 6522 be close.
How can I find a range of available Ports? I have searched the Internet and found a few sites that outline commonly used Port numbers, but I would like to find a free-range for the individual PC the software is installed on.
How can I scan for unused Ports?

A: Unless you register your port numbers with IANA, other programs may try to bind to the same port (it may already be in use by another application). Even if you registered your port numbers, other programs that don't heed the standards may still try to bind to the same port.
Since you require a large number of ports and a non-specific number of ports, you probably will not have any luck registering the ports with IANA.
Therefore, you should use ports >= 49151. The standard practice is to attempt to bind to a port, and if it's in use, the bind will fail. You catch the exception and try the next port.
There is nothing that lists free ports, but you can get in-use ports. Ports range from 1 to 65535, so you can figure out the list of free ports with the list of in-use ports. I find that quite often, the list of in-use ports will show false positives. Eg. ports may show as in use that aren't actually in use any more, but eventually they clear up over time.
So, if you need blocks of free ports, you can derive that list from the in-use ports.
Your server may wish to host the list of ports that it's using via a web server on the known port 80. Client/server communication relies on having at least one known port that the client can use to connect to the server.


text:
Q: Forcing a tab stop on a hidden element? Possible? The site is here
I have opt to using the radiobutton's labels as customized buttons for them. This means the radio inputs themselves are display:none. Because of this, the browsers don't tab stop at the radio labels, but I want them to.
I tried forcing a tabindex to them, but no cigar.
I have came up with just putting a pointless checkbox right before the labels, and set it to width: 1px; and height 1px; which seems to only really work on chrome & safari.
So do you have any other ideas for forcing a tab stop at those locations without showing an element?
Edit:
Just incase someone else comes by this, this is how I was able to insert small checkboxes into chrome & safari using JQuery:
if ($.browser.safari) {
    $("label[for='Unlimited']").parent().after('<input style="height:1px; width:1px;" type="checkbox">');
    $("label[for='cash']").parent().after('<input style="height:1px; width:1px;" type="checkbox">');
    $("label[for='Length12']").parent().after('<input style="height:1px; width:1px;" type="checkbox">');
}

Note: $.browser.webkit was not becoming true...so I had to use safari

A: Keep the radio input hidden, but set tabindex="0" on the  element of reach radio input.
(A tab index of 0 keeps the element in tab flow with other elements with an unspecified tab index which are still tabbable.)

A: If you separate the label from any field and set a tabIndex you can tab to it and capture mouse and key events. It seems more sensible to use buttons or inputs with type="button",
but suit yourself.
<form>
    <fieldset>
        <input value="today">
        Label 1
    </fieldset>
</form>

A: a working solution in my case to enable tab selection / arrow navigation was to set the opacity to zero rather than a "display: none"
.styled-selection input {
    opacity: 0;         // hide it visually
    z-index: -1;        // avoid unintended clicks
    position: absolute; // don't affect other elements positioning
}

A: I have an alternative answer that I think has not been mentioned yet. For recent work I've been reading the Mozilla Developer Docs MDN Docs, Forms, especially the Accessibility Section MDN Docs, Accessible HTML(5), for information related to keyboard accessibility and form structure.
One of the specific mentions in the Accessibility section is to use HTML5 elements when and where possible -- they often have cross-browser and more accessible support by default (not always true, but clear content structure and proper elements also help screen reading along with keyboard accessibility).
Anyway, here's a JSFiddle: JSFiddle::Keyboard Accessible Forms
Essentially, what I did was:

*

*shamelessly copy over some of the source code from a Mozilla source code to a JSFiddle (source in the comments of the fiddle)

*create a TEXT-type  and assign it the "readonly" HTML5 attribute

*add attribute tabindex="0" to the readonly

*Modify the "readonly" CSS for that input element so it looks "blank" or hidden"

HTML
<title>Native keyboard accessibility</title>

Native keyboard accessibility

Links

This is a link to Mozilla.

Another link, to the Mozilla Developer Network.

Buttons

    <button data-message="This is from the first button">Click me!</button>
    <button data-message="This is from the second button">Click me too!
    </button>
    <button data-message="This is from the third button">And me!</button>

  Hidden Anchor Point
  <input type="text" class="hidden-anchor" id="hidden-anchor" tabindex="0" readonly />

Form

  <form name="personal-info">
    <fieldset>
      <legend>Personal Info</legend>

        Fill in your name:
        <input type="text" id="name" name="name">

        Enter your age:
        <input type="text" id="age" name="age">

        Choose your mood:
        <select id="mood" name="mood">
          <option>Happy</option>
          <option>Sad</option>
          <option>Angry</option>
          <option>Worried</option>
        </select>

    </fieldset>
  </form>

CSS Styling
input {
  margin-bottom: 10px;
}

button {
  margin-right: 10px;
}

a:hover, input:hover, button:hover, select:hover,
a:focus, input:focus, button:focus, select:focus {
  font-weight: bold;
}

.hidden-anchor {
  border: none;
  background: transparent!important;
}
.hidden-anchor:focus {
  border: 1px solid #f6b73c;
}

BTW, you can edit the CSS rule for .hidden-anchor:focus to remove the highlight for the hidden anchor if you want. I added it just to "prove" the concept here, but it still works invisibly as requested.
I hope this helps!

A: My preference:
.tab-only:not(:focus) {
  position: fixed;
  left: -999999px;
}

<button class="tab-only">Jump to main</button>

A: Another great option would be to nest your input + div in a label and hide the input by setting width and height to 0px instead of display: none
This method even allows you to use pseudo-classes like :focus or :checked by using input:pseudo + styleDiv

    <input type="radio">

Display text

input
{
    width: 0px;
    height: 0px;
}

input + .styleDiv
{
    //Radiobutton style here
    display: inline-block
}

input:checked + .styleDiv
{
   //Checked style here
}

A: Discard the radio-buttons and instead; keep some hidden fields in your code, in which you store the selected value of your UI components.


text:
Q: Insert Image path to a database using servlet I want to insert an image to the database using servlet. i have created images folder inside web pages and i want sent the to that folder. here is my code.
CompanyReg.jsp
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Colorlib Templates">
<meta name="author" content="Colorlib">
<meta name="keywords" content="Colorlib Templates">
<title>New Member?</title>
<link href="resources/CompanyReg/vendor/mdi-font/css/material-design-iconic-font.min.css" rel="stylesheet" media="all">
<link href="resources/CompanyReg/vendor/font-awesome-4.7/css/font-awesome.min.css" rel="stylesheet" media="all">
<link href="https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<link href="resources/CompanyReg/vendor/select2/select2.min.css" rel="stylesheet" media="all">
<link href="resources/CompanyReg/vendor/datepicker/daterangepicker.css" rel="stylesheet" media="all">
<link href="resources/CompanyReg/css/main.css" rel="stylesheet" media="all">
<link rel="shortcut icon" href="resources/CompanyReg/favicon.ico">
<link rel="stylesheet" type="text/css" href="resources/CompanyReg/css/normalize.css" />
<link rel="stylesheet" type="text/css" href="resources/CompanyReg/css/demo.css" />
<link rel="stylesheet" type="text/css" href="resources/CompanyReg/css/component.css" />

Registration Form

                <form method="POST" action="CompanyReg" enctype='multipart/form-data'>

                                Company Name
                                <input class="input--style-4" type="text" name="company_name">

                                Established Date

                                    <input class="input--style-4 js-datepicker" type="text" name="est_year">

                                Address
                                <input class="input--style-4" type="text" name="address">

                                Email
                                <input class="input--style-4" type="text" name="email">

                                Phone Number
                                <input class="input--style-4" type="text" name="phone">

                                Password
                                <input class="input--style-4" type="Password" name="password">

                                Repeat Password
                                <input class="input--style-4" type="Password" name="repeatPassword">

                                Upload Company Photo

                                    <input type="file" name="photo" id="file-1" class="inputfile inputfile-1" data-multiple-caption="{count} files selected" multiple style="display: none;" />
                                    <svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17"><path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/></svg> Choose a file…

                        <button class="btn btn--radius-2 btn--blue" type="submit">Submit</button>

                </form>

this is my servlet code
 package Company;

 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.PrintWriter;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import javax.servlet.ServletException;
 import javax.servlet.annotation.MultipartConfig;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.Part;
 @MultipartConfig(maxFileSize = 16177215)
 public class CompanyReg extends HttpServlet {

private static final String SAVE_DIR ="images";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("");
        out.println("");
        out.println("<title>Servlet CompanyReg</title>");
        out.println("");
        out.println("");
        out.println("
Servlet CompanyReg at " + request.getContextPath() + "
");
        out.println("");
        out.println("");
    }
}

// <editor-fold
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String savePath = "F:\\JAVA EE Final\\Java Final\\web" + File.separator +SAVE_DIR;
    File fileSaveDir = new File(savePath);

    String company_name = request.getParameter("company_name");
    String company_email = request.getParameter("email");
    String est_date = request.getParameter("est_year");
    String company_address = request.getParameter("address");
    String company_pasword = request.getParameter("password");
    String company_contactno = request.getParameter("phone");
    Part part = request.getPart("photo");
    String filename = extractFileName(part);
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/javanew","root","");
        PreparedStatement pst = con.prepareStatement(" insert into company (Name,Email,Est_date,Address,Password,ContactNo,Photo) values(?,?,?,?,?,?,?)");
                    pst.setString(1, company_name);
                    pst.setString(2, company_email);
                    pst.setString(3, est_date);
                    pst.setString(4, company_address);
                    pst.setString(5, company_pasword);
                    pst.setString(6, company_contactno);
                    String filePath = savePath + File.separator + filename;
                    pst.setString(7, filePath);
        int rs=pst.executeUpdate();
        if(rs>0)
        {
            getServletContext().getRequestDispatcher("").forward(request, response);
        }
    }
    catch (Exception e)
    {
        PrintWriter out = response.getWriter();
        out.print(e);
    }
}
@Override
public String getServletInfo() {
    return "Short description";
}
private String extractFileName(Part part) {

    String contenDisp = part.getHeader("content-disposition");
    String [] items = contenDisp.split(";");
    for (String s : items)
    {
        if (s.trim().startsWith("filename"))
        {
            return s.substring(s.indexOf("=") + 2, s.length()-1);
        }
    }
    return "";
}

}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
    <servlet-name>CompanyReg</servlet-name>
    <servlet-class>Company.CompanyReg</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>CompanyReg</servlet-name>
    <url-pattern>/CompanyReg</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>

</web-app>

my database shows the path correctly but the image not be seen in that folder. so plese tell me what to do

A: yes thats because the image is not in that folder. so when submitting your form you need to copy the image to the folder you created. here is a sample code to copy the image to your folder
    public void copyFile(String fileName,String fileType, InputStream in) {

       try {

       //relativeWebPath is the path to the folder you created in your web directory
            File file = getUniqueFilename(new File(relativeWebPath+"/"+fileName));

          try ( // write the inputStream to a FileOutputStream
                  OutputStream out = new FileOutputStream(new File(relativeWebPath + "/"+file.getName()))) {
              int read = 0;
              byte[] bytes = new byte[1024];

              while ((read = in.read(bytes)) != -1) {
                  out.write(bytes, 0, read);
              }

              in.close();
              out.flush();

          }

    } catch (IOException e) {
        System.out.println(e);
    }
}

//returns a file with a unique name in case an image with the same name
//already exist in the folder

private static File getUniqueFilename( File file )
    {
        String baseName = FilenameUtils.getBaseName( file.getName() );
        String extension = FilenameUtils.getExtension( file.getName() );
        int counter = 1;
        while(file.exists())
        {
            file = new File( file.getParent(), baseName + "-" + (counter++) + "." + extension );
        }
        return file;
    }

A: Part filePart = request.getPart("photo");
//Retrieves <input type="file" name="file">

fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.

uploadedInputStream = filePart.getInputStream();

Try this code


text:
Q: How to initialize Angular service, custom class from component? I use a Angular Elements
My application has bootstrapped component as MapComponent.
Also there is a core class MapCore that contains all domain logic:
class MapCore {
   constructor(props: Props) {
       // Config here
   }
}

This core class should be shared across whole Angular application. So I can make it injectable and register in root.
I need to configure this class manually from component like, therefore I use it like:
@Component({
  selector: 'map-root',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss']
})
export class MapComponent {
    @Input() props: Props;
    @Input() center: Center;
    ngOnInit() {
         this.map = new MapCore(this.props);
    }
}

I need that because when I get result a custom element I can pass parameters to tag for configuration a map:
<map-root center="56,90" props="props">

My question is, how to configurate service in my case it is new MapCore custom class from component and share across application?
Could you share your expirience how to solve this issue?

A: I think you can do that easily using @Injectable. To do this you can update you class named MapCore  like below
import { Injectable } from '@angular/core';

 @Injectable({
      providedIn: 'root'
    })
    class MapCore {
       constructor(props: Props) {
           // Config here
       }
    }

It will available your class across whole Angular application and you can using it like below from any component=>
export class YourComponent {
  constructor(private mapCore : MapCore ){}
}


text:
Q: ListView correctly display only 10 items I am developing a time-tracking app, in my list listview I have 10 timers, with Start/Pause buttons, if I add 11'th timer, he will (only visually) took the counting of the 1 timer and vice versa, if I starts 11'th timer the first timer will go too.
Then if I add 12'th, 2'nd will go and vice versa, add 13'th e.t.c
Problem just in displaying data, programmatically it works well.
I am using viewPager with fragments. Here is fragment of code of my adapter:
@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
    View row = convertView;
    final Tracker tracker = trackerList.get(position);
    final Thread thread = tracker.getThread();
    ViewHolder holder;
    long days,hours,minutes,seconds;
    long eDays,eHours,eMins,eSecs;

    if(row == null){
        row = inflater.inflate(R.layout.list_item,parent,false);
        holder = new ViewHolder(row);
        row.setTag(holder);
    }else {
        holder = (ViewHolder) row.getTag();
    }

    //изнальначальный вид
    final ViewHolder finalHolder = holder;
    finalHolder.start.setVisibility(View.VISIBLE);
    finalHolder.stop.setVisibility(View.GONE);
    finalHolder.name.setText(tracker.getName());

    if(tracker.getElapsedTime()!=0 && tracker.getLimitTime()==0){//если прошедшее время !=0 и таймер без лимита
        days = tracker.getElapsedTime()/86400000;
        hours = (tracker.getElapsedTime()/3600000)%24;
        minutes = (tracker.getElapsedTime()/60000)%60;
        seconds = (tracker.getElapsedTime()/1000)%60;
        if(days!=0)
            finalHolder.days.setText(Util.concat(days <= 9 ? 0 : "", days));
        if(hours!=0)
            finalHolder.hours.setText(Util.concat(hours <=9 ?0:"",hours));
        if(minutes!=0)
            finalHolder.minutes.setText(Util.concat(minutes<=9?0:"",minutes));
        if(seconds!=0)
            finalHolder.seconds.setText(Util.concat(seconds<=9?0:"",seconds));
    }else{
        if(tracker.getIsFinished()){//если таск закончен, дошел до лимита
            hours = (tracker.getLimitTime()/3600000)%24;
            minutes = (tracker.getLimitTime()/60000)%60;
            seconds = (tracker.getLimitTime()/1000)%60;
            finalHolder.start.setVisibility(View.GONE);
            finalHolder.textFinish.setVisibility(View.VISIBLE);
            finalHolder.stop.setVisibility(View.GONE);
            if(seconds!=60)
                finalHolder.seconds.setText(Util.concat(seconds<=9?0:"",seconds));
            if(minutes!=60)
                finalHolder.minutes.setText(Util.concat(minutes<=9?0:"",minutes));
            if(hours!=24)
                finalHolder.hours.setText(Util.concat(hours <= 9 ? 0 : "", hours));

        }else{
            if(tracker.getLimitTime()!=0 && !tracker.getIsFinished()){//если установлен лимит, но еще не дошел до конца
                days = tracker.getLimitTime()/86400000;
                hours = (tracker.getLimitTime()/3600000)%24;
                minutes = (tracker.getLimitTime()/60000)%60;
                finalHolder.textLimit.setVisibility(View.VISIBLE);
                finalHolder.limHours.setVisibility(View.VISIBLE);
                finalHolder.limDay.setVisibility(View.VISIBLE);
                finalHolder.limMin.setVisibility(View.VISIBLE);
                finalHolder.limDay.setText(Util.concat(days <= 9 ? 0 : "", days, ":"));
                finalHolder.limHours.setText(Util.concat(hours <= 9 ? 0 : "", hours, ":"));
                finalHolder.limMin.setText(Util.concat(minutes<=9?0:"",minutes));

                eDays = (tracker.getElapsedTime() / 86400000);
                eHours = (tracker.getElapsedTime()/3600000)%24;
                eMins = (tracker.getElapsedTime()/60000)%60;
                eSecs = (tracker.getElapsedTime()/1000)%60;

                if(eSecs!=0)
                    finalHolder.seconds.setText(Util.concat(eSecs<=9?0:"",eSecs));
                if(eMins!=0)
                    finalHolder.minutes.setText(Util.concat(minutes<=9?0:"",eMins));
                if(eHours!=0)
                    finalHolder.hours.setText(Util.concat(hours<= 9 ? 0 : "", eHours));
                if(eSecs!=0)
                    finalHolder.days.setText(Util.concat(days<= 9 ? 0 : "", eDays));

            }else {
                finalHolder.textLimit.setVisibility(View.GONE);
                finalHolder.limHours.setVisibility(View.GONE);
                finalHolder.limDay.setVisibility(View.GONE);
                finalHolder.limMin.setVisibility(View.GONE);
            }
        }
    }
    if(tracker.getIsStart() && !tracker.getIsFinished()) {//если был стартован
        finalHolder.start.setVisibility(View.GONE);
        finalHolder.stop.setVisibility(View.VISIBLE);
    }
    tracker.setHolder(finalHolder);
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btStart:
                    tracker.setStartTime(System.currentTimeMillis());
                    tracker.setIsStart(true);
                    tracker.setHolder(finalHolder);
                    finalHolder.start.setVisibility(View.GONE);
                    finalHolder.stop.setVisibility(View.VISIBLE);
                    if(tracker.getUpdateTime()==0)
                        thread.start();
                    else
                        tracker.getThread().start();

                    break;
                case R.id.btStop:
                    tracker.setLastPause(tracker.getUpdateTime());
                    finalHolder.stop.setVisibility(View.GONE);
                    finalHolder.start.setVisibility(View.VISIBLE);
                    tracker.setIsStart(false);
                    break;

            }
        }
    };
    finalHolder.start.setOnClickListener(onClickListener);
    finalHolder.stop.setOnClickListener(onClickListener);
    return row;
}

@Override
public int getViewTypeCount() {
  /*  Log.d("myTag","getViewTypeCount() = "+getCount());
   if(getCount()==0)
      return super.getViewTypeCount();
    else
      return getCount();*/
    return 1;
}

@Override
public int getItemViewType(int position) {
    return position;
}

static class ViewHolder{
  @InjectView(R.id.tvName) TextView name;
  @InjectView(R.id.tvDays) TextView  days;
  @InjectView(R.id.tvHours) TextView  hours;
  @InjectView(R.id.tvMinutes) TextView minutes;
  @InjectView(R.id.tvSeconds) TextView  seconds;
  @InjectView(R.id.btStart) ButtonFloatSmall start;
  @InjectView(R.id.btStop) ButtonFloatSmall stop;
  @InjectView(R.id.txtFinish) TextView  textFinish;
  @InjectView(R.id.txtLimit) TextView textLimit;
  @InjectView(R.id.limDay) TextView limDay;
  @InjectView(R.id.limHours) TextView limHours;
  @InjectView(R.id.limMin) TextView limMin;

    public ViewHolder(View view){
        ButterKnife.inject(this,view);
    }
}

Here is listview
<ListView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/trackListview"
    android:scrollingCache="false"
    android:drawSelectorOnTop="true"
    android:persistentDrawingCache="none"
    android:divider="@android:color/transparent"
    android:dividerHeight="5.0sp"
    />

This is my log of getView(), first start app.
http://iscr.ru/photo/1433874284_getView.PNG


text:
Q: How to sort a vector in non-descending order without touching -1 values in R? The question:
"Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. People can be very tall!"
Example
For
 a = [-1, 150, 190, 170, -1, -1, 160, 180],

the output should be
 solution(a) = [-1, 150, 160, 170, -1, -1,   180, 190].

We basically need to scan through this list and see where there a downstep (unless it is to a -1) and then find a way to re-order non -1 elements so that the list is non-ascending. I basically don't know where to even begin on this question. Would anyone give this a go in base R and talk me through your thinking?

A: a = c(-1, 150, 190, 170, -1, -1, 160, 180)
a[a>0] = sort(a[a>0])
a

[1]  -1 150 160 170  -1  -1 180 190

Explanation:

*

*a>0 is boolean mask to get the non-trees values:

FALSE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE
If you apply it to a you get :
#a[a>0]
150 160 170 180 190

An thus you can order the values with  sort(a[a>0]) and set back to the orignal vector using the same aproach with the boolean mask.
a[a>0] = sort(a[a>0])


text:
Q: Word meaning you accept someones beliefs without believing in them yourself? What is a word for when you accept someone else's beliefs, but do not believe in them yourself?

A: If it suits your context consider
unbigoted
and
broad-minded
These words are more specific to beliefs than one suggestion - tolerant.

A: Tolerant
willing to accept feelings, habits, or beliefs that are different from your own

a culture tolerant of religious differences

If I say I am tolerant of someone's beliefs it means I accept his/her faith without prejudice. However, this does not mean I will share his/her religious convictions or views; I may even want to distance myself from them.
The antonym of tolerant is intolerant
Wikipedia has a passage which illustrates how closely related the two words are.
They are, ironically, often used in unison.

Walzer, Karl Popper and John Rawls have discussed the paradox of
  tolerating intolerance. Walzer asks "Should we tolerate the
  intolerant?" He notes that most minority religious groups who are the
  beneficiaries of tolerance are themselves intolerant, at least in some
  respects. Rawls argues that an intolerant sect should be tolerated in
  a tolerant society unless the sect directly threatens the security of
  other members of the society. He links this principle to the stability
  of a tolerant society, in which members of an intolerant sect in a
  tolerant society will, over time, acquire the tolerance of the wider
  society.

A: The Orwellian coinage doublethink is applicable.
OED definition:

the acceptance of contrary opinions or beliefs at the same time.

A: Hypocrite.  The urban dictionary actually has "hippocrite," meaning "A squishy hippo that happends to be hypocritical of others. Derived from the word hypocrite, but accomodated to specificy hippos."  (http://www.urbandictionary.com/define.php?term=hippocrite).  My laugh for the day.  Cheers all.


text: Q: mdbreact datatable pagination issue Im using mdbreact package to display the data in a datatable. In the datatable I have a column with checkbox to change the value. When I check or Uncheck and move to the second page, the values of the checkbox in the second page is also changing. How do I sort this issue?


text:
Q: Getting contents of a URL and comparing locally I'm looking to get a URL (it returns just one line, no html, just plaintext) every 3000sec. I want to compare it against "previous.txt" and call a function if it's different, then write it to previous.txt.
If it's same, do nothing.
Can someone point me in a place to starting ?I'm not python much before.
Thanks.

A: Here are some hints.
Looking at your question tags you already know that urllib will help. Try urllib2.urlopen() to retrieve the data from the URL.
Comparing previous and current contents is as simple as reading in the contents of previous.txt and doing a string comparison with whatever you have just retrieved from the URL. If the two strings are different, write the newer one to the file. Look at open() and read/write for your file IO needs.
If your Python process is long running, performing the task every 3000 seconds can be done using time.sleep() or signal.alarm() (or several other ways).


text:
Q: How to share image of app I have picture in drawable and I want to share that one image.
Following is my code,
 btnic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.defaultpicture);
            Intent ppp = new Intent("android.intent.action.SEND");
            ppp.setType("image/png");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            b.compress(Bitmap.CompressFormat.PNG, 100, bytes);
            String path = MediaStore.Images.Media.insertImage(getContentResolver(),
                    b, "defaultpicture", null);
            Uri uri =  Uri.parse(path);
            ppp.putExtras(Intent.EXTRA_STREAM, uri); **i am getting error here**
            MainActivity.this.startActivity(Intent.createChooser(ppp, "Send picture"));
            Toast.makeText(getApplicationContext(), "Picture Copied", Toast.LENGTH_SHORT).show();
        }
    });

where am i doing wrong?

A: Intent.EXTRA_STREAM takes value as Local path of file on storage not on resource (Not a resource ID).
 So you need to first save the image as file in storage then pass the url to sharing Intent .
First decode resource.
Bitmap b = BitmapFactory.decodeResource(res, id);

Save it to specific location on storage and use this file path as value in intent. you can save it as below or in some other way.
String path = MediaStore.Images.Media.insertImage(getContentResolver(),
        b, "myFile", null);

A:                 final Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType("image/jpg");
                final File photoFile = new File(getFilesDir(), "yourimage.jpg");
                Log.d("TAG", "onClick: "+photoFile);
                shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
                startActivity(Intent.createChooser(shareIntent, "Share image using"));

for more about Sharing Content with Intents


text:
Q: How to know if a folder is a symbolic link? I am looking for a way, if it exists, to know if a the path to a folder is a symbolic link or the original path to the folder.
Is there such a thing ?

A: Alternative approach:
1, using file
file /usr/lib/jvm/jre-9
/usr/lib/jvm/jre-9: symbolic link to /etc/alternatives/jre_9

2, using readlink
readlink -f /usr/lib/jvm/jre-9
/usr/lib/jvm/java-9-openjdk-9.0.4.11-6.fc28.x86_64

Here you can see that path is expanded to link target

A: If you want to check programmatically whether a given object is a plain directory
or a symbolic link to a directory you may use the test command. Note that it
returns is directory for both directories and symlinks to directories but only
returns is symlink for symbolic links. Hence:
#!/usr/bin/env bash

mkdir i_am_a_directory
ln -s i_am_a_directory i_am_a_symlink_to_a_directory

for object in i_am_a_directory i_am_a_symlink_to_a_directory; do
    if test -d $object; then
        if test -L $object; then
            echo "$object is a symlink to a directory"
        else
            echo "$object is just a plain directory"
        fi
    else
        echo "$object is not a directory (nor a link to one)"
    fi
done

Result:
i_am_a_directory is just a plain directory
i_am_a_symlink_to_a_directory is a symlink to a directory

A: There are many ways, my usual way is using stat
guiverc@ultracrap:~$   stat vids
  File: vids -> Videos/
  Size: 7               Blocks: 0          IO Block: 4096   symbolic link
Device: fd00h/64768d    Inode: 524725      Links: 1
Access: (0777/lrwxrwxrwx)  Uid: ( 1000/ guiverc)   Gid: ( 1001/ guiverc)
Access: 2019-05-25 00:16:26.708558789 +1000
Modify: 2019-05-25 00:16:26.708558789 +1000
Change: 2019-05-25 00:16:26.708558789 +1000
 Birth: -

You'll note my ~/vids is a symbolic link to my ~/Videos/ directory

A: namei will break down every component in a path, whether the path leads to a directory or not.
For example my ~/Playlists is a symlink to Documents/Playlists, and Documents itself is a symlink to Dropbox/Documents:
$ namei Playlists
f: Playlists
 l Playlists -> Documents/Playlists
   l Documents -> Dropbox/Documents
     d Dropbox
     d Documents
   d Playlists

In this output,

*

*f: means the pathname currently being resolved

*l means symbolic link

*d means directory (folder)

*Each level of indentation represents a level of symlinks

A: To determine whether the folder is a symbolic link you can use either of these methods.

*

*GUI Method:
The folder icon will be different. The icon of the folder would have an arrow.

*CLI Method
The output of ls -l will clearly indicate that the folder is a symbolic link and it will also list the folder where it points to.
$ ls -l
total 4
drwxr-xr-x 2 t domain users 4096 mai  24 15:56 original
lrwxrwxrwx 1 t domain users    8 mai  24 15:56 symbolic -> original

Here symbolic is a symbolic link pointing to original folder.
The starting l in lrwxrwxrwx represents a symbolic link, while d represents folder (directory), and - represents file.

A: Go to the parent directory of the suspected symlink and do
ls -la
The -a is in case your file is a . hidden file.
Then it should start with l if its a link:
(automl-meta-learning) miranda9~/automl-meta-learning/automl-proj/experiments $ ls -la ~
total 136
drwx------. 18 miranda9 miranda9  4096 May  2 15:55 .
drwxr-xr-x. 23 root     root         0 May  2 15:45 ..
drwxrwxr-x.  8 miranda9 miranda9  4096 May  2 12:17 automl-meta-learning
-rw-------.  1 miranda9 miranda9 49858 May  2 15:10 .bash_history
-rw-r--r--.  1 miranda9 miranda9    18 Aug 22  2019 .bash_logout
-rw-r--r--.  1 miranda9 miranda9   176 Aug 22  2019 .bash_profile
-rw-r--r--.  1 miranda9 miranda9  1132 May  2 12:49 .bashrc
drwxrwxr-x.  6 miranda9 miranda9    70 Jan 30 14:29 .cache
lrwxrwxrwx.  1 miranda9 miranda9    26 May  2 15:55 .conda -> /home/miranda9/miniconda3/

see the last one:
lrwxrwxrwx.  1 miranda9 miranda9    26 May  2 15:55 .conda -> /home/miranda9/miniconda3/

starts with an l and even shows you where it's pointing too.


text:
Q: adding structured property to ndb.model : google app egnine I have two classes in this way:
class comment(ndb.Model):
    date =ndb.StringProperty()
    title=ndb.StringProperty()
    name=ndb.StringProperty()
    content=ndb.StringProperty()

class report(ndb.Model):
    comments=ndb.StructuredProperty(comment,repeated=True)

so i get the comment from the user and then append it to the list comments in report class, this what i do:
class add(webapp2.RequestHandler):
   def post(self):
     key_url=self.request.get("key")
     key=ndb.Key(urlsafe=key_url)
     report=key.get()
     title=self.request.get("title")
     name=self.request.get("name")
     date=self.request.get("date")
     content=self.request.get("content")
     new_comment=comment(date=date,title=title,name=name,content=content)
     report.comments.append(new_comment)
     report.put()

unfortunately this don't work i get this error:
 BadValueError: Expected string, got comment(key=Key('comment', 5659645909663744), content=u'dasdsad', date=u'', name=u'', title=u'')

please help me !
       Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
    rv = self.handle_exception(request, response, e)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
    rv = self.router.dispatch(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
    return handler.dispatch()
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
    return method(*args, **kwargs)
  File "/base/data/home/apps/s~newseltira/1.374670644492631009/upload_comment.py", line 65, in post
    report.put()
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3339, in _put
    return self._put_async(**ctx_options).get_result()
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 325, in get_result
    self.check_success()
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 368, in _help_tasklet_along
    value = gen.throw(exc.__class__, exc, tb)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/context.py", line 748, in put
    key = yield self._put_batcher.add(entity, options)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 371, in _help_tasklet_along
    value = gen.send(val)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/context.py", line 280, in _put_tasklet
    keys = yield self._conn.async_put(options, datastore_entities)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 1791, in async_put
    pbs = [entity_to_pb(entity) for entity in entities]
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 648, in entity_to_pb
    pb = ent._to_pb()
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3052, in _to_pb
    prop._serialize(self, pb, projection=self._projection)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1365, in _serialize
    values = self._get_base_value_unwrapped_as_list(entity)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1135, in _get_base_value_unwrapped_as_list
    wrapped = self._get_base_value(entity)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1123, in _get_base_value
    return self._apply_to_values(entity, self._opt_call_to_base_type)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1295, in _apply_to_values
    value[:] = map(function, value)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1177, in _opt_call_to_base_type
    value = _BaseValue(self._call_to_base_type(value))
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1198, in _call_to_base_type
    return call(value)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1274, in call
    newvalue = method(self, value)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 1695, in _validate
    (value,))
BadValueError: Expected string, got comment(content=u'dasdsad', date=u'', name=u'', title=u'')

A: Ok from your last comment we can now see the problem
 class report(ndb.Model):
    comments=ndb.StructuredProperty(comment,repeated=True)
    date=ndb.StringProperty()
    title=ndb.StringProperty()
    content=ndb.BlobKeyProperty()
    comments=ndb.StringProperty(repeated=True)
    images=ndb.BlobKeyProperty(repeated=True)
    images_urls=ndb.StringProperty(repeated=True)
    status=ndb.BooleanProperty()

Can you see the problem.
You have defined comments twice and the second definition is the only one that will be used. You have redefined the comments as a StringProperty
Do you see how important it is to be accurate in the information you have provided.
The error message you are getting is telling you the exact problem


text:
Q: keras: Change dimension of Image object to feed into an ANN? I'm trying to learn Neural Networks!
I'm trying to compare Convolutional Neural Network and Dense Neural Network on OCR of 100 x 100 pixel character.
I'm modifying David Shapiro's code on OCR to create an ANN to compare to his CNN model. https://github.com/daveshap/ocr_svc
His random character image generator generates 100 x 100 (I modified it from 32x32 to 100x100 to really see the effect of overfitting - if it happens)
def make_random_image(font_file, c, i):
    paper = 255 #white
    ink = random.randint(0, 90)
    font_size = random.randint(min_font, max_font)
    font = ImageFont.truetype(font_dir + font_file, font_size)
    string = c
    canvas = Image.new('RGBA', (base_size, base_size), (paper, paper, paper))
    draw = ImageDraw.Draw(canvas)
    w, h = draw.textsize(text=string, font=font)
    w = round((base_size - w) / 2)
    h = round((base_size - h) / 2)
    draw.text((w, h), string, (ink, ink, ink), font=font)
    ImageDraw.Draw(canvas)
    canvas = Image.fromarray(np.uint8(canvas))
    # save file
    filename = font_file.lower().replace('.ttf', '') + '_%s_%s_%s.png' % (charset.index(c), c, i)
    canvas.save(save_dir + filename)
    canvas = np.asarray(canvas)
    canvas = cv2.cvtColor(canvas, cv2.COLOR_RGB2GRAY)
    return canvas

Then using Keras front-end and Tensorflow backend, I (atleast wanted to ) create an ANN:
def instantiate_model():
    print('COMPILING MODEL')
    model = Sequential()
    model.add(Dense(10000,input_shape=input_shape, activation='relu'))
    model.add(Dense(1000, activation='relu'))
    model.add(Dense(num_classes, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=
    ['accuracy'])
    print(model.summary())
    return model

What should be the input shape and how can I change the 100x100 Image to the appropriate input shape? Also, any suggestion on the shape of this ANN? I'm expecting it to fail compared to CNN from what I read.
I feel like the input shape should be 1 dimension 10,000 but I am not sure.
EDIT=========
David Shapiro prepares his training set by:
def prepare_datasets(samples):
    random.shuffle(samples)
    training_set = samples[:round(len(samples) / 10 * 9)]
    training_data = [i[0] for i in training_set]
    training_data = np.asarray(training_data).astype('float32')
    training_data = np.expand_dims(training_data, axis=3)
    training_data /= 255
    training_labels = [i[1] for i in training_set]
    training_labels = np.asarray(training_labels)
    training_labels = np_utils.to_categorical(training_labels, num_classes)
    print('TRAINING DATA SHAPE', training_data.shape)
    print('TRAINING LABELS SHAPE', training_labels.shape
    return training_data, training_labels

The result of his method is:
TRAINING DATA SHAPE (9360, 100, 100, 1)
TRAINING LABELS SHAPE (9360, 26)
which then is fed to model.fit(training_data, training_labels, batch_size=batch, epochs=epoch, verbose=1)
Maybe changing the dimension could be done from here! I'm still learning how to use numpy so I dont know all the methods...
Thank you for even reading this long post!


text:
Q: how to count total number of words in a file? I am looking for a command to count number of all words in a file. For instance if a file is like this,
today is a
good day

then it should print 5, since there are 5 words there.

A: I came up with this for JUST the number:
wc -w [file] | cut -d' ' -f1

5

I also like the wc -w < [file] approach
Finally, for storing just the word count in a variable, you could use the following:
myVar=($(wc -w /path/to/file))

This lets you skip the filename elegantly.

A: The command wc aka. word count can do it:
$ wc -w <file>

example
$ cat sample.txt
today is a
good day

$ wc -w sample.txt
5 sample.txt

# just the number (thanks to Stephane Chazelas' comment)
$ wc -w < sample.txt
5

A: The better solution is using Perl:
perl -nle '$word += scalar(split(/\s+/, $_)); END{print $word}' filename

@Bernhard
You can check the source code of wc command from coreutils, I test in my machine, with file subst.c in bash 4.2 source.
time wc -w subst.c

real    0m0.025s
user    0m0.016s
sys     0m0.000s

And
time perl -nle '$word += scalar(split(" ", $_)); END{print $word}' subst.c

real    0m0.021s
user    0m0.016s
sys     0m0.004s

The bigger the file is, the more efficient Perl is with respect to wc.

A: Let's use AWK!
$ function wordfrequency() { awk 'BEGIN { FS="[^a-zA-Z]+" } { for (i=1; i<=NF; i++) { word = tolower($i) words[word]++ } } END { for (w in words) printf("%3d %s\n", words[w], w) } ' | sort -rn }
$ cat your_file.txt | wordfrequency

This lists the frequency of each word occurring in the provided file. I know it's not what you asked for, but it's better! If you want to see the occurrences of your word, you can just do this:
$ cat your_file.txt | wordfrequency | grep yourword

I even added this function to my .dotfiles

Source: AWK-ward Ruby

A: The wc program counts "words", but those are not for instance the "words" that many people would see when they examine a file.  The vi program for instance uses a different measure of "words", delimiting them based on their character classes, while wc simply counts things separated by whitespace.  The two measures can be radically different.  Consider this example:
first,second

vi sees three words (first and second as well as the comma separating them), while wc sees one (there is no whitespace on that line).  There are many ways to count words, some are less useful than others.
While Perl would be better suited to writing a counter for the vi-style words, here is a quick example using sed, tr and wc (moderately portable using literal carriage returns ^M):
#!/bin/sh
in_words="[[:alnum:]_]"
in_punct="[][{}\\|:\"';<>,./?\`~!@#$%^&*()+=-]"
sed     -e "s/\($in_words\)\($in_punct\)/\1^M\2/g" \
        -e "s/\($in_punct\)\($in_words\)/\1^M\2/g" \
        -e "s/[[:space:]]/^M/g" \
        "$@" |
tr '\r' '\n' |
sed     -e '/^$/d' |
wc      -l

Comparing counts:

*

*Running the script on itself, gives me 76 words.

*The example in Perl by @cuonglm gives 31.

*Using wc gives 28.

For reference, POSIX vi says:

In the POSIX locale, vi shall recognize five kinds of words:

*

*A maximal sequence of letters, digits, and underscores, delimited at both ends by:

*

*Characters other than letters, digits, or underscores

*The beginning or end of a line

*The beginning or end of the edit buffer

*A maximal sequence of characters other than letters, digits, underscores, or  characters, delimited at both ends by:

*

*A letter, digit, underscore

*<blank> characters

*The beginning or end of a line

*The beginning or end of the edit buffer

*One or more sequential blank lines

*The first character in the edit buffer

*The last non-<newline> in the edit buffer


text:
Q: Databinding and Eventhandles - Passing Parameters I have a Windows WPF application that bind an Observablecollection of Objects of type 'Person' to a listbox. The Person is displayed via a template, and this template generates an 'Expander' for each person (i.e, "see more details about Mr.X"). On expasion I want to do something in the background (so I add an eventhandler 'Expander_Expanded', but also I need the program to remember which expanders were expanded, i.e., I'd like to pass the 'name' of the person into the event. Although I found some similar questions I did not quite understand the answers...
Also, maybe someone knowledgeable of the language architecture can explain why the language not allow the following, most logical solution: Add a property to the person class
public ExpanderName {get{return "Expander_"+this.Name;}}

and then bind the name of the expander to this,
<Expander Name="{Binding ExpanderName}" Expanded="Expander_PersonDetails">

then one could access the name of the person that was expanded in the eventhandler by recovering it from 'sender.name'. The compiler hwever says that the 'name' of an UIcontrol element cannot be bound. Why?
Thanks in advance!

A: The Name is not a bindable property, it needs to be known at compile time so that the compiler can generate the proper object to be accessed in code-behind.
What you can use is the generic Tag property - you can bind anything you want to it, and then you can access it in code. Try this:
<Expander Tag="{Binding ExpanderName}" Expanded="Expander_PersonDetails">

void Expander_PersonDetail(object sender, RoutedEventArgs args)
{
  var expander = (Expander)sender;
  string expanderName = (string)expander.Tag;
}

A better solution would be to bind (two-way) the Expander.IsExpanded property to a field directly in the Person class - this way you will always have the correct state stored in the correct object, and the handling will be much simpler.


text:
Q: Size of the closure of a set Why in a Hausdorff sequentially compact space the size of the closure of a countable subset is less or equal than $c$ ? I can see why this is true when the space if first countable but we are not assuming so.

A: Here is some progress in the positive direction.
Theorem. In any Hausdorff space, the closure of a
countable set has size at most $2^{\mathfrak{c}}$, where $\mathfrak{c}$ is the
continuum.
Proof. Suppose that $X$ is a Hausdorff topological space
with a countable set $D$. For any point $a$ in the closure
$\bar D$, we may consider the collection of open sets
containing $a$, and their trace on $D$. That is, consider
$F_a=\{U\cap D\mid a\in U\text{ open }\}$. Since there are
only continuum many subsets of $D$, there are therefore at
most $2^{\mathfrak{c}}$ many possible such families.
If the closure $\bar D$ had size larger than $2^{\mathfrak{c}}$, then
there would be at least two (in fact many) distinct points
$a$ and $b$ in $\bar D$ for which $F_a=F_b$. Let $U$ and
$V$ be disjoint neighborhoods of $a$ and $b$. Let $U_1$ be
another neighborhood of $a$ such that $U_1\cap D=V\cap D$,
which must exist since $F_a=F_b$. Thus, $U\cap U_1$ is a
neighborhood of $a$ that is disjoint from $D$,
contradicting $a\in\bar D$. QED
The bound is sharp, even for compact Hausdorff spaces, in
the sense that the Stone–Čech
compactification
$\beta\mathbb{N}$ is a Hausdorff topological space of size
$2^c$ with a countable dense set. But $\beta\mathbb{N}$ is
not sequentially compact, so this is not actually a
counterexample to your question.
What the argument actually shows is that if $a$ and $b$ are
in the closure of the countable set $D$, then $F_b$ is not a
subset of $F_a$. If it were, we could find disjoint
neighborhoods $U$ and $V$ of $a$ and $b$, respectively, and
then $V\cap D\in F_b$, and so there is a neighborhood $U_1$
of $a$ with $U_1\cap D=V\cap D$, making $U\cap U_1$ a
neighborhood of $a$ having no points from $D$, a
contradiction. By symmetry, we conclude $F_a$ and $F_b$ are
incomparable with respect to $\subset$ for all $a,b\in\bar
D$.
I suspect that such a line of reasoning could be improved
when there is sequential compactness, perhaps by using a
cardinal characteristic, such as the splitting number.

A: The statement is consistently false.
In vaughn's article "Countably compact and sequentially compact spaces" in the Handbook of Set-Theoretic Topology, he gives the following equivalences for an infinite cardinal $\kappa$:

*

*$\{0,1\}^\kappa$ is sequentially compact

*$\kappa < \mathfrak{s}$ (where $\mathfrak{s}$ is the "splitting number")

*every compact space of weight $\leq\kappa$ is sequentially compact

Thus if we are in a universe where $\omega<\omega_1=\kappa<\mathfrak{s}\leq\mathfrak{c}<2^\kappa$ then the space
$\{0,1\}^{\omega_1}$ gives a separable space which is sequentially compact but has cardinality greater than $\mathfrak{c}$.
Added: including the forcing construction to get such a model (from van Douwen's article):
Start with ground model
$M\models(\mathfrak{c}=\omega_2 \wedge 2^{\omega_1}=\omega_3)$
then obtain an iterated ccc extension $\langle M_\eta : \eta\in\omega_2\rangle$ by adding $X_\eta\in[\omega]^\omega$ at stage $\eta\in\omega_2$ s.t. $\forall Y\in M\cap[\omega]^\omega$ either $X_\eta\subseteq^* Y$ or $X_\eta\subseteq^* (\omega\setminus Y)$.  Then in $M_{\omega_2}$ we have $\mathfrak{c}=\omega_2<2^{\omega_1}$, $\mathfrak{t}=\omega_1$, $\mathfrak{s}=\omega_2$, exactly as desired.  (Details are left as an exercise).

A: It seems like you don't need all the conditions, so maybe I am missing something.  There are only continuum many sequences of points from a countable set.  So the limit points are at most continuum many.


text:
Q: Broken windows - MSO tag wiki references I used to refer MSO tag wikis in the past, like this: https://meta.stackoverflow.com/tags/broken-windows/info and especially like this:

would you mind explaining more on what it does and why do you recommend it as answering the question asked? "Link-only answers" are not quite welcome at Stack Exchange

FWIW, the latter reference is used several hundreds times in comments at Programmers.
After the split, some of these links became dead, what would be the recommended way to handle this?

A: Ok. I just copied most of these over from MSE verbatim.
Not the most elegant solution, but... No more broken links.
Of course, most of the tags will be deleted in 24 hours and I'll have to re-create them after we migrate questions that actually use them. But, the concept is sound.


text:
Q: how to a regex for similar string i have this string
[url=test.php]test[/url]

or
[url=http://test.php]text[/url]

I want to a regex get this
[url=http://test.php]text[/url]

example:
before:
str = "[url=test.php]text[/url]"
str.gsub(/\[url=(.*?)\](.*?)\[\/url\]/,'[url=http://\1]\2[/url]')
=> "[url=http://test.php]text[/url]"

question:
str = "[url=http://test.php]text[/url]"
str.gsub(/\[url=(.*?)\](.*?)\[\/url\]/,'[url=http://\1]\2[/url]')
=> "[url=http://http://test.php]text[/url]"

so..  two "http://"
Any ideas anyone?
thanks

A: Thanks for clarifying your question.
You need a regex that only matches [url] BBCode tags if the linked URL is not starting with http.
\[url=\s*(?!http)([^\]]+)\](.*?)\[/url\]

should work:
str.gsub(/\[url=\s*(?!http)([^\]]+)\](.*?)\[\/url\]/,'[url=http://\1]\2[/url]')

Explanation:
\[url=\s*   # match [url= literally, plus optional space
(?!http)    # assert that it's not possible to match http here
([^\]]+)    # match 1 or more characters except ], capture in \1
\]          # match ]
(.*?)       # match link text, capture in \2
\[/url\]    # match [/url]


text:
Q: Adjacency matrix of a square of a graph.
What is the relation between $A(G)$ and $A(G^2)$?

Where $G^2$ is the square of a graph $G$ and $A(G^2),A(G)$ their respective adjacency matrix.

A: $G^2$ is the graph with the same set of vertices as $G$, but with edges connecting vertices with distance $\leq 2$ in $G$.
$A(G)$ shows which vertices in $G$ have a distance of 1. $A(G^2)$ shows which vertices in $G^2$ have a distance of $1$, or a distance of $\leq 2$ in $G$.
So, $A(G^2) - A(G)$ shows which vertices in $G$ have a distance of exactly 2. This difference would have non-zero, non-diagonal entries in the same places as $[A(G)]^2$ (where $A_{ij}^{2}$ is the number of walks of length $2$ between vertices $i$ and $j$).


text:
Q: Whenever run "npm start" this error is showing. How to solve it? Error:
Failed to compile
./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css)
TypeError: Cannot read property 'prefix_exceptions' of undefined
at Array.map ()
This error occurred during the build time and cannot be dismissed.


text:
Q: Drupal AJAX checkbox When click on checkbox I want to call function checkbox_ajax, I tried but it does not work
function checkbox1($form_state) {
    $form['checkbox'] = array(
                '#type' => 'checkbox',
                '#prefix' => "
",
                '#suffix' => "
",
                '#ajax' => array(
                  'callback' => 'checkbox_ajax',
                'wrapper' => 'checkbox_ajax-wrapper'
                ),
                  );
    return $form;
}

I need to change prefix class
function checkbox_ajax($form, &$form_state) {

  $form['checkbox']['#prefix'] = "
";

  return $form['checkbox'];

}

if someone can help?

A: Try:
function checkbox1($form, &form_state) {

and:
function checkbox_ajax($form, $form_state) {

A: function checkbox1($form_state) {
    $form['checkbox'] = array(
                '#type' => 'checkbox',
                '#prefix' => (isset($form_state['values']['checkbox']) && $form_state['values']['checkbox'] ) ? "
" : "
", //CHANGE HERE
                '#suffix' => "
",
                '#ajax' => array(
                  'callback' => 'checkbox_ajax',
                'wrapper' => 'checkbox_ajax-wrapper'
                ),
                  );
    return $form;
}

if $form['checkbox'] is checked than $form_state['values']['checkbox'] will equal to 1 thus ($form_state['values']['checkbox']) will equal to true.
I think this should work, but didn't test yet.


text:
Q: How do I make the instagram login in my app, connected through auth0? I'm developing a mobile app in Ionic3, that is connected with auth0, to login with instagram, but I cannot find the correct credentials (client id, and client secret) to get that working properly. I need help because old Instagram API is no longer reviewing apps, I really don't know what to do.
I've already tried searching and connecting with all the credentials that New facebook developer dashboard gave me, but no one works. Also I have created the app in Facebook dashboard.

A: You can find both your Client ID and Client Secret within your application's setting tab within your Auth0 Dashboard.
https://auth0.com/docs/api-auth/tutorials/client-credentials
(Affiliation: I'm Community Lead at Auth0.)


text:
Q: Spring security configuration; both Basic Auth and SiteMinder I have a Spring boot web app that serves up both web content and exposes REST Services. The web content is protected by SiteMinder, the REST Services are protected by "Basic Auth".
I using Springs security 4.2.3. My Java code is extending the class WebSecurityConfigurerAdapter, my configure(HttpSecurity) method looks like:
@Override
protected void configure(HttpSecurity http) throws Exception {

    RequestHeaderAuthenticationFilter siteMinderFilter = new RequestHeaderAuthenticationFilter();
    siteMinderFilter.setAuthenticationManager(authenticationManager());

    http
      // Error page is for everyone
      .authorizeRequests()
      .antMatchers("/error.html")
      .permitAll()
      .anyRequest()
      .anonymous()

      // Basic Auth for our REST services
      .and()
      .authorizeRequests()
      .antMatchers("/services/**")
      .permitAll()
      .anyRequest()
      .authenticated()
      .and()
      .httpBasic()
      .authenticationEntryPoint(authenticationEntryPoint)

      // Site-Minder protection for the web content
      .and()
      .addFilter(siteMinderFilter)
      .authorizeRequests()
      .antMatchers("/**").permitAll()
      .anyRequest().hasRole(ApplicationConstants.SITE_MINDER_AUTHORITY);

    http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
}

Is there something wrong with my configuration? Does my configuration create three separate filters? Maybe my question should be, how do I create the three filters?
When I attempt to call the REST Service using PostMan / "Basic Auth", I get the error message:
  org.springframework.security.web.authentication.preauth.PreAuthenticatedCredentialsNotFoundException: SM_USER header not found in request.

I expect the service to get called, instead I get the SiteMinder filter firing.


text:
Q: NSDateFormatter gets stringFromDate wrong I have a string as follows:

2012-11-01

And I want to get a string representing the day from that. So this is how I approach it:
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat: @"yyyy-mm-dd"];

NSDate *date = [dateFormatter dateFromString: @"2012-11-01"];

[dateFormatter setDateFormat: @"EEE"];

NSString *string = [dateFormatter stringFromDate: date];

NSLog(@"%@", string);

And the output is:

Sun

When it really should be:

Thu

(If my calculations are correct!)
So what is the problem here? Is this an internal bug? Something wrong with my code?
Thanks!

A: Change your first date format string to:
[dateFormatter setDateFormat: @"yyyy-MM-dd"]; // Capital MM for month

It should work then.


text:
Q: Is there a pattern for dealing with non-memory resources on cleaning up an ObjC object? It's usual for objects which have some state related to a non-memory resource to provide a method for explicitly 'finishing' with that resource. Is there a preferred common practice for dealing with the case where an object deallocation is attempted while still in the "using my resource" state? I have seen a couple of different approaches:

*

*log that the programmer made a mistake and tell them how to debug it (NSLock does that)

*let the caller choose whether the resource is managed by the caller or relinquished on deallocation (e.g. NSFileHandle)

*raise an exception if the object is not in an expected final state, i.e. assert that the programmer isn't going to use my object in that way

*always clean up on the way out.

The GC docs confirm that managing other resources alongside memory management is A Bad Idea and (yet) provide an example of doing 4, albeit with caveats. So has anyone "chosen" an approach to always follow?

A: Since most of the Cocoa framework objects predate garbage collection, you can't make the assumption that NSFileHandle, for example, is doing it the best way.  I think this problem is one of many where we'd like to have one pattern to follow for every scenario and save us the trouble of making a choice.  Unfortunately, I don't think that's possible; you're going to have to determine what's best on a case-by-case basis.
Here are reasons to choose any of your options:

*

*If automatic cleanup is reasonably safe but the program really ought to do it manually.

*If you're writing a library and the resource may or may not be owned by your object.

*If automatic cleanup is not possible or somehow risky.

*If automatic cleanup is trivial and not worth bothering anybody to do it manually.


text:
Q: Change some text using jquery Here is my code
    var payload ={"html":[
    {
        "caption":"Name",
        "name":"name",
        "type":"text",
        "required":true,
        "field_options":{"size":"small","description":""},
        "cid":"c11",
    },

      {
        "caption": "Please enter your clearance number",
        "type": "text",
        "required": true,
        "field_options": {},
        "cid": "c6"
      },
      {
        "caption": "Security personnel?",
        "type": "radio",
        "required": true,
        "field_options": { "include_other_option": false},
            "options": [{
                "caption": "Yes",
                "checked": false
            }, {
                "caption": "No",
                "checked": false
            }],

        "cid": "c10"
      },
      {
       "caption":"Country",
       "name":"country",
       "type":"select",
       "required":true,
       "options":[{
              "caption":"India",
              "checked":false
            },
            {
              "caption":"US",
              "checked":true
            }
       ],
       "cid":"c23"
      }

    ]

Now i want to replace caption to html where type is select
I want to change this
 {
       "caption":"Country",
       "name":"country",
       "type":"select",
       "required":true,
       "options":[{
              "caption":"India",
              "checked":false
            },
            {
              "caption":"US",
              "checked":true
            }
       ],
       "cid":"c23"
      }

to this
 {
       "caption":"Country",
       "name":"country",
       "type":"select",
       "required":true,
       "options":[{
              "html":"India",
              "checked":false
            },
            {
              "html":"US",
              "checked":true
            }
       ],
       "cid":"c23"
      }
    ]
  };

How to replace caption to html using jquery

A: Simple as this:
$.each(payload.html, function (i, item) {
    if (item.type == 'select') {
        $.each(item.options, function(o, option) {
            option.html = option.caption;
            delete option.caption;
        });
    };
});

Check the Fiddle.

A: do you mean this:
var payload ={"html":[
{
    "caption":"Name",
    "name":"name",
    "type":"text",
    "required":true,
    "field_options":{"size":"small","description":""},
    "cid":"c11",
}, {
    "caption": "Please enter your clearance number",
    "type": "text",
    "required": true,
    "field_options": {},
    "cid": "c6"
}, {
    "caption": "Security personnel?",
    "type": "radio",
    "required": true,
    "field_options": { "include_other_option": false},
    "options": [{
            "caption": "Yes",
            "checked": false
        }, {
            "caption": "No",
            "checked": false
        }],
    "cid": "c10"
}, {
   "caption":"Country",
   "name":"country",
   "type":"select",
   "required":true,
   "options":[{
          "caption":"India",
          "checked":false
        }, {
          "caption":"US",
          "checked":true
        }
   ],
   "cid":"c23"
}

]};

payload.html[3].options[1].html = payload.html[3].options[1].caption;
delete payload.html[3].options[1].caption;
console.log(payload.html[3].options[1]);

A: Try like this also using map and hasOwnProperty method.
Code snippets:
var data = payload.html;
var records = $.map(data, function (record) {
    if (record) {
        if (record.caption && record.type == "select" && record.options.length > 0) {
            var opt = record.options;
            $.map(opt, function (rec) {
                if (rec.hasOwnProperty("caption")) {
                    rec["html"] = rec["caption"];
                    delete rec["caption"];
                }
            });
        }
        return record;
    }
});
var updatedPayload = { html: records };
console.log(updatedPayload);

I hope you will like this !!!


text:
Q: Initializing SparkContext inside another SparkContext object I'm using PySpark to distribute a machine learning operation which consists of the following steps:

*

*Read data

*Divide data based on a column (~100 columns, dividing on one column that has 50 unique values, hence need to distributing the process on this column)
       I am parallelizing this process using sc.parallelize method

*On each data, initialize a classifier through a pipeline and use GridSearchCV from spark_sklearn to parallelize this operation. Since this requires it's own sparkcontext, I am creating another spark context object for this inside the small function.
A sample code is below
sample code
sc = SparkContext('local', appName="abc")

def sample():
    ## some code

    ## read data and extract text features using pipeline
    ## use grid search CV from spark_sklearn package -- this requires its own sparkcontext
    sc1 = SparkContext('local', appName="xyz")
    grid_search = sp_GridSearchCV(sc1, clf, parameters, n_jobs=-1, cv=cv, verbose=1, scoring='f1_macro')
    grid_search.fit(X, y)
    sc1.stop()
    return grid_search

results = sc.parallelize(labels).map(sample).collect()
sc.stop()

I would like to know if this would be the correct way of doing this and if not what would be the best way. I think the process can surely be improved. For example, initializing the sparkobject everytime adds an extra overhead which can be minimized
Any directions would be appreciated. Thanks!

A: This is not how Spark works.
When you create a SparkContext you are setting up your cluster, getting all information from YARN about how is your cluster. How much resources and stuffs.
SparkContext is responsible to handle this resources, hold the metadata for your RDDs, DataFrames, DataSets. And it will distributed between your workers. You can see below:

You can check with more details about it in this link.
But why that is not going to work, and why if its works you would be losing resources.
Why it will not work
Calling spark context in the worker side you will create a new "driver" and according to spark architecture you can just have drivers in the master node.
Why it will not give performance improvement
Spark always try to use all the resources of your cluster if you are using dynamic allocation to run that. And due to the Catalysis Optimizer this will create a plan of execution that in the most of times is better than what we used to build manually. And if you were able to create SparkContext in the workers side you would loose that executor just for the driver so, losing resources.

A: I like your thinking but after you have Spark Context, think of it as a lazy single machine which does one job at a time. The only difference between the usual single machine & spark context single machine is awesomeness(ram/processing/coordination/resilience).
It's pretty much considered as bad idea to send a map with a function containing ParamGrid. But above logic will help you :)


text:
Q: Impresspages 4 Model.php I have Model.php:
<?php
/**
* @package   ImpressPages
*/

namespace Plugin\My_plugin_name;

class Model
{
public static function getVideoList()
{
    $videos = ipDb()->selectAll('plugin_db', '*', array('language'=> ipContent()->getCurrentLanguage()->getCode()), 'ORDER BY row_number ASC');
    return $videos;
}

}

But when I try to call to this function in Widget/some_plugin/skin/view.php
$videos = Model::getVideoList();

I get:
Fatal error: Class 'Model' not found in .......Widget/some_plugin/skin/view.php

A: I feel like I've already answered this question. You have to use full namespace:
$videos = \Plugin\MyPlugin\Model::getVideoList();


text:
Q: Using ALL tenses in this text I wrote an imaginary text in which I used all tenses (12 tenses) to familiarize with them. The tenses are:

PAST: Past simple, Past perfect simple, Past continuous, Past perfect continuous.
PRESENT: Present simple, Present perfect simple, Present continuous, Present perfect continuous.
FUTURE: Future (will), Future perfect simple, Future continuous, Future perfect continuous.

Then what I ask here is: advice about my text, because me as a non-native english speaker I do not know if I am using the tenses correctly or not.
I got help from Cambridge Dictionary, where I got information about tenses in grammar section.
So, I will start with the text...:

My diary:
16/12/2019 - The crazy day:
This is the most weird day that I have ever had (Present perfect simple). I had been walking (Past perfect continuous) to my friend's house when (=suddenly) I saw (Past simple) a bull in the street!. In that moment, I ran too fast to the opposite direcion meanwhile I was screaming (Past continuous) for help. I had experienced (Past perfect simple) a similar situation like that, but in a secure environment (with fences).
I have (Present simple) a mix of feelings now. I am thinking (Present continuous) about before, I have been running (Present perfect continuous) too fast, I thought that the bull was near me after that race.
The next year I will have been writting (Future perfect continuous) in this diary for 10 years, and this is the most weird fact that I have ever had.
Now, what I want is: talk with my friend face-to-face about that moment, so, I think that I will go (Future: will) to his house tomorrow (I will be checking (Future continuous) well the path, because I could see other one again!)
I will close this crazy day with the hope that for the next year I will not have lived (Future perfect simple) another day like this.

I add to my first question: Could you check the last sentence? Because I used the future perfect simple and I am doubting about its use in that sentence.

A: Your last sentence using the future perfect simple tense( future perfect tense) is adequate for the following reasons.
1/It describe an event in the future that hasn't happened and is in no way planned.
2/Said(anticipated) event take place prior in time of the stated time of recollection."for the next year"
However, since you used "for the next year" as your designated time of recollection therefore it is slightly more appropriate to use the future continuous tense.(For more clarity and formality)

A: In your post, I believe that using the past continuous in place of  the past perfect continuous tense would have made more sense.
You didn't state the duration of the action while emphasizing the interruption of the said action.This is the textbook definition of the past continuous tense.