text:
Q: Erro ao criar array de strings Eu estou tendo problemas ao tentar inicializar um vector de strings o meu codigo se encontra assim:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char *str[3];
    printf("DIGITE QUALQUER STRING: ");
    scanf("%s", str[0]);
    printf("%s\n", str[0]);
    printf("DIGITE OUTRA STRING: ");
    scanf("%s", str[1]);
    printf("%s\n", str[1]);
    printf("DIGITE MAIS OUTRA: ");
    scanf("%s", str[2]);
    printf("%s\n", str[2]);

    /*
    char *str[2];
    str[0] = "abc";
    str[1] = "cba";
    printf("%s\n", str[0]);
    printf("%s", str[1]);
    */
    return 0;
}

Quando eu compilo esse código o compilador não me retorna nenhum aviso e nenhum erro, quando eu o executo e entro com o primeiro valor ele para e sai do programa dai se eu diminuir o meu vetor para apenas 2 e entrar com o primeiro valor ele me retorna lixo de memoria e no segundo me retorna a string passada.
Se em vez de vetor eu fizer com apenas char *str uma string ele me retorna o valor passado normalmente eu estou tentando pegar o macete de alocação dinâmica tenho quase a certeza que eu estou fazendo alguma coisa de errado.

A: Dá erro porque não está alocando espaço para as strings, só para seus ponteiros. Então ou muda para array e aloca na stack o que me parece mais conveniente para este caso ou use o malloc() para alocar no heap e retornar um ponteiro.
#include <stdio.h>

int main(){
    char str[3][30];
    printf("DIGITE QUALQUER STRING: ");
    scanf("%s", str[0]);
    printf("%s\n", str[0]);
    printf("DIGITE OUTRA STRING: ");
    scanf("%s", str[1]);
    printf("%s\n", str[1]);
    printf("DIGITE MAIS OUTRA: ");
    scanf("%s", str[2]);
    printf("%s\n", str[2]);
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

A: O post é velho, e já tem uma resposta correta, porém, acredito que possa ajudar novos usuários.
Não utilize scanf para pegar entrada do teclado. Scanf não tem um limite definido, se a entrada do usuário for maior que o espaço alocado, será possível realizar a técnica de buffer overlow.
Eu sugiro:
#include <stdio.h>

#define BUFFER_TAMANHO_MAXIMO 30

int main(void) {

        char str[3][BUFFER_TAMANHO_MAXIMO];

        // -1 para incluir o NULL_BYTE \0 no final da string.
        fgets(str[0], BUFFER_TAMANHO_MAXIMO - 1, stdin);
        puts(str[0]);
        return 0;
}


text:
Q: what is the purpose of this(1) & this(2) in the following program? in the following program i have use the this(1) & this(2) what is the purpose of using this(1) & this(2) and i also want to know is this is a keyword or method?I am new to java programming language.
class Const
{
    Const()
    {
        this(1);
        System.out.println(1);

    }
    Const(int x)
    {
        System.out.println(2);
    }
}
class const1 extends Const
{
    int a;
    const1()
    {
        this(8);
        System.out.println(3);

    }
        const1(int x)
    {

        System.out.println(4);

    }
    public static void main(String s[])
    {
        new const1();
    }
}

A: These are alternate constructor invocations. They invoke another constructor in the same class. This allows multiple constructors to share the same code for common behavior.  Without it, you'd sometimes be forced to repeat yourself.
For example:
Const()
{
    this(1);
    ...
}

Calls this constructor with the actual argument "1":
Const(int x) { ... }

You can use the keyword super() in a similar way to invoke a superclass constructor.
From the Java Language Specification, 8.8.7.1, Explicit constructor invocations:

Explicit constructor invocation statements can be divided into two kinds:
Alternate constructor invocations begin with the keyword this (possibly prefaced with explicit type arguments). They are used to invoke an alternate constructor of the same class.
Superclass constructor invocations begin with either the keyword super (possibly prefaced with explicit type arguments) or a Primary expression. They are used to invoke a constructor of the direct superclass.

A: this() if used inside a constructor is actually used to invoke another constructor of the same class. It is particularly useful if you keep overloaded constructors .
public class Rectangle {
  private int x, y;
  private int width, height;

  public Rectangle() {
     this(0, 0, 0, 0);
  }
  public Rectangle(int width, int height) {
      this(0, 0, width, height);
  }
  public Rectangle(int x, int y, int width, int height) {
      this.x = x;
      this.y = y;
      this.width = width;
      this.height = height;
  }
...
}

Remember, this() or super() has to be the first statement in the constructor , if you use them . Hence they cannot be used together inside a constructor.
this if used inside a method body will refer to the current instance on which the method was invoked.
Read the Oracle tutorial for this and super.

A: Its similar to creating overloads to methods so they emulate having 'optional' parameters such as this:
DoStuff(int x, int y)
{
    //Stuff
}

DoStuff(int x)
{
    DoStuff(x, x);
}

Except you are doing it in the constructor (if they don't pass a value just use the value 1).  To answer the question this invokes the constructor of the object.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom tabs with glitches I'm trying to craft fancy looking tabs using angular and its bootstrap component - ui.bootstrap.tabs from http://angular-ui.github.io/bootstrap/. So far it looks like this:

Notice glitches in red circles. They are not always there, only appear when browser window is resized to a particularly unhappy size.
The styling is as following:
.nav-tabs > li > a,
.nav-tabs > li > a:hover,
.nav-tabs > li > a:focus {
    color: #000000;
    text-align: center;
    vertical-align: middle;
    position: relative;
    display: block;
    text-align: center;
    padding: .2em 0 .2em 1em;
    margin: 0px;
    height: 2em;
    background: white;
    border-left: 0.1em solid #b0b7bb;
    border-top: 0.1em solid #b0b7bb;
    border-bottom: 0.1em solid #b0b7bb;
    border-right: none;
    border-top-left-radius: 0.3em;
    border-top-right-radius: 0;
    margin: 0px 3.2em 0px 0px;
}

.nav-tabs > li > a:before {
    content: '';
    position: absolute;
    top: -0.1em;
    right: -2em;
    height: 2em;
    width: 2em;
    background: white;
    border-left: none;
    border-top: 0.1em solid #b0b7bb;
    border-bottom: 0.1em solid #b0b7bb;
    border-right: none;
}

.nav-tabs > li > a:after {
    content: '';
    position: absolute;
    top: -0.1em;
    right: -3em;
    height: 2em;
    width: 2em;
    background: white;
    padding: 0px;
    margin: 0px;
    -webkit-transform: skew(0deg, 0deg);
    -moz-transform: skew(0deg, 0deg);
    -ms-transform: skew(0deg, 0deg);
    -o-transform: skew(0deg, 0deg);
    transform:  skew(20deg, 0deg);
    border-left: none;
    border-top: 0.1em solid #b0b7bb;
    border-bottom: 0.1em solid #b0b7bb;
    border-right: 0.1em solid #b0b7bb;
}

.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
    color: white;
    border-left: 0.1em solid #b0b7bb;
    border-top: 0.1em solid #b0b7bb;
    border-bottom: 0.1em solid #b0b7bb;
    border-right: none;
    background: #0066cc;
}

.nav-tabs > li.active > a:before {
    background: #0066cc;
}

.nav-tabs > li.active > a:after {
    background: #0066cc;
}

.nav-tabs {
    border: 0 none;
    padding: 0;
    margin: 0;
}

.tab-content {

}

Full plunk is here http://plnkr.co/edit/FViETgumIqWCWzQjo8Ff?p=preview .
The question is how to get rid of these glitches. Any help is highly appreciated.
Best regards, Eugene.

A: Its your transform:  skew(20deg, 0deg); on the .nav-tabs > li > a:after  I understand that you are trying to achieve a 'slanted' effect, but the skew is skewing by 20degs after the element per the css rules.
MDN suggests not using it:
https://developer.mozilla.org/en-US/docs/Web/CSS/transform#skew
You may want to try this alternative technique.
http://lea.verou.me/2013/10/slanted-tabs-with-css-3d-transforms/


text:
Q: Applying Android Dialog Animations? I want to set animation to my Dialog.  The challenge here is that I want to do this programatically.
The reason for that is I have too many different size of dialogs and I don't want to create a new animation file for each type of dialog.
As of now, this if what I am doing:
res/anim/anim_myDialog_SlideUp.xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:shareInterpolator="false">

   <translate android:fromXDelta="0%"
        android:toXDelta="0%"
        android:fromYDelta="200%"
        android:toYDelta="0%"
        android:duration="400"/>
</set>

res/anim/anim_myDialog_SlideDown.xml file:
<?xml version="1.0" encoding="UTF-8" ?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
   android:shareInterpolator="false">

   <translate android:fromXDelta="0%"
        android:toXDelta="0%"
        android:fromYDelta="0"
        android:toYDelta="200%"
        android:duration="400"/>
</set>

In my res/values/styles.xml file:
<style name="slideUpAndDown">
    <item name="android:windowEnterAnimation">@anim/anim_myDialog_SlideUp</item>
    <item name="android:windowExitAnimation">@anim/anim_myDialog_SlideDown</item>
</style>

<style name="myDialogSlideUpAndDown" parent="@android:style/Theme.Dialog">
    <item name="android:windowAnimationStyle">@style/slideUpAndDown</item>
</style>

In my MainActivity.cs file:
Dialog myDialog = new Dialog(this, Resource.Style.myDialogSlideUpAndDown);

I can create the animations programmatically with no problem.  The problem is how can I set those animations to my Dialog?
If I create a Dialog and not set it's style in the constructor:
Dialog myDialog = new Dialog(this);

Then I have the option to do this to set it's animation:
myDialog.Window.SetWindowAnimations(int);

SetWindowAnimations requires an int.  Can I create this animation int manually?
Sorry for the long explanation and thank you for your time.


text:
Q: How do I solve a bounded ODE with Maple? My task is to solve the ordinary differential equation $x^2y'' + 4xy' + (2+x^2)y = x^2$ with initial conditions $y(2\pi)=1$ and $y'(2\pi)=0$ on the interval $[0.5, 40]$. When I enter this into Maple with dsolve, nothing happens. What am I doing wrong?
I'm using Maple 2015. This is my Maple equation:
dsolve({x^2*(diff(y(x), x, x))+4*(diff(xy(x), x))+(x^2+2)*y(x) = x^2, y(2*Pi) = 1, (D(y))(2*Pi) = 0})

A: hint
Just replace the term 4*diff(xy(x), x)
by 4*x*diff(y(x), x).


text:
Q: Как связать две базы Можно ли связать две базы, возможно при помощи оператора where?
Я хотел создать комментарии к самописным новостям, но когда я написал
 $resulc =mysql_query("select * from ` comment` where `new_id`   ='"$result['id']"' order by dask");

выводится только последняя новость, а комментариев вообще нет.
С помощью echo $result; пробовал, и выводил с помощью цикла while fetch_array.

A: Присоединяюсь к предыдущему коментатору, либо у вас просто ошибка в запросе вот тут:
comment
лишний пробел.


text:
Q: Spark jobs running on EMR cluster. system.exit(0) used to gracefully completion of job but still Step on EMR fails In spark job. I am using if file not found the system.exit(0). It should gracefully complete the job. Locally It is successfully completed. But when I am running on EMR. Step is failing.

A: EMR uses YARN for cluster management and launching Spark applications. So when you're running a Spark app with --deploy-mode: cluster in EMR, the Spark application code is not running in a JVM on its own, but is rather executed by the ApplicationMaster class.
Browsing through the ApplicationMaster code can explain what happens when you try to execute System.exit(). The user application is launched in startUserApplication, and then the finish method is called after the user application returns. However, when you call System.exit(0), what is executed instead is a shutdown hook which sees that your code hasn't finished successfully, and marks it as an EXIT_EARLY failure. It also has this useful comment:
  // The default state of ApplicationMaster is failed if it is invoked by shut down hook.
  // This behavior is different compared to 1.x version.
  // If user application is exited ahead of time by calling System.exit(N), here mark
  // this application as failed with EXIT_EARLY. For a good shutdown, user shouldn't call
  // System.exit(0) to terminate the application.


text:
Q: Why is this Class' object not serialized properly in different processes? Context
I made a Java application, and need to run two instances of that application, synchronizing some of their attributes via socket each time there's some change. To communicate those changes, Serializable objects are sent through a socket using ObjectStreams (input and output) using read/writeUTF() for an identifier, and read/writeObject() and flush(). The app is the exact same .jar, run twice with some changes like having different ports and ip (if necessary).
Problem
I noticed that objects of some of my classes (e.g. Notification) were sent and received without any troubles, but objects from another class (RegisteredUsers) weren't sent (or received) properly. So I ran some tests to send objects between the two apps and found that the object is being sent and isn't null, it's attribute (a HashMap<String,User>) is also being sent and isn't null, but is always empty.
So I decided to scale it down to what the problem was exactly: I'm trying to write an object through a Stream, and read it in a different process of the same .jar, and with most classes it seems to work, but it doesn't with one.
There seems to be something I'm missing or don't understand about this serialization process, if the object is written and read during the execution of the same process it works, but not if this object is read on another instance of the same app. I even added a HashMap to Notification with the same creation process, but it still works, I really don't get it, what am I missing?
Code
I have taken some code from the bigger app and trimmed it down to the basic problem if anyone wants to test it. To reproduce the errors, run Main1, which will create the two files with an object persisted in each one (one with a Notification object and the other with a RegisteredUsers object) and shows their information, then Main2, which reads them from the files and shows their information, and the problem should be printed. That being that reg3's HashMap is empty and thus neither of the Users are registered.
Main1
public class Main1 {

    public static void main(String[] args) {
        String regFile = "registry.txt";
        String notificationFile = "notification.txt";
        Persistence pers = new Persistence();

        RegisteredUsers reg1 = new RegisteredUsers();
        RegisteredUsers reg2 = new RegisteredUsers();

        reg1.register("Name1", "127.0.0.1");
        reg1.register("Name2", "127.0.0.1");

        try {
            pers.writeReg(reg1, regFile);
        } catch (IOException e) {
            System.out.println("Error writing registry.");
        }
        try {
            reg2 = pers.readReg(regFile);
        } catch (IOException e) {
            System.out.println("Error reading registry.");
        }
        System.out.println("Original registry: ");
        System.out.println(reg1.isRegistered("Name1") + " " + reg1.isRegistered("Name2"));
        System.out.println("Registry read from file: ");
        System.out.println(reg2.isRegistered("Name1") + " " + reg2.isRegistered("Name2"));

        Notification noti1 = new Notification("Name", "127.0.0.1");
        Notification noti2 = new Notification(); //not necesary but it's the way it's done in the bigger app.
        try {
            pers.writeNotif(noti1, notificationFile);
        } catch (IOException e) {
            System.out.println("Error writing notification.");
        }
        try {
            noti2 = pers.readNotif(notificationFile);
        } catch (IOException e) {
            System.out.println("Error reading notification.");
        }
        System.out.println("Original notification: ");
        System.out.println(noti1.getAttributes().get(0) + " " + noti1.getAttributes().get(1));
        System.out.println(noti1.getMap());
        System.out.println("Notification read from file: ");
        System.out.println(noti2.getAttributes().get(0) + " " + noti2.getAttributes().get(1));
        System.out.println(noti2.getMap());
    }
}

Main2
public class Main2 {
    public static void main(String[] args) {
        String regFile = "registry.txt";
        String notificationFile = "notification.txt";
        Persistence pers = new Persistence();
        RegisteredUsers reg3 = new RegisteredUsers();

        try {
            reg3 = pers.readReg(regFile);
        } catch (IOException e) {
            System.out.println("Error reading registry.");
        }
        if (reg3 == null) {
            System.out.println("reg3 is null");
        }
        if (reg3.getMap() == null)
            System.out.println("reg3 has a null map");
        if (reg3.getMap().isEmpty())
            System.out.println("reg3 has an empty map");

        System.out.println("Registry read from file on another process: ");
        System.out.println(reg3.isRegistered("Name1") + " " + reg3.isRegistered("Name2"));

        Notification noti3 = new Notification(); //not necesary but it's the way it's done in the bigger app.
        try {
            noti3 = pers.readNotif(notificationFile);
        } catch (IOException e) {
            System.out.println("Error reading notification.");
        }
        System.out.println("Notification read from file on another process: ");
        System.out.println(noti3.getAttributes().get(0) + " " + noti3.getAttributes().get(1));
        System.out.println(noti3.getMap());
    }
}

A Class to persist the objects in the files:
public class Persistence {
    public void writeReg(RegisteredUsers regus, String file) throws IOException {
        try(FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);) {
                oos.writeObject(regus);
                oos.flush();
            }
    }

    public RegisteredUsers readReg(String file) throws IOException {
        RegisteredUsers regus = null;
        try(FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);) {
                regus = (RegisteredUsers) ois.readObject();
        } catch (ClassNotFoundException e) {
        System.out.println("Wrong class.");
        }
        return regus;
    }

    public void writeNotif(Notification regus, String file) throws IOException {
        try(FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);) {
                oos.writeObject(regus);
                oos.flush();
            }
    }

    public Notification readNotif(String file) throws IOException {
        Notification notif = null;
        try(FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);) {
                notif = (Notification) ois.readObject();
        } catch (ClassNotFoundException e) {
        System.out.println("Wrong class.");
        }
        return notif;
    }
}

RegisteredUsers
public class RegisteredUsers implements Serializable {
    private static HashMap<String, User> users;

    public RegisteredUsers() {
        users = new HashMap<String, User>();
    }

    public HashMap<String, User> getMap() {
        return users;
    }

    public boolean isRegistered(String name) {
        User us = users.get(name);
        return us != null;
    }

    public void register(String name, String ip) {
        users.put(name, new User(name, ip, false));
    }
}

Notification
public class Notification implements Serializable {
    private ArrayList<String> attributes;
    private HashMap<String, User> map = new HashMap<>();

    public Notification() {
    }

    public Notification(String name, String ip) {
        attributes = new ArrayList<String>();
        attributes.add(0, name);
        attributes.add(1, ip);
        map.put(ip, new User(name, ip, false));
    }

    public ArrayList<String> getAttributes() {
        return attributes;
    }

    public HashMap<String, User> getMap() {
        return map;
    }
}

User
public class User implements Serializable {
    private String name;
    private String ip;
    private boolean connection_state;

    public User(String name, String ip, boolean connection_state) {
        this.name = name;
        this.ip = ip;
        this.connection_state = connection_state;
    }
}

A: In java static fields are implicitly transient, and transient fields are not serialized.
If you modify the RegisterdUsers to
public class RegisteredUsers implements Serializable {
    private HashMap<String, User> users; // static modifier is removed
    ...
}

The serialization will work.


text:
Q: Applying ellipsis to one child element but not the other I have the following layout:

  <div1>
    <span1>
    <span2>

  <div2>

Div1 has the property flex-grow: 1 so that it can take up all the available space it needs.
When div1 takes up all the space it needs and when the browser window is made smaller, span1 should get ellipsis while span2 should not.
How can I do this? I have tried various uses of flex, adding more divs, and changing width with no success.
Cheers.

A: What I ended up doing was turning both span1 and span2 into divs. Setting a hardcoded width on span2(div2) then setting the width on span1(div1) to
max-width: -moz-calc(100% - 110px);
max-width: -webkit-calc(100% - 110px);
max-width: -o-calc(100% - 110px);
max-width: calc(100% - 110px);

where 110px is the width on span2(div2)


text:
Q: Rail Object Relationships & JSON Rendering I already know how to include the relationships of has_many & has_one relationships into my JSON rendering.  I even know how to exclude certain attributes when doing so.  For those that don't know here's a good post:
Rails Object Relationships and JSON Rendering
However, what I don't know how to do is have it use the as_json on the child object so I don't have to redeclare it on every parent relationship.
So if I have something like this...
class Customer < ActiveRecord::Base
  has_many :orders

  def as_json(options={ })
    super({ :except => :Password, :include => [:orders] }.merge(options))
  end
end

class Order < ActiveRecord::Base
  has_one :customer

  def as_json(options={ })
    super({ :include => [:customer] }.merge(options))
  end
end

It ends up sending back the Customer password when you view it from the Order perspective.
Ideally I'd want it to follow the rules of the as_json defined in the model so I don't have to put in exceptions for the inclusion of :customer on every child object.
P.S. - This is just an example not a real world scenario.

A: I would encourage you to use the RABL gem versus overriding as_json for all of your models.  It's much easier to define your JSON responses using only the parameters / relationships you want.  You can also easily create parent/children nesting.
https://github.com/nesquena/rabl


text:
Q: Weak keyword with computed properties private weak var _delegate: SomeClassDelegate?
weak var delegate: SomeClassDelegate? {
    get {
        return _delegate
    }
    set {
        _delegate = newValue
    }
}

This is valid code. Is there is any sense in using weak keyword with computed delegate property? Logically no; how compiler will process through this code?

A:
Is there is any sense in using weak keyword with computed delegate property?

Not only is it sensible to do so, but it's important to do so. This computed property is your public interface to this private hidden property. If the computed property lacks the weak qualifier, callers will draw incorrect conclusions about the underlying semantics.
Consider:
class SomeClass {
    private weak var _delegate: SomeClassDelegate?
    var delegate: SomeClassDelegate? {             // whoops; this should be `weak`
        get { return _delegate }
        set { _delegate = newValue }
    }
}

And
class CustomDelegate: SomeClassDelegate { ... }

Then
let object = SomeClass()
object.delegate = CustomDelegate()

In the absence of the the weak qualifier on the computed property and without diving into the implementation details, the programmer might incorrectly conclude that the above is fine. But it's not. Because the underlying _delegate is weak, this CustomDelegate() instance will be deallocated immediately, and the object will end up with no delegate object. And there's no compiler warning about this behavior.
If, however, we fix SomeClass like so:
class SomeClass {
    private weak var _delegate: SomeClassDelegate?
    weak var delegate: SomeClassDelegate? {        // great; matches underlying semantics
        get { return _delegate }
        set { _delegate = newValue }
    }
}

Then the programmer will receive a very helpful warning:
let object = SomeClass()
object.delegate = CustomDelegate()  // results in "Instance will be immediately deallocated because property 'delegate' is 'weak'"

They'll then correctly deduce that they should keep their own strong reference to this CustomDelegate for the code to work properly.
So, bottom line, you don't technically need the weak qualifier on the computed property that is backed by a private weak stored property, but it's prudent to do so to avoid mysterious bugs and/or misunderstandings about the underlying semantics.

A: Computed properties aren't retain by ARC, so you don't need to mark it as weak.
Only one pros that I know about is to ensure that property could be nil in future. You cannot declare it as:
weak var youProperty: YourType {
    get {
        return _yourProperty
    }
    set {
        _yourProperty = newValue
    }
}


text:
Q: Android -Writer Exception: Data is too big I am using below function to pass hexcode to create a bitmap(qr code image) but its throwing the exception.
The exception its throwing is :Writer exception ,Data is too big
The code is as below.
      try {
val qrcodeImage = encodeAsBitmapOne(
    loadImage, )
val baos = ByteArrayOutputStream()

qrcodeImage ? .compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
val base64String = Base64.encodeToString(b, Base64.NO_WRAP)

 } catch (e: WriterException) { // Exception here. Data is
  too big
  print(e)
 }

 @Throws(WriterException::class)
fun encodeAsBitmapOne(str: String ? ): Bitmap ? {
   val hintMap: MutableMap < EncodeHintType,
   Any > = HashMap()
   hintMap[EncodeHintType.MARGIN] = 0
   hintMap[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.L

   val result: BitMatrix =
    try {
        MultiFormatWriter().encode(
            str,
            BarcodeFormat.QR_CODE, 400, 400, hintMap
        )
    } catch (iae: IllegalArgumentException) {
        return null
    }
    val w = result.width
    val h = result.height
    val pixels = IntArray(w * h)
    for (i in 0 until h) {
    val offset = i * w
    for (j in 0 until w) {
        pixels[offset + j] =
            if (result[i, j]) BLACK
        else WHITE
    }
}
    val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
    bitmap.setPixels(pixels, 0, 500, 0, 0, w, h)
    return bitmap
}

Any suggestions on why it's throwing an exception?
Thanks


text: Q: Which statistical test should I use to compare land use type and species abundance? I have abundance data for a species of bird and data on land use type in the areas where the bird data was collected. I want to test whether land use type affects bird abundance but I don't know what type of statistical analyses I should use for this. I know the question is very general, but any starting pointers would be great.


text:
Q: Hide Port Numbers after redirect from IIS to Apache I am running IIS 6.0 and Apache 2.2 on a Windows Server 2003 (dedicated)
I have a default website on IIS which is required on port 80 (default). Apache has been setup to listen on 8080. I need IIS for one sytem and Apache for another.
I have setup an IIS redirect to URL to forward any request to www.myotherdomain.com to www.myotherdomain.com:8080 (all works fine)
The problem is I don't want the port number showing in the address bar. Is there any way i can mask it?

A: I would take a slightly different approach to acheive desired effect.
You could make one server 'forward' requests onto the other - this is known as a 'reverse proxy', and is different to a redirect. It's invisible to the user.
Can you switch Apache to port 80 and IIS to 8080?
If so, you can make Apache forward certain requests to IIS, based on part of the URL.
Apache has a module called mod_proxy. See the example labelled 'Reverse Proxy'
http://httpd.apache.org/docs/2.0/mod/mod_proxy.html
Note: you can also use Apache's mod_rewrite to acheive the same thing, and with more flexibility.
Note2: I don't know if IIS has a similar feature.


text:
Q: JOIN two tables to show already purchased items I have a table where I keep all my templates:
templates

*

*template_id

*template_name

*template_price

These templates can be purchased by a registered user and then are inserted in the payments table:
payments

*

*payment_id

*template_id

*user_id

Is there a way to join these two tables and get not just a list of templates that have been purchased by a certain user, but all the templates? And then figure out from there which ones have already been purchased?
I used this SELECT, but only the ones that the user bought showed up. I would like to have all the rows from templates, but empty in case the user_id doesn't match.
SELECT *
FROM templates
LEFT JOIN payments
ON templates.template_id = payments.template_id
WHERE user_id = 2
GROUP BY templates.template_id

A: SELECT t.*, IF(p.user_id IS NULL, 'not purchased', 'purchased ') AS is_purchased
FROM templates t
LEFT JOIN payments p
ON t.template_id = p.template_id
GROUP BY t.template_id

A: Using a subselect this would be
SELECT t.*, p.payment_id
FROM templates t
LEFT JOIN (
    SELECT * FROM payments WHERE user_id=2
) p ON t.template_id = p.template_id

This shows you all the templates and the payment_id, if there is one for that user.

A: try this:
SELECT *
FROM  templates
LEFT  JOIN payments
ON    templates.template_id = payments.template_id
AND   user_id = 2 -- <-- change Where to and
GROUP BY templates.template_id

A: Try this:
SELECT templates.template_id, templates.template_name, templates.template_price, payments.user_id
FROM  templates
LEFT  JOIN payments
ON    templates.template_id = payments.template_id

This will show all the templates, BUT does not give you an unique list.

A: Try this one using UNION
SELECT  b.template_name, 'purchased' `status`
FROM    payments a
            INNER JOIN templates b
                on a.template_id = b.templateID
WHERE a.user = 2
UNION
SELECT  template_name, 'not purchased' `status`
FROM templates
WHERE template_name NOT IN
(
    SELECT  b.template_name
    FROM    payments a
                INNER JOIN templates b
                    on a.template_id = b.templateID
    WHERE a.user = 2
)


text:
Q: How do I set the height of tableHeaderView (UITableView) with autolayout? I'm been smashing my head against the wall with this for last 3 or 4 hours and I can't seem to figure it out. I have a UIViewController with a full screen UITableView inside of it (there's some other stuff on the screen, which is why I can't use a UITableViewController) and I want to get my tableHeaderView to resize with autolayout. Needless to say, it's not cooperating.
See screenshot below.

Because the overviewLabel (e.g. the "List overview information here." text) has dynamic content, I'm using autolayout to resize it and it's superview. I've got everything resizing nicely, except for the tableHeaderView, which is right below Paralax Table View in the hiearchy.
The only way I've found to resize that header view is programatically, with the following code:
CGRect headerFrame = self.headerView.frame;
headerFrame.size.height = headerFrameHeight;
self.headerView.frame = headerFrame;
[self.listTableView setTableHeaderView:self.headerView];

In this case, headerFrameHeight is a manual calculation of the tableViewHeader height as follows (innerHeaderView is the white area, or the second "View", headerView is tableHeaderView):
CGFloat startingY = self.innerHeaderView.frame.origin.y + self.overviewLabel.frame.origin.y;
CGRect overviewSize = [self.overviewLabel.text
                       boundingRectWithSize:CGSizeMake(290.f, CGFLOAT_MAX)
                       options:NSStringDrawingUsesLineFragmentOrigin
                       attributes:@{NSFontAttributeName: self.overviewLabel.font}
                       context:nil];
CGFloat overviewHeight = overviewSize.size.height;
CGFloat overviewPadding = ([self.overviewLabel.text length] > 0) ? 10 : 0; // If there's no overviewText, eliminate the padding in the overall height.
CGFloat headerFrameHeight = ceilf(startingY + overviewHeight + overviewPadding + 21.f + 10.f);

The manual calculation works, but it's clunky and prone to error if things change in the future. What I want to be able to do is have the tableHeaderView auto-resize based on the provided constraints, like you can anywhere else. But for the life of me, I can't figure it out.
There's several posts on SO about this, but none are clear and ended up confusing me more. Here's a few:

*

*Auto layout on UITableViewHeader

*Auto Layout for tableHeaderView

*Is it possible to use AutoLayout with UITableView's tableHeaderView?

*table header view height is wrong when using auto layout, IB, and font sizes
It doesn't really make sense to change the translatesAutoresizingMaskIntoConstraints property to NO, since that just causes errors for me and doesn't make sense conceptually anyway.
Any help would really be appreciated!
EDIT 1:
Thanks to TomSwift's suggestion, I was able to figure it out. Instead of manually calculating the height of the overview, I can have it calculated for me as follows and then re-set the tableHeaderView as before.
[self.headerView setNeedsLayout];
[self.headerView layoutIfNeeded];
CGFloat height = [self.innerHeaderView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height + self.innerHeaderView.frame.origin.y; // adding the origin because innerHeaderView starts partway down headerView.

CGRect headerFrame = self.headerView.frame;
headerFrame.size.height = height;
self.headerView.frame = headerFrame;
[self.listTableView setTableHeaderView:self.headerView];

Edit 2: As others have noted, the solution posted in Edit 1 doesn't seem to work in viewDidLoad. It does, however, seem to work in viewWillLayoutSubviews. Example code below:
// Note 1: The variable names below don't match the variables above - this is intended to be a simplified "final" answer.
// Note 2: _headerView was previously assigned to tableViewHeader (in loadView in my case since I now do everything programatically).
// Note 3: autoLayout code can be setup programatically in updateViewConstraints.
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];

    [_headerWrapper setNeedsLayout];
    [_headerWrapper layoutIfNeeded];
    CGFloat height = [_headerWrapper systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    CGRect headerFrame = _headerWrapper.frame;
    headerFrame.size.height = height;
    _headerWrapper.frame = headerFrame;
    _tableView.tableHeaderView = _headerWrapper;
}

A: This solution resizes the tableHeaderView and avoids infinite loop in the viewDidLayoutSubviews() method I was having with some of the other answers here:
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let headerView = tableView.tableHeaderView {
        let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
        var headerFrame = headerView.frame

        // comparison necessary to avoid infinite loop
        if height != headerFrame.size.height {
            headerFrame.size.height = height
            headerView.frame = headerFrame
            tableView.tableHeaderView = headerView
        }
    }
}

See also this post: https://stackoverflow.com/a/34689293/1245231

A: You need to use the UIView systemLayoutSizeFittingSize: method to obtain the minimum bounding size of your header view.
I provide further discussion on using this API in this Q/A:
How to resize superview to fit all subviews with autolayout?

A: Your solution using systemLayoutSizeFittingSize: works if the header view is just updated once on each view appearance. In my case, the header view updated multiple times to reflect status changes. But systemLayoutSizeFittingSize: always reported the same size. That is, the size corresponding to the first update.
To get systemLayoutSizeFittingSize: to return the correct size after each update I had to first remove the table header view before updating it and re-adding it:
self.listTableView.tableHeaderView = nil;
[self.headerView removeFromSuperview];

A: I've found an elegant way to way to use auto layout to resize table headers, with and without animation.
Simply add this to your View Controller.
func sizeHeaderToFit(tableView: UITableView) {
    if let headerView = tableView.tableHeaderView {
        let height = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        var frame = headerView.frame
        frame.size.height = height
        headerView.frame = frame
        tableView.tableHeaderView = headerView
        headerView.setNeedsLayout()
        headerView.layoutIfNeeded()
    }
}

To resize according to a dynamically changing label:
@IBAction func addMoreText(sender: AnyObject) {
    self.label.text = self.label.text! + "\nThis header can dynamically resize according to its contents."
}

override func viewDidLayoutSubviews() {
    // viewDidLayoutSubviews is called when labels change.
    super.viewDidLayoutSubviews()
    sizeHeaderToFit(tableView)
}

To animate a resize according to a changes in a constraint:
@IBOutlet weak var makeThisTallerHeight: NSLayoutConstraint!

@IBAction func makeThisTaller(sender: AnyObject) {

    UIView.animateWithDuration(0.3) {
        self.tableView.beginUpdates()
        self.makeThisTallerHeight.constant += 20
        self.sizeHeaderToFit(self.tableView)
        self.tableView.endUpdates()
    }
}

See the AutoResizingHeader project to see this in action.
https://github.com/p-sun/Swift2-iOS9-UI

A: I really battled with this one and plonking the setup into viewDidLoad didn't work for me since the frame is not set in viewDidLoad, I also ended up with tons of messy warnings where the encapsulated auto layout height of the header was being reduced to 0. I only noticed the issue on iPad when presenting a tableView in a Form presentation.
What solved the issue for me was setting the tableViewHeader in viewWillLayoutSubviews rather than in viewDidLoad.
func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        if tableView.tableViewHeaderView == nil {
            let header: MyHeaderView = MyHeaderView.createHeaderView()
            header.setNeedsUpdateConstraints()
            header.updateConstraintsIfNeeded()
            header.frame = CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), CGFloat.max)
            var newFrame = header.frame
            header.setNeedsLayout()
            header.layoutIfNeeded()
            let newSize = header.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
            newFrame.size.height = newSize.height
            header.frame = newFrame
            self.tableView.tableHeaderView = header
        }
    }

A: This worked for me on ios10 and Xcode 8
func layoutTableHeaderView() {

    guard let headerView = tableView.tableHeaderView else { return }
    headerView.translatesAutoresizingMaskIntoConstraints = false

    let headerWidth = headerView.bounds.size.width;
    let temporaryWidthConstraints = NSLayoutConstraint.constraintsWithVisualFormat("[headerView(width)]", options: NSLayoutFormatOptions(rawValue: UInt(0)), metrics: ["width": headerWidth], views: ["headerView": headerView])

    headerView.addConstraints(temporaryWidthConstraints)

    headerView.setNeedsLayout()
    headerView.layoutIfNeeded()

    let headerSize = headerView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
    let height = headerSize.height
    var frame = headerView.frame

    frame.size.height = height
    headerView.frame = frame

    self.tableView.tableHeaderView = headerView

    headerView.removeConstraints(temporaryWidthConstraints)
    headerView.translatesAutoresizingMaskIntoConstraints = true

}

A: It works for both header view and footer just replace the header with footer
func sizeHeaderToFit() {
    if let headerView = tableView.tableHeaderView {

        headerView.setNeedsLayout()
        headerView.layoutIfNeeded()

        let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
        var frame = headerView.frame
        frame.size.height = height
        headerView.frame = frame

        tableView.tableHeaderView = headerView
    }
}

A: For iOS 12 and above, the following steps will ensure autolayout works properly in both your table and the header.

*

*Create your tableView first, then the header.

*At the end of your header creation code, call:

[headerV setNeedsLayout];
[headerV layoutIfNeeded];

*Upon orientation change, mark the header for layout again and reload the table, this needs to happen slightly after the orientation change is reported:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 *NSEC_PER_SEC), dispatch_get_main_queue(), ^{

  [tableV.tableHeaderView setNeedsLayout];
  [tableV.tableHeaderView layoutIfNeeded];
  [tableV reloadData];});

A: In my case viewDidLayoutSubviews worked better. viewWillLayoutSubviews causes white lines of a tableView to appear. Also I added checking if my headerView object already exists.
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    if ( ! self.userHeaderView ) {
        // Setup HeaderView
        self.userHeaderView = [[[NSBundle mainBundle] loadNibNamed:@"SSUserHeaderView" owner:self options:nil] objectAtIndex:0];
        [self.userHeaderView setNeedsLayout];
        [self.userHeaderView layoutIfNeeded];
        CGFloat height = [self.userHeaderView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
        CGRect headerFrame = self.userHeaderView.frame;
        headerFrame.size.height = height;
        self.userHeaderView.frame = headerFrame;
        self.tableView.tableHeaderView = self.userHeaderView;

        // Update HeaderView with data
        [self.userHeaderView updateWithProfileData];
    }
}

A: It is quite possible to use generic AutoLayout-based UIView with any AL inner subview structure as a tableHeaderView.
The only thing one needs is to set a simple tableFooterView before!
Let self.headerView is some constraint-based UIView.
- (void)viewDidLoad {

    ........................

    self.tableView.tableFooterView = [UIView new];

    [self.headerView layoutIfNeeded]; // to set initial size

    self.tableView.tableHeaderView = self.headerView;

    [self.tableView.leadingAnchor constraintEqualToAnchor:self.headerView.leadingAnchor].active = YES;
    [self.tableView.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor].active = YES;
    [self.tableView.topAnchor constraintEqualToAnchor:self.headerView.topAnchor].active = YES;

    // and the key constraint
    [self.tableFooterView.trailingAnchor constraintEqualToAnchor:self.headerView.trailingAnchor].active = YES;
}

If self.headerView changes height under UI rotation one have to implement
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    [coordinator animateAlongsideTransition: ^(id<UIViewControllerTransitionCoordinatorContext> context) {
        // needed to resize header height
        self.tableView.tableHeaderView = self.headerView;
    } completion: NULL];
}

One can use ObjC category for this purpose
@interface UITableView (AMHeaderView)
- (void)am_insertHeaderView:(UIView *)headerView;
@end

@implementation UITableView (AMHeaderView)

- (void)am_insertHeaderView:(UIView *)headerView {

    NSAssert(self.tableFooterView, @"Need to define tableFooterView first!");

    [headerView layoutIfNeeded];

    self.tableHeaderView = headerView;

    [self.leadingAnchor constraintEqualToAnchor:headerView.leadingAnchor].active = YES;
    [self.trailingAnchor constraintEqualToAnchor:headerView.trailingAnchor].active = YES;
    [self.topAnchor constraintEqualToAnchor:headerView.topAnchor].active = YES;

    [self.tableFooterView.trailingAnchor constraintEqualToAnchor:headerView.trailingAnchor].active = YES;
}
@end

And also Swift extension
extension UITableView {

    func am_insertHeaderView2(_ headerView: UIView) {

        assert(tableFooterView != nil, "Need to define tableFooterView first!")

        headerView.layoutIfNeeded()

        tableHeaderView = headerView

        leadingAnchor.constraint(equalTo: headerView.leadingAnchor).isActive = true
        trailingAnchor.constraint(equalTo: headerView.trailingAnchor).isActive = true
        topAnchor.constraint(equalTo: headerView.topAnchor).isActive = true

        tableFooterView?.trailingAnchor.constraint(equalTo: headerView.trailingAnchor).isActive = true
    }
}

A: This solution works perfectly for me:
https://spin.atomicobject.com/2017/08/11/swift-extending-uitableviewcontroller/
It extends the UITableViewController. But if you are just using a UITableView, it will still work, just extend the UITableView instead of the UITableViewController.
Call the methods sizeHeaderToFit() or sizeFooterToFit() whenever there is an event that changes the tableViewHeader height.

A: Copied from this post
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let headerView = tableView.tableHeaderView {

        let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        var headerFrame = headerView.frame

        //Comparison necessary to avoid infinite loop
        if height != headerFrame.size.height {
            headerFrame.size.height = height
            headerView.frame = headerFrame
            tableView.tableHeaderView = headerView
        }
    }
}


text:
Q: How to send data to router link body I am using router link, i want to pass some data to the router body.
So i have code in HTML file as below
routerLink="/detailReports/{{report.id}} - here i want to pass the report name as well to the router data.
So that when i try to retrieve something from ActivatedRouteSnapshot like below i can get the data that i have passed from the routerlink.
private getActivatedComponent(snapshot: ActivatedRouteSnapshot): ActivatedRouteSnapshot {
    if (snapshot.firstChild) {
      return this.getActivatedComponent(snapshot.firstChild);
    }
    return snapshot;
  }

A: If you want to send more information in your request, I recommend you to use query params. You can send more info like this:
<a [routerLink]="['/users']"
   [queryParams]="{ filter: 'new' }"
   queryParamsHandling="merge">
  Users
</a>

You can checkout here https://www.digitalocean.com/community/tutorials/angular-query-parameters


text:
Q: Repeating an audio file without waiting for it to finish - Javascript I am working on a program which plays audio files creating "melodies". The melodies are randomly created and then performed. The pitches are played in intervals of 1-5 seconds. The audio files are about 4 seconds long. At the start of the program I load all the notes, 40-80, and then simply play them when needed.
(The numbers in the array are pitch numbers.) The eventual output is something like this:
audioFile[80].play();
audioFile[64].play();
audioFile[65].play();

But sometimes the same note is performed twice:
audioFile[65].play();
audioFile[65].play();

or:
audioFile[65].play();
audioFile[63].play();
audioFile[72].play();
audioFile[65].play();

In this case 65 is heard only once because the second 65 is waiting for the first to finish, and sometimes it is still playing by the time the second 65 needs to play.
What can I do to make overlapping of the same audio file possible? Thanks!

Context code
Performing a pitch:
let loadedAudioArr=[];
function playPitch(y){ //y = pitch int
    loadedAudioArr[y].play();
}

Loading all the sounds:
function loadSounds(x,r,rr){ //x = instrument; r = range lower; rr = range upper
    for (var z=r; z<=rr; z++){
        loadedAudioArr.push(new Audio ("../audio"+"/"+x+"/"+z+".mp3"));
    }
}

Performing 2 notes, wait, repeat ...
for (var i=0; i<=sequencedNotes-1; i++) {
  (function(num){
      setTimeout(function(){
          playPitch(pitches[num*2]);
          playPitch(pitches[(num*2)+1]);
      }, eval(tempo) * (i+1));
  })(i);
}


text:
Q: Construction of a point with resprect to a triangle For a given  triangle $ABC$, how to construct a point $P$ such that $PA \colon PB \colon PC = 1 \colon 2 \colon4$?

A: Here is a solution:
Orient the triangle such that AC lies on the x-axis and B lies on the y-axis. Then, we have that $A = (-a,0), B = (0,b), C = (0,c)$. Draw circles around each of these points with a radius $r$, $2r$ and $4r$.
If these circles are to meet at a point $(x, y)$, then we have the following simultaneous equations:
$$(x+a)^2 + y^2 = r^2$$
$$x^2 + (y-b)^2 = (2r)^2$$
$$ (x-c)^2 + y^2 = (4r)^2$$
There are three equations and three variables. You can now solve it to obtain, $x$ and $y$ (and $r$ too which will be helpful if you want to physically construct it with a compass).

A: Given points A and B, the locus of points P such that PA:PB = 1:2 (P is twice as far from B as it is from A) is a circle, and similarly for locus PA:PC = 1:4. So draw the two circles, and P is at an intersection of the circles. Note that you may get 0, 1, or 2 possible points for P. In the diagram below I show a situation giving 2 points $P_1$ and $P_2$.

Here is an overview of the construction:
1) Construct point $H$ on $\overline {AB}$ such that $AH = \frac{1}{3}AB$.
2) Construct point $J$ on ray $\overrightarrow {BA} $ (not on $\overline {AB}$) such that $AJ = AB$.
3) Construct the circle that has $\overline {HJ}$ as a diameter.
4) Construct point $U$ on $\overline {AC}$ such that $AU = \frac{1}{5}AC$.
5) Construct point $W$ on ray $\overrightarrow {CA} $  (not on $\overline {AC}$) such that $AW = \frac{1}{3}AC$.
6) Construct the circle that has $\overline {UW}$ as a diameter.
7) Mark point $P$ at an intersection of the circles.
ADDED:
I just realized that it would be easier to construct the 1:2 circle between A and B and the 1:2 circle between B and C. Oh, well, what I showed above also works.
ADDED LATER:
I just had to add a diagram of the better construction using two 1:2 circles. In the diagram below, $AH = \frac13AB$, $AI=AB$, $BQ=\frac13BC$, $BM=BC$, and $\overline {HI}$ and $\overline {MQ}$ are diameters of circles $p$ and $u$ respectively.


text:
Q: pass parameters to pdf metadata in hyperref I'm trying to pass data to metadata setup of the .pdf file with this code  but its brings me an error, when passing the data
\def\author#1{\gdef\insertauthor{#1}\gdef\@author{#1}}
\def\title#1{\gdef\inserttitle{#1}\gdef\@title{#1}}
\def\firstsupervisor#1{\gdef\insertsupervisor{#1}}
\def\secondsupervisor#1{\gdef\insertsupervisor{#1}}
\def\institution#1{\gdef\insertinstitution{#1}}
\def\degree#1{\gdef\insertdegree{#1}}
\def\faculty#1{\gdef\insertfaculty{#1}}
\def\department#1{\gdef\insertdepartment{#1}}
\def\submitdate#1{\gdef\insertsubmitdate{#1}}
\def\keywords#1{\gdef\insertkeywords{#1}}
\submitdate{\number\the\year}

\RequirePackage[final,breaklinks,bookmarks]{hyperref}
\hypersetup{%
    colorlinks=true,allcolors=black,
    pdftitle    = {\inserttitle},
    pdfkeywords = {\insertkeywords},
    pdfauthor   = {\textcopyright\ \insertauthor},
    pdfcreator  = {\LaTeX\ with package \flqq hyperref\frqq},
    pdfproducer = {pdfeTeX-0.\the\pdftexversion\pdftexrevision}
}
\RequirePackage{hypcap}

the error says Undefined control sequence. }

A: \hypersetup comes into action before \title is used, so it tries to get grip of an undefined command \inserttitle at that time. The same is true for \insertauthor and \insertkeywords. LaTeX is complaining on \inserttitle because its the first of those three commands used in \hypersetup.
Since \hypersetup is no preamble-restricted command, it can be used more than once and even in the document body, if needed.
I suggest to use the \title etc. commands to automatically insert the relevant data. This works, as long as \title etc. are not used before hyperref is loaded and preset \hypersetup only with basically-non-author/document content relevant data
Apparently the shown fragment is from a .cls or .sty file, I've built a document around it, wrapping \makeatletter...\makeatother pair around the various \def.... commands there.
\documentclass{article}

\makeatletter

\def\author#1{\gdef\insertauthor{#1}\gdef\@author{#1}\hypersetup{pdfauthor={\textcopyright\ #1}}}
\def\title#1{\gdef\inserttitle{#1}\gdef\@title{#1}\hypersetup{pdftitle={#1}}}
\def\firstsupervisor#1{\gdef\insertsupervisor{#1}}
\def\secondsupervisor#1{\gdef\insertsupervisor{#1}}
\def\institution#1{\gdef\insertinstitution{#1}}
\def\degree#1{\gdef\insertdegree{#1}}
\def\faculty#1{\gdef\insertfaculty{#1}}
\def\department#1{\gdef\insertdepartment{#1}}
\def\submitdate#1{\gdef\insertsubmitdate{#1}}
\def\keywords#1{\gdef\insertkeywords{#1}\hypersetup{pdfkeywords={#1}}}
\submitdate{\number\the\year}

\makeatother

\RequirePackage[final,breaklinks,bookmarks]{hyperref}

\hypersetup{%
    colorlinks=true,allcolors=black,
%    pdftitle    = {\inserttitle},%
%    pdfkeywords = {\insertkeywords},
%    pdfauthor   = {\textcopyright\ \insertauthor},%
    pdfcreator  = {\LaTeX\ with package \flqq hyperref\frqq},
    pdfproducer = {pdfeTeX-0.\the\pdftexversion\pdftexrevision}
}

\title{Theory on Brontosaurs}
\author{Miss Ann Elk}
\keywords{Brontosaurs,Monty Python,LaTeX is fun}

\begin{document}
\maketitle%

Lorem ipsum

\end{document}

Please note, that \maketitle redefines \title, and \author etc. in many classes to become effectively nothing.

A: The first call to \hypersetup where you want to set the PDF document properties requires all of the macros to exist, otherwise there you're receive an error message. My suggestion would therefore be to make sure all of these new \insert... macros exist. Do so by adding
\providecommand{\insertauthor}{}
\providecommand{\inserttitle}{}
\providecommand{\insertfirstsupervisor}{}
\providecommand{\insertsecondsupervisor}{}
\providecommand{\insertinstitution}{}
\providecommand{\insertdegree}{}
\providecommand{\insertfaculty}{}
\providecommand{\insertdepartment}{}
\providecommand{\insertsubmitdate}{}
\providecommand{\insertkeywords}{}

to your preamble. Secondly, delay the setting of PDF document properties until the end of the document using
\AtEndDocument{
  \hypersetup{
    pdftitle    = \inserttitle,
    pdfkeywords = \insertkeywords,
    pdfauthor   = \insertauthor
  }
}


text:
Q: Fabric JS Touch Events I'm working with Fabric js inside a Phonegap application and although the touch events work, the handles are very hard to catch and use. Specifically the rotate and resize handles. If you touch them 90% of the time they just disappear. I tired fingers and styles. Same result. Confirmed the same behavior on ipad pro and my Galaxy note 4. I'm copy/pasting the same demo from their site:
http://fabricjs.com/touch-events
Has anyone experienced this? How can I make those handles easier to touch?

A: Solved it. All I needed to do was increase the size of the handles. It's a property passed to each object type you make.


text:
Q: How can I filter locations by name in my db? Im trying to gather into a list all the locations from my db that has the same name, in order to do that Im using this:
public static List<Location> searchRepe(List<Location>ls){
        List<Location>res=new ArrayList<Location>();
        for(Location l:ls){
            ls.remove(l);
if(ls.stream().anyMatch(x>x.getProvinceName().equals(l.getProvinceName()))){
                res.add(l);}
            ls.add(l);
        }
        return res;
    }

ERROR:Exception in thread "main" java.util.ConcurrentModificationException
I first remove the location of the list and then check if there is another location with the same name. After checking that if the name of the location is in the list I add it to my res list. In any case I will always keep the original list the same because after checking I read the element to the list. I know the error is caused because I remove and add in every iteration but if in every iteration I remove and then add the same element the size of the list will be always the same.
Could someone tell me a better way to do this? If it is possible using java8

A: The foreach statement uses Iterator to retrieve item, and Iterator can't remove item directly, otherwise the method will throw ConcurrentModificationException. So you can remove item from list by following approach:
for (int index = 0; index < list.size(); index++) {
    if(condition){
        list.remove(index);
        index--;
    }
}

In your problem, you can use Multimap which is a new Collection Type in Guava library, like this:
public static List<Location> searchRepe(List<Location>ls){
    Multimap<String,Location> locationMap = HashMultimap.create();
    for (Location l : ls) {
        locationMap.put(l.getProvinceName(),l);
    }
    List<Location> result=new ArrayList<>();
    for (Map.Entry<String, Collection<Location>> entry : locationMap.asMap().entrySet()) {
        Collection<Location> value = entry.getValue();
        if(value.size()>1){
            Location next = value.iterator().next();
            result.add(next);
        }
    }
    return result;
}

Pay attention to this line locationMap.put(l.getProvinceName(),l), the result of put method depends on the equals method in Location class.

A: If you absolutely want to use stream and java8, i believe this is right solution.
Just filter all elements where count of occurrences based on ProvinceName more than one
public static List<Location> searchRepe(List<Location> ls) {

    return ls.stream()
             .filter(
                     location -> ls.stream()
                                   .map(Location::getProvinceName)
                                   .filter(n -> Objects.equals(n, location.getProvinceName()))
                                   .count() > 1L
             )
             .collect(Collectors.toList());
}

or by using grouping by
public static List<Location> searchRepe(List<Location> ls) {

    return ls.stream()
             .collect(Collectors.groupingBy(Location::getProvinceName))
             .entrySet()
             .stream()
             .map(Map.Entry::getValue)
             .filter(entry -> entry.size() > 1)
             .map(entry -> entry.get(1))
             .collect(toList());
}


text:
Q: Qualcomm Atheros weak Wifi signal on Ubuntu 18.04 I am a newbie to Ubuntu and this is my first post on this forum, so please excuse any mistake.
Having said that the issue is after I recently installed Ubuntu 18.04 LTS, I noticed that my Wifi signal is very weak. I have 2 OS, Windows 10 and Ubuntu 18.04. While Windows 10 shows proper signal, in Ubuntu the signal is very weak. I have not even seen full signal anytime, even though when I am literally sitting next to the router.
My Driver details are below:
Command:
lspci

Output:
02:00.0 Network controller: Qualcomm Atheros QCA9377 802.11ac Wireless Network Adapter (rev 31)

Command:
lspci -nnk | grep -A2 0280

Output:
02:00.0 Network controller [0280]: Qualcomm Atheros QCA9377 802.11ac Wireless Network Adapter [168c:0042] (rev 31)
Subsystem: AzureWave QCA9377 802.11ac Wireless Network Adapter [1a3b:2231]
Kernel driver in use: ath10k_pci

Command:
sudo lshw -C network

Output:
*-network
   description: Wireless interface
   product: QCA9377 802.11ac Wireless Network Adapter
   vendor: Qualcomm Atheros
   physical id: 0
   bus info: pci@0000:02:00.0
   logical name: wlp2s0
   version: 31
   serial: 40:9f:38:d4:ac:c3
   width: 64 bits
   clock: 33MHz
   capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
   configuration: broadcast=yes driver=ath10k_pci driverversion=4.15.0-20-generic firmware=WLAN.TF.1.0-00002-QCATFSWPZ-5 ip=192.168.0.15 latency=0 link=yes multicast=yes wireless=IEEE 802.11
   resources: irq:130 memory:ef000000-ef1fffff

I have tried doing the below but to no affect:
sudo modprobe -rv ath10k_pci
sudo modprobe -v ath10k_pci ant_sel=1

My current kernel version is:
4.15.0-20-generic

Any suggestions to improve this?

A: Suggest, after you do
sudo modprobe -rv ath10k_pci

to try
sudo modprobe -v ath10k_pci ant_sel=2

as it might be an RF issue which Windows resolved by using antenna #2.

A: Run in terminal
sudo tee /etc/modprobe.d/rtl8723be.conf <<< "options rtl8723be ant_sel=2"

This will create a config file to make the setting permanent. Then restart.

A: For all other Qualcomm cards...
check this command lspci | grep 'Network'
if output comes as
02:00.0 Network controller: Qualcomm Atheros QCA9377 802.11ac Wireless Network Adapter (rev 31)

Then this solution may work for you
sudo apt-get update
sudo apt-get install linux-headers-generic build-essential
wget https://www.kernel.org/pub/linux/kernel/projects/backports/2015/11/20/backports-20151120.tar.gz
tar -zxvf backports-20151120.tar.gz
cd backports-20151120
make defconfig-ath10k
make
sudo make install

ignore if you get any errors or warnings for make

A: This solution given by Manas worked for me with some minor tweak.
Before executing the wget command check for you linux kernel version.
$ uname -r

Then go to https://mirrors.edge.kernel.org/pub/linux/kernel/projects/backports/stable/ and check for the closest kernel version available there and then download the backports tar file using the following command.
$ wget https://kernel.org/pub/linux/kernel/projects/backports/stable/v5.1.16/backports-5.1.16-1.tar.gz

Here 5.1.16 is the linux kernel version.
Then run these. After successful installation of these three commands reboot.
$ make defconfig-ath10k
$ make
$ sudo make install

Reboot.


text:
Q: getting error during selenium automation selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: python i need to click second row submit buttonI am trying to use the XPath of the tab present on the website and collected XPath using chrome/firefox but it seems that every time I am getting an exception as below:
I have kept sleep time and can see website loading pretty early than the sleep time still getting the errors.
 said_input = driver.find_element_by_xpath('//*[@id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder3Col_txtSubmitCase"]')
 print(said_input)
 said_input.send_keys(said)

exception:
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder3Col_txtSubmitCase"]

One thing is that i have navigated to another page of website by clicking one of the menu button will this driver.find_element_by_xpath will be able to locate it. if not how can i do so in case if i hae to browse through multiple pages and fill few forms.


text:
Q: What performance improvements can I make to Symfony + Doctrine? I've recently built a reasonably complex database application for a university handling almost 200 tables. Some tables can (e.g. Publications) hold 30 or more fields and store 10 one-to-one FK relations and up to 2 or 3 many-to-many FK relations (using crossreference-ref tables). I use integer IDs throughout and normalisation has been key every step of the way. AJAX is minimal and most pages are standard CRUD forms/processes.
I used Symfony 1.4, and Doctrine ORM 1.2, MySQL, PHP.
While the benefits to development time and ease of maintenance have been enormous (in using an MVC and ORM), we've been having problems with speed. That is, when we have more than a few users logged in and active at any one time the application slows considerbly (up to 20 seconds to save or edit a record).
We're currently engaged in discussions with our SysAdmin but they say that we should have more than enough power. With 6 or more users engaged in activity, we end up queuing 4 CPUs in a virtual server environment while memory usage is low (no bleeds).
Of course, we're considering multi-threading our mySQL application (if this will help), refining our code (though much of it is generated by the MVC) and refining our cache usage (this could be better, though the majority of the screen used is user-login specific and dynamic); we've installed APC, extra memory, de-fragmented our database, I've tried unsetting all recordsets (though I understand this is now automatic within the ORM), instigating manual garbage recycling...
But the question I'm asking is whether mySQL, PHP, and Symfony MVC was actually a poor choice for developing an application of this size in the first place? If so, what do people normally use/recommend for a web-based database interface application of this kind of size/complexity?

A: I don't have any experience with Symfony or Doctrine. However, there are certainly larger sites than yours that are built on these projects. DailyMotion for instance uses both, and it serves a heck of a lot more than a few simultaneous users.
Likewise, PHP and MySQL are used on sites as large as Wikipedia, so scalability should not be a problem. (BTW, MySQL should be multithreaded by default—one thread per connection.)
Of course, reasonable performance is relative. If you're trying to run a site serving 200 concurrent requests off a beige box sitting in a closet, then you may need to optimize your code a lot more than a Fortune 500 company with their own data centers.
The obvious thing to do is actually profile your application and see where the bottleneck is. Profiling MySQL queries is pretty simple, and there are also assorted PHP profiling tools like Xdebug. From there you can figure out whether you should switch frameworks, ORMs (or ditch ORM altogether), databases, or refactor some code, or just invest in more processing power.

A: The best way to speed up complex database operation is not calling them :).
So analyize which parts of your application you can cache.
Symfony has a pretty well caching system (in symfony2 even better) that can be used pretty granulary.
On database side another way would be to use views or nested sets to store aggregated data.
Try to find parts where this is appropriate.


text:
Q: How to seed utcnow() for EF Core and Postgres I am trying to seed some values for a DateTime property in EF Core. Currently, it is seeding DateTime.Now with the following code
modelBuilder.Entity<AnalysisFile>()
                .Property(analysisFile => analysisFile.TimeCreated)
                .HasDefaultValueSql("now()");

So now() is basically a native Postgres method that is doing the magic here. I searched online and also looked at the Postgres documentation to see if there is a function that gives me something like utcnow().
https://www.postgresql.org/docs/current/functions-datetime.html
I was not able to find anything like that. Maybe that functionality does not exist in Postgres. Then I started wondering if there is any way to specify timezone in conjunction with `HasDefaultValueSql. I did not find much help there as well.
Am I missing something here? I thought this would be straightforward but I am not able to find any functionality in either EF Core or Postgres that does it natively. Any suggestions?

A: I created a constants file.
public static class SqlKeyWords
{
    public const string CurrentUserDefault = "CURRENT_USER"; /* SqlServer, PostGres */

    //public const string CurrentTimeStamp = "GETUTCDATE()"; /* SqlServer */

    public const string CurrentTimeStamp = "timezone('utc', now())"; /* PostGres */
}

and then I refer to that single source of truth in my "Map":
using System.Diagnostics.CodeAnalysis;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace MyCompany.MyEfLayer.OrmMaps
{
    [ExcludeFromCodeCoverage]
    public class MyThingMap : IEntityTypeConfiguration<MyThingEntity>
    {
        public void Configure(EntityTypeBuilder<MyThingEntity> builder)
        {

            builder.Property(cn => cn.LastUpdated).HasColumnName("LastUpdatedColumn");
            builder.Property(dvsql => dvsql.LastUpdated).HasDefaultValueSql(SqlKeyWords.CurrentTimeStamp);
            builder.Property(req => req.LastUpdated).IsRequired();

        }
    }
}


text:
Q: perl find odd odd number in argument Example:
./odd.pl a a b b b

output:
b b b

find a odd number argument and print
I tried:
my %count;
foreach $arg (@ARGV) {
    $count{$arg}++;
    if ($count{$arg} % 2 eq 1) { print "$arg"; }
}

print "\n";

A: It looks like you want to print the values that appear an odd number of times.
The problem with your attempt is that you check the counts before you finish obtaining the count of the different values!
Solution:
my %counts;
for my $arg (@ARGV) {
    ++$counts{$arg};
}

my @matches;
for my $arg (@ARGV) {
    if ($counts{$arg} % 2 == 1) {
        push @matches, $arg;
    }
}

print("@matches\n");

Note that I changed eq to == because eq is for string comparisons.
Simplified solution:
my %counts;
++$counts{$_} for @ARGV;
my @matches = grep { $counts{$_} % 2 } @ARGV;
print("@matches\n");


text:
Q: Rails tutorial 6.3.4 authenticate error I'm doing the ruby on rails tutorial book and I have come to an error. I checked everything he wrote and I still get the error. It tells me authenticate is an undefined method for nil:NILclass. I don't know what to do.
user.rb:
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
attr_accessor :password, :password_confirmation
has_secure password

before_save { |user| user.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX}, uniqueness:  {case_sensitive: false}
validates :password, presence: true, length:{ minimum: 6 }
validates :password_confirmation, presence: true
end

and (some of) my user_spec.rb
before do
  @user = User.new(name: "Example User", email: "User@example", password: "foobar", password_confirmation:"foobar")
end

    subject { @user }

it { should respond_to(:password_digest) }
it { should respond_to(:password) }
it { should respond_to(:password_confirmation) }
it { should respond_to(:authenticate) }

it { should be_valid }

       #    USER.PASSWORD

describe "when password is not present" do
  before { @user.password = @user.password_confirmation = " "}
  it {should_not be_valid}
end

describe "when password is not present" do
  before { @user.password_confirmation = "mismatch" }
  it { should_not be_valid }

describe "when password is nil" do
  before { @user.password_confirmation = nil }
  it {should_not be_valid}
end

describe "with a password that's too short" do
  before { @user.password = @user.password_confirmation = "a" * 5 }
  it { should be_valid }
end

describe "return value of authenticate method" do
  before { @user.save }
  let(:found_user) { User.find_by_email(@user.email) }

  describe "with valid password" do
    it { should == found_user.authenticate(@user.password) }
    end

  describe "with invalid password" do
    let(:user_for_invalid_password) { found_user.authenticate("invalid") }

    it {should_not == user_for_invalid_password}
    specify { user_for_invalid_password.should be_false}
  end
end
end

Thanks alot for all that can help.

A: I am new in ruby on rails.I just pass this tutorials. when I doing I found errors same you.
I hope my solved can help you.
in your user.rb
remove line: attr_accessor  and edit has_secure password to has_secure_password (add underscore)
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
has_secure_password
enter code here
  before_save { |user| user.email = email.downcase }
  validates :name, presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, format: { with: VALID_EMAIL_REGEX},
  uniqueness:  {case_sensitive: false}
  validates :password, presence: true, length:{ minimum: 6 }
  validates :password_confirmation, presence: true
end

in your user.spec.rb
1) you missed 'end' tag in describe "when password is not present"
2) Change test describe 'with a password that's too short'
from it { should be_valid} to it { should be_invalid }   I think it should be invalid if password less than 5.
3) finally if you want to test pass authenticate you should change your email end with .com or any that matches with VALID_EMAIL_REGEX in user.rb like:
before do
@user = User.new(name: "Example User", email: "User@example.com",
password: "foobar", password_confirmation:"foobar")
end

I wish this help you.
sorry for my bad english.


text:
Q: Is there a way to tell Gradle to always search in cache and then search online? NPM acts like that, Nuget acts like that. They first search their global cache to see if they find a match of the requested dependency, then if not found, they fallback online automatically, find the requested dependency, cache it for future reuse and everything works just fine.
With Gradle it doesn't seem to be the case. When building, it notifies "go offline" and when going offline by adding a new dependency it can't find it and complaints that "no match found in cache for x in offline mode".
Is there a way to tell Gradle/Android Studio to not be so dumb and automatically do these things?
I mean this problem is solved for decades. The very concept of fallback and priority/order has been there from the beginning of the time. Why Gradle can't follow such a simple pattern?

A: Gradle does what you describe and expect. However, if it has been configured in offline mode, which appears to be your case, then it will not go online if things are missing in the local cache.


text:
Q: Creating a function that returns index of minimum value in a list? def minimum_index(xs):
    minimum_index=xs[0]
    for i in range(len(xs)):
    if xs[i]<xs[i+1]:
        min_i=i
    elif xs[i]>xs[i+1]:
        min_i=i+1
        continue
return minimum_index

This looks correct to me, but for some reason, I keep trying to change things around and I either get an incorrect return value or no return value.

A: Simplify the function
def minimum_index(xs):
    ans = 0
    for i in range(1, len(xs)):
        if xs[i] < xs[ans]:
            ans = i
    return ans

or in a more pythonic way
minimum_index = lambda xs: xs.index(min(xs))

A: Your code has at least two issues: You seem to have two variables that stand for the minimal index, and you mix them up. Also, it is not enough to compare subsequent elements, you will have to compare to the minimal value. Try this:

def minimum_index(xs):
    minx = xs[0]
    mini = 0
    for i in range(1,len(xs)):
        if xs[i]<minx:
            mini = i
            minx = xs[i]
    return mini

If you are using numpy, then you can simply use their numpy.argmin(xs).


text:
Q: Программная реализация I2C шины через расширитель портов Есть:

*

*МК (Ардуино или Esp8266)

*8 расширителей портов MCP23017

*8 датчиков влажности HTU21D с интерфейсом I2C.

У расширителей портов есть возможность менять адрес в I2C шине используя перемычки A0-A2 и они подключаются к одной общей шине с Мастером (Ардуино или Esp8266). У датчиков влажности такого функционала нет, у них одинаковый адрес. Можно ли подключить датчики влажности с интерфейсом I2C к расширителю портов по GPIO и программно реализовать шину I2C.
Необходимо с МК получить доступ к данным датчиков влажности через расширитель портов. Как это реализовать?
Теоретическая схема такого подключения.


text:
Q: Alternative methods to solve DLP for $GL_{3}(\mathbb{F}_2)$ Is there (or rather what is) a more elegant/efficient way to solve the DLP for $g^x=h$ in $GL_3(\mathbb{F}_2)$ where
$$g=\begin{pmatrix}0 &1 & 1 \\ 1 &1 &1 \\ 1&0&1 \end{pmatrix}$$
and
$$h=\begin{pmatrix}1 &1 & 0 \\ 0 &1 &1 \\ 1&1&1 \end{pmatrix}$$
other than using the brute force method which will reveal the answer to be $x=6+7m$?

A: The characteristic polynomial of $g$ over $\mathbb F_2$ is $p(t) = t^3 + t + 1$ which is irreducible.  The splitting field of this polynomial has $2^3 = 8$ elements, so any nonzero element of it satisfies $r^7 = 1$.  The eigenvalues of $g^7$ are all $1$, and $g^7$ must be diagonalizable over the splitting field since $g$ is, so we must have $g^7 = I$.
Now if
$h = g^k$, an eigenvector of $g$ for eigenvalue $r$ will be an eigenvector of $h$ corresponding for eigenvalue $r^k$.  An eigenvector of $g$ for eigenvalue $r$ is
$$ v = \pmatrix{ r\cr r+1\cr r^2 + r + 1\cr}$$
and
$$ h v = \pmatrix{1 \cr r^2 \cr r^2 + r\cr} = r^{-1} v$$
Thus $h = g^{-1} = g^{6 + 7 m}$ for any $m$.


text:
Q: Adding extra legend information using ggplot2 I'm trying to add extra information to the legend in this stacked bar plot, but the information comes from a different data frame. What I want to do is to add a legend line (beneath the others) that has a solid dot and the text is "Recorded Contaminant Values". I've tried all kinds of stuff, and nothing has worked. Here is the code I have so far:
library(ggplot2)

columns <- unlist(lapply(1:4, function(x) rep(x,32)))
labels <- c("SuperDeduper", "AdapterTrimmer", "QWindowTrim", "Reads Remaining")
diffs <- c(35666631, 36774314, 36193131, 36140701, 41584694, 33888805,
41314700, 36430192, 36164379, 37684733, 36156080, 33443533, 28441368,
33025395, 31980771, 29354621, 29042522, 33575127, 34144001, 35359005,
34037116, 34030228, 30695581, 27310435, 33448959, 39547820, 37183407,
40013726, 35679976, 33506154, 31546743, 33917856, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49237692,
50180374, 47276553, 48635427, 54147578, 39709279, 47969795, 44230737,
52976902, 55651916, 55788100, 54082912, 50965229, 48481376, 54821029,
55814879, 50763305, 54242897, 57001053, 54111642, 50922042, 55563781,
48964424, 46377355, 46074343, 57514467, 51998501, 58061503, 55020584,
54041618, 48210015, 55463206)

samps <- c("CHOR1", "CHOR10", "CHOR2", "CHOR3", "CHOR4", "CHOR5", "CHOR6",
"CHOR7", "CHOR8", "CHOR9", "CPC1", "CPC10", "CPC11", "CPC2",
"CPC3", "CPC4", "CPC5", "CPC6", "CPC7", "CPC8", "CPC9", "CPP1",
"CPP2", "CPP3", "CPP4", "CPP5", "CPP6", "NB1", "NB2", "NB3",
"NB4", "NB5", "CHOR1", "CHOR10", "CHOR2", "CHOR3", "CHOR4", "CHOR5",
"CHOR6", "CHOR7", "CHOR8", "CHOR9", "CPC1", "CPC10", "CPC11",
"CPC2", "CPC3", "CPC4", "CPC5", "CPC6", "CPC7", "CPC8", "CPC9",
"CPP1", "CPP2", "CPP3", "CPP4", "CPP5", "CPP6", "NB1", "NB2",
"NB3", "NB4", "NB5", "CHOR1", "CHOR10", "CHOR2", "CHOR3", "CHOR4",
"CHOR5", "CHOR6", "CHOR7", "CHOR8", "CHOR9", "CPC1", "CPC10",
"CPC11", "CPC2", "CPC3", "CPC4", "CPC5", "CPC6", "CPC7", "CPC8",
"CPC9", "CPP1", "CPP2", "CPP3", "CPP4", "CPP5", "CPP6", "NB1",
"NB2", "NB3", "NB4", "NB5", "CHOR1", "CHOR10", "CHOR2", "CHOR3",
"CHOR4", "CHOR5", "CHOR6", "CHOR7", "CHOR8", "CHOR9", "CPC1",
"CPC10", "CPC11", "CPC2", "CPC3", "CPC4", "CPC5", "CPC6", "CPC7",
"CPC8", "CPC9", "CPP1", "CPP2", "CPP3", "CPP4", "CPP5", "CPP6",
"NB1", "NB2", "NB3", "NB4", "NB5")

dffs <- structure(list(x = structure(1:32, .Label = c("CHOR1", "CHOR10",
"CHOR2", "CHOR3", "CHOR4", "CHOR5", "CHOR6", "CHOR7", "CHOR8",
"CHOR9", "CPC1", "CPC10", "CPC11", "CPC2", "CPC3", "CPC4", "CPC5",
"CPC6", "CPC7", "CPC8", "CPC9", "CPP1", "CPP2", "CPP3", "CPP4",
"CPP5", "CPP6", "NB1", "NB2", "NB3", "NB4", "NB5"), class = "factor"),
    y = c(0.0544709955463634, 0.0596702158255113, 0.0586614896014222,
    0.0624578654972305, 0.0627572173362813, 0.0652714546210198,
    0.0720983861755616, 0.0721253780749289, 0.0663543751407387,
    0.0550210025217426, 0.058055876946208, 0.0600278464411527,
    0.0614602587742175, 0.0647506573410938, 0.044467464960404,
    0.0463054497208508, 0.0540317062311753, 0.0623795178994235,
    0.0609709990407159, 0.0660813707986263, 0.0564277955767876,
    0.0657846664725093, 0.0702825464296669, 0.056445470816807,
    0.0676118554533865, 0.06639558163306, 0.0850892537531267,
    0.0593398767389062, 0.0896267454136998, 0.047540684416275,
    0.101005522315739, 0.0840679762789124)), .Names = c("x",
"y"), row.names = c(NA, -32L), class = "data.frame")

ggplot() +
      geom_bar(data=data, aes(fill=columns, y=diffs, x=samps), stat="identity", position="fill") +
      scale_fill_discrete(name="Preprocessing Steps\n(Dots are recorded\ncontaminant values)",labels=labels) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
      xlab("Samples") + ylab("Fractions of all reads") +
      geom_point(data=dffs, aes(x=x,y=y))

A: I'm not quite sure what you mean with to add a legend line. Do you maybe mean that you want a key in the legend for the dots that co-exists with the keys of the preprocessing steps?
If that is the case I would recommend mapping the geom_point() colour to a variable, which can exist outside any data.frame:
ggplot() +
  geom_bar(aes(fill=columns, y=diffs, x=samps), stat="identity", position="fill") +
  scale_fill_discrete(name="Preprocessing Steps",labels=labels,
                      # Order set to 1 to appear before dot
                      guide = guide_legend(order = 1)) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  xlab("Samples") + ylab("Fractions of all reads") +
  # Add a colour mapping
  geom_point(data=dffs, aes(x=x,y=y, colour = "Recorded\nContaminant\nValues")) +
  # You can colour the dot how you like
  scale_colour_manual(values = "red", name = "")

Which gave me the following plot:

Is that close to what you wanted?


text:
Q: Not entirely sure how my two CBVs should inherit from a base I have realized that I've got two CBV's with 99% identical code, so I figured I'd abstract it and use a mixin where I can put all the "generic" code. The only real difference between the views are the templates they are rendering. I'm having a hard time figuring out what should be put in what class. Here's the original two CBV's
Class 1
@method_decorator(login_required, name='dispatch')
class TimesheetEditorView(View):
    form_class = TimesheetModelFormSet

    def get(self, request, *args, **kwargs):
        year = kwargs.get("year") or datetime.datetime.now().year
        week = kwargs.get("week") or Week.thisweek().week
        user = request.user
        if invalid_week(week, year):
            raise Http404("Invalid week / year")

        next_year, next_week = calc_next(year, week)
        previous_year, previous_week = calc_previous(year, week)

        timesheet = Timesheet.objects.filter(year=year, week=week, user=user).order_by("project_id")  # only show timesheet rows that belongs to logged in user

        timesheet_formset = self.form_class(queryset=timesheet)
        create_timesheet_form = TimesheetModelForm(user)
        context = {
            "create_timesheet_form": create_timesheet_form,
            "timesheet_formset": timesheet_formset,
            "week": week,
            "year": year,
            "next_week": next_week,
            "next_year": next_year,
            "previous_week": previous_week,
            "previous_year": previous_year,
        }

        return render(request, "timesheets/timesheet.html", context)

Class 2
class TimesheetApproveView(TimesheetEditorView, View):

    def get(self, request, *args, **kwargs):
        year = kwargs.get("year") or datetime.datetime.now().year
        week = kwargs.get("week") or Week.thisweek().week
        next_year, next_week = calc_next(year, week)
        previous_year, previous_week = calc_previous(year, week)
        timesheets = Timesheet.objects.timesheets_to_approve(request.user).filter(year=year, week=week)
        context = {
            "timesheets": timesheets,
            "year": year,
            "week": week,
            "next_week": next_week,
            "next_year": next_year,
            "previous_week": previous_week,
            "previous_year": previous_year,
        }

        return render(request, "timesheets/approve_timesheets.html", context)

I'm simply just inheriting TimesheetEditorView into my second class.
As you can see, the only difference here is the templates being rendered in the return statement.
So, I figured I'd put that chunk of code in a base mixin:
class BaseTimesheet(object):

    def get_context_data(self, **kwargs):
        context = super(BaseTimesheet, self).get_context_data(**kwargs)
        year = kwargs.get("year") or datetime.datetime.now().year
        week = kwargs.get("week") or Week.thisweek().week

        next_year, next_week = calc_next(year, week)
        previous_year, previous_week = calc_previous(year, week)

        if invalid_week(week, year):
            raise Http404("Invalid week / year")

        context["week"] = week
        context["year"] = year
        context["next_week"] = next_week
        context["previous_week"] = previous_week
        context["next_year"] = next_year
        context["previous_year"] = previous_year

Is this the "correct" way to do it? If so - how can I makes sure that I get the context for each return statement in my two View classes?
E.g
class TimesheetApproveView(BaseTimesheet, View):
    template_name = "timesheets/approve_timesheets.html"

    def get(self, request, *args, **kwargs):
        return render(request, "timesheets/timesheet.html") # how to get context?

approve_timesheets.html:
{% extends "base_layout.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}

Timesheet approvals

                    Current week

{% regroup timesheets by project as projects %}

        <form method="post" autocomplete="off">

                {% for project in projects %}

                            {{project.grouper}}
                            Mon
                            Tue
                            Wed
                            Thu
                            Fri
                            Sat
                            Sun

                        {% for user in project.list %}
                          ...
                        {% endfor %}

                {% empty %}

No timesheets to approve for this week

                {% endfor %}

        </form>

{% endblock %}

A: First of all, you forgot to return the context:
class BaseTimesheet:

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        year = kwargs.get("year") or datetime.datetime.now().year
        week = kwargs.get("week") or Week.thisweek().week

        next_year, next_week = calc_next(year, week)
        previous_year, previous_week = calc_previous(year, week)

        if invalid_week(week, year):
            raise Http404("Invalid week / year")

        context["week"] = week
        context["year"] = year
        context["next_week"] = next_week
        context["previous_week"] = previous_week
        context["next_year"] = next_year
        context["previous_year"] = previous_year
        return context
You call the function:
class TimesheetApproveView(BaseTimesheet, View):
    template_name = "timesheets/approve_timesheets.html"

    def get(self, request, *args, **kwargs):
        return render(request, "timesheets/timesheet.html", self.get_context_data(**kwargs))
But this will error, since there is no super().get_context_data for a generic view. You can make use of a TemplateView [Django-doc], in that case you do not even need to specify the get method:
from django.views.generic.base import TemplateView

class TimesheetApproveView(BaseTimesheet, TemplateView):
    template_name = "timesheets/approve_timesheets.html"
In your other view, you can then add the logic for the form:
from django.contrib.auth.mixins import LoginRequiredMixin

class TimesheetEditorView(LoginRequiredMixin, BaseTimesheet, TemplateView):
    form_class = TimesheetModelFormSet
    template_name = "timesheets/timesheet.html"

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        timesheet = Timesheet.objects.filter(
            year=context['year'],
            week=context['week'],
            user=self.request.user
        ).order_by("project_id")
        timesheet_formset = self.form_class(queryset=timesheet)
        create_timesheet_form = TimesheetModelForm(user)
        context.update(
            create_timesheet_form=create_timesheet_form,
            timesheet_formset=timesheet_formset
        )
        return context

Note: You can limit views to a class-based view to authenticated users with the
  LoginRequiredMixin mixin [Django-doc].


text:
Q: jqgrid paging on server side I'm trying to add server side paging to my grid. In adittion, I have a filter by 'license', 'number' and 'group'. When I press the next page button the controller is called and I obtain the data but my grid is reload on page 1 and I cant view the page 2 or 3 or 4...
In onPaging event if I use a local datatype no data is shown, if I use json datatype I only can see the first page.
This is the code:
var arrayData = [];
var pgevent;
var pager;
var accion;

$(function() {
    navLocal.cambia('002');

    $( "#tabs" ).tabs();
    $("#tblResults").jqGrid({
        mtype: 'POST',
        datatype: "local",
        height: 250,
        colNames:['license', 'id', 'number', 'brand', 'model', 'show'],
        colModel:[
            {name:'license',index:'license', width:110},
            {name:'id',index:'id', hidden: true},
            {name:'number',index:'number', width:110, sorttype:"int"},
            {name:'brand',index:'brand', width:250},
            {name:'model',index:'model', width:250},
            {name:'show',index:'show', width:60, align:"center", sortable:false, formatter:playerPicFormatter}
        ],
        multiselect: false,
        viewrecords: true,
        pager: "#jqGridPager",
        rowNum: 10,
        caption: "Results",
        width: 700,
        loadonce: true,

        rowList: [10,20,50],

        onPaging : function(pgButton) {
            $("#tblResults").setGridParam({datatype:'json'});
            find();
            pgevent = pgButton;
            pager = this.p.pager;

        },

        loadComplete: function () {
            $("#tblResults").setGridParam({datatype:'local'});
        }

    });

    find();
});

function find() {

    var gridArrayData = [];

    $.ajax({
        url : "/find.htm",
        type : "POST",
        dataType : "json",
        data: {
            license: $("#license").val(),
            number: $("#number").val(),
            group: $("#group").val(),
            page: $("#tblResults").jqGrid().getGridParam('page'),
            rowNum: $("#tblResults").jqGrid().getGridParam('rowNum'),
            sortname: $("#tblResults").jqGrid().getGridParam('sortname'),
            sortorder: $("#tblResults").jqGrid().getGridParam('sortorder')

        },
        success : function(result) {

            jQuery('#tblResults').jqGrid('clearGridData');

            for ( var i = 0; i < result.length; i++) {
                var item = result[i];
                gridArrayData.push({
                    id : item.id,
                    license : item.license,
                    number : item.number,
                    brand : item.brand,
                    model : item.model

                });
            }
            // set the new data
            $("#tblResults").jqGrid('setGridParam', {
                data : gridArrayData
            });

            // refresh the grid
            $("#tblResults").trigger('reloadGrid', [{page:2}]);
        },

        loadComplete: function () {
            $("#tblResults").setGridParam({datatype:'local'});
            }
    });

    arrayData = gridArrayData;

}

A: You are doing asynchronous calls in find but in your callback you have other statement after find. These will be executed before find finishes.
Could that be the problem?


text:
Q: Python asyncio task list progress logging I need to process a massive amount of data rows and it only makes sense to do this asynchronously.
I need to see list processing status, i.e. Done processing 1/3, but when I increment the counter, it always stays at 1. This makes sense since I send the counter into the function. I needed to do this because without it, I would get:
UnboundLocalError: local variable 'processed' referenced before assignment

Using Python 3.8
Any help would be appreciated!
Here's a link to test: https://ideone.com/gRjrf2
I've abstracted my code below:
    import os, logging
    import asyncio

    logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', datefmt='%d-%b-%y %H:%M:%S')
    logger = logging.getLogger(__name__)

    items = [{"name": "A"}, {"name": "B"}, {"name": "C"}]

    processed = 0

    async def increment(item):
        count = item.get('count', 0)
        count += 1
        return count

    async def get_and_update(item, processed):
        item['count'] = await increment(item)
        # Show progress now, but how?
        processed += 1
        logger.info(f"You can't see me {processed}")

    async def run():
        logger.info(f"Processing {len(items)} items...")
        await asyncio.gather(*[
            asyncio.create_task(
                get_and_update(item, processed)
            ) for item in items
        ])

    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())

The output I get is:
28-Aug-20 11:19:22 INFO     [prog.py:23] Processing 3 items...
28-Aug-20 11:19:22 INFO     [prog.py:20] You can't see me 1
28-Aug-20 11:19:22 INFO     [prog.py:20] You can't see me 1
28-Aug-20 11:19:22 INFO     [prog.py:20] You can't see me 1

A: Your basic problem is that by declaring processed as a parameter to get_and_update, you're shadowing the global processed variable. You need to drop the parameter and then declare processed as global within that function, like this:
import os, logging
import asyncio

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', datefmt='%d-%b-%y %H:%M:%S')
logger = logging.getLogger(__name__)

items = [{"name": "A"}, {"name": "B"}, {"name": "C"}]

processed = 0

async def increment(item):
    count = item.get('count', 0)
    count += 1
    return count

async def get_and_update(item):
    global processed

    item['count'] = await increment(item)
    # Show progress now, but how?
    processed += 1
    logger.info(f"You can't see me {processed}")

async def run():
    logger.info(f"Processing {len(items)} items...")
    await asyncio.gather(*[
        asyncio.create_task(
            get_and_update(item)
        ) for item in items
    ])

loop = asyncio.get_event_loop()
loop.run_until_complete(run())

The output of the above is:
28-Aug-20 08:15:00 INFO     [asynctest.py:25] Processing 3 items...
28-Aug-20 08:15:00 INFO     [asynctest.py:22] You can't see me 1
28-Aug-20 08:15:00 INFO     [asynctest.py:22] You can't see me 2
28-Aug-20 08:15:00 INFO     [asynctest.py:22] You can't see me 3


text:
Q: calling c from php I was wondering if there was a way to call existing C code from php?

A: If your C code is compiled to an executable, that executable can be executed from PHP -- but I'm guessing this is not quite what you meant ?
If you want to excute C code from PHP : that is not possible... unless you compile your C code to a PHP extension.
A PHP extension is like a .dll, on windows : it's a library, that can export functions that can be called from PHP.

If you want to learn more about writing PHP extensions, those links will probably interest you :

*

*Extension Writing Part I: Introduction to PHP and Zend

*Extension Writing Part II: Parameters, Arrays, and ZVALs

*Extension Writing Part II: Parameters, Arrays, and ZVALs [continued]

*Extension Writing Part III: Resources

*And, just for reference, as i'ts about C++ and not C : Wrapping C++ Classes in a PHP Extension
And, if you are really interested by the subject, and ready to spend some money on it, you could buy the book Extending and Embedding PHP (some pages are available as preview on Google Books too) ; It's considered as the book to read when interested on this subject (In fact, I've bought it some time ago, and, in my opinion, it is indeed an interesting read)
BTW, the author of that book is also the author of the first four articles I linked to ;-)

A: This article talks about PHP-C++ bindings. May be of help. In particular, checkout the BEGIN_EXTERN_C/END_EXTERN_C macros.


text:
Q: How to split string in SQL Server and store each one in new row I have a column that contains string of words split by comma I want to split each word to new row.
This is table example
PL          | Year
------------+------
Java, C#, C | 2018

I want results like this
PL     | Year
-------+--------
Java   | 2018
C#     | 2018
C++    | 2018

My query attempt:
select into #TempTable PL, Year
from myTable;

A: Try this one:
Best in class for pure SQL
Unless you write a CLR, this one blows all others out of the water for performance


text:
Q: How to copy a file from one directory to another directory in UNIX Ex: I have 2 directories

*

*dir1

*

*file1.txt

*dir2

I need to copy file1.txt into dir2.
Note: dir2 is not a sub-directory of dir1. both are unique directories.

A: cp dir1/file1.txt dir2

or if you are in dir1
cp file1.txt ../dir2

A: cp dir1/file1.txt dir2/. -v
-v Verbosiry


text:
Q: Deserialize of an API response and display it in view loop I have a problem with response deserialization. What is the best way to deserialize data to projects and display it in view in the simplest way? My IDE doesn't find map() method.
Response:
{
    "totalCount": 2,
    "items": [
        {
            "title": "TestProject1",
            "id": 1
        },
        {
            "title": "TestProject2",
            "id": 2
        }
    ]
}

Typescript:
  private usertoken: string;
  private projects: any;
  constructor(private http: HttpClient, private cookie : CookieService) { }

  ngOnInit() {
    this.usertoken = this.cookie.get('usertoken');
    console.log("asdasdasd1");

    this.http.get("https://localhost:5001/api/abc/cba",
      {headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.usertoken)})

      .subscribe(data =>{
        this.projects = data;
    });

Html:

        {{ project.totalCount }}

A: As @Nico suggested, you are iterating the wrong object. If you set the data directly in the projects, you have the projects.Items and project.TotalCount, so you should make the for in the Items which is the array.

   {{ projects.totalCount }}	  //Get total Count from the main object
   {{ project.title }}	  //Get name from the items interaction