text:
Q: Android compound control won't display I'm trying to create a counter as a compound control.
TallyItem.java
package com.anna.mytallykeeper;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;

public class TallyItem extends LinearLayout {
private Button decrementButton;
private Button incrementButton;
private TextView descriptionText;
private TextView countText;

public TallyItem(Context context) {
    super(context);

    LayoutInflater inflate = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflate.inflate(R.layout.tallyitem_layout, this);

    /*
    String service = Context.LAYOUT_INFLATER_SERVICE;
    LayoutInflater li = (LayoutInflater)getContext().getSystemService(service);
    li.inflate(R.layout.tallyitem_layout, this, true);
    */

    //Get the fields
    decrementButton = (Button)findViewById(R.id.decrement);
    incrementButton = (Button)findViewById(R.id.increment);
    descriptionText = (TextView)findViewById(R.id.description);
    countText = (TextView)findViewById(R.id.count);

    decrementButton.setOnClickListener(buttonListener);
    incrementButton.setOnClickListener(buttonListener);
}

public TallyItem(Context context, AttributeSet attrs) {
    super(context, attrs);
}

private OnClickListener buttonListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        Button button = (Button)v;
        int count = Integer.parseInt(countText.getText().toString());

        if (button.getText().equals("-")) {
            count--;
        } else if (button.getText().equals("+")) {
            count++;
        }

        countText.setText("" + count);
    }
};
}

tallyitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<Button
    android:id="@+id/decrement"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_gravity="center"
    android:gravity="center"
    android:text="-"
    android:textSize="30sp"
    />
<LinearLayout
    android:orientation="vertical"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    >
        <TextView
            android:id="@+id/description"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Item 1"
            android:textSize="25sp"
            />
        <TextView
            android:id="@+id/count"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="0"
            android:textSize="60sp"
            />
</LinearLayout>
<Button
    android:id="@+id/increment"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_gravity="center"
    android:gravity="center"
    android:text="+"
    android:textSize="30sp"
    />
</LinearLayout>

main.xaml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<com.anna.mytallykeeper.TallyItem
    android:id="@+id/tallyItem1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
</LinearLayout>
</merge>

I am at a loss as to why it won't show up in main.xml.
Thanks for any help.

A: your view need a constructor with the AttributeSet passed in.  Change your constructor to this:
public TallyItem(Context context, AttributeSet attr) {
    super(context, attr);
    ...
}

and get rid of the constructor with the single argument.

A: try this in your main.xml
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<com.anna.mytallykeeper.TallyItem
    android:id="@+id/tallyItem1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
</merge>


text:
Q: Golang - How can I get authorization from mux? I'm a new beginner of Golang, I start learning Gorilla/Mux with JWT.
I'm just success in doing register a user to MongoDB and then login.
I use Postman to test. But when I try to browse to protected route.
I get the error "Missing auth token" as I have in the verification.
How can postman get the authorization to browse protected route?
Below is the code of register and login:

Router Function

func Router() *mux.Router {

    router := mux.NewRouter().StrictSlash(true)
  router.Use(CommonMiddleware)

  //router.HandleFunc("/", middleware.TestAPI).Methods("GET", "OPTIONS")
  router.HandleFunc("/register", middleware.RegisterHandler).Methods("POST", "OPTIONS")
  router.HandleFunc("/login", middleware.LoginHandler).Methods("POST", "OPTIONS")

  secure := router.PathPrefix("/auth").Subrouter()
  secure.Use(auth.JwtVerify)

    secure.HandleFunc("/api/task", middleware.GetAllTask).Methods("GET", "OPTIONS")
    secure.HandleFunc("/api/task", middleware.CreateTask).Methods("POST", "OPTIONS")
    secure.HandleFunc("/api/task/{id}", middleware.TaskComplete).Methods("PUT", "OPTIONS")
    secure.HandleFunc("/api/undoTask/{id}", middleware.UndoTask).Methods("PUT", "OPTIONS")
    secure.HandleFunc("/api/deleteTask/{id}", middleware.DeleteTask).Methods("DELETE", "OPTIONS")
    secure.HandleFunc("/api/deleteAllTask", middleware.DeleteAllTask).Methods("DELETE", "OPTIONS")
    return router
}

func CommonMiddleware(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
    w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Access-Control-Request-Headers, Access-Control-Request-Method, Connection, Host, Origin, User-Agent, Referer, Cache-Control, X-header")
    next.ServeHTTP(w, r)
  })
}

Register function

func RegisterHandler(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "application/json")
  var user models.User
  body, _ := ioutil.ReadAll(r.Body)
  err := json.Unmarshal(body, &user)
  var res models.ResponseResult
  if err != nil {
    res.Error = err.Error()
    json.NewEncoder(w).Encode(res)
    return
  }

  var result models.User
  err = usercollection.FindOne(context.TODO(), bson.D{{"username", user.Username}}).Decode(&result)

  if err != nil {
    if err.Error() == "mongo: no documents in result" {
      hash, err := bcrypt.GenerateFromPassword([]byte(user.Password), 5)

      if err != nil {
        res.Error = "Error While Hashing Password, Try Again"
        json.NewEncoder(w).Encode(res)
        return
      }
      user.Password = string(hash)

      _, err = usercollection.InsertOne(context.TODO(), user)
      if err != nil {
        res.Error = "Error While Creating User, Try Again"
        json.NewEncoder(w).Encode(res)
        return
      }
      res.Result = "Register Successful"
      json.NewEncoder(w).Encode(res)
      return
    }
    res.Error = err.Error()
    json.NewEncoder(w).Encode(res)
    return
  }
  res.Result = "Username already exists!!"
  json.NewEncoder(w).Encode(res)
  return
}

Login Function

func LoginHandler(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Content-Type", "application/json")
  var user models.User
  body, _ := ioutil.ReadAll(r.Body)
  err := json.Unmarshal(body, &user)

  if err != nil {
    log.Fatal(err)
  }
  //var resultToken models.Token
  var resultUser models.User
  var res models.ResponseResult

  err = usercollection.FindOne(context.TODO(), bson.D{{"username", user.Username}}).Decode(&resultUser)

  if err != nil {
    res.Error = "Invalid username"
    json.NewEncoder(w).Encode(res)
    return
  }

  expiresAt := time.Now().Add(time.Minute * 100000).Unix()

  errf := bcrypt.CompareHashAndPassword([]byte(resultUser.Password), []byte(user.Password))

  if errf != nil && errf == bcrypt.ErrMismatchedHashAndPassword {
    var  res = map[string]interface{}{"status": false, "message": "Invalid login credential. Please try again"}
    json.NewEncoder(w).Encode(res)
    return
  }
  tk := &models.Token{
    Username: user.Username,
    StandardClaims: &jwt.StandardClaims{
      ExpiresAt: expiresAt,
    },
  }

  token := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), tk)

  tokenString, err := token.SignedString([]byte("secret"))

  if err != nil {
    res.Error = "Error while generating token, Try again"
    json.NewEncoder(w).Encode(res)
    return
  }
  var resp = map[string]interface{}{"status": false, "message": "logged in"}
  resp["token"] = tokenString
  resp["tk"] = tk

  json.NewEncoder(w).Encode(resp)
}

Verification Function

func JwtVerify(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    var header = r.Header.Get("x-access-token")

    json.NewEncoder(w).Encode(r)
    header = strings.TrimSpace(header)

    if header == "" {
      w.WriteHeader(http.StatusForbidden)
      json.NewEncoder(w).Encode(Exception{Message: "Missing auth token"})
      return
    }

    tk := &models.Token{}

    _, err := jwt.ParseWithClaims(header, tk, func(token *jwt.Token) (interface{}, error) {
      return []byte("secret"), nil
    })

    if err != nil {
      w.WriteHeader(http.StatusForbidden)
      json.NewEncoder(w).Encode(Exception{Message: err.Error()})
      return
    }

    ctx := context.WithValue(r.Context(), "user", tk)
    next.ServeHTTP(w, r.WithContext(ctx))
  })
}

A: Since you are checking for the token x-access-token in the request header, you need to add the same while sending the request. This can be easily done in Postman as shown below -

The router I've used is -

package main

func router() *mux.Router {
    router := mux.NewRouter().StrictSlash(true)
    secure := router.PathPrefix("/auth").Subrouter()
    secure.Use(auth.JwtVerify)
    secure.HandleFunc("/api", middleware.ApiHandler).Methods("GET")
    return router
}

func main() {
    r := router()
    http.ListenAndServe(":8080", r)
}

The middleware I've used is -

package auth

func JwtVerify(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        var header = r.Header.Get("x-access-token")

        json.NewEncoder(w).Encode(r)
        header = strings.TrimSpace(header)

        if header == "" {
            w.WriteHeader(http.StatusForbidden)
            json.NewEncoder(w).Encode("Missing auth token")
            return
        } else {
            json.NewEncoder(w).Encode(fmt.Sprintf("Token found. Value %s", header))
        }
        next.ServeHTTP(w, r)
    })
}

and the handler is -

package middleware

func ApiHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode("SUCCESS!")
    return
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cassandra node goes down Last night, my node.js API threw error
All host(s) tried for query failed.First host tried, 127.0.0.1:Host considered as DOWN.

As suggested in error, it looks like cassandra node was down, so i dig into cassandra logs and found that their is an exception thrown by cassandra, but i could not figure out when this error could have been thrown.
Cassandra logs
INFO  [MemtableFlushWriter:73] 2015-04-02 19:12:58,844 Memtable.java:370 - Completed flushing; nothing needed to be retained.  Commitlog position was ReplayPosition(segmentId=1427954898588, position=3473692)
INFO  [CompactionExecutor:60] 2015-04-02 19:18:28,208 CompactionManager.java:521 - No files to compact for user defined compaction
INFO  [CompactionExecutor:61] 2015-04-02 19:28:28,209 CompactionManager.java:521 - No files to compact for user defined compaction
ERROR [CompactionExecutor:62] 2015-04-02 19:38:17,782 CassandraDaemon.java:153 - Exception in thread Thread[CompactionExecutor:62,1,main]
java.lang.NullPointerException: null
    at org.apache.cassandra.service.CacheService$KeyCacheSerializer.serialize(CacheService.java:475) ~[apache-cassandra-2.1.1.jar:2.1.1]
    at org.apache.cassandra.service.CacheService$KeyCacheSerializer.serialize(CacheService.java:463) ~[apache-cassandra-2.1.1.jar:2.1.1]
    at org.apache.cassandra.cache.AutoSavingCache$Writer.saveCache(AutoSavingCache.java:236) ~[apache-cassandra-2.1.1.jar:2.1.1]
    at org.apache.cassandra.db.compaction.CompactionManager$11.run(CompactionManager.java:1089) ~[apache-cassandra-2.1.1.jar:2.1.1]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) ~[na:1.7.0_67]
    at java.util.concurrent.FutureTask.run(FutureTask.java:262) ~[na:1.7.0_67]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) ~[na:1.7.0_67]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_67]
    at java.lang.Thread.run(Thread.java:745) [na:1.7.0_67]
INFO  [ScheduledTasks:1] 2015-04-02 19:38:22,991 ColumnFamilyStore.java:856 - Enqueuing flush of sstable_activity: 65753 (0%) on-heap, 0 (0%) off-heap
INFO  [MemtableFlushWriter:74] 2015-04-02 19:38:22,992 Memtable.java:324 - Writing Memtable-sstable_activity@166239084(6642 serialized bytes, 2952 ops, 0%/0% of on/off-heap limit)
INFO  [MemtableFlushWriter:74] 2015-04-02 19:38:23,105 Memtable.java:363 - Completed flushing /var/lib/cassandra/data/system/sstable_activity-5a1ff267ace03f128563cfae6103c65e/system-sstable_activity-ka-208-Data.db (3897 bytes) for commitlog position ReplayPosition(segmentId=1427954898588, position=3589687)
INFO  [CompactionExecutor:63] 2015-04-02 19:38:23,106 CompactionTask.java:136 - Compacting [SSTableReader(path='/var/lib/cassandra/data/system/sstable_activity-5a1ff267ace03f128563cfae6103c65e/system-sstable_activity-ka-205-Data.db'), SSTableReader(path='/var/lib/cassandra/data/system/sstable_activity-5a1ff267ace03f128563cfae6103c65e/system-sstable_activity-ka-207-Data.db'), SSTableReader(path='/var/lib/cassandra/data/system/sstable_activity-5a1ff267ace03f128563cfae6103c65e/system-sstable_activity-ka-208-Data.db'), SSTableReader(path='/var/lib/cassandra/data/system/sstable_activity-5a1ff267ace03f128563cfae6103c65e/system-sstable_activity-ka-206-Data.db')]
INFO  [CompactionExecutor:63] 2015-04-02 19:38:23,221 CompactionTask.java:252 - Compacted 4 sstables to [/var/lib/cassandra/data/system/sstable_activity-5a1ff267ace03f128563cfae6103c65e/system-sstable_activity-ka-209,].  15,482 bytes to 3,897 (~25% of original) in 113ms = 0.032889MB/s.  328 total partitions merged to 82.  Partition merge counts were {4:82, }
INFO  [CompactionExecutor:62] 2015-04-02 19:38:28,210 CompactionManager.java:521 - No files to compact for user defined compaction
INFO  [CompactionExecutor:64] 2015-04-02 19:48:28,213 CompactionManager.java:521 - No files to compact for user defined compaction
INFO  [CompactionExecutor:65] 2015-04-02 19:58:28,214 CompactionManager.java:521 - No files to compact for user defined compaction
INFO  [CompactionExecutor:66] 2015-04-02 20:08:28,215 CompactionManager.java:521 - No files to compact for user defined compaction
INFO  [CompactionExecutor:67] 2015-04-02 20:18:28,216 CompactionManager.java:521 - No files to compact for user defined compaction
INFO  [BatchlogTasks:1] 2015-04-02 20:19:58,913 ColumnFamilyStore.java:856 - Enqueuing flush of batchlog: 5848 (0%) on-heap, 0 (0%) off-heap
INFO  [MemtableFlushWriter:75] 2015-04-02 20:19:58,914 Memtable.java:324 - Writing Memtable-batchlog@1542233641(4538 serialized bytes, 10 ops, 0%/0% of on/off-heap limit)
INFO  [MemtableFlushWriter:75] 2015-04-02 20:19:58,915 Memtable.java:370 - Completed flushing; nothing needed to be retained.  Commitlog position was ReplayPosition(segmentId=1427954898588, position=3789073)
INFO  [CompactionExecutor:68] 2015-04-02 20:28:28,217 CompactionManager.java:521 - No files to compact for user defined compaction
INFO  [ScheduledTasks:1] 2015-04-02 20:38:22,989 ColumnFamilyStore.java:856 - Enqueuing flush of compaction_history: 1214 (0%) on-heap, 0 (0%) off-heap
INFO  [MemtableFlushWriter:76] 2015-04-02 20:38:22,990 Memtable.java:324 - Writing Memtable-compaction_history@1912511539(240 serialized bytes, 9 ops, 0%/0% of on/off-heap limit)
INFO  [ScheduledTasks:1] 2015-04-02 20:38:22,992 ColumnFamilyStore.java:856 - Enqueuing flush of sstable_activity: 65753 (0%) on-heap, 0 (0%) off-heap
INFO  [MemtableFlushWriter:77] 2015-04-02 20:38:22,993 Memtable.java:324 - Writing Memtable-sstable_activity@1348219988(6642 serialized bytes, 2952 ops, 0%/0% of on/off-heap limit)
INFO  [MemtableFlushWriter:76] 2015-04-02 20:38:23,049 Memtable.java:363 - Completed flushing /var/lib/cassandra/data/system/compaction_history-b4dbb7b4dc493fb5b3bfce6e434832ca/system-compaction_history-ka-107-Data.db (250 bytes) for commitlog position ReplayPosition(segmentId=1427954898588, position=3841853)
INFO  [MemtableFlushWriter:77] 2015-04-02 20:38:23,053 Memtable.java:363 - Completed flushing /var/lib/cassandra/data/system/sstable_activity-5a1ff267ace03f128563cfae6103c65e/system-sstable_activity-ka-210-Data.db (3916 bytes) for commitlog position ReplayPosition(segmentId=1427954898588, position=3841853)
INFO  [CompactionExecutor:69] 2015-04-02 20:38:28,217 CompactionManager.java:521 - No files to compact for user defined compaction

No logs are generated after this point, possibly node went down and server side apis start throwing error.

A: Upgrade to Cassandra 2.1.5, see CASSANDRA-8067


text:
Q: Transforming a Δ source to a Y source When having Y-Δ or Δ-Y 3 phase circuits, it is more convenient to transform the source configuration into the load configuration to make the circuit easier.
When going from a Δ source with line-line voltage of 400V to a Y source with phase voltage of 400/sqrt(3), we need to subtract -30 degrees from the initial phase of the Δ source, correct?

simulate this circuit – Schematic created using CircuitLab

A: Line voltage leads phase voltage by 30° as per this diagram (taken from here): -

\$V_{AB}\$ is the line voltage and, \$V_A\$ is its related phase voltage. So, if you wanted a version of \$V_A\$ that is in phase with \$V_{AB}\$, you need to advance it by 30° in time or, subtract 30° from it.

A: I tried simulating it on the multisim live circuit simulator and these are the results:

It is clearly shown that when transforming sources we must take into consideration the phase shift between Δ and Y source(the voltage of the resistor with the Δ voltage source is ahead of the voltage of the resistor with the Y source by 30 degrees).


text:
Q: JTable JQuery and one to many relationships Hello I need to show with jtable an entity. i have in my db impl/dto one 'one to many relationship', this boils down to have a set of objects related with an entity. More specifically:
public class UserEntityDTOImpl{
  @JsonProperty("UserId")
  private Long userId;
  @JsonProperty("UserName")
  private String userName;
  ....
  @JsonProperty("UserAddress")
  private Set<AddressEntityDTOImpl> userAddress = new HashSet<AddressEntityDTOImpl>(0);
  ...
}

public class AddressEntityDTOImpl  {
      @JsonProperty("AddressId")
        private Long address_id;
      @JsonProperty("Country")
        private String country;
      @JsonProperty("Address")
        private String detailAddress;
      @JsonProperty("PostCode")
        private String postCode;
....
}

and i am talking about UserAddress.
What i want is to use jtable and have enabled CRUD operations on the user including address list of each user (see user's address list, delete address list entries, add new address list entries and update existing ones).
I am stuck exaclty on the address list and need help on jtable as i am tottaly new to jtable/jquery/javascript.
i was thinking jtable supports something like this but could not find anything. The way i was thinking of it was to have something like one jtable inside another in terms that each user in my main jtable has one inner jtable which would have the address list.
Is this possible? If yes a short example how i can do this would be perfect.
If no, anyone had same issue to cope with and any proposals how to handle it?
If nothing of the above is applicable, one further question is as follows to use as work around, can i add somehow an extra button per row (next to delete/update buttons of jtable), which when pressed will direct me to another page?
i.e. {edit address button}-->/users/edit/address?userId={user.getId}
then if this is possible i could have a second jquery at another page to cope with specific user's address list.

A: Does this look similar to your use case?
http://jtable.org/Demo/MasterChild


text:
Q: How to conditionally set column to editable in kendo grid? Right now I am setting the entire grid to false for editing
(function(){
    let grid = $('#MyGrid').data('kendoGrid');
    grid.setOptions({
        editable: false
    });
})();

The problem I now have is that I need to be able to allow editing on two columns and am not sure how to do that?
So if my columns are Last, First, Age, Gender, I need to allow editing in Last and First while the rest are not allowed to edit.
EDIT
This is needed for when I set the grid as "read only", but some of the columns need to still be editable

A: You can control editability of columns through the data source model:
Leave the grid as editable, and turn off/on the field editable as desired.
Example (untested):
// make all fields uneditable (protected)
$.each(grid.dataSource.model.fields, function (name, options) {
  options.editable = false;
});

// unprotect the two fields in which changes will be allowed
grid.dataSource.model.fields["First"].editable = true;
grid.dataSource.model.fields["Last"].editable = true;


text:
Q: Why is my Bootstrap Carousel not working? I am making a MEAN stack application using angular 7. I use a Bootstrap Carousel but it's not working.

#slider .item {
  height: 500px;
}

.carousel-caption {
  font-size: 18px;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />

Welcome

Travel! Enjoy!

Welcome

Travel! Enjoy!

Welcome

Travel! Enjoy!

Is there any mistake I am doing with the code? I think #slider is not working in angular 7.

A: As I already explained here (marked as duplicate but nothing happened):

You have to give all items (pictures) of the carousel the class
  carousel-item but you only gave them the class item. Same with the
  Previous and Next buttons. The classes should be carousel-control-prev and carousel-control-next but you only gave
  them the class carousel-control.
The rest seems to be working just fine! When handling Bootstrap you
  always have to look out for the classes since they have to be exactly
  right for it to work at all. (You could also probably remove the
  popper.js-script at the bottom since it is not used at all.)
So basically just change all
 to
 and add -next and -prev to the control
  classes as I did here:

#slider .carousel-item {
  height: 500px;
}

.carousel-caption {
  font-size: 18px;
}

.carousel-item>img {
  width: 100%
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />

Welcome

Travel! Enjoy!

Welcome

Travel! Enjoy!

Welcome

Travel! Enjoy!

    Previous

    Next

A: I have the same problem like that.
You must be careful to read again Getting Started carousel focused on Dependency.
https://ng-bootstrap.github.io/#/getting-started
Don't forget to add BootstrapCDN (content delivery network)  in your HTML file:
https://www.bootstrapcdn.com/
this is my BootstrapCDN in my workspace:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />


text:
Q: How can I use the rear facing camera on video conferencing apps like Skype and Zoom? I use an iPhone 8. By default, Skype and Zoom use the front camera. But my rear camera has higher resolution and quality, correct? How can I order video conferencing apps like Skype and Zoom to use the rear camera?

A: If the app itself doesn't support it, you can't do it. It's the code of the app that determines which camera is to be used. There is no system-wide setting to override this.
I don't have Zoom, but Skype does have the option to switch cameras; there's an icon in the top right corner which does this:

A: Zoom has the ability to switch cameras in the iOS app.  The switch is available in the top left of the screen once you have started a meeting.  It does not appear that you can select the rear camera before you start the meeting;  so you will always have a moment where the front camera is "on" before you switch to the rear camera.


text:
Q: auto login to other site after successfully login to main site i have created login portal which is site (A) for users and i want to redirect them to other site (B)
i have all code and authority of site A and for site B i don't have any code and authority
site B contains of one input field where email id is require and one submit button
so what i want is user comes to site A and logins with userid and password and gets redirected to site B also i want auto input of that email in input field and auto button click
so in simple word user login to site A and redirect and also gets auto login to site B
my question is it is possible if yes then how ? which language can be used like it is possible in javascript ?
for site A i am using python flask

A: Assuming Site B does not require CSRF token, you might be able to do something like this in the template rendered after logging in to site A:
var xhr = new XMLHttpRequest();
$.ajax({
    type: 'POST',
    url: 'siteB.com/login',  // the URL site B email form makes POST to
    data: {email: '{{ email }}'}, // the email used to login at site A passed as context to the template rendered after site A login
    xhr: function() {
        return xhr;
    }
}).success(function() {
    window.location.replace(xhr.responseURL); // optionally redirect the client to the responseURL from POST made to site B
});


text:
Q: Post request returns dictionary with empty list In an attempt to subtract some data from a website with python.
Im not getting the same response as show in the developers window in the browser.
The preview code is the browsers returns:
{$id: "989"...}
$id: "989"
rows:[{$id: "990",constructionId: 84, constructionUnitId: Null,...}]
0: {$id: "990",constructionId: 84, constructionUnitId: Null,...}
1: {$id: "991",constructionId: 108, constructionUnitId: Null,...}
2: {$id: "992",constructionId: 157, constructionUnitId: Null,...}
3: {$id: "993",constructionId: 186, constructionUnitId: Null,...}

The response im getting in python:
{'$id': '990', 'rows': []}

The code im using is:
Obj_req = s.post('https://########.com/api/v1/Projects/GetDetailedTree', json=data, headers=headers)
    Obj_req_js = Obj_req.json()
    a = json.loads(Obj_req.text)
    print(a)

How can I get a list of the constructionId in this dictionary?

A: You are not sending some informations to server. For example bad user-agent or missing some "protection variable headers".
Next thing is you are missing cookies generated on website load.
I can't comment so i post answer.


text:
Q: How to resolve resource records in the private hosted zone created within Route53 over WireGuard VPN I created the WireGuard VPN tunnel which works fine, but local hosts are accessible only by the IP address. I would like to use a private hosted zone as well as to give to every host static name, so I can access hosts by FQDNs like "myhost.myprivatesubdomain.mydomain.com" for example.
I found in the AWS documentation, that I can do it by using Route53, but to achieve it I need to create the  "Client VPN endpoint". The procedure is well explained but there is a catch, the cost per hour associated with the endpoint is something like $0.15/h (~$100/month). Quite a lot for such a simple service.
I think there are a few ways how to do it.

*

*keep Route53 for the public zone and use for example UnBound DNS server for the private host zone.  (not sure for that)

*creating own DNS and remove Route53 in full (a lot of work but doable)

The best could be if I can keep in the Route53 the private zone setup and use the additional DNS server just to handle this ENDPOINT issue! (not sure is that actually possible)
I am not very skilled in DNS setup, so I have been trying to find the internet resource that treats such a case, but without success.
Could anyone point me in the right direction, please?
Thanks in advance.


text:
Q: Learning C#'s async/await/Task structure; code hangs at await? To get a sense for how C#'s threading constructs work, I've written a simple test program that performs the same task - sleeping for 3 seconds then returning an object - both synchronously and asynchronously.  I've set up some stopwatches to get a better sense as to how the code is flowing.
The synchronous call is working as expected: there's a 3 sec delay between the "before sync" and "after sync" prints.  However, for the async call, the program hangs indefinitely after "after async".  I'm expecting "before async" and "after async" to print quickly in succession (since ExecuteAsync just returns a Task), then for "awaited async" to print three seconds later (or rather, at least three seconds later; if there was a ton of logic between ExecuteAsync and when that Task is awaited, it might be longer).
namespace TaskTest
{
    class Program
    {
        static void Main(string[] args)
        {
            doStuff().Wait();

            Console.WriteLine("Press any key to end");
            Console.ReadKey();
        }

        static async Task doStuff()
        {
            TestClass tceOn = new TestClass(true);

            Stopwatch s = Stopwatch.StartNew();

            s.Checkpoint("Before sync on");
            tceOn.ExecuteSync();
            s.Checkpoint("After sync on");

            Console.WriteLine();

            s.Checkpoint("Before async on");
            Task<Foo> fooTask = tceOn.ExecuteAsync();
            s.Checkpoint("After async on");

            Foo foo = await fooTask;
            s.Checkpoint("Awaited async on");
        }
    }

    class TestClass
    {

        public bool ShouldWait = false;

        public TestClass(bool tce)
        {
            ShouldWait = tce;
        }

        public Task<Foo> ExecuteAsync()
        {
            Task<Foo> output;
            RunExecute(out output, true);
            return output;
        }

       public Foo ExecuteSync()
        {
            Task<Foo> dud;
            return RunExecute(out dud);
        }

        private Foo RunExecute(out Task<Foo> task, bool async = false)
        {
            Foo outputFoo;

            if(async)
            {
                task = new Task<Foo>(makeFoo);
                outputFoo = null;
            }

            else
            {
                task = null;
                outputFoo = makeFoo();
            }

            return outputFoo;
        }

        private Foo makeFoo()
        {
            if (ShouldWait)
                Thread.Sleep(3000);
            return new Foo();
        }
    }

    class Foo { }
}

To clean it up a bit, I didn't paste the extension method for Stopwatch's Checkpoint() method; it just prints the number of ticks so I can get a sense for the time elapsed.
So, why isn't this code working as expected?  I was hoping this would be a "simplest thing that could possibly work"-type scenario.  Thanks!
Update:
Having changed my code according to Peter Duniho's first suggestion (task = Task.Run(() => makeFoo());), I'm now trying to figure out how to get this to work with a .ContinueWith() block:
private Foo RunExecute(out Task<Foo> task, bool async = false)
{
    Foo outputFoo;

    if(async)
    {
        task = Task.Run(() => makeFoo()).ContinueWith((t) => // **** error here ****
        {
            outputFoo = null;
        });
    }

    else
    {
        task = null;
        outputFoo = makeFoo();
    }

    return outputFoo;
}

This is giving me an implicit conversion error on the line where I made the change:
Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'System.Threading.Tasks.Task<TaskTest.Foo>'
Because I'm new to how Tasks, Actions, and the like work, I'm not quite sure what the problem is/what's not matching up.

A: You haven't actually run any Task. So you're waiting on something that will never complete.
To fix your code exactly as it is, you can do this:
private Foo RunExecute(out Task<Foo> task, bool async = false)
{
    Foo outputFoo;

    if(async)
    {
        task = Task.Run(() => makeFoo());
        outputFoo = null;
    }
    else
    {
        task = null;
        outputFoo = makeFoo();
    }

    return outputFoo;
}

A more idiomatic way would look something like this:
private Foo RunExecute(out Task<Foo> task, bool async = false)
{
    Foo outputFoo;

    if(async)
    {
        task = makeFooAsync();
        outputFoo = null;
    }
    else
    {
        task = null;
        outputFoo = makeFoo();
    }

    return outputFoo;
}

async Task<Foo> makeFooAsync()
{
    await Task.Delay(3000);
    return new Foo();
}

You can even change the example so that both the synchronous and asynchronous work exactly the same (and don't require the out parameter):
private Task<Foo> RunExecute(bool async = false)
{
    Foo outputFoo;

    if(async)
    {
        return makeFooAsync();
    }
    else
    {
        return Task.FromResult(makeFoo());
    }
}

A:
To get a sense for how C#'s threading constructs work, I've written a simple test program that performs the same task - sleeping for 3 seconds then returning an object - both synchronously and asynchronously.

Your actual code is quite complex. So let's start with the "simplest possible" 3-second synchronous sleep:
class Program
{
    static void Main(string[] args)
    {
        TestClass tceOn = new TestClass();
        Stopwatch s = Stopwatch.StartNew();
        s.Checkpoint("Before sync on");
        tceOn.Execute();
        s.Checkpoint("After sync on");

        Console.WriteLine("Press any key to end");
        Console.ReadKey();
    }
}

class TestClass
{
    public Foo Execute()
    {
        Thread.Sleep(3000);
        return new Foo();
    }
}

class Foo { }

Now, to create an asynchronous equivalent, you first start at the "leaves" - in this case, Thread.Sleep in TestClass.Execute, and work your way up. This is the natural way to convert code to be asynchronous (except in this case, we're creating the asynchronous code side-by-side instead of in-place). The first step is always to identify blocking operations (Thread.Sleep) and discover asynchronous equivalents (in this case, Task.Delay):
class TestClass
{
    public async Task<Foo> ExecuteAsync()
    {
        await Task.Delay(3000);
        return new Foo();
    }

    public Foo Execute()
    {
        Thread.Sleep(3000);
        return new Foo();
    }
}

Note the similarities between the two methods. Also note that there is no need for Task.Run. This is the case for all naturally-asynchronous code.
At this point, you're ready to add the asynchronous test. Since Main can't be async, this is the point at which you need to move the test code to another method:
class Program
{
    static void Main(string[] args)
    {
        MainAsync().Wait();
        Console.WriteLine("Press any key to end");
        Console.ReadKey();
    }

    static async Task MainAsync()
    {
        TestClass tceOn = new TestClass();
        Stopwatch s = Stopwatch.StartNew();
        s.Checkpoint("Before sync on");
        tceOn.Execute();
        s.Checkpoint("After sync on");

        s.Checkpoint("Before async on");
        Task<Foo> fooTask = tceOn.ExecuteAsync();
        s.Checkpoint("After async on");

        Foo foo = await fooTask;
        s.Checkpoint("Awaited async on");
    }
}

For your final question regarding ContinueWith, the answer is "don't use ContinueWith; use await instead".


text:
Q: E-Book reader development technique I'm working on a web project using AngularJs and WebApi 2 to create cross platform web client.
The project should support PDF and ePUB books and I need to provide the client with rich unified book viewer for booth formats.
My thoughts was to upload both formats and convert the PDF to the ePUB format and develop or find an open source ePUB viewer for the client side UI.
Problems:

*

*Proper C# library to convert PDF to ePUB keeping the PDF format.

*Ideas for streaming the books with large size to the client.

*Secure the book If download needed.

A: I contacted the client and did some changes, I knew that the PDF books are scanned images so I extracted it using ITextSharp library,About the ePUB books I used the "VersFx.Formats.Text.Epub" library form NuGet to pares the books and it was sufficient.

*

*About the readers I used "JQuery booklet plugin" for ePUB as it is text based books, And "TurnJS plugin" for image based books "PDF" as mentioned earlier.


text:
Q: How can I configure XAMPP to fix this errors? I just have installed XAMPP in my computer but in the log console it gives to me this following errors:
[Apache]    Apache Service detected with wrong path
[Apache]    Change XAMPP Apache and Control Panel settings or
[Apache]    Uninstall/disable the other service manually first
[Apache]    Found Path: "C:\Apache24\bin\httpd.exe" -k runservice
[Apache]    Expected Path: "c:\xampp\apache\bin\httpd.exe" -k runservice
[Apache]    Problem detected!
[Apache]    Port 80 in use by ""C:\Apache24\bin\httpd.exe" -k runservice" with PID 1632!
[Apache]    Apache WILL NOT start without the configured ports free!
[Apache]    You need to uninstall/disable/reconfigure the blocking application
[Apache]    or reconfigure Apache and the Control Panel to listen on a different port
[mysql]     Problem detected!
[mysql]     Port 3306 in use by ""C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld" --defaults-file="C:\ProgramData\MySQL\MySQL Server 5.5\my.ini" MySQL55"!
[mysql]     MySQL WILL NOT start without the configured ports free!
[mysql]     You need to uninstall/disable/reconfigure the blocking application
[mysql]     or reconfigure MySQL and the Control Panel to listen on a different port

I don't have any idea about how to solve them.

A: you installed XAMPP Mysql and Apache. If you are going to use XAMPP you need to uninstall Apache and Mysql. That will fix your problem
I am not sure why you installed XAMPP which contains Apache and Mysql and then you install separately Apache and Mysql.
If for some reason you dont want to uninstall Apache and Mysql, you can go to Windows > Type services.msc and stop service Mysql and apache

A: you will try change port 80 of httpd.conf in apache directory:
C:\xampp\apache\conf\httpd.conf
It´s appear in some lines. Sometimes, it´s after IP, for example, 192.168.1.x:80


text:
Q: Groovy criteria query I have a domain model that looks like this
Category 1 ------- * Type 1 ------- * Expense

Or in English "An expense has a type, and each type belongs to a category". I want to write a Criteria query that will find all expenses in a particular category. I tried both this
Expense.withCriteria {
    eq('type.category', someCategoryInstance)
}

and this
Expense.withCriteria {
    type {
        eq('category', someCategoryInstance)
    }
}

But neither of them work, what am I missing?
Update
I've been asked to show the domain classes, so here they are:
public class Category {

    String description
    static hasMany = [types: Type]
}

public class Type {

    String description
    static hasMany = [expenses: Expense]
    static belongsTo = [category: Category]
}

public class Expense {

    static belongsTo = [type: Type]

    Date date
    String description
    float amount
}

A: Depending on how the associations are declared, the type table might not be joined in to the query.  You can explicitly tell it to join with a join in your criteria.
Expense.withCriteria {
    join('type')
    type {
        eq('category', someCategoryInstance)
    }
}


text:
Q: Can't install add-ons for Firefox on newly installed Lubuntu 17.04 I installed Lubuntu for the first time yesterday and since then I'm unable to access the Firefox Add-ons website properly. The site takes a very long time to load and then I only get the html without the CSS. I can find some add-on and try to install it but again it fails to download.
Every other website that I've tried is working just fine. I tried chromium as well and it works perfectly with extensions.
I haven't installed Flash or restricted extras, just the base system.
Any help would be appreciated.


text:
Q: Slurm: How to find out how much memory is not allocated at a given Node i am new to SLURM. I am searching for a comfortable way, to see how many memory at an node/nodelist is available for my srun allocation.
I already played around with sinfo and scontrol and sstat but none of them gives me the information i need in one comfortable overview.
I had the idea to write a shell script, in order to fetch all  fields of all jobs from scontrol and sum them up. But there must be an easier way.
Would be great if anyone has an hint or idea!

A: The 7th column of the output of sinfo -N -l will tell you how much memory is installed in each compute node.
$sinfo -N -l
Wed Nov  6 16:31:45 2013
NODELIST                NODES PARTITION       STATE CPUS    S:C:T MEMORY TMP_DISK WEIGHT FEATURES REASON
node001                    1      Def*        idle    8    2:4:1  24150   920644    100 Xeon,X55 none

The command scontrol -o show nodes will tell you how much memory is already in use on each node. Look for the AllocMem entry. (Needs Slurm 2.6.0 or more recent)
$ scontrol -o show nodes | awk '{ print $1, $13, $14}'
NodeName=node001 RealMemory=24150 AllocMem=0


text:
Q: From http to Https Service Call is there a way for some one to sneak in the to see data if my service is over http and the caller in my case is hosted on http (i.e. service is on secure ssl host while caller is on simple http).
is that call secure or not?

A: Basic HTTP without any encryption or other means of obfuscating your content is just plain text going over the wire. Anyone with a bit of knowledge can trap that connection and just read everything that goes on.
I don't quite understand what you mean by the server is on secure host but the client is not? Either the conversation between those two is secured by SSL / HTTPS (but then BOTH ends need to participate), or not. If not - it's just clear text on the wire.

A: *

*Yes if someone is able to sneak into your transmissions, they can workout if the messages are encrypted or not.

*When you connect to a server marked with server side SSL (server marked with https), it sends a copy of its cert to the client (e.g. your browser) which verifies if its a genuine cert. This only confirms that the server is really what it says it is and not someone else masquerading.
This does not guarantee that no can intercept your message. They can intercept but wont be able to decrypt.


text:
Q: How to check connectivity to a server IP I have a flutter app, which connects to the local network via wifi, so I need to validate that the device has the connection with the server to consume web services, and in case it has no connection notify the user of the error.
Is there any way to ping in a flutter?


text:
Q: React | How to Pass FormikProps one Component Up I am trying to pass values and props, that formik needs 1 component up. I am using various little components for some forms, and I am passing them in a complex component that needs to pass them down to each individual render when called.
Basically all the FormikProps. Here is one such component.
import React, { Fragment } from 'react';
import debounce from 'debounce-promise';
import classNames from 'classnames';
import { Field, FormikProps, ErrorMessage } from 'formik';

import Asterisk from 'shared/common/components/element/Asterisk';
import { validateUsername } from '../../utils/index';

interface IValues {
  username?: string;
  email?: string;
}

export const InfoFields = (props: FormikProps<IValues>): JSX.Element => {
  const debounceUsernameValidation = (): void => {
    debounce(validateUsername, 500);
  };

  const { touched, errors } = props;

  return (
    <Fragment>

          Username <Asterisk />

        <Field
          validate={debounceUsernameValidation}
          className={classNames('form-control', {
            'is-invalid': errors.username && touched.username
          })}
          placeholder="Username (Required)"
          autoComplete="username"
          name="username"
          type="text"
        />
        <ErrorMessage name="username" component="div" className="text-danger" />

        Email
        <Field
          className={classNames('form-control', {
            'is-invalid': errors.email && touched.email
          })}
          autoComplete="email"
          placeholder="Email"
          name="email"
          type="email"
        />
        <ErrorMessage name="email" component="div" className="text-danger" />

    </Fragment>
  );
};

export default InfoFields;

And here I am calling it inside the complex component:

  render(): ReactNode {
    const { mode } = this.props;
    return (
      <Formik
        initialValues={this.getInitialValues()}
        validationSchema={this.getValidationSchemas()}
        onSubmit={this.handleSubmit}
        validateOnBlur={false}
        render={({ status, isSubmitting }) =>
          (
            <Form>
              {status && (

                  {status}

              )}
              {mode === ActionMode.ADD_USER && (
                <Fragment>
                  <InfoFields /> // This is the component from above
                </Fragment>
              )}
              <Button
                className="btn btn-primary w-100 mt-5"
                disabled={isSubmitting}
                loading={isSubmitting}
                type="submit"
              >
                {mode === ActionMode.ADD_USER && CREATE USER}
              </Button>
            </Form>
          ) as ReactNode
        }
      />
    );
  }

Now when I call that component inside another one, I get this error:
Uncaught TypeError: Cannot read property 'username' of undefined. It refers to this line of code:
errors.username && touched.username and this
errors.email && touched.email

interface IProps {
  doSubmit(service: object, values: object): LensesHttpResponse<string>;
  onSave(values: { username?: string; email?: string; password?: string; group?: string }): void;
  notify(config: object): void;
  mode: ActionMode;
  user: IUser;
}

interface IValues extends FormikValues {
  username?: string;
  email?: string;
  password?: string;
  group?: string;
}

I need a way to pass the props username, email and the rest to each individual compoenent.The problem is the component is called 2 renders down, so it doesn't have access to them
I am kind at a loss here. Can someone help me? Thanks!!

A: You aren't actually passing props to InfoFields although you've written that component to accept FormikProps<IValues>. Either you can pass Formik's props in like this:
<Formik
    render={formikProps => (
        <Form>
            // Other Code.

            <InfoFields {...formikProps} />

            // Other Code.
        </Form>
    )}
/>

Or (my personal preference), remove InfoField's props and use Field as a render prop, for example:
<Field
    name="username"
    validate={debounceUsernameValidation}
>
    {({ field, form }: FieldProps) => (
        <Fragment>
            <input
                {...field}
                className={classNames('form-control', {
                    'is-invalid': form.errors[field.name] &&
                        form.touched[field.name]
                })}
                placeholder="Username (Required)"
                type="text"
            />
            <ErrorMessage
                name={field.name}
                component="div"
                className="text-danger"
            />
        </Fragment>
    )}
</Field>

With the field render prop you can access the form values in components nested further down without passing props all over the place.


text:
Q: running cron.php thows a "maximum execution time exceeded" fatal error I am using Drupal 6.19 with quite a lot modules. Since I added another domain using Domain Access, added a panel variant and a node type, the cron first exhausted the memory limit of 512MB. I increased this limit to 1024MB. After I have done that, the "Maximum execution time" of 240 seconds is being exceeded.
Any ideas? What additional information shpould I give?
Thanks
Lukas

A: Try to look for croon implementations in your modules. Disable each of these (separately) temporarily too see if it makes any difference.
Maybe a module is running in some kind of loop. A possible candidate would be search.module, that lodas all comments of a single node. If you have nodes with thousands of comments (forum posts), that could be causing this.

A: Look inside: includes/common.inc
Line: 2716
Change the set_time_limit to a higher number such as 400.
Hope it will help someone.
Finau

A: You should be able to raise the max execution time with set_time_limit() but I think it would be good to find out what your script is doing for four minutes!
I don't know much about this drupal script but would suggest the following:

*

*Keep an eye on the database while it's running, I'm guessing that slow MySQL queries are likely to be the primary cause of it running slow

*If slow queries aren't the cause setup some kind of profiling (would recommend xdebug + webgrind for something simple), set_time_limit() to something really high and run the script. Use the profiling data to see what's so slow and then work to optimise it.


text:
Q: List if list to a array of objects I am trying to map a list of list to an array of objects. The list looks like this[[1592870400000,0],[1592524800000,2],[1592352000000,0],[1592179200000,0],[1591920000000,0],[1591833600000,0],[1591574400000,0],[1591228800000,0]]
I want map it to an array of objects `class RiskTrend {
final int riskScore;
final int dateTime;
RiskTrend({this.riskScore, this.dateTime});
}`
How do I do this?

A: The easiest way would be to iterate over the original list and add the elements to your new list.
List<RiskTrend> list = new List<RiskTrend>();
for(var i = 0; i < original.length; i++){
    list.add(new RiskTrend(original[i][0],original[i][1]));
}


text:
Q: How to abbreviate journal name with the first letters? I use the command "bibentry" to show the references in the slides with beamer.
And i want to get an abbreviated journal name, e.g. "Physical Review Letters" thansfors into "PRL". How can I achieve that? How to modify the "bst" file?


text:
Q: UDF to extract specific data from a generic string I'm trying to create a function like =Extractinfo("A2","Name"), which can extract name, phone and email id from raw data, one function for all 3 extractions, I already have a function to extract email id
 Raw Data

"Name":"Ram","Phone":"9898989898","Email":"abcd@gmail.com"
"Name":"Raju","Phone":"2323232323","Email":"xyz123@gmail.com"
"Name":"Rameshsing","Phone":"555999999","Email":"rameshsing@gmail.com"

(Function to extract)          (Expected Result)
=Extractinfo("A2","Name")      Ram
=Extractinfo("A2","Name")      Raju
=Extractinfo("A4","Name")      Rameshsing

Function ExtractEmailFun(extractStr As String) As String

 Dim CharList As String
 On Error Resume Next
CheckStr = "[A-Za-z0-9._-]"
OutStr = ""
Index = 1
Do While True
Index1 = VBA.InStr(Index, extractStr, "@")
getStr = ""
If Index1 > 0 Then
    For p = Index1 - 1 To 1 Step -1
        If Mid(extractStr, p, 1) Like CheckStr Then
            getStr = Mid(extractStr, p, 1) & getStr
        Else
            Exit For
        End If
    Next
    getStr = getStr & "@"
    For p = Index1 + 1 To Len(extractStr)
        If Mid(extractStr, p, 1) Like CheckStr Then
            getStr = getStr & Mid(extractStr, p, 1)
        Else
            Exit For
        End If
    Next
    Index = Index1 + 1
    If OutStr = "" Then
        OutStr = getStr
    Else
        OutStr = OutStr & Chr(10) & getStr
    End If
Else
      Exit Do
End If
Loop
ExtractEmailFun = OutStr
End Function

A: Your RAW data seems to match the JSON format. One thing that can be done is to use a module (like this one that worked very well for me) to parse it (i.e. put some order in it, so you can easily get the result you are looking for).
Follow the simple instructions to add this module to your VBA project (remember to add the Microsoft.Scripting Reference!). Then your function would look like this :
Public Function Extractinfo(byval CompleteString as String, byval FieldName as String) as String

    Dim JSON as Object
    Set JSON = JsonConverter.ParseJson(CompleteString)

    ExtractInfo = JSON(FieldName)

End Function

This code sample is overly simplified (does not have any error handling), but this should get you started.

A: How about:
Public Function ExtractInfo(s As String, choice As String) As String

    dq = Chr(34)
    arr = Split(s, dq)

    If choice = "Name" Then
        ExtractInfo = arr(3)
        Exit Function
    End If

    If choice = "Phone" Then
        ExtractInfo = arr(7)
        Exit Function
    End If

    If choice = "Email" Then
        ExtractInfo = arr(11)
        Exit Function
    End If

    ExtractInfo = "bad data"
End Function

This assumes that all your data follows the same schema.  Options would be:
=extractinfo(A1,"Name")
=extractinfo(A1,"Phone")
=extractinfo(A1,"Email")

You could also use Case for this.


text:
Q: Erlang ports and thread safety I'm looking to call a C function from an Erlang process via an Erlang port, as described here:
http://www.erlang.org/doc/tutorial/c_port.html
In production I will need multiple Erlang processes calling the C function in parallel, each with a different set of arguments.
My question is, will this be thread safe at the C function level ?
The docs talk about the controlling Erlang process creating a 'connected process', which it sounds as if is responsible for creating an isolated instance of the 'external program' (C function).
So it sounds like it's thread safe at the C level but I'd like to be 100% sure.
TIA

A: It may depend on your implementation, but with Ports, the answer is almost definitely "yes" for the reason you mention. If you were using a NIF and using shared memory inside of the NIF, you would have some concern for thread safety.
With ports, however, the "controlling process" acts as a serialization (as in arranged in a series) layer, meaning requests are handled one after the other and not all at once. Moreover, I believe (but do not know for certain) that the communication protocol ports use also requires this serial execution.

A: A port is a program that communicates to the Erlang side using standard input output. Whether you need thread safety or not depends on the communication protocol you implement.
If you think in terms of a port being an erlang process (which for the erlang side is the abstraction your erlang code sees) you could implement a protocol whether for each request you send to it, it will block until it sends back a response, or that you could send several requests in parallel and get responses for all of them asynchronously.
Going the the C side, the implementation of the former case would be a simple loop doing

*

*read command from stdin

*process that command

*write result to stdout

*go to 1

The concurrency is handled in the erlang side as all incoming commands will pile up in the port inbox while the port is processing one at a time.
For the latter, you would need a mechanism to handle input messages git remote add origin git@bitbucket.org:samuelrivas/dfberl.git
asynchronously, I'll use threads here for simplicity:
The main loop:

*

*read command from stdin

*spawn a thread to process it

*go to 1

The thread loop:

*

*process command

*write result to stdout

Note that threads will need some kind of locking when writing to stdout, I usually implement that part as yet another thread with an asynchronous queue where all the other threads publish results to.
In the second scenario you will have concurrency in the C side, so you need to care about thread safety. In the first one the C side doesn't handle any concurrency, so thread safety is not a concern there.


text:
Q: Write $e^{\ln(5)}i$ in polar and rectangular form Is there something I'm missing? Below is my attempt, but I feel as though I might have missed something to learn about complex numbers when $r=e^n$.
$$|ie^{\ln(5)}|=e^{\ln(5)}$$
$$\theta=\arctan(\frac{e^{\ln(5)}}{0})=\text{undefined}; \text{thus}, \theta=\frac{\pi}{2}$$
$$z=e^{\ln(5)}e^{i\frac{\pi}{2}}=e^{\ln(5)+i\frac{\pi}{2}}$$

A: Let $z$ be your number.
Sometimes it's easier to figure out the angle just visualizing the number in the plane, for $i$ it's particularly easy, as it lies in an axis perpendicular to the real line, we can infer that it's $\frac \pi 2 $.
As $e^{\ln 5}=5$, we have that $|z|=|5i|=|5|\cdot |i|=5 \cdot 1$.
And $\arg(z)=\arg(5i)=\arg(5)+\arg(i)=0+\frac \pi 2.$
So $z=5e^{i\frac\pi 2}=0+5i$.
I've used a few properties ($|zw|=|z|\cdot|w|, \arg(zw)=\arg(z)+\arg(w)$) which proofs I leave as exercise.


text:
Q: Download a Excel from GiThub into Excel I would like with M to build a script to connect to an Excel file.
One example:
https://github.com/owid/covid-19-data/tree/master/public/data/owid-covid-data.xlsx
Tann

A: You want the URL to the raw file rather than that web page.
Excel.Workbook(Web.Contents(
"https://github.com/owid/covid-19-data/blob/master/public/data/owid-covid-data.xlsx?raw=true"
))

Full example that can be pasted into the Advanced Editor:
let
    Source = Excel.Workbook(Web.Contents("https://github.com/owid/covid-19-data/blob/master/public/data/owid-covid-data.xlsx?raw=true")),
    Sheet1_Sheet = Source{[Item="Sheet1",Kind="Sheet"]}[Data],
    #"Promoted Headers" = Table.PromoteHeaders(Sheet1_Sheet, [PromoteAllScalars=true]),
    #"Changed Type" = Table.TransformColumnTypes(#"Promoted Headers",{{"iso_code", type text}, {"continent", type text}, {"location", type text}, {"date", type date}, {"total_cases", Int64.Type}, {"new_cases", Int64.Type}, {"new_cases_smoothed", type number}, {"total_deaths", Int64.Type}, {"new_deaths", Int64.Type}, {"new_deaths_smoothed", type number}, {"total_cases_per_million", type number}, {"new_cases_per_million", type number}, {"new_cases_smoothed_per_million", type number}, {"total_deaths_per_million", type number}, {"new_deaths_per_million", type number}, {"new_deaths_smoothed_per_million", type number}, {"reproduction_rate", type number}, {"icu_patients", type any}, {"icu_patients_per_million", type any}, {"hosp_patients", type any}, {"hosp_patients_per_million", type any}, {"weekly_icu_admissions", type any}, {"weekly_icu_admissions_per_million", type any}, {"weekly_hosp_admissions", type any}, {"weekly_hosp_admissions_per_million", type any}, {"new_tests", type any}, {"total_tests", type any}, {"total_tests_per_thousand", type any}, {"new_tests_per_thousand", type any}, {"new_tests_smoothed", type any}, {"new_tests_smoothed_per_thousand", type any}, {"positive_rate", type any}, {"tests_per_case", type any}, {"tests_units", type text}, {"total_vaccinations", type any}, {"new_vaccinations", type any}, {"total_vaccinations_per_hundred", type any}, {"new_vaccinations_per_million", type any}, {"stringency_index", type number}, {"population", Int64.Type}, {"population_density", type number}, {"median_age", type number}, {"aged_65_older", type number}, {"aged_70_older", type number}, {"gdp_per_capita", type number}, {"extreme_poverty", type any}, {"cardiovasc_death_rate", type number}, {"diabetes_prevalence", type number}, {"female_smokers", type any}, {"male_smokers", type any}, {"handwashing_facilities", type number}, {"hospital_beds_per_thousand", type number}, {"life_expectancy", type number}, {"human_development_index", type number}})
in
    #"Changed Type"


text:
Q: Find all elements with a given class and data-value, take data-value and add class to other elements with matching class I am using facetwp plugin for Wordpress for filtering posts. Each facet outputs its options with markup like this...

 ...

When an option is selected the class .checked is added.
So on a given page I might have something like this..

 ...

 ...

 ...

 ...

 ...

I need to cycle through all these elements, fine the ones that have the .checked class, take their data-value and find other elements on the page that have classes equal to the data-value and add the .checked class to them.
I have working code for a single instance..
    if ($('.facetwp-facet .checked[data-value="blue"]').length > 0) {
    $('.blue').addClass('checked');
    } else {
    $( ".blue" ).removeClass( "checked" );
    }

How can I amend this code to 'cycle' dynamically through all of the possible combinations?

A: If I am understanding your question, you are looking to iterate through the set of all checked radios, and then obtain an attribute for each element in that set.  Then you seek to find all elements that have those values as a class.
$(".facetwp-radio .checked").each(function() {
    var dv = $(this).attr("data-value");
    var classSelector = "." + dv;
    var elementList = $(classSelector);
    <Do whatever you want to do with that element set>
});

A: $('.facetwp-radio').each(...) to iterate all elements. Not common practice to have dot inside css class name.
Demo at https://codepen.io/ProGu/pen/jOLqrZP
  $('.facetwp-radio').each(function() {
    if ($(this).hasClass('.checked')) {
      $('.' + $(this).data('value')).addClass('.checked');
    } else {
      $('.' + $(this).data('value')).removeClass('.checked');
    }
  });


text:
Q: frequency distribution I'm not familiar with probability.
Say I have some n data points over the reals $\{x_i\}_{i=1}^n \subset \mathbb{R}$ such as the distance to the basket during a field goal attempt. How should I construct a distribution over the real line to fit this data?
Say I pick the normal distribution (not sure about the connection to the data). How can I measure the probability that a new data point z will exist according to my distribution?
Certainly, to get a positive probability, I must pick a neighborhood around the data point. But my probability then depends on the width of the neighborhood...
Do I need to make the domain discrete?


text:
Q: FormMail not sending image I'm using the latest version of Matts formmail but for some reason I'm not able to configure image upload. Is the script capable of image upload? or is this an html problem in my form?
It is uploading this form. Wiling to make a small donation to whoever helps.
    <form id="buy-online" class="automatic-pricing c7" action="FormMail/formmail.pl"      method="post" enctype="multipart/form-data">

Get a QuickQuote

Product:            <select id="product-data" name="ddl_product">
<option value="">Select a product...</option>
<option value="Luxury">Luxury Lawn</option>
<option value="Lush">Lush Lawn</option>
<option value="Natural">Natural Lawn</option>
<option value="RG Basic">RG Basic</option>
<option value="------">-------</option>
<option value="Multiple">Multiple, please state below</option>
</select>

Width: <input type="text" name="Width" id="Width" />

Length: <input type="text" name="Length" id="Length" />

Ground Conditions
<textarea style="width:450px" name="Ground Conditions"></textarea>

Comments and Requests
  <textarea style="width:450px" name="Ground Conditions3"></textarea>

  Area Photos

<input name="Image 1" type="file" />

<input name="Image 1" type="file" />

<input name="Image 1" type="file" />

<input name="Image 1" type="file" />

<input name="Image 1" type="file" />

Your Garden Plan

<input name="Image 1" type="file" />

Phone Number

  <input type="text" name="phone" id="phone">

<textfield style="width:450px" name="phonenumber"></textfield>

Post Code

  <input type="text" name="phone" id="phone">

<textfield style="width:450px" name="phonenumber"></textfield>

<button id="button-buy-now" name="btn_buy_now" type="submit">        Get a Quote</button>

<input type="hidden" name="redirect"    value="http://www.sgsgrass.co.uk/submitconfirmation.php" />
</form>


text:
Q: Xcode - many windows I have a confusing problem in Xcode.
The problem occures only in a single project and started about few days ago (don't know what caused it).
I need to see many parts of code in different files to code something, so I just double click a file from the Xcode's sidebar and it opens in a new Xcode window (a little bit simplified then the main window).
When I do the same with the next file, the next window is shown (so I should have three windows now), but in this project it's not. The previous window is replaced with the title and content on new file.
It's really annoying - I even can't see at once the localization file, and the both .h and .m file of the class I'm working on.
Does anyone knows a solution? I repeat - it's only in this project - in the other project it works fine.
I have the 3.2.5 version, but it was present in previous as well.

A: Once you open the new window click on the group/ungroup button at the right hand top.  This will solve your problem.


text:
Q: PG::SyntaxError at / ERROR: syntax error at or near ")" Rails I am getting this error some time and some time not. That is strange.

ERROR:  syntax error at or near ")" LINE 1: SELECT  locations.*, () as
  distance FROM "locations"  ORDER ...

In line
nearby_locations.includes(:events).each do |location|

In my Dashboard controller
 def home
    nearby_locations = Location.with_distance_to(remote_ip).order('distance').limit(10)
    @events  = []
    nearby_locations.includes(:events).each do |location|
        @events += location.events.where("publish = true")
    end
end

In my Location.rb model
geocoded_by :address
extend Geocoder::Model::ActiveRecord
  reverse_geocoded_by :latitude, :longitude

  scope :with_distance_to, ->(point) { select("#{table_name}.*").select("(#{distance_from_sql(point)}) as distance") }

A: To stop the errors, you should validate that remote_ip in your dashboard_controller exists before using the scope you have defined on Location.
 def home
  unless remote_ip.blank?
    nearby_locations = Location.with_distance_to(remote_ip).order('distance').limit(10)
    @events  = []
    nearby_locations.includes(:events).each do |location|
        @events += location.events.where("publish = true")
    end
  end
end

To really understand the problem, find out how remote_ip is blank in the first place and fix that issue.


text:
Q: LibGdx `ShapeRenderer` on Android does not honor alpha channel I have a program where I am drawing some lines on each frame using ShapeRenderer. On each frame I want to draw on top the previous, faded by a amount, frame.
So what I am doing is first draw a black rectangle with an alpha less than 1 and then draw the current frame. On desktop it works well and the result is something like this

But on Android it does not work. It renders like this.

I tried enabling blending before drawing rectangle
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);

Also tried seting the alpha channel to 8 bits in AndroidApplicationConfiguration (config.a = 8)
Nothing of these worked. What else can I try?
Also is there a better way to achieve what I want?
Screen code
package com.waterpaw.trochoids.screen;

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

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.waterpaw.trochoids.Trochoid;
import com.waterpaw.trochoids.Trochoids;

public class GameScreen extends BaseScreen {
    private ShapeRenderer sr;

    private ScreenViewport viewport;

    private List<Trochoid> trochoids = new ArrayList<Trochoid>();

    public GameScreen(Trochoids game) {
        super(game);

        viewport = new ScreenViewport();
        Gdx.input.setInputProcessor(this);
        sr = new ShapeRenderer();
    }

    private int resized;

    @Override
    public void resize(int width, int height) {
        viewport.update(width, height);

        trochoids.clear();
        trochoids.add(new Trochoid(viewport.getWorldWidth(), viewport.getWorldHeight()));
        resized = 2;
    }

    @Override
    public void render(float delta) {
        if(resized-- > 0) {
            Gdx.gl.glClearColor(0f, 0f, 0f, 0f);
            Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        }
        processInput();

        if(!trochoids.get(0).isPaused()) {
            updateTrochoids();
            renderTrochoids();
        }
    }

    private void processInput() {
        if(Gdx.input.isKeyJustPressed(Keys.P)) {
            if(trochoids.get(0).isPaused()) {
                trochoids.get(0).unpause();
            } else {
                trochoids.get(0).pause();
            }
        } else if(Gdx.input.isKeyJustPressed(Keys.SPACE)) {
            touchDown(0, 0, 0, 0);
        }
    }

    @Override
    public void dispose() {
        sr.dispose();
    }

    @Override
    public boolean touchDown(int x, int y, int pointer, int button) {
        trochoids.get(0).initialize();
        return true;
    }

    public void renderTrochoids() {
        sr.setProjectionMatrix(viewport.getCamera().combined);

        float w = viewport.getWorldWidth();
        float h = viewport.getWorldHeight();
        sr.setColor(0, 0, 0, 0.1f);
        sr.begin(ShapeRenderer.ShapeType.Filled);
        sr.rect(-w / 2, -h / 2, w, h);
        sr.end();

        sr.begin(ShapeRenderer.ShapeType.Line);
        for(int i = 0; i < trochoids.size(); i++) {
            trochoids.get(i).render(sr);
        }
        sr.end();
    }

    private void updateTrochoids() {
        for(int i = 0; i < trochoids.size(); i++) {
            trochoids.get(i).update();
        }
    }
}

A: LibGDX uses double buffering on Android, so your technique won't work. Draw to a FrameBuffer so you can ensure your previous drawing is not cleared every other frame.  Then draw the FrameBuffer's color texture to the screen on every frame.


text:
Q: Java - Set half of a JFrame to a specific color Im trying to set the horizontal half of the JFrame to display the color that the cursor is on.
This is what I got so far.
enter code here
package finalproject;

import java.awt.Canvas;
import javax.swing.JFrame;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.PointerInfo;
import javax.swing.JLabel;
import javax.swing.*;
import java.awt.event.MouseMotionListener;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.*;
public class FinalProject {
    public static void main(String[] args) throws AWTException {
        JFrame frame = new JFrame();
        JLabel rgbLabel = new JLabel();
        rgbLabel.setVerticalAlignment(SwingConstants.NORTH);
        rgbLabel.setHorizontalAlignment(SwingConstants.CENTER);
        frame.setLocationRelativeTo(null);
        frame.add(rgbLabel);
        rgbLabel.setAlignmentX(50);
        rgbLabel.setAlignmentY(10);
        rgbLabel.setVisible(true);
        frame.setLocation(650, 350);
        frame.setVisible(true);
        frame.pack();
        frame.setTitle(display.TITLE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(display.WIDTH, display.HEIGHT);
        frame.setResizable(true);
        frame.setVisible(true);
        while (true){
            PointerInfo cursorLocation = MouseInfo.getPointerInfo();
            Point position = cursorLocation.getLocation();
            int x = (int)position.getX();
            int y = (int)position.getY();
            Robot robot = new Robot();
            Color pixelColor = robot.getPixelColor(x, y);
            int colorRed = pixelColor.getRed();
            int colorGreen = pixelColor.getGreen();
            int colorBlue = pixelColor.getBlue();
            rgbLabel.setText("Red: " + colorRed + " Green: " + colorGreen + " Blue: "     + colorBlue + "\n" );

            }
        }
    public static class display {
        public static final int WIDTH = 250;
        public static final int HEIGHT = 135;
        public static final String TITLE = "Colorblind Assistant";
    }
}

I know that putting
frame.getContantPane().setBackground(pixelColor);

under the while loop will change the whole frame to the color, but I only need the bottom half of the frame to be that color.
Some help would be appreciated.
Thank you.

A: *

*Use a MouseListener, not a while (true) that will tie up the Swing event thread.

*Get all that code out of the main method and into a proper class. The main method should do nothing other than set your program in motion.

*Have your JFrame hold two JPanels in a GridLayout, and in the background of one of the JPanels be set by the MouseListener.


text:
Q: Use wildcard with os.path.isfile() I'd like to check if there are any .rar files in a directory. It doesn't need to be recursive.
Using wildcard with os.path.isfile() was my best guess, but it doesn't work. What can I do then?

A: Wildcards are expanded by shell and hence you can not use it with os.path.isfile()
If you want to use wildcards, you could use popen with shell = True or os.system()
>>> import os
>>> os.system('ls')
aliases.sh
default_bashprofile     networkhelpers          projecthelper.old           pythonhelpers           virtualenvwrapper_bashrc
0
>>> os.system('ls *.old')
projecthelper.old
0

You could get the same effect with glob module too.
>>> import glob
>>> glob.glob('*.old')
['projecthelper.old']
>>>

A: If you just care about whether at least one file exists and you don't want a list of the files:
import glob
import os

def check_for_files(filepath):
    for filepath_object in glob.glob(filepath):
        if os.path.isfile(filepath_object):
            return True

    return False

A: Without using os.path.isfile() you won't know whether the results returned by glob() are files or subdirectories, so try something like this instead:
import fnmatch
import os

def find_files(base, pattern):
    '''Return list of files matching pattern in base folder.'''
    return [n for n in fnmatch.filter(os.listdir(base), pattern) if
        os.path.isfile(os.path.join(base, n))]

rar_files = find_files('somedir', '*.rar')

You could also just filter the results returned by glob() if you like, and that has the advantage of doing a few extra things relating to unicode and the like.  Check the source in glob.py if it matters.
[n for n in glob(pattern) if os.path.isfile(n)]

A: glob is what you need.
>>> import glob
>>> glob.glob('*.rar')   # all rar files within the directory, in this case the current working one

os.path.isfile() returns True if a path is an existing regular file. So that is used for checking whether a file already exists and doesn't support wildcards. glob does.

A: import os
[x for x in os.listdir("your_directory") if len(x) >= 4 and  x[-4:] == ".rar"]

A: to display full path and filter based on extension,
import os
onlyfiles = [f for f in os.listdir(file) if len(f) >= 5 and  f[-5:] == ".json" and isfile(join(file, f))]

A: iglob is better than glob here since you do not actually want the full list of rar files, but just want to check that one rar exists

A: Just another method to get the job done using subprocess.
import subprocess

try:
        q = subprocess.check_output('ls')
        if ".rar" in q:
             print "Rar exists"
except subprocess.CalledProcessError as e:
        print e.output

Reference : https://docs.python.org/2/library/subprocess.html#subprocess.check_output


text:
Q: Is it possible to mult-line comment in Kusto? I can definitely use "//" to comment every line, but was wondering if there was a way to do avoid doing this.

A: The visual studio keyboard shortcut for commenting (Ctrl+K+C) or uncommenting (Ctrl+K+U) multiple lines can be useful if you want to do it quickly. I have tested it on Web UI. Alternatively, if you are a Resharper user, you can also use Ctrl+/

A: to date (2020-07-10) - that's not supported.
feature requests can be raised/upvoted @ https://aka.ms/adx.uservoice


text:
Q: Keep the conditional formatting on pasting value For a particular column I have conditional formatting to fill cell colour when there is value change.
When pasting a value from different column, conditional formatting is removed.
How do I keep the conditional formatting?

A: You cannot prevent that the conditional formatting is overwritten (and therefore deleted on the destination cell). Workaround is that you immediately reassign the formatting. You can use the Worksheet.Change-event that is fired when the value of a cell is changed.
The following code is an example, try if it helps you. Put the code into the Worksheet-Module of the sheet and adapt it to the range (column) with the formatting:
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim formattedRange As Range
    Set formattedRange = Range("E:E")
    If Intersect(Target, formattedRange) Is Nothing Then Exit Sub

    Dim fc As FormatCondition, i As Integer
    For i = 1 To formattedRange.FormatConditions.Count
        Set fc = formattedRange.FormatConditions(i)
        fc.ModifyAppliesToRange formattedRange
    Next
End Sub

Update
When the pasted cells have already conditional formatting, this formatting will get copied to the destination and the code will apply it to the whole formattedRange. I updated the routine, the following logic deletes all formatting that was introduced by the modified cells. Note that you need to run the loop backwards because of the deletion.
Private Sub Worksheet_Change(ByVal Target As Range)

    Dim formattedRange As Range
    Set formattedRange = Range("E:E")
    If Intersect(Target, formattedRange) Is Nothing Then Exit Sub

    Dim fc As FormatCondition, i As Integer
    For i = formattedRange.FormatConditions.Count To 1 Step -1
        Set fc = formattedRange.FormatConditions(i)
        If fc.AppliesTo.Address <> formattedRange.Address _
           And Not Intersect(Target, fc.AppliesTo) Is Nothing Then
            fc.Delete
        Else
            fc.ModifyAppliesToRange formattedRange
        End If
    Next
End Sub


text:
Q: How to put Nav, Title and Image in one line? My end result is to have my nav on both the right and left, with the the title between them with an image between the title. I use a-hrefs in a div as the links with uls and lis as my subnavs.
What are the options to keep it all on one line and the image centered vertically with the text.
Example:

      LINK
      LINK

TITLE

TITLE

      LINK
      LINK

I have tried to slip the div up ending the first part of the div where the
 goes, then picking it back up after the second title
.
Example:

      LINK
      LINK

TITLE

TITLE

      LINK
      LINK

A: Although that is not the best practice as you have done it in your example, but for the sake of simple answer you can just add CSS vertical-align: middle to title/logo wrapper. Like this:
HTML part:

  Link
   Link
   Link

Your title  Your title

   Link
   Link
   Link

And CSS:
.menu { text-align: center; }
.menu a, .menu div { display: inline-block; }
.menu a { margin: 0px 5px; }
.menu div { font-size: 20px; font-weight: bold; margin: 0px 20px; vertical-align:middle}

Here is sample demo in codepen - http://codepen.io/anon/pen/JdzvgK
And, btw - YES, this is valid code - you can safely put IMG inside H1. Even w3 themselfs is using this practice in their header - http://www.w3.org/ :)

A: try this way

     LINK
     LINK

TITLE

TITLE

     LINK
     LINK

A: A pretty common practice is to use a ul structure. It give you some nice structure.
I gave an outline here:
How to style more than one ul (it is for a nav)
And also provided this link (there are lot of nav oriented example on the internet):
http://www.noupe.com/essentials/freebies-tools-templates/100-great-css-menu-tutorials.html


text:
Q: Parse an environment variable in a Windows BAT script I'm trying to create a simple application launcher for the software Nuke that puts the path together by evaluating an environment variable.  The value of the variable is used in two ways.  First it's used as-is.  The second time I need to split the variable and use the first half.
The env variable set for the system:

NUKE_VERSION = 10.0v5

The path to the application:

C:\Program Files\Nuke10.0v5\Nuke10.0.exe

The code below works fine on the cmd prompt:
FOR /F "delims=v tokens=1" %i IN ("%NUKE_VERSION%") DO set NUKE_MAJOR=%i
"C:\Program Files\Nuke%NUKE_VERSION%\Nuke%NUKE_MAJOR%.exe"

But when I run a .bat with the code, it returns this error:

NUKE_VERSIONi was unexpected at this time.

Any insights into what is going on?  I could just do this in python, but something this simple I shouldn't have to, right?  Many thanks in advance.

A: In a CMD Window a FOR-LOOP uses a single % sign as you have listed in your question.
In a Batch file a FOR-LOOP uses a double %% sign.
FOR /F "delims=v tokens=1" %%i IN ("%NUKE_VERSION%") DO set NUKE_MAJOR=%%i


text:
Q: Ruby exclamation mark -printing next line TENANT_NAME=gets.chomp('/\p{Alnum}/')

$first = TENANT_NAME.slice(0,1).capitalize

$second = TENANT_NAME.slice(1..-1)

EXPORT_PASSWORD="Export-"+ $first + $second + "!"

puts EXPORT_PASSWORD

I want to print EXPORT_PASSWORD in one-line, but when i am trying to print it prints ! from another line. I am using Ruby
output:
devi123kumari
Export-Devi123kumari
!

A: >TENANT_NAME=gets.chomp('/\p{Alnum}/')
somename
TENANT_NAME
=> "somename\n"

see you are getting \n here which is shifting your ! to second line.
>TENANT_NAME=gets.chomp
somename
TENANT_NAME
=> "somename"

now you wont get the extra line.

A: Try:
EXPORT_PASSWORD="Export-"+ $first + $second.chomp + "!"'

This is because if you check the value of $second, it contains trailing \n.
Also in Ruby prepending $ to variable names is not a standard practice.

A: chomp removes the given argument from the end of the string or carriage return characters (i.e. \n, \r, and \r\n) if no argument is given:
"hello".chomp                #=> "hello"
"hello\n".chomp              #=> "hello"
"hello".chomp("llo")         #=> "he"

Your code removes '/\p{Alnum}/' (that's a string, not a regexp) from the end of a string:
'hello/\p{Alnum}/'.chomp('/\p{Alnum}/') #=> "hello"

This is probably not what you want. Just use chomp without an argument.


text:
Q: How to solve a php strtotime language issue not sincronyzed with server bash language I have a server which is running a German local language for Bash. When I try to change maillog time
in this server in Unix timestamp using ..
$time1="Mai-05-20 17:22:36";
$unix_time=strtotime($time1);

$unix_time returns empty, I think because bash is using German but PHP is running english (?).
How can I set the php script to run in the same language of Bash local language ?

A: From docs (emphasis mine):

strtotime — Parse about any English textual datetime description into a Unix timestamp

In case you don't need the full power of strtotime() (after all, you seem to be parsing logs from one single program) you can try IntlDateFormatter::parse(). Here's a quick and dirty demo:
$fmt = new IntlDateFormatter('de_DE', null, null);
$fmt->setPattern('M-dd-yy hh:mm:ss');
$log_time = "Mai-05-20 17:22:36";
$unix_time = $fmt->parse($log_time);
echo date('r', $unix_time);

Tue, 05 May 2020 17:22:36 +0200

Note that a Unix time is a fixed moment in time, thus unaffected by time zones. I get +0200 when casting to local time because my PHP default time zone is currently CEST.


text:
Q: Once per browser session cookie i have this popup code that activates once the user closes the browser window. The problem is that i have pics on my site so every time a surfer clicks on a picture it is like he's taken away from the site and the popup is shown.
i'd like to make this popup to show just once per browser session.
var sync = true;
window.onbeforeunload = doSync;

function doSync() {
if (sync == true) {
window.open('myurl', '_blank');
}
else {
return;
}
}

So... what code should I place to make a once-per-browser-seession cookie?
Thanks in advance!

A: Cookies are for storing data you want sent to the server with every REQUEST so don't use cookies at all for this, use sessionStorage
var sync = true;
window.onbeforeunload = doSync;

function doSync() {
    if (sync && !window.sessionStorage.getItem('popupShown')) {
        window.sessionStorage.setItem('popupShown', 1);
        window.open('myurl', '_blank');
    }
}

Where popupShown is the flag in sessionStorage designating that it's happened before.


text:
Q: How do I remove the comma from a CSV output? I'm outputting some results to a CSV in two columns so that I can create a basic graph. Due to the CSV format the values in my first column display as "10," I was wondering how I can remove the comma to make my data look neat.
Would I have to separate the data into columns in a different way or is their a way you can get the comma to not write to the CSV file?
    FileWriter wr = new FileWriter("Results.csv");
    wr.append(Integer.toString(r.length) + ", ");
    wr.append(Long.toString(execution_time));
    wr.append('\n');
    wr.flush();
    wr.close();

A: FileWriter wr = new FileWriter("Results.csv");
wr.append(Integer.toString(r.length) +" ");
wr.append(Long.toString(execution_time));
wr.append('\n');
wr.flush();
wr.close();

this output a space instead of comma

A: Open this in Excel, so the CSV is opened as a xml file. Use this command removing the extra spaces:
    FileWriter wr = new FileWriter("Results.csv");
    wr.append(Integer.toString(r.length) + ",");
    wr.append(Long.toString(execution_time));
    wr.append('\n');
    wr.flush();
    wr.close();

A: You might try to use tab as separator:
FileWriter wr = new FileWriter("Results.csv");
wr.append(Integer.toString(r.length) +"\t");
wr.append(Long.toString(execution_time));
wr.append('\n');
wr.flush();
wr.close();


text:
Q: How to reorder fill factor within the x-axis? I would like to reorder the groupings on the x-axis in a particular way, so that the order of my "Sites" at each "Month" is BTH, FOX, MEF, DUR. As of right now, the Sites are ordered alphabetically.
Site Month N flux N flux_SE
BTH May 0.047 0.009
BTH Jun 0.974 0.14
BTH Jul 0.698 0.124
BTH Aug 0.112 0.017
BTH Sep 0.107 0.019
BTH Oct 0.234 0.018
FOX May 0.072 0.02
FOX Jun 0.562 0.094
FOX Jul 0.250 0.056
FOX Aug 0.097 0.017
FOX Sep 0.105 0.015
FOX Oct 0.409 0.078
MEF May 0.072 0.025
MEF Jun 0.434 0.167
MEF Jul 0.224 0.058
MEF Aug 0.132 0.047
MEF Sep 0.073 0.024
MEF Oct 0.271 0.08
DUR May 0.039 0.01
DUR Jun 0.342 0.155
DUR Jul 0.175 0.044
DUR Aug 0.065 0.018
DUR Sep 0.061 0.021
DUR Oct 0.279 0.067

flux$Month = factor(N_flux$Month, levels = month.abb)  #This will get the motnhs in chronological order using 3-letter month abbreviations

ggplot(N_flux, aes(x=Month, y=N.flux, fill=factor(Site), reorder(month,month.name))) + #this code makes a 4-panel bar graph by site
  geom_bar(stat="identity", colour="black",position=position_dodge(.9)) +
  scale_y_continuous(expand = c(0,0), limits = c(0,1.5), breaks = seq(0,1.5, by=.2)) +
  ylab(expression("Nitrogen flux (g N m"*{}^-2*")")) + xlab("Month") + labs(fill = "Site") +
  theme_bw() +
  theme(panel.border = element_rect(color = "black", fill = NA),
        strip.text.x = element_text(colour = 'black', size = 15, face = "bold"),
        axis.text = element_text(colour = "black"),
        panel.grid.major = element_blank(), panel.grid.minor = element_blank(),
        legend.position = c(0.9,0.82), legend.text = element_text(size = 9),
        legend.key.size = unit(.55, "cm")) +
  scale_fill_manual(values = c("black", "grey70","grey50", "white")) +
  geom_errorbar(aes(ymin=N.flux, ymax=N.flux+N.flux_SE), size=0.5,
                width=.25,position=position_dodge(.9))

Figure I have so far...

A: You just need to set the column as a factor, much like you did for Month, and specify the levels. Add this line.
N_flux$Site = factor(N_flux$Site, levels = c("BTH", "FOX", "MEF", "DUR"))
Then, you can change the first line of your ggplot command.
ggplot(N_flux, aes(x=Month, y=N.flux, fill=Site, reorder(month,month.name))) +
Since it's already a factor, no need to create a factor again.


text:
Q: Can't migrate:fresh -seed errno: 150 "Foreign key constraint is incorrectly formed" Yet here I am with another errno 150. Tried most of everything around here with no luck now I need a expert who might see the mistake within my code.
When trying to php artisan migrate:fresh --seed
Getting error 1005-150
SQLSTATE[HY000]: General error: 1005 Can't create table `webmall`.`order_items` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `order_items` add constraint `order_items_product_id_foreign` foreign key (`product_id`) references `products` (`id`) on delete cascade)

order_items migration:
Schema::create('order_items', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('order_id');
            $table->unsignedBigInteger('product_id');

            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');

            $table->float('price');
            $table->integer('quantity');

            $table->timestamps();
        });

Databaseseeder.php
public function run()
    {
        // $this->call(UserSeeder::class);
        $this->call(ProductSeeder::class);
        $this->call(DataTypesTableSeeder::class);
        $this->call(DataRowsTableSeeder::class);
        $this->call(CategoriesTableSeeder::class);
        $this->call(PostsTableSeeder::class);
        $this->call(PagesTableSeeder::class);
        $this->call(MenusTableSeeder::class);
        $this->call(MenuItemsTableSeeder::class);
        $this->call(RolesTableSeeder::class);
        $this->call(UserRolesTableSeeder::class);
        $this->call(PermissionsTableSeeder::class);
        $this->call(PermissionRoleTableSeeder::class);
        $this->call(SettingsTableSeeder::class);

        $this->call(UsersTableSeeder::class);

thank you as usuall!

A: This is because your foreign key has a different type from the primary key it references.
It is very conventional to use bigIncrements as id/primary key column so if you're referencing it you must use bigInteger
So your migration should look like
Schema::create('order_items', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('order_id');
        $table->BigInteger('product_id');

        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');

        $table->float('price');
        $table->integer('quantity');

        $table->timestamps();
    });


text:
Q: Checking conflicting data with SELECT and IF statements in a procedure I am using the SELECT statement to select the conflicting treatments from the prescription table that i have and the i am using an IF statement to check the selected data against the data that i am entering when running the procedure. What i expect this procedure to do is disallow the same client to book conflicting treatments on the same day. But when i run my procedure i am getting an error "exact fetch returns more than requested number of rows". If i run the select statement on its own, it works as explained above. Here is my procedure:
CREATE OR REPLACE PROCEDURE FPRESC (
    FP_ID VARCHAR2,
    FTREAT_ID VARCHAR2,
    FCLIENT_ID VARCHAR2,
    FDOC_ID VARCHAR2,
    FP_DATE DATE)
AS
   V_CLIENT_ID PRESCRIPTION.CLIENT_ID%TYPE;
   V_CONFLICT TREATMENTS.CONFLICT%TYPE;
   V_P_DATE PRESCRIPTION.P_DATE%TYPE;
   V_TREAT_ID TREATMENTS.TREAT_ID%TYPE;
BEGIN
    SELECT P.CLIENT_ID, T.CONFLICT, P.P_DATE, T.TREAT_ID
    INTO V_CLIENT_ID, V_CONFLICT, V_P_DATE, V_TREAT_ID
    FROM PRESCRIPTION P, TREATMENTS T
    WHERE P.TREAT_ID=T.TREAT_ID
    AND T.CONFLICT IS NOT NULL;

    IF FP_DATE = V_P_DATE AND FCLIENT_ID = V_CLIENT_ID AND FTREAT_ID = V_TREAT_ID THEN
         DBMS_OUTPUT.PUT_LINE('CONFLICT');
    ELSE
         INSERT INTO PRESCRIPTION (P_ID, TREAT_ID, CLIENT_ID, DOC_ID, P_DATE)
         VALUES (FP_ID, FTREAT_ID, FCLIENT_ID, FDOC_ID, FP_DATE);
    END IF;
END FPRESC;
/

and an example of the data i am trying to enter for new prescription (note: this data is conflicting, so it should throw an error when entered):
 EXEC FPRESC ('P00011', 'T016', 'C00017', 'D006', '28-NOV-14');

Some insight would be much appreciated, if possible

A: "exact fetch returns more than requested number of rows" is a pretty clear message, and probably refers to your select statement. Using select ... into your query must return exactly one row, because you only specify one set of variables. This message suggests that your query returns more than one row.
I think the best solution would be to do the checks in the query itself. Then you can return wether or not the query matches anything (in which case there is a conflict). This query will always return exactly one record with a 1 or 0 indicated a conflict or not, even if the subquery that does the checks returns more than 1 conflict.
SELECT
    CASE WHEN EXISTS
        (SELECT 'X'
        FROM
          PRESCRIPTION P
          INNER JOIN TREATMENTS T ON T.TREAT_ID = P.TREAT_ID
        WHERE
          FP_DATE = P.P_DATE
          AND FCLIENT_ID = P.CLIENT_ID
          AND FTREAT_ID = T.TREAT_ID
          AND T.CONFLICT IS NOT NULL) THEN
        1
    ELSE
        0
    END
INTO
    V_EXISTS
FROM DUAL;

IF V_EXISTS = 1 THEN
    RAISE_APPLICATION_ERROR(-20000, 'Conflict'); -- Actual exception, if you like
ELSE
    INSERT INTO PRESCRIPTION (P_ID, TREAT_ID, CLIENT_ID, DOC_ID, P_DATE)
         VALUES (FP_ID, FTREAT_ID, FCLIENT_ID, FDOC_ID, FP_DATE);
END IF;

By the way, if you need to read more than one row from a query, you can either open it as a cursor, to process it one by one. Use a for loop for easy access.
Or you can use bulk collect into to read all the data into a single table-like variable.


text:
Q: How to I get the name of a program in Java I'm writing a Java program and want to be able to get the name of program (meaning the .jar program that is opened to start the application). I have searched around and have been unable to find a method that works for my use case. Anyone have a way to do this?
Thanks!


text:
Q: What is the plural form of "the name of which"? Consider we have a sentence:

I have a box named "A".

rewritten as such:

I have a box, the name of which is "A".

How should we rewrite the sentence if now there is more than one "item"?

I have three boxes, named "A", "B", and "C".

Is the sentence below grammatical? :

I have three boxes, the names of them are "A", "B", and "C".

A: In your last sentence, you should replace "them" with "which"; so it becomes,

I have three boxes, the names of which are A, B and C.

Or, you could simply say,

*

*I have three boxes, namely A, B and C.

*I have three boxes, named A, B and C.

*I have three boxes, A, B and C.

A: It is still "which" in the plural.
The following sentence is grammatical:

I have three boxes, the names of which are "A", "B", and "C".


text:
Q: URL Regex mapping in tornado web server I am using tornado web server for my application.
following is one of the url mapped to a handler.
from publish.handler import PublishHandler, PublishedHandler

URLS = [(r'/public/project/(?P<project>.*?)/?$', PublishHandler),
        (r'/stitchemapp-public/project/(?P<project>.*?)/version/(?P<version>v\d{1,}.*)/image/(?P<image>.*?)/$',
                                                    PublishedHandler),
    ]

All import and call to the handler is happening fine.
But some problem with kwargs being generated from the second url map tuple in the URLS list.
When I do
print kwargs

it prints :
{'project': u'clearsoup', 'version': u'v2/image/project_home_page_v1.jpg'}

But I am expecting:
{'project': u'clearsoup', 'version': u'v2', 'image': 'project_home_page_v1.jpg'}

Where I am doing wrong. I can always write hacks to get the exact info from the kwargs which handler is getting, but that's not the right way.
Kindly  suggest me where I am doing wrong.
Thanks in advance for the help.

A: I know this is very old, but it is as simple as the version regex is using a greedy quantifier.  According to Python's re documentation:
"The '', '+', and '?' qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE <.> is matched against  b , it will match the entire string, and not just . Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE <.*?> will match only ."
So, to fix, replace the .* with .*?.
You used the non-greedy quantifier in the other 2 regexes, so I imagine this was a mistake.