text:
Q: A veces crea las cardview y a veces no Una consulta. En mi código estoy creando una lista de CardViews a partir de un JSONArray que reccorro con un for y voy llenando una lista para crear las CardViews, solo que a veces si las crea y a veces no, no se por que, les dejo mi código.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_promos_por_concepto);

    Intent promosIntent = getIntent();
    final Bundle promosExtras = promosIntent.getExtras();
    cp_id = promosExtras.getString("cp_id");
    listaPromosConcepto = new ArrayList<>();

    //Llamamos método para crear cards
    CreaCard();

}

public void CreaCard(){
    //Recibimos la respuesta del Json filtrada por el cp_id
    Response.Listener<String> promosConceptoListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JSONArray promosArray = new JSONArray(response);

                for (int y = 0; y < promosArray.length(); y++) {

                    JSONObject promosObjectArray = promosArray.getJSONObject(y);
                    JSONArray promoConceptoArray = promosObjectArray.getJSONArray("promos");

                    for (int i = 0; i < promoConceptoArray.length(); i++) {

                        JSONObject promoConcepto = promoConceptoArray.getJSONObject(i);
                        String promoDesc = promoConcepto.getString("prom_desc");
                        String neg_Nomb = promoConcepto.getString("neg_nombre");
                        String calificacion = promoConcepto.getString("calificacion");
                        String promImgUrl = promoConcepto.getString("logo");
                        listaPromosConcepto.add(new FuentePromosPorConcepto("Título promo", neg_Nomb, promoDesc, promImgUrl, calificacion));

                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    };

    PromosInfoConceptoRequest promosInfoConceptoRequest = new PromosInfoConceptoRequest(cp_id, promosConceptoListener);
    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    queue.add(promosInfoConceptoRequest);

    final RecyclerView recyclerPorConcepto = findViewById(R.id.recyclerContenedorDetalle);
    recyclerPorConcepto.setHasFixedSize(true);
    LinearLayoutManager layout = new LinearLayoutManager(getApplicationContext());
    layout.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerPorConcepto.setAdapter(new PromosPorConceptoAdapter(listaPromosConcepto));
    recyclerPorConcepto.setLayoutManager(layout);
    PromosPorConceptoAdapter adapter = new PromosPorConceptoAdapter(listaPromosConcepto);
    recyclerPorConcepto.setAdapter(adapter);
}

A: Lo que creo que pasa es que estas haciendo una peticion con volley. Al ser tu peticion asincrona, no sabes en que momento tienes informacion en tu arreglo listaPromosConcepto. Algunas aveces cuando inicializas tu adapter, puede o no haber llegado la informacion que solicitaste con volley (por eso aveces muestra algo y aveces no)
Lo que tienes que hacer es despues de recibir los datos de tu peticion hacer un notifyDataSetChanged en tu adapter, para refrescar el contenido de tu lista.
private PromosPorConceptoAdapter adapter;

public void CreaCard(){
    adapter = new PromosPorConceptoAdapter(listaPromosConcepto);
    Response.Listener<String> promosConceptoListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //etc etc rellenar arreglo
                //hacer esto fuera de los 2 ciclos for
                adapter.notifyDataSetChanged();
            }
    };

Nota: estas asignandole 2 veces a tu recyclerPorConcepto el adapter, hazlo solo 1 vez.


text:
Q: Please identify this equation: $\nabla^2 \mathbf F -k^2 \mathbf F = \mathbf A$ Is this equation
$$
\nabla^2 \mathbf F -k^2 \mathbf F = \mathbf A
$$
somehow named? F and A are vector fields. I guess inhomogeneous sign reversed Helmholtz equation isn't appropriate ...

redpajama_set_name: RedPajamaStackExchange


text:
Q: String.join array from last element I have a scenario where I am getting a comma separated string LastName, FirstName. I have to convert it into FirstName LastName.
My code is below:
Public static void main(string [] args)
{
      var str = "Lastname, FirstName":
      var strArr = str.Split(',');
      Array. Reverse(strArr);
      var output = string.join(" ", strArr);
}

Is there a better way to do this, like in one line or using LINQ?

A: Yes there is already a Reverse extension method for IEnumerables:
var output = string.Join(" ",str.Split(',').Reverse());

A: Use Aggregate and Trim your names after splitting, you do not need reversing.
 str.Split(',').Aggregate((lname, fname) => fname.Trim() + " " + lname.Trim())

A: This takes care of a lot of the various edge cases. You mentioned one but did not include it in your initial question so I assume there could be others.
var tests = new[]{"Lastname, FirstName", "Lastname, ", ", FirstName", "Lastname", "FirstName"};
foreach(var str in tests)
{
    var strArr = str.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
        .Where(x => !string.IsNullOrWhiteSpace(x))
        .Reverse()
        .Select(x => x.Trim());
    var output = string.Join(" ", strArr);
    Console.WriteLine(output);
}

Working Fiddle

A: Below is my new code:
Public static void main(string [] args)
    {
          var str = "Lastname, FirstName":
          var strArr = str.Split(',').Select(p=>p.Trim()).ToArray();
          var output = string.join(" ", strArr.Reverse());
    }


text:
Q: How to proportional(Aspect Ratio) image using ffmpeg function? Why following function is not execute in php ? Same function is using for video. Please correct me if anything wrong with syntax. I have to proportion watermark as per image width and height. If there is any other command then please help me.
$command = "ffmpeg -i input.jpg -i watermark.png -filter_complex
    \"[1:v][0:v]scale2ref=(W/H)*ih/8:ih/8[wm][base];[base][wm]overlay=10:10\"
    -pix_fmt yuv420p -c:a copy output.jpg";

exec($command);

A: You are adding downscaling so the overlay will be smaller. Remove the extra stuff:
$command = "ffmpeg -i input.jpg -i watermark.png -filter_complex
    \"[1:v][0:v]scale2ref[wm][base];[base][wm]overlay=10:10\"
    -frames:v 1 output.jpg";

exec($command);


text:
Q: How do I reset the control strip on the touch bar to the default settings? How do I reset the control strip on the touch bar to the default factory settings? I've tried searching for how to do this but have only found information on how to restart the touch bar process.

A: This was tested using macOS Monterey.

*

*Open Terminal.

*Type the following. If prompted, type your password.

defaults delete com.apple.controlstrip && sudo pkill TouchBarServer

The touch bar will turn off momentarily, but the TouchBarServer process should restart fairly quickly and the touch bar will be restored to the default factory settings.


text:
Q: Ghostscript adds whitespace no matter what bounding box I use I'm trying to convert a page of a PDF to an image. I'm successful with most PDF's I've tried with but this one in particular always ends up with a lot of whitespace on one side or strange scaling.
I've tried every combination of every fixed media, fixed resolution, fit page, use crop/bleed/trim/art box, etc. parameter to fix the issue but nothing does it. The best I get is the right content size but offset and chopped off.

Here's what it should look like, according to every PDF reader I've tried:

Here's a link to the PDF (8 MB) for testing.
https://drive.google.com/file/d/1ErS3KxADb1YAdzM7FG7T5dO8QnW4l1AQ/view?usp=sharing
Edit 1:
Here's what it looks like using just -dUseCropBox without a cropbox override:

I'm using Ghostscript.NET with very simple code. I create a rasterizer, call Ope(PDF file, ghostscript dll in bytes), then GetPage(DPI, page number). To use other flags I add a custom switch to the rasterizer before calling open
using(var rasterizer = new GhostscriptRasterizer()) {
    //rasterizer.CustomSwitches.Add("-dFIXEDMEDIA");
    //rasterizer.CustomSwitches.Add("-dFIXEDRESOLUTION");
    //rasterizer.CustomSwitches.Add("-dPSFitPage");
    //rasterizer.CustomSwitches.Add("-dFitPage");
    //rasterizer.CustomSwitches.Add("-dPDFFitPage");
    //rasterizer.CustomSwitches.Add("-dUseCropBox");
    //rasterizer.CustomSwitches.Add("-dPrinted");
    //rasterizer.CustomSwitches.Add("-dUseBleedBox");
    //rasterizer.CustomSwitches.Add("-dUseTrimBox");
    //rasterizer.CustomSwitches.Add("-dUseArtBox");
    //rasterizer.CustomSwitches.Add("-sPAPERSIZE=letter");
    //rasterizer.CustomSwitches.Add("-dORIENT1=true");
    //etc

    rasterizer.Open(pdfFilePath, ghostscriptDLL);

    img = rasterizer.GetPage(dpi, pageNumber);
    img.Save(pageFilePath, imageFormat);
}

I'll try again with the latest version of just ghostscript (no .NET) and see if that makes a difference.
Edit 2:
Using just gswin64c version 9.55.0 and -dUseCropBox works as KenS said. Since I don't need Ghostscript.NET to do that, that's a good resolution.

A: Using just gswin64c version 9.55.0 and -dUseCropBox works as KenS said. Since I don't need Ghostscript.NET to do that, that's a good resolution.


text:
Q: imagecopyresampled() expects parameter 5 to be long I work with PHP on my project, and my friend use this code :
function imagecopyresampled($out, $in, $dstX, $dstY, $srcX=0, $srcY=0, $dstW, $dstH,        $srcW, $srcH)
{
    if($this->GD_VERSION==2)
        return imagecopyresampled($out, $in, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
    else
        return imagecopyresized($out, $in, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);
}

and when I whant to upload an image I receive this error :

Warning: imagecopyresampled() expects parameter 5 to be long, string
  given in
  /home/mbeuser/public_html/nephrogest/includes/common/image/ImageFilter.class.php5
  on line 917

this is line 917:
return imagecopyresampled($out, $in, $dstX, $dstY, $srcX,
                          $srcY, $dstW, $dstH, $srcW, $srcH);

A: Remove the ='' that appear in the parameter list of the function itself.

A: The errormessage tells you: the function needs the fifth parameter to be an integer (long) value, not a string, like in your case.

A: Within your function, the 5th and the 6th parameters are strings :
function imagecopyresampled($out, $in, $dstX, $dstY, $srcX='', $srcY='', $dstW, $dstH,        $srcW, $srcH)
                                                     ^^^^^^^   ^^^^^^

According to the PHP docs, they should be Integers, so remove the ='' in those both parameters and it should be fine !
If it still doesn't work, check the parameters where you're calling this function. Make them integers like this : (int) $var; or use the intval function.


text:
Q: Create UDP listening service on Azure Service Fabric I have created a simple service for receiving UDP packets and am trying to deploy in Service Fabric.
When running locally, I am able to spam packets to the service (running in local SF Cluster), but when deployed to Azure the service, and even the VM, does not receive the UDP packets.
I even RDPed into the VM and installed Wireshark, my packets weren't present.
I did the same with a standard Windows DC VM, and was able to see the packets arrive.
Clearly there is an issue with the firewall which is configured upon creation of a SF cluster.
PS I have followed the steps here https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-connect-and-communicate-with-services to ensure that the LB rule is set to UDP (as is not an option upon creation).
EDIT - Note I also followed the advice on this question Service Fabric Stateless Server Custom UDP Listener

A: So turns out that modifying an existing Load Balancer rule does not change the protocol on the firewall (speculation).
I created a NEW Load Balancer rule with the appropriate protocol/port and traffic was flowing.
Modifying an existing Load Balancer rule to change to an appropriate protocol does not work, and traffic ends at firewall.


text:
Q: Joomla URL rewrite for component without a redirect I have a Joomla component "com_foo" which works fine when called via...
http://my.joomla.site/index.php?option=com_foo&id=1234
... but I need the URL be in the following format:
http://my.joomla.site/getfoo/1234
The closest I can get is with the following .htaccess rewrite which causes a redirect:
RewriteEngine On

# My Rule
RewriteRule ^getfoo/(.*)$ /index.php?option=com_foo&id=$1 [R=301,L]

#  Joomla rules
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteCond %{REQUEST_URI} /component/|(/[^.]*|\.(php|html?|feed|pdf|vcf|raw))$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L]

I can't seem to figure out how to make the same thing work "internally" w/o the redirect. So in my example above what happens is:
[1] GET http://my.joomla.site/getfoo/1234 REDIRECTS TO
[2] GET http://my.joomla.site/index.php?option=com_foo&id=1234 RENDERS PAGE

What I need is
[1] GET http://my.joomla.site/getfoo/1234 RENDERS PAGE

Almost everything I try results in a 500 error. I feel like it's got to be something simple but it's got me beat at the moment.

A: Try:
RewriteEngine On
RewriteCond %{THE_REQUEST} ^(GET|POST)\ /index\.php\?option=com_foo&id=(.*)\ HTTP
RewriteRule ^ /getfoo/%2\? [R=302,L]

RewriteRule ^getfoo/(.*)$ /index.php?option=com_foo&id=$1 [L]

The above will:

*

*Redirect http://my.joomla.site/index.php?option=com_foo&id=1234 to http://my.joomla.site/getfoo/1234 and show the information from the http://my.joomla.site/index.php?option=com_foo&id=1234 page

When viewing

*

*http://my.joomla.site/getfoo/1234 will display the information from the http://my.joomla.site/index.php?option=com_foo&id=1234 page

Change the R=302 to R=301 when you are sure the redirect works.

A: Although you could probably get this working using the .htaccess file, by seperating the SEF logic from the component code you open yourself up to a management nightmare down the road. Joomla does however, provide a means to manage SEF url parsing and generation with your custom components.  By placing the file router.php in the root of your component's folder, Joomla will automatically use this file to both generate and parse SEF urls.  Although the link below does provide detailed information on how to implement, I've found reverse engineering core components router.php file helped me tremendously.
http://docs.joomla.org/Supporting_SEF_URLs_in_your_component


text:
Q: Project folder in Visual Studio - Read only and cannot be written to I'm currently trying to make an admin page in an e-commerce website using windows 8 and Visual Studio 2015 Community that should allow an Admin to update/change items on the site.
When I attempt to edit an item on the site I get the following error:

"Access to the path 'C:\Users..(Web site path)..\Secure' is denied."

The following description is given with the error:

"ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and the configured application pool identity on IIS 7.5) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.
To grant ASP.NET access to a file, right-click the file in File Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access."

Stack trace for the Error:
[UnauthorizedAccessException: Access to the path 'C:\Users\..(Web Site Path)..\Secure' is denied.]
    System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +419
    System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) +886
    System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) +144
    System.IO.FileStream..ctor(String path, FileMode mode) +91
    System.Web.HttpPostedFile.SaveAs(String filename) +100
    Secure_Admin.btnImgUpdate_Click(Object sender, EventArgs e) +149
    System.Web.UI.WebControls.Button.OnClick(EventArgs e) +138
    System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +150
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6023

I have checked the security section in the project folder and I have complete access to all files in the web site. However, the check box for "Read Only" is checked and when I uncheck it and click "Apply" and then "OK", the box re-checks itself when I open the properties window.
Any ideas on how to get around this?

A: Right click on the folder, select PROPERTIES >> SECURITY and give your all users full privileges on the folder. You will need to be logged in as an admin user.


text:
Q: how to check java console logs after it is closed I have a java applet to be run in browser, when it is started by jre plugin its console starts but before i could see something, it gets closed. Is there a way to chcek these console logs even if it is closed? may be some file or something where it is saved.

A: Enable Tracing in Java Control Panel. This way the console outputs are saved in a file here:
<User Application Data Folder>\Sun\Java\Deployment\log

More info here: http://docs.oracle.com/javase/7/docs/technotes/guides/jweb/jcp/tracing_logging.html


text:
Q: How to create a Rectangle class in Java? I have this problem where I am supposed to write this program where using a Point class to create points, then create a Rectangle class with methods like area,perimeter, and pointInside... My code is always resulting in a Null Pointer Exception and I don't know why.
class Point {
   int x, y;

   Point() {
      x = y = 0;
   }

   Point(int x0, int y0) {
      x = x0;
      y = y0;
   }

   public String toString() {
      return "(" + x + "," + y + ")";
   }
}
class Rectangle {
   Point p1,p2;

   Rectangle(int x1,int y1,int x2,int y2)
   {
     x1 = p1.x;
     y1 = p1.y;
     x2 = p2.x;
     y2 = p2.y;
   }
   Rectangle(Point p1,Point p2)
   {
      this.p1 = p1;
      this.p2 = p2;
   }

   public int area ()
   {
     int width = p2.x - p1.x;
     int height = p2.y - p1.y;
     int area = width * height;
     return area;
   }
   public int perimeter()
   {
     int side1 = p2.x - p1.x;
     int side2 = p2.y - p1.y;
     int perimeter = side1 + side2 + side1 + side2;
     return perimeter;
   }
   public boolean pointInside(Point p)
   {
     if ((p.x >= p1.x && p.x <= p2.x) && (p.y >= p1.y && p.y <= p2.y))
     {
       return true;
     } else {
       return false;
     }
   }

}

class TestRectangle {
   public static void main(String[] args) {
      Point a = new Point(1,1);
      Point b = new Point(2,2);
      Point c = new Point(3,4);
      Point d = new Point(8,2);

      Rectangle yellow  = new Rectangle(a, c);
      Rectangle orange  = new Rectangle(2, 3, 9, 6);
      Rectangle green    = new Rectangle(3, 4, 4, 5);
      Rectangle blue    = new Rectangle(5, 1, 6, 5);
      Rectangle red = new Rectangle(7, 3, 9, 5);

      System.out.println("Perimeter of the yellow rectangle = " + yellow.perimeter()); // 10
      System.out.println("Perimeter of the orange rectangle= " + orange.perimeter()); // 20

      System.out.println("Area of the yellow rectangle = " + yellow.area()); // 6
      System.out.println("Area of the orange rectangle = " + orange.area()); // 21

      System.out.println("Point B inside yellow? " + yellow.pointInside(b)); // true
      System.out.println("Point D inside yello? " + yellow.pointInside(d)); // false

   }

}

A: When something calls this constructor
Rectangle(int x1,int y1,int x2,int y2)
   {
     x1 = p1.x;
     y1 = p1.y;
     x2 = p2.x;
     y2 = p2.y;
   }

your variables p1 and p2 haven't been initialized to anything, since before that, all you do is declare those two fields, not actually set them to anything. They are null by default.
What you need to do is
Rectangle(int x1, int y1, int x2, int y2) {
  p1 = new Point(x1, y1);
  p2 = new Point(x2, y2);
}

I also have no idea why you're modifying the arguments to the constructor in the original.


text:
Q: Rsync out of memory I'm using a VPS (running Debian) with 512mb RAM. I'm trying to copy some file locally on the server with rsync, but it fails fast with this message:
rsync: writefd_unbuffered failed to write 5 bytes to socket [sender]: Broken pipe (32)
rsync: connection unexpectedly closed (13505 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(601) [sender=3.0.7]

It's only 113MB of files (10.000 of them). But it fails long before reaching all of those files.
I believe this is because of the limited memory availible but it seems like i should be enough? Is there any way around this? Could i make rsync use a file as a memory stack?
Update on request
rsync command
rsync -av /srv .
ulimit -a
nine@www:~$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 16382
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) unlimited
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

free
nine@www:~$ free
             total       used       free     shared    buffers     cached
Mem:        524288     231104     293184          0          0          0
-/+ buffers/cache:     231104     293184
Swap:            0          0          0

Swap would probably help. The problem is that i don't think my VPS supports adding that.
Try to make a swap
nine@www:~$ sudo swapon /home/nine/swap.file
swapon: /home/nine/swap.file: swapon failed: Operation not allowed

Why I think it's a memory problem
I got the question why I think it's a memory problem. It's because of what the control panel for my VPS tells me. There is a table which shows errors for the machine in it looks like this:
resourcetype    held    maxheld     limit           failcnt
numiptent       24  24      800             0
numfile         1612    2324        4200            0
dcachesize      440391  547046      20480000        0
numothersock    104     139     6000            0
dgramrcvbuf     0   17224       262144000       0
othersockbuf    172272  442048      262144000       0
tcprcvbuf       114688  4962176     262144000       0
tcpsndbuf       122528  2177672     262144000       0
numsiginfo      0   3       256             0
numpty      1   3       32          0
numflock        6   13      4120            0
numtcpsock      7   34      6000            0
oomguarpages    14029   23497       131072          0
vmguarpages     0   0       131072          0
physpages       14029   23497       9223372036854776000     0
numproc         102     142         4000            0
shmpages        697     1993        512000          0
privvmpages     57818   131075      131072          51
lockedpages     0   0       8192            0
kmemsize        5566036 7796832     117760000       0

Watch the fail count for privvmages, which I believe shows when the memory burst above it's burst limits. This counts up whenever I'm running rsync.

A: rsync takes more memory when there are more files.
Either split the files in separate folders and rsync them, or TAR all the 10,000 files at source location and rsync the 10000.tar to your vps and then untar it.
I don't know whether this problem is addressed in the latest version (3.1), but it was an issue with earlier versions.


text:
Q: Is there a wavelet frame for $L^2[0,\infty)$? What systems of wavelets provide a frame for $L^2[0,\infty)$.
For example, the Haar system of wavelets  provides a basis for $L^2[0,1]$, and the harmonic wavelets provide a basis for all of $L^2(R)$. I'm not sure if I can use any of these as a basis for $L^2(0,\infty)$
Edit: The Haar system can be used for $L^2[0,\infty)$ by successively translating it the right (see comment). But I need a wavelet frame for $L^2[0,\infty)$ that is both continuous and differentiable (I need second continuous derivatives). The Haar wavelets are discontinuous. Also it would be useful if the wavelet had compact support (in the time-domain or in the frequency-domain).
Thanks.


text:
Q: Calling C from Rust with external headers in C file I am trying to call C code from Rust, I succeeded! The only issue I get is when I try to take other libraries with me... the documentation says that you should include all headers in the one file you try to load in Rust, so I do this in the .c file...
#include <stdio.h>
#include <stdbool.h>

#include "dependencies/glfw-3.3.4/include/GLFW/glfw3.h"

int someFunc() {
    int i = glfwInit();
    glfwTerminate();
    return i;
}

But when I run the Rust program, it says glfwInit and glfwTerminate are unresolved symbols... If I do this instead:
...

#include <GLFW/glfw3.h>

...

I get the error in my Rust program that there is no such directory, though the library was linked correctly using CMake... I read something about a cmake crate, so I am guessing it has something to do with that, but at the moment I am completely clueless. I must say that I am new to both Rust and C/C++ (student in Computer Science...) :slight_smile:
Note that when I remove any glfw related stuff, everything works correctly!
I am thinking if I can somehow invoke CMake from the build.rs file, that I can link everything in the C project correctly, right? I just do not understand very much CMake since I have been doing everything with an IDE (CLion by jet brains) and very limited commands in CMakeLists.txt.
This is how the project is organised...
project structure:
// generated with cargo new rust_project ...
    .../rust_project/
       c_project/          // This was generated with the IDE for C (CLion)...
          dependecies/
             glfw-3.3.4/
                include/
                ...
          CMakeLists.txt
          MyCFile.c
          ...
       src
          main.rs
       build.rs
       cargo.toml
       ...

CMakeLists.txt:
cmake_minimum_required(VERSION 3.17)
project(c_project)

set(CMAKE_C_STANDARD 11)

add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/dependencies/glfw-3.3.4)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/dependencies/glfw-3.3.4/include)
##some more libraries... not currently included in MyCFile.c !##

add_library(c_project MyCFile.c)

target_link_libraries(c_project PRIVATE <other_libraries> glfw ${GLFW_LIBRARIES} <other_libraries>)

MyCFile.c:
#include <GLFW/glfw3.h>

int someFunc() {
    int i = glfwInit();
    glfwTerminate();
    return i;
}

main.rs:
extern "C" {
    fn someFunc() -> i32;
}

fn main() {
    unsafe {
        println!("{}", someFunc());
    }
}

build.rs
extern crate cc;

fn main() {
    cc::Build::new()
        .file("c_project/MyCFile.c")
        .compile("library");
    /*
     * I am guessing here goes something along the lines:
     * "CMakeLists.txt".execute (as pseudo code...)
     */
}

cargo.toml:
[package]
name = "rust_project"
version = "0.1.0"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[build-dependencies]
cc = "1.0.70"

the error message upon "cargo check":
error: failed to run custom build command for `version_zero v0.1.0 (D:\...\rust_project)`

Caused by:
  process didn't exit successfully: `D:\...\rust_project\target\debug\build\rust_project-bf398c13c8af8b0c\build-script-build` (exit code: 1)
  --- stdout
  TARGET = Some("x86_64-pc-windows-msvc")
  OPT_LEVEL = Some("0")
  HOST = Some("x86_64-pc-windows-msvc")
  CC_x86_64-pc-windows-msvc = None
  CC_x86_64_pc_windows_msvc = None
  HOST_CC = None
  CC = None
  CFLAGS_x86_64-pc-windows-msvc = None
  CFLAGS_x86_64_pc_windows_msvc = None
  HOST_CFLAGS = None
  CFLAGS = None
  CRATE_CC_NO_DEFAULTS = None
  CARGO_CFG_TARGET_FEATURE = Some("fxsr,sse,sse2")
  DEBUG = Some("true")
  running: "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.29.30037\\bin\\HostX64\\x64\\cl.exe" "-nologo" "-MD" "-Z7" "-Brepro" "-W4" "-FoD:\\...\\rust_project\\target\\debug\\build\\version_zero-54603a96dee57aac\\out\\c_project/MyCFile.o" "-c" "c_project/MyCFile.c"
  MyCFile.c
  c_project/MyCFile.c(5): fatal error C1083: Cannot open include file: 'GLFW/glfw3.h': No such file or directory
  exit code: 2

  --- stderr

  error occurred: Command "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.29.30037\\bin\\HostX64\\x64\\cl.exe" "-nologo" "-MD" "-Z7" "-Brepro" "-W4" "-FoD:\\...\\rust_project\\target\\debug\\build\\version_zero-54603a96dee57aac\\out\\c_project/MyCFile.o" "-c" "c_project/MyCFile.c" with args "cl.exe" did not execute successfully (status code exit code: 2).

I used: https://crates.io/crates/cc, https://liufuyang.github.io/2020/02/02/call-c-in-rust.html, https://docs.rust-embedded.org/book/interoperability/c-with-rust.html

CMake was installed through: https://cmake.org/download/.
Downloaded the option: "Windows x64 Installer: Installer tool has changed. Uninstall CMake 3.4 or lower first!  cmake-3.21.2-windows-x86_64.msi"
Honoustly don't know how you would do it with the zip files...
tried to uninstall the current CMake, and downloaded version 3.4 (and installed it).
Also changed the build.rs file to:
use cmake;

fn main() {
    let dst = cmake::build("c_project");
    println!("cargo:rustc-link-search=native={}", dst.display());
    println!("cargo:rustc-link-lib=static=MyCFile");
}

cargo check compiles just fine, cargo run, will produce an error:
<lots of file paths...>
  = note: LINK : fatal error LNK1181: cannot open input file 'MyCFile.lib'

Note that I do not get any indications anymore of cmake not being installed...

A: Cannot open include file: 'GLFW/glfw3.h': No such file or directory - the error states that the c compiler cannot find the header file glfw3.h from your build point. The cc crate provides the .include for it's builder. Find out where you have the glfw3.h file and pass its path into the include builder method:
fn main() {
    cc::Build::new()
        .file("c_project/MyCFile.c")
        .include("path/to/glfw3.h")
        .compile("library");
    /*
     * I am guessing here goes something along the lines:
     * "CMakeLists.txt".execute (as pseudo code...)
     */
}


text:
Q: How to prove that a series is convergent Given three series $A_n \leq B_n \leq C_n$, I should prove that $B_n$ is convergent if the series of the partial sums of $A_n$ and $C_n$ are convergent.

A: That need not to be true. Take an increasing sequence $A_n$ that converges to $-1$ and a decreasing sequence $C_n$ that converges to $1$. Then take $B_n = (-1)^n$. Clearly the relation you state holds, but $\lim B_n$ does not exist. What I think you're looking for is the so called squeeze theorem:
THEOREM
Let $a_n < b_n < c_n$ for all $n \in \Bbb N$. Then if $\lim\limits_{n \to \infty} a_n = \lim\limits_{n \to \infty} c_n=\mu \in \Bbb R$ we also have $\lim\limits_{n \to \infty} b_n = \mu $.

A: Have you tried using squeeze theorem here. It is quite useful in calculating limits of functions. See it might work for series as well because you are using the concept of convergence of the series of partial sum of $A_n$ and $C_n$.

A: To prove this, the hypothesis must be strengthened very slightly.  We will assume not only that the partial sums are bounded, but also that the partial sums of $A_n$ and $C_n$ approach a limit, which we will denote $\sum A_n$ and $\sum C_n$, respectively.
By the first inequality, $C_n-A_n\ge B_n-A_n \ge 0$.
$\sum B_n-A_n$ is monotonic (since each successive term is positive) and is bounded above by $\sum C_n-A_n$.  A monotonic sequence bounded above converges to a limit$^1$.  Therefore, $\sum_{n=0}^{\infty} B_n - A_n$ exists and $\sum B_n$ converges.
$^1$This sequence is monotonic increasing, so the limit of the sequence is the least upper bound of the sequence itself.


text:
Q: Ubuntu 10.04 - Display Issues We have a Visio VX32L tv in our lobby that displays a web page welcoming visitors to our company. Currently there is a Dell GX260 workstation running windows xp that is used to display the web page. I am trying to replace the windows install with Ubuntu but I am having issues with the video.
I have installed 10.04 in my office with the workstation hooked up to a 17" NEC monitor. Everything works fine, the display is correct and I have plenty of options to change the screen resolution etc. I then take the workstation up to the lobby and hook it up and this is where the trouble starts. I get the Dell BIOS screen, no problem. Then it displays the start of the Ubuntu splash screen for a second and immediately goes away displaying "No Input Signal". I have reconnected it to the 17" monitor and set the resolution to one that I know the lobby screen supports but I receive the same results. The windows xp install displays fine and there were no special drivers needed. I had origianlly tried using 10.10 and it would display on both monitors but I had no options to change the screen resolution at either place. From what I found through Google, this was a common issue on 10.10 so I dropped back to 10.04. 10.04 is halfway there buts still not 100%. Any help would be greatly appreciated! I am trying to introduce Ubuntu to our workplace but it is just not cooperating!!!

A: First, I would check and see if you could generate a new Xorg.conf file for the monitor in the other room (use SSH to access the box). Back up the old one by moving it out of the /etc/X11/ directory to somewhere safe. While X will work on on monitor, I can pretty much guarantee all of the horizontal/vertical frequencies will be different on the big TV. You're better off starting with a clean Xorg.conf file so that it can generate everything for the new monitor.


text:
Q: Svelte3/sapper/rollup exclude file pattern from compilation I am trying to setup a TDD environment for an app I am building using svelte + sapper.
I need to ignore some files during the compilation (which uses rollup by default)... the reason why I need to exclude them is that I want to have a scalable scaffolding for my application, just like this:
src
|___components
    |
    |___aComponent
        |___aComponent.svelte
        |___aComponent.test.js

(e2e tests and integration will probably follow a different structure in order to maintain the separation of concerns and not to bound route and component.
The issue I am having right now is that js files are by default added into the project because of course I may need to create helper classes etc.
I already added exclude: **/*.test.js, but it looks like it's not enough...
here's my configuration.

A: This came up in a google search for me and is probably old, but in your exclude you have:
{
  exclude: ["node_modules/@babel/**", "**/*s.test.js"]
}

instead of:
{
  exclude: ["node_modules/@babel/**", "**/*.test.js"]
}


text:
Q: What are the odds of getting 3 pair in texas holdem? I'm looking to create a variant of holdem allowing 6 and 7 card hands in special situations.  Namely, 3 pair, 2 set, and quads over set (a full mansion).
My probability skills are rusty, but I'm still able to break down the problems, I think!
I've started trying to calculate the odds of 3-pair so I can find where to rank the hand.  I'm using the probability tree method.  The branch at the top is clear, pocket pair vs non pocket pair.

When you go down the pocket pair side (0.059), the board must also 2 pair to have a 6 card 3 pair hand.
There are 66 combinations (12 choose 2) of the other than our current pocket pair pairs that the board can make.
The odds of a single combination of such a board would be, I believe, (4/50) * (3/49) * (4/48) * (3/47) * (40/46) = 2.26548e-05
The reason for 40 is because you can't create a set of any of the 3 pairs with the last card or else you'd create a full house, so you need to subtract those 6 remaining cards.
I'm struggling to remember how exactly to use this value.  I know it's not just multiplying by 5! due to the fungibility of each paired card.
I think I need to use permutation with repetition?  That would mean 5! on the numerator, then divided by (2! * 2!), coming out to 30.
Meaning the final calculation for the odds of there being 3 pair when you are holding a pocket pair to be:
2.26548e-05 * 66 * 30 = 0.044856504

On the other side of the tree, where you don't have a pocket pair (.941), the board must pair both your pocket cards and also pair itself for you to have 3 pair.
There are 11 other pairs the board could make besides the 2 cards you're holding.
The odds of a single permutation of such a board is:
(3/50) * (3/49) * (4/48) * (3/47) * (40/46) = 1.69911e-05
Using the same permutation with repetition formula, it should be (5! / 2!) or 60.
So the odds of getting 3 pair with a mixed hand would be 1.69911e-05 * 11 * 60 = 0.011214126

Combining both sides of the tree, we get
pocket pair = 0.059 * 0.044856504 = 0.0026465337
mixed hand = 0.941 * 0.011214126 = 0.0105524926
For a combined odds of 0.0138606597 or 1.386%.
That actually would rank higher than a full house (2.6% chance) which is surprising to me.  I figured this would rank much lower closer to a straight or a set.  Of course, that assumes I didn't mess up my math somewhere!  Thanks for reading and please help me correct my mistakes :)

A: Since you chose a somewhat roundabout way to do the calculation, let's do it again in a slightly more direct way to check your result. There's no need to treat the two pocket cards any differently than the five board cards – all you want to know is the probability for seven cards to contain three pairs, without any distinction among the cards.
We need to choose $3$ out of $13$ ranks for the pairs, $1$ more rank out of the remaining $10$ for the singleton, $2$ out of $4$ cards for each paired rank, and $1$ out of $4$ cards for the singleton, so the probability is
$$
\frac{\binom{13}3\binom{10}1\binom42^3\binom41}{\binom{52}{7}}=\frac{2376}{128639}\approx1.85\%\;,
$$
slightly higher than your result but still lower than you expected.
Two errors kept you from reaching this result. One is where you say "the board must pair both your pocket cards and also pair itself for you to have $3$ pair". That's not true – the board can pair one of your cards and add another two pairs. Since we can choose $1$ of $2$ pocket cards to pair, $1$ of the remaining $3$ cards of that rank, $2$ out of $11$ remaining ranks for the other pairs and $2$ out of $4$ cards of those $2$ ranks, the probability for this is
$$
\frac{\binom21\binom31\binom{11}2\binom42^2}{\binom{50}5}=\frac{297}{52969}\approx0.56\%\;.
$$
The other error is in your addition of $0.0026465337$ and $0.0105524926$, which yields approximately $1.32\%$, not $1.386\%$. If you correct those two errors, your approach also yields
$$
\frac1{17}\cdot\frac{\binom{12}2\binom42^2\binom{10}1\binom41}{\binom{50}5}+\frac{16}{17}\cdot\frac{\left(\binom{11}1\binom31^2\binom42\binom41\binom{10}1+\binom21\binom31\binom{11}2\binom42^2\right)}{\binom{50}5}=\frac{2376}{128639}\approx1.85\%\;.
$$


text:
Q: Resolution of identity in interacting QFT $\mathbf{Background:}$ Consider a free scalar field $\phi$ ($\mathcal{L}_0 = \frac{1}{2}\partial_\mu \phi \partial^\mu \phi + \frac{1}{2}m^2 \phi^2$).
In the Hamiltonian viewpoint, this system has a Hilbert space $\mathcal{H}_0$ (the Fock space).  We can write down a resolution of the identity in $\mathcal{H}_0$ (in the Schrodinger picture):
$\begin{align}
I  = |0 \rangle \langle 0 | + \int dp\ |p \rangle \langle p | + \frac{1}{2!} \int dp_1 dp_2\ |p_1 p_2 \rangle \langle p_1 p_2 | +\ \cdots
\end{align}$
$\mathbf{Question:}$  If we add an interaction term to the Lagrangian (such as $\lambda \phi^4$), is $I$ still the identity operator in the new Hilbert space $\mathcal{H}$?
(To be clear, I mean exactly the same $I$, with the free vacuum and free particle states.)
$\mathbf{Motivation:}$ The analogous thing holds in QM.  A non-relativistic particle moving in a potential $V$ has a Hilbert space $L^2({\mathbb{R}})$, so by Fourier transform, $\int dp\ |p \rangle \langle p |$ is a resolution of the identity.  (Where $\langle x | p \rangle = \frac{1}{\sqrt{2\pi}} e^{i p x}$ are free particle states.)  The Hilbert space is the same regardless of $V$.

A: Yes, that's still a resolution of the identity.
But knowing this isn't likely to make your life easier.  The observable algebra for the free theory and the observable algebra for the interacting theory are generated by unbounded operators.  These algebras do not have the same domains of definition.  The 'free-particle' resolution of the identity you wrote down is convenient when you're dealing with the domain where the free field operators have a well-defined action, but it's generally singular when you're trying to study vectors which live in the domain of the interacting field operators.


text:
Q: How to use Grafana to create graphs with data from Spring Boot I am new to Grafana and Spring Boot. I am trying to create a Spring Boot application, and use Grafana SimpleJSON Datasource plugin to get data from my Spring Boot APIs and create graphs. I'm following instructions here https://grafana.com/grafana/plugins/grafana-simple-json-datasource/. Right now I am just hard-coding data into my Spring Boot App.
My question is - Are there other better plugins or approaches people would suggest me to use? SimpleJSON seems to require a very specific format of JSON response, and I don't see too many detailed docs online. Is there any way that I can be more free on my JSON responses of my APIs, and set the parameters needed to plot graphs in Grafana?
Thank you.

A: You can use Micrometer with Spring Boot Actuator framework to expose metric data to a time series database such as Prometheus. Or you can simply write log files, collect them with Promtail and store them in Loki.
At first this might seem like a lot of work to get these things running, but it might be worth it.
I found it surprisingly simple to get the whole monitoring stack running locally with docker-compose:

*

*Add services grafana, prometheus, promtail and loki.

*Configure each of them.

The docker-compose might look like this:
version: "3"

services:
  prometheus:
    image: prom/prometheus:latest
    command:
      - --config.file=/etc/prometheus/prometheus.yml
    volumes:
      - ./config/prometheus/prometheus_local.yml:/etc/prometheus/prometheus.yml
    ports:
      - "9090:9090"

  loki:
    depends_on:
      - promtail
    image: grafana/loki:latest
    volumes:
      - ./config/loki:/etc/loki
    ports:
      - "3100:3100"
    command: -config.file=/etc/loki/loki-local-config.yaml

  promtail:
    image: grafana/promtail:latest
    volumes:
      - .log:/var/log
      - ./config/promtail/promtail-docker-config.yaml:/etc/promtail/config.yml
    command: -config.file=/etc/promtail/config.yml

  grafana:
    depends_on:
      - prometheus
      - loki
    image: grafana/grafana:latest
    volumes:
      - ./config/grafana/grafana.ini:/etc/grafana/grafana.ini
      - ./config/grafana/provisioning:/etc/grafana/provisioning
      - ./config/grafana/dashboards:/etc/grafana/dashboards
    ports:
      - "3000:3000"

Sample config files for provisioning grafana can be found in the grafana git repository. Loki provides sample configurations for itself and promtail. For Prometheus, see here.
The official documentaion about installing Grafana with loki can be found here. There is also documentation about the Prometheus configuration.
Now you need to configure your application. Enable and expose the endpoint prometheus as described in the spring boot documention. Configure a log file appender to write the logs to the above configured log directory .log.
Your logs will now get collected by Promtail and sent to Loki. Metrics will get stored in Prometheus. You can use PromQL and LogQL to write Grafana queries and render the results in Grafana panels.
With this solution you can add tags to your data that can later be used by grafana.


text:
Q: comparision of two columns within a single table i have a table alpha ,this contains two columns A And B. I need to find out how many A's are there for B.
      A             B
      1     1
      2     2
      3     3
      4     3
      5     4
      6     7

A: Try grouping :
SELECT `B`, COUNT(*) AS `Count`
FROM `Alpha`
GROUP BY `B`

A: try this
SELECT COUNT( * ) AS  `Items` ,  `B`
FROM  `alpha`
GROUP BY  `b`


text:
Q: Why does $k_\text{B} T \ll \hbar\sqrt{k_\text{Hooke}/m}$ imply that vibrational motion is negligible? I want to estimate the heat capacity of a diatomic molecule whose movement has been constrained to a 2-dimensional plane.
I can assume that
$$
k_\text{B} T ~\ll~ \hbar\sqrt{\frac{k_\text{Hooke}}{m}}
\tag{1}
\,,$$ where $k_\text{Hooke}$ is the Hooke's law constant.
The answer is $\frac{3}{2} k_\text{B} ,$ since there are 2 translational movements and one rotational, so:
$$
U = \frac{f}{2}k_\text{B} T
~~\implies~~
C = \frac{3}{2} k_\text{B}
\,.$$
Since the heat capacity, $C ,$ isn't dependent on $k_\text{Hooke} ,$ this seems to say that vibration can be neglected.  However, how does the assumption in $\operatorname{Eq.}{\left(1\right)}$ end up resulting in this conclusion that vibration can be neglected?
Question:  How does $k_\text{B} T \ll \hbar \sqrt{k_\text{Hooke}/m}$ imply that the vibrational motion is frozen out?

A: To help understand what your assumption is saying, it might be easiest to start by defining what each side measures. What does $k_B T$ measure? What does $\hbar\sqrt{k/m}$ measure? What are the units of them?
And once you figure out the units and what each side represents, what does it mean that one side is much, much less than the other side? What would happen if the inequality is reversed? What happens when they are of similar order of magnitude?


text:
Q: clearinterval on document.ready hello im new to javascript
<script type="text/javascript">
    $(document).ready(
        function(){
            Dashboard("<?php echo base_url();?>Kasir/display")
            var again = setInterval(function(){Dashboard("<?php echo base_url();?>Kasir/display")},2000);
        }
    )
    function klik2(){
        alert('jwqeoiqej');
        clearInterval(again);
    }
</script>

my alert works but i dunno why my clearinterval doesnt seems to work when i run that function


text:
Q: Primary decomposition of $ (x,y^2)$ Let $K$ be a field and $K[x,y]$ is a ring. How can I find primary decomposition of $(x,y^2)$ ideal? Thanks

A: Remember that, given an ideal $\mathfrak{q}$ in a commutative ring $R$, if the radical $\sqrt{\mathfrak{q}}$ is maximal, then $\mathfrak q$ is primary.
In you case, note that $(x,y^2)=(x)+(y^2)$
$$\sqrt{(x)+(y^2)}=\sqrt{\sqrt{(x)}+\sqrt{(y^2)}}=\sqrt{(x)+(y)}$$
and since $K[x,y]/(x,y)\simeq K$ is a field, you're done.
No need to use computer algebra in these cases, you'll get lazy as me :)


text:
Q: PostGIS trigger : table and materialized view I have a PostGIS polygons table for my "cities".
I have a point table for my "boreholl".
I created a "mv" materialized view defined by a spatial join as follows:
SELECT boreholl.*,
       cities.gid,
       cities.insee_id,
       cities.name
FROM   boreholl, cities
WHERE  st_intersects(boreholl.geom, cities.geom);

Now I want as soon as an updating takes place for the "cities_name" column of my "cities" polygon table,
this change also occurs in the "name" column of my materialized view.
As far I understood,the trigger must be defined on the "cities" table as follows :
CREATE TRIGGER cities_trigger
after  update
on cities
FOR EACH STATEMENT.
execute procedure trigger_function

Now I need to define the function. It is for this step that I need you.
Below, a proposed structure. But a lot is missing :
CREATE or replace FUNCTION  trigger_function
returns trigger
langage sql
AS $$
BEGIN
 if    then
update
end if ;
return new
refresh materialized view
END;
$$

A: Creating a materialised view executes a query and writes the result to disk. It will only update the result set when told to do so (REFRESH MATERIALIZED VIEW {view table}).
A view will only execute the query when the view itself is queried (i.e. SELECT * FROM {view table} is essentially a proxy to the query defined by the CREATE VIEW command). A view is therefore not physically materialised (hence the name distinction).
So querying a non-materialised view will retrieve the latest information, there is no need for an insert trigger. Whether this is a better option for you than a materialised view depends on how long the query takes, and how often updates occur. I tend to use views a lot more frequently than materialised views, which I usually reserve for cases of heavy spatial operators.
If you still want to use a materialised view (there are good reasons this may be so), and you want the latest updates in your result set, then you must use REFRESH MATERIALISED VIEW before querying your view. Using an insert trigger is still an option, I think, but it probably isn't a good idea since triggers are meant to be quick record-level updates — I tend to use them for things like deriving geometries, e.g. so I can have a polygon and its centroid pre-calculated and available in the same table.


text:
Q: C# MVC AntiForgeryToken генерирует не правильный Hidden Данные в контроллере подготавливаются верные и на представление приходят корректные данные. Имеется вот такая незаурядная модель:
public class InfoServiceSystem : Tuple<bool, InfoServiceSystemBase>
{
    public InfoServiceSystem() : base(false, new InfoServiceSystemBase()) { }

    public InfoServiceSystem(bool isAvailable, InfoServiceSystemBase item)
       : base(isAvailable, item) { }

    public bool IsAvailable
    {
        get { return this.Item1; }
    }

    public InfoServiceSystemBase ItemBase
    {
        get { return this.Item2; }
    }
}

Свойства IsAvailable и ItemBase добавил для удобства (так как Item1 и Item2 нельзя изменить, а более удобно использовать осмысленные имена).
Имеется представление содержащее следующий код:
@using (Html.BeginForm())
    {
         @Html.AntiForgeryToken()
         ...

                     ...

            Система...
            @Html.CheckBoxFor(m => m.SystemsContext.ElSystemInfo.IsAvailable)
            ...

Отображается все верно, вот только если взглянуть на код страницы, то увидим следующее:

Как видим, input, являющийся hidden - генерируется false. Ранее IsAvailable у меня был одним из полей класса InfoServiceSystem и все работало корректно, но появилась необходимость в разделении и после этого появилась странное поведение...какие предположения будут по поводу такого странного поведения и варианты решения? Может кто сталкивался с подобной проблемой?
Если убрать:
@Html.AntiForgeryToken()

и писать везде:
@Html.HiddenFor(m => m.SystemsContext.ElSystemInfo.IsAvailable)

то все равно поведение не то, которого хотелось бы.
Внесу небольшую поправку, изначально оно и должно генерироваться значением по умолчанию (в нашем случае false), но перед отправкой значений с формы - заполняется нужным значением и в контроллер приходит то, что нужно (в нашем случае true). Раньше заполнялось, а теперь нет. Почему так?

A: Дело оказалось в том, что у Tuple не редактируемые свойства. И их нельзя переопределить. Поэтому значения из false в true не изменялись после отправления данных с формы и в контроллер приходили не те значения, которые ожидались.


text:
Q: Get the domain of the website requesting to access another website I have 2 different websites that need to be integrated. Let's name them, Web1 and Web2.
I want to verify if the requesting Web1 is indeed the Web1 before allowing any access to Web2.
The Request.Url.Host will only get the domain of the current website.
What I need is to verify the domain of Web1 inside the Web2 C# codes.
Currently, this is how I called the Web2 from Web1.
$("#btn").click(function() (
    window.location.href = "http:\\Web2.com\Test"
)}

Thanks

A: URL referrer and Origin header can be spoofed. So it's not reliable.
The only way I can see being able to come close to a reliable solution is to add in server-to-server communication to perform the hand-off between the two applications.
So in your click event, these things would happen:

*

*The browser makes an AJAX call to Web1 to request a URL to Web2

*Web1 makes an HTTP call (from the server) to Web2

*Web2 returns a unique URL (for example, http:\\Web2.com\FromWeb1\8247983659 (or maybe with a GUID, whatever you want)

*Web1 returns the unique URL to the browser

*The browser redirects the user to the unique URL

*Web2 verifies that the URL used is one that it generated and thus knows the user came from Web1

You'd still need some authentication in step 2 so that Web2 knows it's Web1 making the call, but at least that authentication is not being exposed to the browser.


text:
Q: Site and Site Collection features available on SharePoint 2013 install I'm looking for a list of all the Site Features and Site Collection features provided by Microsoft and available on SharePoint 2013 to install.  I did an extensive search and was not able to find any.  All searches are pointing me to currently installed features, but I need the initial set.

A: You can use PowerShell to get list of Installed features.
Get-SPFeature -Limit ALL | Where-Object {$_.Scope -eq "SITE"}

I believe this will return features irrespective its activated or deactivated.

A: You can try below powershell, it will give you all OOTB feature scoped to Farm, web App, Site and Web. script create a csv and then you can filter it as per your need.
$lcid=1033

$delimiter = "*"

Get-SPFeature -Limit ALL | % { Get-SPFeature -Identity $_ | % { $_.DisplayName + $delimiter + $_.GetTitle($lcid) +$delimiter +$_.Scope + $delimiter + $_.Id + $delimiter + $_.GetDescription($lcid)} } >>"C:\Features.csv"

Listing All SharePoint Server 2013 Features – Including Name, Title, Scope, ID and Description

A: Which site collection features are available out of the box in a site collection will depend upon which site template you chose when creating the initial site collection as well as which service applications have an association to the web application hosting the site collection.
So there's no one simple list, the exact features depend on the context of your specific environment. Hence all the other answers and search results just telling you how to get that environment-specific list.


text:
Q: Is this possible to do in ionic? I have to develop an app and I have chosen ionic because I need to do both, ios and web but I am not sure if I wil be able.
This would be the app:

As you can see I need to show a map with different placeholder and when you click in some it would appear a box. Do you think ionic have the tools and the power to achieve this?
The way to map the placeholders in html would be with position absolute and coordinate x and y but I don't think this is a good way
Thank you


text:
Q: Ejecutar un código al dar al botón de volver atrás o salir la app Me gustaría saber como ejecutar un código cuando el usuario vuelva atrás con el botón de su smartphone y salga de ese activity, y ejecutar un código tambien al salir de la aplicación ( en segundo plano )
Lo que quiero con ello es que al salir de un activity donde se reproduce un sonido, si le dan atrás y salen de ese activity o saliendo y teniendo la app en segundo plano, ese sonido se pare con release()

A: Para detectar el botón de regreso y finalizar la activity, sobre escribe el método onBackPressed()   y usa finish() para terminar la Activity:
   @Override
    public void onBackPressed() {

        finish();
    }

Si deseas llamar un método al salir y destruirse la Activity sobre escribe el método onDestroy():
@Override
protected void onDestroy() {
    //Realiza un proceso.
    super.onDestroy();
}

Si deseas detectar cuando tu aplicación pasa a segundo plano sobre escribe el método onPause(), aquí puedes llamar .release() :
@Override
public void onPause() {
    super.onPause();

    myMediaPlayer.release();

}

A: Cuando una Activity se pone en pausa o finaliza se ejecutan una serie de métodos que puedes sobreescribir, te los dejo a continuación:

El siguiente método te ayudará:
@Override
protected void onDestroy() {
    //Aquí el código que quieras ejecutar al finalizar el Activity

    super.onDestroy();
}


text:
Q: How I can send ping to IPv4 address from IPv6 I have a CentOS server that only has IPv6 address.
I want to send a ping to an IPv4 address with the ping Linux command.
Is this possible?
[root@test conf.d]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc pfifo_fast state UP group default qlen 1000
    link/ether fa:16:3e:ab:f7:f0 brd ff:ff:ff:ff:ff:ff
    inet6 fd00:4888:1::10/64 scope global noprefixroute
       valid_lft forever preferred_lft forever
    inet6 fe80::f816:3eff:feab:f7f0/64 scope link noprefixroute
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether fa:16:3e:35:5c:ed brd ff:ff:ff:ff:ff:ff
    inet6 2001:1b70:4280:18e2::10/64 scope global noprefixroute
       valid_lft forever preferred_lft forever
    inet6 fe80::f816:3eff:fe35:5ced/64 scope link noprefixroute
       valid_lft forever preferred_lft forever
[root@vnflcm-test-vnflcm-services-0 conf.d]#

A: It's not possible without some help. The IPv6 machine doesn't speak IPv4 and vice versa. You'll need the help of a machine that speaks both: a NAT64 gateway.
You can find a few public ones for testing on https://go6lab.si/current-ipv6-tests/nat64dns64-public-test/. Not all of them are online all the time, so try a few.
The system works because IPv6 addresses are much bigger than IPv4 addresses. It is therefore possible to put an IPv4 address inside an IPv6 address. For example the address 8.8.8.8 can be reached through 2001:67c:27e4:1064::808:808 or 2001:67c:27e4:1064::8.8.8.8 (yes, this notation is perfectly valid!).
The DNS64 servers mentioned on the page above do this automatically for you, so it works fine even when using host names.
When you want to use this in production (for example to run an office network with only IPv6 while still being able to access the IPv4 internet) you should run your own NAT64 and DNS64 gateways.

A: In short: No
IPv6 and IPv4 cannot interact, it is technically impossible to directly send this ping.
What you would need is a proxy with both IPv4- and IPv6-capability that may be used to forward pings between the two protocols.


text:
Q: I'm at loss with a recursive method on leetcode 72 Though it will be TLE,I think it's useful for me to understand the valid solution which use Dynamic Programming,here is the Description and the code:
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
int minDistance(string word1, string word2) {
        if(word1 == word2) return 0;

        int m = word1.size();
        int n = word2.size();

        if(word1 == "")
        {
            return n;
        }

        if(word2 == "")
        {
            return m;
        }

        if(word1[0] == word2[0])
        {
            return minDistance(word1.substr(1), word2.substr(1));
        }
        else
        {
            return min(1 + minDistance(word1, word2.substr(1)), min(1 + minDistance(word1.substr(1), word2), 1 + minDistance(word1.substr(1), word2.substr(1))));
        }

    }

One question is that I can't understand the ELSE Structure's meaning for sure--In my opinion,it has three different situations,so I guess it respectively achieves insert delete and replace(Maybe the order is incorrect)
Another is how to understand when one string is empty,the result will be the other string's length?

A: return
min
(
1 + minDistance(word1, word2.substr(1)), <-insert from word2
1 + minDistance(word1.substr(1), word2), <-delete from word1
1 + minDistance(word1.substr(1), word2.substr(1)) <-replace
)

Firstly,
the "insert" case implies that we take a first character from word2 and insert it into word1 (and increment the "edit distance" cost), which leaves us with word1 and word2.substr(1)
the "delete" case implies that we throw away a first character of word1 (and increment the "edit distance" cost), which leaves us with word1.substr(1) and word2
the "replace" case implies that the first chars of both words are different so we increment "edit distance" cost and throw away the first chars which leaves us with word1.substr(1) and word2.substr(1)
the "same" case implies that the first chars of both words are the same so we don't need to increment "edit distance" cost and hence we just throw away the first chars which leaves us with word1.substr(1) and word2.substr(1)
Hence we have 3 different possibilities to check, that's why we recursively call the function for all 3 cases and compare their final costs by picking up the minimal one.
Secondly,
the base case "return n" implies that in order to convert empty string into word2 we definitely need to insert n chars from word2 into word1 which adds "n" to the "edit distance" cost
Similarly, the base case "return m" implies that in order to convert word1 into empty string we definitely need to delete m chars from word1 which adds "m" to the "edit distance" cost
Your algorithm is a special case of a more general "edit distance" algorithm which can be applied to the wide range of problems by modifying the cost of insert/delete/replace/same. For your specific case, the goal is to find the minimum number of steps needed to convert word1 into word2 so the cost=1 for "insert/delete/replace" and cost=0 for "same" would be the solution.
Regarding dynamic programming version of the algorithm, it is straightforward to derive it, once you have defined the recursion and necessary base cases.


text:
Q: How to fix a for loop that is skipping some values? I basically have a date entered in cell N3 and a column (column I) that contains date sorted by date. I am trying to write a code that asks the user to input a date at first. Then the program would look for that date in the column I and delete ALL the rows after the row in which the match was found.
My code is somehow working, but here is my problem. Only a part of the rows under the wanted row are being deleted and not all of them. I was thinking that could be an issue with the for-loop or the counter?
Please let me know if you could help :)
Sub DeleteAllRowsPaymentTooFar()

Worksheets("Master").Activate

Dim date_max As Date
date_max = InputBox("What is the maximum date to filter? ")

Range("N3").Value = date_max
Range("N3").NumberFormat = ("ddddd, mmmmmmmmm d, yyyy")

Dim i As Long
i = Range("A4").End(xlDown).Row
Dim result As Integer
Dim str1 As String, str2 As String
Dim counter As Long

str1 = Cells(3, 14).Text

counter = 4

Do While counter <= i

str2 = Cells(counter, 9).Text

result = StrComp(str1, str2, vbTextCompare)

  If result <> 0 Then
 MsgBox ("The date is not yet reached.")

  Else

        For K = counter To i
        Worksheets("Master").Rows(K).EntireRow.Delete
        Next

    End If

counter = counter + 1
Loop

End Sub

I expect to remove all the rows under the row where the match was found.

A: This may help you:
For i=LastPoint To FirstPoint Step-1

    Worksheets("Master").Rows(i).EntireRow.Delete

Next i


text:
Q: Human verification on failing to include necessary tag On submitting a question here at Meta Stack Overflow, it is required to include a tag if it's a bug, feature-request or a discussion.  Failing to do so results in an error and returns you to the form.  After filling in the correct tag and submitting it again, the human verification form was shown.
IMO, when the error is the failure to include one of those tags and the form is re-submitted, the human verification should not be necessary because new meta stackoverflow users are bound to commit that error.
Better yet, use an input type that explicitly shows that those tags are required instead of letting them type it.  It could be a radio button or a drop down (not autocomplete) if only one of those tags should be included or a checkbox if 2 or more of those tags can be included.

A: This could lead to very easy exploits where you send in a form missing a tag, then edit the form and resubmit it in order to never get a captcha (much easier to spam).
The radio buttons or drop down could be a decent addition, but it's honestly not that difficult to type in a tag.


text:
Q: how to adjust label text center in react native svg charts in react native       <View style={{flex: 1, height: windowHeight * 0.39, marginLeft: 10}}>
    <BarChart
      style={{flex: 1}}
      data={data}
      spacingInner={width * 0.000999}
      spacingOuter={
        Months.length == 1
          ? width * 0.36
          : Months.length == 3
          ? width * 0.3
          : null
      }
      horizontal={false}
      yAccessor={({item}) => item.value}
      svg={{fill: fill}}
      contentInset={{top: width * 0.025, bottom: width * 0.025}}
      spacing={0.2}
      gridMin={0}
      gridMax={Math.max(...values)}>
      <Grid svg={{stroke: LineFill}} />
    </BarChart>
    <XAxis
      xAccessor={({index}) => index}
      data={Months}
      formatLabel={(label, index) => data[index].label}
      style={{
        marginHorizontal: width * -0.03,
        height: width * 0.04,
        alignItems: Months.length == 1 ? 'center' : null,
      }}
      contentInset={{
        left: Months.length == 3 ? width * 0.26 : Months.length == 4 ? width * 0.09 :  width * 0.07,
        right: Months.length == 3 ? width * 0.26 : Months.length == 4 ? width * 0.09 : width * 0.066,
      }}
      svg={axesSvgXAxis}
    />
  </View>

Blockquote
Hi i am new to react native , i am using react native-svg-charts , i am facing issue in adjust label text center according to the position of bars in react native-svg-charts.strong text

https://i.stack.imgur.com/TXSNA.png


text:
Q: Maximum value of range of values in array (C++) The array ampVal has 25600 integers inside it. I need to find the maximum value of each set of 1024 values in the array and store it in another array. However I'm not getting this part to work it only gives 21 values and a random number '1348410436'. ampVal is a dynamic array.
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;

int main() {

ifstream miniProject;
int n = 0;
miniProject.open("C:\\Users\\Simeon Ramjit\\Desktop\\audioframes.txt");
if (!miniProject) {
    cout << "File not found" << endl;
}
else {
    cout<<"File Located ! :D \nCounting Lines in file..." << endl;

    while (miniProject) {
        string lines;
        getline(miniProject, lines);
        n++;

    }
    cout << "Number of lines in file are: " << n << endl;
    miniProject.close();
}

int *frNum = new int[n];
int *bitNum = new int[n];
int *ampVal = new int[n];
     for (int i = 0; i < n;i++){
         frNum[i] = 0;
         bitNum[i] = 0;
         ampVal[i] = 0;
   }

miniProject.open("C:\\Users\\Simeon Ramjit\\Desktop\\audioframes.txt");
if (!miniProject) {
    cout << "File not found" << endl;
}
else {
    int i = 0;
    string frameNumber, bitNumber, amplitudeValue;
    while (miniProject) {
        (miniProject >> frameNumber >> bitNumber >> amplitudeValue);
        stringstream(frameNumber) >> frNum[i];
        stringstream(bitNumber) >> bitNum[i];
        stringstream(amplitudeValue) >> ampVal[i];
        i++;

    }
}
miniProject.close();

int frameGroupStart = 0;
int frameGroupEnd = 1024;
int maxAmpVal = 0;
while (frameGroupEnd != 25600) {
    for (int i = frameGroupStart; i < frameGroupEnd; i++) {
        if (ampVal[i] >maxAmpVal) {
            maxAmpVal = ampVal[i];
            cout << maxAmpVal << endl;
        }
    }
    frameGroupStart = frameGroupStart + 1024;
    frameGroupEnd = frameGroupEnd + 1024;
}

getchar();
return 0;

}

A: I used an alternate approach and this gets the job done:
int bitGroupStart = 0;
int bitGroupEnd = 1024;
int arrayOfMaxAmpVal[25];
int frameNumMaxVal[25];
int maxAmpVal = 0;

for (int i = 0; i < 25; i++) {
    for (int j = bitGroupStart; j < bitGroupEnd; j++) {
        if (ampVal[j] > maxAmpVal) {
            maxAmpVal = ampVal[j];
        }
    }
    bitGroupStart = bitGroupStart + 1024;
    bitGroupEnd = bitGroupEnd + 1024;
    arrayOfMaxAmpVal[i] = maxAmpVal;
    frameNumMaxVal[i] = i;
    maxAmpVal = 0;
}


text:
Q: Node.js: Error: spawn ENOENT while using GM module Even though this has been asked several times, none of the existing answers helped me out. Using a MEAN environment (on Mac OSX), I installed graphicsmagick using:
sudo npm install gm

Whenever I run the following script, I get this error:
{ [Error: spawn ENOENT] code: 'ENOENT', errno: 'ENOENT', syscall: 'spawn' }

This is the piece of code I am trying to run:
var gm = require('gm');
//var gm = require('gm').subClass({ imageMagick: true }); //tried this one too

    gm('./project/public/images/webshots/test1.jpg')
           .resize(320, 240)
           .write('./project/public/images/webshots/test2.jpg', function (err) {
        if (!err) console.log('done');
        if(err){
           console.log(err);
        }
        });

Appropriate writing permissions were given by:
sudo chmod -R 777 ./project/public/images/webshots

I even tried several source/destination path combinations. What else could I have missed?

A: It is looking for the gm(GraphicsMagick) binary
Install GraphicsMagick via PPA:
sudo add-apt-repository ppa:dhor/myway
sudo apt-get update
sudo apt-get install graphicsmagick

This worked for me

A: This helped me solving this issue.
gm('./project/public/images/webshots/test1.jpg')
.options({imageMagick: true})
.resize(320, 240)
.write('./project/public/images/webshots/test2.jpg', function (err) {
    if (!err) console.log('done');
    if(err){
       console.log(err);
    }
});

Note: imageMagick should be installed

A: The gm module can't find the path to the gm executable. So it sounds like your $PATH needs to be updated to include the path where graphicsmagick was installed to.


text:
Q: How to set unset sequence in php there are two inputs that should show interactions. Everything works, but when I want to refresh the page I add unset($_SESSION['one'], $_SESSION['second']) an error appears
Without unset($_SESSION['one'], $_SESSION['second'])

But you still need to reset everything when you refresh the page
search.php
<?php
session_start();
?>

   <form action="new.php" method="post">

         <input type="search" name='search1' list="doc" id="inp1">
         <datalist id='doc'>
            <option value="diclo">diclo</option>
            <option value="keto">keto</option>
         </datalist>

         <input type="search" name='search2' list="doc2" id="inp2">
         <datalist id='doc2'>
            <option value="diclo">diclo</option>
            <option value="keto">keto</option>
         </datalist>

         <button name='btn'>Save</button>

   </form>
<?php
if(isset($_SESSION['error'])) { ?>

 <?= $_SESSION['error'] ?>

<?php }
unset($_SESSION['error']);
if(isset($_SESSION['one']) && isset($_SESSION['second'])) { ?>

<?= $_SESSION['one'] ?>

<?= $_SESSION['second'] ?>

   <form action="del.php" method='post'>
      <button name='btn1'>INTERACTION</button>
   </form>

<?php }
?>
<?php
if (isset($_SESSION['yes'])) {
   $getDrugInt = $model->getDrugInt($_SESSION['one'], $_SESSION['second']);
   for ($i = 0; $i < count($getDrugInt); $i++) { ?>

 <?= $getDrugInt[$i]['profDescription']?>

<?php   }
}
unset($_SESSION['yes']);
?>
<?php
unset($_SESSION['one'], $_SESSION['second']); ?>

new.php
session_start();
$arr = array('diclo', 'keto');

if(isset($_POST['btn'])) {
   unset($_SESSION['one'], $_SESSION['second']);
   $inputone = $_POST['search1'];
   $inputsecond = $_POST['search2'];
   if(in_array($inputone, $arr) && in_array($inputsecond, $arr)) {
      $_SESSION['one'] = $inputone;
      $_SESSION['second'] = $inputsecond;
      header('location: search.php');
   } else {
      $_SESSION['error'] = 'No results found';
      unset($_SESSION['one'], $_SESSION['second']);
      header('location: search.php');
   }
}

del.php
session_start();
if(isset($_POST['btn1'])) {
   $_SESSION['yes'] = true;
   header('location: search.php');
} else {
   $_SESSION['yes'] = false;
}

Thank you.


text:
Q: What for are the commonly used PKCS-Standards: PKCS#7, PKCS#10 and PKCS#12? What for are the commonly used PKCS-Standards: PKCS#7, PKCS#10 and PKCS#12?

A: PKCS#7 lets you sign and encrypt generic data using X.509 certificates. Also PKCS#7 format can be used to store one or more certificates without private keys (private keys can be put as a data payload and encrypted this way).
PKCS#10 defines format for certificate requests.
PKCS#12 provides a container for one or several certificates with private keys.

A: See on RSA: http://www.rsa.com/rsalabs/node.asp?id=2124.
UPDATED: It's funny, that the old URL still on. It's a pity, that it shows absolutely another content as more as 5 years before. RSALabs had nice list of all PKCS standards with good overview. The new web-site have a little close information (currently) under the location (see here, here and so on).


text:
Q: How to approach designing a 30GHz bandpass filter? How would one approach designing bandpass filters in the 3GHz - 30GHz range, each with ~2.4GHz bandwidth, for a 50Ω spectrum analyzer or sampling oscilloscope? I've learned how to implement some simple RF designs in the 1GHz-5GHz range, and some of what to look out for.

*

*What circuit topologies are used? (Eg. coupled line vs capacitive-gap resonator vs capacitive coupled shunt resonator.)

*Any active components?

*What bandwidths and falloffs can be expected?

A: For 30ghz, there likely are no commonly used active filter topologies.  However you can use galium arsenide FETs in this region to build various circuits (PA, LNA, mixer, VCO, etc), never seen them used at 30ghz but have seen them used for 24 Ghz I would think you could extend their operation to 30Ghz if care was taken.
Passive filters will definitely be implemented with microstrip structures, lumped elements will not be useful at these frequencies.  You'll also need to find a very good substrate to work at 30Ghz.
Falloff is dependent on the topology you use and the number of poles in the filter much as it would be at lower frequencies.  For instance Chebyshev filters are common.
My only experience near such frequencies was a 24Ghz FMCW radar front end, that used GaAs FETS for the PA, VCO, mixer, a hairpin bandpass filter and was built on Roger 5870 substrate.  I didn't do the RF design this was an externally sourced design and we ended up using a 10.5Ghz variant of it.
My initial thought is that your desired bandwidth is really wide, and that will greatly complicate the design.
Your best bet is to get a couple books on RF filter design, make sure your up on your calculus and start running some simulations using various topologies.  Ansoft Designer and Microwave Office are the two simulation packages that i've bumped into in the past for RF circuit simulation.  I believe they both have free trials.

A: Very late answer, but, I would think that 3 - 30 GHz is a wide enough passpand that you can implement the bandpass filter by cascading a low-pass filter (at 30 GHz) and a high-pass filter (at 3 GHz). Which simplifies your problem somewhat. But it doesn't mean that designing either of the two component filters for operation out to 30 GHz will be easy.
With this wide a band, you will probably not be able to use any simple transmission line structures to implement your filter, because that generally only works over a fraction of an octave. Some kind of distributed structure (multiple stubs of different lengths connected periodically to your main line) may be possible.

A: 30 odd GHz is quite a bit of bandwith.
There may be some useful info for you {here}.


text:
Q: What formula should i use on if and and question: if experience is more than 10 years and basic salary is less than 3000 and sales region is bedok then bonus is 1000, else if experience is more than 10 years and basic salary is less than 3000 and sales region is other region then bonus is 500, else bonus is 0
I have tried but result is all 0

A: For both Microsoft Excel and Google Sheets:
The formula you should use is as follows:
=IF(AND(EXPERIENCE>10, SALARY<3000), IF(REGION="bedok", 1000, IF(REGION<>"bedok", 500)), 0)

You must enter this formula in the BONUS cell.
Where:
EXPERIENCE is the cell where the experience is written to.
SALARY is the cell where the basic salary is written to.
REGION is the cell wehre the region is written to.
The statement works as follows:
IF(AND(EXPERIENCE>10, SALARY<3000)

If the experience is over 10 years and the salary is under 3000, then:
IF(REGION="bedok", 1000

If region is "bedok", set cell value to 1000, else:
IF(REGION<>"bedok", 500)), 0)

If region isn't bedok, set cell value to 500, else set value to 0.
In pseudo-code, it looks like this:
if experience > 10 and salary < 3000:
   if region == "bedok":
        bonus = 1000
    else if region != "bedok":
        bonus = 500
else:
    bonus = 0

This is what I understood to be your condition:
If someone has both more than 10 years of experience and salary of less than 3000, check if his region is "bedok" or something else. If the region is "bedok", set bonus to 1000, else if region is another region, set bonus to 500. Else, if that someone doesn't have more than 10 years of experience or has a salary of more than 3000, don't give any bonus (set bonu to 0).
Correct me if I'm wrong.


text:
Q: How can I capture data from the 'tooltip' in Fusioncharts that shows date/time? So, if you go to https://www.fusioncharts.com/dev/fusiontime/getting-started/create-your-multi-variate-chart-in-fusiontime and hover your mouse on the chart, you will see a tooltip that shows a startdate and an enddate and these dates update for each new point in the chart. Such as in this tooltip below.
Fusioncharts tooltip
I am looking to capture these updating dates and display a picture inside a div if it falls between these 2 dates.
These values update depending on which sample point it is within the data, it applies some simple algorithm within it to decide the duration between startDate and endDate but these dates are provided with a JSON file to the charts in this format:
..... [ "1/4/2011", 16.448 ], [ "1/5/2011", 272.736 ], ....
Where and what is it that I should look for that reflects these updating values? Is there a variable in the framework? You may or may not know about Fusioncharts but at some level, this problem boils down to being somewhat generic such as
"How to locate the variables within the Fusioncharts framework that reflect these dates from the data for each sample point?"
Any help is appreciated.
This is the link to Fusioncharts framework as CDN:
https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js
https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.timeseries.js
I am not sure what is it that I should even look for so I haven't been able to try it out

A: You can use the toolText property to set any tooltip text you want.
It should be something like this:
const dataset1 = [];
const dataset2 = [];

for (const row of data) {
  dataset1.push({
    value: row.value1,
    toolText: formatTooltipText(row.myDate1),
  });
  dataset2.push({
    value: row.value2,
    toolText: formatTooltipText(row.myDate2),
  });
}

const chart = {
  chart: myChartConfig,
  categories: myChartCategories,
  dataset: [
    {
      seriesname: mySeriesName1,
      color: myColor1,
      data: dataset1,
    },
    {
      seriesname: mySeriesName2,
      color: myColor2,
      data: dataset2,
    },
  ],
};
return chart;


text:
Q: Fair three-way sandwich division This question discusses fair three-way sandwich division. Mentoined solutions include
the Selfridge–Conway discrete procedure and the moving-knife procedure. I posed the question to the guys at the office and we can't think why this method would not be a solution:

*

*A makes the first cut.

*B makes the second cut.

*C chooses a piece.

*A chooses a piece.

*B gets the remaining piece.

Is this a solution? If not then why not?

A: Suppose that A thinks that he has cut the sandwich into 1/3 and 2/3, but B then cuts the piece which A thought was 1/3. C can now take the piece which A thinks is 2/3, and A is going to be very unhappy.


text: Q: Phonegap app suddenly quit after downloading the app from AppStore My app is live on the AppStore. I have used cordova 2.5. Past few days people give me the feedback that the app quit unexpectedly after downloading from the AppStore. The users with whom this problem occurred, mostly have iPhone 5 and iPod touch with iOS 7. I have download the app from the AppStore on iPhone5 on which iOS 7 is installed but it is working fine. I have already given the press release to 100 media channels and it is very crucial problem for me at this time. Please someone help me. I shall be thankful to you.


text:
Q: How to debug error "PHP Startup: Invalid library (maybe not a PHP library)" when install php extension ? I developed very simple php extension,  here's the source code:
https://github.com/jackey/nicequery
i did this:
phpize

./configure

make

make install

no error output , everything's OK.
then i edited php.ini to enable it.
but got error "PHP Startup: Invalid library (maybe not a PHP library)".
i checked the source code very carefully but not found any problem. :(
So can you give me any idea to debug the error like that and help to check the code where's the problem is ?
i fall into the stupid hole :(

A: the problem is
#ifdef COMPILE_DL_EXTNICEQUERY

ZEND_GET_MODULE(nicequery)

#endif

it should be
#ifdef COMPILE_DL_NICEQUERY

ZEND_GET_MODULE(nicequery)

#endif


text:
Q: Code Signed Application Generates Warning Message Being fully aware of the depreciation of SHA1 and having access to an SHA256 certificate (issued by Comodo) which I have installed to my system and am using to code-sign project executables (in this case, the project executable is an INNO compiled setup file), I am continuing to receive complaints from users about seeing this warning message :

This is the command that I am using to code sign with (I have added the path to SignTool.exe to the system Path variable so I do not qualify it completely when I call it; Also, the command is in a .bat file):
SignTool.exe sign /v /a /fd sha256 /du "http://www.foo.bar" %1

My first guess is that I am not using the SignTool sign command correctly. I know that the certificate is installed because I have seen it when I looked with the Certmgr.msc. More evidence that the code sign is successful :

Why is this still happening?

A: I'm not sure what the problem is specifically, but you can verify the signature after signing using SignTool.exe
I use it with the following arguments:
signtool.exe verify /pa /v [pathToSignedFile]


text:
Q: If I buy all DLC will the golden menu item "Downloadable Content" disappear? I was wondering if I can have "clean" menu if I own all of the Rocket-League's DLC.
Currently in the menu there are 4 items:

*

*Chaos Run

*Back to the Future™

*Revenge of the Battle-Cars

*Supersonic Fury

On Steam there is also Official Game Soundtrack.
I currently own only Back to the Future™ and in the menu it shows "Already Owned".
Anybody who has all of these 4 DLC, is the menu item still golden?

A: When you have purchased all of the in-game DLC, the Downloadable Content menu disappears. I have purchased all but the soundtrack and the image below is my menu (note no gold DLC option):

A: Based on my previous experience, owning Supersonic Fury, Revenge of the Battle-Cars, and the Back to the Future DLC when that was 100% of the available DLC, no, it is still highlighted/visible.
However, I cannot confirm this with all of the current DLC.


text:
Q: Joining Tables: Only (!) add missing rows I want to join the following tables (records, tip). Goal is that the missing WAR rows (dependend on the ID) will be added. For example you see that WAR = 2 is missing for ID = 80.
Note: WAR is always smaller or equal with the value of TIP. The value of Value should be NULL in the added rows. The table in the bottom is the goal.

I am not sure how to solve this problem. But a condition that results of this is records."TIP" >= tip."TIP".
I use HANA as database.
Thank you in advance. Best regards.

A: This is how it works (sorry all these TIPs are a little bit confusing):
   SELECT a."ID", b."TiP" "WAR", c."VAL" FROM (
        SELECT DISTINCT "ID", MAX("TIP") "max" FROM records t
        GROUP BY "ID"
    ) a
    INNER JOIN tip b ON 1=1
    LEFT JOIN T0 c ON a."ID" = c."ID" AND b."TiP" = c."WAR"
    WHERE b."TiP" <= a."max"
    ORDER BY a."ID", b."TiP"


text:
Q: About Theorem 5.13 in "Principles of Mathematical Analysis" by Walter Rudin L'Hospital's Rule L'Hopital's Rule I am reading "Principles of Mathematical Analysis" by Walter Rudin.
Thank you Saaqib Mahmood.
I copied and pasted your text
Theorem 5.13 on p.109:

Suppose $f$ and $g$ are real and differentiable in $(a, b)$, and $g^\prime(x) \neq 0$ for all $x \in (a, b)$, where $-\infty \leq a < b \leq +\infty$. Suppose
  $$ \frac{f^\prime(x)}{g^\prime(x)} \to A \ \mbox{ as } \ x \to a. \tag{13} $$
  If
  $$ f(x) \to 0 \ \mbox{ and } \ g(x) \to 0 \ \mbox{ as } \ x \to a, \tag{14} $$
  or if
  $$ g(x) \to +\infty \ \mbox{ as } \ x \to a, \tag{15} $$
  then
  $$ \frac{f(x)}{g(x)} \to A \ \mbox{ as } \ x \to a. \tag{16}$$
  The analogous statement is of course also true if $x \to b$, or if $g(x) \to -\infty$ in (15). Let us note that we now use the limit concept in the extended sense of Definition 4.33.

Here is Definition 4.33:

Let $f$ be a real function defined on $E \subset \mathbb{R}$. We say that
  $$ f(t) \to A \ \mbox{ as } \ t \to x, $$
  where $A$ and $x$ are in the extended real number system, if for every neighborhood $U$ of $A$ there is a neighborhood $V$ of $x$ such that $V \cap E$ is not empty, and such that $f(t) \in U$ for all $t \in V \cap E$, $t \neq x$.

And, here is Rudin's proof:

We first consider the case in which $-\infty \leq A < +\infty$. Choose a real number $q$ such that $A < q$, and then choose $r$ such that $A < r < q$. By (13) there is a point $c \in (a, b)$ such that $a < x < c$ implies
  $$ \frac{ f^\prime(x) }{ g^\prime(x) } < r. \tag{17} $$
  If $a < x < y < c$, then Theorem 5.9 shows that there is a point $t \in (x, y)$ such that
  $$ \frac{ f(x)-f(y) }{ g(x)-g(y) } = \frac{f^\prime(t)}{g^\prime(t)} < r. \tag{18} $$
  Suppose (14) holds. Letting $x \to a$ in (18), we see that
  $$ \frac{f(y)}{g(y)} \leq r < q \qquad \qquad \qquad  (a < y < c) \tag{19} $$
Next, suppose (15) holds. Keeping $y$ fixed in (18), we can choos a point $c_1 \in (a, y)$ such that $g(x) > g(y)$ and $g(x) > 0$ if $a < x < c_1$. Multiplying (18) by $\left[ g(x)- g(y) \right]/g(x)$, we obtain
  $$ \frac{ f(x) }{ g(x) } < r - r \frac{ g(y) }{g(x)} + \frac{f(y)}{g(x)} \qquad \qquad \qquad (a < x < c_1). \tag{20}$$
  If we let $x \to a$ in (20), (15) shows that there is a point $c_2 \in \left( a, c_1 \right)$ such that
  $$ \frac{ f(x) }{ g(x) } < q \qquad \qquad \qquad (a < x < c_2 ). \tag{21} $$
Summing up, (19) and (21) show that for any $q$, subject only to the condition $A < q$, there is a point $c_2$ such that $f(x)/g(x) < q$ if $a < x < c_2$.
In the same manner, if $-\infty < A \leq +\infty$, and $p$ is chosen so that $p < A$, we can find a point $c_3$ such that
  $$ p < \frac{ f(x) }{ g(x) } \qquad \qquad \qquad ( a< x < c_3), \tag{22} $$
  and (16) follows from these two statements.

Rudin didn't write $g(x) - g(y) \neq 0$ for any $x, y$ such that $a < x < y < b$ in $$ \frac{ f(x)-f(y) }{ g(x)-g(y) } = \frac{f^\prime(t)}{g^\prime(t)} < r. \tag{18} $$
Is this fact so obvious?
If so, please tell me the reason why this fact is so obvious.
I didn't think this fact was so obvious, so I proved:

By assumption, $g'(x) \neq 0$ on $(a, b)$.
  Let $x, y$ be any real number such that $a < x < y < b$.
  Let $x', y'$ be any real number such that $a < x' < x$ and $y < y' < b$.
  Then, $g$ is a differentiable function on $[x', y']$.
  By the Intermediate Value Theorem for derivatives (Theorem 5.12 on p.108),
$g'(x) > 0$ for all $x \in [x', y']$ or $g'(x) < 0$ for all $x \in [x', y']$.
  So, $g$ is strictly monotonically increasing on $[x', y']$ or $g$ is strictly monotonically decreasing on $[x', y']$.
  So $g(x) < g(y)$ or $g(x) > g(y)$.
  So, $g(x) - g(y) \neq 0$.


text:
Q: How to set up cron job in MySQL for windows server How to set up cron job in MySQL for windows server?
The purpose is for sending a reminder mail.
Any help would be appreciated

A: Create a Windows Service. Windows service will run like a cron job.

A: Use Windows Task Scheduler via Control Panel -> Scheduled Tasks or SchTasks.exe which is a CLI to Scheduled Tasks

A: cron job is specific to *nix based os for windows windows scheduler will be there
http://support.microsoft.com/kb/308569
follow this link for more details


text:
Q: How to redirect a HTTP request to localhost on windows? I've created a node.js app. When it runs my mobile phone can connect to it using address 192.168.1.5. In other words, when I open a browser on my phone and enter 192.168.1.5 I get a welcome page served by the app running on my PC.
The problem is that the IP address is not human friendly. Is there a way to access my app by an alias? For example, http://myapp or something like this?

A: Yes, these aliases are provided by the domain name service (DNS).  You need to set up a hostname on DNS to point to your machine's local address.
Put that IP address into a DNS server.
Here's a free way to do that.

*

*Create a FreeDNS account by visiting https://freedns.afraid.org/

*Click on Subdomains.

*Click the Add link.

*Create a subdomain hostname under one of FreeDNS's public domains. Maybe mydev.manidos.mooo.com is a good choice

*Put your machine's IP address into it.
Then, use https://mydev.manidos.mooo.com to hit your development machine's nodejs app.

You can pay FreeDNS to register your own domain name and use that if you prefer.
There are all sorts of other ways to register a domain and then add address records to it, to translate from hostnames to IP addresses.
Edit If you were connecting to and from your desktop / laptop machine, you could add a hostname to your hosts file. The hosts file is itself a little DNS registry that's local to your machine.  On windows it's at C:\Windows\System32\drivers\etc\hosts. On *nix and mac it's at /etc/hosts.
But, you are connecting to your app from a mobile device. Editing the hosts file in a mobile device is unreasonably difficult.


text:
Q: How to check whether the user is logged in? I try in my page "connexion.php" to verify whether the user is already logged or not. Normally, my code should work, but it doesn't. The error seems to appear in the redirection. Here is my code.
x

If i do a var_dump(), my $_SESSION['id'] does exist and if i had a echo''; after the header("Location: ../../Index/v/index.php");, the text is well displayed so the error seems to be in the redirection, even if it's written good.

A: A header() command will only actually work if it is sent to the client BEFORE any other tranfer of data has happened, so because you have already output the HTML from <!DOCTYPE html> to  the header() will be ignored.
Try doing that checking before you output any HTML
<?php
    //Ouverture session
    session_start();

    if(isset($_SESSION['id'])) {
        header("Location: ../../Index/v/index.php");
    }
?>
<!DOCTYPE html>

    <title>Undbe</title>
    <meta charset="utf-8" />

<?php

    if(isset($_COOKIE['login_email']) && isset($_COOKIE['login_pass']))
    {
        // Soon
    }

    else
    {
?>

Connexion

        <form method="post" action="../c/c_connexion.php">
            Votre email : <input type="email" name="email" id="email" />

            Votre password : <input type="password" name="password" id="password" />

            <input type="checkbox" name="remember" id="remember" /> Rester connecté.
            <input type="submit" value="Envoyer" />
        </form>
<?php
    }

?>


text:
Q: Does machine learning methods adjust confounding effect of the variables? I have implemented machine learning (RF) for analysis of a dataset, evaluating observations' survival.
After analysis (including variable importance) one of my collegues asked me that does ML method consider independent effect of a variable, like what we see in adjusted multivariate coxph analysis ?
I did not know the exact answer.
As I know in ML methods, for example RF, split rule is log rank test, which does not account and does not adjust the confounding effect of the other variables.
So for example if another variable has remarkable effect on both target and our variable of interest, based on logrank splitrule,RF would not know the confounding effect of another variable, and thinks that this is our variable of interest which causes the target.
So I don't know that if my conclusion is correct or not?
I did not find the answer in SE pointing out machine learning.
I really appreciate your help

A: Many machine learning models do not care about the effect of confounding variables, because they only care about the accuracy of the model, but not casual relationship between independent variables and dependent variable.
We can easily make an example using simulation: let variable $A$ have prior distribution of $P(A)$, and generate two other variables $B$ and $C$ with conditional distribution $P(B|A)$ and $P(C|A)$ given. Then generate the prediction target $Y$ from all three variables. Finally we can use random forest to predict and check the performance.
You can see, random forest will work "fine" on all variable included, although there are confounding variables exists.

A: Haitao Du is correct that this is the most common approach. Adam Kelleher references Sendhil Mullainathan in talking about machine learning vs social science as follows:

In machine learning, the goal is often just to reduce prediction
error, and not to estimate the effects of interventions in a system.
Social science is much more concerned with the effects of
interventions, and how those might inform policy. At IC2S2 recently,
in Sendhil Mullainathan's keynote, he called this the "beta-problem"
(the focus on the regression coefficients, more common in social
science) and the "y-hat problem" (the focus on the actual prediction,
more common in machine learning).

That said, as Adam also points out, people working in causal inference ML, building on work by Judea Pearl and others, bridge this gap between ML and social science as they are interested in the beta-problem.
The DoWhy package for causal inference in Python by Amit Sharma and Emre Kiciman is a good example. They're also working on a book on this. Another good example is the "Elements of Causal Inference: Foundations and Learning Algorithms" book by Jonas Peters and colleagues.