text:
Q: Ubuntu Desktop Installation Partition Sizing Formula I want to reinstall Ubuntu from scratch.
I have read (here and here) that it is recommended to have 3 partitions for the desktop installation: root, home and swap as having a separate home and root can simplify the process if you want to upgrade or reinstall Ubuntu (if you break something by mistake).
But there is no type of formula (that I can find) on how big each partition should be.
I know this is somewhat dependant on what you plan to install. I want to have flexibility down the line to install new software without having to worry about shifting the partition sizes around.
Does anyone know of a formula or percentage breakdown that they have used to successfully calculate partition sizes?
i.e. x% of space will be allocated to the swap, y% of space to the root partition and z% of space to the home partition

A: To my experience a formula describing partition sizes in % are no use here. Absolute values I would recommend are

*

*4 GB Swap

*10-15 GB for OS depending on how much software you want to install

*the rest for the home partition.

It should be sufficient for beginner to experienced user, I don't know what exact demands real power users have.


text:
Q: If f is differentiable with a continuous derivative function, then the set of critical points of f is closed. If f is differentiable with a continuous derivative function, then the set of critical points of f is closed.
Is this a true statement? I'm kinda lost.

A: Well, the critical points of $f$ are the set of $x$ such that $f'(x) = 0$. So this follows from the more general fact that if $g$ is a continuous function, $Z_g = \{x : g(x) = 0\}$ is closed. Let's use the limit point definition of closed sets: $D$ is closed if $x_n$ is a convergent sequence, its limit is also in $D$. So pick a sequence $(x_n) \subset Z_g$; then $g(x_n)$ = 0; and because $g$ is continuous, $g(\lim x_n) = \lim g(x_n) = 0$. So $\lim x_n \in Z_g$, and $Z_g$ is closed.

A: Suppose $f'(x) \neq 0$. Since $f'$ is continuous, there is some open set $U$ containing $x$ such that $f'(y) \neq 0$ for $y \in U$. Hence the set $\{x | f'(x) \neq 0 \}$ is open, and so
$\{x | f'(x) = 0 \} = \{x | f'(x) \neq 0 \}^c$ is closed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with size f array with paginator paginate Class in CakePHP 2 I am new to CakePHP, I stuck at a point.
I have two tables , user and payment and I have put hasMany relation for those and applied condition on paginator paginate to search for specific payment type. While searching for some fields, it returns empty array of payment, but paginator paginate class shows total count '1' because it returns user array. Below is the array, I am getting:-
Array
 (
    [0] => Array
    (
        [User] => Array
            (
                [id] => 80
                [username] => a
                [email] => a@a.com
            )

        [PaymentInfo] => Array
            (

            )

    )

)
I want to know how I can use paginator paginate class so, it can show total records '0' if payment method array is empty.
Please help me to get out from this.

A: Make sure your association is properly set both side.
In your situation model 'User' will have 'hasMany' relation with 'Payment' as well you have to set 'belongsto' relation with 'User' model in 'Payment' Model.
If you don't have any payment records added for specific user in database then Payment array will be blank.
So first of all check your association first and check if payment record are exist or not.


text:
Q: How to transfer a war file to a remote server using Jenkins pipeline? How can I copy a war file using pipeline script.I have been trying this for long time and no luck on this. I have Publish Over ssh plugin installed and configured correctly. The test configuration is working fine. Following is the command which i have tried for copying war file to remote machine.
 sh 'scp /var/lib/jenkins/workspace/heloWorld/target/heloWorld.war ubuntu@server:/home/ubuntu/jenkinsbuilds/'

Whenever i run i will get an error and following is the error.
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,password).
lost connection

Is there any relationship between Publish Over ssh plugin and scp command in pipeline? How can i get it working? Any help would be greatly appreciated.


text:
Q: CSS: Scale font a constant factor I work on a website that uses a font which does not support a new language that we have to support for the website. (A couple of letters are missing)
An easy fix was to exchange the font that we currently use (Neuton) to just "serif" for that language, which at least gives us a complete set of characters for the new language.
Unfortunately, the font is much larger than Neuton was before, even though font-size stayed the same everywhere. It is impossible to change hundreds of "font-size" directives - is there a way to scale the font in general in "font-family"?


text:
Q: Efficient way to match two arrays I have 2 arrays , one is inputs pins names, the other is their actual numbers.
const char *pins[]={"d1","d2","d3","d4","d5","o1","o2","o3","o4"};
const int pinsNumbers[9]={1,2,19,4,14,6,12,15,17};

When I get as an input "d3" , I would like to find the corresponding - 19 .

*

*Is there more efficient way to save these "matches" ?

*How would one loop over the pins array with an input and find its match- as efficiently as possible ?

A: If the array pins is ordered (otherwise you can sort it using for example qsort) then you can use the following approach as it is shown in the demonstrative program
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int cmp( const void *a, const void *b )
{
    const char *lhs = *( const char ** )a;
    const char *rhs = *( const char ** )b;

    return strcmp( lhs, rhs );
}

int main( void )
{
    const char *pins[]      = { "d1", "d2", "d3", "d4", "d5", "o1", "o2", "o3", "o4" };
    const int pinsNumbers[] = { 1, 2, 19, 4, 14, 6, 12, 15, 17 };

    const char *key = "d3";

    const char **p = bsearch( &key, pins, sizeof( pins ) / sizeof( *pins ), sizeof( const char * ), cmp );

    if ( p ) printf( "%d\n", pinsNumbers[p - pins] );

    return 0;
}

The program output is
19

A: You can structure your data like this to emulate a C++ map:
struct My_pair {
    const char* pin;
    int number;
};

const My_pair pairs[] = {
    {"d1", 1},
    {"d2", 2},
    ...
};

A: As easy and fast as it is possible. And if you will use two consecutive symbols (for example 'a' and  'b') - you can calculate and check it just as offset inside groups in code bellow. Ideone online executable code.
#include <stdio.h>

#define D1_VAL  1
#define D2_VAL  2
#define D3_VAL  19
#define D4_VAL  4
#define D5_VAL  14

#define D_CNT   5
#define D_OFS   0

#define O1_VAL  6
#define O2_VAL  12
#define O3_VAL  15
#define O4_VAL  17

#define O_CNT   4
#define O_OFS   D_CNT

#define PIN_NUM_CNT     (D_CNT+O_CNT)
#define PIN_GRP_CNT     2

enum decode_res_e {
    DECODE_OK = 0,
    DECODE_ERR = !DECODE_OK
};

int const pin_num_tab[PIN_NUM_CNT] = {
    D1_VAL, D2_VAL, D3_VAL, D4_VAL, D5_VAL,
    O1_VAL, O2_VAL, O3_VAL, O4_VAL,
};

typedef struct { unsigned char chr, ofs, cnt; } pin_grp_t;

pin_grp_t const pin_grp_tab[2] = {
    { .chr = 'd', .ofs = D_OFS, .cnt = D_CNT },
    { .chr = 'o', .ofs = O_OFS, .cnt = O_CNT },
};

int pin_to_num(int * num, unsigned char * pin)
{
    unsigned char i = 0, tmp = pin[1] - 0x31;
    while (i < PIN_GRP_CNT) {
        if (pin_grp_tab[i].chr == pin[0]) {
            if (tmp >= pin_grp_tab[i].cnt) break;
            *num = pin_num_tab[pin_grp_tab[i].ofs + tmp];
            return DECODE_OK;
        }
        i++;
    }
    return DECODE_ERR;
}

int main(void)
{
    int num;
    unsigned char const inp[] = "d3";
    printf("\f%s is ",inp);
    if (pin_to_num(&num,inp) == DECODE_OK) {
        printf("%d\r\n",num);
    } else {
        printf("err\r\n");
    }
    return 0;
}

A: You can use a binary search...as long as the array above is sorted.


text:
Q: CSS Bootstrap : 2 column form with label on the left I've been trying for 3 hours to make a 2 column form with the label aligned on the left, but i am really not getting it. I've read bootstrap documentation, tried to play with "row" class but i dont have the result i want.
Here's a picture of what i'm trying to do, it has to be in 1 form. I've seen a lot of question about this, but no one seems to fit my problem ( people wanted them vertical aligned or within 2 different forms )
If anyone can show me the way to do it, and if possible, some explanation about how to align things using rows, it would be awesome !

A: You say 2 columns, but this configuration looks to me like it should be 4 columns. Because the labels should be their own column, and the textboxes should also be their own.
Something like this:

label

textbox

label in "2nd" column

textbox in "2nd" column

label

textbox

label in "2nd" column

textbox in "2nd" column

label

textbox

Pay by Phone/SMS

A:
I've been trying for 3 hours to make a 2 column form with the label aligned on the left, but i am really not getting it.

Because it's a form, you should really take advantage of Bootstraps .form-control and .form-group classes. Here is a sample fiddle for you to review http://jsfiddle.net/yongchuc/hzktphu6/. Bootstrap reference can be found here as well: http://getbootstrap.com/css/#forms

A: Try this ;)
<form class="form-horizontal" role="form">

        Test

          <input class="form-control">

        Test

          <input class="form-control">

</form>

http://jsfiddle.net/ttyneyq9/

A: Shouldn't be too bad. You can do it a couple ways:
1) Split each row up into 4 columns

Username

<input type="text" name="Username" />

Membership>

<select name="Membership"></select>

2) Use nested rows/columns

Username

<input type="text" name="Username" />

Username

<select name="Membership"></select>

In Bootstrap, each row consists of 12 columns by default. The column span is specified in the CSS class for each column (e.g. "col-md-3" will span 3 columns on medium sized screens or larger, for smaller screens the labels will go above the input). You'll just have to adjust the column spans to your liking.

A: For me it will be something like that

Username

<input type="text" name="Username" class="form-control" />

Password

<input type="password" name="Password" class="form-control" />

Email

<input type="email" name="Email" class="form-control" />

Membership

<select name="Membership">----options------</select>

Payment

<select name="Payment">----options------</select>

and the reason why this is the better solution is because when it's displayed on mobile they will show below each others in the same order as they're written above

A:                        <form class="form-horizontal">

                              Valet Parking

                                  <input type="email" class="form-control" id="inputEmail" placeholder="Email">

                              Kids menus

                                  <input type="email" class="form-control" id="inputEmail" placeholder="Email">

                              Car Parking

                                  <input type="password" class="form-control" id="inputPassword" placeholder="Password">

                              High chairs

                                  <input type="password" class="form-control" id="inputPassword" placeholder="Password">

                              Internet

                                  <input type="email" class="form-control" id="inputEmail" placeholder="Email">

                              Play areas

                                  <input type="email" class="form-control" id="inputEmail" placeholder="Email">

                              TVs

                                  <input type="password" class="form-control" id="inputPassword" placeholder="Password">

                              Handicap accessible

                                  <input type="password" class="form-control" id="inputPassword" placeholder="Password">

                              Outdoor seating

                                  <input type="email" class="form-control" id="inputEmail" placeholder="Email">

                              Pets

                                  <input type="password" class="form-control" id="inputPassword" placeholder="Password">

                              Smoking areas

                                  <input type="password" class="form-control" id="inputPassword" placeholder="Password">

                      </form>


text:
Q: Submitting two HTML forms with one submit button in Razor First of all sorry for my bad English. I am new to ASP.NET MVC and currently I am doing small "Rent-a-car" project on it.
I want to make a form where administrator of the page can add Cars on page with details like name, year of production and picture. Following some tutorials I made a form to create a car with name and year of production and I made separately a form where administrator can upload a picture of the car.
Now I have two HTML forms with two submit buttons, one for creating a car and second for uploading an image of the car. I want to combine those two forms into one where Administrator could type name of the car, year of production, select a picture which he want's to upload and then submitting all that with one button.
I have no idea how to do that so please review my code below and tell me what changes do I have to make, I will appreciate any help
This is my Car model:
public class Car
{
    [Key]
    public int CarID { get; set; }
    public string Model { get; set; }
    public int YearOfProduction { get; set; }
    public string Price { get; set; }
    public string Photo { get; set; }
    public string AlternateText { get; set; }
    [NotMapped]
    public HttpPostedFileBase File { get; set; } //for image upload
}

This is my Create (car) Action Method in the "Cars" controller:
[Authorize(Roles = "Administrator")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "CarID,Model,YearOfProduction")] Car car)
    {
        if (ModelState.IsValid)
        {
            db.Cars.Add(car);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(car);
    }

This is my Upload (image of the car) Action Method in the "Cars" controller:
    [HttpPost]
    public ActionResult Upload(Car picture)
    {
        if (picture.File.ContentLength > 0)
        {
                var fileName = Path.GetFileName(picture.File.FileName);
                var path = Path.Combine(Server.MapPath("~/Images/Cars"), fileName);
                picture.File.SaveAs(path);
        }

        return RedirectToAction("Index");
    }

This is my HTML form for creating a car:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

Car

    @Html.ValidationSummary(true, "", new {@class = "text-danger"})

        @Html.LabelFor(model => model.Model, htmlAttributes: new {@class = "control-label col-md-2"})

            @Html.EditorFor(model => model.Model, new {htmlAttributes = new {@class = "form-control"}})
            @Html.ValidationMessageFor(model => model.Model, "", new {@class = "text-danger"})

        @Html.LabelFor(model => model.YearOfProduction, htmlAttributes: new {@class = "control-label col-md-2"})

            @Html.EditorFor(model => model.YearOfProduction, new {htmlAttributes = new {@class = "form-control"}})
            @Html.ValidationMessageFor(model => model.YearOfProduction, "", new {@class = "text-danger"})

            <input type="submit" value="Create" class="btn btn-default"/>

}

This is my HTML form for uploading an image of the car:
@using (Html.BeginForm("Upload", "Cars", FormMethod.Post, new { enctype  = "multipart/form-data" }))
{

        File:
        <input type="file" name="File" id="File"/>

            <input type="submit" name="submit" value="Upload"/>

    }

A: You can use the command name in your <input> tag as shown below:
@Html.BeginForm()
{
  @Html.AntiForgeryToken()

        File:
        <input type="file" name="File" id="File"/>

            <input type="submit" name="commandName" value="Upload"/>

            <input type="submit" name="commandName" value="Create" class="btn btn-default"/>

}

And in your controllers' action method accept it as a parameter.
public ActionResult Create(Car car, string commandName)
{
    if(commandName.Equals("Create"))
    {
      // Call method to create new record...
    }
    else if (commandName.Equals("Upload"))
    {
      // Call another method to upload picture..
    }
}

If you research, there is another elegant generic solution, where you can just apply a multiple-button attribute on the Action method and it will automatically call the controller action. However, you need to be careful about getting values in that case ( *It's out of scope for this question). You can refer: How do you handle multiple submit buttons in ASP.NET MVC Framework?

A: You can add the input file field in the other form and merge both action method's code into one.
@using (Html.BeginForm())
{
  @Html.AntiForgeryToken()

Car

    @Html.ValidationSummary(true, "", new {@class = "text-danger"})

        @Html.LabelFor(model => model.Model, htmlAttributes: new {@class = "control-label col-md-2"})

            @Html.EditorFor(model => model.Model, new {htmlAttributes = new {@class = "form-control"}})
            @Html.ValidationMessageFor(model => model.Model, "", new {@class = "text-danger"})

        @Html.LabelFor(model => model.YearOfProduction, htmlAttributes: new {@class = "control-label col-md-2"})

            @Html.EditorFor(model => model.YearOfProduction, new {htmlAttributes = new {@class = "form-control"}})
            @Html.ValidationMessageFor(model => model.YearOfProduction, "", new {@class = "text-danger"})

      File
      <input type="file" name="File" id="File"/>

            <input type="submit" value="Create" class="btn btn-default"/>

}

and the action method, save the file to disk and store the filename in your db table records so that you can retrieve this file later (for view purposes).
[Authorize(Roles = "Administrator")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Car car)
{
    if (ModelState.IsValid)
    {
      if (car.File.ContentLength > 0)
      {
         var fileName = Path.GetFileName(car.File.FileName);
         var path = Path.Combine(Server.MapPath("~/Images/Cars"), fileName);
         picture.File.SaveAs(path);
         car.Photo = fileName;
      }
      db.Cars.Add(car);
      db.SaveChanges();
      return RedirectToAction("Index");
    }
    return View(car);
}

Also, you may consider generating a unique file name so that you won't overwrite the existing files on disk if user is updating the file with same name for different records.
You can use this code to generate a random file name.
var fileName = Path.GetFileName(car.File.FileName);
fileName = Path.GetFileNameWithoutExtension(fileName) +
                            "_" +
                   Guid.NewGuid().ToString().Substring(0, 4) + Path.GetExtension(fileName);
var path = Path.Combine(Server.MapPath("~/Images/Cars"), fileName);
//continue with saving

Also remember, the best way to prevent over posting is by using a view model with properties needed for your view. You can create a view model and use that to transfer data from view to action method. In that case, you can totally remove the property (decorated with [NotMapped] from your entity class)

A: Have a look at this.
It looks like it might help you combine your two forms (and controller actions) into one


text:
Q: how can a 1 second audio effect be played for 0.5 seconds in AVAudioPlayer? I am using the following code to play sound effects in my Swift SpriteKit game.
    func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer  {
    let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
    let url = NSURL.fileURLWithPath(path!)
    var audioPlayer:AVAudioPlayer?

    do {
        try audioPlayer = AVAudioPlayer(contentsOfURL: url)
    } catch {
        print("NO AUDIO PLAYER")
    }

    return audioPlayer!
}

The sound effect duration is a second and I call it each time a sprite is created at a 0.5 second interval. Since the sound effect is longer than the creation interval, the effect only plays once. I believe reducing the effect duration could solve this issue, though I am open to other approaches to solving my problem.

A: You can also use AVAudioEngine()
Just put your audioFile in AVAudioEngine() and change the speed with the following parameter:
// The default value is 1.0. The range of supported values is 1/32 to 32.0.
changeAudioUnitTime.rate = 1.0

ExampleCode below:
    var audioPlayer: AVAudioPlayer!
    var audioEngine = AVAudioEngine()
    var audioFile: AVAudioFile!
    var audioPlayerNode: AVAudioPlayerNode?

    audioPlayer = try AVAudioPlayer(contentsOfURL: currentAudio!)
    audioFile = try! AVAudioFile(forReading: audioPlayer!.url!)
    audioEngine.attachNode(audioPlayerNode!)

    let changeAudioUnitTime = AVAudioUnitTimePitch()
    // The default value is 1.0. The range of supported values is 1/32 to 32.0.
    changeAudioUnitTime.rate = 1.0
    audioEngine.attachNode(changeAudioUnitTime)
    audioEngine.connect(audioPlayerNode!, to: changeAudioUnitTime, format: nil)
    audioEngine.connect(changeAudioUnitTime, to: audioEngine.outputNode, format: nil)
            audioPlayerNode!.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
    do {
       try audioEngine.start()
    } catch {
       print("audio Engine could not be started: \(error)")
    }

    // play the costumized sound
    audioPlayerNode!.play()

Hope this example helps you.... if I understood you wrong please feel free to correct me. Regards, Alex


text:
Q: External Memory IC which increments data on a clock pin I am searching, with no success, in multiple categories of the external memory IC market for a chip that can do the following:

*

*Store 1MB of data of 16-bit data

*This data is stored at specific addresses

*When I put it into read mode it uses it's 16 output pins to display it's 16-bit values in memory    i.e. if the value at address 0x0000 was 0000 0000 0001
0010 this value would be on the pins in +V/0V.

*When I increment a pin with a clock it will change to address 0x0001 and display that value on it's pins.

*Preferably has unlimited write cycles like SRAM.

*Data can be volatile

I can find sram which matches the address on it's input pins and then displays the value at that address to it's output pins. but it won't clock automatically to increment and requires specific reconfiguring of the address pins.
An example that is close is the CY62256NLL-70ZRXIT. but it will not auto increment its address with an external input on its display pins.
Anyone got any suggestions?
I suspect it's maybe a type of ram that I am not aware of.

A: You appear to be describing a FIFO chip, and contrary to the other answers, they do exist as COTS products. For example, IDT has a line of chips of that type. Unfortunately, the 1 MB parts (512k × 18 bits) have prices on the order of $200 in small quantities.
But the rest of your functional description is so vague that I can't be sure. Also, if you have an FPGA in your system anyway, its on-chip block RAM can be configured to do the same thing (assuming that there's enough of it).

A: What you're describing doesn't exist as a single IC, as far as I know. I have never seen such a device in the last few decades.
That function can readily be implemented with (a) a RAM chip and several 74xxx logic ICs or (b) a RAM chip and a cheap CPLD.
So there would be little incentive for an IC manufacturer to produce a dedicated chip with few and obscure applications that could be implemented with only two ICs.

A: I'd suggest this 10nS SRAM
http://www.issi.com/WW/pdf/61-64WV102416DALL_BLL.pdf
with a 20-bit counter in front of it. Perhaps one made of a loadable counter so that you can set up the starting address from you wish to start displaying data, such as 5 of these daisychained:
http://www.ti.com/lit/ds/symlink/sn74hc193.pdf
or 3 of these much pricier 8-bit parts
http://www.ti.com/lit/ds/symlink/sn74as867.pdf
Similar parts are available in other logic families for different speeds.
Might also be less expensive to run two 1M x 8 parts in parallel.


text:
Q: Need to make a gridview with two static text fields Hello i need to make a gridview like the following images with static textviews.
I need to make it in Portrait mode. I know there are lot of guides available on stackoverflow on how to make a gridview with two textviews but i am unable to follow them and failed many times trying to create a gridview exactly like this. Instead of marking my post as negative if someone could help me build a gridview like above i will be really great full.
Thanks!
Edit: I have tried a TableLayout in order to achieve the above layout and things are going well except i cannot draw a vertical line(divider). See the image below:
My Code:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:divider="#FF909090"
android:orientation="horizontal"
android:stretchColumns="1"
android:background="@drawable/custom_background"
android:showDividers="middle">
<TableRow>
    <TextView
        android:text="Name"
        android:padding="3dip" />
    <TextView
        android:text="Imran"
        android:gravity="left"
        android:padding="3dip" />
</TableRow>

<View
    android:layout_height="2dip"
    android:background="#FF909090" />

<TableRow>
    <TextView
        android:text="Name"
        android:padding="3dip" />

    <TextView
        android:text="Test"
        android:gravity="left"
        android:padding="3dip" />
</TableRow>

<View
    android:layout_height="2dip"
    android:background="#FF909090" />

<TableRow>
    <TextView
        android:text="Name"
        android:padding="3dip" />

    <TextView
        android:text="Test"
        android:gravity="left"
        android:padding="3dip" />
</TableRow>

Thanks to all for helping me out.

A: I think your problem is in the assumption that you need to use a GridView here.
What you presented should be done with a ListView or, even better, a RecyclerView.
Try looking at each row as a list item and the task will become really easy :-)
Like this:


text:
Q: How can I use with() method and where() method using nested columns? There is a structure like this:
Entity1 has many Entity2 that has many Entity3
I want to get all entities of Entity3 that are associated with one entity of Entity1.
In SQL it would be something like:
 SELECT Entity3.*
    FROM Entity3
    INNER JOIN Entity2 on Entitity3.entity2_id = Entity2.id
    INNER JOIN Entity1 on Entity2.entity1_id = Entity1.id
    WHERE
        Entity1.id = X;

A: In Entity1 model:
public function getEntities2()
{
     return $this->hasMany(Entity2::className(), ['id' => 'entity2_id']);
}

public function getEntities3()
{
     return $this->hasMany(Entity3::className(), ['id' => 'entity3_id'])->via('entities2');
}

A: I could find a way, as it follows:
$entities3 = Entity3::find()->joinWith(['entity2.entity1'])->where('entity2.entity1_id='.$entity1_id)->all();


text:
Q: how to avoid loops HI All,
I'm new to R.
I have two panel data files, with columns "id", "date" and "ret"
file A has a lot more data than file B,
but i'm primarily working with file B data.
Combination of "id" and "date" is unqiue indentifier.
Is there an elegent way of looking up for each (id, date) in B, I need to get the past 10 days ret from file A, and store them back into B?
my naive way of doing it is to loop for all rows in B,
for i in 1:length(B) {
    B$past10d[i] <- prod(1+A$ret[which(A$id == B$id[i] & A$date > B$date[i]-10 & A$date < B$date[i])])-1
}

but the loops takes forever.
Really appreciate your thoughts.
Thank you very much.

A: Did you try ?merge ?
"Merge two data frames by common columns or row names, or do other versions of database join operations. "
Besides I suggest to use a little local MySQL / PostgreSQL (RMySQL / RPostgreSQL) database if you continously sport composite PKs or whatsoever as unique identifiers. To me SQL rearranging of data and afterwards using data.frames from view is a lot easier than looping.

A: I think the key is to vectorize and use the %in% operator to subset data frame A. And, I know, prices are not random numbers, but I didn't want to code a random walk... I created a stock-date index using paste, but I'm sure you could use the index from pdata.frame in the plm library, which is the best I've found for panel data.
A  <- data.frame(stock=rep(1:10, each=100), date=rep(Sys.Date()-99:0, 10), price=rnorm(1000))
B <- A[seq(from=100, to=1000, by=100), ]
A <- cbind(paste(A$stock, A$date, sep="-"), A)
B <- cbind(paste(B$stock, B$date, sep="-"), B)
colnames(A) <- colnames(B) <- c("index", "stock", "date", "price")
index <- which(A[, 1] %in% B[, 1])
returns <- (A$price[index] - A$price[index-10]) / A$price[index-10]
B <- cbind(B, returns)

A: Is this any faster? (I am assuming the combination of B$id and B$date is a unique identifier not replicated anywhere - implied by your code)
B$idDate <- factor(B$id):factor(B$date)
B$past10 <- sapply(B$idDate, function(x){with(B[B$idDate == x,],
    prod(1+A$ret[A$id == id & A$date > date-10 & A$date < date])-1)})

A: If you haven't got data that is replicated in both A and B, then rbind is the simplest solution.
#Sample data
A <- data.frame(
  id = rep(letters[1:3], each = 13),
  date = Sys.Date() + -12:0,
  ret = runif(39)
)

B <- data.frame(
  id = rep(letters[5:6], each = 5),
  date = Sys.Date() + -4:0,
  ret = runif(10)
)

#Only take the last ten days from A
A_past_10_days <- A[A$date > Sys.Date() - 10,]

#Bind by rows
rbind(A_past_10_days, B)

A: In general, you ought to avoid looping in R.  It's much quicker if your code operates on vectors.
I would use merge, as suggested by ran2.  You can set all.x = T (or all.y or all) to get all the rows from one (or other or both) - data frames.  This is quick and will typically work-out which fields to match by itself.  Otherwise you'll need to specify by.x (and by.y or by) as a lookup field.  By the sounds of it you may need to create this field yourself (as per John's comment).
You can then filter by date.

A: Given that you're having memory issues perhaps paring down A first might help.  First, get rid of extraneous ids.
A <- A[A$id %in% B$id,]

Reducing the A dataset completely still wants to grab more memory.  It's not possible without storing some variables.  Nevertheless, we can get rid of a bunch of it I'm hoping by lopping off every date below our absolute minimum and above our absolute maximum.
A <- A[A$date > (min(B$date) - 10) & A$date <= max(B$date),]

Of course, by not qualifying this by id we haven't get the smallest version of A possible but hopefully it's enough smaller.
Now run the code I first proposed and see if you still have a memory error
B$idDate <- factor(B$id):factor(B$date)
B$past10 <- sapply(B$idDate, function(x){with(B[B$idDate == x,],
    prod(1+A$ret[A$id == id & A$date > date-10 & A$date < date])-1)})

A: library(data.table)
#create data
A  <- data.table(id=rep(1:10, each=40000), date=rep(Sys.Date()-99:0,  4000), ret=rnorm(400000))
B  <- data.table(id=rep(1:5,  each=10), date=rep(Sys.Date()-99:0),  ret=rnorm(50))

#find dates to compare against
n <- NROW(B)
B_long <- B[,.(id = rep(id,each=10),date = rep(date,each=10))]
s <- rep(-10:-1,n)
B_long[,date:=date + s]

#information in one column
B_long$com <- as.numeric(paste0(B_long$id,as.numeric(B$date)))
A$com <- as.numeric(paste0(A$id,as.numeric(A$date)))

#compare
setkey(A,com)
X <- A[com %in% B_long$com,]

This answer builds on Richards answer but is more targeted to the question.
Key idea is to build one vector of id date combinations to compare against. This happens in the second code block.
My solution uses the data.table package but should with some syntax changes work with a data.frame. But using the data.table package has the advantage of keycolumns.
If you still have trouble you can pair this approach with john's second answer and first crop A.


text:
Q: Infer type for multiple properties to be the same Is it possible in Typescript to infer multiple properties to be the same type, or maybe infer the types based on a specific property..
Lets say we have ->
interface Test<T> {
  value1: T;
  value2: T;
}

const test1:Test<string> = {
    value1: 'string1',
    value2: 'string1'
}

In the above if I made value1 or value2 into a number it would error, great.  But it would be nice to remove the generic <string> and for it to work out it's based on maybe the first property types value1.
At first I thought I could use a default for T as any, and it would then later infer the type, but it just keeps as any, as can be seen below we have a string and a number.
interface Test<T = any> {
  value1: T;
  value2: T;
}

const test1:Test = {
    value1: 'string1',
    value2: 2
}

A: As you saw, a generic type parameter default doesn't have the effect you intend.  If you refer to the type as Test without specifying the type parameter as in Test<string>, the compiler will use the default and interpret it as Test<any>.  It will not infer string for you.  There is a feature request, microsoft/TypeScript#10671, asking for a way to have the compiler infer unspecified type parameters... something like Test<infer> or Test<*>. But so far TypeScript does not have this feature.
Instead what you can do is create a generic utility function which returns its input:
const asTest = <T,>(test: Test<T>) => test;

When you call a generic function, TypeScript will try to infer an appropriate type for a test parameter.  You can call this function instead of annotating the variable:
const testString = asTest({
  value1: "string1",
  value2: "string2"
})
// const testString: Test<string>

const testStringNumber = asTest({
  value1: "string1",
  value2: 2 // error! 'number' is not assignable to 'string'
})
// const testString: Test<string>

This behaves as desired.

Do note though that it's not always obvious whether the compiler will reject a value or synthesize a union type for its type parameter.  In testStringNumber it would have been reasonable for T to be inferred as string | number, but the heuristic the compiler uses is that people don't generally want to infer unions of primitive types.
On the other hand, the following code causes a union to be inferred:
const testUnion = asTest({
  value1: { a: "" },
  value2: { b: "" }
})
/* Test<{
    a: string;
    b?: undefined;
} | {
    b: string;
    a?: undefined;
}> */

That type, Test<{a: string; b?: undefined} | {b: string; a?: undefined}> does accurately describe the type of the value passed in to asTest(). The compiler's heuristic assumes that unions of object types are more acceptable and expected.

But perhaps you'd have preferred something that complains about such unions, and uses only (say) value1 to infer T, and then just checks value2 against it.  That is, you'd like the T in value2 to be a non-inferential type parameter usage as requested in microsoft/TypeScript#14829.  There is no official direct support for this, but there are some reasonable ways to simulate it.  For example:
const asTest = <T, U extends T>(test: { value1: T, value2: U }): Test<T> => test;

This version of asTest uses two generic type parameters; T for value1, and U for value2.  U is constrained to be assignable to T, so the compiler will only accept inputs where value2 has a type that can be assigned to value1.  And the compiler will only infer T by looking at value1 and not at value2.  It works the same for testString and testStringNumber:
const testString = asTest({ value1: "string1", value2: "string2" });
// const testString: Test<string>

const testStringNumber = asTest({
  value1: "string1",
  value2: 2 // error! 'number' is not assignable to 'string'
})
// const testString: Test<string>

But now testUnion produces an error:
const testUnion = asTest({
  value1: { a: "" },
  value2: { b: "" } // error! '{ b: string; }' is not assignable to '{ a: string; }'
})

because {b: ""} cannot be assigned to the type {a: string} as inferred from value1.

Playground link to code


text:
Q: Can you execute chdk scripts externally via USB? I have been tinkering around with CHDK (canon hack development kit). I have been able to run chdk via SD card on my powershot g12 and even been able to run a script on it.
My interest lies more in controlling this externally via a USB cable. For starters I want to try controlling it from the computer, then maybe another device.
I have been to the CHDK website http://chdk.wikia.com/wiki/CHDK and peeked around their forum as well but have not seen any mention of external execution.

A: Yes, you can.  There are two approaches I've used with some success.
1.) I can control my Powershot G9 using CHDKPTP (https://app.assembla.com/spaces/chdkptp/wiki).  I'm using Ubuntu 16.04 and the r735 binary from the website.  The GUI lets you control the camera and run scripts.  This approach should work for any camera that CHDK supports.  (There is also a python binding for CHDKPTP, although I haven't managed to successfully build it yet.)
2.) Another approach is to use gphoto2, if your camera is supported by gphoto2. (NOTE:  It doesn't look like the G12 is supported by gphoto2, but I'm including it here in case it's useful to others)  On the G9, CHDK adds a property chdk_script to the available options in gphoto2.  Then scripts should be runnable with
gphoto2 --set-config chdk_script="scriptname"
The gphoto2 approach is demonstrated here (https://www.youtube.com/watch?v=v_42jd9tGF0)


text:
Q: How to connect java code with database without using any jar files? Can I connect java code with database without using jar files?
I want to write java code which will not be dependent on odbc6.jar files to connect with database. Is it possible?

A: There are two possible ways to connect to an Oracle DB without depending on the jar file which contains the jdbc driver.

*

*Extract the files out of the jar using: jar xf odbc6.jar

*Implement your own jdbc driver, in effect writing your own version of the jdbc driver for oracle.


text:
Q: jquery randomly animate div (zoom in and out) http://jsfiddle.net/xwb0d48v/

ZOOMING

NO ZOOM YET

NO ZOOM YET

NO ZOOM YET

NO ZOOM YET

NO ZOOM YET

How do I randomly animate (zoom in and zoom out and zoom into another one) all the divs every 5 seconds?
Thanks,

A: You can use a timeout for change ever n second the images, you call the timer for example
setTimeout(function(){ alert("Hello"); }, 3000);

in the event load of you page


text:
Q: Trying to deploy a project in docker I execute the

docker-compose up -d

command
WARNING: The HOST_MACHINE_UNSECURE_HOST_PORT variable is not set. Defaulting to a blank string.
WARNING: The HOST_MACHINE_SECURE_HOST_PORT variable is not set. Defaulting to a blank string.
WARNING: The DOMAIN variable is not set. Defaulting to a blank string.
WARNING: The MYSQL_DATABASE variable is not set. Defaulting to a blank string.
WARNING: The MYSQL_USER variable is not set. Defaulting to a blank string.
WARNING: The MYSQL_PASSWORD variable is not set. Defaulting to a blank string.
WARNING: The DOMAIN_API variable is not set. Defaulting to a blank string.
WARNING: The MYSQL_ROOT_PASSWORD variable is not set. Defaulting to a blank string.
ERROR: The Compose file './docker-compose.yml' is invalid because:
services.proxy.ports is invalid: Port ranges don't match in length
services.proxy.ports is invalid: Port ranges don't match in length

At work, did everything well.
OC:Manjaro 18
image: traefik:1.7

A: This is most likely due to you referencing environment variables in docker-compose.yml that are not present. All environment variables defined in the .env file are loaded in by default.
Make sure you have the .env file in the same directory as docker-compose.yml with all of your variables. In your case it may look like this:
HOST_MACHINE_UNSECURE_HOST_PORT=80
HOST_MACHINE_SECURE_HOST_PORT=443

HOST_MACHINE_MYSQL_PORT=3306

MYSQL_ROOT_PASSWORD=rootroot
MYSQL_USER=root
MYSQL_PASSWORD=rootroot
MYSQL_DATABASE=dockertest

Or if your docker-compose.yml explicitly defines an env_file make sure it exists.
web:
  env_file:
    - ./.prod-env

E.g. with this example, there should be a file named .prod-env in the same directory as docker-compose.yml


text:
Q: how to check ping for a bluetooth device in python i have connected a bluetooth controller to control a rover.
i am able to ping the controller using sudo l2ping 84:30:95:06:C6:6C on the terminal.
basically i want to execute certain code when ping is not available. i.e., when controller is disconnected.
i tried this:
import bluetooth

while True:
    if bluetooth.lookup_name('84:30:95:06:C6:6C'):
        print("do nothing")

    else:
        print("do something")

but this has bit of delay, it takes around 2-3 seconds to give me the output when the controller is disconnected.
is there any other way of doing this in python ?

A: so we can use hcitool to know the status of the bluetooth device. here is a small snippet that worked for me. there is no delay to get the output and this works absolutely fine.
import subprocess as sp

dev_addr = '84:30:95:06:C6:6C'
stdoutdata = sp.getoutput("hcitool con")

while True:
    if dev_addr in stdoutdata.split():
        print("do nothing")

    if dev_addr not in stdoutdata.split():
        print("do something")


text:
Q: returning reference and use of cascading function Please tell me the use of cascading, and when to use & before function  like this int &func()
Where should i use that please give me small example, Thanks. I think it does return an address but no idea how to use.

A:
when to use &

Return by value vs return by reference
You usually return a reference when you want a caller to be able to change the original variable. Example can be returning elements of an array
struct Array
{
    int values[ 10];
};

// Returns a reference to the nIndex element of rArray
int& Value( Array &rArray, int nIndex)
{
    return Array.values[ nIndex];
}

int main()
{
    Array myArray;
    // Set the 10th element of sMyArray to the value 5
    Value( myArray, 10) = 5;

    assert( myArray.values[ 10] == 5);  // OK
    return 0;
}

Another example is returning reference to class member. You want to return original variable, not a copy of it. Consider:
struct A {
  int something;
  int f() { return something; }
  int& g() { return something; }
};

int main()
{
    A myA;
    int i = myA.f();  // return by value: not original
                      // int but its copy with same value
    i = 200;

    assert( myA.something == 200);  // fail
    return 0;
}

but:
int main()
{
    A myA;
    int& i = myA.g();  // return by reference: original
                       // variable is referenced by i now
    i = 200;

    assert( myA.something == 200);  // OK
    return 0;
}

Operator chaining
Operator chaining is made to allow for expressions like:
a = b + c + d;

or
std::cout << "this" << " and " << "this";

Usually there is choice between returning by value or by reference made by considering the meaning of the operator or independent factors like for example that std::istream and std::ostream are not copyable, so trying to return objects of those types by value is an error.

A: You are about to commit a very common newbie mistake in C++, namely returning references to dead objects.
int &GetNumber()
{
    int number = 123;
    return number;
}

int main()
{
    int x = GetNumber();
    int y = x + 1;
}

Looks innocent but will create so-called undefined behaviour. This means that the program may do whatever it wants to - it will likely crash, or it will sometimes crash. In any case, it won't be safe. Your compiler may even warn you if you attempt to do this. The reason is that by the time GetNumber has finished, the local number is destroyed, and you end up with a reference to a destroyed object.
Usually, you will want to return a copy instead of a reference. This is the "normal" thing to do in C++:
int GetNumber() // now OK
{
    int number = 123;
    return number;
}

int main()
{
    int x = GetNumber();
    int y = x + 1;
}

Returning references is only safe when you know that the object referred to will continue to exist after the function returns. One example is when you are just returning a reference you were passed:
int &MyFunction(int &number)
{
    // do something
    return number;
}

This then allows you to chain functions:
struct Example
{
    Example &MyFunction(Example &example)
    {
        // do something
        return example;
    }
};

int main()
{
    Example example;
    example.MyFunction(example).MyFunction(example).MyFunction(example);
}

Now, if this example strikes you as particularly useless (as it should), look at how the standard library handles << calls with std::ostream for a realistic use case.
std::cout << 1 << "a" << 0.5;

This syntax works because each operator<< call returns a reference to std::cout.


text:
Q: Collect statistic of Apache Ignite I'm using Apache Ignite to cache SQL query result with native persistence enabled, so part of query result will be stored in disk.
When I fetch query result from cache, is there a way I can get statistic about how much data is loaded from memory and how much from disk for this query?
Thanks

A: The only relevant metric I know is org.apache.ignite.DataRegionMetrics#getEvictionRate, which lets you understand how often you are hitting disk, but it is not per-query granular.


text:
Q: When does NHibernate execute my query? I am trying to write a generic repository for my NHibernate data access. The Get<T>() method should be able to take an optional predicate, that should be included in the query - that is, NHibernate should generate the WHERE clause in the SQL.
    public virtual IList<T> Get(Func<T, bool> predicate = null)
    {
        // Open NHibernate Session
        using (var session = NHibernateHelper.OpenSession())
            return (predicate != null
                       ? session.Query<T>().Where(predicate)
                       : session.Query<T>()).ToList();

    }

When I pass in a predicate, and observe the SQL statement NH generates, I see no where clause.
When does NHibernate execute the query? Right when calling .Query<T>()? If so, how can I achieve this?

A: The query should be executed by the call ToList().
The case why the WHERE clause is not included in your sql statement is that you need to pass an Expression<Func<T,bool>> to your method.
public virtual IList<T> Get(Expression<Func<T, bool>> predicate = null)
    {
        // Open NHibernate Session
        using (var session = NHibernateHelper.OpenSession())
            return (predicate != null
                       ? session.Query<T>().Where(predicate)
                       : session.Query<T>()).ToList();

    }

The extension method Where(Func<T,bool>>) is defined on Enumerable, so that the the query loads all data and then applies the WHERE-filter in memory.
The extension method Where(Expression<Func<T,bool>>) is defined on Queryable, so that the query provider (NHibernate) can build a sql statement including your WHERE condition that gets executed on the data source.

A: Since @Jehof gave you correct explanation I just want to add separate note - you should not return IList<T> from you repository method as then any other linq operation will be executed in memory and not in the database. Assume following calls
var data = repository.Get<Company>(c=>c.Name.StartsWith("MyCompany"));
... some other operations / method calls etc.
var companySubset = data.Where(...);

so now if you have IList<T> Get<T>() you decrease performance but with IQueryable<T> Get<T> you would still have the second Where() appended to the database query.
Of course not all linq operations are supported by IQueryable like (join , last ) and this is the only place to call ToList() extension to evaluate expression.


text:
Q: How to get unique list of values from the list of dictonaries I have a python list of dictionaries like this
test_list = [{'id': 0, 'A':True, 'B':123},
             {'id':76, 'A':True, 'B':73},
             {'id':5, 'A':False, 'B':223},
             {'id':5, 'A':False, 'B':223},
             {'id':85, 'A':True, 'B':4},
             {'id':81, 'A':False, 'B':76},
             {'id':76, 'A':True, 'B':73}]

And I want to make this list unique
using simple set(test_list) give you TypeError: unhashable type: 'dict'
My below answer works fine for me, but I am looking for a better and short answer
unique_ids = list(set([x['id'] for x in test_list]))
d = {}
for item in test_list:
    d[item['id']] = item

new_d = []
for x in unique_ids:
    new_d.append(d[x])

A: Create a new dictionary with keys as ids and the values as the entire dictionary and access only the values:
new_d = list({v["id"]: v for v in test_list}.values())

>>> new_d
[{'id': 0, 'A': True, 'B': 123},
 {'id': 76, 'A': True, 'B': 73},
 {'id': 5, 'A': False, 'B': 223},
 {'id': 85, 'A': True, 'B': 4},
 {'id': 81, 'A': False, 'B': 76}]
~~


text:
Q: How to print letters(DNA) in a format of (0,10,6) I am struggling with this code here. I want print out dna in java that shows format of (0, 10, 6) which need to pass a until test
instead of looking like this
ACAAGATGCC ATTGTCCCCC GGCCTCCTGC TGCTGCTGCT CTCCGGGGCC ACGGCCACCG
CTGCCCTGCC CCTGGAGGGT GGCCCCACCG GCCGAGACAG CGAGCATATG CAGGAAGCGG
CAGGAATAAG GAAAAGCAGC CTCCTGACTT TCCTCGCTTG GTGGTTTGAG TGGACCTCCC
AGGCCAGTGC CGGGCCCCTC ATAGGAGAGG AAGCTCGGGA GGTGGCCAGG CGGCAGGAAG
GCGCACCCCC CCAGCAATCC GCGCGCCGGG ACAGAATGCC CTGCAGGAAC TTCTTCTGGA
AGACCTTCTC CTCCTGCAAA TAAAACCTCA CCCATGAATG CTCACGCAAG TTTAATTACA

It looks like this
ATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGG....
here is my code
public String formatInGroups(int index, int basesPerGroup, int groupsPerLine) {
      StringBuilder formattedSequence = new StringBuilder();
      String sequence = sequences.get(index);
      int num = 0;

      while(num < sequence.length()) {
         for(int i = 0; i < groupsPerLine; i++) {
            for( int j = 0; j < basesPerGroup; j++) {
               if(num < sequence.length()) {
                  formattedSequence.append(sequence.charAt(num));
                  num++;
               }
            }

      }

   }
  return sequence;
}
}

A: You should append a white space to the sequence after a dna sequence is appended (at the end of the inner for loop). Also, when a line is full, you should append a new line (\n) character to the sequence(at the end of the outer for loop).
public String formatInGroups(int index, int basesPerGroup, int groupsPerLine) {
    StringBuilder formattedSequence = new StringBuilder();
    String sequence = sequences.get(index);
    int num = 0;

    while(num < sequence.length()) {
        for(int i = 0; i < groupsPerLine; i++) {
            for( int j = 0; j < basesPerGroup; j++) {
               if(num < sequence.length()) {
                  formattedSequence.append(sequence.charAt(num));
                  formattedSequence.append(" ");
                  num++;
               }
            }
            formattedSequence.append("\n");
         }
    }
    return formattedSequence.toString();
}

A: Looking at your code, I think you just missed some little things here and there, add a new line break after a certain character count and a space after some groups, and also you were returning the wrong variable.
Here check this code I edited based on yours, I just added some simple stuff and you got the remaining right.
public String formatInGroups(int index, int basesPerGroup,
 int groupsPerLine) {
        // I suppose you have a 'sequences' list somewhere
        sequences.add(dna());
        StringBuilder formattedSequence = new StringBuilder();
        String sequence = sequences.get(index);
        int num = 0;

        while(num < sequence.length()) {
            for( int j = 0; j < basesPerGroup; j++) {
                if(num < sequence.length()) {
                    if (num % (basesPerGroup * groupsPerLine) == 0){
                        formattedSequence.append("\n");
                    }
                    formattedSequence.append(sequence.charAt(num));
                    num++;
                }
            }
            formattedSequence.append(" ");
        }
    return formattedSequence.toString().trim();
}

Little things to consider on your next problem:
1 - You were returning your original sequence instead of the formattedSequence.toString();
2 - Try to avoid using global variables, you can declare them inside your for loop;
3 - Try using better variable names, instead of num you could name your variable after something that it is doing, like charPositionCounter, it will improve your code readability.


text:
Q: How to make landscape mode rotate properly in a twoside book? How can I use pdflscape (or some other?) package in a twoside book so that landscape mode is always rotated so that top of the page points to the middle of the book? By default it seems landscape mode does not do that?
So I would like to have from time to time a page in a landscape mode, but it should be rotated correctly. This will probably make some landscape pages hard to read on a screen, as they will be flipped, but it would be much better printed.

A: What you ask is actually really hard, try adding the following to your preamble:
\makeatletter
\global\let\orig@begin@landscape=\landscape%
\global\let\orig@end@landscape=\endlandscape%
\gdef\@true{1}
\gdef\@false{0}
\gdef\landscape{%
    \global\let\within@landscape=\@true%
    \orig@begin@landscape%
}%
\gdef\endlandscape{%
    \orig@end@landscape%
    \global\let\within@landscape=\@false%
}%
\@ifpackageloaded{pdflscape}{%
    \gdef\pdf@landscape@rotate{\PLS@Rotate}%
}{
    \gdef\pdf@landscape@rotate#1{}%
}
\let\latex@outputpage\@outputpage
\def\@outputpage{
    \ifx\within@landscape\@true%
        \if@twoside%
            \ifodd\c@page%
                \gdef\LS@rot{\setbox\@outputbox\vbox{%
                    \pdf@landscape@rotate{-90}%
                    \hbox{\rotatebox{90}{\hbox{\rotatebox{180}{\box\@outputbox}}}}}%
                }%
            \else%
                \gdef\LS@rot{\setbox\@outputbox\vbox{%
                    \pdf@landscape@rotate{+90}%
                    \hbox{\rotatebox{90}{\hbox{\rotatebox{0}{\box\@outputbox}}}}}%
                }%
            \fi%
        \else%
            \gdef\LS@rot{\setbox\@outputbox\vbox{%
                \pdf@landscape@rotate{+90}%
                \hbox{\rotatebox{90}{\hbox{\rotatebox{0}{\box\@outputbox}}}}}%
            }%
        \fi%
    \fi%
    \latex@outputpage%
}
\makeatother


text:
Q: Custom WPF Control using Expression Effect dll I have set up the dependency properties:
   Public Shared ReadOnly SourceImageColor00Property As DependencyProperty = DependencyProperty.Register("SourceImageColor00", GetType(ColorToneEffect), GetType(OPCWPFImageColor))

And my property look lie this:
      <Description("Image Color to display"), _
Category("Color Properties")> _
Public Property SourceImageColor00() As ColorToneEffect
    Get
        Return DirectCast(Me.GetValue(SourceImageColor00Property), ColorToneEffect)
    End Get
    Set(ByVal value As ColorToneEffect)
        Me.SetValue(SourceImageColor00Property, value)
    End Set
End Property

The problem is that when I have an instance of the control in design mode the property name is displayed as "Color Tone" instead of "SourceImageColor00".
Any help would be greatly appreciated.

A: Set an DisplayName attribute for property:
<Description("Image Color to display"), _
Category("Color Properties"), _
DisplayName("Color Tone")> _
Public Property SourceImageColor00() As ColorToneEffect
    Get
        Return DirectCast(Me.GetValue(SourceImageColor00Property), ColorToneEffect)
    End Get
    Set(ByVal value As ColorToneEffect)
        Me.SetValue(SourceImageColor00Property, value)
    End Set
End Property

http://msdn.microsoft.com/en-us/library/system.componentmodel.displaynameattribute(v=vs.110).aspx


text:
Q: Segmentation Fault when trying to implement cat command functionality I am trying to make my own cat command in C by the name of "lolcat". It will read the command line arguments such as file name, open that file and print its contents in reverse order. The program is working fine when I run such commands as :
./lolcat file1.txt
It prints the file content in reversed order.
But when I try to implement the -n functionality to count the total number of lines.
such as
./lolcat -n file1.txt
It displays segmentation fault(core dumped).
I have the attached the code below:
#include <stdio.h>

int main(int argc , char *argv[])
{

    printf("%s" , argv[1]);

    int command = 0;
    if(argv[1] == "-n")
    {
        command = 2;
    }
    else{
        command = 1;
    }

    for(int i = command ; i < argc ; i++)

    {

        FILE *myFile = NULL;
        myFile = fopen(argv[i] , "r");
        char word[255];
        char c;
        int  c_count = 0;
        int w_count = 0;
        int l_count = 0;
        int prev_c_count = 0;
        int x = 0;
        int out = 0;

        while((c = fgetc(myFile)) != EOF)
        {
            word[x] = c;
            c_count++;
            if(c == '\n' || c == '\0')
            {
                l_count++;

                    if(command == 1)
                    {
                        for(int j = c_count - 1 ; j>=prev_c_count ; j--)
                        {
                            printf("%c" , word[j]);
                        }

                    }

                prev_c_count = c_count;
            }

            x++;

        }

        printf("\n");

            l_count++;

                    if(command == 1)
                    {
                        for(int j = c_count - 1 ; j>=prev_c_count ; j--)
                        {
                            printf("%c" , word[j]);
                        }
                    }

            prev_c_count = c_count;

        printf("\n");

    }

    return 0;
}

A: The cause for your segmentation fault is that your code is trying to run fgetc() on a null FILE stream pointer in the line:
while((c = fgetc(myFile)) != EOF)

This causes the libc to try to dereference a null pointer when it tries to read the file contents.
The root cause is, as mentioned in the comments, because you are doing a comparison between two char pointers (char *):
if(argv[1] == "-n")

And then setting the command variable based on that comparison and subsequentely setting i to this command value. Since the code will always enter the else block, command will start at 1.
Then you have the lines:
FILE *myFile = NULL;
myFile = fopen(argv[i], "r");

If command is 1, and therefore i starts as 1, the first argument to the fopen() call will be argv[1], which is, if you run $ ./lolcat -n file1.txt, the "-n" string. Since there's (probably) no '-n' file. (fun fact: I put some effort to create a file named '-n', and your code reads the files fine if this file is present)
How to fix it
The simplest (and quickiest) fix for your code would be replacing your if line (the one I mentioned as the root cause) by:
if(strcmp(argv[1], "-n") == 0)

Remember that, while C supports strings, it has no string type. Your compiler builts binaries having a string on a certain region of your memory, and it has functions to handle strings. However, a char * is NOT a string, it is rather a pointer to a char (the first char of the string. Since strings are null-terminated, functions like strcmp() iterate into the memory region started at the character pointed by the pointer until it finds a null character; there the string functions know the string ended.
Therefore, while it would work for a 'learning project', it's not safe to use in production since an attacker might easily make your program get stuck in an (almost) infinite loop.
Other issues
I could see some other possible problems in your code:

*

*Since you're statically allocating word as a 255-character array, if you get a line with more than 255 characters your code will have a buffer overflow.

*If no argument is passed, argv[1] will be a null pointer when you check it to define the value of command. Therefore, strcmp() will dereference a null pointer and you'll have a segmentation fault. You must check the value of a pointer every time you dereference it or run a function that does so (check the function docs/specs; but if a function receives a pointer argument, it likely does.

Hint: To make your life easier, you might want to take a look at getopt library to parse command-line arguments.


text:
Q: How to upload tar.gz and jar files as GitHub assets using python requests? In a certain directory, I have one .tar.gz and one .jar artifact.  I want to upload these assets for a release using requests.   Unfortunately, I can't get it to work.
Assuming that this .tar.gz file was called peaches.tar.gz here is what I tried doing:
headers = {'Content-Type': 'application/gzip'}
myAuth = {'MyGithubName', 'myToken'}
requests.post('https://api.github.com/repos/MyGithubName/MyRepo/releases/SomeIDNumber/assets?name=peaches.tar.gz, auth= myAuth, headers= headers, data= open('peaches.tar.gz', 'rb'))

A: From the Github documentation, to upload an asset you need the upload_url :
POST https://<upload_url>/repos/:owner/:repo/releases/:id/assets?name=foo.zip

You will need to extract this url from the get release API (list releases, get a single release or get latest release). You can find here :

Note: This returns an upload_url key corresponding to the endpoint for
uploading release assets. This key is a hypermedia resource.

The upload url is an URI template such as :
https://uploads.github.com/repos/bertrandmartel/ustream-dl/releases/8727946/assets{?name,label}

To build it, you can use uritemplate module & expand the name property (also described here)
The following will get the latest release and upload peaches.tar.gz asset to it (with name peaches.tar.gz) :
import requests
from uritemplate import URITemplate

repo = 'bertrandmartel/ustream-dl'
access_token = 'YOUR_ACCESS_TOKEN'

r = requests.get('https://api.github.com/repos/{0}/releases/latest'.format(repo))

upload_url = r.json()["upload_url"]

t = URITemplate(upload_url)
asset_url = t.expand(name = 'peaches.tar.gz')

headers = {
    'Content-Type': 'application/gzip',
    'Authorization': 'Token {0}'.format(access_token)
}
r = requests.post(
    asset_url,
    headers = headers,
    data = open('peaches.tar.gz', 'rb').read()
)
print(r.status_code)
print(r.text)


text:
Q: getting live webcam feed from opencv to Unity I have a project in Unity using openCV 2.3 with Mat images, but Im stuck at finding a way to get a live feed from the webcam to a Unity 2dtexture. I've caught that you somewhat need to pass a array to the plugin dll file, which will then paste the image data into the array, but I don't know how to do that. Hope someone can help

A: You can extract the pointer to the data array from the Mat image and pass it to your other module:
VideoCapture cap;
Mat frame;
.....

cap >> frame;
uchar* imgData = (uchar*)(frame.data);
myBeautifulFunctionThatNeedsArray(imgData, frame.cols, frame.rows, ...);


text:
Q: Root element is missing when trying to Publish It has been a while since I've published my app to Azure. During that time frame, I've upgraded my system from 32-bit to 64-bit meaning a fresh install of Windows and Visual Studio. And Visual Studio Update 3 came out and was applied. When I went to publish an update today, I received the following:
The following exception was thrown trying to publish: Root element is missing.
My web.config file looks fine so I don't think it's this issue.
The app works fine in debug mode so I don't think it's any of the .lsml files as is mentioned here.
And I tried this procedure to hand edit the .ls3proj file but it didn't seem to help.
I previously had an issue trying to publish when I upgraded from the standalone LightSwitch 2011 to Visual Studio 2012. I was able to overcome that issue using the method described in this thread.
Attempting to use this same method resulted in my new project has a full screen error saying "There are critical errors in the application definition metadata..." and 210 individual errors (max errors reached).
The first error, "Cannot create unknown type '{http://schemas.microsoft.com/LightSwitch/2010/xaml/model}GlobalAttributeGroup'." Doesn't make sense because that line in the .lsml is identical from the old project to the new project.
The second error, "Could not find any application definition in the project." Which I do not understand at all.
I am able to publish a simple "Hello, world" style app to my Azure account.
What could be causing this? How can I get more information about exactly which element is causing the issue? The log produced by running devenv /log was not helpful.

A: Matt Thalman was able to solve my problem over in the Microsoft Forums. The ServiceConfiguration.cscfg and ServiceDefinition.csdef were missing from the project when checked out of version control. Copying those over from a new project restored my ability to publish.


text:
Q: run apt update and get E: Failed to fetch File has unexpected size (2572288 != 2581052). Mirror sync in progress Good day!
I use local Ubuntu mirror repo to download software and security update, now when I run apt update command on a server, and it prompts the following error:
Err:12 http://security.ubuntu.com/ubuntu bionic-security/main amd64 Packages
File has unexpected size (2228224 != 2237636). Mirror sync in progress? [IP: xx.xxx.xx.x 80]
Hashes of expected file:

*

*Filesize:2237636 [weak]

*SHA256:53ff6687d2d7b881a42bb252d0420483c56dda25eb31957d4b02182bba3225e5

*SHA1:df28b37a3a7deb2e09ae2bcfcdecd590d2c8d6f8 [weak]

*MD5Sum:5bd4346c9d5d17625f15287c94d7ae5e [weak]
Release file created at: Mon, 23 May 2022 22:52:13 +0000

My Ubuntu version is 18.04, I check apt sources.list setting not found any issue, do I need to wait until the repo sync finished then run apt update? or is something wrong?

A: It turns out that the mirror server run out of disk and stuck at some packages, I expand the root directory and run "nohup sudo apt-mirror &", after apt-mirror sync completed, then run "apt update" command again, it works like a charm.


text:
Q: How to scale function parallel to x-axis I got this question on a mini test. The curve $y=\frac{-1}{x^2}$ is stretched parallel to the y-axis with scale factor 2. State the equation of the transformed curve.
I wrote $y=2f(-x)$
How is this wrong?

A: Your answer is almost correct.
Hint: Consider what happens to the function $f(x)$ when you replace in the brackets by -x. You are reflecting the function about the y-axis. Is this nescessary for the question asked?


text:
Q: Tomcat not starting after adding Elastic search High Level Client Dependency I have an existing project deployed into Tomcat v 8.5.
Once I added the elastic Search High Level client dependency, I am getting below exception while starting the server.
FYI. Earlier I have added a main method and wrote some basic code to do a POC on ES high level client and that time I had to exclude couple of dependency from other dependency as I was ClassNotFoundException.
Can someone help on this please?
 <dependency>
                <groupId>org.elasticsearch.client</groupId>
                <artifactId>elasticsearch-rest-high-level-client</artifactId>
                <version>7.6.1</version>
 </dependency>

Though the exception trace doesn't say anything related to Elastic search but when i remove the dependency server gets started without any issue.
Exception is -->
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/register-services]]
  at java.util.concurrent.FutureTask.report(FutureTask.java:122)
  at java.util.concurrent.FutureTask.get(FutureTask.java:192)
  at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:939)
  at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
  at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
  at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
  at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/register-services]]
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
  ... 6 more
Caused by: org.apache.tomee.catalina.TomEERuntimeException: org.apache.openejb.OpenEJBException: Unable to create annotation scanner for web module register-services: null
  at org.apache.tomee.catalina.TomcatWebAppBuilder.loadApplication(TomcatWebAppBuilder.java:2299)
  at org.apache.tomee.catalina.TomcatWebAppBuilder.startInternal(TomcatWebAppBuilder.java:1187)
  at org.apache.tomee.catalina.TomcatWebAppBuilder.configureStart(TomcatWebAppBuilder.java:1124)
  at org.apache.tomee.catalina.GlobalListenerSupport.lifecycleEvent(GlobalListenerSupport.java:133)
  at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:94)
  at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5087)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
  ... 6 more
Caused by: org.apache.openejb.OpenEJBException: Unable to create annotation scanner for web module register-services: null
  at org.apache.openejb.config.DeploymentLoader.addWebModule(DeploymentLoader.java:886)
  at org.apache.openejb.config.DeploymentLoader.load(DeploymentLoader.java:233)
  at org.apache.tomee.catalina.TomcatWebAppBuilder.loadApplication(TomcatWebAppBuilder.java:2297)
  ... 12 more
Caused by: java.lang.IllegalArgumentException
  at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source)
  at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source)
  at org.apache.xbean.asm5.ClassReader.<init>(Unknown Source)
  at org.apache.xbean.finder.AnnotationFinder.readClassDef(AnnotationFinder.java:1169)
  at org.apache.xbean.finder.AnnotationFinder.<init>(AnnotationFinder.java:147)
  at org.apache.xbean.finder.AnnotationFinder.<init>(AnnotationFinder.java:160)
  at org.apache.openejb.config.FinderFactory$OpenEJBAnnotationFinder.<init>(FinderFactory.java:546)
  at org.apache.openejb.config.FinderFactory.newFinder(FinderFactory.java:267)
  at org.apache.openejb.config.FinderFactory.create(FinderFactory.java:80)
  at org.apache.openejb.config.FinderFactory.createFinder(FinderFactory.java:69)
  at org.apache.openejb.config.DeploymentLoader.addWebModule(DeploymentLoader.java:878)
  ... 14 more

Mar 17, 2020 7:16:37 PM sun.reflect.NativeMethodAccessorImpl invoke
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
  at java.util.concurrent.FutureTask.report(FutureTask.java:122)
  at java.util.concurrent.FutureTask.get(FutureTask.java:192)
  at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:939)
  at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
  at org.apache.catalina.core.StandardService.startInternal(StandardService.java:422)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
  at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:793)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
  at org.apache.catalina.startup.Catalina.start(Catalina.java:655)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:355)
  at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:495)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167)
  at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
  at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
  at java.util.concurrent.FutureTask.run(FutureTask.java:266)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
  at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
  at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:947)
  at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:872)
  at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
  ... 6 more


text:
Q: How to trigger email for every check-out in EME - Ab Initio I would like to create a new notification email with each checkout in EME (Enterprise Meta Environment). I have been searching the web for a valid lead but I didn't come across any blogs or article.

A: It depends on whether you are using GDE or you are using air commands to check out.
If you are using a air commands then its straight farward. Write a generic checkout script and add a mailx command after the air commands. Ask your team to use this generic script for all check out check-in tasks :)


text:
Q: facebook application get the username using php api i 've found using file_get_contents like
json_decode(file_get_contents('http://graphdotfacebookdotcom/'.$uid));
will make my application very slow to load, are there any methods to retrieve the username of the facebook user?
thanks

A: You may use the facebook sdk for this.
$session = $facebook->getSession();

$me = null;
// Session based API call.
if ($session) {
  try {
    $uid = $facebook->getUser();
    $me = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}

To see the complete example https://github.com/facebook/php-sdk/blob/master/examples/example.php

A: $facebook = new Facebook(array(
'appId'  => $APIappId,
'secret' => $APIsecret,
'cookie' => true
 ));
$facebook->api('/'.$uid);

Don't forget to include facebook.php at the top

A: Why dont you use Facebook PHP SDK to get the details.
You can get the other basic information also without time consuming.

A: You can speed this up by requesting less information like so (in PHP):
$me = $fb->api('me', array('fields' => 'username'));
$username = (isset($me['username'])) ? $me['username'] : '';

and in the JS SDK like so:
FB.api('me', {fields: 'username'}, function() { console.log(arguments); });

A: No. There's no way to speed it up.


text:
Q: hybrid graphics card issues radeon I have a dell inspiron 5567 laptop and am dual booting windows 10 and ubuntu 16.04. I have been trying for a while now to get the integrated graphics card working, which windows sees as a Radeon R7 M440 but ubuntu shows Topaz XT [Radeon R7 M260/M265].
I have tried vgaswitcheroo here: https://help.ubuntu.com/community/HybridGraphics , but it doesn't do anything. When I tried what is suggested by the first post here vgaswitcheroo not selecting discrete card it simply shut the screen down until I forced a shutdown.
PRIME (https://wiki.archlinux.org/index.php/PRIME) seems to work, except that I tested it using glmark2 and got significantly better performance from the integrated card than the discrete card, with the integrated card achieving 1076 FPS on the first test while discrete card only got 478 FPS. sudo lshw -C video shows the discrete card as using the amdgpu drivers.
From the output if glmark2 (given below), it seems to me that the discrete card is working but does not work with the intel card very efficiently.
Is there any way to make the machine only use the discrete graphics card without using VGAswitcheroo? or have I used vgaswitcheroo improperly? I am still reliatively new to ubuntu so any help is appreciated.
The full output of sudo lshw -C video is:
  *-display
   description: VGA compatible controller
   product: Intel Corporation
   vendor: Intel Corporation
   physical id: 2
   bus info: pci@0000:00:02.0
   version: 02
   width: 64 bits
   clock: 33MHz
   capabilities: pciexpress msi pm vga_controller bus_master cap_list rom
   configuration: driver=i915 latency=0
   resources: irq:280 memory:de000000-deffffff memory:b0000000-bfffffff ioport:f000(size=64) memory:c0000-dffff
  *-display
   description: Display controller
   product: Topaz XT [Radeon R7 M260/M265]
   vendor: Advanced Micro Devices, Inc. [AMD/ATI]
   physical id: 0
   bus info: pci@0000:01:00.0
   version: c3
   width: 64 bits
   clock: 33MHz
   capabilities: pm pciexpress msi bus_master cap_list rom
   configuration: driver=amdgpu latency=0
   resources: irq:281 memory:c0000000-cfffffff memory:d0000000-d01fffff ioport:e000(size=256) memory:df200000-df23ffff memory:df240000-df25ffff

xrandr --listproviders shows:
Providers: number : 2
Provider 0: id: 0x64 cap: 0x9, Source Output, Sink Offload crtcs: 3 outputs: 2 associated providers: 1 name:modesetting
Provider 1: id: 0x3f cap: 0x4, Source Offload crtcs: 0 outputs: 0 associated providers: 1 name:Unknown AMD Radeon GPU @ pci:0000:01:00.0

The first few results from glmark2 are as follows:
glmark2 gave:
=======================================================
    glmark2 2014.03+git20150611.fa71af2d
=======================================================
    OpenGL Information
    GL_VENDOR:     Intel Open Source Technology Center
    GL_RENDERER:   Mesa DRI Intel(R) HD Graphics 620 (Kaby Lake GT2)
    GL_VERSION:    3.0 Mesa 17.2.8
=======================================================
[build] use-vbo=false: FPS: 1076 FrameTime: 0.929 ms
[build] use-vbo=true: FPS: 1223 FrameTime: 0.818 ms
[texture] texture-filter=nearest: FPS: 1176 FrameTime: 0.850 ms
[texture] texture-filter=linear: FPS: 1206 FrameTime: 0.829 ms
[texture] texture-filter=mipmap: FPS: 1172 FrameTime: 0.853 ms
[shading] shading=gouraud: FPS: 1082 FrameTime: 0.924 ms
[shading] shading=blinn-phong-inf:^C

DRI_PRIME=1 glmark2
=======================================================
    glmark2 2014.03+git20150611.fa71af2d
=======================================================
    OpenGL Information
    GL_VENDOR:     X.Org
    GL_RENDERER:   AMD ICELAND (DRM 3.18.0 / 4.13.0-41-generic, LLVM 5.0.0)
    GL_VERSION:    3.0 Mesa 17.2.8
=======================================================
[build] use-vbo=false: FPS: 478 FrameTime: 2.092 ms
[build] use-vbo=true: FPS: 506 FrameTime: 1.976 ms
[texture] texture-filter=nearest: FPS: 470 FrameTime: 2.128 ms
[texture] texture-filter=linear:^C

A: The product string can be mismatch with what it should be. I think its fine as long as string shows same product family. Hybrid cards indeed complicated stuff and when its about the play games at Steam, selecting right card can be so buggy. As an example Dota with Hybrid RADV didnt work with Mesa 17.2 and below, at least for me.
Well first try blacklist radeon module from kernel.
How to blacklist radeon module?
Try Oibaff's Mesa stacks, and if there no problem appear use them.
Install radeon-profile with its daemon. https://github.com/marazmista/radeon-profile
Its a usefull control center for your AMD card. Set Performance/High mode your card. You can OC too, as i always do.
Last use glxinfo | grep "OpenGL" for GLStrings, its more proper way yet produce same result.


text:
Q: Trying to understand exif.encode_unicode Occasionally I get PHP errors from my site's users uploading photos, and the EXIF data not being valid UTF-8 when I subsequently try to json_encode it. The specific error I get is:
E_WARNING: json_encode(): Invalid UTF-8 sequence in argument

That's generated by the final line of the code below.
ini_set('exif.encode_unicode', 'UTF-8');
$exif_data = exif_read_data($uploader_target_dir . $_POST['uploader_' . $i . '_tmpname']);
$when_photo_taken = isset($exif_data['DateTime']) ? (int)strtotime($exif_data['DateTime']) : 0;
$exif_data = (json_encode($exif_data));

As you can see, I'm setting the exif.encode_unicode option to UTF-8, although I'm not 100% sure of what this does (the sentence "exif.encode_unicode defines the characterset UNICODE user comments are handled" in the manual seems pretty ambiguous/confusing to me), but either way it hasn't fixed the problem.
Does anyone know exactly what this configuration option does? Or what is causing my E_WARNING?

A: I'm reasonably sure that that config tells the exif code which character set to convert to when it's converting the text that is stored in the image.
The issue will be that some of the text read from the exif data will either claim to be in UTF-8 format but actually has some invalid bytes, or is in some other way garbled.
If you want to investigate the cause of the issue, which may be worth reporting as a bug if it affects lots of images, you can get the raw bytes from the text, and should be able to see what exactly is causing the error by emitting the raw bytes:
foreach ($exif_data as $key => $value) {

    $resultInHex = unpack('H*', $value);
    $resultInHex = $resultInHex[1];
    $resultSeparated = implode(', ', str_split($resultInHex, 2)); //byte safe

    var_dump($resultSeparated);
}

If you don't care and just want to cleanse your data so that it stops throwing errors, you can just remove all non-valid UTF8 characters from your users data - which you probably should be anyway.
function removeInvalidChars ($text) {
    $regex = '/( [\x00-\x7F] | [\xC0-\xDF][\x80-\xBF] | [\xE0-\xEF][\x80-\xBF]{2} | [\xF0-\xF7][\x80-\xBF]{3} ) | ./x';
    return preg_replace($regex, '$1', $text);
}


text:
Q: Random Sampling a linearly constrained region in n-dimensions... Hi,
So here is my problem:
Given a nonlinear, discontinous, cost function $f(x_1,x_2,..,x_N)$ along with linear constraints $x_n \ge 0, \forall n$
$x_n \le c_n$
 and $\sum_{n=1}^N x_n = 1$ find an optimal (local) solution by randomly sampling the feasible region.  $c_n$ are just constants.
The issue I am having is indexing the space, since it is not a simple n-dimensional cube but rather a polytope(i believe its convex).  Discretizing and enumerating all possible combinations of points to sample is much too hard since N =20.  Approximating the polytope with a n-dimensional cube and sampling from the cube, only about 1% of the samples fall within the feasible region...which is inefficient if I'm trying to generate many samples.
I've tried finding the volume of the space analytically, however the complexity of computing the integral gets overwhelming for many dimensions.
I was wondering if anyone has come across this type of problem and has any recommendation as to different methods I could try to sample this space.  Essentially, I need a good way to estimate the volume...am I looking at this the correct way?
any help would be greatly appreciated...

A: I believe the primary method to generate uniform samples in convex polytopes is via a Markov-chain random walk.
For example, the paper by
Ravi Kannan and
Hariharan Narayanan,
"Random walks on polytopes and an affine interior point method for linear programming,"
STOC 2009,
(ACM link)
achieves a strongly polynomial mixing time.
The basic idea is explained in these older notes by H.E. Romeijn and R.L Smith, "Sampling through Random Walks," (PDF), or,
perhaps better, Santosh Vempala's 2008 notes on Algorithmic Convex Geometry (PDF).
The Kannan-Narayanan paper gives a condensed history of algorithms to find (approximately) the volume
of a convex polytope, starting from the Dyer, Frieze, and Kannan paper from 1991 whose
mixing time was $O(n^{23})$ for a polytope in $\mathbb{R}^n$, through a series of steady improvements
reducing the dependency on $n$ down to closer to $n^2$.  I am not certain this is the latest word on
this topic.

A: Your constraints $x_n \geq 0$, $\sum_{n=1}^N x_n = 1$, are those for the standard simplex.  You could try uniform sampling from the standard simplex, and then reject any sample that doesn't also satisfy the $x_n \leq c_n$ constraints.
An alternative to the procedure described in the linked paper above for uniform sampling from the standard simplex is to generate $n$ exponential(1) random variables $X_1, X_2, \ldots, X_n$ and let $Y_i = X_i/\sum_{i=1}^n X_i$.  Then $(Y_1,Y_2,\ldots,Y_n)$ is uniformly distributed on the standard simplex.  This can be thought of as generating a random vector from the symmetric Dirichlet distribution.  (Also, generating exponential(1) random variables is easy; if $Z \sim U(0,1)$ then $-\ln(Z)$ has an exponential(1) distribution.)  Once again, you would then reject any sample that doesn't also satisfy the $x_n \leq c_n$ constraints.

A: If the $c_n$ are sufficiently small (say, all smaller than $1/\sqrt{n}$) or sufficiently large (say, all at least $1$) the polytope is a simplex, so estimating the volume and sampling are both easy as pointed out in @Mike's answer. On the other hand, trying to find a local optimum by uniform sampling is doomed in $20$-dimensional space, since the distance between the samples will be very large for any reasonable number of samples. (for example, if your polytope were a cube of side one, generating $2^{40}$ points will have inter point distances around $1/4.$ Needless to say, generating $2^{40}$ points might take a while.


text:
Q: Cordova Telerik Native transition plugin I would like to use this [plugin from Telerik] (http://plugins.telerik.com/cordova/plugin/native-page-transitions) in my Cordova project.
I've followed the guide and use the following code to transition to another view:
window.plugins.nativepagetransitions.slide({
"href" : "#page-id"
});

But the view doesn't update. My index.html is structured so that each page is a section with a unique id. In their documentation they say the following

So before the transition, but after the screenshot is created, the view needs to change. There are several ways to do this, but it's probably easiest to to let the plugin handle this for you. Every function accepts a 'href' parameter which you can fill with stuff like '#home', 'home.html', 'details.html?item=3', etc. Basically anything you'd normally put in a href tag to enable navigation in your app. Note that because of this approach even a classic frameworkless multi-page app can now have page transitions!

But who is hiding and showing the section? Is the plugin or do I need to do it?
I'm not using any framework like jquery mobile etc.

A: So here is the mystery solved.
Your HTML structure needs to follow JQuery Mobile convention. So in order for views to change successfully you need to use divs with data-role="page", data-role="header" and so on.
This is not ideal if you have an HTML structure in place or would like to use HTML5.


text:
Q: AWS DynamoDB - sync localhost db with server hosted db? I'm very new to working with databases in general! I'm working with DynamoDB for a mobile app and I recently discovered that I could use Python to script table creation and data entry by running DynamoDB locally on my computer. Now, intuitively, I thought there must be a way to test my database and locally, but then push the changes to my server hosted DB. But after countless searches on Google, I still can't find a way to do so and it doesn't seem like this concept exists?
Can anyone fill in the blanks for me here? Thanks!

A: Are you using DynamoDBLocal for testing your changes?
If so, DynamoDBLocal is meant to be a standalone application purely for offline testing. There is no way or mechanism to sync the changes to the local database to the API hosted service.


text:
Q: Jquery open document file on click or it open on browser new tab I want to open document file on click in browser's new Tab or in its relevant Software, like .doc file open in Microsoft Word.
check my screen shots

and

Here is my code:
var doc1 = obj[i].resume;
var doc = "documents/"+ doc1;   //documents/BPO INTRVW QUE.rtf
html1 += "" + ''+doc1+''+ "	";

A: using  instead of  '
passing string as a href in link like '" "' it should close issue


text:
Q: uploading wordpress files to web host I have a hosting server subscription, and on that server I want to start building my Wordpress website, I just finished uploading the Wordpress files to the web host file manger,  and doing the configuration of database file,
when I was about testing the Wordpress page, an error message poped out says:
HTTP ERROR 500
could anyone tell what is this problem about? and how can I fix it?


text:
Q: HTTP PUT request, how can i generate one and where can i find examples/syntax? I have an assignment at school to build a webserver that handles GET/HEAD/PUT requests, via browser and Telnet, i have a working server handling GET/HEAD and telnet requests but i cant find out how a put request works/looks. I know its used to put content on a webserver but the syntax i cant find=/
-Jonas

A: PUT /urlofnewresource HTTP/1.1
Content-Length: xxx
Host: example.org
Connection: close
Any-Other-Header: ..

Contents. This can be any binary or text file.

A response to this (if you created a new resource) may be something like this:
HTTP/1.1 201 Created
ETag: ".."
Content-Length: 0

If you updated an existing resource, it could be
HTTP/1.1 204 No Content
ETag: ".."
Content-Length: 0

Or just '200 Ok' if you want to return some more information.
This information is not that hard to find though, just look in the HTTP/1.1 specification.


text:
Q: Constraining map panning with zoom.translateExtent in D3 v4 I'm trying to display a map of a single state, with zooming and panning constrained to the boundaries of the state. It's mostly working, except for the panning constraint when the state path is scaled to fit a smaller container. I think this comes down to me not understanding what arguments to use for zoom.translateExtent (although I'm very new to this, so it could be something else).
Live example on bl.ocks.org, with links to prior art.
One notable thing is that I'm using a null projection for d3.geoPath, because I used ogr2ogr to generate a shapefile in projected coordinates for each state. That's why I used a zoom transform to fit the map to its container.

A: @McGiogen's solution is almost correct but misses that MIN needs to vary depending on the zoom scale factor transform.k.
I drew a diagram to see how I needed to constrain my svg to always be contained inside the zoomed view (depicted in my drawing as the LARGER of the boxes, only a portion of which is visible to the user):

(since the constraint x+kw >= w is equivalent to x >= (1-k)w, with a similar argument for y)
thus assuming your svg container size [w, h]:
function zoomed() {
    var t = d3.event.transform;

    t.x = d3.min([t.x, 0]);
    t.y = d3.min([t.y, 0]);
    t.x = d3.max([t.x, (1-t.k) * w]);
    t.y = d3.max([t.y, (1-t.k) * h]);

    svg.attr("transform", t);
}

A: I'm facing the same problem today and I've done some tests.
I've noticed that it's the same weird behaviour happening when you have a translateExtent box smaller than the content's elements.
In your (and mine) code the same behaviour is triggered by zooming out: it doesn't matter if you have the translateExtent box correctly set with no zoom, if you zoom out the box is reduced at higher rate than the elements and at some point you will have translateExtent box smaller than the content (and the weird behaviour).
I temporary solved this as said here
D3 pan+ zoom constraints
var MIN = {x: 0, y: -500},     //top-left corner
    MAX = {x: 2000, y: 500};   //bottom-right corner

function zoomed() {
   var transform = d3.event.transform;

   // limiting tranformation by MIN and MAX bounds
   transform.x = d3.max([transform.x, MIN.x]);
   transform.y = d3.max([transform.y, MIN.y]);
   transform.x = d3.min([transform.x, MAX.x]);
   transform.y = d3.min([transform.y, MAX.y]);

   container.attr("transform", transform);
}

I'm still a d3 newbie but I think that this is a bug in translateExtent code.


text:
Q: MySQL manipulate view data I am reading a view which gives me data like below:
msn       | global_device_id | meter_datetime        | interval| channel_id | active_energy_pos_t1
==================================================================================================
3798000021| 980021           | 2020-07-29 16:45:00   | 15      | 1          | 72.80300
3798000021| 980021           | 2020-07-29 17:00:00   | 15      | 1          | 72.80300
3798000021| 980021           | 2020-07-29 17:15:00   | 15      | 1          | 72.80300
3798000021| 980021           | 2020-07-29 17:30:00   | 15      | 1          | 72.80300
....

The channel_id is 1 for each and every record. I want to manipulate it. I want to make exact 3 copies of the above data virtually the 1st data should have channel_id as 1 the second should have channel_id as 2 and the 3rd should have channel_id as 3 like below
msn       | global_device_id | meter_datetime        | interval| channel_id | active_energy_pos_t1
==================================================================================================
3798000021| 980021           | 2020-07-29 16:45:00   | 15      | 1          | 72.80300
3798000021| 980021           | 2020-07-29 17:00:00   | 15      | 1          | 72.80300
3798000021| 980021           | 2020-07-29 17:15:00   | 15      | 1          | 72.80300
3798000021| 980021           | 2020-07-29 17:30:00   | 15      | 1          | 72.80300
3798000021| 980021           | 2020-07-29 16:45:00   | 15      | 2          | 72.80300
3798000021| 980021           | 2020-07-29 17:00:00   | 15      | 2          | 72.80300
3798000021| 980021           | 2020-07-29 17:15:00   | 15      | 2          | 72.80300
3798000021| 980021           | 2020-07-29 17:30:00   | 15      | 2          | 72.80300
3798000021| 980021           | 2020-07-29 16:45:00   | 15      | 3          | 72.80300
3798000021| 980021           | 2020-07-29 17:00:00   | 15      | 3          | 72.80300
3798000021| 980021           | 2020-07-29 17:15:00   | 15      | 3          | 72.80300
3798000021| 980021           | 2020-07-29 17:30:00   | 15      | 3          | 72.80300

....

The view name is load_profile_data.  How can I do it?

A: You can cross join the view with a list of fixed values:
select l.msn, l.global_device_id, l.meter_datetime, l.interval, c.channel_id, l.active_energy_pos_t1
from load_profile_data l
cross join (select 1 channel_id union all select 2 union all select 3) c

A: One approach uses a union:
SELECT msn, global_device_id, meter_datetime, `interval`, channel_id, active_energy_pos_t1
FROM load_profile_data
UNION ALL
SELECT msn, global_device_id, meter_datetime, `interval`, 2, active_energy_pos_t1
FROM load_profile_data
UNION ALL
SELECT msn, global_device_id, meter_datetime, `interval`, 3, active_energy_pos_t1
FROM load_profile_data;

Side note: INTERVAL is a reserved keyword in MySQL.  I escaped in backticks in the query above, but in general you should avoid using reserved keywords to name your database objects.

A: Try union:
select msn , global_device_id , meter_datetime . interval, channel_id ,active_energy_pos_t1 from load_profile_data

union

select msn , global_device_id , meter_datetime . interval, channel_id +1 ,active_energy_pos_t1 from load_profile_data

union

select msn , global_device_id , meter_datetime . interval, channel_id+2 ,active_energy_pos_t1 from load_profile_data