text:
Q: How Can i pass result from a method in groovy to the body of a request in SOAPUi Can i start by saying i am new to programming and SoapUI(more like a week old). i apologies in advance for asking the question(s) i am about to ask.
Problem
basically, i am trying to automate webservice.
I need to create xml using Groovy in soapui and send it as part of a request body to a webservice(REST not SOAP) and do some assertion on the response received.  i will be sending quite a few request, hence the reason to automate.
My proposed solution (which i am not sure about)
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
import groovyx.net.http.Method

class XmlGenerator {

  // I created a class i.e. called XmlGenerator with a
  // static method called GetXML() which looks like this:
  public static def GetXML()
  {
    def  writer = new StringWriter()
    def  xml = new MarkupBuilder(writer)
    xml.GetDMessage() //creating the xml message
    {
      PrescribedItems
      {
        PrescribedMethod(xml,'Some Value','Some Value','Some Value')
        PrescribedItem
        {
          PrescribedMethod(xml,'Some Value','Some Value','Some Value')
        }
      }
    }
    return writer
  }

  // This method creates the XML needed but then i need to
  // pass the xml generated to a request boy; so i
  //create another method within the same class:
  static def postXML(String baseUrl, String path)
  {
    def RequestBody = XmlGenerator.GetXML()  // i am not sure if this will work
    try
    {
      def ret = null
      def http = new HTTPBuilder(baseUrl)
      http.request(Method.POST, ContentType.XML)
      {
        uri.path = path
        body = RequestBody
      }
    }
    catch (groovyx.net.http.HttpResponseException ex)
    {
      ex.printStackTrace()
      return null
    }
    catch (java.net.ConnectException ex)
    {
      ex.printStackTrace()
      return null
    }
  }
}

Summary
A class called XmlGenerator() with 2 methods; GetXML() (used to generate XML ) and postXML() (Used to send XML generated by GetXML() to the Webservice.)
Questions

*

*How can i make sure that this 2 methods ( GetXML() and postXML() ) are used by other request messages i.e. do i need to import the groovy scripte.g. do i do an import ... GroovyScriptName , if yes, please how?

*How can i create create the xml and run the request in subsequent request messages. For instance;
do i do this; XmlGenerator() gen = new XmlGenerator(), then do gen.GetXML() and gen.postXML() to create and run the request. Also, what role can testRunner play in all this

*Running the code currently throws up HTTPBuilder, ContentType , Method can not be resolved even though i have imported them in the script (see above)

*Finally, what role can property play in building this framework? bearing in mind that the each request will be independent from the other request i.e. nothing is been passed around from one request to the other during test execution

A: You can specify the REST request you are testing using standard soapui functionality, as outlined here:
http://www.soapui.org/REST-Testing/getting-started.html
Follow the steps in the above page to create a:

*

*New REST Service

*New REST Resource

*New REST Method

Then you can add a REST Test Step to your Test Case that invokes that request.
You can then insert a Groovy Test Step before the REST Test Step to build your xml body; here's a simple example of building a XML string:
import groovy.xml.MarkupBuilder

context.writer = new StringWriter()
def xml = new MarkupBuilder(context.writer)
xml.books() {
  book(name:'blue ocean') {
    format ('paperback')
    year ('2010')
  }
  book(name:'quicksilver') {
    format ('hardback')
    year ('2011')
  }
}

Note that the XML is assigned to a context variable (context.writer). This makes it available for use in subsequent steps within the scope of the Test Case for the duration of the test run.
Then, insert the following code into the body of your REST Test Step:
${=context.writer}

Finally, you have the option of adding Assertions within the REST Test Step; here's some information on that:
http://www.soapui.org/Functional-Testing/getting-started-with-assertions.html


text:
Q: Can't duplicate function When I try to duplicate function
it show RootNavigator error

Duplicate function implementation.ts(2393)

I try add export at the top but won't work
export {}

https://reactnavigation.org/docs/native-stack-navigator#options
const DashboardStack = createNativeStackNavigator<RootStackParamList>();

function RootNavigator() {
  return (
    <DashboardStack.Navigator>
      <DashboardStack.Screen name="Root" component={BottomTabNavigator} options={{ headerShown: false }} />
      <DashboardStack.Screen name="NotFound" component={NotFoundScreen} options={{ title: 'Oops!' }} />
      <DashboardStack.Group screenOptions={{ presentation: 'modal' }}>
      </DashboardStack.Group>
    </DashboardStack.Navigator>
  );
}

const ActivityStack = createNativeStackNavigator<RootStackParamList>();

function RootNavigator() {
  return (
    <DashboardStack.Navigator>
      <DashboardStack.Screen name="Root" component={BottomTabNavigator} options={{ headerShown: false }} />
      <DashboardStack.Screen name="NotFound" component={NotFoundScreen} options={{ title: 'Oops!' }} />
      <DashboardStack.Group screenOptions={{ presentation: 'modal' }}>
      </DashboardStack.Group>
    </DashboardStack.Navigator>
  );
}

A: You can't have two variables with the same name in the same scope. You have to give them different names.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create a bookmarkable material link with mat-icon I want to create a mat-icon link so I can bookmark it with the link name.
However, material design put the icon name in the middle of the  tag.
    <a mat-raised-button
      [routerLink]="['users']">
      <mat-icon >visibility</mat-icon>
      {{user.name}}
    </a>

In this case my bookmark will display the bookmark icon + 'visibility'.
I just want to have the username in the bookmark next to the icon.


text:
Q: bash script, check port response with bash's built-in /dev/tcp, time delay | hangs | speed up With this scripts i check if a host is response on a given port with the bash's built-in /dev/tcp.
I can use ip address or domains(hostnames).
Script 1
#!/bin/bash

HOST_NAME="127.1"
HOST_PORT="80"

if ( (exec 3<>/dev/tcp/${HOST_NAME}/${HOST_PORT}) 2> /dev/null); then
    echo -e "PORT: ${HOST_PORT} | ON"
    else
    echo -e "PORT: ${HOST_PORT} | OFF"
fi

exit;

Script 2
#!/bin/bash

HOST_NAME="127.1"

for HOST_PORT in {1..1000}
do

if ( (exec 3<>/dev/tcp/${HOST_NAME}/${HOST_PORT}) 2> /dev/null); then
    echo -e "PORT: ${HOST_PORT} | ON"
    else
    echo -e "PORT: ${HOST_PORT} | OFF"
fi
done

exit;

Script 3
#!/bin/bash

HOST_NAME="127.1"
declare -A PORT_ON

for HOST_PORT in {1..65535}
do
    if ( (exec 3<>/dev/tcp/${HOST_NAME}/${HOST_PORT}) 2> /dev/null); then
        PORT_ON[${HOST_PORT}]="ON"
    fi
done

for i in ${!PORT_ON[*]}
do
    echo -e "$i : ${PORT_ON[$i]}"
done

exit;

On some of our local and online domains Script 3 hangs on some ports and takes longer to jump to the next port scan, for example on ssh(because of firewalls or other services). How can i manage this that it continues straight away and is it possible to speed the script up, it takes a long time, when i scan all 65535 ports an.
My GNU/Linux Distro:
Distributor ID: Debian

Description:    Debian GNU/Linux 10 (buster)

Release:        10

Codename:       buster

4.19.0-16-amd64

My /etc/apt/sources.list
deb http://security.debian.org/debian-security buster/updates main contrib

deb-src http://security.debian.org/debian-security buster/updates main contrib

deb http://deb.debian.org/debian/ buster-updates main contrib

deb-src http://deb.debian.org/debian/ buster-updates main contrib

I can only install  from this repos.
bash script, check port response with bash's built-in /dev/tcp, time delay | hangs | speed up
how can i speed up and terminate the time delay?

A: run this with timeout i put a timer variable to check the running time it seems you can't speed up the script more than 0.01 if this script is executed with 0.001 you will only see the result of the timer variable but no other result even with 1, 0.1 or 0.01 you will always get the same result i tested this script with ubuntu 22.04 and set the ports to 10000
#!/bin/bash

starttime=$(date +%s)
HOST_NAME="127.0.0.1"
declare -A PORT_ON

for HOST_PORT in {1..10000}
do
 if((timeout 0.1 bash -c "</dev/tcp/${HOST_NAME}/${HOST_PORT}") 2> /dev/null); then
    PORT_ON[${HOST_PORT}]="ON";
  fi
done

for i in ${!PORT_ON[*]}
do
  echo -e "$i: ${PORT_ON[$i]}"
done

endtime=$(date +%s)

echo "runtime: $(($endtime - $starttime))"


text:
Q: IIS10 UrlRewrite, multiple canonical TLD's & non-canonical sub-domains + HTTPS I'm having some trouble with URL rewrite.
I have a website that hosts multiple child sites all within the same Site in IIS10. The primary site has 3 TLD's that should redirect to a primary canonical TLD.
On the same site there are multiple additional bindings for sub-domains of the primary TLD that I don't want redirecting to my primary TLD.
This is how I'd like to have URL rewrite working:
TLD's
mydomain.com
mydomain2.com
mydomain3.com
--> mydomain2.com & mydomain3.com should redirect to mydomain.com with HTTP to HTTPS.
Sub Domains
c1.mydomain.com
c2.mydomain.com
c3.mydomain.com
etc..
--> c1.mydomain.com, c2.mydomain.com, c3.mydomain.com, etc... should NOT redirect to mydomain.com with HTTP to HTTPS.
These are my problematic areas
If I create a redirect HTTP to HTTPS rule then mydomain2.com & mydomain3.com don't pull up as my SSL cert is only for mydomain.com and I don't want mydomain2.com & mydomain3.com as the site's URL, I only want them to redirect to mydomain.com
If I don't create a canonical rule then when visiting either mydomain2.com or mydomain3.com it will fail as there is no matching SSL for those TLD's and the HTTP to HTTPS rule is sending visitors to the HTTPS version a TLD that has not HTTPS binding. Additionally I don't want those URL's staying in the address bar, I want the final domain to be mydomain.com
If I DO create a canonical rule then all my sub-domain bindings will now redirect to mydomain.com which is problematic as those are completely different websites being redirected.
I'm using DNN as the CMS so if your familiar with Portals, that's what's happening all child portals are now redirecting to my parent portal and I don't want that.

UPDATE per Lex Li's request
Rules 1) Here is the URL Rewrite rule for redirecting HTTP to HTTPS
The problem here is that I don't have a canonical redirect to my primary domain.
<rewrite>
            <rules>
                <rule name="Redirect to HTTPS" enabled="true" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
                </rule>
            </rules>
        </rewrite>

Rules 2) Here is the URL rewrite rules WITH canonical redirect + HTTP to HTTPS
The problem here is that subdomain.mysite.com is redirecting to mysite.com where it shouldn't. I see there is a condition's area perhaps there is a way to condition this rule so it doesn't apply to my subdomains?
<rewrite>
            <rules>
                <rule name="CanonicalHostNameRule1">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^example\.com$" negate="true" />
                    </conditions>
                    <action type="Redirect" url="http://example.com/{R:1}" />
                </rule>
                <rule name="Redirect to HTTPS" enabled="true" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" />
                </rule>
            </rules>
        </rewrite>

Observations:
Rules 1 Enabled:
example.com redirects to https://example.com (correct)
example2.com redirects to https://example2.com (fails | no SSL on example2.com & it should redirect to example.com)
sub.example.com redirects to https://sub.example.com (correct)
Rules 2 Enabled:
example.com redirects to https://example.com (correct)
example2.com redirects to https://example.com (correct)
sub.example.com redirects to https://example.com (fails, it should redirect to https://sub.example.com)

A: Modify rule "CanonicalHostNameRule1" to,
                <rule name="CanonicalHostNameRule1">
                    <match url="(.*)" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{HTTP_HOST}" pattern="^example\.com$" negate="true" />
                        <add input="{HTTP_HOST}" pattern="^sub\.example\.com$" negate="true" />
                    </conditions>
                    <action type="Redirect" url="http://example.com/{R:1}" />
                </rule>


text:
Q: jQuery: set value into select input field I am building an edit form using Django forms. When user click on a particular table row, it will open up an editModal and take value of that table rows. However, I couldn't set the value into input of type select.
$("#question_type").val("question_type");

The code above doesn't work.
jQuery
//Edit OnClick- Question
$(".table-row td:not(:has(input))").on("click", function(){
  $('#editModal').modal('show');
  let rowId = $(this).closest('tr').attr('data-id');
  var test_id, question_type, question_name, option;

  $.ajax({
    url: "{% url 'edit_question' %}",
    type: 'GET',
    data: {"rowId" : rowId},
    dataType: 'json',
    success: function(data){
      test_id = data.question[0]['test_name'];
      question_name = data.question[0]['question_name'];
      question_type = data.question[0]['question_type'];
      if (question_type == 'QCM'){
        option = parseInt(data.question[1].length);
      }

      $(".question_name").val(question_name);
      //input of type text works fine.
      $(".question_type").val(question_type);
      $(".test_id").val(test_id);
      },
    });

$(".question_type").val(question_type);
    $(".test_id").val(test_id); //doesn't set the value into select input

.html

                    <form class="form" method="POST" action="{% url 'edit_test' %}">
                        {% csrf_token %}

Edit Question

                                Test :

                                    {{questionForm.test_id}}

                                Type :

                                    {{questionForm.question_type}}

                                Question :

                                    {{questionForm.question_name}}

                    </form>

forms.py
class QuestionForm(ModelForm):
        class Meta:
            model = Question
            fields = ['test_id','question_type','question_name']
        test_id = forms.ModelChoiceField(queryset=Test.objects.all(), empty_label=None, label='Test',
                widget=forms.Select(
                    attrs={
                        'id': "test_id",
                        'name': "test_id",
                        'title': 'Select a Test',
                        'class': 'selectpicker form-control test_id',
                        'data-style': 'btn btn-primary btn-sm',
                        'data-size': '7',
                    }
                )
        )
        question_type = forms.ChoiceField(choices = QUESTION_TYPE, initial='QCM',
                widget=forms.Select(
                    attrs={
                        'id': "question_type",
                        'name': "question_type",
                        'title': 'Select a Test',
                        'class': 'selectpicker form-control question_type',
                        'data-style': 'btn btn-primary btn-sm',
                        'data-size': '7',
                    }
                )
        )
        question_name = forms.CharField(label='Question',
            widget=forms.TextInput(
                attrs={
                    'id': "question_name",
                    'name': "question_name",
                    'class': 'form-control question_name',
                    'placeholder': 'Add question here...',
                }
            )
        )

I've searched through many solutions, but none work. What cause the errors? How could I fix this? Thank you.

A: After trying many solutions, I came to realize that I was not able to set the value into the input field because input field is created using bootstrap select. using val() to set the value doesn't refresh the UI so I cannot see change on the browser.
Solution
$(".question_type").selectpicker('val', question_type);

I make this change, and now everything work fine!
Read more Bootstrap-select .selectpicker('val')


text:
Q: how to make 3d terrain using voxels and perlin noise Ive read many tutorials on this concept but I feel none of them go into too much depth on how to do it. I already know how 3d programming (rasterizing, projection matrix, etc.) raycasting (using euclidean geometry and vectors) and raytracing work I just need to know how a voxel landscape is generated and rendered using perlin noise. Also, I know that maps are created with 2d arrays but does each element of the array represent each vertical column of voxels or just a generalized point on the map (like the peak of a mountain or a hill top). Thanx in advance for the answers!

A: I don't know what you're after.  Are you looking for basic terrain mapping like any video game or are you looking for "voxels" like Minecraft voxels?  Games like Minecraft use 3d Perlin noise not 2-d as you seem to believe.  The 3-d noise is what helps generate caves and caverns underground.  If you're just talking about height maps, the way those work is, yes, the "color" or value on a 2-d plane represents the height of the grid point.  Dark points on a 2-d noise map will often be valleys and light points mountains or whatever you want.
Here's a great source on implimenting 3-d Perlin noise that helped me a great deal to understand it.  If you haven't had multivariable calc you might be a little more confused by it, but judging by the other stuff you're talking about, it should be a breeze for you.  I'd probably be able to do it, but I'd sweat a lot if I were trying to program view frustums: http://staffwww.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf
Here's a great video of someone mapping 3d Simplex noise in space: https://www.youtube.com/watch?v=GTAqjyG2oOc
Both Perlin and Simplex (made by the same guy) establish an algorithm where you can sample values at coordinates.  You can then use these values for whatever you want and the potential of them is really quite varied.  From generating terrain to easily tiled textures, to clouds or making millions off your dorky dig and place blocks game.
Here was my first test of my 3-d Perlin noise.  I used it to sample the density of the 3-d noise at all the places on the surface of a sphere.  Since the sphere is, abstractly, "placed in a 3-d cloud" sampling the value of the cloud on the sphere's surface produces a perfectly tiling and not stretched map of noise for the sphere: http://imageshack.com/a/img908/4101/75e2a4.png
There's an example of both how 3-d noise and 2-d noise can be used.  The 3-d noise is used to create the seamless texture on the sphere and then the texture on the sphere is used to generate a height and color map for the very badly sketched out planet (it was just a test of the noise, not something to be used).
Anyway, I don't know if you mean "voxels" as in generating minecraft like content or if you simply mean voxels in the mathematical sense.  For general terrain generation on your standard game where you don't have to be digging around in the dirt for blocks, 2-d noise would generally be implimented similar to how my planet uses the 2-d texture which is generated from 3-d noise.  It simply maps heights of the terrain mesh to a 2-d plane.  For finer details, normal maps and bump maps create the illusion of deformations in the underlying mesh by rendering shadows on otherwise flat surfaces.
EDIT: I'm confused what you mean by "I know the voxels are stored in 2-d arrays"...  If you mean vertices on a map, well, that would make sense because you have the x index of the array, the y index of the array and the value index of the z (height).  Most terrain I've seen has absolutely no skewing of the z coordinates on terrain meshes.  That's why you sometimes get that nasty stretched texture look on the sides of mountains in older games like WoW: http://img90.imageshack.us/img90/7000/155n.jpg  The face of the mesh has been stretched because the x and y of the "z" value are clamped (I would assume to integers) for convenience.

A: You can get a height map based voxel landscape using the amplitude of the return value of a 2D perlin noise fed with a 2d grid. The higher is the returned value, the more you add voxels vertically. If you want 3d landscape with caving effects, then you need an extra dimension (ex: feeding 3D perlin with the vertex positions of a 3D grid) and add voxels where your noise surface lies (ex: where the return value is 0, if your perlin implementation returns between -1 and 1).

A: 3d noise function returns 1 to -1 for any XYZ point in space...
run the noise function for chosen xyz spaces.
if it's more than 0, it contains a voxel.
when xyz returns a density field like -1/1 its called isosurface function.
look for isosurface tutorial online for images and infos.


text:
Q: ORA-01292: Can't access log file with log miner while using online catalog I'm currently trying to add logminer to my Oracle database.
The goal is to use le online catalog but when i use :
EXECUTE DBMS_LOGMNR.START_LOGMNR(OPTIONS => DBMS_LOGMNR.DICT_FROM_ONLINE_CATALOG);
to start the log miner i get this error :
ORA-01292: aucun fichier journal n'est indique pour la session LogMiner actuelle
ORA-01292: no log file for current LogMiner session.
Do you have any clue on this ?
Do i need to add a log file even if i use the online catalog ?
Thanks,


text:
Q: Can't find the created file in the ExternalStoragePublicDirectory in android I am working on an application that records acceleration data from the smartphone and save them into a file everytime i click on the start recording button,
but i can't find the created file alhough no exceptions have been raised.
I added the permission request <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in the manifest file and i checked the previously asked questions related to this topic but i still can't find where the problem is?
Here is the code :
public class MainActivity extends AppCompatActivity implements SensorEventListener {

    int clicknumber = 0;
    private static final String LOG_TAG ="";
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private Button mstartButton= null;
    private boolean servicestatus = false;
    private RelativeLayout Rl = null;
    private LinearLayout ll= null;
    long timeOffsetMs= System.currentTimeMillis()-System.nanoTime() / 1000000;

    File file=null;
    BufferedWriter out = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        final String path = Environment.getExternalStoragePublicDirectory
                (Environment.DIRECTORY_DOCUMENTS).getPath();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        servicestatus = isMyServiceRunning(RecordService.class);
        mstartButton = (Button) findViewById(R.id.recordButton);
        mstartButton.setText("Start Recording");
        mstartButton.setTextColor(Color.GREEN);
        Rl= (RelativeLayout) findViewById(R.id.Rlayout);
        ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.VERTICAL);
        Rl.addView(ll);
        final Intent service = new Intent(this, RecordService.class);
        mstartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clicknumber+=1;
                if (clicknumber % 2 != 0 || clicknumber == 0  ){
                    startService(service);
                    mstartButton.setText("Stop Recording");
                    mstartButton.setTextColor(Color.RED);
                    String newpath = path +"data.txt";
                    file = new File(newpath);

                }
                else{
                    stopService(service);
                    mstartButton.setText("Start Recording");
                    mstartButton.setTextColor(Color.GREEN);
                }
      }
        });
    }
    protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);

    }
    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);

    }
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {

        Sensor mySensor=sensorEvent.sensor;
        if (mySensor.getType()==Sensor.TYPE_ACCELEROMETER){
            float x=sensorEvent.values[0];
            float y=sensorEvent.values[1];
            float z=sensorEvent.values[2];
            long  timestamp=timeOffsetMs+ sensorEvent.timestamp / 1000000;
            if (isMyServiceRunning(RecordService.class) == true){
                TextView tv = new TextView(this);
                tv.setTextColor(Color.WHITE);
                tv.setText(String.format("t=%d,x=%.1f,y=%.1f,z=%.1f", timestamp,x,y,z));
                ll.addView(tv);
                try
                {
                    BufferedWriter out = new BufferedWriter(new FileWriter(file));
                    out.write(Float.toString(x) + Float.toString(y) +
                            Float.toString(z) );
                    out.close();
                }
                catch (IOException e)
                {
                    Log.e(MainActivity.LOG_TAG ,"Exception");
                }

            }
        }
    }
    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {}

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service :
                manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}

Thanks in advance!

A: Your File is at: /storage/emulated/0/Documentsdata.txt
Note that 2 things should meet, because the error here is not intended.

*

*The Directory Document must exist.

*You forgot / in the following line
Error  : String newpath = path +"data.txt"
No Error : String newpath = path +"/"+"data.txt"

If you test your code now, you can get you file or an exception is thrown.
which api are you using ?. declaring the permission in the manifest for writing file to a Storage is neccessary. but for the completness you should have granted permission from the user if the system api > 23.


text:
Q: Azure blob client-side encryption using Javascript I am working on Azure blob storage and using an HTML page with JS which is using Azure storage Rest API. I am able to Upload/Download blobs to my storage account. My requirement is to use client-side encryption for upload/download blobs so that files are encrypted before they are uploaded to blob storage account. There are few tutorials which explain this functionality using the library for .net/java and python, however, I am not able to find any documentation/sample to achieve this using JavaScript. Please help with any pointer which can help in my implementations.

A: try this doc: Azure Blob Storage
This doc has a lot of examples for implement for Nodejs


text:
Q: redis master slave replication stopped working I'm trying to figure out how to troubleshoot my redis master / slave replication.  It has "just stopped" working.
Setup Information
Let's say my master's IP address is 10.1.2.3
Here's what I've checked so far:

*

*I've restarted redis on both the master and slave... but anytime I run INFO REPLICATION on the slave it shows the link as "down"

*Ran netstat -lnp on both the master and slave.  Here's the output from the master:

masterdb:~# netstat -lnp | grep 6379
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      21611/redis-server
tcp        0      0 10.1.2.3:6379      0.0.0.0:*               LISTEN      21611/redis-server

And from the slave machine:

slavedb:~# netstat -lnp | grep 6379
tcp        0      0 0.0.0.0:6379            0.0.0.0:*               LISTEN      5577/redis-server
tcp        0      0 :::6379                 :::*                    LISTEN      5577/redis-server
slavedb:~#

*I've checked the logs on both the master and the slave and I don't see any error messages. But I see timeout messages on the slave... which I think I've seen before, even when replication was working.  The log looks like this on the slave:

5577:S 26 Oct 13:17:19.510 * MASTER <-> SLAVE sync started
5577:S 26 Oct 13:18:20.597 # Timeout connecting to the MASTER...
5577:S 26 Oct 13:18:20.597 * Connecting to MASTER 10.1.2.3:6379
5577:S 26 Oct 13:18:20.597 * MASTER <-> SLAVE sync started
5577:S 26 Oct 13:19:21.685 # Timeout connecting to the MASTER...

*When i start the redis-cli on the slave and re-issue the slaveof command, i get this message:
127.0.0.1:6379> slaveof 10.1.2.3 6379
OK Already connected to specified master
127.0.0.1:6379>

*I also tried the following commands on the master :

127.0.0.1:6379> save
OK
127.0.0.1:6379> bgsave
Background saving started
127.0.0.1:6379>

But that didn't resolve anything on the slave.  It still says the link is down when I check the INFO on REPLCIATION:
   127.0.0.1:6379> info replication
    # Replication
    role:slave
    master_host:10.1.2.3
    master_port:6379
    master_link_status:down
    master_last_io_seconds_ago:-1
    master_sync_in_progress:0
    slave_repl_offset:1
    master_link_down_since_seconds:1477488462
    slave_priority:100
    slave_read_only:1
    connected_slaves:0
    master_repl_offset:0
    repl_backlog_active:0
    repl_backlog_size:1048576
    repl_backlog_first_byte_offset:0
    repl_backlog_histlen:0
    127.0.0.1:6379>

I'm not sure what else to check.

A: sounds like a networking issue. Try to
telnet masterip 6379 from the slave next time it happens to ensure it is a network issue.


text:
Q: Trouble with a GUI toolkit in C++. Passing lambdas into a vector of std::function The problem I have is kind of difficult to describe but I will do my best to make it understandable.
I am creating a C++ GUI toolkit similar to the Windows Forms System in C#. The whole system is event based. My Event class consists of a vector of std::function's, which acts as a list of subscriber functions, and some utility methods.
template<class T>
class Event
{
public:

  Event() {}
  ~Event() {}

  void Raise(T context)
  {
    for(std::function<void(T&)> subscriber : Subscribers)
    {
      subscriber(context);
    }
  }

  void Subscribe(std::function<void(T&)> subscriber)
  {
    try { Subscribers.push_back(subscriber); } catch (std::exception) { /*...*/ }
  }

private:

  std::vector<std::function<void(T&)>>> Subscribers;

}

My project contains an EventProvider class which provides a bunch of events to all derived classes.
class EventProvider
{
public:

  Event<LoadEventContext> LoadEvent;
  // ...
  // ...

}

Also like in Windows Forms I have a Window class and a Control class. Both of them inherit EventProvider. Like in C# the actual Window class where all functionalities are defined must inherit the Window class.
class Control : public EventProvider { /*...*/ }

class Window : public EventProvider { /*...*/ }

class MyWindow : public Window { /*...*/ }

In my MyWindow class I am binding methods to the events of the Window via lambdas. Binding methods of the MyWindow class to events of the MyWindow class works just fine. Also binding a control's member function to an event of MyWindow works without problems. In Windows Forms all event methods of the controls are also contained in the Window class. The same I wanted to do in my project. So the MyWindow class contains the instances of my controls, it's own event methods and the event methods of my controls. But when I try to bind a control event function to a control event I am getting a runtime error.
// ===  MyWindow.hpp  ===

#ifndef __MY_WINDOW_HPP__
#define __MY_WINDOW_HPP__

#include <Control.hpp>
#include <Window.hpp>

class MyWindow : public Window
{
public:

  MyWindow();
  ~MyWindow();

private:

  Control* button = nullptr;

  void OnLoadEvent(LoadEventContext& context);
  void button_OnLoadEvent(LoadEventContext& context);

}

#endif

// ===  MyWindow.cpp ===

#include <MyWindow.hpp>

MyWindow::MyWindow()
{
  button = new Control();

  LoadEvent.Subscribe([&](LoadEventContext& context) { OnLoadEvent(context); }); // WORKS
  LoadEvent.Subscribe([&](LoadEventContext& context) { button->OnLoadEvent(context); }); // WORKS

  button->OnLoadEvent.Subscribe([&](LoadEventContext& context) { OnLoadEvent(context); }); // Runtime Error
}

MyWindow::~MyWindow() { /*...*/ }

MyWindow::OnLoadEvent(LoadEventContext& context) { /*...*/ }

MyWindow::button_OnLoadEvent(LoadEventContext& context) { /*...*/ }

//

When MyWindow calls the control's load event to add the lambda function to the event's vector of subscriber functions a read access violation is thrown in the stl's vector class.

This line of code called the event to add the lambda function:
button->OnLoadEvent.Subscribe([&](LoadEventContext& context) { OnLoadEvent(context); }); // Runtime Error

and this one in the Event class caused the error:
try { Subscribers.push_back(subscriber); } catch (std::exception) { /*...*/ }

I am still not very advanced in programming with function pointers, functors, functionoids and all that stuff. Nevertheless I hope I pointed out my problem clearly enough for you and I hope that anyone can help me with this issue.

A: I've got it. The problem was that I bound my event method the event of my control before this control has been created at all.


text:
Q: Can ActiveAdmin serve individual javascript files in development via Rails asset pipeline? I've configured ActiveAdmin to include my own javascript, following these instructions Active Admin: Including Javascript.
In my initializers/active_admin.rb:
  config.register_javascript 'application.js.coffee'

But now I get one massive precompiled application.js served to me (application.js.coffee requires many small files); in development mode when I visit the active admin pages. I still want the individual javascript files to served individually for easier debugging. Is there a way to get this?

A: Put this in your development.rb:
config.assets.debug = false


text:
Q: How can I define APPEND for Rebol3 PORT? I'm working on scheme in Rebol3 and I'd like to add APPEND action. However, adding APPEND actor to the scheme does nothing, result of append my-scheme://localhost foobar is my-scheme://localhostfoobar instead of my action. The documentation is bit unfinished in this regard.

A: You need to use append on the port, and not the url!
port: open my-scheme://localhost
append port "my data"

The only port actors that can take a URL as an argument are those that have a port! specified as an argument.  These are create, delete, open, close, read, write, open?, query, update, and rename.  See http://www.rebol.net/wiki/Schemes:Notes#Port_Actions


text:
Q: CSS - How do I move a button up to be side-by-side? I just want to move the Cancel Filter button up to the right of the Filter button. This is MVC / Index.cshtml file. I'm using Bootstrap too. I'm using Chrome.
I did an inspect on the 2nd form and manually set the CSS as display: inline-block and it does not move up. I tried a few things with no luck.

    @Html.ActionLink("Create New", "Create")

    @using (Html.BeginForm("Index", "Movies", FormMethod.Get))
    {

            Genre: @Html.DropDownList("movieGenre", "All")
            Title: @Html.TextBox("searchStringEntered")
            <input type="submit" value="Filter" />

    }

    @using (Html.BeginForm("Index", "Movies", FormMethod.Get))
    {

           <input type="submit" value="Cancel Filter" />

    }

Here's the screen shot.

Per discussions below, I created a rule in my Site.css file for the form:
.side-by-side {
    display: inline-block !important;
}

In the inspector, I can manually add it to both form tags and it works, but when  I run the page, my custom Site.css file is not being shown. So the rule is not getting to the browser. However, my custom Site.css file shows for other rules elsewhere. So I don't understand why it is not being picked up by the browser.
Here is a screenshot of me having manually adding to both form tags - the display: inline-block - and it works. It moved the Cancel Filter button up. The screen shot also shows the new CSS class I added to the tag.

Here is a screen shot where it picks up my Site.css file and applies a CSS rule. So I know it recognizes it.

A: You can use something like so:

 Filter

 Cancel

Because your p blocks that you want side by side are already inside another element this should work.

A: remove the p inside the forms since I see no reason to keep them and use
display: inline-block;
for both your forms.


text:
Q: Adding on_release action to buttons in loop class WidgetFiscal(Screen):
    box = ObjectProperty(None)

    def on_box(self, *args):
        fiscal = ['Elzab Mera TE FV', 'Posnet Thermal XL', 'Posnet HD', 'Elzab Sigma', 'Novitus Delio Prime E', 'Elzab D10', 'Posnet Trio', 'Epson TM-T801FV']
        for i in fiscal:
            self.box.add_widget(Button(text=str(i), background_color=[1,2,1,1]))

my .kv file :
<FiscalPrinter>:
    name: 'fiscal_printer'

    BoxLayout:
        size: root.size
        spacing: 20
        padding: 10,10,10,10
        orientation: 'vertical'

        Label:
            text: 'Choose fiscal printer which you want to rent'
            size: root.width, root.height / 10
            size_hint: None, None

        WidgetFiscal:

        Button:
            text: 'GO BACK'
            size: root.width, root.height / 10
            size_hint: None, None
            on_release: app.root.current = "rent_device"

<WidgetFiscal>:
    box: box

    GridLayout:
        background_color: 1,2,1,1
        cols: 3
        id: box

A: Adding on_release event to Button widget.
self.box.add_widget(Button(..., on_release=self.mycallback))

Notes
Kivy » Touch event basics

By default, touch events are dispatched to all currently displayed
  widgets. This means widgets receive the touch event whether it occurs
  within their physical area or not.
...
In order to provide the maximum flexibility, Kivy dispatches the
  events to all the widgets and lets them decide how to react to them.
  If you only want to respond to touch events inside the widget, you
  simply check:
def on_touch_down(self, touch):
    if self.collide_point(*touch.pos):
        # The touch has occurred inside the widgets area. Do stuff!
        pass

Solution
Therefore you want to define class PrinterButton with inheritance of Button widget and implement on_touch_down method to only respond to touch events for Button touched.
Snippets
class PrinterButton(Button):
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            print(f"\nPrinterButton.on_touch_down: text={self.text}")
            self.dispatch('on_release')
            return True    # consumed on_touch_down & stop propagation / bubbling
        return super(PrinterButton, self).on_touch_down(touch)

class WidgetFiscal(Screen):
    box = ObjectProperty(None)

    def on_box(self, *args):
        fiscal = ['Elzab Mera TE FV', 'Posnet Thermal XL', 'Posnet HD', 'Elzab Sigma', 'Novitus Delio Prime E', 'Elzab D10', 'Posnet Trio', 'Epson TM-T801FV']
        for i in fiscal:
            self.box.add_widget(PrinterButton(text=str(i), background_color=[1,2,1,1], on_release=self.mycallback))

    def mycallback(self, instance):
        print(f"mycallback: Button.text={instance.text}")

Output


text:
Q: How can I fix my WRT54GL's constant crashing? I have a Linksys WRT54GL wireless router (the old blue-and-black) whose underside indicates it is Version 2. I've noticed that, on wireless mode, if I am on a Skype call or in a Google Hangout, the wireless aspect will crash completely. In addition, if I am connected via an ethernet cord, my quality (that is, how my voice is received) tanks very quickly.
I suspect this is due, in part, to my internet connectivity itself (I'm on Comcast instead of Verizon FiOS, as I'd prefer) but I'd like to stop my wireless router's wireless capability from crashing.
I considered a firmware upgrade, but it looks to me as if I am upgraded.

Short of manually running ethernet all over my house, I'm not sure what to do. How can I solve my wireless router's issues? If the answer is "buy a new router," then that's valid, as well, in my opinion.

A: These routers are pretty bad about this, honestly.  You could consider putting aftermarket firmware on it - Tomato and DD WRT both should work on this model, and while I can't promise they'll fix issues it certainly can't hurt to try, and you get a lot more functionality anyway.
If you're too gun-shy to try something like that, I would simply buy another router.  Couldn't hurt to have wireless N capability anyway for future-proofing your network, and it's available fairly cheaply as I write this.


text:
Q: PBS Postgres SQL not starting after restart. Cant remove postmaster.pid file
Ple
Could not delete using rm -f postmaster.pid command.
The file does not go away after restart.
Both images are given to describe the problem.


text:
Q: How to replace the value of GtkEntry properly Inside handlers clearHandle and replaceHandle i'm trying to replace the value of GtkEntry using gtk_entry_set_text function but it's not working for me.
Here is what i did
#include <gtk/gtk.h>

void clearHandle(GtkEntry *e)
{
    gtk_entry_set_text(e, "");
}

void replaceHandle(GtkEntry *e)
{
    gtk_entry_set_text(e, "Hello World");
}

static void activate(GtkApplication *app, gpointer user_data)
{
    GtkWidget *window;
    GtkWidget *button_box;
    GtkWidget *text_box;
    GtkWidget *clearButton;
    GtkWidget *replaceButton;
    GtkWidget *textInputBox;

    window = gtk_application_window_new(app);
    gtk_window_set_title(GTK_WINDOW(window), "First GUI in c");
    gtk_window_set_default_size(GTK_WINDOW(window), 600, 600);

    // Containers and adding them to the window
    button_box = gtk_button_box_new(GTK_ORIENTATION_VERTICAL);
    text_box = gtk_fixed_new();

    // Textbox inside container
    textInputBox = gtk_entry_new();
    gtk_entry_set_text((GtkEntry *)textInputBox, "Hello boom World");

    clearButton = gtk_button_new_with_label("Clear");
    replaceButton = gtk_button_new_with_label("Replace with hello World");

    gtk_container_add(GTK_CONTAINER(button_box), textInputBox);
    gtk_container_add(GTK_CONTAINER(button_box), clearButton);
    gtk_container_add(GTK_CONTAINER(button_box), replaceButton);

    g_signal_connect(clearButton, "clicked", G_CALLBACK(clearHandle), (GtkEntry *)textInputBox);
    g_signal_connect(replaceButton, "clicked", G_CALLBACK(replaceHandle), (GtkEntry *)textInputBox);

    gtk_container_add(GTK_CONTAINER(window), button_box);

    gtk_widget_show_all(window);
}

int main(int argc, char **argv)
{
    GtkApplication *app;
    int status;

    app = gtk_application_new("org.yk.dev", G_APPLICATION_FLAGS_NONE);
    g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
    status = g_application_run(G_APPLICATION(app), argc, argv);
    g_object_unref(app);

    return status;
}

While Running this i'm getting following error in terminal
(main:14233): Gtk-CRITICAL **: 06:08:43.524: gtk_entry_set_text: assertion 'GTK_IS_ENTRY (entry)' failed

(main:14233): Gtk-CRITICAL **: 06:08:44.188: gtk_entry_set_text: assertion 'GTK_IS_ENTRY (entry)' failed

A: The clicked signal gives two arguments: first the GtkButton * that was clicked, then the userdata pointer. Your callbacks need to take that GtkButton * as the first argument (even though you don't use it); currently it tries to use the button as the entry, which is why you get the "'GTK_IS_ENTRY (entry)' failed".


text:
Q: Angular multiple router outlets I have an angular 6 application that I am trying to use multiple router-outlets with but cannot get the navigation to work.
My app.component looks like this
<router-outlet></router-outlet>

I then have a home component which has a navigation bar on the left hand side and a main section to the right of it. I am using this to display content in the main section without affecting the navigation bar on the left
<div toolbar></div>
<div mainSection>
   <router-outlet name="mainoutlet"></router-outlet>
</div>

My routing module looks like as follows
 path: '', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuard], children:
  [{ path: '', component: MainSectionComponent, outlet: 'mainoutlet' },
    { path: 'test1', component: Test1Component, pathMatch: 'full'},
    { path: 'test2', component: Test2Component, pathMatch: 'full' }

The MainSectionComponent is loaded correctly within the main section, however whenever I try to navigate to test1 or test2 it fails with an Angular error in the console.
I am trying to navigate using a the following code in a service.
    this.router.navigate('test1');

I am wondering if its because its being called from a service that its failing but I dont know. I have tried using a non-named router-outlet but this gives me the same result. I have also tried moving the routes out of the maincomponent children but this also does not work.
For reference, my setup looks to be exactly the same as https://stackblitz.com/angular/aepvpqmoqaj?file=src%2Fapp%2Fapp.component.html. The only difference being I am using a service to navigate rather than routerLinks in the html. That said I have noticed this code also fails with the same Angular error that I am receiving.


text:
Q: Create a NetworkPolicy that allows access to a pod from 2 specific pods Assuming I have a pod that has a label app=foo in a namespace.
I only want this pod to be accessible from 2 other pods in the same namespace (and no other else pod being able to access it) via a NetworkPolicy
These pods have the following labels
pod1
labels:
  app: foo1
  type: frontend

labels:
  app: foo2
  type: backend

My question is whether I am able to define 2 podSelector fields in the ingress section of the NetworkPolicy as follows
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: my-network-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      app: foo
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          app: foo1
          type: frontend
    - podSelector:
        matchLabels:
          app: foo2
          type: backend
    ports:
    - protocol: TCP
      port: 6379

Is the above NetworkPolicy definition going to meet my requirements?

A: yes I think so, I had to mention that manifest you wrote is applied only to that pod with label foo(restriction only to foo) and ingress traffic coming either from within the cluster or outside of it  will be blocked ... however, both pods with label foo1 and foo2 can communicate or receive communication from anywhere inside your cluster . Have you implemented it ? what network plugin did you installed ?

A: Assuming that all these three pods are in the same namespace, yes, you have defined proper NetworkPolicy. Your yaml file is applied only to that pod with label foo - ingress traffic coming either from within the cluster or outside of it will be blocked but both pods with labels foo1 frontend and foo2 backend can communicate or receive communication from anywhere inside your cluster .
Note:
If you are declaring values or objects in default namespace you don't have put it in definition - like namespace: default. By default they will be assigned to it.
See: matching-expression-networkpolicy.
Read more: declaring-network-policy, network-policies.
Take a look: guide-network-policies.


text:
Q: Abel's Summation formula help. I want to be able to show that,
\begin{equation}
\sum_{p} \log(p) p^{-s} = s \int_{1}^{\infty} \frac{\theta(t)}{t^{s+1}} dt
\end{equation}
 where $\theta(x) =\sum_{p \le x} \log p$. and $\theta(x) = O(x)$.
Using Abel's Summation formula, letting $a(n) = \log(n)$ and $\phi(n) = n^{-s}$,from the definitions here https://en.wikipedia.org/wiki/Abel%27s_summation_formula
I have,
\begin{equation}
\sum_{1 \le p \le x} \log p (x^{-s}) - \int_{1}^{x} \sum_{1 \le p \le x} \log u (u^{-s})' du
\end{equation}
Is this the right formula to use?

A: Yes, using the definition of theta function $\theta\left(x\right)=\sum_{p\leq x}\log\left(p\right)
 $ you have, using Abel summation $$\sum_{p\leq x}\frac{\log\left(p\right)}{p^{s}}=\frac{\theta\left(x\right)}{x^{s}}+s\int_{2}^{x}\frac{\theta\left(t\right)}{t^{s+1}}dt
 $$ and now, assuming $\textrm{Re}\left(s\right)>1
 $, take the limit $x\rightarrow\infty
 $.

A: I think you meant to write $\theta(x) = \sum_{p \le x} \log \boldsymbol{p}$. Anyway, the derivation is actually rather straightforward.
Here is a useful trick. Let $\chi_{E}(x)$ be the function that is $1$ if $x \in E$ and is $0$ otherwise. Then you can write $$\sum_{p \le x} \log p = \sum_p \log p \chi_{[p,\infty)}(x).$$ Since everything is nonnegative you can swap summation and integral:
$$ \int_1^\infty \frac{\theta(t)}{t^{s+1}} \, dt = \int_1^\infty \left( \sum_p \log p \chi_{[p,\infty)}(t) \right)t^{-s-1} \, dt = \sum_p \log p \int_1^\infty \chi_{[p,\infty)}(t) t^{-s-1}\, dt$$
where
$$\int_1^\infty \chi_{[p,\infty)}(t) t^{-s-1}\, dt = \int_p^\infty t^{-s-1} \, dt = \frac{1}{s} p^{-s}.$$


text:
Q: "build.js does not exist" after upgrading to Play 2.3 (requireJsShim) I have a project using Play 2.2 and am attempting to upgrade it to Play 2.3.
As part of the build process, we used a custom RequireJS config file "build.js" imported using the option "requireJsShim" in our Build.scala file.
val myProject = Project("MyProject" ....).settings(
    requireJsShim += "build.js"
)

This correctly used the configuration file "/app/assets/javascripts/build.js for the RequireJS compilation stage.
However after upgrading to Play 2.3, I'm getting the following error
/target/scala-2.10/classes/public/javascripts/build.js does not exist

It appears requireJsShim is looking for the file here, however the new SbtWeb build pipeline is instead placing it here
/skedulo/target/web/rjs/build/javascripts/build.js

The requireJsShim option no longer appears to be a documented configuration parameter, and the new options as part of the RJS pipeline don't seem to cover the same use-case. Is there a way of having requireJsSim support in Play 2.3?

A: Instead of requireJsShim use RjsKeys.mainConfig := "build"
Also check my answer to a similar question. I've put more information there:
Play 2.3 requireJs optimization and shim for multiple modules


text:
Q: Installation of mac brew vim version 8.1 I'm using brew vim which is currently at version 8.0.1850 but 8.1 has just been released and I'm wondering if there is a way to upgrade to it yet? I've done some digging and can't see an option to do it.

A: There is a pull request on homebrew's github to update the Vim formula to 8.1: https://github.com/Homebrew/homebrew-core/pull/27983
When that merges, just run brew upgrade vim.
If you want to install 8.1 yourself, you can do so by cloning and following the build instructions on the vim official repo: https://github.com/vim/vim.

A: vim 8.1 is out now in homebrew
$ brew info vim
vim: stable 8.1.0200 (bottled), HEAD
Vi 'workalike' with many additional features
https://www.vim.org/
Conflicts with:
  ex-vi (because vim and ex-vi both install bin/ex and bin/view)
Not installed
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/vim.rb
==> Dependencies
Required: perl ✘, ruby ✘
Recommended: python ✔
Optional: gettext ✔, lua ✔, luajit ✘, python@2 ✔
==> Options


text:
Q: How to use CSLA FieldDataManager to track individual property IsDirty status? In a WinForms application I want to track the IsDirty status of a specific property (besides the IsDirty status of the business object. I found some references to Csla.Core.FieldManager.FieldDataManager being able to do this via its IsFieldDirty method, but I can not find an example.
In Visual Studio Intellisense does not show which parameters are needed in the FieldDataManager's constructor. I just get errors that there is no constructor with x arguments (tested with 0 up to 4 arguments).
FieldDataManager isn't mentioned in the CSLA books.
How can I use FieldDataManager to track the IsDirty status of a property?
Is there another way to do it?
Regards,
George


text:
Q: Trust anchor for certification path not found in localhost (Android studio insecure communication) I'm following this guide for an university project: https://checkmarx.github.io/Kotlin-SCP/m3-insecure-communication/
The attack works properly, but when I change to https i get that error. Googling I've seen that maybe the problem is Android, because the Let's Encrypt SSL certificate works on local so my phone doesn't recognize it as a valid certificate (?)
Perhaps I'm not setting the certificate from Let's Encrypt right. Can someone help?


text:
Q: Non-continuous linear functional over polynomials with inner product $\langle f,g \rangle = \int_{0}^{1} f(x)g(x)dx$ Let $P(X)$ denote the set of polynomials $p:\mathbb{R} \to \mathbb{R}$, I found that the functional $\phi:P(X) \to \mathbb{R}$ such that $p \mapsto p(0)$ is linear but does not correspond to an inner product $\langle \cdot, v\rangle$. All these is done with the inner product $\langle f,g \rangle = \int_{0}^{1} f(x)g(x)dx$.
According to Riesz-Fréchet theorem, it should be the case except if $\phi$ is not continuous or $P(X)$ is not a Hilbert space with the given norm. What is the problem in this case?

A: Of course $P(X)$ is not a Hilbert space, so the theorem does not apply.
And regardless, it's clear that $\phi$ is not continuous: Let $p_n(t)=(1-t)^n$. Then you can check that $||p_n||^2=\langle p_n,p_n\rangle\to0$ although $\phi(p_n)=1$ (so in fact $\phi$ is not given by the inner product with any vector in the completion of $P(X)$; not being continuous, there's no reason it should be.)

A: $P(X)$ is not an Hilbert space since it is not complete by Stone Weirstrass, every continuous function is a limit of a sequence of polynomials.

A: $P(X)$ is for the set of $L^2$ functions, a bit like what $\mathbb{Q}$ is for $\mathbb{R}$...


text:
Q: Dot at the end of a glossary entry I Have a strange problem with my glossaries. When you compile the provided example, pdflatex adda period for the first and last glossary entry but not for the second. I added the nopostdot option to the glossaries package.
MWE
\documentclass[a4paper,12pt,dvipsnames]{report}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[nottoc,numbib]{tocbibind}
 \usepackage[french, english]{babel}
\usepackage[
    style=super, toc, nopostdot, acronym, ]{glossaries}

\makeglossaries

\begin{document}

\newglossaryentry{hypermedia} {
    name={Hyperm\'edia},
    description={Hypermédia est une extension de l'hypertexte à des données
    multimédias comme des images, sons et vidéos}
}

\newglossaryentry{kanban} {
name={Kanban},
description={La méthode Kanban permet, à l'aide d'un tableau, de visualiser
    le processus de traitement d'une tâche. Les colonnes du tableau sont les
    états possibles pour une tâche et chaque colonne contient un nombre
    maximum prédéfini de tâches simultanées. Les tâches passent alors d'un
    état à un autre selon l'avancement de projet}
}

\newglossaryentry{monkeypatching} {
    name={Monkey patching},
    description={\textit{Monkey patching} est une façon de modifier ou
    d'étendre du code sans modifier le code source original. Ceci est
    possible avec les langages de programmations dynamiques}
}

\glsaddall
\printglossaries

\end{document}

Result


text:
Q: UML diagram for OpenGL ES 2.0 state? Can anybody provide a UML diagram describing the OpenGL ES 2.0 state machine?
Ideally, such a diagram should describe thing such as textures have width, height, type, internal format, etc.; programs have attached shaders, may or may not be linked, have uniforms, etc.; et al.
The reason I would be very interested is because I often find myself wondering things such as:

*

*Are texture parameters (set with glTexParameter) associated with the current texture, or texture unit?

*Is the set of enabled generalized vector attributes part of the currently bound VBO? Or part of the current program? Or global?

Having a UML diagram of OpenGL would be tremendously useful in answering these things at a glance rather than having to pour through obscene amounts of documentation to try to figure out how all the different components play together.
I realize looking for this is a long shot because I imagine it a tremendous effort to put together. Still, I think it would be tremendously useful. Even a partial answer could help a lot. Likewise, a diagram of some version of OpenGL other than the one I'm targeting (ES 2.0) would be useful.

A: The website for the OpenGL Insights book provides a UML state diagram for the whole rendering pipeline for both OpenGL 4.2 and OpenGL ES 2.0: http://openglinsights.com/pipeline.html
This diagram roughly shows the interaction of the stages and what GL objects are involved in each state and it shows the chapter of the specification that describe these objects.
What the diagram doesn't show is the state of the objects involved, but you can find that in the specification itself. In the OpenGL ES 2.0 specification chapter 6.2 all objects and aspects are listed with their state and how you can access it.
So, if you annotate the state diagram with the table numbers from the specification you more or less have everything you want.


text:
Q: Creating custom mouseover in angular and passing $event to directive controller I'm getting an error:
TypeError: Cannot read property 'x' of undefined

Heres my directive called tooltip:
.directive('tooltip', function() {
return {
    restrict: 'A',
    controller: function($scope) {
      $scope.enter = function(evt) {
          console.log('x: ' + evt.x + ', y: ' + evt.y);
      };
    },
    link: function(scope, element, attrs) {
      element.bind("mouseenter", function() {
        scope.$apply(attrs.tooltip);
      });

    }
}

});
HTML:
<svg>
  <g pathing tooltip="enter($event)">
   ...
  </g>
</svg>

A: You aren't passing the mouseenter event to the function.
This should work
element.bind("mouseenter", function(event) {
    scope.$apply(function(){
         attrs.tooltip(event);
     });
  });

Not sure why you don't just use call from scope:
$scope.enter(event)

A: The function passed in via attrs.tooltip cannot be called directly like that.
You have to use the $parse service to invoke the function like this:
.directive('tooltip', function($parse) {
  return {
    restrict: 'A',
    controller: function($scope) {
      $scope.enter = function(evt) {
        console.log('x: ' + evt.x + ', y: ' + evt.y);
      };
    },
    link: function(scope, element, attrs) {
      var fn = $parse(attrs.tooltip);
      element.bind("mouseenter", function(event) {
        fn(scope, { $event: event });
      });
    }
  };
});

But, even better than that, why don't you just use the ng-mouseover directive
<g pathing ng-mouseover="enter($event)">
...
</g>

Example: http://plnkr.co/edit/hh0OCDWsRhYWcyhjvGiD?p=preview


text:
Q: Expected invocation on the mock once, but was 0 times, with Func(T, TResult) I appear to be having an issue with Mock.Verify that believes a method wasn't called but I can fully verify that it is.
Runnable version from Git
Unit test:
[Test]
public void IterateFiles_Called()
{
     Mock<IFileService> mock = new Mock<IFileService>();
     var flex = new Runner(mock.Object);

     List<ProcessOutput> outputs;
     mock.Verify(x => x.IterateFiles(It.IsAny<IEnumerable<string>>(),
                    It.IsAny<Func<string, ICsvConversionProcessParameter, ProcessOutput>>(),
                    It.IsAny<ICsvConversionProcessParameter>(),
                    It.IsAny<FileIterationErrorAction>(),
                    out outputs), Times.Once);

        }

Alternative Unit test: (after comment below)
[Test]
public void IterateFiles_Called()
{
     Mock<IFileService> mock = new Mock<IFileService>();
     var flex = new Runner(mock.Object);

     List<ProcessOutput> outputs;
     mock.Verify(x => x.IterateFiles(It.IsAny<string[]>(),
                        flex.ProcessFile, //Still fails
                        It.IsAny<ICsvConversionProcessParameter>(),
                        It.IsAny<FileIterationErrorAction>(),
                        out outputs), Times.Once);

}

Runner.cs:
public class Runner
    {
        public Runner(IFileService service)
        {
            string[] paths = new[] {"path1"};

            List<ProcessOutput> output = new List<ProcessOutput>();

            service.IterateFiles(paths, ProcessFile, new CsvParam(), FileIterationErrorAction.ContinueThenThrow, out output);
        }

        public ProcessOutput ProcessFile(string file, ICsvConversionProcessParameter parameters)
        {
            return new ProcessOutput();
        }
    }

When I debug I can see that service.IterateFiles is being called.  In addition as all parameters are marked with It.IsAny<T> the arguments passed don't matter (with the exception of the out parameter - my understand is this cannot be mocked).  Yet Moq disagrees the method is called.
Any ideas where I'm going wrong?

A: Basically, the problem is that something in the Verify doesn't exactly match what is there at run-time (it can be quite fickle).
I was able to get it pass via changing the code in Runner to:
service.IterateFiles<ICsvConversionProcessParameter, ProcessOutput>(paths, ProcessFile, new CsvParam(), FileIterationErrorAction.ContinueThenThrow, out output);

(Specifiying TFileFunctionParameter and TFileFunctionOutput explicitly)
Which seemed to help nail down the types for moq's verify to match.
As @Lukazoid said much better than I," Moq treats DoSomething as a different method to DoSomething."

Some candidates, since ruled out:

*

*There seems to be a mismatch between Func<string, ICsvConversionProcessParameter, ProcessOutput> and ProcessFile as ProcessFile doesn't seem to be defined as a func.

*Another potential difference I can see is string[] vs IEnumerable<string>.

*List<ProcessOutput> as the out param

A: NikolaiDante's answer together with the comments below it, essentially gives the explanation. Still, since I have investigated it a bit, I will try to write it clearly.
Your question entirely fails to show the main cause of your problem which is that the method is a generic one. We had to go to the Git files you link, to find out about that.
The method as declared in IFileService is:
void IterateFiles<TFileFunctionParameter, TFileFunctionOutput>(
    IEnumerable<string> filePaths,
    Func<string, TFileFunctionParameter, TFileFunctionOutput> fileFunction,
    TFileFunctionParameter fileFunctionParameter,
    FileIterationErrorAction errorAction,
    out List<TFileFunctionOutput> outputs);

To call it, one has to specify both the two type arguments, TFileFunctionParameter and TFileFunctionOutput, and the five ordinary arguments filePaths, fileFunction, fileFunctionParameter, errorAction, and  outputs.
C# is helpful and offers type inference with which we do not have to write the type arguments in the source code. The compiler figures which type arguments we want. But the two type arguments are still there, only "invisible". To see them, either hold your mouse over the generic method call below (and the Visual Studio IDE will show you them), or look at the output IL.
So inside your Runner class, the call really means:
service.IterateFiles<CsvParam, ProcessOutput>(paths,
  (Func<string, CsvParam, ProcessOutput>)ProcessFile,
  new CsvParam(), FileIterationErrorAction.ContinueThenThrow, out output);

Pay attention two the two types in the first line, and note that the method group ProcessFile is actually turned into a Func<string, CsvParam, ProcessOutput> even if the methods signature looks more like Func<string, ICsvConversionProcessParameter, ProcessOutput>. Delegates can be created from methods groups like that. (And it is not really relevant that Func<in T1, in T2, out TResult> is marked as contravariant in T2.)
If we inspect your Verify, then we see that type inference really sees it as:
mock.Verify(x => x.IterateFiles<ICsvConversionProcessParameter, ProcessOutput>(
  It.IsAny<IEnumerable<string>>(),
  It.IsAny<Func<string, ICsvConversionProcessParameter, ProcessOutput>>(),
  It.IsAny<ICsvConversionProcessParameter>(),
  It.IsAny<FileIterationErrorAction>(),
  out outputs), Times.Once);

So Moq cannot really verify that this is called, since the call uses a different first type argument, and also the fileFunction Func<,,> has another type. So this kind of explains you problem.
NikolaiDante shows how you can change runner to actually use the type arguments that your Verify expects.
But it feels more appropriate two change the test and keep the runner code unchanged. So what we want in the test, is:
mock.Verify(x => x.IterateFiles(It.IsAny<IEnumerable<string>>(),
  It.IsAny<Func<string, CsvParam, ProcessOutput>>(),
  It.IsAny<CsvParam>(),
  It.IsAny<FileIterationErrorAction>(),
  out outputs), Times.Once);

(type inference will give the correct TFileFunctionParameter and TFileFunctionOutput from this).
However: You have put your test class in another project/assembly than the Runner class. And the type CsvParam is internal to its assembly. So you really need to make CsvParam accessible to the test in my solution.
You can make CsvParam accessible either by making the class public, or by making the test assembly a "friend assembly" of the MoqIssue assembly by including the attribute:
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("MoqIssueTest")]

in some file belonging to the MoqIssue project.
Note that the Moq framework has no problems with an internal type, so you do not have to turn any of Moq's assemblies into "friends" for this. It is only required to express the Verify easily (i.e. without ugly reflection) in your MoqIssueTest assembly.


text:
Q: Django seems to be caching datetime.now() I have a model that looks like this:
class Item(models.Model):
    ...
    publish_date = models.DateTimeField(default=datetime.datetime.now)
    ...

And a manager that looks like this:
from datetime import datetime

class ItemManager(Manager):
    def published(self):
        return self.get_query_set().filter(publish_date__lte=datetime.now()

And a view that looks like this:
class ItemArchive(ArchiveIndexView):
    queryset = Item.objects.published()
    date_field = 'publish_date'

The idea being that I can call Item.objects.published() and get a queryset of all published Items.
The problem is that Django seems to be executing the datetime.now() call in the manager when the server is started and then caching that value. So if today is May 24th, and I created an Item with a publish date of May 23rd, and started the server on May 22nd, that May 23rd item will not show up in the ItemArchive view. As soon as I restart Apache, the May 23rd item shows up in the view correctly.
How can I force Django to execute datetime.now() every time the manager is called?

A: Don't use the queryset class variable, and override get_queryset instead. In general, I think queryset is a bit of a red herring. If you just specify model instead, Django automatically sets the queryset to self.model.objects.all(). If you need any filtering, 99 times out of 100 you'll need to override get_queryset to be thread-safe. Try the following instead.
class ItemArchive(ArchiveIndexView):
    model = Item
    date_field = 'publish_date'

    def get_queryset(self):
        return super(ItemArchive, self).get_queryset().published()

A: I believe this is caused by your view defining queryset = Item.objects.published() as a class variable. This line will be executed once, when your ItemArchive class is initially imported. You should move that line into a method where it will be executed each time a view is called.

A: First, just use models.DateTimeField(auto_now_add=True)
Edited:
Second, use get_queryset method:
class ItemArchive(ArchiveIndexView):
    date_field = 'publish_date'

    def get_queryset(self):
        return Item.objects.published()


text:
Q: How can I get a relative path from listed files? I'm writing a method copies all files for specified Path to a local directory.
How can I get a relative path name from anyone of listed files?
FileSystem fs = ...;

// remote directory whose files are copied from
org.apache.hadoop.fs.Path path = new Path("/path/to/the/directory");

// local directory into which files are copied.
java.nio.file.Path directory = ...;

for (LocatedFileStatus status : fs.listFiles(path, true)) {

    // status: HdfsNamedFileStatus{path=hdfs://.../path/to/the/directory/.../...; ...}
    // status.getPath(): hdfs://.../path/to/the/directory/.../...

    // How can I get a relative path name for each status
    // against the source path
    // so that I can createDirectories on the target directory?

    // I need the .../... part from hdfs://.../path/to/the/directory/.../...
    // so that I can call Files.createDirectories(directory.resolve(.../...))
}

A: I think you can use:
public FileStatus[] listStatus(Path p)

To get the contents of a directory.


text:
Q: Backface visibility on Firefox and Bootstrap 4 carousel I'm developing a website that has a Bootstrap 4 slider (carousel), I had some problem in Chrome because I got a blurry text when I activated the slider.
I solved this problem on Chrome with this code:
.carousel-item {
    -webkit-backface-visibility: unset!important;
    backface-visibility: unset!important;
}

but now I got an issue on Firefox. The slider doesn't slide well.
This is my website on my test machine:
http://www.matrix-test.com/roofing/
and as you can see in Firefox there is a problem.


text:
Q: Should unit/functional tests assume the parts of the application NOT being tested are operating correctly? I'm new to test-driven development but have a new application I'm working on. I have some of the basic functionality already created but thought this might be a good chance to start using test-driven development. I'm writing the test requirements to cover the main features using this basic outline (thanks, wikipedia):

*

*Setup

*Execution

*Validation

*Cleanup

And then, when I begin to code the tests, I was going to follow this workflow:

*

*Add a test

*Run all tests & verify the new test fails

*Write code to cause the new test to pass (quick/dirty, tech debt is fine here)

*Run all tests & verify all pass

*Refactor the code to reflect best practices, be more maintainable, etc.

I understand that tests should be independent of each other, but a question arises when writing a test for a specific feature (B) of the application when that feature relies on the functionality of a different feature (A) of the application that is covered by a different test. Is it appropriate for the test of feature B to assume that the functionality of feature A is operational? Or would it be better to manually perform whatever steps feature A does inside the test code for the feature B test? What happens when there is a bug in feature A? That would break both tests and perhaps cause some ambiguity regarding what the issue is. To me it seems like the right choice would be to not allow feature B test to run feature A, but then I might just end up replicating feature A code in feature B test code. Or the test code might become too large or unmaintainable.

A: There are at least two ways of doing this.

*

*As you say, write a test for feature (B) which relies on feature (A). When the test runs and executes part of (B) it also makes use of (A).

*Or write a test for feature (B) which relies on a mocked out (A). Because your test is very fine-grained, you will know exactly which part of (A) will be used and what the return values will be for calls to (A). A mock is more useful when (A) is a large component that is difficult to setup, but where you will only be using a small part of it.

When there is a bug in feature (A), your tests for (A) will pick it up, although it can be difficult to interpret the test failures when this happens.

A: If you are using TDD as part of your development process, there are two distinct "running the tests" use cases to think about.
When you are refactoring, you don't typically care how many tests fail when you verify a refactoring.  If the count of tests is zero, then you keep going; if the count of tests is not zero, then you can discard your changes, confirm that you are back in a passing state, and try to make the change again with more care.
When you are merging, things get a lot more interesting; we now have many candidate changes that could explain why tests are failing.  In that case, precise test failures can help.
If A is testable (in the sense that including the real implementation of A doesn't violate one of our other concerns about the test being fast, reliable, deterministic, etc), and stable (doesn't change often), then it is common that the investment odds favor just using it in the test.
When A is unstable - especially in the case where the observable behavior of A is unstable -- then we may want to consider techniques that would isolate the tests of B from that instability.
The two most common approaches here are to either (a) use a stable substitute/test-double to stand in for the role played by A or (b) to use the real A when we create the expression that will be used to evaluate B.
Consider this trivial example
A(x):
  return 2 * x

B(y):
  if y:
    return A(7)
  // ...

If A is stable, we can just ignore it as an implementation detail when we write our tests
assert 14 == B(true)

But an equivalent way of describing the same behavior would be to use the language of A.
assert A(7) == B(true)

Read: B(true) returns the same value as A(7)
Useful reading: James Shore's Testing Without Mocks.


text:
Q: React JSX: setting variable leads to page not being loaded I have a question regarding setting a specific variable based on another.
I have stored the gender of the user in the database as U, M, F.
U stands for Undefined, M for Male, F for Female etc.
now I want to show the text Undefined instead of U and Male instead of M.
export const AccountTile: React.FC = () => {
  const [isEditing, setIsEditing] = React.useState(false);
  const [setAccountUpdate, { data, error }] = useAccountUpdate();
  const { data: user } = useUserDetails();

  let userGender = user.gender;
  if(userGender === "U"){
    userGender = "Undefined";
  }

  React.useEffect(() => {
    if (data && !error) {
      setIsEditing(false);
    }
  }, [data, error]);
  return (
    <S.TileWrapper>
      <Tile>
        <S.Wrapper>
          <S.Header>MY DATA</S.Header>
          <S.Content>
            <S.HeaderSmall>
              Personal details
              {!isEditing && (
                <IconButton
                  name="edit"
                  size={22}
                  onClick={() => setIsEditing(isEditing => !isEditing)}
                />
              )}
            </S.HeaderSmall>
            {isEditing ? (
              <AccountUpdateForm
                initialValues={{
                    birthday: (user && user.birthday) || "",
                  firstName: (user && user.firstName) || "",
                  gender: (user && user.gender) || "",
                  lastName: (user && user.lastName) || "",

                }}
                handleSubmit={data => {
                  setAccountUpdate({ input: data });
                }}
                hide={() => {
                  setIsEditing(false);
                }}
              />
            ) : (
              <S.ContentOneLine>
                <Attribute
                  description="First Name"
                  attributeValue={(user && user.firstName) || "-"}
                />
                <Attribute
                  description="Last Name"
                  attributeValue={(user && user.lastName) || "-"}
                />
                <Attribute
                  description="Birthday"
                  attributeValue={(user && user.birthday) || "-"}
                />
                <Attribute
                  description="Gender"
                  attributeValue={(user && user.gender) || "-"}
                />
              </S.ContentOneLine>
            )}
          </S.Content>
        </S.Wrapper>
      </Tile>
    </S.TileWrapper>
  );
};

However once I add this part, the page stops working.
let userGender = user.gender;
  if(userGender === "U"){
    userGender = "Undefined";
  }

This doesn't produce any errors I can see however the page remains blank, doesn't get loaded when this part is added. I didn't even get to using the set variable. Does anyone have an idea on why this happens?
Otherwise, when this part is removed, the code works fine and 'U' is printed in the gender field.
(React, and front-end in general are new to me )
Thanks in advance.

A: One issue I can see is data can be undefined. So you need to check before picking out gender from data.
let userGender = user && user.gender;
  if(userGender === "U"){
    userGender = "Undefined";
}

Also instead of assigning it into a separate variable, you can use a map to store the name mappings and define a function to get user's gender from user object.
const getGender = (user) => {
    const nameMap = {
        U: 'Undefined',
        M: 'Male',
        F: 'Female'
    };
    return nameMap[user?.gender] || "";
}

And use it like
...
<AccountUpdateForm
    initialValues={{
        birthday: (user && user.birthday) || "",
    firstName: (user && user.firstName) || "",
    gender: getGender(user),
    lastName: (user && user.lastName) || "",

    }}
    handleSubmit={data => {
    setAccountUpdate({ input: data });
    }}
    hide={() => {
    setIsEditing(false);
    }}
...


text:
Q: Knowledge sources for Apache Cassandra I'm planning to start project with NoSQL for data storage. I was trying to find informations about Cassandra in google but I've found very basic info.
Anyone know where I can find good source of knowledge about Cassandra (planing data structure, working with data (maybe migrating from mysql?) etc)?

A: DataStax has comprehensive Cassandra documentation at http://www.datastax.com/docs/1.0/index.
"Cassandra High Performance Cookbook" is a decent book.  O'Reilly's "Definitive Guide" is actually even worse than a 0.7 book; it's a mix of 0.6, 0.7, and stuff that was cut from 0.7 before release.

A: The best source of information is the Cassandra wiki at http://wiki.apache.org/cassandra/.
There's also an O'Reilly book, Cassandra: The Definitive Guide, but this is for Cassandra 0.7, so is a bit out of date now.

A: Found this very useful - http://www.datastax.com/events/cassandrasf2011/presentations


text:
Q: Seleção com Dapper usando cláusula IN A minha ideia é gerar uma pesquisa no meu banco usando a cláusula in através do Dapper. Por exemplo:
select * from product
where CasNo in(@filtro)

Lembrando que dentro desse @filtro tem uma lista de CasNo que é do tipo List<String>.
Testes
List<Product> IProductRepository.RetornarPesquisaProdutos(List<string> filtroId) =>
    conn.Query<Product>(
        @"
        SELECT
            pr.IdProduct as IdProduct,
            pr.Name as Name,
            sup.Name as Supplier,
            sup.IdSupplier as IdSupplier
        FROM Product pr
            FULL OUTER JOIN Supplier AS sup ON (pr.IdSupplier = sup.IdSupplier)
        where
            pr.IdProduct in (@filtroId) or
            pr.CASNo     in (@filtroId)
        ORDER BY pr.CommercialName",
        param: new { filtroId }).ToList();

Isso não deu certo.
Também tentei fazer como eu passava no ADO.NET (que deu certo lá, porém era de uma forma muito escrota que eu tinha feito) concatenando direto nesta lista todos os itens que eu precisava. Exemplo filtro = "'123-1', '326-3', '684-8'"); e mandava esse filtro direto na minha Query sem fazer o cmd.Parameters.AddWithValue(filtro);.
Porém agora eu preciso fazer no Dapper essa ideia de passar uma lista dentro do IN

A: É só tirar os parênteses. O Dapper já faz isso.
select * from product
where CasNo in @filtro


text:
Q: how to show products json in api I am stuck to a problem, I am unable to get the products json in magento2? Can any one solve my problem, I get the token successfully but unable to get the products json in php
Here is my following php code
<?php
$userData = ["username" => "admin", "password" => "admin_password"];

    $ch = curl_init("https://www.experian-ccmp.com/rest/V1/integration/admin/token");
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Content-Lenght: " . strlen(json_encode($userData))));

    $token = curl_exec($ch);

    $ch = curl_init("https://www.experian-ccmp.com/rest/V1/products");
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); //  method
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($emailcontent));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", "Authorization: Bearer " . json_decode($token)));
    $result = curl_exec($ch);
    echo $result;
    die;
    $result = json_decode($result, 1);
    echo '<pre>';print_r($result);
?>

here is what I get the response in json, field name is required
{"message":"%fieldName is a required field.","parameters":{"fieldName":"product"},"trace":"#0 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/framework\/Webapi\/ServiceInputProcessor.php(131): Magento\\Framework\\Webapi\\ServiceInputProcessor->processInputError(Array)\n#1 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/module-webapi\/Controller\/Rest\/InputParamsResolver.php(101): Magento\\Framework\\Webapi\\ServiceInputProcessor->process('Magento\\\\Catalog...', 'save', Array)\n#2 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/module-webapi\/Controller\/Rest.php(299): Magento\\Webapi\\Controller\\Rest\\InputParamsResolver->resolve()\n#3 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/module-webapi\/Controller\/Rest.php(216): Magento\\Webapi\\Controller\\Rest->processApiRequest()\n#4 \/home2\/bhagnani\/public_html\/experian-ccmp\/var\/generation\/Magento\/Webapi\/Controller\/Rest\/Interceptor.php(37): Magento\\Webapi\\Controller\\Rest->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#5 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/framework\/App\/Http.php(135): Magento\\Webapi\\Controller\\Rest\\Interceptor->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#6 \/home2\/bhagnani\/public_html\/experian-ccmp\/vendor\/magento\/framework\/App\/Bootstrap.php(258): Magento\\Framework\\App\\Http->launch()\n#7 \/home2\/bhagnani\/public_html\/experian-ccmp\/index.php(39): Magento\\Framework\\App\\Bootstrap->run(Object(Magento\\Framework\\App\\Http))\n#8 {main}"}

Thanks for the comments in advance

A: Instead of
$ch = curl_init("https://www.experian-ccmp.com/rest/V1/products");
Try this to get all product list
$ch = curl_init("https://www.experian-ccmp.com/rest/V1/products?searchCriteria=");
Hope this helps!

A: Your URL are ok.
Only change:
$ch = curl_init("https://www.experian-ccmp.com/rest/V1/products");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); //  method

to:
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); //  method
Check: http://devdocs.magento.com/swagger/


text:
Q: Generate random samples from $f(x) \propto [1 + \sin^2(3 x)] [ 1+ \cos^4(5x)] e^{-x^2/2}$ using slice sampler I am trying to understanding the Example 8.3 of Monte Carlo Statistical Methods from Robert and Casella. The example shows how to generate from the density
$$f(x) \propto [1 + \sin^2(3x)] [ 1+ \cos^4(5x)] e^{-x^2/2}$$
using slice sampler.

Example 8.3 Consider the density proportional to $$
  (1+\sin^2(3x))\,(1+\cos^4(5x))\,\exp\{-x^2/2\}. $$ The corresponding
  functions are, for instance, $f_1(x)=(1+\sin^2(3x))$,
  $f_2(x)=(1+\cos^2(5x))$, and $f_3(x)=\exp\{-x^2/2\}$. In an iteration
  of the slice sampler, three uniform $\mathcal U([0,1])$ $u_1,u_2,u_3$ are
  generated and the new value of $x$ is uniformly distributed over the
  set $$ \left\{ x:\, |x| \le \sqrt{-2\log\omega_3}\right\} \cap \left\{
  x:\, \sin^2(3x) \ge 1-\omega_1 \right\} \cap \left\{ x:\, \cos^4(5x)
  \ge 1-\omega_2 \right\} \,, $$ which is made of one or several
  intervals depending on whether $\omega_1=u_1 f_1(x)$ and $\omega_2=u_2
  f_2(x)$ are larger than $1$.

My doubth is how can I generate an uniform distribution over the set $A$?
I am using the following R code, but the result is not the expected one when comparing theoretical and empirical distributions.
f1 = function(x) 1 + sin(3 * x)^2
f2 = function(x) 1 + cos(5 * x)^4
f3 = function(x) exp(- x^2 / 2)

xs = seq(-3, 3, l = 10000)
x = c()
x0 = 0
for(j in 1:5000)
{
  cat(j, "\n")
  w1 = runif(1, 0, f1(x0))
  w2 = runif(1, 0, f2(x0))
  w3 = runif(1, 0, f3(x0))

  A1 = ifelse(w1 < 1, NaN, sample(xs[f1(xs) >= w1], 1))
  A2 = ifelse(w2 < 1, NaN, sample(xs[f2(xs) >= w2], 1))

  i3 = max(-3, -sqrt(-2 * log(w3)))
  s3 = min(sqrt(-2 * log(w3)), 3)
  A3 = runif(1, i3, s3)

  At = c(A1, A2, A3)
  At = At[!is.na(At)]

  x[j] = sample(At, 1)

  x0 = x[j]

}

fx_propto <- function(x) (1 + sin(3 * x)^2) * ( 1 + cos(5 * x)^4) * exp(-x^2 / 2)
fx <- function(x)
{
  const = integrate(fx_propto, -3, 3)$value
  fx_propto(x) / const
}

fdens = sapply(xs, fx)
hist(x, breaks = 100, probability = T)
lines(xs, fdens, col = "blue", type = "l")

Obs.: I truncated the distribution on $[-3, 3]$.

A:
Debugging: In your R code, you generate three Uniforms over the three
  component sets of $A$ and pick one of the three at random: there is no reason for this
  outcome to (i) belong to $A$ and (ii) to be uniformly distributed over
  $A$.

Here is the R code that we used for this example, verbatim:
x<-rep(0,5000)
for (i in 2:5000){
  omega1<-(1+sin(3*x[i-1])^2)*runif(1)-1
  omega2<-(1+cos(5*x[i-1])^4)*runif(1)-1
  omega3<-sqrt(-2*log( runif(1)*exp(-x[i-1]^2/2)))
  repeat{
      y<--omega3+2*omega3*runif(1)
      if ((sin(3*y)^2>omega1)&&(cos(5*y)^4>omega2)) break
      }
  x[i]<-y
  }
plo<-hist(x,nclass=75,col="grey",proba=T,xlab="x",ylab="",main="")
labs<-seq(-3,3,.01)
dense<-(1+sin(3*labs)^2)*(1+cos(5*labs)^4)*exp(-labs^2/2)
dense<-dense*max(plo$density)/max(dense)
lines(labs,dense,col="sienna4",lwd=2)

returning the following graph (as in the book):

The explanation for the R code being justified as a Uniform simulation over $A$ is that we simulate uniformly over the component set
$$A_3=\left\{x:\ |x| \leq \sqrt{-2 \log w_3 } \right\}$$
namely
y<--omega3+2*omega3*runif(1)

until the outcome belongs to $A$:
if ((sin(3*y)^2>omega1)&&(cos(5*y)^4>omega2)) break

which is a rudimentary form of accept-reject since $A\subset A_3$.


text:
Q: Adding search parameter to url to enable direct search from address bar I have a few old sites that I want to add routing parameters. They were coded without using mvc so there are no global.asax with the handy MVC settings.
Currently I have a page with the url abc.com/xyz that has a search function. I can input a query which would send  me to another page but it has the same url. I want to make it so that if i put some variation of the url  abc.com/xyz?search='what_You_Query', it gives me the searched page. Right now that url sends me to the page where I input my query.
The website is coded in C# and html and saved in aspx files. The webpages also make use of jscripts
I'd appreciate any help I can get
Edit: Seems like there was some confusion, there is a search box that allows the user to query on the webpage. What I want is to allow users to directly link to a searched page.

A: You'd need to capture that on the page load - check the query string (https://msdn.microsoft.com/en-us/library/ms524784%28v=vs.90%29.aspx) and if search is in it, redirect to the search page.
MODIFIED TO INCLUDE MORE DETAILS
I'm assuming your working with web forms (Microsoft alternative to MVC).  You would need to add a server-side (http://www.seguetech.com/blog/2013/05/01/client-side-server-side-code-difference) Page_Load event (https://msdn.microsoft.com/en-us/library/6w2tb12s.aspx).  There the code would look something like this:
protected void Page_Load(object sender, EventArgs e)
{
    if(Request.QueryString["search"] != null)
        Response.Redirect("/search?" + UrlEncode(Request.QueryString["search"]), true);
}

Please note I have not tested the code and am going by memory a bit here - but that should do the trick.


text:
Q: Interpreting ANCOVA results independent variable gender. Gender is a binary column consisting of 0 and 1.From the linear model summary below my observations are:

*

*Gender is significant for height dependent variable. Which means height and weight's relationship for males and females are different.

*Weight is significant as well which means weight influences height.
I am not sure about my first assumption. Would you say my statement is right and gender significance shows that for males and females weight and height relationship are different? Or would you say just being male and female effects height and it's significance does not show anything about the relationship between weight and height?
Call:
lm(formula = height ~ weight + as.factor(gender), data = example.data)

Residuals:
     Min       1Q   Median       3Q      Max
-26.8555  -6.0428   0.0415   6.0871  26.5539

Coefficients:
                  Estimate Std. Error t value Pr(>|t|)
(Intercept)       -9.76841    1.87468  -5.211 2.19e-07 ***
weight             0.49532    0.02278  21.741  < 2e-16 ***
as.factor(gender)0 3.09201    0.48129   6.424 1.86e-10 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 8.526 on 1293 degrees of freedom
Multiple R-squared:  0.2705,    Adjusted R-squared:  0.2694
F-statistic: 239.7 on 2 and 1293 DF,  p-value: < 2.2e-16
```


text:
Q: User defined hash function for unordered map I have defined my own hash function for an unrorderd_map. But I am unable to search in the container using the find function. I have tried debugging using a print statement within the hash function and it generates the same hash value which was generated while inserting the key/value. It would be great if someone could point out the error. I am using Eclipse IDE on windows and I am compiling with -std=c++11
typedef struct tree node;

struct tree
{
int id;
node *left;
node *right;
};

class OwnHash
{
public:
    std::size_t operator() (const node *c) const
    {
       cout << "Inside_OwnHash: " <<std::hash<int>()(c->id) + std::hash<node *>()(c->left) + std::hash<node *>()(c->right) << endl;
       return std::hash<int>()(c->id) + std::hash<node *>()(c->left) + std::hash<node *>()(c->right);
    }
};

int main()
{
std::unordered_map<node *,node *,OwnHash> ut;

node * one = new node;
one->id = -1;
one->left = nullptr;
one->right = nullptr;
ut.insert({one,one});

node * zero = new node;
zero->id = 0;
zero->left = NULL;
zero->right = NULL;
ut.insert({zero,zero});

node * cur = new node;
cur->id = 5;
cur->left = zero;
cur->right = one;
ut.insert({cur,cur});

for (auto& elem : ut)
{
    std::cout << "key: " << elem.first << "\t" << "value: " << elem.second->id << std::endl;
}

node * parse = new node;
parse->id = 5;
parse->left = zero;
parse->right = one;

std::unordered_map<node *,node *>::const_iterator got1 = ut.find (parse);

if ( got1 == ut.end() )
    std::cout << "not found";
else
    std::cout << got1->first << " is " << got1->second->id << std::endl;

return EXIT_SUCCESS;
}

    Output:
    Inside_OwnHash: 4294967295
    Inside_OwnHash: 0
    Inside_OwnHash: 22946517
    key: 0xaf11b0   value: 5
    key: 0xaf1180   value: 0
    key: 0xaf1150   value: -1
    Inside_OwnHash: 22946517
    not found

A: Hash is not enough, you must implement equality comparison too!
The hash has to be a function such that if the items are equal, they hash equal. But since the items may be arbitrarily complex and the hash result is just size_t, the opposite implication does not and cannot hold. So to find the exact element, you need an equality comparison too.
When looking up, the hash function points it to the right "bucket", but there may be multiple elements in it or there may be an element there, but not the one you are looking for. So it takes all elements in the bucket and compares each to the one you are searching.
Now you provided a hash function, but did not provide equality comparator. So it uses the default, which is operator== and that is for pointers defined as comparing the addresses. And the addresses are not equal. You need to provide equality functor that compares the values.


text:
Q: $360\times 60$ nautical mile is not equal with $6400$ km of earth radius One degree on a great circle of earth equals to $60$ Nautical Miles. Hence:
$\ 360 \times 60 = 21,600$ M (Nautical Mile)
$\ 21,600M \times 1852$ Meters $= 40,003,200$ Meters $= 40,003.2$ Kilometers
While the radius of earth is $6400$ Kilometers. What is problem with my calculation?
UPDATE: The question is wrong in nature. I confused the radius of earth with circumference of the earth!

A: You need to divide by $2\pi$ to get the radius.  You have calculated the circumference.


text:
Q: Is this error related to sfDoctrinePlugin or Symfony? How can I fix this? I have a project created using Symfony 1.4.15. Because I like Doctrine :) I created a admin module using the command: "doctrine:generate-admin". All works fine when I "save & add" but when I "save" only I get this error:

500 | Internal Server Error | Doctrine_Record_UnknownPropertyException |
  Unknown record property / related component "name" on "Ncargo"

and I not know how to fix this, any help on this? This happen with all the modules generated by doctrine:generate-admin task.
Cheers and thanks in advance

A: In this case, I would recommand to:
rebuild the model classes: ./symfony doctrine:build --all-classes
clear the cache: ./symfony cc
What's happend here is that Doctrine think there is a "name" field on your model.
You should also send us your generator.yml, have you set any "name" in it? Send us your model too.


text:
Q: Saving output of mplayer How can I save the output of mplayer?
For example, if to play slowly an mp3 file, I use mplayer -speed 0.6 file.mp3. However, mplayer -speed 0.6 file.mp3 > file2.mp3 won't save the output to a file (which should be just the same, but slower).
Any alternative command-line solution is welcome too, I am not tied to mplayer.

A: Try mencoder instead:
mencoder -speed 0.6 -o output_file file.mp3


text:
Q: Showing a set of the form $\bigcup_{x \in E} [x - 1 , x + 1]$ is measurable Let $E \subseteq \mathbb{R}$ be a subset of $\mathbb{R}$, and consider $F = \bigcup_{x \in E} [x - 1, x + 1]$. I know that under the assumption that $E$ is measurable, the set $F$ is measurable, but I can't think of an example where $F$ is not measurable. Is $F$ always measurable, independent of whether $E$ is measurable? If not, what would be a counterexample?
Thanks.
EDIT: Measurability is meant with respect to Lebesgue measure

A: $F$ is always measurable, but it is a bit tricky to argue that this is tha case. The point in here is that if $d(x,y)<2$ then $[x - 1, x + 1] \cup [y - 1, y + 1]$ is a single closed interval.
From here, you can deduce that $F$ is a disjoint union of intervals of diameter at least 2. This can probably be faster proven by looking at the connected components. Show that any such union has only countably many terms.