text:
Q: Retrofit2-AWS S3 Multipart image File corrupt issue I am using Retrofit2 for handling API calls in my Android application. The application contains several image upload features. All the image uploading features are wired up to two API calls and will fire one after another.

*

*The first API will upload the image content to the server and the server will generate a dynamic signed AWS S3 image URL as a response.

*The second API is using the above-signed URL and PUT the data into AWS S3.
It was working perfectly for small images. For large images, the API has failed. The possible solution for this issue is to change the upload API as multipart. So I have changed the second API as "Retrofit2-multipart". But the problem here is,  After uploading the image, the file got corrupted in the S3.
So my question is, Is retrofit multipart is fit for ASW S3 upload?
Do we have any solution to solve this issue?.
Please check my Implementation
Retrofit API Interface
 @Multipart
    @PUT
    Call<Void> uploadFile(@Url String url,
                          @Part MultipartBody.Part file);

Retrofit service creator
 private ApiServicesList createService() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(300, TimeUnit.SECONDS)
                .connectTimeout(360, TimeUnit.SECONDS)
                .cache(null)
                .addInterceptor(new NetworkInterceptor(context))
                .addInterceptor(createLoggingInterceptor())
                .addInterceptor(createSessionExpiryInterceptor())
                .addInterceptor(createContextHeaderInterceptor())
                .build();

        return new Retrofit.Builder()
                .baseUrl(FirebaseConfig.getInstance().getStagingBaseURl())
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build()
                .create(ApiServicesList.class);
    }

File Upload Class
 public void uploadFileTos3(String url, MultipartBody.Part file, Callback<Void> listener) {
        Call<Void> call = mAPIServices.uploadFile(url,file);
        call.enqueue(listener);
    }

Presenter API Call
networkServices.uploadFileTos3(credentials.getSignedUrl(), prepareRequestBody(file), new Callback<Void>() {
            @Override
            public void onFailure(Call<Void> call, Throwable t) {
               //App Action
            }

            @Override
            public void
            onResponse(Call<Void> call, Response<Void> response) {
               //App Action
            }
        });

Request Body Method
 public static MultipartBody.Part prepareRequestBody(File file) {
        RequestBody requestFile = RequestBody.create(MediaType.parse(CONTENT_TYPE), file); // Checked Both "image/jpeg" and "multipart/form-data"
        return  MultipartBody.Part.createFormData("image", file.getName(), requestFile);
    }

DDMS LOGS
2019-04-10 19:07:13.926 18761-18874/com.xxx D/OkHttp: --> PUT https:Signed URL(Removed actual URL)
2019-04-10 19:07:13.926 18761-18874/com.xxx D/OkHttp: Content-Type: multipart/form-data; boundary=60561d1c-ff3f-4a43-8022-ca2be3e8ec4e
2019-04-10 19:07:13.926 18761-18874/com.xxx D/OkHttp: Content-Length: 71154
2019-04-10 19:07:13.931 18761-18874/com.xxx D/OkHttp: --60561d1c-ff3f-4a43-8022-ca2be3e8ec4e
2019-04-10 19:07:13.931 18761-18874/com.xxx D/OkHttp: Content-Disposition: form-data; name="image"; filename="forest-trees-fog-foggy.jpg"
2019-04-10 19:07:13.931 18761-18874/com.xxx D/OkHttp: Content-Type: image/jpeg
2019-04-10 19:07:13.931 18761-18874/com.xxx D/OkHttp: Content-Length: 70934
2019-04-10 19:07:13.931 18761-18874/com.xxx D/OkHttp: Image Body
2019-04-10 19:07:13.942 18761-18874/com.xxx D/OkHttp: --60561d1c-ff3f-4a43-8022-ca2be3e8ec4e--
2019-04-10 19:07:13.942 18761-18874/com.xxx D/OkHttp: --> END PUT (71154-byte body)
2019-04-10 19:07:15.648 18761-18874/com.xxx D/OkHttp: <-- 200 OK


text:
Q: Should this rolling resistance formula be scaled based on wheel count? I found two websites that model the power required to overcome the losses due to rolling resistance when riding a bike, here and here.
Both of them give the same formula for the Power (ignoring the gradient term in the first link, which is 1 for a flat road),
$$ P_{rr} = C_{rr}mgv $$
That equations seems reasonable given that $C_{rr}$ is defined as $F_{rr} = C_{rr}N = C_{rr}mg$, and $P=Fv$.
But link #2 seems to suggest that this will calculate the power required to overcome the resistance of just one wheel, and so to get the total result we must multiply by 2.
Link #1 doesn't seem to include this in the calculation.
So my question is : Do we need to multiply by the number of wheels?
Intuitively to me, I assumed that the m in the equation above was the mass of the system (bike + rider). Surely if you multiply the value by 2, you're compensating for the fact that each wheel takes approximately (very approximately I would guess) half the load of the system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript file 404s when loaded via Require JS alias I've ran into a strange problem where a custom javascript file 404s when loaded via a RequireJS alias but it works fine when loaded directly.
This does not work
Require JS
var config = {
    map: {
        '*': {
            recentlyViewedCarousel: 'Magento_Reports/js/recently-viewed'
        }
    }
};

Template
File: app/design/frontend/Vendorname/theme/Magento_Reports/templates/widget/viewed/column/viewed_images_list.phtml

<?php if ($exist): ?>
    <script type="text/x-magento-init">
        {
            "*": {
                "recentlyViewedCarousel": {}
            }
        }
    </script>
<?php endif; ?>

Error
GET http://localhost:3000/static/frontend/Vendorname/default/en_GB/recentlyViewedCarousel.js 404

require.js:166 Uncaught Error: Script error for: recentlyViewedCarousel

Yet this does work
Template
File: app/design/frontend/Vendorname/theme/Magento_Reports/templates/widget/viewed/column/viewed_images_list.phtml

<?php if ($exist): ?>
    <script type="text/x-magento-init">
        {
            "*": {
                "Magento_Reports/js/recently-viewed-carousel": {}
            }
        }
    </script>
<?php endif; ?>

The path is the exact same, the only difference is the method that does not work uses a Require alias and the method that does work directly references the file.
I have done this exact same thing as part of the Magento_Theme module and it works fine.
I'm happy with the workaround but I'm intrigued as to what's causing this.
This template is loaded via the CMS recently viewed widget inside a static block, so it may be a bug where Require aliases do not work with CMS widgets?


text:
Q: Read file and count same entries in Java I need some advice. I know how to solve this problem clumsily, but I want to do it the right way, as I need to impress someone for a potential internship.
I have a textfile, for example:
[XXX622] [YYY]  [LLL]   [E77700]  [NNN]  [6JL99NNN] [HH66]  [0770LLL]  [R88] [VVV]
[B177HQ] [8RR22]   [PPP]  [GGG]  [CCXXXGG]   [8IIXX0] [3KCC]   [00222]
[222] [OO] [OO] [OO] [99]   [555444]   [33]

I need to read the entries and then do processes with them, for example sort alphabetically.
The process I don't know how to do is counting how many similar entries are in each line.
If I read the entries into a string array and pass the array to the counting method, then how should I make it so the method knows from which line each entry is? Should I create a 2D array and insert the linenumber along with the entry into it as a string?
Thanks in advance!

A: Here's a hint.
Use a Map (some concrete implementation thereof; HashMap would work) when you process the line. If you know how to insert an entry into a Map, and if you know how to tell if an entry already exists in the Map, you have your solution!
If you really want to impress them  explain to them why the Map solution is fast and then also explain the speed vs. memory trade-offs. Using Big-O notation will impress them more and will also show that you know what you're talking about.
I'm not going to give you the entire (working) solution since you said this was for an internship. If your intent is to impress them, you should work out the solution yourself. Presenting a community solution as your own would be a little dishonest, in my opinion.

A: You have a few good options. The simplest would be to simply read the entries in and process them one line at a time, rather than all at once. Another option would be to create a class that represents a line:
public class CodeLine {
    public int lineNumber;
    public List<string> codes;
}

This is a more "object-oriented" way to represent your lines, as opposed to a 2D array.


text:
Q: How can send email to two email Id's in Mail function This is my code
$secondEmail="eamail2@gmail.com";

to send mail two emails
$to = $email,$secondEmail;
$email_from = 'website.com';
$email_subject = "Register Details: " ;
$email_body = "Sender Name: $from"

.

A: You can add multiple emails With comma separated values
$to = "myfirstemail@xyz.com, mysecondemail@xyz.com";
$email_from = 'website.com';
$email_subject = "Register Details: " ;
$email_body = "Sender Name: $from" ;

For variable simply put it in "";
$email1="eamil1@gmail.com";
$email2="email2@gmail.com";
$to = "$email1 , $email2";

A: You can use mail ids as string,
$to = $email.",".$secondEmail;
$email_from = 'website.com';
$email_subject = "Register Details: " ;
$email_body = "Sender Name: $from"


text:
Q: unable locate element when using by,linktext I am trying to test the filter function at
https://todomvc.com/examples/vue/

user can click 'All' 'Active' or 'Completed' to filter the list.
the java class:
public static By filterButtonWithLabel(String filters) {
    return By.linkText(filters);
}

error:
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"link text","selector":""Active""}

what is this error about? is that telling i cannot use by.linktext?

A: I just realize it is the steps problem
I should not use double quote, just type the string "Completed" directly.
And I filter the list to show Completed tasks


text:
Q: How to reshape data from wide to long with multipe variables? I have a very large dataset that I need to reshape from wide to long.
Here is a demo of my datset which contains all the situation:
genename    case1   case2   case3   strand
TP53            1       0       1      pos
TNN             0       0       1      pos
CD13            0       0       0      pos
AP35            1       1       1      neg

And the case will be only kept and reshape to longitudinal when an 1 exist, just like the following:
genename    case    strand
TP53       case1       pos
TP53       case3       pos
TNN        case3       pos
AP35       case1       neg
AP35       case2       neg
AP35       case3       neg

How could I process this kind of reshape in R?

A: tidyverse
df <- read.table(text="genename    case1   case2   case3   strand
TP53            1       0       1      pos
TNN             0       0       1      pos
CD13            0       0       0      pos
AP35            1       1       1      neg", header =T)

library(tidyverse)

df %>%
  gather( case, case_value, c(case1, case2, case3) ) %>%
  filter( case_value == 1 )

#   genename strand  case case_value
# 1     TP53    pos case1          1
# 2     AP35    neg case1          1
# 3     AP35    neg case2          1
# 4     TP53    pos case3          1
# 5      TNN    pos case3          1
# 6     AP35    neg case3          1

data.table
library(data.table)
data.table::melt( setDT(df), id.vars = c("genename", "strand"), measure.vars = c("case1", "case2", "case3") )[value == 1, ][]

#    genename strand variable value
# 1:     TP53    pos    case1     1
# 2:     AP35    neg    case1     1
# 3:     AP35    neg    case2     1
# 4:     TP53    pos    case3     1
# 5:      TNN    pos    case3     1
# 6:     AP35    neg    case3     1

benchmarks
microbenchmark::microbenchmark(
tidyverse = { df %>%
  gather( case, case_value, c(case1, case2, case3) ) %>%
  filter( case_value == 1 )},
data.table = { melt( setDT(df), id.vars = c("genename", "strand"), measure.vars = c("case1", "case2", "case3") )[value == 1, ][] },
times = 1000)

# Unit: milliseconds
#       expr      min       lq     mean   median       uq      max neval
# tidyverse 2.335393 2.569323 3.157647 2.737729 3.089605 29.29513  1000
# data.table 1.374062 1.551656 1.845519 1.676229 1.838309 28.23499  1000


text:
Q: C++ Understanding Functors Polymorphism I try to implement polymorphic functor objects (pure abstract base class and children) for understanding purposes only. My goal is to create many objects of the base class that use different implementations of the pure virtual functions.
When I create a pointer of the base class and set it equal to a new child class, I can not call the object as a function. The error is:
main.cpp:29:7: error: 'a' cannot be used as a function

Here is the code:
#include <iostream>

class foo{
public:
    virtual void operator()() = 0;
    virtual ~foo(){}
};

class bar: public foo{
public:
    void operator()(){ std::cout << "bar" << std::endl;}
};

class car: public foo{
public:
    void operator()(){ std::cout << "car" << std::endl;}
};

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

    foo *a = new bar;
    foo *b = new car;

    //prints out the address of the two object:
    //hence I know that they are being created
    std::cout << a << std::endl;
    std::cout << b << std::endl;

    //does not call bar() instead returns the error mentioned above
    //I also tried some obscure variation of the theme:
    //*a(); *a()(); a()->(); a->(); a()();
    //just calling "a;" does not do anything except throwing a warning
    a();

    //the following code works fine: when called it print bar, car respectivly as expected
    // bar b;
    // car c;
    // b();
    // c();

    delete b;
    delete a;
    return 0;
}

My current understanding is that "foo *a" stores the address of of the function object "bar" in a (as shown by the cout statement). Hence dereferencing it "*a" should provide access to the function to which "a" is pointing to and "*a()" should call it.
But it does not. Can anyone tell me why?

A: Since you have a pointer for a, you must dereference it to call the () operator:
(*a)(); // Best use parentheseis around the dereferenced instance

A: When you dereference a you threw away the polymorphism, the foo::operator() should be called instead of bar::operator(), thus a pure virtual function call exception was thrown.


text:
Q: Liferay SQL data types list Is there any documentation available to get the list of available SQL datatypes used in the service.xml?
What value should I use to make the configuration compatible with the following table structure:
CREATE TABLE SAMPLE_TABLE (
    NAME         varchar(100) NOT NULL,
    DESCRIPTION  varchar(300) DEFAULT NULL,
    CREATE_DATE  timestamp
)

A: It always feels funny to link to the service-builder DTD (here the HTML version - just see the declaration at the top of your service.xml for the actual file), but you can actually learn a lot from it: It contains way more documentation than actual DTD code, so it's human readable for anybody dealing with service builder. In the DTD you'll find the attributes to declare that you want to connect to an existing table instead of creating one through servicebuilder default mechanisms.
There's another file, which AFAIK sadly does not have a DTD: model-hints.xml. However, luckily there's a developer guide chapter on it: This contains quite some extra information, like: max-length of VARCHAR fields etc. . Use this file for more validation or to specify more details for the columns that get autogenerated into your entity tables.


text:
Q: How to find LSTMCell weight and bias names to load values into them? I have been trying to load some altered weights back into the Tensorflow computational graph while training a multilayered LSTM RNN. Using the follwing lines of code:
variables_names =[v.name for v in tf.trainable_variables()]
values = session.run(variables_names)

gives me names and values of the variables used, the names of the weights of the LSTMCells however are in the form
rnn/multi_rnn_cell/cell_0/lstm_cell/weights:0
rnn/multi_rnn_cell/cell_1/lstm_cell/weights:0

and so on, but I cannot use the above names directly in
rnn/multi_rnn_cell/cell_0/lstm_cell/weights.load(values[0], session)

method to load the values back. Does anyone know how to load new weights back into the LSTM cells?

A: The easiest way to turn a variable name into a tf.Variable object is to filter tf.trainable_variables(), matching on the name:
cell_0_weights = [v for v in tf.trainable_variables()
                  if v.name == 'rnn/multi_rnn_cell/cell_0/lstm_cell/weights:0'][0]

(This is not particularly efficient, but the set of variables is usually small enough that the inefficiency is unimportant.)
Once you have a tf.Variable object, you can use its load() method to assign a new weight:
cell_0_weights.load(values[0], sess)


text:
Q: JS Check Date is Within 6 Months of Today I am using Bootstrap Datepicker, and based on the date selection I need to display a message to the user.
I have never used the Date Constructor before so it's very new to me.
What I need to do is the following;

*

*allow user to select a date

*display a message / alert based of the logic below

If their selected date is within the last 6 months of today, they quality for discount.
If their selected date doesn't fall within the last 6 months of today, they don't.
Although it's not working correctly have created a fiddle here.
Any help would be appreciated. Code also below;
HTML
<input type="text" class="form-control" id="datepicker" placeholder="Year Graduated" value="" data-date-format="dd/mm/yyyy">

JS
  function compareDate() {
    // get date from datepicker
    var dateEntered = $("#datepicker").datepicker("getDate");
    dateEntered = new Date(dateEntered).getTime();
    //alert("date entered: " + dateEntered);
    // set todays date
    var now = new Date();
    // set date six months before today
    var sixMonthBeforeNow = new Date(now).setTime(now.getTime() - 3 * 28 * 24 * 60 * 60);
    //alert("six months before: " + sixMonthBeforeNow);
    // if date entered is within six months from today
    if (dateEntered > sixMonthBeforeNow) {
      alert("You qualify for the discount rate.");
      $("#rate").html('discount rate');
    }
    // if date entered is over six months from today
    if (dateEntered < sixMonthBeforeNow) {
      alert("you graduated more than six months ago");
      $("#rate").html('no discount');
    }
  }

  $("#datepicker").datepicker({
    weekStart: 1,
    daysOfWeekHighlighted: "6,0",
    autoclose: true,
    todayHighlight: true
  });

  $("#datepicker").change(function() {
    compareDate();
  });

Note: I'd prefer not to use any other 3rd party JS library / plugin.

A: Just change your sixMonthBeforeNow with the below code, that should work.
var sixMonthBeforeNow = new Date(now).setMonth(now.getMonth() - 6);

A: You need to be careful with date arithmetic because it's not symmetric due to the uneven length of months, so you need rules to deal with it. E.g. what date is exactly 6 months before 31 August?
Before answering, consider:

*

*28 February plus 6 months is 28 August

*1 March plus 6 months is 1 September.

*So what date is 6 months before 29, 30 and 31 August? Is it 28 February or 1 March?

Similar issues arise for any last day of a month where the month 6 months previous doesn't have 31 days. Should the limit be the 30th of the month or the 1st of the following month? When you've answered that question, then you can devise an algorithm to deliver the right answer and then the code to implement it.
If you want such cases to set the date to the end of the month 6 months before, then you can check the month resulting from subtracting 6 months and if it's not 6, set it to the last day of the previous month, e.g.

function sixMonthsPrior(date) {
  // Copy date so don't affect original
  var d = new Date(date);
  // Get the current month number
  var m = d.getMonth();
  // Subtract 6 months
  d.setMonth(d.getMonth() - 6);
  // If the new month number isn't m - 6, set to last day of previous month
  // Allow for cases where m < 6
  var diff = (m + 12 - d.getMonth()) % 12;
  if (diff < 6) d.setDate(0)

  return d;
}

// Helper to format the date
function formatDate(d) {
  return d.toLocaleString(undefined, {day:'2-digit', month:'short', year:'numeric'});
}

// Tests
[ new Date(2018, 7,31), // 31 Aug 2018
  new Date(2018, 8, 1), //  1 Sep 2018
  new Date(2018,11,31), // 31 Dec 2018
  new Date(2019, 2,31)  // 31 Mar 2019
].forEach( d => console.log(formatDate(d) + ' => ' + formatDate(sixMonthsPrior(d))));

If that is't the logic you wish to apply, you need to say what is.
PS. You can also implement the above logic by just comparing the start and end dates (day number). If they're different, it must have rolled over a month so set to 0.


text:
Q: Simple Font resizer with JavaScript I have this simple font resize build with JavaScript. It resizes app p tags on page but I need to add other tags, like li. How can I do that. Any help much appreciated.
var min=8;
var max=18;
function increaseFontSize() {
   var p = document.getElementsByTagName('p');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=max) {
         s += 1;
      }
      p[i].style.fontSize = s+"px"
   }
}
function decreaseFontSize() {
   var p = document.getElementsByTagName('p');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=min) {
         s -= 1;
      }
      p[i].style.fontSize = s+"px"
   }
}

Many Thanks for your help in advance.
Dom

A: Use querySelectorAll to use CSS selectors, e.g.:
var nodes = document.querySelectorAll('p, li');

A: If your pattern is simple (eg "p li") and don't want to use javascript libraries, you can use document.createTreeWalker


text:
Q: How to extract part of string using regex I am trying to extract a part of a string as date-timestamp.
Example string:
Upgrade starting on Mon Aug 9 06:46:00 UTC 2021 with ...

Extracted values should be:
Mon Aug 9 06:46:00 UTC 2021

I tried applying the following regex to extract the timestamp:
(\d{2}:\d{2}:\d{2})

How can I extract the day month and year as well.

A: Use regex to extract part of string from raw string, the following is the whole code
package main

import (
    "fmt"
    "regexp"
)

func main() {

    // extract part of string using regex
    str := "Upgrade starting on Mon Aug 9 06:46:00 UTC 2021 with ..."

    // extract string "Mon Aug 9 06:46:00 UTC 2021" using regex
    re := regexp.MustCompile(`(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2} \d{2}:\d{2}:\d{2} (\S{3}) \d{4}`)
    t := re.FindString(str)
    fmt.Println(t)

}


text:
Q: How to set a max/limit on how much a movieclip can be moved by x and y? I'm making a Create-a-Character.One of the features is being able to adjust a facial feature's placement.E.g. can move the nose up or down
(Through arrow buttons, example: 1 click on up button, move nose up by a little bit.)
But obviously I don't want the eyes or nose or lips floating outside the face or a nose ending up on a forehead that would be strange lol.
So how do I code so that the user can only move a movieclip a set amount of times in the chosen direction?

A: If you use just arrow buttons to move objects, it is very easy. Once a button is clicked, check object's position and move it if needed. Basic example:
// if arrow up clicked
if (nose.y > 100)
{nose.y -= 2}

// if down arrow clicked
if (nose.y < 140)
{nose.y += 2}

It's same for x axis and obviously, numbers 100 and 140 can be anything you want. It means, move objects just between these points.

A: User 987 answer is correct, however if your button moves the object at a faster pace say +-5, setting +-2 to the offset might not put it back in the boundary. It will correct itself by +-2 every frame there after, not accounting for if the user continues to hold down the button to try and exceed the boundary further. The nose will continue to glide further away.
The better way to implement this is to immediately set the nose back to the edge of the boundary.
if (nose.y > 140) {
  nose.y = 140;
}


text:
Q: Recommendations to remove SSL certificate and generate one with Letsencrypt NGINX on ubuntu 16 I would like to learn some approach for doing the following:
I must remove ComodoSSL certificate from some nginx running on ubuntu 18. I want to eliminate as much traces as possible from Comodo. After the removal process Letsencrypt will be used to generate a free certificate. Someone has a similar question but considering a post-scenario when the certificate is already installed and there are 2 certificates. Reference to other question.
I plan this:

*

*I dont know the server much so i ran dpkg -l | less to find some references to comodo pacakages and i couldnt find anything

*edit the nginx config file in /sites-available to remove references to the old certificate

*install letscencryp utility certbot

*generate certificate for domain and FQDN example.io and www.example.io letsencrypt question on doing this certificate generation but for apache

*Generate certificate with letsencrypt certbot

*modify the NGINX configuration file to point to the letsencrypt certificate paths

*test with wget utility

wget www.recover.example.com

wget recover.example.com

wget https://www.recover.example.com/

wget https://recover.example.com

A: The only artifacts relating to Comodo will be the SSL certificate and key listed in your nginx.conf files (ssl_certificate_key and ssl_certificate and parameters).
Once you enroll for a certificate via Let's Encrypt (check out https://github.com/Neilpang/acme.sh) you can update your Nginx config to point at those files and then delete the files that had the Comodo Related certificate and keys.
Schedule the Let's Encrypt (acme.sh, etc) client to run periodically and then you should be good to go.


text:
Q: Intuitive Sortable and Draggable UI indicators I've got elements which i can sort and elements which I can drag and drop into container and back. How should I show to users that some elements can be sorted and some of them are draggable (so I also need to show drop area, which I can just highlight while dragging)?
In jQuery Sortable UI demo I see double-arror indicator, on some sites there are two column dotted dash.
Share your experience, please

*

*Some draggable examples

*Some sortable examples

A: For marking up drop area's I always use the start option of the draggable for adding a class, for deleting the class I use the stop option. Something like this:
$(".draggable").draggable({
    start: function() {
        $('.droppable').addClass('droppableArea');
    },
    stop: function() {
        $('.droppable').removeClass('droppableArea');
    },
});

When dragging a file, a hover class is always nice on the droppable:
$('.droppable').droppable({
    over: function() {
        $(this).addClass('droppableHover');
    },
    out: function() {
        $(this).removeClass('droppableHover');
    }
});

And your css:
.droppableArea {
    border: 1px solid black;
}
.droppableHover {
    border: 1px solid red;
}

You can check it out in action here

A: The problem, at this stage at least, is that dynamic-reordering of lists, etc. is a relatively new concept for most people... there doesn't seem to be any real convention surrounding the issue, as there is for more established interactions like buttons, checkboxes, etc.
I would tend to suggest that anything that represents that the item might be 'grab-able' or 'sortable' would be an excellent idea.  Arrows work, as do the ridged handles on iOS (three horizontal, inset bars) - but neither is inherently obvious.  As always, real-world mapping is the ideal here... but as practically everything in the 'real world' is manipulable, it makes the task rather more difficult.  There's nothing that truly maps from the real world to a UI to show 'ability to be dragged'.
Whatever you decide to use, you're probably going to have to provide some advice to your end-user on what the symbols mean (perhaps a tool-tip, or a simple once-off notification)... as it's not always immediately obvious.  Personally, I'd probably go with the JQuery-style arrows to show the list as sortable (but it still doesn't really highlight the possibility of a drag interaction... do I click the arrows to move them, or do I click and drag, or is there some other mechanism?).


text:
Q: Best practices for developing refactor friendly code Being a Java developer in an agile development cycle, I have learnt that it is essential to make sure I design my classes in a manner that I can refactor them easily without much of a pain. I want to know, what are the best practices that you follow in your daily design/development cycle that helps you to perform refactoring easily.
For example, I know that I should hide the implementation details behind an interface. So that event if I am changing the implementation tomorrow, I am not disturbing the client code which consumes this APIs. Similarly I should use "factory design pattern" wherever possible so that the change of implementation classes can be controlled from one factory class rather than find out all the places and change them.
Similarly I would like to know what all best practices that you are following which will help me.

A: You should have a bunch of unit tests that can prove the codebase was not (inadvertantly) affected each time you refactor.

A: This may sound like a bit of circular reasoning but I find it to be true in my experience:
Refactor it a lot.
Many of the answers here (especially a strong test suite) are great advice and help a lot, so let me be clear in saying that I'm all for those pre-emptive measures as well.
At first, it's always easy to change (when it's small).   Then, you generally have to go through a few bouts of tough refactoring before you have a breakthrough and get something that is really supple.

A: Use TDD. Seriously. Writing tests while you write your classes forces you to think about how they will be used by others. You'll tend to write better abstractions when you do this.
Entire books have been written on this subject:

*

*Code Complete

*Working Effectively with Legacy Code

*Clean Code

*Refactoring

*Refactoring to Patterns

*Agile Principles, Patterns and Practices

Each one of these touches on this subject in its own unique way.

A: Don't copy and paste (also known as DRY: Don't Repeat Yourself). When any given functionality is implemented in no more than one place, then it's easier to reimplement that functionality.

A: My answer relates to what constitutes a good result after the refactoring.
Methods should be...

*

*short - they should never be more than a screen full of code.

*do at most one thing:

*

*calculate a value

*test and branch

*log

*guard and throw exception

*have a single exit point - my reasoning..

*

*If you later need to come back and do something to the return value, it all happens in one spot.

*Easy to set a breakpoint and inspect the returned value...

*Amounts to DRY.

A: I would recommend picking up two books if you're going to be doing a lot of java.
I'd recommend Effective Java and Design Patterns: Elements of Reusable Object-Oriented Software.


text:
Q: API request succeds but catch is executed instead of then? I have this weird error in my React app at the moment. I am sending an api request and I want to do something if it succeeds and something else if I get an error back. The api requests succeeds, the post is getting approved, but the catch clause is executed instead of then.
Can you see something in this code that might make that happen?
The request which I am talking about is the Request.post one... the large one that ecompasses a few other requests.
    export const approvePostSubmission = (post, date) => dispatch => {
  const label = `${post.campaign_product_name} on ${moment(date).format('LL')}`;

  if (post.post_type === 3) {
    dispatch(sendGoogleEvent(GOOGLE_EVENT.STORY.APPROVE, label));
  } else {
    dispatch(sendGoogleEvent(GOOGLE_EVENT.POST.APPROVE, label));
  }

  dispatch({
    type: APPROVE_POST_PENDING,
  });

  return Request.post(
    API_ENDPOINT.POST_APPROVE(post.id),
    { publish_at: date },
    false
  )
    .then(response => {
      const { selectedContent } = store.getState().inbox;

      dispatch(getUserWallet());

      dispatch({
        type: APPROVE_POST_SUCCESS,
      });

      const getPostTypeText = post_type => {
        switch (post_type) {
          case 3:
            return 'Story';
          case 4:
            return 'IGTV Post';
          case 5:
            return 'Carousel';
          case 6:
            return 'IG Live';
          default:
            return 'Post';
        }
      };

      const postType = getPostTypeText(selectedContent.post.post_type);

      setTimeout(() => {
        toast.show(
          <p>
            {`Woo! You approved a ${postType}! It will be published on `}
            <RouterLink
              to="/calendar"
              color="#0dd36b"
              onClick={e => toast.hide()}
            >
              {`${moment(date).format('LL')} `}
            </RouterLink>
          </p>,
          {
            type: 'success',
            dismiss: true,
          }
        );
      }, 100);

      // Send slack bot message
      Request.post(`${SLACKBOT.URL}/new-post`, {
        post_status: 1,
        post_type: selectedContent.post.post_type,
        post_id: selectedContent.post.id,
        campaign_name: selectedContent.post.campaign_product_name,
        influencer_id: selectedContent.influencer.id,
        influencer_name: selectedContent.influencer.full_name,
        campaign_id: selectedContent.post.campaign_id,
        post_image: selectedContent.post.image_url,
        slack_channel: SLACKBOT.CHANNELS.NEW_POST,
      })
        .then(data => {})
        .catch(err => console.error(err));

      return response;
    })
    .catch(err => {
      setTimeout(() => {
        dispatch({
          type: APPROVE_POST_FAIL_SHOW_ERR,
          payload: !!err.response
            ? err.response.data.message
            : 'Unable to approve post!',
        });

        !!err.response &&
          toast.show(
            `${err.response.data.message || err.response.data.error} `,
            { type: 'fail' }
          );
        setTimeout(() => {
          dispatch({
            type: APPROVE_POST_FAIL,
          });
        }, 3000);
      }, 500);
    });
};


text:
Q: How to import values from Laravel into react.js How do I import a variable value from PHP Laravel into my React.js frontend.
Is that even possible to begin with.
Thank you from Zambia.
the variable from PHP
{{$category->category_name}}

and the div from react.js

{category_name}

I have no where to begin from, so ye sorry I couldn't provide any work that I have done

A: You want to pass values from html to react through as innerHTML in your html element. In order to accomplish this you have to render each html component separately through ReactDOM.render
Setup your html element with the inner Content, Render the component in ReactDOM.render and pass that data through inside the element. Grab the value in your React block like you would any props.children passed through

/* pass through as props.children */

function App(props){
return
Child: {props.children}

}

const application = document.getElementById('application');
ReactDOM.render(<App>{application.innerHTML}</App>, application );

From HTML


text:
Q: Swift(iOS) inserting UIImage array to subview? Swift(iOS) problem: how can I insert UIImage array to subview? I wanted to make a horizontal scroll view in view controller with very little experience with swift. Here is the code:
override func viewDidLoad() {
    super.viewDidLoad()

    configurePageControl()

    var pictures:[UIImage] = [ ]
    pictures.append(UIImage(named: "SOVERMENT1.jpg")!)
    pictures.append(UIImage(named: "SOVERMENT2.jpg")!)
    pictures.append(UIImage(named: "SOVERMENT3.jpg")!)
    pictures.append(UIImage(named: "SOVERMENT4.jpg")!)

    scrollView.delegate = self
    self.view.addSubview(scrollView)
    for index in 0..<4 {

        frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
        frame.size = self.scrollView.frame.size
        self.scrollView.pagingEnabled = true

        var subView = UIView(frame: frame)
        **subView.backgroundColor = [UIColor colorWithPatternImage : ]**
        self.scrollView.addSubview(subView)
    }

This is first problem. How can I insert pictures into subview.backgroundColor? I searched it for 1~2hours, but I couldn't find any answer.
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * 4, self.scrollView.frame.size.height)
    pageControl.addTarget(self, action: Selector("changePage:"), forControlEvents: UIControlEvents.ValueChanged)

}

func configurePageControl() {

   ** self.pageControl.numberOfPages = pictures.count **
    self.pageControl.currentPage = 0

And here. Why array pictures cannot be counted?

A: Unless these are repeatable pattern images, I think you want to use a UIImageView. I also don't think you need to use a UIPageControl, because you're only using one UIViewController. You can say something like:
    override func viewDidLoad() {
        super.viewDidLoad()

        var pictures:[UIImage] = [ ]
        pictures.append(UIImage(named: "SOVERMENT1.jpg")!)
        pictures.append(UIImage(named: "SOVERMENT2.jpg")!)
        pictures.append(UIImage(named: "SOVERMENT3.jpg")!)
        pictures.append(UIImage(named: "SOVERMENT4.jpg")!)

        self.scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * CGFloat(pictures.count), scrollView.frame.size.height)
        for index in 0..<pictures.count {
            var frame = CGRectZero
            frame.origin.x = scrollView.frame.size.width * CGFloat(index)
            frame.size = scrollView.frame.size
            scrollView.pagingEnabled = true

            var subView = UIImageView(frame: frame)
            subView.image = pictures[index]
            subView.contentMode = .ScaleAspectFit
            self.scrollView.addSubview(subView)
        }

    }

A: You better use UICollectionView for such purposes

A: For setting the backgroundColor call the UIColor initializer:
for picture in pictures {
    subView.backgroundColor = UIColor(patternImage: picture)
}


text:
Q: .NET How to combine FileSystemWatcher with ReadDirectoryChangesW to monitor Folder/File Opening? I am currently using FileSystemWatcher to monitor my local file system changes but i want to monitor Folder/File opening. after a lot of investigations, i found that this can be done using ReadDirectoryChangesW but i can't use this method along with FileSystemWatcher. My question is how to combine ReadDirectoryChangesW  with FileSystemWatcher with a sample code on how to do this.
public class Watcher : FileSystemWatcher
{

}

A: To get events like accessed - you need to add an audit on this directory/files.
Then you can consume audit entries to see who/when accessed file
see more here


text:
Q: What thread runs the code after the `await` keyword? Let me just post a simple example:
    private void MyMethod()
    {
        Task task = MyAsyncMethod();
        task.Wait();
    }

    private async Task MyAsyncMethod()
    {
        //Code before await
        await MyOtherAsyncMethod();
        //Code after await
    }

Let's say I run the above code in a single threaded app -like a console app-. I'm having a difficult time understanding how the code //Code after await would be able to run.

I understand that when I hit the await keyword in MyAsyncMethod() control goes back to MyMethod(), but then I'm locking the thread with task.Wait(). If the thread is locked, how can //Code after await ever run if the thread that is supposed to take it is locked?

Does a new thread get created to run //Code after await? Or does the main thread magically steps out of task.Wait() to run //Code after await?

I'm not sure how this is supposed to work?

A: Code as posted will "Deadlock" in Winform App if called from main thread because you're blocking the main thread with the Wait().

But in console app this works. but how?

Answer is hidden in the SynchronizationContext.Current. await captures the "SynchronizationContext" and when the task is completed it will continue in the same "SynchronizationContext".
In winform app SynchronizationContext.Current will be set to WindowsFormsSynchronizationContext which will post to the call to "Message loop", but who is going to process that? out main thread is waiting in Wait().
In console app SynchronizationContext.Current will not be set by default so it will be null when no "SynchronizationContext" available for await to capture so it will schedule the continuation to ThreadPool(TaskScheduler.Default which is ThreadpoolTaskScheduler) and so the code after await works(through threadpool thread).
Aforementioned capturing behavior can be controlled using Task.ConfigureAwait(false); which will prevent winform app from deadlocking but code after await no longer runs in UI thread.

A:
Does a new thread get created to run //Code after await?

Maybe. Maybe not. The awaitable pattern implementation for Task runs the continuation (the bit after the await expression) using the synchronization context which was "current" when at the start of the await expression. If you're in the context of a UI thread, for example, that means that you'll end up back on the same UI thread. If you're in a thread-pool thread, you'll end up back on some thread-pool thread, but it could be a different one.
Of course with your code sample, if you're in a UI thread, your call to Wait() will block the UI thread so that the continuation can't run - you need to be careful about that. (Calling Wait() or Result on tasks that you don't know to be completed, and which may require work on the current thread, is a bad idea.)
Note that you can call Task.ConfigureAwait so that you can express the intention of not requiring to continue on the same context. This is usually appropriate for library methods which don't care which thread they run on:
await task.ConfigureAwait(false);

(It affects more than the thread - it's the whole context which is captured or not.)
I think it's a good idea to get familiar with what's going on under the hood with await. There's plenty of documentation online, and if you'll allow me a brief plug, there's also the 3rd edition of C# in Depth, and my Tekpub screencast series on the topic. Or start with MSDN and proceed from there.


text:
Q: How do I use bower in a typical .NET / Visual Studio workflow? I'm unhappy how nuget handles client-side packages, so I want to try bower, as per the process described here. I want the tool to fit into my workflow, not vice versa.
Note that what I'm interested in is bower - I just want client-side package manager, not those grunt/gulp build tools.
What I've done:

*

*Everything in that post. I'm on VS2013 Update 4, I installed those 3 extensions, and the windows version of nodejs, and then bower.

What I want to do, is more or less a .NET/VS-ish worflow:

*

*When I install some package, it pulls the entire repo! I only want the sort of files you'd get in a nuget package, e.g. foo.js, foo.min.js, foo.css, foo.min.css and webfonts.

*I want those files to go to the right places, so scripts to ~/scripts/lib, stylesheets to ~/styles/lib and fonts to ~/fonts. Right now it's just dumping everything in bower_components which is no better than what nuget does for me.

*I'd like to rename those files to the way we do it in the .NET world, so foo-2.0.1.js and foo-2.0.1.min.js, etc.

A: This is how I did it:

*

*Apparently Bower pulls down all the junk, and there's nothing you can do about it! Seems silly to me coming from a nuget background, but that's how it works in this tool.

*I moved the files from the bower_components directory, to the appropriate places, using a javascript-based build tool. I used "Gulp", which has tooling support in VS2013-Update3 onwards.

*I didn't change the filenames. The node stack seems to work better that way.


text:
Q: React Native Axios and ngrok Error on Get returning hyperlink I am working on a simple application composed of React Native for my front end and React Express for my API. I am storing images on AWS S3. Uploading images works, and downloading images kind of works.
Postman Get Call on Image using Image Key
As you can see in the link above, when I test the download, it gives me a signed URL which is live for 15 minutes which I can access. The idea is to pass that as my URI to my Image component.
However, when I try to do the same exact thing from my front end using Axios (the API is not deployed, and I am using ngrok to tunnel into it for local easy testing), this is what I get:
Front End Get Call on Image using Image Key
When I attempt to decode the base64 payload string, it is simply restating what the top half of the image says. This issue doesn't occur with many of my other API calls from my front-end through ngrok. I am able to have authorization mechanics, group mechanics, and even OCR functionality via API calls.
Is it because it is returning a hyperlink? Is there a way to return it as simply a string? This is new territory for me. I am using aws-sdk/clients/s3 library and using getSignedUrl, and passing the return of that back via res.status(200).send(signedUrl).
Thank you for reading.


text:
Q: Post Angular form data to Node.js with Sendgrid/Nodemailer I have followed this example to post data from my Angular app to Node.js to post a webform to Sendgrid. This works fine after some changes and thanks a lot for the quickstart. Posting my form data to Sendgrid is working now!
For this project i'm using Angular Fullstack to be able to use Node functionalities within my Angular app.
However, this example has just input fields and a textarea. I want to be able to add a file (PDF, Docx, e.g) so that people can send an attachment to the recipient via Sendgrid. I have searched for a solution but couldn't find a working example. Maybe because it is not possible what i want to achieve.
MY VIEW (CLIENT):

Solliciteer direct

              <form id="loginform" class="form-horizontal" role="form" name="contactform">

                    <input type="email" name="to" ng-model="email.to" ng-required="true" id="email-to" class="form-control" name="username" value="" placeholder="The emailadres from the employer">

                      <input type="email" name="from" ng-model="email.from" ng-required="true" id="email-from" class="form-control" name="email-from" placeholder="Your e-mail address">

                      <input type="text" name="subject" ng-model="email.subject" ng-required="true" id="email-subject" class="form-control" name="subject" placeholder="Your subject please">

                      <input type="file" name="file" ng-model="email.file" ng-required="true" id="email-file" class="form-control" name="file">

                    <textarea ng-model="email.text" name="text" placeholder="Enter Text Here.." class="form-control" rows="5" id="comment"></textarea>

                            <button id="emailSubmitBn" class="btn btn-success" type="submit" ng-click="submitEmail()">Submit</button>

              </form>

MY CONTROLLER (CLIENT):
angular.module('angularMyApp')
.controller('ContactFormCtrl', function ($scope, $http) {
  $scope.submitEmail = function() {

    console.log("TEST");
    //Request
    $http.post('/api/email', $scope.email)
    .success(function(data, status) {
        console.log("Sent ok");
    })
    .error(function(data, status) {
        console.log("Error");
    })
  };
});

MY APP.JS (SERVER):
'use strict';

// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var express = require('express');
var config = require('./config/environment');
var http = require('http');
var bodyParser = require('body-parser');

var options = {
    auth: {
        api_key: process.env.SENDGRID_APIKEY;
    }
}

var nodemailer = require('nodemailer');
var sgTransport = require('nodemailer-sendgrid-transport');

// Setup server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);

var mailer = nodemailer.createTransport(sgTransport(options));

app.post('/api/email', function(req, res) {
var mailOptions = {
    to: ['test@test.nl', req.body.to],
    from: req.body.from,
    subject: req.body.subject,
    text: req.body.text
};

mailer.sendMail(mailOptions, function(err, res) {
    if (err) {
        console.log(err)
    }
    console.log(res);
  });
});

// Start server
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});

// Expose app
exports = module.exports = app;

Well there are two main issues:

*

*Clientside: How can i post the attachment from Angular to Node within this form? Do i have to upload the file first or can i send it to Node with $http.post? Or do i have to use ng-file-upload?

*Serverside: How can i send an attachment to Sendgrid/Nodemailer. Sending a hardcoded file from my app.js on the server to Sendgrid doesn't work. The mail is send succesfully to Sendgrid but it doesn't contain an attachment.

Many thanks in advance!

A: 1. Uploading a file with a form in angular
The first trouble you have is that ng-model doesn't work with <input type="file" />.  So, you will need to create a custom directive to populate the model with the file.
.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

Then use the directive on your file input element like this:
<input type="file" file-model="email.attachment" ng-required="true" id="email-attachment" name="attachment" class="form-control" />

Note that I changed email.file to email.attachment to avoid confusion in the rest of the code.
Next, you need to include the file in your AJAX request.  You will need to use FormData for that.  Populate it from the scope using FormData.append():
$scope.submitEmail = function() {
    var formData = new FormData();
    Object.keys($scope.email).forEach(function(key) {
        formData.append(key, $scope.email[key]);
    });
    $http.post('/api/email', formData, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).then(function(data, status) {
        console.log("Sent ok");
    }, function(data, status) {
        console.log("Error");
    });
};

Notice I also passed a config object to $http.post().  This is to prevent angular from parsing the FormData object and setting the content type.
I relied heavily on this blog post for this part of the answer.
2. Sending an attachment with Nodemailer
To access the file in express, use multer.
Install:
$ npm install --save multer

Usage:
var multer = require('multer');
var upload = multer();

app.post('/api/email', upload.single('attachment'), function(req, res) {
    // req.file contains the 'attachment' file
    ...
});

From Nodemailer's Readme section on email fields it says to use an attachments property that is an array of attachment objects.
app.post('/api/email', upload.single('attachment'), function(req, res) {
    var mailOptions = {
        to: ['test@test.nl', req.body.to],
        from: req.body.from,
        subject: req.body.subject,
        text: req.body.text,
        attachments: [
            {
                filename: req.file.originalname,
                content: req.file.buffer
            }
        ]
    };

    mailer.sendMail(mailOptions, function(err, res) {
        if (err) {
            console.log(err)
        }
        console.log(res);
    });
});

The above example keeps the attachment in memory, which could be bad if large files are uploaded frequently.  You can write files to disk instead:
var upload = multer({ dest: '/uploads' });

Then, instead of setting the file's buffer as the attachment's content, you would set the attachment's path to the file's path:
attachments: [
    {
        filename: req.file.originalname,
        path: req.file.path
    }
]

A: I finally got the job done thanks to gilly3. I had to do one minor change in his code. In the controller I changed:
formData.set(key, $scope.email[key]);

to the following code:
formData.append(key, $scope.email[key]);


text: Q: How to fix problems when Laravel pages are not loading properly after uploaded to the host I have uploaded my first Laravel project folder to the host and when I load the page it appears broken but it works properly in localhost. Do not know how to fix, some advice would be great. Thanks in advance.


text:
Q: How do I call a Flex SWF from a remote domain using Flash (AS3)? I have a Flex swf hosted at http://www.a.com/a.swf.
I have a flash code on another doamin that tries loading the SWF:
_loader = new Loader();
var req:URLRequest = new URLRequest("http://services.nuconomy.com/n.swf");
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoaderFinish);
_loader.load(req);

On the onLoaderFinish event I try to load classes from the remote SWF and create them:
_loader.contentLoaderInfo.applicationDomain.getDefinition("someClassName") as Class

When this code runs I get the following exception
SecurityError: Error #2119: Security sandbox violation: caller http://localhost.service:1234/flashTest/Main.swf cannot access LoaderInfo.applicationDomain owned by http://www.b.com/b.swf.
    at flash.display::LoaderInfo/get applicationDomain()
    at NuconomyLoader/onLoaderFinish()

Is there any way to get this code working?

A: This is all described in The Adobe Flex 3 Programming ActionScript 3 PDF on page 550 (Chapter 27: Flash Player Security / Cross-scripting):

If two SWF files written with ActionScript 3.0 are served from different domains—for example, http://siteA.com/swfA.swf and http://siteB.com/swfB.swf—then, by default, Flash Player does not allow swfA.swf to script swfB.swf, nor swfB.swf to script swfA.swf. A SWF file gives permission to SWF files from other domains by calling Security.allowDomain(). By calling Security.allowDomain("siteA.com"), swfB.swf gives SWF files from siteA.com permission to script it.

It goes on in some more detail, with diagrams and all.

A: You'll need a crossdomain.xml policy file on the server that has the file you load, it should look a something like this:
<?xml version="1.0"?>
<!-- http://www.foo.com/crossdomain.xml -->
<cross-domain-policy>
  <allow-access-from domain="www.friendOfFoo.com" />
  <allow-access-from domain="*.foo.com" />
  <allow-access-from domain="105.216.0.40" />
</cross-domain-policy>

Put it as crossdomain.xml in the root of the domain you're loading from.
Also you need to set the loader to read this file as such:
var loaderContext:LoaderContext = new LoaderContext();
loaderContext.checkPolicyFile = true;

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );
loader.load( new URLRequest( "http://my.domain.com/image.png" ), loaderContext );

code sample yoinked from http://blog.log2e.com/2008/08/15/when-a-cross-domain-policy-file-is-not-enough/

A: Mayhaps System.Security.allowDomain is what you need?


text:
Q: Create objects of custom class from YAML in Python I have Class definition:
Class definition
class Task(object):
    def __init__(self, name, *depends):
        self.__name    = name
        self.__depends = set(depends)

    @property
    def name(self):
        return self.__name

    @property
    def depends(self):
        return self.__depends

The rest of the code is using sample definition like this:
a = Task("a", "b")
b = Task("b")

nodes = (a, b)

I am trying to create this objects dynamically by parsing YAML in separate function which returns dictionary data and then I create all the objects:
Yaml File
a:
  foo:
   - "bar"
  graph_dep:
  - "b"
b:
  foo:
   - "bar"

I believe I was able to achieve creation of a and b objects of a Task class via function
def format_input(data):
    services = data.keys()
    holder = {Task(name=name) for name in services}
    return holder

q1: How do I combine them to get nodes object and have same result as using sample definitions?
q2: How do I get values from graph_dep and add them in holder = {Task(name=name) for name in services} string?
Sorry newbie question in Python :)

A: Generally, if you don't need the YAML's original structure, it is unnecessary to load it into native Python types. Instead, you should only load them into a YAML node graph and then load the native structure you want to have from that:
import yaml

input = """
a:
  foo:
   - "bar"
  graph_dep:
  - "b"
b:
  foo:
   - "bar"
"""

class Task(object):
  def __init__(self, name, *depends):
    self.__name    = name
    self.__depends = set(depends)

  @property
  def name(self):
    return self.__name

  @property
  def depends(self):
    return self.__depends

  def __str__(self):
    return "Task({}, {})".format(self.__name, self.__depends)

def load_dependency_list(loader, node):
  for item in node.value:
    if item[0].value == "graph_dep":
      return loader.construct_sequence(item[1])
  return []

def load_tasks(loader, node):
  ret = ()
  for item in node.value:
    name = loader.construct_scalar(item[0])
    deplist = load_dependency_list(loader, item[1])
    ret += (Task(name, *deplist),)
  return ret

loader = yaml.SafeLoader(input)
nodes = load_tasks(loader, loader.get_single_node())
for node in nodes:
  print(node)

What this code does is:

*

*getting the node graph of the single document in the YAML file via get_single_node()

*on the returned root node, execute your loading code

load_tasks and load_dependency_list handle the levels in the YAML. PyYAML does provide facilities to register these functions as constructors, however that only makes sense if you have tags in your YAML input (like e.g. --- !nodes as first line). Without tags, PyYAML cannot automatically map constructors so you need to implement the construction process yourself.
In this case, load_dependency_list constructs the list contained in graph_dep or returns the empty list, ignoring other things in the YAML node. load_tasks iterates over the top level items, constructing Task object from each of them, and concatenates them into a tuple.
I added a __str__ method to Task for output. The output is
Task(a, {'b'})
Task(b, set())

This code has no safeguards whatsoever and I advise to check for proper node types whereever you access a YAML node so that the user gets a good error message if the structure is wrong.


text:
Q: Maximum entropy of dice How can be proven that the entropy of a die with equal probability for all its faces is at its maximum?
It's clear that the entropy will be smaller if there are more chances for a particular face, but how can be this proven?

A: It is a direct consequence of the concavity of the function $-x \log(x)$ for arguments between $0$ and $1$.
The entropy of a die with $n$ sides and probabilities $p_1, p_2, \ldots, p_n$ is defined to be the sum of the $-p_i \log(p_i)$, which is a continuous function of the $p_i$ for all possible probability assignments (including possibly setting some of them to zero).  Taking second derivatives gives a diagonal hessian with values $-1/p_i$, showing the function is everywhere concave. This immediately implies it has a unique critical point where none of the $p_i$ is zero and that it corresponds to a global maximum.  But the entropy is a symmetric function of the $p_i$, whence it must have a critical point where all the $p_i$ are equal, QED.

Edit
There is a proof which is at once elementary and pretty.  It uses two simple, well-known ideas:

*

*A function is optimized simultaneously with any monotonic re-expression of its values.  In particular, the entropy $H = -\sum p_i \log(p_i)$ is maximized when $e^{-H} = \prod (p_i)^{p_i}$ is minimized.

*The (weighted) Geometric Mean-Harmonic Mean Inequality.  Let $x_i$ be arbitrary positive numbers and $p_i$ be positive "weights" summing to $1$.  The weighted geometric mean (GM) of the $x_i$ is $\prod x_i^{p_i}$. Similarly, the weighted harmonic mean (HM) of the $x_i$ is the reciprocal of $\sum p_i(1/x_i)$.  The GM-HM Inequality asserts that $GM \ge HM$ and that equality holds if and only if all the $x_i$ are equal to each other.  There are many elementary proofs of this.  (A good account of the weighted version of the GM-HM Inequality is difficult to find on the Web, although it is well covered in various texts.  See the top of page 5 in Bjorn Poonen's notes on inequalities, for instance.)
Looking at #1, we recognize $e^{-H}$ as the GM of the $x_i$ with weights $p_i$ where $x_i=p_i$.  From the GM-HM Inequality, this value is never less than the HM, which is the reciprocal of $\sum_i p_i \left(1/x_i\right)$ = $\sum_i p_i/p_i$ = $\sum_i 1 = n$.  Also, the GM and HM are equal to each other (and therefore equal to $1/n$) if and only if all the $p_i$ are equal.  It is immediate that $H$ is maximized when the $p_i$ are equal and will have the maximum value $\log(n)$.
This argument covers all but the cases where some of the $p_i$ may be zero.  But in such cases, where there are $n' \lt n$ nonzero $p_i$, the foregoing shows that $H$ cannot exceed $n'$, whence it is not possible to maximize the entropy by setting any of the probabilities to zero.


text:
Q: Best Practices: sharing files between projects in Eclipse I'm using Eclipse (Helios 3.6.2) and Android SDK.
Is there any way to accomplish this without using symlinks?
Template Project: this is the "Main" Project. All other projects will derive from this.
- src
  - A.java
  - B.java
- layout
  - j.xml
  - l.xml
- drawable
  - x.png
  - y.png

Customer 1 Project:
- src
  - A.java (from template)
  - B.java (not from template. custom file used only in this project)
- layout
  - j.xml  (from template)
  - l.xml  (not from template. custom file used only in this project)
- drawable
  - x.png  (from template)
  - y.png  (not from template. custom file used only in this project)

Customer 2 Project:
- src
  - A.java (from template)
  - B.java (from template)
- layout
  - j.xml  (from template)
  - l.xml  (from template)
- drawable
  - x.png  (not from template. custom file used only in this project)
  - y.png  (not from template. custom file used only in this project)

Customer "N" Project:
  and so on with many combinations of using/not using from template...
  (This is for illustration only. My real projects have hundreds of files of course)

I'm kinda rookie in Eclipse. In VisualStudio I can do this by adding files by reference. I couldn't find something similar to this in Eclipse.

A: You can make a project reference, but I don´t think this is exactly what you are looking for. So here is a brief explanation:
You got to have Customer 1 Project and Template Project in your current workspace. Then right-click on Customer 1 Project in the Package Explorer and select Build Path -> Configure Build Path... Here go to Projects tab and select Add.... Here select your Template project.
This solution might lead to a problem if B.java from Customer 1 Project and Template Project is in the same package (which it probably is). So you have to choose another name for that class.


text:
Q: Directing requests to instance on Google Cloud Is it possible to group certain requests togeather based on their url ensuring that similar requests go to the same instance?
E.g.
There are multiple instances for my app engine
myurl.com?foo=abc // Multiple people putting in this url will all go to the same instance
myurl.com // I don't care which one this goes

A: I don't think you can control which instance handles a url pattern.
If you want to send certain urls to a certain service, what you want is a dispatch.yaml, which does exactly that.  You can use regex to tailor how you want. With some strategy, you could match urls with (groups of) instances, though they would be in separate services.  If your site doesn't get a lot of traffic, you could essentially have one instance per service, and accomplish what you want.
dispatch:
# don't forget: gcloud app deploy dispatch.yaml   after changes !!!

- url: "*/some/high/memory/urls/*"
  service: my_high_memory_service

- url: "*/some/fast/cpu/url"
  service: my_fast_cpu_service

- url: "*/.*"
  service: default

More at:  https://cloud.google.com/appengine/docs/standard/python/reference/dispatch-yaml


text:
Q: Unit elements in Hurwitz quaternions Hurwitz quaternions are defined as:
$$H_u = \left\{a+bi+cj+dk\mid (a,b,c,d) \in\mathbb{Z}\mbox{ or }(a,b,c,d) \in\mathbb{Z}+\frac{1}{2}\right\}$$
(that is, all integer or half integer quaternions).
I'm trying to show that if $a$ is a unit, then $||a||=1$ (the usual quaternion norm), but I can only sort of show that using very tedious calculations.
Is there a short(er) and more elegant way to see this, preferably purely algebraic?

A: Suppose $x$ is a unit. Then $x^{-1}$ satisfies $\lVert x \rVert \lVert x^{-1} \rVert = 1$. So $\lVert x^{-1} \rVert = \lVert x \rVert ^{-1}$, and in particular one of $\lVert x \rVert$, $\lVert x^{-1} \rVert$ must be less than or equal to 1. But it's not hard to see that in fact the norm is an integer and not zero, so it must be 1.


text:
Q: How to prevent sssd package from modifying nsswitch.conf We are running sssd on a number of Xenial servers to authenticate against Active Directory.
Upon installation, the sssd package added sss to most lines in /etc/nsswitch.conf as documented in https://help.ubuntu.com/lts/serverguide/sssd-ad.html#sssd-ad-nsswitch . Regrettably, this includes the sudoers line, which results in an error message
problem with defaults entries

being mailed to the root account for every single use of sudo, which in our case includes an important number of cron jobs resulting in a lot of mails.
This is easily fixed by manually removing sss from that line again. However, each update of the sssd package re-adds that unwanted entry, triggering another flood of mails before we manually remove it again.
How can we avoid that?

A: The solution on the bug report is to disable sudo support. From the link:

As a workaround that doesn't require changing /etc/nsswitch.conf, you can also explicitely disable sudo support for your sssd domain :

[sssd]
services = nss, pam, sudo

[mydomain/LDAP]
sudo_provider = none

This is easily fixed by manually removing sss from that line again. However, each update of the sssd package re-adds that unwanted entry, triggering another flood of mails before we manually remove it again.

An update should not change a configuration file. Configuration files contain specific directives for your system and not for all systems for all users. I would consider that a bug.


text:
Q: How can i get simple yyyy-MM-dd out of this date? I have String with date format dd.MM.yyyy, and I want to upload it to my MS SQL server, but the required format is yyyy-MM-dd. I tried this but it doesn't work like I want to.
    String expDate = mDatePickerBtn.getText().toString();
    Date date = null;

    SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
    try {
        date = format.parse(expDate);
        expDate = date.getYear() + "-" + date.getMonth() + "-" + date.getDay();
    } catch (ParseException e) {
        e.printStackTrace();
    }

For example if I pass 31.12.2032 to the expDate, the date variable will cointain "Fri Dec 31 00:00:00: GMT+01:00 2032", and the expDate will contain "132-11-5" and I don't even know why.
I would use DateTimeFormatter but my minimal API level is 24.
My question is: where did I make mistake or how else can I get correct format out of this?

A: Go compile your app with Android Gradle Plugin 4.0.0+ and use java.time then like this:
public static void main(String[] args) {
    // get / provide the String to be parsed
    String expDate = "31.12.2032";
    // provide a pattern that parses such a date
    String pattern = "dd.MM.uuuu";
    // create a DateTimeFormatter with this pattern
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
    // parse the String with the DateTimeFormatter
    LocalDate expLocalDate = LocalDate.parse(expDate, dtf);
    // print the default format of a LocalDate
    System.out.println(expLocalDate);
    // print the LocalDate using the pattern created for parsing
    System.out.println(expLocalDate.format(dtf));
    // create a totally different DateTimeFormatter inline and format the date differently
    System.out.println(expLocalDate.format(DateTimeFormatter.ofPattern("EEE, dd 'of' MMMM uuuu",
                                                                        Locale.ENGLISH)));
}

The output would be this:
2032-12-31
31.12.2032
Fri, 31 of December 2032

A: Try this way
  String expDate = mDatePickerBtn.getText().toString();
    Date date = null;

    SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
    try {
        date = format.parse(expDate);

        SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
        format1.format(date);

        expDate =  format1.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }


text:
Q: How can I have @if inside the value of a CSS property? Is there a way to use Sass' @if statement inside the value part of a property? I.e. make the following code work:
@mixin color-transition($color:true, $background:true, $border:true, $duration: 0.2s) {
    transition:
        @if ($color) {
            color $duration linear,
        }
        @if ($background) {
            background-color $duration linear,
        }
        @if ($border) {
            border-color $duration linear,
        }
    ;
}

I can't move transition: inside of the if clause because in that case the last of them would overwirte the former …

A: @mixin color-transition($color:true, $background:true, $border:true, $duration: 0.2s) {
    $transition : '';
    @if ($color) {
        $transition : 'color #{$duration} linear,'
    }
    @if ($background) {
        $transition : '#{$transition} background-color #{$duration} linear,'
    }
    @if ($border) {
        $transition : '#{$transition} border-color #{$duration} linear,'
    }
    @if (str-length($transition) > 0) {
        transition: unquote(str-slice($transition, 1, -2));
    }
}

Then you can @include color-transition() in any CSS rule.  Tested.
Edit
Now the property isn't showed if there is no transition, and bugs fixed.

A: You could simply concatenate the answer and print it afterwards...
@mixin color-transition($color:true, $background:true, $border:true, $duration: 0.2s) {
    $transition: '';
    @if ($color) {
        $transition: $transition + 'color #{$duration} linear';
    }
    @if ($background) {
        @if ($transition != ''){ $transition: $transition + ','; }
        $transition:  $transition + 'background-color #{$duration} linear';
    }
    @if ($border) {
        @if ($transition != ''){ $transition: $transition + ','; }
        $transition:  $transition + 'border-color #{$duration} linear ';
    }
    transition: unquote($transition);
}

But of course, you could just simply do it like this:
@mixin color-transition($color:0s, $background:0s, $border:0s){
    transition: color $color linear, background $background linear, border $border linear;
}

Which allows you to call them all in one go:
@include color-transition(1s,1s,2s);

With an output like this:
transition: color 1s linear, background 1s linear, border 2s linear;

Since the default is 0s, technically you have no transition set for those values, although it might overwrite preset values somewhere else, so I see why it might not be ideal, just an idea.

A: You can't use a control directive in the middle of a statement like that.  You have to append a string or list variable inside of your @if statements and then write out the finished property at the very end.
Your specific use case would be best solved by passing in a list of the properties you want to modify:
@mixin color-transition($duration: 0.2s, $properties...) {
    $collector: ();

    // optional
    @if length($properties) == 0 {
        $properties: color, background-color, border-color;
    }

    @each $p in $properties {
        $collector: append($collector, $p $duration linear, comma);
    }

    transition: $collector;
}

Usage:
.foo {
  @include color-transition();
}

.bar {
  @include color-transition(0.2s, color);
}

.buzz {
  @include color-transition(0.2s, background-color, border-color);
}

Output:
.foo {
  transition: color 0.2s linear, background-color 0.2s linear, border-color 0.2s linear;
}

.bar {
  transition: color 0.2s linear;
}

.buzz {
  transition: background-color 0.2s linear, border-color 0.2s linear;
}

Variation to allow for optional duration:
@mixin color-transition($properties...) {
    // optional
    @if length($properties) == 0 {
        $properties: color, background-color, border-color;
    }

    $duration: 0.2s; // default value

    $collector: ();
    @each $p in $properties {
        @if type-of($p) == number {
            $duration: $p;
        } @else {
            $collector: append($collector, $p $duration linear, comma);
        }
    }

    transition: $collector;
}

.foo {
  @include color-transition(color);
}

As a quirky side-effect, you can specify different durations of each property:
.bar {
  @include color-transition(color, 0.3, background);
}


text:
Q: How can I record the "resolution" of non-conflict merges? I know that I can use rerere to record the resolution of merges with conflicts.
But that doesn't help me in my current situation:
I had an experimental branch which I merged into my main branch using --strategy ours, discarding any changes I made there, but keeping all the history for future reference. The changes in the experimental branch were unrelated to any changes in the main branch, so there were no conflicts and thus rerere didn't record anything.
Now I want to rebase this part of my history (using --preserve-merges), but since there was no conflict, Git happily replays the merge using the default strategy, instead of the ours strategy that I originally used. Now all the changes from the obsolete experimental branch end up in my rebased main branch (but I want them to be discarded again).
How can I teach Git to remember the merge strategies I used and re-use them when rebasing?

A: You probably could run git rebase -p -i (interactive) and replace picking merges with manual exec git merge -sours ... calls. Note I did not test if it works.

A: You could also use script git-rehi (disclaimer: written by me) which has exactly this feature: it detects ours merges (by comparing tree hashes) and replays them as ours
There are also other tools around: git-reintegrate, git-remerge etc. which you could check if they do it.

A: I believe you're looking to force a recursive merge. You can do this by adding --no-ff, and a merge commit will be made.

--no-ff
Create a merge commit even when the merge resolves as a fast-forward. This is the default behaviour when merging an annotated (and possibly signed) tag.

from git-scm documentation


text:
Q: How to setup a router as a sub local network The question is not phrased very well but bear with me here, I have zero experience in network talk.
At home we have a D-link modem/router but my brother decided it would a good idea to turn on AP isolation meaning devices can't talk to each other, which is not very good for me because I have a linux machine with all my media and bulk storage that I want offload storage and downloading things to so I dug up an old Huawei router that I want setup in the following way:
It (the Huawei box) connects to the main box (D-link) to get internet access and then my linux box and any other devices I might have connect to the Huawei box in a way that they would be able to talk to each other in a sort off subnet thing without ever talking to the D-link router meaning it would be inaccessible from my devices.
The D-link router is a DSL-2750U and it has 4 ports marked LAN and 1 marked WAN, the Huawei is an HG532s and has 4 marked LAN. I have zero control over the D-link router and full control on everything else.
It would much help if someone could guide me through setting this thing up.

A: This tutorial should help you do what you want. A quote from the article:

In this post, I am going to show you how you can add a second wireless router to the network that will be on a different subnet then the first router, but will still connect to the Internet using the main router as a gateway.

I believe that is what you want to do based on your explanation.

A: Turns out I had a TP-link repeater so I put that in the closet with the linux box, connected ethernet between them and setup the repeater with an ssid different from the main router. Now I can go back to doing nothing but watching pokemon :)


text:
Q: SWIFT: iPhone held "upwards" or is laying on a table How do I have to use the accelerometer / gyroscope in Swift in order to find out if...
A) the iPhone is held just in front of the users face, i.e. it is held "upwards" or
B) the iPhone has been put for instance on a table, i.e. the display is facing up.
C) make an if statement for when it is put on a table or up in front of the users face.

A: UIDeviceOrientation will return a value for which way a device is oriented:
   enum UIDeviceOrientation : Int {
        case Unknown
        case Portrait
        case PortraitUpsideDown
        case LandscapeLeft
        case LandscapeRight
        case FaceUp // <- THIS IS THE ONE THAT YOU ARE LOOKING FOR
        case FaceDown
    }

Without seeing your actual code or knowing exactly what you are trying to achieve it is impossible to give you more specific help than that.


text:
Q: How to (properly) enrich the standard library? I would like to define an implicit conversion from Iterator[T] to a class that I have defined: ProactiveIterator[A].
The question isn't really how to do it but how to do it properly, i.e. where to place the method, so that it is as transparent and unobtrusive as possible. Ideally it should be as the implicit conversion from String to StringOps in scala.Predef If the conversion was from a class in the library to some other class, then it could be defined inside that class, but AFAIK that's not possible here.
So far I have considered to add an object containing these conversions, similarly to JavaConversions, but better options may be possible.

A: You don't really have much of a choice. All implicits must be contained within some sort of object, and imported with a wildcard import (you could import them individually, but I doubt you want that).
So you'll have some sort of implicits object:
package foo.bar

object Implicits {
   implicit class ProactiveIterator[A](i: Iterator[A]) {
      ...
   }
}

Then you must explicitly import it wherever you use it:
import foo.bar.Implicits._

In my opinion, this is a good thing. Someone reading the code might not understand where your pimped methods are coming from, so the explicit import is very helpful.

You can similarly place your implicits within a package object. You would have to import them the same way into other namespaces, but they would be available to classes within the same package.
For example, using the following, anything within foo.bar will have this implicit class available:
package foo

package object bar {
   implicit class ProactiveIterator[A](i: Iterator[A]) {
      ...
   }
}

Elsewhere you would import foo.bar._ (which may or may not be as clean, depending on what's in bar).


text:
Q: Conditions for l'Hôpital's rule According to l'Hôpital's rule, given functions $f,g$ which are differentiable around $a\in \mathbb R$, such that --

*

*$\lim_{x\to a} f(x)=\lim_{x\to a}g(x)=0$

*$g'(x)\neq 0$ on some deleted neighborhood of $a$.

*$\lim_{x\to a} {\frac {f'(x)}{g'(x)} }$ exists (widely).

Then  $\ \ \lim_{x\to a} {\frac {f(x)}{g(x)} } = \lim_{x\to a} {\frac {f'(x)}{g'(x)} }$.
Condition 2 is necessary for the proof, but I can't find a counterexample for the theorem without it. Could you give an example of differentiable functions $f,g$ aroud $a$, such that conditions 1,3 hold, but
$\ \ \lim_{x\to a} {\frac {f(x)}{g(x)} } \neq \lim_{x\to a} {\frac {f'(x)}{g'(x)} }$?

A: Condition (2) is present not simply to ensure existence of $\lim f'(x)/g'(x).$
One can construct counterexamples where condition (2) is violated but $f'(x)$ and $g'(x)$ share a common factor -- such that $\lim f'(x)/g'(x)$ exists but $\lim f(x)/g(x)$ fails to exist.
Stolz produced such a counterexample for the case where $f(x), g(x) \to \infty$ as $x \to a = \infty$. Specifically,
$$f(x) = \int_0^x \cos^2(t) \, dt \\ g(x) = f(x)\exp ( \sin x).$$

A: If condition 2 wasn't satisfied, then $\lim_{x\to a}\frac {f'(x)}{g'(x)}$ couldn't be well-defined in an interval $(a-\epsilon, a+\epsilon)$ for $\epsilon \in \mathbb R$ such that $\exists y \in (a-\epsilon, a+\epsilon)$ : $g'(y)=0$.


text:
Q: MongoDB or SQL for text file? I have a 25GB's text file with that structure(headers):
Sample Name Allele1 Allele2 Code metaInfo...

So it just one table with a few millions of records. I need to put it to database coz sometimes I need to search that file looking, for example, specific sample. Then I need to get all row and equals to file. This would be a basic application. What is important? File is constant. It no needed put function coz all samples are finished.
My question is:
Which DB will be better in this case and why? Should I put a file in SQL base or maybe MongoDB would be a better idea. I need to learn one of them and I want to pick the best way. Could someone give advice, coz I didn't find in the internet anything particular.

A: Your question is a bit broad, but assuming your 25GB text file in fact has a regular structure, with each line having the same number (and data type) of columns, then you might want to host this data in a SQL relational database.  The reason for choosing SQL over a NoSQL solution is that the former tool is well suited for working with data having a well defined structure.  In addition, if you ever need to relate your 25GB table to other tables, SQL has a bunch of tools at its disposal to make that fast, such as indices.

A: Both MySQL and MongoDB are equally good for your use-case, as you only want read-only operations on a single collection/table.
For comparison refer to MySQL vs MongoDB 1000 reads
But I will suggest going for MongoDB because of its aggeration pipeline. Though your current use case is very much straight forward, in future you may need to go for complex operations. In that case, MongoDB's aggregation pipeline will come very handy.


text:
Q: pjsip2.5 local sdp port erro config_site.h
#define PJMEDIA_HAS_VIDEO 1

pjsua_config_default(&app_config.cfg);
app_config.cfg.cb.on_incoming_call = &on_incoming_call;
app_config.cfg.cb.on_call_media_state = &on_call_media_state;
app_config.cfg.cb.on_call_state = &on_call_state;
app_config.cfg.cb.on_dtmf_digit = &call_on_dtmf_callback;
app_config.cfg.cb.on_reg_state2=&on_reg_state_callback;
app_config.cfg.cb.on_call_sdp_created=&on_call_sdp_created;

pjsua_call_setting  call_opt

pjsua_call_setting  call_opt;
pjsua_call_setting_default(&call_opt);
call_opt.aud_cnt=1;
call_opt.flag=PJSUA_CALL_UNHOLD;
call_opt.req_keyframe_method=PJSUA_VID_REQ_KEYFRAME_SIP_INFO;
call_opt.vid_cnt=1;

Add local account
pjsua_acc_add_local(transport_id, PJ_TRUE, &aid);

/* Adjust local account config based on pjsua app config */
{
     pjsua_acc_config acc_cfg;
    pjsua_acc_get_config(aid, tmp_pool, &acc_cfg);

    acc_cfg.rtp_cfg = app_config.rtp_cfg;
    app_config_init_video(&acc_cfg);
    acc_cfg.rtp_cfg = app_config.rtp_cfg;
    pjsua_acc_modify(aid, &acc_cfg);
}

The phone calls in for the first time, and the second time will quit.

voip: ../src/pjsip-ua/sip_inv.c:1135: pjsip_inv_verify_request3:
  Assertion (status=pjmedia_sdp_validate(l_sdp))==PJ_SUCCESS' failed.

Why is l_sdp unavailable?

A: config_site.h  #define PJMEDIA_HAS_VIDEO 0
Disable video, it is normal
Is there a problem with the settings?


text:
Q: TYPO3 CMS 9.5.5 most simple extension I have to create a simple TYPO3 extension for version 9.5.5.
i installed TYPO3 CMS 9.5.5  from https://bitnami.com/stack/typo3
in docu for latest (9-dev)
https://docs.typo3.org/typo3cms/CoreApiReference/ExtensionArchitecture/FilesAndLocations/Index.html
they say "usually located in typo3conf/ext for local extensions, or typo3/sysext for system extensions."
i dont have a "typo3conf/ext", no "typo3conf" and "typo3/ext" . and yes there is a "typo3/sysext".
I have not found a guide online that takes this fact into account.
Then i read "... there is a tool which makes it easier to start. It is called Extension builder" ( https://docs.typo3.org/typo3cms/CoreApiReference/ExtensionArchitecture/CreateNewExtension/Index.html )
Ttherefore I have installed this "Extension Builder"
via Zip from https://extensions.typo3.org/extension/extension_builder/

*

*Download ZIP file

*Log into your TYPO3 backend

*Go to Extension Manager module

*Press the upload button on the top bar

*Select the ZIP file and upload it.

and with me it looks very different as in the documentation:

then i read "Docs » Creating a first extension » Create Folder Structure And Configuration Files" (https://docs.typo3.org/typo3cms/ExtbaseFluidBook/4-FirstExtension/2-create-folder-structure-and-configuration-files.html)
There they talk about "unique identifier of our extension". whats this?
"as store_inventory". whats this?
anyway.
and "These are in the folder typo3conf/ext/"
but this folder does not exist in my installation.
I then looked into an installation of another computer days later and there was this folder also not.
anyway.
i created then "typo3conf/ext/store_inventory" (as described there).
then I wondered about the following formulation:
"The name of this folder must be written like the extension key"
So this folder probably had to be different named?
then i found this folder structure at the same page:
https://docs.typo3.org/typo3cms/ExtbaseFluidBook/_images/figure-4-1.png
and I wondered a lot about the amount of folders and files.
I just wanted to make a simple extension that just lists files.
I thought that's a few lines of source code.
is not that any easier?
I do not need all these things like eg. ext_icon.gif. i hope i do not need to create all that files and folder manually.

A: Here are some answers:
The extension key is the name of your folder inside of "typo3conf/ext". I recommend not using an underscore because it might be confusing for you later on as a beginner with TYPO3. Choose a simple and short name. To make sure the name is not available already, please check "extensions.typo3.org" to see if the key (extension name) is already taken. If you want to be 100% sure, you have to register an account there and register the extension key officially. This is all free of course.
The file ext_icon.gif is indeed not necessary, but looks nice when your extension is shown in the list of extensions in the Extension Manager of TYPO3.
You say you want to "list files". I guess you are talking about static files like images etc. that you have in your fileadmin folder already?
So in this case you need a minimum folder structure like this:
store_inventory
    Classes
        Controller
            StoreController.php (Contains PHP function "filesList")
    Configuration
        TypoScript
    Resources
        Private
            Templates
                Files.html (Contains HTML/Fluid-Code for Frontend)
    ext_emconf.php (Contains necessary information about your Ext.)
    ext_localconf.php (Contains registration of Frontend-Plugin/Controller)

A more detailed answer requires more information about your extension's exact requirements. Here are some more links that I think you might need for this project:
ext_emconf.php
https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ExtensionArchitecture/DeclarationFile/Index.html#
ext_localconf.php
https://docs.typo3.org/m/typo3/book-extbasefluid/master/en-us/4-FirstExtension/7-configuring-the-plugin.html
Controllers and Actions:
https://docs.typo3.org/m/typo3/book-extbasefluid/master/en-us/7-Controllers/1-Creating-Controllers-and-Actions.html
Your Controller needs to have a function called for instance "fileAction" and the template file for this "Action" must be named "File.html" in order to work. If you name the action "fileListAction", your template file must be named "FileList.html" and so on...
There are some other small things to think about, but I don't know enough about your exact requirements. If you have any trouble, don't hesitate to ask more questions!
I know, TYPO3 can be frustrating. I do it for decades already ;)
Good luck


text: Q: What is Serialization and why? [Unity3D] So, I've been learning some new stuff with Unity lately and I see people making private variables (movement speed, etc), and serializing them. Is there a point to this as opposed to making variables public?


text:
Q: Using Globalization in .Net I've read some article about globalization in asp.net but some points are not clear for me.
All of this articles are saying that we should add some part in our web.config such as:
<system.web>
<globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" culture="de-DE" uiCulture="de-DE"/>
</system.web>

and in aspx and aspx.cs too like:
<%@ Page UICulture="de-DE" Culture="de-DE" ....%>

and
using System.Threading;
using System.Globalization;
....

protected void Page_Load(object sender, EventArgs e)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("de-DE");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE");
            //Button1.Text = Resources.Resource1.city;
        }

if I want to change the text of lables and etc. I should add Resourse file and some code like this:
Button1.Text = Resources.Resource1.city;

if I delete the configurations from web.config and pageload, above line of code  code  works fine without problem but why should I add this configuration in web.config, aspxpage and page load?

A: you must just add in your configuration file in order to generalize for your application. you can delete from yours pages and your code


text:
Q: Pick content from DB while using update query in Mongodb? I want to update all the database :-
Their are Models like:
{
    "_id" : ObjectId("593800da81dd4240d42f0c98"),
    "leaveType" : ObjectId("5927da8b7094b726fecaa3b5"),
    "units" : 20,
    "employee" : ObjectId("59283f772c3bd82eaca28153"),
    "__v" : 0
}

What I want is, update all the models with inserting new value as unitsAvailed with making same Number as Corresponding units
{
    "_id" : ObjectId("593800da81dd4240d42f0c98"),
    "leaveType" : ObjectId("5927da8b7094b726fecaa3b5"),
    "units" : 20,
    "unitsAvailed" : 20,
    "employee" : ObjectId("59283f772c3bd82eaca28153"),
    "__v" : 0
}

A: you can use this query to update all documents
var cursor = db.collectionName.find({});
cursor.forEach(function(data) {
  data.unitsAvailed = data.units;
  data.save();
});

A: You can run server-side code with db.eval().see below example
 db.eval(function() {
  db.collection.find({tag : "refurb"}).forEach(function(e) {
    e.Price = e.Price * 0.5;
    db.collection.save(e);
  });
});

see Multiply field by value in Mongodb

A: You can use this:
 db.collectionName.updateMany({},{$set:{unitsAvailed: 20}})


text:
Q: Replacing the parameters of a function with a vector In Scala, if I have a function f(X, Y, Z) is it possible to pass a variable W that will represent (X, Y, Z) so I can use f(W) instead of f(X,Y,Z)? If so, how can this be done?

A: If you mean to pass a tuple or case class instead of the three parameters. Then yes, you can.
First, If it is a function, you can just: f.tupled(tuple).
If it is a method then: (m _).tupled(tuple). _(it is basically the same, but using eta-expansion to turn the method into a function).
If you have a case class instead of a tuple, you can to turn an instance of it into a tuple with this: W.unapply(w).get (where W is the companion object of the case class, and w is the instance).


text:
Q: tcpdump filter for given bytes on given position I'm searching for a way to filter traffic for specific bytes.
What I have is a stream that I capture with wireshark or tcpdump. Now it logs way too much, so I want to drop every packet that has 0x23 at place 42 in the payload.
Is there an easy way to do this? I'm searching for gsmtap, but any example with any protocol should be fine.

A: tcpdump(1) uses libpcap(3), which uses a filter syntax documented in the pcap-filter(7) man page.
You might want to skip down to the expr relop expr section, and the square-bracket notation:
expr relop expr
       True if the relation holds, where relop is one of >, <, >=, <=,  =,  !=,  and
       expr  is an arithmetic expression composed of integer constants (expressed in
       standard C syntax), the normal binary operators [+, -, *, /, &, |, <<, >>], a
       length  operator,  and  special packet data accessors.  Note that all compar-
       isons are unsigned, so that, for example, 0x80000000 and 0xffffffff are >  0.
       To access data inside the packet, use the following syntax:
            proto [ expr : size ]
       Proto  is  one of ether, fddi, tr, wlan, ppp, slip, link, ip, arp, rarp, tcp,
       udp, icmp, ip6 or radio, and indicates the protocol layer for the index oper-
       ation.   (ether,  fddi,  wlan,  tr,  ppp, slip and link all refer to the link
       layer. radio refers to the "radio header" added  to  some  802.11  captures.)
       Note  that  tcp, udp and other upper-layer protocol types only apply to IPv4,
       not IPv6 (this will be fixed in the future).  The byte  offset,  relative  to
       the  indicated  protocol layer, is given by expr.  Size is optional and indi-
       cates the number of bytes in the field of interest; it  can  be  either  one,
       two,  or  four,  and  defaults to one.  The length operator, indicated by the
       keyword len, gives the length of the packet.

So for example, if you wanted to filter out packets with 0x23 at location 42 of the payload of an Ethernet-II frame, that would be at offset 56 of the overall Ethernet frame (your offset of 42 plus an offset of 14 bytes to get past the Ethernet headers to the payload), so you could do something like this:
ether[56] != 0x23

I didn't fully read up on gsmtap so I'm not guaranteeing that the above filter is exactly what you need, but it should start you in the right direction.


text:
Q: What is the wpa_supplicant configuration file for a hidden network without password? I need to connect to a hidden network without password with wpa_supplicant:
iwlist <interface> scan  output:
 Cell 02 - Address: 11:22:33:44:55:66
                    Channel:1
                    Frequency:2.412 GHz (Channel 1)
                    Quality=67/70  Signal level=-43 dBm
                    Encryption key:on
                    ESSID:""
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                              9 Mb/s; 12 Mb/s; 18 Mb/s
                    Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=##################
                    Extra: Last beacon: 248ms ago
                    IE: Unknown: ######
                    IE: Unknown: ##################
                    IE: Unknown: #####
                    IE: Unknown: ##############
                    IE: Unknown: ######
                    IE: Unknown: ###############
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (1) : CCMP
                        Authentication Suites (1) : PSK
                    IE: WPA Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (2) : CCMP TKIP
                        Authentication Suites (1) : PSK
                    IE: Unknown: ###################

What is the wpa_supplicant configuration file needed to connect to this network?

Wrong guess:
network={
    ssid=""
    bssid=11:22:33:44:55:66
 }

A: According to Wiki-Archlinux you should add scan_ssid=1 to your wpa_supplicant configuration file:

Tip: To configure a network block to a hidden wireless SSID, which by definition will not turn up in a regular scan, the option scan_ssid=1 has to be defined in the network block.

to connect to an open network, you need to add the key_mgmt=NONE option to your wpa_supplicant configuration file :
network={
        ssid=""
        bssid=11:22:33:44:55:66
        scan_ssid=1
        key_mgmt=NONE
}


text:
Q: How to use intersection observer in the  tag? I'm trying to observe the last element and make an API call to load more customer in option Here is the code, type of observer is boolean, it returns true if visible otherwise false.
The customer data contains more than 37 thousand customer's name. To minimize the resource usage, I want to load more options once the last option is visible while scrolling and make an API request if the last element is observed.
Link for intersection observer API https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver

<select
  id="customer_id"
  name="customer_id"
  placeholder={strings.select_customer}
  options={customerOptions}
  value={formValue.customer_id ? formValue.customer_id : null}
  onChange={handleCustomerChange}
  isLoading={customerListLoading}>
  {customerOptions?.map((customer: Customer) => {
    return (
      <option key={customer?.id} value={customer?.id}>
        {customer?.name}
      </option>
    );
  })}
  <option ref={observer}>last visible option</option>
</select>