text:
Q: Making calendar in c I wrote a code for printing calendar according to  Gregorian calendar. But I have a problem, I need to calculate the current number of week in order to print my calendar with help of array[5][7]. I need formula or program to find number of week for ex. year:2020 month:4 day:26 and I should find number of week and it's 4. is there any formula ?

A: You have to know the day of week first!
For this use Gauss's algorithm Kraitchik's variation:
https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week
    dayofweek(y, m, d)  /* 1 <= m <= 12,  y > 1752 (in the U.K.) */
    {
        static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
        y -= m < 3;
        int k = (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
        return k == 0 ? 6 : (k-1); // This will return 0 for monday...6 for sunday
    }

Then, your week number will be shifted regarding first day of month:
w = (d - 1 + dayofweek(y, m, 1))/7 + 1;

here a code sample working for me:
#include <stdio.h>
#include <stdint.h>

static const int days[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

static const char* dayofws[] = {"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"};

static int dayofweek(int y, int m, int d)  /* 1 <= m <= 12,  y > 1752 (in the U.K.) */
{
    static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
    y -= m < 3;
    int k = (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
    return k == 0 ? 6 : (k-1); // This will return 0 for monday...6 for sunday
}

void main (void)
{
    int y = 2020;

    for (int m = 1; m <= 12; m++)
    {
        for (int d = 1; d <= days[m]; d++)
        {
            int w = (d - 1 + dayofweek(y, m, 1))/7 + 1;
            printf("%d    ", dayofweek(y, m, 1));
            printf("%d/%02d/%02d : %d  (%s)\n", y, m, d, w, dayofws[dayofweek(y, m, d)]);
        }
        printf("\n");
    }
}

A: Can't you just get the number of days since January 1st, divide this number by 7 and add 1 (so it starts with week 1 and not 0)
For example:
January 17th: 17 / 7 = 2 -> 2+1 = Week 3
For the 7th, 14th, 21st, 28th etc day, you could check the remainder. If remainder is 0, week should be week-1. So day 14 is week 2 and not week 3.


text:
Q: Find the Most common term in Scikit-learn classifier I'm following the example in Scikit learn docs where CountVectorizer is used on some dataset.
Question: count_vect.vocabulary_.viewitems() lists all the terms and their frequencies. How do you sort them by the number of occurances?
sorted( count_vect.vocabulary_.viewitems() ) does not seem to work.

A: vocabulary_.viewitems() does not in fact list the terms and their frequencies, instead its a mapping from terms to their indexes. The frequencies (per document) are returned by the fit_transform method, which returns a sparse (coo) matrix, where the rows are documents and columns the words (with column indexes mapped to words via vocabulary_). You can get the total frequencies for example by
matrix = count_vect.fit_transform(doc_list)
freqs = zip(count_vect.get_feature_names(), matrix.sum(axis=0))
# sort from largest to smallest
print sorted(freqs, key=lambda x: -x[1])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как указать Gson`у, чтобы он использовал именно мой сериализатор/десериализатор? Написал собственный конвертер, зарегистрировал в GsonBuilder'е. Но отрабатывает только сериализатор и только в одном "rest-методе".
То есть, он работает, но работает сериализация и десериализация по умолчанию, а мой конвертер работает только при сериализации одного метода, когда получаю список объектов, в остальных случаях игнорируется. В логах ошибок нет, тихо и не правильно работает, не знаю уже что делать. Сталкивался ли кто-нибудь с таким, что не так идет?
Наверно это лишнее, но всё же распишу подробнее.
Провайдер для gson'а.
Класс GsonJsonProvider.java
@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class GsonJsonProvider implements MessageBodyReader<Object>, MessageBodyWriter<Object>{

//---
//инициализация gson и его настроек
private Gson getGson(){
    if (gson == null) {
        gson = new GsonBuilder()
                .registerTypeAdapter(UUID.class, new UUIDConverter())
                .registerTypeAdapter(LocalDateTime.class, new DateTimeConverter())
                .registerTypeAdapter(Note.class, new NoteConverter())
                .setPrettyPrinting()
                .serializeNulls()
                .setLenient()
                .create();

        System.err.println("Gson Initialization");
    }
    System.err.println("Gson work");
    return gson;
}
//---
//метод getGson вызывается в этих методах и больше нигде
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    InputStreamReader streamReader = new InputStreamReader(entityStream, UTF_8);
    try {
        Type jsonType;
        if (type.equals(genericType)) {
            jsonType = type;
        } else {
            jsonType = genericType;
        }
        return getGson().fromJson(streamReader, jsonType);
    } finally {
        streamReader.close();
    }
}

//----
public void writeTo(Object object, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8);
    try {
        Type jsonType;
        if (type.equals(genericType)) {
            jsonType = type;
        } else {
            jsonType = genericType;
        }
        getGson().toJson(object, jsonType, writer);
    } finally {
        writer.close();
    }
}

Класс модель Note.java
@Entity
@Table(name = "notes")
@NamedQuery(name = "Note.getAll", query = "SELECT n FROM Note n ORDER BY n.id ASC")
public class Note extends Model{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_post")
private int id;
@Type(type = "org.hibernate.type.PostgresUUIDType")
private UUID uuid;
private String title;
private String text;
private String password;
private LocalDateTime date;
private int status;
//---

Класс конвертер NoteConverter.java
@Override
public JsonElement serialize(Note note, Type type, JsonSerializationContext context) {

    JsonObject result = new JsonObject();
    result.add("uuid", context.serialize(note.getUuid()));
    result.addProperty("title", note.getTitle());
    result.addProperty("text", note.getText());
    result.addProperty("password", note.getPassword() != null ? note.getPassword() : "null_password");
    result.add("date", context.serialize(note.getDate()));
    result.addProperty("status", note.getStatus());

    return result;
}

и
@Override
public Note deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException {

    JsonObject jsonObject = jsonElement.getAsJsonObject();

    Note note = new Note();
    note.setUuid(context.deserialize(jsonObject.get("uuid"), UUID.class));
    note.setTitle(jsonObject.get("title").getAsString());
    note.setText(jsonObject.get("text").getAsString());
    note.setPassword(jsonObject.get("password").getAsString());
    note.setDate(context.deserialize(jsonObject.get("date"), LocalDateTime.class));
    note.setStatus(jsonObject.get("status").getAsInt());

    return note;
}

Класс NoteResource.java
//вот здесь мой сериализатор отрабатывает,
//отдаёт список объектов, где поле date в миллисекундах.
//в логах светится "Gson work" тот, что в GsonJsonProvider.java
@GET
@Produces("application/json; charset=UTF-8")
public Response getAll(){
    List<Note> noteList = dao.getAll("Note.getAll", noteClass);
    return Response.ok(noteList).build();
}

//а здесь, работает сериализация по умолчанию
//и в логах "Gson work" не выходит, то есть он вообще не при делах, почему???
@GET
@Path("/{id}")
@Produces("application/json; charset=UTF-8")
public Response getNote(@PathParam("id") int id){
    Note note = dao.getById(id, noteClass);
    return Response.ok(note).build();
}

//и здесь тоже самое, сам объект note приходит
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addNote(Note note){
    StatusResponse response = new StatusResponse();
    if (note == null) { //эту проверку проходит
        System.err.println("Added, note null!");
        return Response.status(Response.Status.BAD_REQUEST).entity(response).build();
    }
    System.err.println("Added, note title: " + note.getTitle());
    System.err.println("Added, uuid: " + note.getUuid());
//а здесь uuid = null, так как не знает как десериализовывать тип UUID
//------

UPDATE
Добавил параметризацию в класс GsonJsonProvider.java
public class GsonJsonProvider<T> implements MessageBodyReader<T>, MessageBodyWriter<T> {
//...

Метод readFrom
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    InputStreamReader streamReader = new InputStreamReader(entityStream, UTF_8);
    try {
        //с genericType так же не работает
        return getGson().fromJson(streamReader, type);
    } finally {
        streamReader.close();
    }
}

Метод writeTo
public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    OutputStreamWriter writer = new OutputStreamWriter(entityStream, UTF_8);
    try {
        //если указывать type вместо genericType, то не работает
        getGson().toJson(t, genericType, writer);
    } finally {
        writer.close();
    }
}

//Сериализация работает как надо, только
//если изменить сеттер в модели Note.java
//но тогда вылетает ошибка при десериализации
//java.lang.ClassCastException: java.util.UUID cannot be cast to java.lang.String
public void setUuid(String uuidString) {
    this.uuid = UUID.fromString(uuidString);
}

//а с таким(нормальным) сеттером
//и сер/десериализация не работает (без ошибок в логах)
public void setUuid(UUID uuid) {
    this.uuid = uuid;
}

A: У вас проблема в куске:
if (type.equals(genericType)) {
        jsonType = type;
    } else {
        jsonType = genericType;
    }

У вас на выходе тип всегда будет genericType, то есть адаптер никогда не вызовется, поскольку вы всегда вызываете Gson с дженерик типом.


text:
Q: How do I resize the canvas in Raphael.js? I'm having difficulty resizing the canvas in Raphael.js. I thought I could simply use:
var paper = Raphael("paper", 100, 100);

and this would create a canvas using the ID "paper" with a width and height of 100 pixels. However when I try this the canvas doesn't initialize with these settings. I'm using some of the free icons on the Raphael.js website and I was wondering how I would change the size of the icons? Do I have to use the transform function as well? If so could somebody please create a jsfiddle example.
Thanks in advance.
Sorry if I haven't explained myself very well, but Raphael.js is completely new to me.
EDIT:
I tried your suggestions, but to no avail. Here's the code I'm working on. Maybe I have a conflict or something. Any ideas?
<!DOCTYPE html>

        <title>Logo Experiment</title>
        <link rel="stylesheet" href="css/960_16_col.css"/>
        <link rel="stylesheet" href="css/stylesheet.css"/>

window.onload = function() {
    var design = Raphael("design");
    design.path("M24.359,18.424l-2.326,1.215c0.708,1.174,1.384,2.281,1.844,3.033l2.043-1.066C25.538,20.822,24.966,19.652,24.359,18.424zM19.143,14.688c0.445,0.84,1.342,2.367,2.274,3.926l2.414-1.261c-0.872-1.769-1.72-3.458-2.087-4.122c-0.896-1.621-1.982-3.108-3.454-5.417c-1.673-2.625-3.462-5.492-4.052-4.947c-1.194,0.384,1.237,4.094,1.876,5.715C16.73,10.147,17.991,12.512,19.143,14.688zM26.457,22.673l-1.961,1.022l1.982,4.598c0,0,0.811,0.684,1.92,0.213c1.104-0.469,0.81-1.706,0.81-1.706L26.457,22.673zM24.35,15.711c0.168,0.339,2.924,5.93,2.924,5.93h1.983v-5.93H24.35zM18.34,15.704h-4.726l-3.424,5.935h11.66C21.559,21.159,18.771,16.479,18.34,15.704zM3.231,21.613l3.437-5.902H2.083v5.93h1.133L3.231,21.613zM15.048,10.145c0-0.93-0.754-1.685-1.685-1.685c-0.661,0-1.231,0.381-1.507,0.936l2.976,1.572C14.97,10.725,15.048,10.444,15.048,10.145zM14.343,12.06l-3.188-1.684L9.62,13.012l3.197,1.689L14.343,12.06zM3.192,26.886l-0.384,1.108v0.299l0.298-0.128l0.725-0.896l2.997-2.354l-3.137-1.651L3.192,26.886zM9.02,14.044l-4.757,8.17l3.23,1.706l4.728-8.186L9.02,14.044z").attr({fill: "#666", stroke: "#000"});

    var build = Raphael("build");
    build.path("M28.537,9.859c-0.473-0.259-1.127-0.252-1.609-0.523c-0.943-0.534-1.186-1.316-1.226-2.475c-2.059-2.215-5.138-4.176-9.424-4.114c-1.162,0.017-2.256-0.035-3.158,0.435c-0.258,0.354-0.004,0.516,0.288,0.599c-0.29,0.138-0.692,0.147-0.626,0.697c2.72-0.383,7.475,0.624,7.116,2.966c-0.08,0.521-0.735,1.076-1.179,1.563c-1.263,1.382-2.599,2.45-3.761,3.667l0.336,0.336c0.742-0.521,1.446-0.785,2.104-0.785c0.707,0,1.121,0.297,1.276,0.433c0.575-0.618,1.166-1.244,1.839-1.853c0.488-0.444,1.047-1.099,1.566-1.178l0.949-0.101c1.156,0.047,1.937,0.29,2.471,1.232c0.27,0.481,0.262,1.139,0.521,1.613c0.175,0.324,0.937,1.218,1.316,1.228c0.294,0.009,0.603-0.199,0.899-0.49l1.033-1.034c0.291-0.294,0.501-0.6,0.492-0.896C29.754,10.801,28.861,10.035,28.537,9.859zM13.021,15.353l-0.741-0.741c-3.139,2.643-6.52,5.738-9.531,8.589c-0.473,0.443-1.452,1.021-1.506,1.539c-0.083,0.781,0.95,1.465,1.506,2c0.556,0.533,1.212,1.602,1.994,1.51c0.509-0.043,1.095-1.029,1.544-1.502c2.255-2.374,4.664-4.976,6.883-7.509c-0.312-0.371-0.498-0.596-0.498-0.596C12.535,18.451,11.779,17.272,13.021,15.353zM20.64,15.643c-0.366-0.318-1.466,0.143-1.777-0.122c-0.311-0.266,0.171-1.259-0.061-1.455c-0.482-0.406-0.77-0.646-0.77-0.646s-0.862-0.829-2.812,0.928L7.44,6.569C7.045,6.173,7.203,4.746,7.203,4.746L3.517,2.646L2.623,3.541l2.1,3.686c0,0,1.428-0.158,1.824,0.237l7.792,7.793c-1.548,1.831-0.895,2.752-0.895,2.752s0.238,0.288,0.646,0.771c0.196,0.23,1.188-0.249,1.455,0.061c0.264,0.312-0.196,1.41,0.12,1.777c2.666,3.064,6.926,7.736,8.125,7.736c0.892,0,2.021-0.724,2.948-1.64c0.925-0.917,1.639-2.055,1.639-2.947C28.377,22.567,23.704,18.309,20.64,15.643z").attr({fill: "#666", stroke: "#000"});

    var deliver = Raphael("deliver");
    deliver.path("M17.078,22.004l-1.758-4.129l-2.007,4.752l-7.519-3.289l0.174,3.905l9.437,4.374l10.909-5.365l-0.149-4.989L17.078,22.004zM29.454,6.619L18.521,3.383l-3.006,2.671l-3.091-2.359L1.546,8.199l3.795,3.048l-3.433,5.302l10.879,4.757l2.53-5.998l2.257,5.308l11.393-5.942l-3.105-4.709L29.454,6.619zM15.277,14.579l-9.059-3.83l9.275-4.101l9.608,3.255L15.277,14.579z").attr({fill: "#666", stroke: "#000"});

    $('.arrow').each(function(i) {
        arrow = Raphael($(this)[0]);
        arrow.path("M10.129,22.186 16.316,15.999 10.129,9.812 13.665,6.276 23.389,15.999 13.665,25.725z").attr({fill: "#666", stroke: "#000"});
    });
};

#design {
    width: 100px;
    height: 100px;
}

A: To answer your exact question in the title, you would use paper.setSize(width, height)
From the Raphael docs:

Your other questions have different answers.
var paper = Raphael("paper", 100, 100); requires that you have some DOM element with the id="paper" already on your page. That DOM element should have width and height enough to hold your canvas (in this case, 100x100). Or, you can leave off the width and the height and it will take on the width and height of the container (very convenient). You can also produce a canvas without a DOM element by putting in all four dimensions, such as var paper = Raphael(0, 0, 100, 100); to make a 100x100 canvas at the top left of the document.
To resize the Raphael icons, you can use the transform function. For example icon.transform("s2"); to make it twice as large.
This fiddle shows how to create a Raphael canvas and put the pencil icon on it, make it yellow, and double-sized. Note that we need to scale around the top left corner (normally it scales around the center) to prevent it from clipping off the top and left of the page.
var pencil = "M25.31,2.872l-3.384-2.127c-0.854-0.536-1.979-0.278-2.517,0.576l-1.334,2.123l6.474,4.066l1.335-2.122C26.42,4.533,26.164,3.407,25.31,2.872zM6.555,21.786l6.474,4.066L23.581,9.054l-6.477-4.067L6.555,21.786zM5.566,26.952l-0.143,3.819l3.379-1.787l3.14-1.658l-6.246-3.925L5.566,26.952z"
var paper = Raphael(0,0,200,200);
var icon = paper.path(pencil).attr({fill: "yellow"}).transform("s2,2,0,0");


text:
Q: Preferences - using media files, images I'm a new developer, so my question maybe too much basic.
I look for example of defining preferences of sound. User can choose what kind of sound will start an application, for example. There can be such a RingtonPreference widjet, so user can choose a sound.
As I know, preferences support the primitive types: Boolean, string, float, long and integer. What way is the best to design preferences: store in entryValues the names if sounds (strings), the address of files from Resourse class (integer), or other way.
Please provide a short example of code.
Thanks in advance!
First of all thank you for the quick and detailed answer!
I want to arrange list of sounds: there must be one "None", list of sounds that contains folder "raw", option to add a new sound from different locations and two buttons: "set" and "cancel". When user touches one item from the list – sound starts to play.
There is a little problem with standard widget that provide android library.  "ListPreference" isn't appropriate because on touch on one of the items – item is chosen and list closes, "there are not buttons set and cancel".
"RingtonPreference" isn't appropriate as well – I didn't succeed to add something to list.
How is possible to build a custom preference layout and that is options that were chosen will be saved as well as on standard widgets. Please provide a short code example. Thanks in advance!

A: I think the best way to store the Resource are by integers. or you could do names.
I think integer is more reliable.
So to use SharedPreference with this you will need to get access to the apps SharedPreference
public class PreferencesDemo extends Activity {

SharedPreferences app_preferences;
private int resourceNumber;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Get the app's shared preferences

   SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);

   resourceNumber = app_preferences.getInt("resourceNumber", 0);

   if(resourceNumber == 0){

   //This means the user hasnt selected a song and you must act accordingly. Or put a resource number where the 0 is do set it to a default song

    }

You will probably want to create a method to put the songs in the SharedPreference such as;
  private void createSongResouces(){

   SharedPreferences.Editor editor = app_preferences.edit();
    //Here you can put as many songs as you want just make sure you call editor.commit(); as i do.

    editor.putInt("resourceNumber", resourceNumber);
    editor.commit(); // Very important
}


text:
Q: Getting return value from angular custom pipe before service return value I am trying to create a custom pipe for getting likes on particular post, it has a service which connects to database and pull all likes related to particular post, but when i try to run in my code, i am getting return value before the getting response from service, i know i should wait for the response but not sure how to do that.. please help me resolve this issue.
HTML page
 {{mainpost | like }}

Service
      getalllikes(post: MainPost): Observable<any> {
    return this.http.post<any>(this.baseUrl + 'GetLikes', post);
  }

Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { MainPost } from '../_models';
import { LikesService } from '../_services';
import { retry } from 'rxjs/operators';

@Pipe({
  name: 'like'
})
export class LikePipe implements PipeTransform {
  postlikes = 0;
  constructor(private likeservice: LikesService) {

  }
   transform(post: MainPost, ...args: any[]): any {
    const UserId = localStorage.getItem('UserId');
    this.getlikes(post);
    if (this.postlikes === 0) {
      return '0 Likes';
      } else {
      return this.postlikes + ' Likes';
      }
  }
   getlikes(post: any) {
    this.likeservice.getalllikes(post).subscribe(data => {
      console.log();
      // likes = data;
      this.postlikes = data;
    }, (err: any) => console.error(err));

  }

}

A: I think that it is a best practice to keep the view logic inside a pipe, you can handle the total amount of likes to each post with the help of Observables, the transform method should be returning Subject<T>:
@Pipe({
  name: 'like'
})
export class LikePipe implements PipeTransform {

  constructor(private likeService: LikeService) {}

  transform(id: number) : Subject<Object> {
    let likeSubject = new Subject<string>();

    this.likeService.getAllLikes(id)
    .subscribe(
      (posts: number) => {
        let message = "";
        if (posts == 0)
          message = "No Likes"
        else
          message = posts.toString() + " Likes"

        likeSubject.next(message);
    });
    return likeSubject;
  }
}

You will have to tell angular to resolve it with the async keyword:
Post1 {{ ( id | like ) | async}}

Post2 {{ ( id2 | like ) | async}}

Here is a full working StackBlitz app with your issue.


text:
Q: Support multiple language fonts in a single TextField in JavaFX I am new to JavaFX, and I was wondering how I can support multiple language fonts (i.e. Chinese, English, Hindi, etc.).
Currently, when I set my TextField to use a font family which support Latin characters in a css, characters from other languages will not render correctly.

This is my css:
@font-face {
    src: url('WorkSans-Regular.ttf');
}
.text-area {
    -fx-font-size: 25;
    -fx-font-family: 'Work Sans';
}

I realised that JavaFX css does not allow for comma sepearated fonts for font stacks and fallback fonts like below:
@font-face {
    src: url('WorkSans-Regular.ttf');
}
@font-face {
    src: url('NotoSansSC-Regular.ttf');
}
.text-area {
    -fx-font-size: 25;
    -fx-font-family: 'Work Sans', 'Noto Sans SC';
}

Is there another way to support typing in multiple languages?
My project requires the user to enter text in multiple languages, and I need to ensure that the fonts are embedded into the .jar so that each user will have the same UI.

A: try this way
    @font-face {
        font-family: 'Work Sans';                  /*  add this line  */
        src: url('WorkSans-Regular.ttf');
    }

    .text-area {
        -fx-font-size: 25;
        -fx-font-family: 'Work Sans';
    }


text:
Q: error when use CommentsResponse callback from android market api on eclipse I use android market api at link:https://code.google.com/p/android-market-api/
Here is my code to get some comment of user on market:
MarketSession session = new MarketSession();
    CommentsRequest commentsRequest = CommentsRequest.newBuilder()
            .setAppId("7065399193137006744").setStartIndex(0)
            .setEntriesCount(10).build();
    session.append(commentsRequest,
            new Callback<Market.CommentsResponse>() {

                public void onResult(ResponseContext arg0,
                        CommentsResponse arg1) {
                    // TODO Auto-generated method stub

                }
            });

    session.flush();

and eclipse alert error at "new Callback() ": The type Request.Callback is not generic; it cannot be parameterized with arguments
and i change to new Callback but has same error. So, anybody can give me a solution?Sory for my bad english,thanks.


text:
Q: Extending methods from Lubin-Tate theory The first lemma in Lubin-Tate theory says the following:

Let $K$ be a local field, $A$ its ring
  of integers, and $f\in A[[T]]$ be such
  that $f(0) = 0$, $f'(0)$ is a
  uniformizer, and $f$ induces Frobenius
  over the residue field.  Then there
  exists a unique formal group law
  $F_f(X,Y)\in A[[X,Y]]$ that makes $f$
  into a formal $A$-endomorphism.

If you go over the details of the lemma, you can (I think) generalize it as follows:

If $R$ is any ring, $f\in R[[T]]$ such
  that $f(0) = 0$ and $f'(0)\in R^\times$
  (Edit: $u=f'(0)$ then $u^n - u\in R^\times$ for all $n$), then there exists a unique
  formal group law $F_f(X,Y)\in R[[X,Y]]$ that makes $f$ into a formal
  $R$-endomorphism.

The business about uniformizers and Frobenius in the Lubin-Tate lemma is just to ensure that everything converges on the maximal ideal of the ring of integers in the separable closure of $K$, so that you get an actual group.
So this is pretty cool---it says that you can take something purely analytic, $f$, and magically give it an algebraic structure.  Specifically, the roots of the iterates $f^{(n)} = f\circ\cdots\circ f$ become a torsion $A$-module.
If the existence of $F_f$ generalizes like I think it does, a natural question is where does $F_f$ converge?  I want to be able to answer the question for specific $f$, a simple example  would be the following: if $R=\mathbb{C}$ and $f(z) = uz + z^2$, then what can you say about the convergence of $F_f$?
Edit: Okay, $\mathbb{C}$ was a bad choice, but suppose $R$ is a ring complete with respect to some $\mathfrak{a}$-adic topology.  Would there be a reason not to study this case? Maybe the question I should be asking is, for what other $R$ and $f$ do people study these formal groups $F_f$?

A: I don't think you should be trying to interpret this stuff over the (real or) complex numbers.  Discs do not have nice algebraic properties in the archimedean world as they do $p$-adically.  Even $p$-adically, one never talks about an actual radius of convergence but just makes sure things converge on the maximal ideal and work there.  For example, the Lubin--Tate series could even be a polynomial, with infinite radius of convergence, but still one just focuses on what it does inside the unit disc ($p$-adically).

A: It does probably not work in the way you wish.
The crucial bit where convergence is used later in Lubin-Tate is to realize the Galois action via these series [a]. The first-level roots will lie in m minus m^2, so you really want convergence in this radius.
For finding roots itself I think convergence really is not the problem, but having some roots will not help you much if you cannot make the machine realizing the Galois action through power series work.
If you look at the proof (e.g. Yoshida's notes or Milne's notes), at some point one uses that
f(X^q) - f(X)^q
is zero modulo p, which is quite crucial for the convergence - as you say above. But this is not just a sufficient condition, I think if you try a series over some other ring where this fails, you'll really inavoidably get a series which doesn't converge in m. Still your Lubin-Tate polynomial (as proposed by KConrad as a good example above) has roots and all that, good, but there is no way to make the formal O_K-module series [a] act on them. I don't quite remember so well, but I am not even so sure whether it is certain that the extension made from the roots of a Lubin-Tate polynomial/powerseries is Galois anymore in general.


text:
Q: How to set parent id when using nested attributes form? I am building a Rails 3.2 webapp. In this app I am using the gem Act_as_tenant.
I also got accounts (tenants) that has many users (trough a join table).
I am creating both the account and the first user using nested attributes.
The user model got an attribute called account_id which I need to fill with the created account. Both the account and the user is created successfully BUT the id of the newly created account is not set in the users model (account_id). How can I make sure it is?


text:
Q: dhcp server not assigning ip (centos 7) I configured a DHCP server on centOS 7 (192.168.1.103) but it's not assigning an IP address to the client (using Windows as client).
I am not getting any errors while starting/restarting the service.
Here is my DHCP configuration file (/etc/dhcp/dhcpd.conf)
subnet 192.168.1.0 netmask 255.255.255.0 {
  range 192.168.1.110 192.168.1.250;
  option subnet-mask 255.255.255.0;
  option routers 192.168.1.103;
  option broadcast-address 192.168.1.255;
  option domain-name-servers 8.8.8.8;
}

/etc/sysconfig/dhcp

DHCPDARGS=enp0s6u1

how this can be solved?

A: Add these options before the subnet line.
default-lease-time 600;
max-lease-time 7200;
authoritative;

also add a
;

To your dhcpargs, make sure that is exactly your interface with the IP in the same network.


text:
Q: Populate 1 form field based on another Is there an easy way to populate one form field with duplicate content from another form field?
Maybe using jQuery or javascript?

A: In Native Javascript:
var v1 = document.getElementById('source').value;
document.getElementById('dest').value = v1;

A: It is easy in javascript using jQuery:
$('#dest').val($('#source').val());

A: You just have to assign the field values:
// plain JavaScript
var first = document.getElementById('firstFieldId'),
    second = document.getElementById('secondFieldId');

second.value = first.value;

// Using jQuery
$('#secondFieldId').val($('#firstFieldId').val());

And if you want to update the content of the second field live, you could use the change or keyup events to update the second field:
first.onkeyup = function () { // or first.onchange
  second.value = first.value;
};

With jQuery:
$('#firstFieldId').keyup(function () {
  $('#secondFieldId').val(this.value);
});

Check a simple example here.


text:
Q: displaying image in datagridviewimagecolumn in vb.net i have a datagridviewimagecolumn which I added using the small arrow when you click the datagridview or should I say not programmatically added.
Can anyone tell me how to display image in datagridviewimagecolumn when the form loads?

A: Programmatically Add Image
This will add YourImage.png to the first row (Rows(0)) in DataGridView1
    Dim ColImage As New DataGridViewImageColumn
    Dim Img As New DataGridViewImageCell

    'Set Name
    ColImage.Name = "ColImg"

    'Set Header text
    ColImage.HeaderText = "Your Image!"

    'Add column to datagridview
    DataGridView1.Columns.Add(ColImage)

    'Set image value
    Img.Value = Image.FromFile("C:\YourImage.png")

    'Add the image cell to a row
    DataGridView1.Rows(0).Cells.Add(Img)

Adding Image By DataGridView Interface
Click on the small arrow in the upper right hand corner of your datagridview. Click "Edit Columns"

*

*A new window pops up, now click on "Add" to add a new column.

*Another window appears, select "DataGridViewImageColumn" as the type in the dropdown menu.

*Set the name and header text, then click on Add

All you need to do next is select the image.

*Tip: Set your ImageLayout to "Zoom" and you'll get a clear image.

A: You can just set the DataGridViewImageColumn.Image property. More information here.


text:
Q: Tableau Export PDF with custom template I have a viz showing on our site and the sales people may have customized it by running filters on it. This customized report we want to export as a pdf. Can i customize this some how to use a specific header and text as well?
Here are some things that i would like to include

*

*I want to put a custom header/image

*Some text to show contact us/sales rep info and some descriptive text

*The viz as it is displaying with filter applied

*Some text underneath the viz

FYI: this viz is showing on our site. I am not referring to Tableau server.
Thanks.

A: Out of the box, with Tableau Server there is a tool called tabcmd that you can use to create a PDF of the viz on Server (see http://kb.tableausoftware.com/articles/knowledgebase/using-tabcmd).
Once you have created the PDF you would need to run a second job with something like Coherent's PDF Command Line Tools (http://www.coherentpdf.com/usage-examples.html) to mark up the PDF with the content you want to add.


text:
Q: angular array item not updating on scope change Spent a few hours on this already, sifted through numerous stack posts and blogs but can't seem to get this to make my model update. More specifically, I am trying to update an array item (ng-repeat). In the simple case below, I iterate over venues list, and upon toggling a "like" button, I update the server appropriately, and reflect the change on the venues item on the $scope.
in my search.html I have a directive:
<ion-content>
   <venues-list venues="venues"></venues-list>
</ion-content>

and search controller I have:
app.controller('bleh', function(Service) {
   ...
   $scope.venues = [{ id: 1, name: 'Venue1', like: false },{ id: 2, name: 'Venue2', like: false }];
   ...
});

Nothing unusual there. Then in my venues-list directive:
app.directive('venues-list', function() {

   function venueListController($scope, Service) {

      $scope.likeToggle = function(venue, $index) {
            Service.likeVenue(venue.id, !venue.like).then(function() {
               $scope.venues[$index].like= !venue.like;
            });
      }
   }

   return {
      strict: 'E',
      templateUrl: 'venue.html',
      controller: venueListController,
      scope: {
         venues: '='
      }
   }
});

then in my venue.html I have:

{{venue.name}}

  <button ng-click="likeToggle(venue, $index)">Like</button>

I have tried many different options:
$scope.$apply() // after updating the $scope or updating scope within apply's callback function;
$scope.$digest()
$timeout(function() { // $scope.venues[$index] .... }, 0);
safe(s,f){(s.$$phase||s.$root.$$phase)?f():s.$apply(f);}

so
safe($scope, function() { $scope.venues[$index].like = !venue.like });

I haven't yet used the link within the directive, but my venues.html template is obviously a little more elaborate than presented here.
EDIT:
Just to keep the discussion relevant, perhaps I should have mentioned - the data is coming back from the server with no issues, I am handling errors and I am definitely hitting the portion of the code where the $scope is to be updated. NOTE: the above code is a small representation of the full app, but all the fundamental pieces are articulated above.

*

*Search Controller

*Venues Service

*venue-list directive and venue.html template to accompany the directive

*directive controller

EDIT #2
$scope.foo = function() {
   $scope.venues[0].like = !$scope.venues[0].like;
}

Just to keep it even simpler, the above doesn't work - so really, the bottom line is my items within an array are not reflecting the updates ...
EDIT #3
$scope.foo = function() {
   $scope.venues[0].like = !$scope.venues[0].like;
}

My apologies - just to re-iterate what I was trying to say above - the above is changing the scope, however, the changes are not being reflected on the view.

A: Perhaps the issue is with your service and promise resolution.. Can you put a console.log there and see if the promise resolution is working fine? or Can you share that code bit. Also where are you checking for scope update? within directive or outside

A: OK after some refactoring I finally got it working.
The "fix" (if you want to call it that) to my specific problem was:
instead of passing an array of venues, I was iterating over the array on the parent controller, passing in a venue as an element attribute that would bind (two-way) on the isolated scope of the directive.
so, instead of:
<ion-content>
   <venues-list venues="venues"></venues-list>
</ion-content>

I now have:
<ion-content>
   <venues-list ng-repeat="venue in venues" venue="venue"></venues-list>
</ion-content>

and my directive now looks like:
app.directive('venues-list', function() {

   function venueController($scope, Service) {

      $scope.likeToggle = function(venue) {
            Service.likeVenue(venue.id, !venue.like).then(function() {
               $scope.venue.like = !venue.like;
            });
      }
   }

   return {
      strict: 'E',
      templateUrl: 'venue.html',
      controller: venueController,
      scope: {
         venue: '='
      }
   }
});

This did the trick!


text:
Q: How to connect Live Writer to Orchard CMS I have followed the instructions found here and here. Also:

*

*I am using Orchard Orchard v.1.7.0.0

*I am hosting in a Windows Azure Website

*I have setup Remote Blog Publishing and XmlRpc.

*I have tried the all three domain names that point to the website.

*My actual blog name is http://www.muddlingthru.com/we-re-all-just-muddling-thru
Here is an image of my attempt to add the blog.

Windows Live Writer says it "was not able to automatically detect your blog settings." So, I try to do it manually as follows.

Windows Live Writer says, "Invalid Server Response - The response to the blogger.getUsersBlogs method received from the blog server was invalid."
I have already setup Remote Blog Publishing and XmlRpc as follows.

Is there anything else that I need to do? For instance, when Windows Live Writer asked for the "Remote posting web address for your blog," it has a template like this:
http://<hostname>/<mw-script>

That I fill in like this:
http://www.muddlingthru.com/we-re-all-just-muddling-thru

I suspect I might have the incorrect remote posting web address.

A: The blog account must be the url of your blog, not of a blog post.
It will then detect special metas that indicates the /XmlRpc url that implements MetaWeblog API.
You can also configure it manually choosing Metaweblog provider.

A: I had the same problem, then I disabled the HTML minifier and it worked...

A: I just installed OpenLive Writer and tried to connect to my Orchard blog and ran into the same problem.
After playing with it a few minutes, I opened the blog page and simply copied and pasted the URL into the Web Address of Your Blog text box.
Bingo, it worked. Only difference, no ending /.


text:
Q: Error while using Subcaption package I am trying to use the subcaption package in my code but it throws errors. Here is the preamble of my code:
\documentclass{report}
\usepackage[utf8]{inputenc}
\usepackage[LGR,T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{microtype}
\usepackage{upgreek}
\usepackage[misc]{ifsym}
\usepackage{graphicx}
\usepackage{tikz}
\usepackage{subcaption}

%%% Maths and science packages

\usepackage{amsmath,amsthm,amssymb}
\usepackage{pgfplots}
    \usetikzlibrary{
        calc,
        patterns,
        positioning
    }
    \pgfplotsset{
        compat=1.16,
        samples=200,
        clip=false,
        my axis style/.style={
            axis x line=middle,
            axis y line=middle,
            legend pos=outer north east,
            x axis line style={
                ->,
            },
            y axis line style={
                <->,
            },
            legend style={
                font=\footnotesize
            },
            label style={
                font=\footnotesize
            },
            tick label style={
                font=\footnotesize
            },
            xlabel style={
                at={
                    (ticklabel* cs:1)
                },
                anchor=west,
                font=\footnotesize,
            },
            ylabel style={
                at={
                    (ticklabel* cs:1)
                },
                anchor=west,
                font=\footnotesize,
            },
            xlabel=$X$,
            ylabel=$Y$
        },
    }
    \tikzset{
        >=stealth
    }

%%% Tables and figures packages

\usepackage{float}
\usepackage{caption}
    \captionsetup{
        format=plain,
        labelfont=bf,
        font=small,
        justification=centering
    }

%%% Numbers and sets

\newcommand{\E}{\mathrm{e}}

\title{Monthly report May 2022}
\author{kashwin975 }
\date{May 2022}

\begin{document}

\maketitle


text:
Q: Alfresco replace component advsearch i successfully modified alfresco advseach.
Now i have to replace the original. I really don't know how can i do this, until this moment i was working in share/target but i can't do that anymore. I need to somehow rewrite default url of advsearch. I need that Alfresco call my advsearch instead of default advsearch after clean installation or after command mvnclean.
I think that this should working:
<extension>
  <modules>
    <module>
      <id>ADVSearchExt</id>
      <version>1.0</version>
      <auto-deploy>true</auto-deploy>
      <components>
          <component>
              <region-id>search</region-id>
              <source-id>advsearch</source-id>
              <scope>page</scope>

              <url>/comp/advsearchext</url>

          </component>
       </components>
     </module>
    </modules>
</extension>

A: NOTE: On subsequent reading of the question, I've realised that this original answer doesn't directly answer the question, however it does contain useful related information... I'll try and answer the actual question as well!
Assuming you're using Alfresco 5.0 or 5.1 then the only way of accessing the advanced search page (via standard navigation) would be via the drop-down menu option in the header bar.
The header bar is an rendered by Aikau and it is a relatively simple exercise to customize the header bar to navigate to an alternative page when you click on that "Advanced Search..." menu item.
This blog post is the first in a 3-part series describing how you can customize the header bar.
The widget that you need to customize is the "alfresco/header/SearchBox" widget. Unfortunately, at the moment it doesn't off a simple configuration option for changing the page to navigate to. In this scenario you could raise an issue on the Aikau Github page to make a request for this feature to be added. This would require that you wait for the feature to be included in a future release (releases are weekly) and then make use of that new configuration option.
The alternative would be to extend the default SearchBox widget and create a new extension module that swaps out the default SearchBox with your custom version. You would need to extend the postCreate function and remove alfresco/menus/AlfMenuItem that is created and replace it with one that has an appropriate targetUrl.
Unfortunately this is neither the most future proof or simplest solution, but is is possible. The most future proof solution (in terms of working with future upgrades to Alfresco) would be to make the feature request as clearly there are benefits to being able to reconfigure the advanced search page.

A: It looks like you've created an alternative WebScript for the Component and you wish to swap it out. It's not possible to reconfigure an existing Component configuration as you are trying to do. What you actually need to do is to create one extension to remove the default component (see this blog post) and then provide another component to render your WebScript (see this blog post).


text:
Q: fullcalendar Can't disable resizing and enable draggable I am using fullcalender and I am not able to disable resizing and enable draggable
My event is
[{
 "title":"Test2",
 "start":"2019-09-28T11:00:00",
 "end":"2019-09-28T13:00:00",
 "backgroundColor":"red",
 "textColor":"white",
 "constraint":"businessHours",
 "eventDurationEditable":false,
 "eventStartEditable":true
 }]

But not draggable, when I see on website If I change to:
editable: true,
eventDurationEditable:false

event draggable and resizible

A: You seem to be setting global options in an event context. When you set these options for each event then the option names are different (without the "event" prefix) - see https://fullcalendar.io/docs/event-parsing.
If you set them as whole-calendar options then your naming would be correct.
Therefore, in your event data use
"editable": true,
"durationEditable": false

instead


text:
Q: Media Queries and Sharepoint Online I'm running into an issue where my media queries are not being rendered by Sharepoint Online.
Here is a list of whats been changed/not changed;
-No customer master page
-Sharepoint is pointed towards the correct CSS file
-Other changes are rendered, but not media queries
-Can't use bootstrap or any custom master page edits (client request)
I'm not sure whats going on.  Here is a snippet of my code.
@media screen and (max-device-width: 1200px)
{
/*Nav*/
#DeltaTopNavigation{
margin-left:15%;
}
}

I'm using this query because the left nav is hidden and replaced with this custom one.  Even when using em instead of pixels it won't render.
Is there a better solution to make Sharepoint more responsive?
Edit: After some time I've added in the meta tag.  Even though the tag is in place, the media queries don't respond.

A: It's possible you're missing a meta viewport tag? Media queries won't work without it.


text:
Q: Using a MEDIAN IF function in Excel as an index? So I have my Median If function as
=MEDIAN(IF($A$6:$A$200=$L$5,D6:D200))
and I want to know if I can wrap this in an INDEX function to return a value on the row of the calculated median, but in a different column (probably using MATCH I guess)? I've looked at a couple of sources online but I'm struggling to come up with a formula to do this.
The A column is a list of organisations, and the D column is a cumulative frequency that the median would be found in (or rather the range it would be found in so wouldn't be an exact match). I then want when my index has found the value in the D column, to retrieve the corresponding value in that row but from the B column. Thanks in advance!

A: Yes use MATCH to return the relative location:
 =INDEX($B$6:$B$200,MATCH(MEDIAN(IF($A$6:$A$200=$L$5,D6:D200)),D6:D200,0))

Depending on ones version of Excel this formula may need to be confirmed with Ctrl-Shift-Enter instead of Enter when exiting edit mode.


text:
Q: Ionic build failed: FAILURE: Build completed with 2 failures It happens when i added braintree plugin.FAILURE: Build completed with 2 failures.
1: Task failed with an exception.

*

*Where:
Script '...\platforms\android\cordova-plugin-braintree\bookmi-build-extras.gradle' line: 16

*What went wrong:
A problem occurred evaluating script.

...\platforms\android\app\res\xml\config.xml (The system cannot find the path specified)

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.

*

*What went wrong:
A problem occurred configuring project ':app'.

compileSdkVersion is not specified. Please add it to build.gradle

*

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

*Get more help at https://help.gradle.org
BUILD FAILED in 2s
Command failed with exit code 1: ...\platforms\android\gradlew cdvBuildDebug -b ...\platforms\android\build.gradle
[ERROR] An error occurred while running subprocess cordova.
    cordova.cmd build android exited with exit code 1.

    Re-running this command with the --verbose flag may provide more information.


text:
Q: iterar una variable y pasar al siguiente si existe php Estoy construyendo una proyección estimada de una llegada de un producto a mi bodega.
Tengo una tabla en mi base de datos donde cada producto tiene un código único, una descripción y una cantidad.
Luego tengo otra tabla llamada tránsitos la cual almacena el código único del producto, una cantidad, una fecha, y un puerto destino. PERO TODO ESTO ESTÁ CONCATENADO EN UN GROUP_CONCAT
tabla transito:

Entonces: el primer código ATA0000060 tiene como cantidad a llegar: 240, fecha estimada de llegada: 2021-12-30 y un puerto de 1, lo que se ve en la imagen 240/2021-12-30@1. Los caracteres de / y @ son separadores específicos para después en php saber por cual separar.
La lógica es: En mi tabla transito almaceno las cantidades unitarias que estarían por llegar en una fecha futura por ejemplo, código ATA0000060: 240 unidades están por llegar el día 2021-12-30 en el puerto #1.
Si se fijan hay varios códigos que tienen múltiples llegadas de mercancías, estas están separadas por una coma (,)
El código AB000005190 tiene 3 registros de tránsitos por llegar, separados por 2 comas, esto nos da a entender que: si en datos_transito no existen comas(0) significa que tenemos un registro, si existe una coma estarían llegando 2 registros, si aparecen dos comas tendríamos 3 registros y así sucesivamente...
Una vez aclarado esto, viene lo divertido..
En HTML y php necesito mostrar todos los tránsitos venideros a partir de hoy (27/09/2021) hasta el día (27-09-2022), es decir un año. para esto programé un bucle for así:
    for ($u=1; $u <360; $u++) {
            $fechaAMostrar2 = date("Y-m-d",strtotime($fechaActualMysql."+ $u"." day"));
}

Este for me muestra todos los días de hoy hasta el 27/09 del otro año
Donde $fechaActualMysql es la fecha actual de hoy, funciona perfecto.
Explicaré a groso modo lo que quiero obtener: Luego de mostrar las fechas como encabezado, necesito mostrar en pantalla cuando está entrando una cantidad en esa fecha especifica en la pantalla es decir si $fechaActualMysql == La fecha en mi registro, tome la cantidad de ese registro y lo muestre, es sencillo cuando solo tienes un registro por recorrer, pero cuando tienes más de uno se complica..
El siguiente código funciona perfecto cuando hay un registro, cunado hay más de dos no logro mostrar la cantidad bien, ni tampoco validarlo, ya que si un registro tiene mas de una coma dará algún error de variable no conocida.
// LA VARIALE $DATOS_TRANSITO ME DEVUELVE TODOS LOS TRANSITOS AGRUPADOS ES DECIR OUTPUT: 50/2021-01-10@1
            // DONDE 50 = TRA_CANTIDAD, 2021-01-10 = TRA_FECHA, 1 = TRA_PUERTO
                $datos_transito = $row['datos_transito'];
           // LA VARIALE $CONTADOR ME DEVUELVE TODOS LOS TRANSITOS INDIVIDUALES SEPARADOS POR LA COMA, ES DECIR SI &CONTADOR_DE_REGISTROS = 0
           // QUIERE DECIR QUE EXISTE UN TRANSITO, SI ES IGUAL A 1 QUIERE DECIR QUE EXISTE 2 TRANSITOS, SI ES IGUAL A 2 QUIERE DECIR QUE EXISTEN 3 TRANSITOS ETC..
                $contador_de_registros = substr_count($datos_transito,',');
            // CONVIERTE DE ARRAY A STRING
                $datos_transito_string = strval($datos_transito);

            // SEPARADORES (NO USADOS EN ESTE EJERCICIO)
                $sp_registro = ", ";
                $sp_cantidad = "/";
                $sp_fecha = "@";
            // DATOS SEPARADOS
                $registro_a_array = explode(',', $datos_transito_string);
                $primer_registro = $registro_a_array[0];
                $primer_caracter =  $primer_registro[0];
                $segundo_registro = $registro_a_array[1];
                // $tercer_registro = $registro_a_array[2];
                 $todos_registros = $primer_registro . '/' .$segundo_registro;

                    for ($u=1; $u <$DiasCal; $u++) {
                       $fechaAMostrar2 = date("Y-m-d",strtotime($fechaActualMysql."+ $u"." day"));

                       $busqueda = str_contains($primer_registro,$fechaAMostrar2);

                        if ($busqueda != true) {
                            $transito_cantidad = 0;
                        }else{
                            $tra_cantidad_ex = explode('/', $primer_registro);
                            $tra = $tra_cantidad_ex[0];
                            $transito_cantidad = intval($tra);

                        }

                        <td> <?php echo $transito_cantidad ?></td>

Lo ideal sería iterar el primer transito, tomar la cantidad y pasar a el siguiente transito si existe, si no pare.
Adjunto este excel que espero ayude a explicar mejor el problema:

Si no se entiende alguna parte, favor hacerlo saber!

A: Como dijo @Sal en los comentarios, lo mejor sería normarlizar la tabla transito, así las queries serán mucho mas sencillas.
En lo personal trataría de resolver todo lo posible en la base de datos, de tal forma que el código php quede lo mas sencillo posible.
Con está query (para MySql >= 8.0) puedes "normalizar" (no es la normazliación a la que hago referencia al principio, aquí solo obtenemos los datos normalizados, pero en la base de datos siguen estando desnormalizados) la información de la tabla transito, de tal forma que te retorne cada estimación de la llegada de un producto en una fila aparte, filtrando por fecha (desde hoy hasta un año).
WITH RECURSIVE trans_norm AS (SELECT pro_codigo,
                                  SUBSTRING_INDEX(datos_transito, ',', 1) AS dt,
                                  1 AS i
                           FROM transito

                           UNION ALL

                           SELECT t.pro_codigo,
                                  SUBSTRING_INDEX(SUBSTRING_INDEX(t.datos_transito, ',', tn.i + 1), ',', -1) AS dt,
                                  tn.i + 1 AS i
                           FROM transito AS t
                           INNER JOIN trans_norm AS tn ON t.pro_codigo = tn.pro_codigo
                           WHERE SUBSTRING_INDEX(SUBSTRING_INDEX(t.datos_transito, ',', tn.i + 1), ',', -1) != SUBSTRING_INDEX(SUBSTRING_INDEX(t.datos_transito, ',', tn.i), ',', -1)
)

SELECT pro_codigo,
       SUBSTRING_INDEX(dt, '/', 1) AS cantidad,
       SUBSTRING_INDEX(SUBSTRING_INDEX(dt, '@', 1), '/', -1) AS fecha_estimada,
       SUBSTRING_INDEX(dt, '@', -1) AS puerto
FROM trans_norm
WHERE SUBSTRING_INDEX(SUBSTRING_INDEX(dt, '@', 1), '/', -1) BETWEEN '2021-09-27' AND '2022-09-27';

Salida (con datos de ejemplo):

pro_codigo
cantidad
fecha_estimada
puerto

AAT0000060
240
2021-12-30
1

AB0005190
100
2021-10-04
1

AB0005190
100
2021-11-02
1

AB0005190
100
2022-01-09
1

Luego lo único que tendrás que hacer en php es transponer el resultado (que las fechas te queden como columnas).
No se si entendí bien la última parte, pero ahora especificando la fecha (creo que en tu caso es la fecha actual) te será mas sencillo saber cual es la cantidad para ese fecha.
con PHP
Otra solución podría ser que al recibir los datos desde la base de datos, los organices utilizando una estructura mas conveniente, la cual te facilite la iteración sobre los mismos, por ejemplo (tendrías que buscar la estructura mas útil para ti):
<?php

//Los datos de transito como llegan desde la base de datos:
$transito = [['AAT0000060', '240/2021-12-30@1'], ['AB0005190', '100/2021-10-04@1,100/2021-11-02@1,100/2022-01-09@1']];

function normalizarTransitos($transito) {
    $sp_registro = ",";
    $sp_cantidad = "/";
    $sp_fecha = "@";
    $resultado = [];

    foreach($transito as $prodTrans) {
        foreach(explode($sp_registro, $prodTrans[1]) as $trans) {
            list($cantidad, $fechaPuerto) = explode($sp_cantidad, $trans);
            list($fecha, $puerto) = explode($sp_fecha, $fechaPuerto);

            $resultado[] = ['producto' => $prodTrans[0], 'cantidad' => $cantidad, 'fecha' => $fecha, 'puerto' => $puerto];
        }
    }

    return $resultado;
}

$datosOrganizados = normalizarTransitos($transito);

?>

$datosOrganizados:
array ( 0 => array ( 'producto' => 'AAT0000060', 'cantidad' => '240', 'fecha' => '2021-12-30', 'puerto' => '1', ), 1 => array ( 'producto' => 'AB0005190', 'cantidad' => '100', 'fecha' => '2021-10-04', 'puerto' => '1', ), 2 => array ( 'producto' => 'AB0005190', 'cantidad' => '100', 'fecha' => '2021-11-02', 'puerto' => '1', ), 3 => array ( 'producto' => 'AB0005190', 'cantidad' => '100', 'fecha' => '2022-01-09', 'puerto' => '1', ), )


text:
Q: Javascript dictionary within dictionary is undefined I'm receiving a response from a server that is a dictionary that has within it another dictionary. The problem is that the inner dictionary is undefined. How do I define this dictionary?
Here's my code
$.ajax({url : destination_url, type : type, data : msg_Json, success : function(result){

                    console.log("Result: " + result);
                    var obj = JSON.parse(result);
                    var message;
                    console.log("Message type: " + obj.messageType);

                    if (obj.messageType == "LOAD"){
                        console.log("game state: " + obj.game_state);
                        message = {messageType : "LOAD", gameState : obj.game_state};
                        iframe.contentWindow.postMessage(message, "*");

Here's what the console prints out:
Result: {"messageType": "LOAD", "gameState": {"playerItems": ["A rock", "A rock", "A rock"], "score": 40}}
Message type: LOAD
game state: undefined

A: well... game_state.. gameState.
One is snake case and the other one is camel case..?


text:
Q: SQL-Select with decimal field not working I have a table with a decimal field in Postgres
The value of the field is 39.95
I try to make a SQL-Query to get all records with value 39.95
This is my code:
SELECT CR_Sale.id , CR_Sale.sale_date, ROUND(CR_Sale.sale_bruto_total, 2)
    AS sale_bruto_total, CR_Sale.sale_ticket
FROM crm_CR_Sale CR_Sale
WHERE sale_bruto_total = 39.95
ORDER BY sale_timestamp DESC;

When I execute the query no results are found.
If I change my code to
WHERE sale_bruto_total <= 39.95

I get a result and can see the records with value 39.95
What am I doing wrong?
Thanks

A: Try as follow:-
SELECT CR_Sale.id , CR_Sale.sale_date, ROUND(CR_Sale.sale_bruto_total, 2)
    AS sale_bruto_total, CR_Sale.sale_ticket
FROM crm_CR_Sale CR_Sale
WHERE sale_bruto_total = CAST(39.95 AS dec(5,2))
ORDER BY sale_timestamp DESC;

Note:- 'sale_bruto_total' column should be decimal type

A: The number 39.95 is not a decimal value but a float and then you can't make equality comparisons due to the internal precision of floats (this being the reason why there is the decimal data type in the first place) so you have to add an explicit cast:
sale_bruto_total = 39.95::decimal(5,2)

Also, if the value of sale_bruto_total is exactly 39.95 because the field is defined as a decimal with two decimals after the dot, then you do not need the round() function in the select list. On the other hand, if there are more decimals then you need to use the round() function in the filter too. So either:
SELECT id, sale_date, round(sale_bruto_total, 2) AS sale_bruto_total, sale_ticket
FROM crm_CR_Sale
WHERE round(sale_bruto_total, 2) = 39.95::decimal(5,2)
ORDER BY sale_timestamp DESC;

or
SELECT id, sale_date, sale_bruto_total, sale_ticket
FROM crm_CR_Sale
WHERE sale_bruto_total = 39.95::decimal(5,2)
ORDER BY sale_timestamp DESC;


text:
Q: Wordpress - Custom field array of image ID's I'm using the new wordpress custom post types and fields.
It's all working great, but for a custom image field (where I can select multiple images in one field), the value of this field when output is an array:
<?php
$field = get_post_meta($post->ID, "puma", false);
echo $field[0];
?>

This results in the following output (there are 3 images here):
180|177|174

These are clearly the image ID's stored in the wp_posts table of the database.
However, before I go mad trying to do this manually via an SQL query (hack), I was wondering if there is a better and more native way in wordpress to get the value of these or the proper way to output these images?
Cheers,
Michael.
EDIT:
Thanks to some help I got below, the final code for anybody who needs it is this:
<?php

    $field = get_post_meta($post->ID, "myImageField", false);
    $str = $field[0] . "|"; // add an extra pipe at the end to get ALL the items (kinda tricking it.
    $theIDarray = explode('|', $str, -1);

    foreach ($theIDarray as $value) {

        echo wp_get_attachment_image($value, "myCustomImageSize");

    }

?>

This works for a custom field with multiple image selections for the 'content-types-wordpress-plugin'. Hope it helps those in need!

A: I think below function can return image, if you pass image id as parameter :
echo wp_get_attachment_image($image_id)


text:
Q: UI5 Tree Table why repeated nodes? I am trying to bind OData to a Tree Table following the OData Samples in sap.ui.table.TreeTable
I have tried both with basic binding with setting treeAnnotationPropertiesin the xml and annotation binding (I have checked the $metadata query and it has the sap:hierarchy- etc).
However, both times I get repeated nodes like:
Id    | Title     | Hierarchy Level | ParentID
----------------------------------------------------
1     | izparent  | 0               | 0
|--1  | izparent  | 0               | 0
|  |-- ...
|--2  | izchild   | 1               | 1
2     | izchild   | 1               | 1

where I get a Node with Id 1 which is expandable, and Node 2 which is not expandable. But if I expand Node 1, I again get Node 1 which is expandable and Node 2, and I can repeated expand Node 1 to get the same result.
I have a feeling I have a similar problem as here, but there is no answer provided for this either: How to define tree table annotation (XML view)
I am using OData Version 2.0 and for my et_entity I just provide a SELECT * FROM a table which has the structure I think I need according to the samples.
Table content:
Id | Title    | HierarchyLevel | ParentID | Drillstate
1    izparent   0                0          expanded
2    izchild    1                1          leaf

What could be the issue here?

A: I found that adding operationMode: 'Client' to the rows parameters solved the issue.
It appears that expanding triggers another Server call (additional $batch appears under debugging network tab), and therefore extra logic has to be included in the GetEntitySet method to handle expands on lower hierarchy levels, so it doesn't provide the full hierarchy anymore (e.g. if hierarchy level = ..., then select only hierarchy level < ...).
 Since the amount of data I am handling allows operationMode: client, I did not further the additional logic approach.


text:
Q: Why is my td onClick not firing? I'm adding a background image to a table dynamically and have a .click function which enables a class that essentially greys out the cell.
    var url;
    url = images[i];
   newImage = "url("+url+")";

    document.getElementById('sq'+(i+1)).style.backgroundImage = newImage;
}
$('body').on('click','td', function() {

    alert("Clicked");
    $(this).toggleClass('ui');

    if ($(this).data('value') == 1) {
        $(this).data('value', 0);
    } else {
        $(this).data('value', 1);
    }

Here is the css class 'ui'
.ui {
visibility: hidden;
 border: 3px solid black;
background-color: #ff1e72 !important;
color: #FFF !important;

}

Here is the table html

A: You should try something like this:
Update: You should use $(this).attr("data-value",thevalue);
$(function(){
$("td").click(function(){
    alert("Clicked");
    $(this).toggleClass('ui');

    console.log($(this).data('value'));
    if ($(this).data('value') == 1) {
        $(this).attr("data-value",0);
    } else {
         $(this).attr("data-value",1);
    }
});
});

Working fiddle: http://jsfiddle.net/robertrozas/mktsapk5/3/

A: Like said A. Wolff you must enclose jquery in Dom Ready event becouse jquery need to scan the dom before perfoming of any actionLike said A. Wolff you must enclose jquery in Dom Ready event becouse jquery need to scan the dom before perfoming of any action, this must help:
$(document).ready(function() {

    $('body').on('click','td', function() {
        alert("Clicked");
        $(this).toggleClass('ui');

        if ($(this).data('value') == 1) {
            $(this).data('value', 0);
        } else {
            $(this).data('value', 1);
     }
});

A: You should:
$(document).ready(function() {
    $( "#some-class tbody td" ).on( "click", function() {
       $(this).toggleClass('ui');
   });
});

try document ready to fire off jquery with document ready; I'm not sure what's going on with your script. have some class to start digging into html, its a good idea to access based on class names to be precise. you should definitely use tbody for a well structured html. Now this isn't tested. I would try blocks of jquery scripts to test throughout your script to resolve your issue.


text:
Q: Does Google Feed API enable access via Node.js? I want to use Google Feed API from a server (Node.js). I have already installed the googleapis module. My code is:
// parts omitted
var googleapis = require('googleapis');
// parts omitted
googleapis.discover('feeds').execute(function(err, client) {
var feed = new google.feeds.Feed('http://rss.lemonde.fr/c/205/f/3050/index.rss');
});
// parts omitted

But Node.js console tells me that "google is not defined". Any idea of the problem and solution?

A: to access Google Feed API using Node.js, you should try the google-feed-api module as explained here:
https://www.npmjs.org/package/google-feed-api
Hope it helps!
Edit:
I tried this with your URL and worked fine:
var gfeed = require('google-feed-api');
var feed = new gfeed.Feed('http://rss.lemonde.fr/c/205/f/3050/index.rss');
feed.listItems(function(items){
    console.log(items);
});

A: It's because google is literally not defined. I don't know very much about that module, but I think that instead of using the google var you should use client , because that's what the execute function returns.
So the code would be:
// parts omitted
var googleapis = require('googleapis');
// parts omitted
googleapis.discover('feeds').execute(function(err, client) {
var feed = new client.feeds.Feed('http://rss.lemonde.fr/c/205/f/3050/index.rss');
});
// parts omitted


text:
Q: Почему не работает ctrl+v в терминале Mingw Почему у меня не работает ctrl+v в git?

Как сделать так чтобы у меня здесь работала функция ctrl+v?
Update:Окей ребят я понял что ctrl+ins я не хочу т.к это только в этой проге и капец как не удобно как перекодить файл? (когда я пытаюсь его изменить мне пишет приложение не является Win32 (у меня 64bit))
Update2:Окей скорее всего у меня не та версия я прав?

У меня версия как у тебя всё-ровно нет такой настройки смотрел как в git bash так и в git cmd

A: *

*ПКМ.

*Shift + Insert

*

*

*Linux: Ctrl + Shift + V
Вроде как все возможные способы.

A: Присоеденяюсь к тому что написал
@tomato-magnet-regulato
От себя добавлю что скорее всего из-за того что у меня windows 7
Также может быть из за того что автор проги решил не парится и не делать возможность ctrl+c ctrl+v


text:
Q: How to compare two pdf files through command line Does anyone know how to compare two pdf files using adobe acrobat through command line.
I want to do this via command line because we want to compare hundreds of file every day through some automated windows tasks.
Any kind of help will be greatly. I do not want to limit myself to acrobat to compare , if there is something else available.

A: How about i-net PDFC - it does a full content comparison - text, images, lines, header/footer-detection and so on. You can use it either on command line or with a GUI (2.0, currently in public beta-phase).
The command-line tool already has the option to compare folders with PDFs against each other (or the extreme way: use the API ;))
Disclaimer: Yep, I work for the company who made this - so feedback highly appreciated.

A: Check out comparepdf:

comparepdf is a command line tool for comparing two PDF files. By default it compares their texts but it can also compare them visually (e.g., to detect changes in diagrams, images, fonts, and layout). It should prove useful for automated testing.

It is Open Source (GPL) and there are Windows binaries available.
Also:

If you want a GUI application that shows the detailed differences between PDFs use DiffPDF instead.

A: What you want simply cannot be done with Adobe Acrobat through the command line. However, you could do it with the help of some commandline utilities which you could unite into a shell or batch script.
1. Quick visual check for page image differences
One ingredient of this would be ImageMagick's convert command, which you can test like this for two 1-page PDF files which have page contents similar to each other's:
convert -label '%f' -density '100' first.pdf second.pdf -scale '100%' miff:- \
 | montage - -geometry +0+0 -tile 1x1 -background white miff:- \
 | animate -delay '50' -dispose background -loop 0 -

This will open a window which switches with a delay of 50 dezi-seconds between displaying each of the two files, so it is easy to discover visual differences.
2. Script to generate PDF output visualizing differences between PDF files
I'm doing the same thing using a shell script on Linux that wraps

*

*ImageMagick's compare command

*the pdftk utility

*Ghostscript (optionally)

(It would be rather easy to port this to a .bat Batch file for DOS/Windows.)
You can read details about this approach in this answer.


text:
Q: Power analysis/sample size determination by simulation: Optimal algorithm for finding $N$ I want to calculate the needed sample size $N$ to achieve $80\%$ power for a complex longitudinal study design. Because of the complexity of the design and because I want to have control over every parameter, I'm using simulations to calculate the power at a particular sample size. I'm using R for the simulations. Unfortunately, even a simulation run with 1000 repetitions takes multiple minutes to finish. Because of that, I want to keep the number of simulation runs as low as possible.
If there was an analytical solution (a formula), I could use a root finding algorithm to find the $N$ that achieves $80\%$ power. Using simulations, however, the estimates of the power at a given sample size are noisy. The monte-carlo standard error of the simulation based power is simply $\sqrt{\hat{p}(1 - \hat{p})/n}$, where $n$ is the number of simulations and $\hat{p}$ the estimated power (the proportions of simulations were significance was achieved).
Question: What strategy/algorithm could I use to automate the process of finding the optimal $N$ with as little simulation runs as possible?

A: I don't have a specific algorithm for you, but here is some general advice.
First, you may want to look to see if you can speed up the simulation analysis process.  There are little inefficiencies in a lot of existing code that generally costs less than a second when running once (so most people will not care), but that time can add up in simulations when running thousands of times.  This could be something like the time it takes the program to convert categorical predictors into indicator variables, check for missing data, calculate transformations, calculate confidence intervals, tests on parameters that you are not interested in, etc.  If you can move these steps outside of the analysis and just do them once up front (in the data generation phase, then skip the extra steps in the analysis) this could speed up your simulations.
Look at how you are doing your simulations, is there a way to be more efficient there?  For example growing a data structure in a for loop in R is much slower than using functions like lapply, sapply, or replicate (or the functions in the purrr package).  Using macro loops in SAS will take orders of magnitude longer than generating all the data in one data step and using by processing to analyze.
Most computers today have multiple processors, are you using parallel processing to speed things up?  For short running simulations parallel processing can slow things down (the extra overhead), but as the individual simulation pieces take longer parallel processing can be a real time saver.  Parallel processing can be as simple as having multiple copies of the program running on different sample sizes at the same time (this may depend on what software you are using).
Which part of the individual simulations is taking the most time? creating the data? or analyzing the data?  If creating the data is taking the most time, you can look at multiple sample sizes in one simulation by generating the largest dataset, then using subsets of that for the other sample sizes, e.g. create data for 1,000 subjects over your time periods/events in the longitudinal design, then analyze using the first 200 subjects, the first 400 subjects, the first 600, the first 800, and finally the full 1,000.  You only had to generate the data once, but have information on 5 different sample sizes.
As you point out, there is uncertainty in the estimated power from a simulation and a small number of simulations does not give very much information, but sometimes a small amount of information is enough.  If you only run 100 simulations then the margin of error is about 10%, but if the sample size you are testing gives an estimate of 40% power then knowing the power could be anywhere between 30% and 50% still tells you that that sample size is too small to give you 80% power without the time needed to run 1,000 or more simulations.  So run several sample sizes with only 100 simulations to get in the general area of 80% power, then run some with 1,000 simulations to further narrow it down, then possibly a final run with more simulations to verify.
Don't throw away the information from the simulations that do not give you what you want, you can fit a logistic regression using the the sample size as the predictor (using splines or polynomial terms to allow non-linearity) and the power (and number of runs) as the response.  Plot the predicted curve along with its confidence interval to suggest what sample sizes are likely to give you your desired power, run a few more simulations with those sample sizes and update your logistic regression plot to suggest next sample sizes to test, etc.


text:
Q: How to store valid ng-change event for checkbox in angularjs I have multiple input text checkbox. I want to store the change box event in an array and later when user submits the Save changes, it should be saved.
<td><input type="checkbox" class="switch" ng-model="each_value.at_enable_flag" ng-change="changeMyArray(each_value)"> </td>

The problem with this is, if a user toggle the check box(On/ Off), it stores both the entries not only the latest one.
I tried to remove the duplicates but that is also having some issue.
Can anyone please help me out how I can store the cehckbox value in an array only if the checkbox original value has changed.
Here is my plunkr. Please have a look and let me know if u need any more details.
https://plnkr.co/edit/ZE5xWhfpmbSXqflDs5Qv?p=preview

A: Simply store original value in separate property. Then compare with your model.
https://plnkr.co/edit/IAOUhH7tekTzl15uFi8N?p=preview
In your code.
$scope.toTemplate.forEach(function (value) {
      value.default = value.at_enable_flag;
    });

    $scope.myArray = [];

    $scope.saveAtData = function() {
      $scope.myArray = $scope.toTemplate.filter(function (value) {
        return value.default !== value.at_enable_flag;
      });

      console.log($scope.myArray);
      $scope.saveValue = $scope.myArray;
    }

There is no need for ng-change on input, as it would fire more than needed. Simply filtering array for changed values is enough.


text:
Q: HTML5 Audio with AudioJS unstable if remotely loaded I am having extremely frustrating problems with loading audio tags. I have spent close to two weeks working on this and for every problem I fix, I create another.
I have a page that contains an < audio > tag that uses audio.js to control the audio. This page is loaded through an iframe sometimes and this is when the problem starts. I need to keep a play count so I have different ways of doing so.
Method One:
I have a PHP file that serves an MP3 to the player, this keeps play count and streams the MP3. The player works fine in Firefox and Chrome if I have < audio > tags in the page but not Internet Explorer (Must be a problem with my PHP throws a Gateway Error).
If I load a page that has < audio > tags into an iframe or with AJAX, the audio file is loaded up to three times. If the player is set to auto play, the audio is played twice over the top of each other. If I pause the player, the music can still be heard playing until I remove the iframe using developer tools.
Possible Solution: I have tried loading this up with AJAX to no avail. I can't stop it loading three times but I can force it to play only once by setting autoplay to true in the AudioJS API. For some reason Internet Explorer doesn't like my PHP MP3 file.
Method Two:
I load the MP3 file directly which also works in all browsers if I embed the player directly into a page. However when loaded externally, through an iframe or AJAX the player streams fine in Firefox and Internet Explorer but takes a minute or so to load in Google Chrome. Again it still seems to load the file three times and play twice (Which is only noticeable when autoplay is set) but less often.  This method uses javascript to add play info into the database.
Possible Solution: I have tried adding a random number to the end of the MP3 like so: ?t=4892393 to force Chrome to reload the MP3 to no avail. I have forced the player to use the Flash Fallback but it's unresponsive and seems to break on some configurations (I have tried in the same Chrome version but on some computers the sound is distorted).
EDIT: I have had a look here: https://github.com/kolber/audiojs/issues/96 on the audiojs github page. I have tried the solution on there to no avail.
What I want to achieve: Audiojs seems to work flawlessly if embedded within a page. The problems only occur when loaded externally. I have looked into my PHP error logs, checked the Dev Console on Chrome, IE and Firefox, I have looked at my access logs and analysed the headers with Fiddler but I just can't seem to work this one out.
I would just like audiojs to work properly when loaded externally.
I'm open to accept that audiojs is old and outdated, I think the last update was 2011, so if no solution is possible then a recommendation of a simple, customisable, audio only player would be fantastic, but nothing seems to come close to audiojs.
Thanks.
EDIT: Just to let you know JWPlayer works perfectly but is way too bulky for my needs and it's hard to customise the look of.
EDIT 2: Here is a jsfiddle of my problem, if you open the dev tools and look at the network it loads three MP3s. In Chrome it takes too long to load the MP3 and it sometimes plays double in Chrome and Firefox.
http://jsfiddle.net/joshkrz/52YEc/7/
However the results are erratic, sometimes it works fine. The only thing consistent is the triple loading.
It's worth pointing out that if the player isn't in an iframe everything works perfectly how it should.
<audio preload="auto" src="/audio/2032c11a6f10a5d21eb91202cf67edd3.mp3" type="audio/mp3" autoplay> </audio>

EDIT 3: Turns out this problem happens only when the audio is set to autoplay within the <audio> tags in Firefox and Chrome. However Chrome also takes forever to load if the audio player is loaded in an iframe.
EDIT 4: After looking carefully at the HTTP headers, it appears that the browsers are requesting a GZIPed MP3 file.
My .htaccess file enabled compression like this:
<IfModule filter_module>
FilterDeclare COMPRESS

FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'text/html'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'text/css'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'text/plain'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'text/xml'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'text/x-component'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'text/javascript'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'application/javascript'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'application/json'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'application/xml'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'application/xhtml+xml'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'application/rss+xml'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'application/atom+xml'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'application/vnd.ms-fontobject'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'image/svg+xml'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'application/x-font-ttf'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'font/opentype'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = 'image/x-icon'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = '/application/(javascript|json|xml|x-javascript)/'"
FilterProvider COMPRESS DEFLATE "%{CONTENT_TYPE} = '/text/(html|css|javascript|plain|x(ml|-component))/'"
FilterChain COMPRESS
FilterProtocol COMPRESS DEFLATE change=yes;byteranges=no
</IfModule>

When requesting the RAW mp3 file the headers are as so:
First MP3 HTTP Request
Request
GET http://tabbidesign.com/audio/2032c11a6f10a5d21eb91202cf67edd3.mp3 HTTP/1.1
Host: tabbidesign.com
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36
DNT: 1
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en
Cookie: _ga=GA1.2.1838870165.1389379988

Response
HTTP/1.1 200 OK
Date: Thu, 20 Feb 2014 12:47:40 GMT
Server: Apache/2.4.6 (Unix)
Last-Modified: Mon, 03 Feb 2014 21:49:07 GMT
ETag: "499ce6-4f1877e331ac0"
Accept-Ranges: bytes
Content-Length: 4824294
Content-Type: audio/mpeg

Second MP3 HTTP Request
Request
GET http://tabbidesign.com/audio/2032c11a6f10a5d21eb91202cf67edd3.mp3 HTTP/1.1
Host: tabbidesign.com
Connection: keep-alive
Accept-Encoding: identity;q=1, *;q=0
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36
Accept: */*
DNT: 1
Referer: http://tabbidesign.com/audio/2032c11a6f10a5d21eb91202cf67edd3.mp3
Accept-Language: en
Cookie: _ga=GA1.2.1838870165.1389379988
Range: bytes=0-

The response is the same as above

A: If you try to load http://tabbidesign.com/audio/2032c11a6f10a5d21eb91202cf67edd3.mp3 in chrome it tries to load it twice. Few things to check:
Is it being served with the correct mime-type? Try adding the following to your .htaccess file.
AddType audio/mp3 .mp3 .m4a

Also I see you have gzip enabled on your server. So apache is gzipping everything before sending it to speed things up. This makes sense for html/css/js but mp files are already compressed. If you compare the 1st & 2nd request, the 2nd Request header Accept-Encoding doesn't specify gzip. I think this is why the second request works.
So try disabling apache compression in apache.conf or .htaccess or compress only a few types.
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript

Hope this helps, good luck!
More info:
http://voice.firefallpro.com/2012/03/html5-audio-video-mime-types.html
How to disable Apache gzip compression for some media files in .htaccess file?


text:
Q: Displaying linechart using angular2-highcharts I want to display a line chart from JSON data. I have used angular2-highcharts. The problem is that the chart is displayed without data. I think that the issue is from extracting data from JSON.
The JSON format looks like this:
[{"_id" : ObjectId("59049a7b223f1e21ee4ee23b"),"amount" : 1,"date" :
 "Mon, 18 Dec 1995 18:28:35 GMT"},{"_id" :
  ObjectId("59049a7b223f1e21ee4ee23b"),"amount" : 1,"date" : "Mon, 18
  Dec 1995 19:28:35 GMT"}]

I need only the "amount" in the X value and the "date" in the Y value.
Here is my code
ChartistJs.service.js
  import {Injectable} from '@angular/core';
  import { Headers, Http, RequestOptions, Response } from '@angular/http';
  import { Observable }     from 'rxjs/Observable';
  import 'rxjs/add/operator/map';
  import { Data } from "./Data";
  import 'rxjs/add/operator/toPromise';

  private Url ='http://localhost:3000/transfer/chart';
  constructor (private http: Http) {}
  getData(){
  return this.http.get(this.Url)
             .toPromise()
             .then(response => response.json())
             .catch(this.handleError);
        }

ChartistJs.component.ts
 import {Component} from '@angular/core';
 import {ChartistJsService} from './chartistJs.service';
 import 'style-loader!./chartistJs.scss';
 import { Observable } from "rxjs/Observable";
 import { ChartModule } from 'angular2-highcharts';
 import 'rxjs/Rx';
 import {Observer} from 'rxjs/Observer';
 import {Http, Jsonp} from '@angular/http';

 @Component({
 selector: 'chartist-js',
 template: `
  <chart [options]="options"></chart>
 `,
 providers : [ChartistJsService]
   })

export class ChartistJs {
options: Object;
constructor(private _chartistJsService:ChartistJsService) {
var chartData = this._chartistJsService.getData();
this.options = {
        title : { text : 'simple chart' },
        xAxis: {
            type: 'category'
        },
        series: [{
          data: chartData

        }]
     };
  }
}

Can you help me  how to deal with JSON data in Angular 2?

A: As Pankaj points out you are trying to pass a promise as the data, not the actual data that the promise eventually resolves to. More broadly, though, you aren't really using the tooling that Angular provides for dealing with HTTP.
In general, I would recommend that you:

*

*Get used to dealing with observables, which is what Angular uses natively, rather than converting everything back to promises (although I think they still show this in the docs); and

*Lean into the asynchronous nature of the observables, using the AsyncPipe to resolve them into your templates and the objects that RxJS provides to manipulate the data flow.

More specifically, here's one way you could implement what you're currently trying to.
Service:
@Injectable()
class DataService {

  // acts as a pipe for the data that you can push new items into
  private dataSubject = ReplaySubject(1);

  // takes the subject and exposes the result, read-only
  chartData$ = this.dataSubject.asObservable();

  constructor (private http: Http) {}

  getData() {
    // GETs the data and pushes it into the subject
    this.http.get('http://localhost:3000/transfer/chart')
      .map(response => response.json())
      .subscribe(data => this.dataSubject.next(data));
  }
}

Component:
@Component({
  ... ,
  // resolves the chart options asynchronously in the template
  template: `
    <chart [options]="chartOptions$ | async"></chart>
  `
})
export class MyChartComponent implements OnInit {
  chartOptions$: Observable<any>;

  constructor(dataService: DataService) {
    // creates a new observable of the chart options
    this.chartOptions$ = this.dataService.chartData$
      .map(data => this.createChartOptions(data));
  }

  ngOnInit() {
    // triggers a fetch of the data to feed the observable
    this.dataService.getData();
  }

  private createChartOptions(data) {
    return {
      title: { text: 'simple chart' },
      xAxis: { type: 'category' },
      series: [{ data: data }],
    };
  }
}

You will probably need to do more to the JSON than just pass it as the series.data, but this hopefully gives you an idea of how to leverage the stream of events an observable can provide. I've written more about this on my blog, including a follow-up article on testing.
Also note that your components shouldn't be importing anything from '@angular/http' - leave that to the services, use them as a layer of abstraction from the source of the data - and you can load providers at the module, rather than component, level.

A: Actually chartData variable does hold Promise returned by getData method. Where you should keep .then over the getData method calla and assign options with chartData like shown below.
It would be more better if you can do the same in ngOnInit lifecycle event.
Code
export class ChartistJs {
  options: Object;
  constructor(private _chartistJsService: ChartistJsService) {}
  ngOnInit() {
   this._chartistJsService.getData().then(
    (data) => {
      this.options = {
        title: {
          text: 'simple chart'
        },
        xAxis: {
          type: 'category'
        },
        series: [{
          data: data
        }]
      };
    }
   );
  }
}


text:
Q: Generics in java wildcards List<Integer> ints = new ArrayList<Integer>();
 ints.add(1); ints.add(2);
 List<? extends Number> nums = ints;
 nums.add(3.14);   // compile-time error
assertints.toString().equals("[1, 2, 3.14]");

Why we are getting compile time error?

A: This is because of type erasure in java generics.
You can't add new elements to listbecause its type parameter is undefined at compile time.
The list List<? extends Number> nums means that you can't call add method on it.

A: List<? extends Number> means that we don't know what type is in the list, other than the fact that it is a Number.
In this case, it is a List<Integer>.  Even when you assign it to a List<? extends Number>, it fundamentally remains a List<Integer>.  And you can't add 3.14 to such a list.
If this were allowed, the following code would be valid:
List<Integer> ints = new ArrayList<Integer>();
ints.add(1); ints.add(2);
List<? extends Number> nums = ints;
nums.add(3.14);
Integer third = ints.get(2);

But ints.get(2) is not an integer, so it would throw an exception here.  Better to catch these kinds of issues at compile time.

A: I think the important part here is the instantiation (new ArrayList<Integer>()), which clearly passes Integer to the List class. The left-hand side diamond notation doesn't really matter that much as long as it's compatible. Since you later on defined the generic as an upper boundary of Integer, mainly Number and its subtypes, Java is okay with that, because it still can deal with the Integers. The object essentially still is a List<Integer>.
This is like assigning a String to an Object. It will work because Object is a supertype of String. Here the List<? extends Number> is kind of like a supertype of List<Integer>. (I know the word "supertype" is incorrect here, so feel free to correct me.)
The instantiation with generics is sort of like an instantiation of the class itself and an object. Some other languages, e.g. Python are using the term "metaclasses" for this sort of behavior.


text:
Q: query on multiple databases best solution i have 8 databases with same tables
db0
  tbluser |  id  |    name

db1
  tbluser |  id  |    name

db2
  tbluser

db3
   tbluser |  id  |    name

db4
   tbluser |  id  |    name

db5
   tbluser |  id  |    name

db6
   tbluser |  id  |    name

db7
   tbluser |  id  |    name

i have another table dbcommon where user messages saved
dbcommon
   message  |  id  |  sender_id  |  recipient_id

My problem is that I need to query all messages with user name in it based on sender id and recipient id
What is the best way to do this on mysql?
My approach now is to combine all db1 to db7 user data using union then inner join to message in dbcommon but i'm not sure if that would be ok, what if i have million of data
on user table select and union would be a trouble.
To better understand my question.
I made this but I will not use it.
select *, sender.nickname as sender_name, recipient.nickname as recipient_name
from dbcommon.message m
inner join
(
select * from db0.tbluser
union
select * from db1.tbluser
union
select * from db2.tbluser
union
select * from db3.tbluser
union
select * from db4.tbluser
union
select * from db5.tbluser
union
select * from db6.tbluser
union
select * from db7.tbluser
) as sender on m.sender_id = sender.id
inner join
(
select * from db0.tbluser
union
select * from db1.tbluser
union
select * from db2.tbluser
union
select * from db3.tbluser
union
select * from db4.tbluser
union
select * from db5.tbluser
union
select * from db6.tbluser
union
select * from db7.tbluser
) as recipient on m.recipient_id = recipient.id

A: Whilst I really think that you should normalise your schema such that all these tables are combined into a single one (perhaps with a suitable, indexed as desired, column that indicates the original database); I think that with the status quo, you have only two options:

*

*Join a UNION to the message table, as you are currently doing (but, as you observe, this may not scale very well): you could define a VIEW to save on having to explicitly state the UNION each time, but this won't have any performance benefit.

*If tbluser tables all use the MyISAM storage engine, you can define a table of their union with The MERGE Storage Engine:
CREATE TABLE dbcommon.tblusers LIKE db0.tbluser;

ALTER  TABLE dbcommon.tblusers
  ENGINE = MERGE
  UNION  = (
             db0.tbluser, db1.tbluser, db2.tbluser, db3.tbluser,
             db4.tbluser, db5.tbluser, db6.tbluser, db7.tbluser
           )
;

Joining this to your message table should yield significant performance benefit over the previous option.

A: you can use like this: (but this is not a good practice to have multiple database for same.
select d1.* from db1.dbcommon d1 inner join db2.tbluser d2 on d1.sender_id = d2.id
UNION
select d1.* from db1.dbcommon d1 inner join db2.tbluser d2 on d1.sender_id = d2.id

A: Use this:
 SELECT NOME_USER, NOME_MAQ
 FROM anapula.utilizador as a
    INNER JOIN cyber.maquinas as b ON a.ID_USER = b.COD_USER;


text:
Q: Assign IEnumerable list inside linq query I'm having an issue with following linq query.
public class Address
    {
        public int addressID { get; set; }
        public string address { get; set; }
    }

public class AdvanceClient
    {
        public int ClientID { get; set; }
        public string Name { get; set; }
        public string Mobile { get; set; }

        public IEnumerable<Address> Addresses { get; set; }

    }

In the below linq query i want to assign IEnumerable list of addresses to the Addresses property. I'm having a one to many relationship between tblAdvanceClient and tblAddress tables.
IEnumerable<AdvanceClient> addcli = from tbcli in dc.tblAdvanceClients
                                                join tbadd in dc.tblAddresses
                                                on tbcli.AddressID equals tbadd.AddressID
                                                select new AdvanceClient
                                                {
                                                    ClientID = tbcli.ClientID,
                                                    Company = tbcli.Company,
                                                    Fax = tbcli.Fax,
                                                    Mobile = tbcli.Mobile,
                                                    Name = tbcli.Mobile,
                                                    Telephone = tbcli.Telephone,
                                                    Addresses = new Address { } // Here i need to get the list of address to each client
                                                };

A: instead of
Address = new Address { }

Change it to
Address = tbcli.Addresses //Since you already have a property in AdvanceClient

So your query would be:
IEnumerable<AdvanceClient> addcli =
        from tbcli in dc.tblAdvanceClients
        join tbadd in dc.tblAddresses
            on tbcli.AddressID equals tbadd.AddressID
            select new AdvanceClient
            {
                ClientID = tbcli.ClientID,
                Company = tbcli.Company,
                Fax = tbcli.Fax,
                Mobile = tbcli.Mobile,
                Name = tbcli.Mobile,
                Telephone = tbcli.Telephone,
                Address = tbcli.Addresses
            };

A: Are you using EntityFramework to retrieve the data? If so, then you can alter your model

public class Address
    {
        public int addressID { get; set; }
        public string address { get; set; }
    }

public class AdvanceClient
    {
        public int ClientID { get; set; }
        public string Name { get; set; }
        public string Mobile { get; set; }
        public int AddressId { get; set; }

        public virtual Address Addresses { get; set; }

    }

EntityFramework will load the address data for you.

A: This design is a bit strange to me, having an address list that always contains only one item, but if you definitely need this you can query with the following:
    var addcli = from tbcli in dc.tblAdvanceClients
                join tbadd in dc.tblAddresses
                on tbcli.AddressID equals tbadd.AddressID into addrList
                select new AdvanceClient
                {
                    ClientID = tbcli.ClientID,
                    Company = tbcli.Company,
                    Fax = tbcli.Fax,
                    Mobile = tbcli.Mobile,
                    Name = tbcli.Mobile,
                    Telephone = tbcli.Telephone,
                    Addresses = from row in addrList
                                select new Address
                                {
                                    addressID = row.AddressID,
                                    address = row.Address
                                }
                };

A: I am sorry if I didn't understand right but I think it should be as below since addresses and clients tables has one-to-one reletionship through AddressID
public class Address
{
    public int addressID { get; set; }
    public string address { get; set; }
}

public class AdvanceClient
{
    public int ClientID { get; set; }
    public string Name { get; set; }
    public string Mobile { get; set; }

    //It can has only one address
    public Address Address { get; set; }

}

And query:
IEnumerable<AdvanceClient> addcli = from tbcli in dc.tblAdvanceClients
                                    join tbadd in dc.tblAddresses
                                    on tbcli.AddressID equals tbadd.AddressID
                                    select new AdvanceClient
                                    {
                                        ClientID = tbcli.ClientID,
                                        Company = tbcli.Company,
                                        Fax = tbcli.Fax,
                                        Mobile = tbcli.Mobile,
                                        Name = tbcli.Mobile,
                                        Telephone = tbcli.Telephone,
                                        //tbadd is the address which you are looking for
                                        Addresses = tbadd;
                                    };