text:
Q: WCF error "there was no endpoint listening at ..." I'm creating my first WCF app. Client can communicate with host when those are on same computer, but failed from other computer on LAN. Both are console app.
Here is my code and config.
Client config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <system.serviceModel>
      <bindings>
         <wsHttpBinding>
            <binding name="WSHttpBinding_ICalculator" />
         </wsHttpBinding>
      </bindings>
      <client>
         <endpoint name="WSHttpBinding_ICalculator"
             address="http://192.168.100.6:8000/ServiceModelSamples/Service/CalculatorService"
             binding="wsHttpBinding"
             bindingConfiguration="WSHttpBinding_ICalculator"
             contract="ServiceReference1.ICalculator">
             <identity>
                <userPrincipalName value="saumitra\skpaul" />
             </identity>
         </endpoint>
      </client>
   </system.serviceModel>
</configuration>

Host code:
class Program
{
    static void Main(string[] args)
    {
        // Step 1 Create a URI to serve as the base address.
        Uri baseAddress = new Uri("http://Localhost:8000/ServiceModelSamples/Service");

        // Step 2 Create a ServiceHost instance
        ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress);

        try
        {
            // Step 3 Add a service endpoint.
            selfHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "CalculatorService");

            // Step 4 Enable metadata exchange.
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            selfHost.Description.Behaviors.Add(smb);

            // Step 5 Start the service.
            selfHost.Open();
            Console.WriteLine("The service is ready.");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();

            // Close the ServiceHostBase to shutdown the service.
            selfHost.Close();
        }
        catch (CommunicationException ce)
        {
            Console.WriteLine("An exception occurred: {0}", ce.Message);
            selfHost.Abort();
        }
    }
}

A: You can get an idea from this post
You can also use Socket Programming. Here is a very good example for mutli-client, two-way communication socket programming.

A: First ensure that the address used from the client is the correct location of the server. Your code is currently hard coded to the destination as...
<endpoint address="http://192.168.100.6:8000/

...but is the server actually running on 192.168.100.6?


text:
Q: What's the difference between compilation debug="false" and Release mode? In ASP.NET, what's the difference between building a project with  in the Web.config and with Release mode in the Configuration Manager?
When would you use one and not the other?

A: Here's the best explanation that I found:
http://odetocode.com/blogs/scott/archive/2005/11/15/debug-and-release-builds-in-asp-net-2-0.aspx

A: ScottGu did a pretty good right up of the differences here on his blog.
I typically use this mode when I need to do debugging inside of Visual Studio or if I'm trying to track down a particularly nasty bug.  So I usually run with debug mode to set to false.

A: Depending on how you set up your web app (Web Site model vs Web Application model), you might be deploying un-compiled source code directly to the web server.  In that case, the ASP.Net runtime needs to know how you want your code compiled when requests start coming in.

A: When compiling in "Release" mode, the web.release.config file will be used, when compiling in debug mode the web.debug.config file will be used (which both extend web.config). See here for more information on those files.
These files may contain a section like this:
<system.web>
    <compilation debug="true" />
    <!-- Lines removed for clarity. -->
</system.web>

In ASP.NET this setting controls whether bundling or minification is done to optimize page load time.

*

*Bundling means: Combine or bundle multiple files into a single file
(to reduce the number of page requests).

*Minification means: Removing unnecessary white space and comments and shortening variable names to
one character.

See here for more information on bundling and minification.
The default value for the ´debug´ is false, so the optimatzions are enabled per default.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Conversion failed when converting varchar into INT I know there are a lot of questions asked like this, but I have tried almost all of the solution, but still can't get that one piece of code to work :( Here's what I'm doing - I'm trying to find the number of rows in a table so that I can use that as a counter to loop and delete rows.
@rc is INT,
@tbname is varchar (500)
and @id is also INT.
This is my query:
set @rc='select count(*) from dbo.[' + @tbname + '] where id = ' + @id

I have also tried these:
set @rc='select cast(count(*) as varchar) from dbo.[' + @tbname + '] where id = ' + @id

and
set @rc='select count(*) from dbo.[' + @tbname + '] where id = ' + cast(@id as varchar)

And a few more permutation of placing cast here and there as well. I also tried changing the declaration of @rc as varchar, still get the same error.

A: Use sp_executesql in this case,
    DECLARE @retval int
    DECLARE @sSQL nvarchar(500);
    DECLARE @ParmDefinition nvarchar(500);

   DECLARE @rc          INT
            ,@str       NVARCHAR(MAX)
            ,@tbname    NVARCHAR(500) = 'Table1'
            ,@id        int

    set @str='select @rcOut = count(*) from dbo.[' + @tbname + '] where id = ' + CAST(@id as NVARCHAR)

    EXEC sp_executesql @str, N'@rcOut int OUTPUT',@rcOut = @rc OUTPUT;

    SELECT @rc;


text:
Q: Panel in grid causes horizontal overflow I'm using Twitter Bootstraps grid system and inside that I use their panels. I have two cols and in each col I have one panel. But this creates a horizontal scrollbar on my page.
I could probably disable the horizontal overflow. But I'd rather "fix" the problem in a cleaner way that Bootstrap is causing.
What would be a good way to solve this problem?
Example: http://www.bootply.com/iPdjlxuexk

Form widgets

        Panel content

Selected page widgets

        Panel content

If I wrap a

 around the row div, then the panels inside are really small. A big margin-left and margin-right apprears on the container. Not really what I'm after either.
http://www.bootply.com/BWMTAFeO8x

A: The problem is occurring because of the following HTML class:
col-md-6

Specifically, with Bootstrap, this means that whatever is currently in this column will extend to be 6 column spaces wide. This is not good if you are looking to only have something, let's say, 3 column spaces wide because it actually stretches what you are trying to do.
How do we fix it?
Use a smaller width space and then use Bootstraps ability to push/pull things. I will demonstrate what I mean via a JsFiddle, which is found here.
Basically, I altered your HTML to become the following:

Form widgets

                    Panel content

Selected page widgets

                    Panel content

NOTE
In my demonstration, I added the ability to view the panels in both a large screen setting and a medium screen setting versus just having it in a medium setting. I also had to push the columns according to the screen sizes. You can see this in effect with the JSFiddle by changing the width of the portion of the output screen in the demo. This is useful because you can see the difference between a large/medium sized screen to a small/extra-small sized screen.
More Information:
You can find more information on the grid system via the actual website. It will show you how the grid system is laid out and how you can use the push/pull aspect as well.
http://getbootstrap.com/examples/grid/


text:
Q: How to update OpenGL on Ubuntu 14.04 LTS with Intel graphic card I am trying to run Supertuxkart >= 0.9.2. It says that my video driver is too old. It wants OpenGL version 3 or greater. So I am trying to update OpenGL.
I have seen other posts about this issue (e.g. How to Update OpenGL with Intel graphics card Ubuntu 14.04 ), but none is working. So I am asking here.
The last thing I did was:
sudo apt-get install --install-recommends xserver-xorg-lts-xenial libqt5gui5 libgles1-mesa-lts-xenial libgles2-mesa-lts-xenial libgl1-mesa-glx-lts-xenial libgl1-mesa-glx-lts-xenial:i386 libglapi-mesa-lts-xenial:i386 libegl1-mesa-lts-xenial libwayland-egl1-mesa-lts-xenial libgbm1-lts-xenial libgl1-mesa-dri-lts-xenial

This updated mesa. I now have
OpenGL vendor string: Intel Open Source Technology Center
OpenGL renderer string: Mesa DRI Intel(R) 945GM x86/MMX/SSE2
OpenGL version string: 1.4 Mesa 11.2.0

However, supertuxkart still says I have OpenGL 2:
[info   ] IrrDriver: OpenGL version: 2.1
[info   ] IrrDriver: OpenGL vendor: Intel Open Source Technology Center
[info   ] IrrDriver: OpenGL renderer: Mesa DRI Intel(R) 945GM x86/MMX/SSE2
[info   ] IrrDriver: OpenGL version string: 1.4 Mesa 11.2.0

My graphic card is:
$ lspci
...
00:02.0 VGA compatible controller: Intel Corporation Mobile 945GM/GMS, 943/940GML Express Integrated Graphics Controller (rev 03)
...

Why OpenGL was not updated?
Thanks in advance.
Update
Thanks Doug. Indeed, my graphic card does not support OpenGL version 3 or greater. I have verified it using OpenGL Extension Viewer. So, this is why nothing was working for updating OpenGL.


text:
Q: Digiwack File Utilities example code? My app allows users to select a file on their Android device. How can my app use Digiwack File Utilities on Android?

A: In activity code, call it this way:
Intent in = new Intent("com.digiwack.util.FileSelect");
in.putExtra("currFolder",Environment.getExternalStorageDirectory().toString());
in.putExtra("operation",0); //indicates "select" operation
//in.putExtra("operation", 1); //indicates "save" operation
//in.putExtra("operation", 2); //indicates "load" operation
startActivityForResult(in, 1); //or any result-code will do

In activity's onActivityResult() method, add this part:
if (resultCode==RESULT_OK && requestCode==yourRequestCode) {
    String filename = data.getExtras().getString("selectedFile");
    if (filename!=null) {
       //user selected a file
       File yourFile = new File(filename);
       //use yourFile as your app see's fit from here on out
    }
}


text:
Q: Toggle from Left to Right issue I was trying to have a navigate toggle list from left to right side.If i click the button,the list should come as native android app in css,But the list should slide from left to right.
$(".logo").click(function()
                {
                    $(".sidebar_list").toggle('slide');
                });

FIDDLE
Example Image:

A: I got my Expected answer..
Here is my code.
$(".logo").click(function()
                {
                    $(".sidebar_list").animate({
                    width: 'toggle'
                }, 100)
                });

FIDDLE


text:
Q: ¿Cual es la razon de ser de saved id en UNIX? No se cual es la diferencia
Estoy aprendiendo con este tutorial, exactamente de lo que estoy preguntando se empieza a hablar en el minuto 35:12.

*

*real id: Es el usuario que inicio el proceso, segun he entendido

*effective id: Es el usuario que determina los privilegios

*saved id: la llamada al sistema exec inicializa este id de usuario de
manera que este valor es igual al de effective id

No se muy bien como es lo del saved id, hasta donde he entendido es como tener el effective id repetido dos veces. ¿En que se diferencia saved id del effective id de un proceso en cuestión?

A: X lo que veo x ahí, el saved user id (suid)se utiliza cuando un programa con altos privilegios necesita hacer acciones que requieren privilegios más bajos. En ese caso se guarda el effective user id (euid) en el suid para poder volver a setear el euid al valor original más adelante. https://en.m.wikipedia.org/wiki/User_identifier


text:
Q: good free PDF library for Delphi is there a good and free PDF generator library for delphi ?
I need one with multipage + graphics support.

A: SynPDF.pas
PDF file generation
this unit is a part of the freeware Synopse framework,
licensed under a MPL/GPL/LGPL tri-license; version 1.16
http://synopse.info

A: I'm using PDFtoolkit VCL, it is excellent. Works in Delphi 7 to Delphi 2010.

A: Can be easy ported to Delphi.
The library "Free JPDF Pascal" is written entirely in "Free Pascal" pure. It was created from the conversion of the FPDF library code written in PHP (http://www.fpdf.org).
You do not need the LCL. It can be used to generate PDF reports for Desktop Applications, Web CGI and / or Mobile.
Download: http://github.com/jepafi/Free-JPDF-Pascal

A: I have been using wPDF for about three years. It is simple to use, comes with examples, and can be extended pretty easily. It works with old and new versions Delphi up to 2010. It's not free but it does have a trial.

A: this article is in portuguese, but it can help you:
http://www.devmedia.com.br/articles/viewcomp.asp?comp=11767
regards

A: Free power pdf
www.est.hi-ho.ne.jp/takeshi_kanno/powerpdf

A: There is also Quick PDF Library, which I have not used myself but only had a quick look at the trial. They have a Lite version (ActiveX only) which is free, and which may meet your needs.


text:
Q: converting ascii to an interger (C) I'm brand new to C and i'm working on a method that converts an ascii to an integer. So bascially if i have  ABCD (base 16) ill get 43981 (base 10).. Just a short walk through of what i have. I take one digit at i time from the string then that number needs to be translated so i call my chartoint method. Then i think i need to * the pervious result by the base before i add the new number. I am also confused on the printf method. Here is my method so far.
void ascii2int(char *ascii, int base){
    int totalstring = 0;
    if(2<= base && base <= 16){
        for (int i = 0; i < strlen(ascii); i++) {
            // Extract a character
            char c = ascii[i];
            // Run the character through char2int
            int digit = char2int(c);
            totalstring= digit * base;
            printf("%d/n",totalstring);
        }
    }
}

char2int
 int char2int(char digit){
    int converted = 0;
    if(digit >= '0' && digit <= '9'){
    converted = digit - '0';
    }
    else if( digit >= 'A' && digit <= 'F'){
    converted = digit - 'A' + 10;
    }
    else{
    converted = -1;}
return converted;
}

A: Assuming that function char2int is implemented correctly...
Change this:
totalstring = digit * base;

To this:
totalstring *= base;  // totalstring = totalstring * base
totalstring += digit; // totalstring = totalstring + digit

Or to this:
totalstring = totalstring * base + digit;

In addition, call printf outside the for loop (and change that /n to \n).

A: Solution :
void ascii2int(char *ascii, int base){
//int digit = 0;
int totalstring = 0;
if(2<= base && base <= 16){
for (int i = 0; i < strlen(ascii); i++) {
    // Extract a character
    char c = ascii[i];
    // Run the character through char2int
    int digit = char2int(c);
totalstring = totalstring * base + digit;
        }
printf("%d", totalstring);

}

}


text:
Q: How can i check whether the filename exist in specific folder I have the following code to update document path field but i like to check first if the file name is exist on the specified folder or not. if the file exist i would like to update the field with the path otherwise skip the update
My code looks shown below
  use WITESTCO
  update [WITESTCO].[dbo].[WIITEMX]
  set [docPath]='\\ABC-SERVER\Data\ABC PRODUCTION\DRAWING\2500000 - 2599999 WHL ASSY\PDF\'+[WITESTCO].[dbo].[WIITEMX].[itemId]+'.pdf' FROM [WITESTCO].[dbo].[WIITEMX] where itemId like '2500%' or itemId like '2501%'

A: I bet this function will work under normal circumstances.
master.dbo.XP_FileExist

I know it will work on the local file system of the SQL instance, however, UNC filenames may or may not work. I have not tested.


text:
Q: symfony doctrine how to reverse entityManager->persist() I am editing an entity, and upon some manual validation error I want to write a log message to the DB, but when I flush that message, the entity under editing is also flushed to DB. I have tried entityManager->clear() but that throws errors about entity configuration (seems like I need additional cascade configuration on my entities in order to use that).
Is there no simple way of just reversing the entityManager->persist()?
What I want is to be able to NOT persist some of the entities previously called ->persist() on (or fetched from the DB thus automatically being persisted).
Edit function:
public function editAction(Request $request, price $price)
{
    $deleteForm = $this->createDeleteForm($price);
    $editForm = $this->createForm(\App\Form\priceType::class, $price);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {

        //check start before stop
        if ( $price->getDateFrom() >= $price->getDateTo()) {
            //$this->em->clear(); //not working
            $this->helper->flash('fail','Du kan inte sätta prisavtalets startdatum till efter eller samma som dess slutdatum, då skulle det inte tillämpas på någon extraöppning.',$price->getACRGroup());
            return $this->render('price/edit.html.twig', array(
                'price' => $price,
                'edit_form' => $editForm->createView(),
                'delete_form' => $deleteForm->createView(),
            ));
        }

And the logging function:
 public function flash($type,$message,$unit=null)
 {

        //REMEMBER when using this logger - use it AFTER your entity work is done (either flushed or $em->clear()

        // currently $type can be 'success', 'fail' or 'warning'.

        //find out (from services.yaml) if this install is set up to store every message (fails and warnings also) or just success (success means something was changed so always store a log on that)
        if (
            ($type == 'fail' && $this->globalParameters->get('systemlog_save_errors') == 0)
            ||
            ($type == 'warning' && $this->globalParameters->get('systemlog_save_warnings') == 0)
            ) {
            return false;
        }

        if ($type == 'fail') {
            $type = 'error';
        }

        //This is important as the flush() below will otherwise flush ANY ENTITY IN EDIT unless that was explicitly removed from entityManager ( $em->clear() ). DANGER! You will easily and inadvertently save unverified data.
        /*
        if ($type == 'error') {
            $this->em->clear(); //not working
        }
        */

        //create log entry
        $em = $this->em;
        $now = new \DateTime("now");

        $entity  = new Systemlog();
        $entity->setACRGroup($unit);
        $entity->setemail($this->security->getUser()->getEmail());
        $entity->setTime($now);
        $entity->setEventType($type);
        $entity->setEventMessage($message);

        $em->persist($entity);
        $em->flush();
    }


text:
Q: Working asynchronously with jsctypes in restartless extension I have a small bootstrapped extension that loads a dll file at startup() and holds it in a global variable. I don't know exactly how to use this properly maybe you will correct me on this, but I'm more interested in knowing if the functions I use from the dll file can be called asynchronously.
Right now what I'm doing is :
Components.utils.import("resource://gre/modules/ctypes.jsm");
log = function(str) { Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService).logStringMessage(str+'\n'); }

var lib;
var someFunc;

...

function startup(aData, aReason) {
   lib = ctypes.open(dllPath);
   if(!lib)
   {
      log("dll load error");
      lib = null;
      return;
   }
   else
   {
      var initDll = lib.declare("Init", ctypes.default_abi, ctypes.long);
      var status = initDll();
      log("Dll returned " + status);

      if(status == ctypes.long(0))
      {
         someFunc = lib.declare("SomeFunc", ctypes.default_abi, ctypes.long, ctypes.long);
      }
   }
}

Once I have someFunc I use it in the code quite often, but the call takes a long time. Is there a way to call it asynchronously? Or to call it in such a way that Firefox doesn't freeze for the duration of the call?

A: If the external (bound via ctypes) API isn't itself asyncrhonous, by definition you're not going to be able to call it asynchronously in JavaScript.
The easiest workaround is to use some kind of WebWorker to call the API in a background thread. Seeing as you need to do some privileged stuff, the ChromeWorker APIs fit the bill.
The mechanics of it are:

*

*Launch the ChromeWorker (a.k.a the 'worker')

*Send the 'worker' a message via postMessage to kick off the 'job'

*The message event handler in the 'worker' should load ctypes and make the synchronous call to the external code, and then...

*Have the 'worker' send a message via postMessage to the caller (your main code) to say (effectively, "I'm done").

If the external API requires call-specific arguments, you could organise to post those via the first postMessage. If the external API returns anything significant, you could organise to receive those via the second postMessage.
All of that will look a bit fiddly, so you'll want to package it into a JavaScript code module; that will allow you to separate the ctypes stuff from the rest of your code, and you can use createEvent and dispatchEvent in the calling thread (inside the module) to make the API seem asynchronous but hide the 'worker' part.

A: This here shows how to use different functions with jsctypes. It may not be specific to your stuff above, if this doesn't help you out let me know and I'll take a look at your specific case.
const {Cc, Ci, Cu} = require('chrome');
Cu.import("resource://gre/modules/ctypes.jsm");

/*start getcursorpos*/
var lib = ctypes.open("user32.dll");

/*foreground window stuff*/
var FindWindowA = lib.declare('FindWindowA', ctypes.winapi_abi, ctypes.uint32_t, ctypes.jschar.ptr, ctypes.jschar.ptr)
var GetForegroundWindow = lib.declare('GetForegroundWindow', ctypes.winapi_abi, ctypes.uint32_t)
function doFindWindow() {
    var wm = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
    var title = wm.getMostRecentWindow('navigator:browser').gBrowser.contentDocument.title;
    Cu.reportError('title=' + title)
    var ret = FindWindowA('', title + ' - Mozilla Firefox');
    //var ret = GetForegroundWindow();

    Cu.reportError(ret);
}
/*end foreground window stuff*/

/* Declare the signature of the function we are going to call */
const struct_lpPoint = new ctypes.StructType("lpPoint",
                        [ { "x": ctypes.int },
                          { "y": ctypes.int } ]);
var GetCursorPos = lib.declare('GetCursorPos', ctypes.winapi_abi, ctypes.bool, struct_lpPoint.ptr);

function doGetCursorPos() {
        var point = new struct_lpPoint;
        var ret = GetCursorPos(point.address());
        Cu.reportError(ret);
        Cu.reportError(point);
}
/*end getcursorpos*/

/*start setcursorpos*/
//var lib = ctypes.open("user32.dll"); //already called on line 4
var SetCursorPos = lib.declare('SetCursorPos', ctypes.winapi_abi, ctypes.bool, ctypes.int, ctypes.int)

function doSetCursorPos() {
    var ret = SetCursorPos(10, 10);
}
/*end setcursorpos*/

/*start mouse_event*/
//used to click
//const DWORD = ctypes.uint32_t; //this just shows you that DWORD == ctypes.uint32_t
var mouse_event = lib.declare('mouse_event', ctypes.winapi_abi, ctypes.void_t, ctypes.uint32_t, ctypes.uint32_t, ctypes.uint32_t, ctypes.uint32_t, ctypes.uintptr_t);
const MOUSEEVENTF_LEFTDOWN = 2;
const MOUSEEVENTF_LEFTUP = 4;

function domouse_event() {
    var ret = mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
    var ret = mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
}
/*end mouse_event*/

/*start MessageBoxW*/
//var lib = ctypes.open("user32.dll"); //already called on line 4
var MessageBoxW = lib.declare('MessageBoxW', ctypes.winapi_abi, ctypes.int32_t, ctypes.int32_t, ctypes.jschar.ptr, ctypes.jschar.ptr, ctypes.int32_t);
var MB_OK = 0;

function doMessageBoxW() {
    var ret = MessageBoxW(0, "Hello world", "title", MB_OK);
}

/*end MessageBoxW*/

exports.main = function (options, callbacks) {

};

exports.onUnload = function (reason) {
    lib.close();
}

var { Hotkey } = require("hotkeys");

var showHotKey = Hotkey({
    combo: "alt-w",
    onPress: function() {
        /*setcursor stuff*/
        //doSetCursorPos();
        //domouse_event();
        /*setcursor stuff*/

        /*foreground stuff*/
        doFindWindow();
        /*foreground stuff*/
    }
});

Other jsctype topics on stackoverflow I found useful:
* Javascript String to C++ char pointer -LPSTR buffer in JSCTypes
* FF addon: How to declare C function fgets in javascript


text:
Q: BigQuery - removing duplicate records sometimes taking long We implemented following ETL process in Cloud: run a query in our local database hourly => save the result as csv and load it into the cloud storage => load the file from cloud storage into BigQuery table => remove duplicate records using the following query.
SELECT
  * EXCEPT (row_number)
FROM (
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY id ORDER BY timestamp DESC) row_number
  FROM rawData.stock_movement
)
WHERE row_number = 1

Since 8 am (local time in Berlin) this morning the process of removing duplicate records takes much longer than it usual does, even the amount of data is not much different than it usual is: it takes usually 10s to remove duplicate records whereas this morning sometimes half an hour.
Is it the performance to remove duplicate record not stable?

A: It could be that you have many duplicate values for a particular id, so computing row numbers takes a long time. If you want to check for whether this is the case, you can try:
#standardSQL
SELECT id, COUNT(*) AS id_count
FROM rawData.stock_movement
GROUP BY id
ORDER BY id_count DESC LIMIT 5;

With that said, it may be faster to remove duplicates with this query instead:
#standardSQL
SELECT latest_row.*
FROM (
  SELECT ARRAY_AGG(t ORDER BY timestamp DESC LIMIT 1)[OFFSET(0)] AS latest_row
  FROM rawData.stock_movement AS t
  GROUP BY t.id
);

Here is an example:
#standardSQL
WITH T AS (
  SELECT 1 AS id, 'foo' AS x, TIMESTAMP '2017-04-01' AS timestamp UNION ALL
  SELECT 2, 'bar', TIMESTAMP '2017-04-02' UNION ALL
  SELECT 1, 'baz', TIMESTAMP '2017-04-03')
SELECT latest_row.*
FROM (
  SELECT ARRAY_AGG(t ORDER BY timestamp DESC LIMIT 1)[OFFSET(0)] AS latest_row
  FROM rawData.stock_movement AS t
  GROUP BY t.id
);

The reason that this may be faster is that BigQuery will only keep the row with the largest timestamp in memory at any given point in time.


text:
Q: Creating a new SQL relational database (MSSQL) from 2 other tables Good day!
I really need your help with this, as I am in unfamiliar territory when it comes to MSSQL and building relational databases.
I typically read and write SQL data (1 table, with columns and row data), but i'd like to know how I would go about creating a relational database where I can reference both my office data with my employee data in the table tbl_accdb_assignment.
Ie. Assign an employee to a single office but also being assign multiple employees who are sharing and sitting in the same office (as displayed in my example below in excel for easy viewing)
What would be the SQL query format to ADD, DELETE, & UPDATE office data with employee data?

A: basically you'd have a table with employee information and a separate table that keeps track of locations in the building(s).  You'd use foreign and primary keys to link the two tables.  To ensure you don't have any employee in more than one location you'll have to write checks to kick out should an employee be found more than once on the locations table.
For such an example I'd probably have three tables, an employee table, a location table, and a table that links the two an employee-location table.  Hopefully that helps.

A: Like this (you can extend this example)
CREATE TABLE Office(ID INT PRIMARY KEY, Name VARCHAR(100));
CREATE TABLE Employee(ID INT PRIMARY KEY, Name VARCHAR(100));
CREATE TABLE OfficeEmployee(OfficeID INT, EmployeeID INT,
  CONSTRAINT PK_OfficeEmployee PRIMARY KEY (OfficeId, EmployeeID),
  CONSTRAINT FK_OfficeEmployee_EmployeeID__Employee_ID FOREIGN KEY (EmployeeID) REFERENCES Employee(ID),
  CONSTRAINT FK_OfficeEmployee_OfficeID__Office_ID FOREIGN KEY (OfficeID) REFERENCES Office(ID)
);


text:
Q: how to post on Linkedin group with javascript? I am trying to post on my group using JavaScript API but getting error Access to write groups denied (403 Forbidden)
How can I solve this error?
IN.API.Raw("/groups/" + 10356772 + "/posts?format=json")
.method("POST")
.body(JSON.stringify({"title": "hi title", "summary": "hi summary"})) .result(onSuccess)
.error(onError);

A: where are you trying to run this script? In the actual Linkedin page under the dev tools console?
You should take a deeper look at the headers sent when you publish a post the proper way. Maybe there's some sort of mechanism to actually prevent this, to avoid spam.
I can imagine them generating a token everytime you open the textarea which validates the post etc.
Try to go through the whole process, and check what kind of cookies and headers they generate before just trying to post and see if you are lucky.


text:
Q: Show that $\{ x = (x_n) \in H^\infty: |x_k - y_k| < \epsilon, k = 1, ..., N\}$ is open in $H^\infty$ Given is $y = (y_n) \in H^\infty$, $N\in\mathbb{N}$, and $\epsilon > 0$, where $H^\infty$ is the Hilbert cube.
Question: How do I show that $\{ x = (x_n) \in H^\infty: |x_k - y_k| < \epsilon, \,\,k = 1, ..., N\}$ is open in $H^\infty$.
Before trying this exercise I never heard about the Hilbert cube. I now know that it's the carthesian product of the intervals [0,1/n], but I have no idea how to proceed from here.
Thanks in advance!

A: Your description of the Hilbert cube is not correcct.
$H^\infty$ is the set aof all real sequences $u=(u_n)$ with $0 \le u_n \le 1$ for all $n$.
For $u,v \in H^\infty$  define
$d(u,v):=\sum_{n=1}^{\infty}\frac{|u_n-v_n|}{2^n}$.
Then $( H^\infty, d)$ is a metric space.
Now let $M=\{ x = (x_n) \in H^\infty: |x_k - y_k| < \epsilon, \,\,k = 1, ..., N\}$.
Are you now in a position to show that $M$ is open in $( H^\infty, d)$ ?


text:
Q: Deploy VM from template and set VM and DNS name I'm using pyVmomi to deploy a VM from a template on vSphere,
this woks ok, the new VM get the name I sent as parameter but I want that the DNS name \ hostname will be same as VM.
Is there a way to set the hostname when doing the actual clone ?
If not how can I do that after the new VM was created ?
Here is part of the code I'm using:
# RelocateSpec
relospec = vim.vm.RelocateSpec()
relospec.datastore = datastore
relospec.pool = resource_pool

# ConfigSpec
configSpec = vim.vm.ConfigSpec()
configSpec.annotation = "This is the annotation for this VM"

# CloneSpec
clonespec = vim.vm.CloneSpec()
clonespec.location = relospec
clonespec.powerOn = power_on
clonespec.config = configSpec

print ("cloning VM...")
task = template.Clone(folder=destfolder, name=vm_name, spec=clonespec)
wait_for_task(task)

A: I think you need a clonespec.customization (vim.vm.customization.Specification). You should be able to specify the hostname there somehow or other.
Oh, as far as I know VMware Tools must be installed for guest OS customization.
Hope that helps.


text:
Q: Process Scheduling from Processor point of view I understand that the scheduling is done by the kernel. Let us suppose a
process (P1) in Linux is currently executing on the processor.
Since the current process doesn't know anything about the time slice
and the kernel is currently not executing on the processor, how does the kernel schedule the next process to execute?
Is there some kind of interrupt to tell the processor to switch to execute the kernel or any other mechanism for the purpose?

A: In brief, it is an interrupt which gives control back to the kernel. The interrupt may appear due to any reason.
Most of the times the kernel gets control due to timer interrupt, or a key-press interrupt might wake-up the kernel.
Interrupt informing completion of IO with peripheral systems or virtually anything that changes the system state may
wake-up the kernel.
More about interrupts:
Interrupts as such are divided into top-half and bottom half. Bottom Halves are for deferring work from interrupt context.
Top-half: runs with interrupts disabled hence should be superfast, relinquish the CPU as soon as possible, usually
1) stores interrupt state flag and disables the interrupts(reset
some pin on the processor),
2) communicates with the hardware, stores state information,
delegates remaining responsibility to bottom-half,
3) restores the interrupt state flag and enables the interrupt((set
some pin on the processor).

Bottom-half: Handles the deferred work(delegated work by the top-half) runs with interrupts enabled hence may take a while before completion.
Two mechanisms are used to implement bottom-half processing.
1) Tasklets
2) Work queues

.
If timer is the interrupt to switch back to kernel, is the interrupt a hardware interrupt???

The timer interrupt of interest under our context of discussion is the hardware timer interrupt,
Inside kernel, the word timer interrupt may either mean (architecture-dependent) hardware timer interrupts or software timer interrupts.
Read this for a brief overview.
More about timers
Remeber "Timers" are an advanced topic, difficult to comprehend.

is the interrupt a hardware interrupt??? if it is a hardware
  interrupt, what is the frequency of the timer?

Read Chapter 10. Timers and Time Management
if the interval of the timer is shorter than time slice, will kernel give the CPU back the same process, which was running early?

It depends upon many factors for ex: the sheduler being used, load on the system, process priorities, things like that.
The most popular CFS doesn't really depend upon the notion of time slice for preemption!
The next suitable process as picked up by CFS will get the CPU time.
The relation between timer ticks, time-slice and context switching is not so straight-forward.
Each process has its own (dynamically calculated) time slice. The kernel keeps track of the time slice used by the process.
On SMP, the CPU specific activities such as monitoring the execution time of the currently running process is done by the interrupts raised by the local APIC timer.
The local APIC timer sends an interrupt only to its processor.
However, the default time slice is defined in include/linux/sched/rt.h
Read this.

A: Few things could happen -
   a. The current process (p1) can finish up its timeslice and then the
   scheduler will check is there is any other process that could be run.
   If there's no other process, the scheduler will put itself in the
   idle state. The scheduler will assign p1 to the CPU if p1 is a CPU hoggy
   task or p1 didn't leave the CPU voluntarily.

   b. Another possibility is - a high priority task has jumped in. On every
   scheduler tick, the scheduler will check if there's any process which
   needs the CPU badly and is likely to preempt the current task.

In other words, a process can leave the CPU in two ways - voluntarily or involuntarily. In the first case, the process puts itself to sleep and therefore releases the CPU (case a). In the other case, a process has been preempted with a higher priority task.
(Note: This answer is based on the CFS task scheduler
of the current Linux kernel)


text:
Q: NServiceBus & IIS NSB 4.6.1
IIS 7.5 - Recyling for this pool is turned off
I am hosting a handler inside of a IIS web appblication which forwards messages to web clients over SignalR. These messages are sent from other NSB services. The problem I run into is that in production the handler for these messages will randomly stop consuming messages from the queue and I have to restart iis to get it to start again. I can't reproduce this issue outside of production, and I cannot find any information in any of my logs.
Anyone have any ideas on what may be causing this?
My NSB configuration
var bus = NServiceBus.Configure.With()
                      .StructureMapBuilder(container)
                      .UseTransport<Msmq>()
                      .UnicastBus()
                      .PurgeOnStartup(false)
                      .CreateBus();

A: can you try to configure IIS as always running and see if the behavior changes?
http://msdn.microsoft.com/en-us/library/ee677261(v=azure.10).aspx
.m


text:
Q: Consequence of the Lax-Milgram theorem I have the following problem:
Let H be a $\mathbb{K}$-Hilbertspace, with finite dimensional subspaces $H_n\subset H, n\in \mathbb{N}$, so that $H_n\subset H_{n+1} \forall n\in \mathbb{N}$ and $\bigcup_{n=1}^\infty H_n$ is dense in H. Also $x'\in H'$ and $a:H \times H\rightarrow \mathbb{K}$ is a continuous, coercive Sesquilinear form.
i) Show: For every sequence $(x_n)_{n\in \mathbb{N}}$ in H is true: $$x_n\rightarrow x\Leftrightarrow x_n\rightharpoonup x \cap lim_{n\rightarrow \infty}  a(x_n,x_n)=a(x,x)$$ for $n\rightarrow \infty$
ii) Show: $\forall n\in \mathbb{N}$ there is exactly one $x_n\in H_n$ so: $$a(y,x_n)=x'(y)\forall y\in H_n$$
iii) $(x_n)_{n\in\mathbb{N}}$ is the in ii) constructed sequence and $x\in H$ is the unique solution of $a(y,x)=x'(y)\forall y\in H$.
Show: $x_n\rightarrow x$ for $n\rightarrow \infty$
I already showed i).
For ii): In the lecture we have the following consequence of the Lax-Milgram theorem:

Let $A\in L(H)$ be defined like in the Lax-Milgram theorem and $H$ is a Hilbertspace and $J$ is the isometry of the Riesz representation theorem. For $u'\in H'$, $u:=A^{-1}J^{-1}u'$ is the unique solution to $$a(v,u)=u'(v) \forall v\in H$$
It is also true: $$||u||_H\le\frac{1}{\alpha} ||u'||_{H'}$$

Since $a$ is a continuous, coercive Sesquilinear form I could use this theorem if I'm able to show that every $H_n$ is a Hilbertspace as well. Is it right to say that, since the $H_n$ are subspaces they are also Hilbertspaces?
If that is the case then ii) should be proofed, right?
For iii) I have no idea how to show that. Can someone help me?


text:
Q: How to restrict torrent download over WIFI? I have a DLink WIFI router with "admin" rights. I want to restrict torrent and other download over network. Please help. I am new to networking.

A: Two options jump to mind.

*

*Block common bittorrent ports.
Most routers allow you to block certain ports, so you could block 6881 - 6999.  That would cut out a significant amount.

*Block common trackers.
Again, most routers provide the opportunity to block connections to certain websites.  If you do a bit of research, you could find the common trackers.  I will use one that is no longer around for an example: block: *.demonoid.*, for example.
If your reason is legality, I would go with option 2 because not all bittorrent is illegal (it's a very effective way to transmit large amounts of data - example: Linux Distros).
If your reason is just bandwidth - then the port method would be more effective.  Or a combination of the two.  Of course, there are always ways around it if someone is determined enough.


text:
Q: Angular jasmine SpyOn service call that throws an error makes the test fail I want to test the following method from my component:
  mymethod() {
    this.myservice.dostuff().subscribe((data: any) => {
      console.log(data)
      this.passed= true

    }, err => {
      console.log(err)
      this.passed= false

    })
  }

and this is the test I wrote:

  it('if error thrown', fakeAsync(() => {
    spyOn(myservice, "dostuff").and.throwError("error");
    fixture.detectChanges()
    component.mymethod()
    tick(1)
    expect(myservice.dostuff).toHaveBeenCalled();
    expect(myservice.dostuff).toThrowError("error");
    expect(component.passed).toBe(false);
    flush()
  }));

but I must be missing something cause when I run the test, it fails with the following message:
MyComponent On failed login
Error: error

A: You should use throwError to mock what happens when your service encounters an exception. This will trigger your expected error callback.
Your service is expected to return an observable. As you have currently written, the service isn't returning anything - it's just throwing an exception. By using throwError and returnValue you return an observable that immediately throws, which triggers the expected callback.
spyOn(myservice, 'dostuff').and.returnValue(throwError('someError'));


text:
Q: Testing "output" with rspec and rails I'm having a hard time learning how to implement appropriate testing with rspec and rails.
Speaking generally, how does one test the "hard cases" such as did a file get generated or was an image properly resized? Currently, to me it seems that unit testing is designed for testing the transformation of values rather than making sure data is processed and output appropriately.

A: TL;DR You should explore for different tools and don't shy away from the "hard cases" that may not seem like traditional "unit tests". The hard cases often are testable.
Testing is definitely a rabbit hole. From the surface, it seems so nice and clean, but as you get in to it, the rabbit hole goes quite far down, and this is one example: how do you test these things? You want to be confident that your code is doing the right thing, but you also don't want to create too complicated and unmanageable tests, and you don't want to test too fine-grained either.
However, to your specific questions, I do have some ideas you may wish to look in to.
For testing that a file got generated, you can check to see that initially the file did not exist (ruby has File.exists?) and then you can, after some method, check to see if it does exist. Of course you have questions like, "Does it have the right content?", "Did it finish to completion?", and you can test that stuff too by opening the file and checking it.
For the images, you probably can find facilities that allow you to check the properties of an image (perhaps Paperclip? Never used it but it's a well known gem). So you can do something like this (in sort-of psuedo code, because I don't know of a tool to do this):
it "resizes the image" do
    img = Image.open_image("pic.png")
    img[:size].should eq [100, 100]
    img.close

    resize_image

    image = Image.open_image("pic.png")
    imge[:size].should eq [25, 25]
    img.close
end

Testing often relies on finding more and more helpful gems/tools to massage situations. "Unit" tests will, yes, only check the unit level code and they may be very simple, but not always. But then you start looking in to library specs, request specs, routing specs, acceptance tests, controller specs, etc. There are lot of tools out there and research is key.
But again, the examples you listed may not be unit tests in the way you think of. If your resizing or file generation is being done off of a Model, then yes it is a unit test, but you're no longer writing that simple code (like accessors and mutators). A lot of the time people new to thorough testing won't think that everything is testable, and it may not be, but if you play around and explore, you can often find a way to do so.


text:
Q: CircuiTikZ: Start ground relative to the closest component Here is a short compilable example
\documentclass{article}
\usepackage{tikz}
\usepackage{circuitikz}

\begin{document}
    \begin{circuitikz}
        \draw node[ground]{} to [short,*-] (0,0) to [C] (0,2) to [short,-*] (0,2);
        \node[xshift=1.75cm](0,0){$ \leftarrow $ Start ground here};
    \end{circuitikz}
\end{document}

which produces

The question is: How do you draw the first line of the ground in the marked point? The CircuiTikZ documentation for the node ground does not define an anchor in that exact position.

A: Although I suspect this is a kind of XY problem, no, there is no provision (for now) for a tailless ground symbol. It is quite straightforward to define one, though:
\documentclass{article}
\usepackage[RPvoltages]{circuitikz}

\makeatletter
\pgf@circ@declareground{myground}{0.6}{0.4}{
    \pgfsetlinewidth{\ctikzvalof{monopoles/ground/thickness}\pgfstartlinewidth}
    \pgfpathmoveto{\pgfpoint{-.6\pgf@circ@res@step}{0pt}}
    \pgfpathlineto{\pgfpoint{.6\pgf@circ@res@step}{0pt}}
    \pgfpathmoveto{\pgfpoint{-.4\pgf@circ@res@step}{-0.2\pgf@circ@res@step}}
    \pgfpathlineto{\pgfpoint{.4\pgf@circ@res@step}{-0.2\pgf@circ@res@step}}
    \pgfpathmoveto{\pgfpoint{-.25\pgf@circ@res@step}{-0.4\pgf@circ@res@step}}
    \pgfpathlineto{\pgfpoint{.25\pgf@circ@res@step}{-0.4\pgf@circ@res@step}}
    \pgfusepath{draw}
}
\makeatother

\begin{document}
    \begin{circuitikz}
        \draw (0,0) node[ground]{} to [C, *-*] (0,2);
        \node[xshift=1.75cm](0,0){$ \leftarrow $ Start ground here};
        \draw (4,0) node[myground]{} to [C, *-*] (4,2);
    \end{circuitikz}
\end{document}

Note that I also simplified out your zero-length short.

A: You can just shift the ground up a little, if you don't mind overlapping the tail.
\documentclass{standalone}
\usepackage{tikz}
\usepackage{circuitikz}

\newlength{\kludge}

\begin{document}
    \begin{circuitikz}
        \kludge=\ctikzvalof{monopoles/ground/width}\csname pgf@circ@Rlen\endcsname
        \draw (0,0) node[ground,yshift=1.2\kludge]{} to [C,*-*] (0,2);
        \node[right=0.5\kludge]{$ \leftarrow $ Start ground here};
    \end{circuitikz}
\end{document}


text:
Q: How do I convert this XPath query to LINQ to XML? I have some data which looks like:
<data>
  <row>
    <v>0.0264</v>
    <v>1073655665.0000</v>  <!-- select this -->
    <v>1073749988.0000</v>
  </row>
  <row>
    <v>0.0056</v>
    <v>1073655714.0000</v>  <!-- select this -->
    <v>1073751235.0000</v>
  </row>
  <row>
    <v>0.0052</v>
    <v>1073655812.0000</v>  <!-- select this -->
    <v>1073741221.0000</v>
  </row>
</data>

How do I select every n'th <v> element in each <row> using LINQ to XML.
Using XPath I'd just do /data/row/v[2] to select every 2nd <v> element but I can't seem to figure out how to do this using LINQ to XML.

A: var qry = from row in dataNode.Elements("row")
           select row.Elements("v").ElementAt(1);

Should do? (untested)


text:
Q: how to convert azure app insights api response to C# models so i am able to call app insight's api "https://api.applicationinsights.io/v1/apps/xx/xx/xx" from my C# code.
i can get the json response.

i have this response in json and i want to serialize it into C# objects. do i have to create matching C# classes my self or is there any built in c# models i can use and serialize them?

A: Not really a direct answer to your question, but instead of consuming REST API directly and doing the conversion/serialization yourself you can simply use Application Insights .Net SDK.
The SDK will do all the necessary conversions for you and give you nice C# objects. The source code for this is also open source and is available here: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/applicationinsights/Microsoft.Azure.ApplicationInsights.Query.
You can take a look here for all the models available to you for direct use here: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/applicationinsights/Microsoft.Azure.ApplicationInsights.Query/src/Generated/Models.

A: In my opinion, if you choose to use app insights api, that means you didn't add any other sdk into your project, that means there's no any built in models for you.
And if you choose to use sdk instead, here's a sample for it, and per my testing, it only provides QueryResults as the response, here's my testing result, and this is the introduction for preparation. Pls note, you need wait for a while to make the newly added role to take effect. If you can't find the api permission mentioned in the document, you can search for it like what I did.


text:
Q: Is it possible to remotely expose a bean in spring boot using REST and httpInvoker I need to expose some service for remote use by Java clients (they shall use httpinvoker) and other languages (they shall use REST).
Can I configure spring boot to expose both ? (I would not mind if two separate instances with different ports would be used, like in this post).
I dumped the idea of providing an API for the Java clients that internally uses REST because it is rather tedious to wire all REST endpoints into the code manually using RestTemplate.
I like the concept of HttpInvoker because a ProxyFactoryBean gets used automagically. If Spring Remoting  would be able to do this in a way it can be done for JMS, AMQP and the others I would head this way.

A: You can use something like this. Expose your services as a rest service. Then  make your java clients to consume those services using http or some other library. If any other party is interested also, they can consume it in their own way too.
Else you can create your own jar consuming your rest services and let your java clients use that, without the knowledge about the rest service.

A: Exposing HTTP invoker endpoints in Spring Boot is actually so easy that it looks as if something was missing. In a @SpringBootApplication that has spring-webmvc on its path (for instance using the spring-boot-starter-web POM), add the following bean definition:
@Bean(name = "/my.service")
public HttpInvokerServiceExporter myHttpInvokerServiceExporter(MyService myServiceImpl) {
    HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
    exporter.setServiceInterface(MyService.class);
    exporter.setService(myServiceImpl);
    return exporter;
}

The HTTP invoker endpoint is now exposed at /my.service and will not affect any other mappings. You can add as many such endpoint as you want; and then some @RequestMappings for REST on top.

A: We use both techniques here.  HttpInvoker for Java-to-Java invocations.  Plain-old JSON over HTTP for other clients (similar to REST but not true REST).  I think that the project jsonrpc4j provides a nice way to implement the HTTP stuff.

A: Have a look at the spring-rest-invoker. It binds Java interfaces to REST services. This doesn't solve the problem of "exposing" the service, but makes it much easier to consume it.
https://github.com/ggeorgovassilis/spring-rest-invoker

A: HttpInvoker was dropped after spring-integration 2.x: http://docs.spring.io/spring-integration/docs/2.0.x/reference/html/httpinvoker.html (!Important header gives details). There is a reference to HTTP Support in 3.x and 4.x versions: http://docs.spring.io/spring-integration/docs/latest-ga/reference/html/http.html
There is also another SO post with someone asking about HTTP support and spring boot with some relevant information: Spring Integration Http with Spring Boot and @RequestMapping
Hopefully this gets you part of the way out of the rabbit hole.

A: Spring HTTP Invoker is dangerous to be used in case when the trust of the caller can't be verified. It is deprecated from quite a long time and its support will be removed in Spring 6 so don't use it.
It's best to implement the communication as REST call and wrap it in easy to use method, like some other answers suggest, i.e. the Maleen Abewardana's one - https://stackoverflow.com/a/29840971/3673367.
References:

*

*https://github.com/spring-projects/spring-framework/issues/27422 - Drop RPC-style remoting: Hessian, HTTP Invoker, JMS Invoker, JAX-WS

*https://nvd.nist.gov/vuln/detail/CVE-2016-1000027 - CVE-2016-1000027 Details

*https://github.com/spring-projects/spring-framework/issues/24434#issuecomment-579669626 – "Java serialization is unsafe, and all we can do is advise against exposing HTTP Invoker endpoints to untrusted clients"

P.S. Yes, I know this question is very old and I'm sure OP doesn't need the answer anymore, but I write it with all the other future readers in mind, so that they don't use Spring HTTP Invoker nor any other RPC/RMI-like Spring features.


text:
Q: If circular type definitions are valid I am confused about type hierarchies in programming languages, which seem to be limited to 2 layers for some reason.
This got me wondering if circular reasoning in regards to types is a logical fallacy or if something is wrong with it, and what exactly is wrong with it if so.
For example, at the base level of the type hierarchy it seems like this....

*

*An Object is an instanceof a Class.

*A Class is an instanceof an Object.

So
Object < Class
Class < Object

I'm wondering if there are mathematically any problems with this. I don't really know what they would be, but if circular reasoning is a logical fallacy, maybe there is something to it. That's why in that linked question I was wondering about infinite types and type universes.
But perhaps with this set of base definitions proofs using these things somehow become invalid or something, I'm not sure what kind of problems this might bring.
I will now explain more of what I mean by "object" and "class"....
An object is an instance of a class. That is, a class defines general properties of a group or collection of things, these things which we name "objects". So any collection of stuff that shares a common set of properties can be said to be a collection of "objects".
A class is that general model of a collection of things we are calling "objects". The thing is, we can have a collection of classes, which together have some general properties. As such we can say we have a class of classes. We can do this as much as we want, to have a class of a class of a class, etc. Because we can have a "collection" of classes, and we call the things in a collection "objects", then classes are also "objects". This means that objects can be classes, but not that all objects are classes. There can be objects that are not classes. In that, these objects aren't collection of other objects all sharing some general properties. Instead, these objects have other properties not really relevant here.
This is a mathematical problem because I would like to see if properly formulating this system will allow you to prove some sort of logical statements regarding the types and type instances. I have looked at Coq but haven't really understood how they formulated the Infinite Types (type universes) from Martin-Löf's Type Theory, and why it's done like that. It doesn't make sense (from as much as I have understood so far from reading about HoTT) what the infinite types / type universes solve, and how it aids in the proving process. I don't see, too, what you really need to prove in a general sense in programming, still having difficulty understanding that. But I feel that if I better understand how types need to work -- so that it results in some sort of "logically valid system" -- that it will make more sense what kind of things you can prove.


text:
Q: Disable built-in module import in embedded Python I'm embedding Python 3.6 in my application, and I want to disable import command in the scripts to prevent users to import any python built-in libraries. I'd like to use only the language itself and my own C++ defined modules.
Py_SetProgramName (L"Example");
Py_Initialize ();
PyObject* mainModule = PyImport_AddModule ("__main__");
PyObject* globals = PyModule_GetDict (mainModule);

// This should work
std::string script1 = "print ('example')";
PyRun_String (script1.c_str (), Py_file_input, globals, nullptr);

// This should not work
std::string script2 = "import random\n"
                      "print (random.randint (1, 10))\n";
PyRun_String (script2.c_str (), Py_file_input, globals, nullptr);

Py_Finalize ();

Do you know any way to achieve this?

A: Python has a long history of being impossible to create a secure sandbox (see How can I sandbox Python in pure Python? as a starting point, then dive into an old python-dev discussion if you feel like it). Here are what I consider to be your best two options.
Pre-scan the code
Before executing anything, scan the code. You could do this in Python with the AST module and then walk the tree, or can likely get far enough with simpler text searches. This likely works in your scenario because you have restricted use cases - it doesn't generalize to truly arbitrary code.
What you are looking for in your case will be any import statements (easy), and any top-level variables (e.g., in a.b.c you care about a and likely a.b for a given a) that are not "approved". This will enable you to fail on any code that isn't clean before running it.
The challenge here is that even trivally obfuscated code will bypass your checks. For example, here are some ways to import modules given other modules or globals that a basic scan for import won't find. You would likely want to restrict direct access to __builtins__, globals, some/most/all names with __double_underscores__ and members of certain types. In an AST, these will unavoidably show up as top-level variable reads or attribute accesses.
getattr(__builtins__, '__imp'+'ort__')('other_module')

globals()['__imp'+'ort__']('other_module')

module.__loader__.__class__(
    "other_module",
    module.__loader__.path + '/../other_module.py'
).load_module()

(I hope it goes somewhat without saying, this is an impossible challenge, and why this approach to sandboxing has never fully succeeded. But it may be good enough, depending on your specific threat model.)
Runtime auditing
If you are in a position to compile your own Python runtime, you might consider using the (currently draft) PEP 551 hooks. (Disclaimer: I am the author of this PEP.) There are draft implementations against the latest 3.7 and 3.6 releases.
In essence, this would let you add hooks for a range of events within Python and determine how to respond. For example, you can listen to all import events and determine whether to allow or fail them at runtime based on exactly which module is being imported, or listen to compile events to manage all runtime compilation. You can do this from Python code (with sys.addaudithook) or C code (with PySys_AddAuditHook).
The Programs/spython.c file in the repo is a fairly thorough example of auditing from C, while doing it from Python looks more like this (taken from my talk about this PEP):
import sys

def prevent_bitly(event, args):
    if event == 'urllib.Request' and '://bit.ly/' in args[0]:
        print(f'WARNING: urlopen({args[0]}) blocked')
        raise RuntimeError('access to bit.ly is not allowed')

sys.addaudithook(prevent_bitly)

The downside of this approach is you need to build and distribute your own version of Python, rather than relying on a system install. However, in general this is a good idea if your application is dependent on embedding as it means you won't have to force users into a specific system configuration.


text:
Q: Using Ant to build project and run JUnit Test Android app but Ant Junit Test fails I have a simple Android project that I created. I also created Junit cases for the project. I have my Android app and TestCases in the same project. My structure is like the following:
-AndroidApp
    -src
       -SampleActivity
    -tests
       -SampleActivityTest

I have changed the Order and export options and made sure JUnit is at the top.
I have added
<instrumentation android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.sample.app"
android:label="UnitTest" />
<uses-library android:name="android.test.runner" />

Running Android JUnit Test works fine in Eclipse, but when I try to build & Junit Test the app with Ant the project/app builds but the test fails.
Here's the error:
test-run:
       [junit] Test com.mark.prototype.test.SampleAndroidAppTest FAILED

compile-and-test:
BUILD SUCCESSFUL
Total time: 3 seconds

Can't figure out why it's failing in Ant.

A: Best way is create auto ant build via Export then select Ant BuildFiles and then modify it according to your requirement.


text:
Q: Angular 5 ngModel setting default value based on form input I have an app built in Angular 5 using Firebase's Real Time Database. My form is using ngModel and has a user id field and a custom username field. I need the username to have a default value of the user id unless the user chooses to change it.
User Name
<input id="userId" type="text" for="idInput" class="form-control"
       required minlength="1" name="userId"
       [(ngModel)]="userData.userId"
       #userId="ngModel"
       placeholder="e.g. johnhancock1776"
       />

Your Custom URL
<input id="vanityId" type="text"
       for="vanityInput"
       class="form-control"
       name="vanityId"
       [(ngModel)]="userData.vanityId"
       value="{{userData.userId}}"
       #vanityId="ngModel"
       placeholder="custom url" />

When the user puts In their user id the vanity id field populates but won't send data to the database unless they add or delete something from the vanity field.
I tried adding:
       [ngModelOptions]="{updateOn: 'submit'}"

to the vanity field witch lets it send an empty string if neither field is touched, but won't send anything when only the user id is changed.

A: you could use a (ngModelChange) event to change the value of userData.vanityId instead of value="{{userData.userId}}" because you only change the view and not userData.vanityId value.
component.html
User Name
<input id="userId" type="text" for="idInput" class="form-control"
       required minlength="1" name="userId"
       [(ngModel)]="userData.userId"
       #userId="ngModel"
       placeholder="e.g. johnhancock1776"
       (ngModelChange)="changeVanityId($event)"
       />

Your Custom URL
<input id="vanityId" type="text"
       for="vanityInput"
       class="form-control"
       name="vanityId"
       [(ngModel)]="userData.vanityId"
       #vanityId="ngModel"
       placeholder="custom url" />

<button (click)="sendBackend()">Send</button>

I added a button to print the userData value to verify that print the correct value.
component.ts
  /**
   * Print in console
   */
  sendBackend() {
    console.log(this.userData);
  }

  /**
   * Change value of vanityId
   */
  changeVanityId(event) {
    this.userData.vanityId = event
  }

I implement this here: https://stackblitz.com/edit/angular-sadk7e


text:
Q: Cannot get Maven Archetype requiredProperty validationRegex to work I have an archetype and I am trying to add a new requiredProperty which should only allow one of two possible values: "hibernate" and "hibernate-reactive". In the archetype-metadata.xml, I have defined the property as shown below:
<requiredProperty key="quarkus_orm_selection">
  <validationRegex><![CDATA[^(hibernate|hibernate-reactive)$]]></validationRegex>
</requiredProperty>

In jshell and in other Java programs, I have verified that the regular expression works properly, but in the archetype when I test using a value like hibernate-ree the archetype proceeds without an error!
I proved out the regex as follows in JShell:
jshell> String[] examples = {"hibernate", "hibernate-reactive", "hibernate-re", "hibernate-ree", "testing", "reactive"}
examples ==> String[6] { "hibernate", "hibernate-reactive", "h ... ", "testing", "reactive" }

jshell> Pattern regex = Pattern.compile("^(hibernate|hibernate-reactive)$")
regex ==> ^(hibernate|hibernate-reactive)$

jshell> Arrays.asList(examples).stream().filter(i -> regex.matcher(i).matches()).forEach(System.out::println)
hibernate
hibernate-reactive

Can anyone suggest what I might be doing wrong?
I am using Maven Archetype Plugin version 3.2.0

A: As far as I can tell maven archetypes only validates reg-ex's if you pass in the property in interactive mode.
I created a archetype-post-generate.groovy script (see below)
src/main/resources/META-INF/archetype-post-generate.groovy:
String ormSelector = request.getProperties().get("quarkus_orm_selection")
def pattern = "^(hibernate|hibernate-reactive)\$" // the \$ is important!
final match = ormSelector.matches(pattern)

if (!match) {
    println "[ERROR] ormSelector: $ormSelector is not valid"
    println "[ERROR] please provide an ormSelector that follows this pattern: '$pattern'"
    throw new RuntimeException("OrmSelector: $ormSelector is not valid")
}


text:
Q: Cloudformation: User-data in EC2 as well as in Launch Template It seems like EC2 User-Data takes preference here and never executes Launch Template User-Data.
if I remove User-Data from EC2 it executes LaunchTemplate User-Data without any problem.
The AMI id being used is of CentOS 7.
How can i achieve to run both User-Data in some order.
I have already played around with cloudformation a lot and looked at forums.
{
    "Resources": {
        "BSLaunchTemplate": {
            "Type": "AWS::EC2::LaunchTemplate",
            "Properties": {
                "LaunchTemplateName": "BroadSoftLaunchTemplate2",
                "LaunchTemplateData": {
                    "KeyName": "haystackaccess",
                    "ImageId": "ami-014b38e758721be30",
                    "InstanceType": "t2.medium",
                    "SecurityGroupIds":["sg-e0b92fa7"],
                    "UserData": {
                        "Fn::Base64": {
                            "Fn::Join":["", [
                                "#!/bin/bash \n",
                                "yum update -y \n",
                                "yum –y install epel-release \n",
                                "yum -y install python-pip \n",
                                "pip install pystache \n",
                                "pip install argparse \n",
                                "pip install python-daemon \n",
                                "pip install requests \n",
                                "yum install -y https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.amzn1.noarch.rpm \n",
                                "echo UD_OF_LT_1 >> /var/log/user-data.log \n",
                                "echo UD_OF_LT_2 >> /var/log/user-data.log \n",
                                "echo UD_OF_Lt_3 >> /var/log/user-data.log \n"
                            ]
                        ]
                        }
                    }
                }
            }
        },
        "primaryec2": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "LaunchTemplate": {
                    "LaunchTemplateId":{"Ref":"BSLaunchTemplate"},
                    "Version":"1",
                },
                "Tags": [
                    {
                        "Key": "Name",
                        "Value": "Network Server"
                    }],
                "UserData":{
                        "Fn::Base64": {
                            "Fn::Join": ["",[
                                "#!/bin/bash \n",
                                "echo UD_OF_EC2_1 >> /var/log/user-data.log \n",
                                "echo UD_OF_EC2_2 >> /var/log/user-data.log \n",
                                "echo UD_OF_EC2_3 >> /var/log/user-data.log \n"
                            ]
                        ]
                        }
                    }
            }
        }
    }
}

A: What's the purpose of the primary ec2 instance? I guess you need to run the extra commands on the primary. I mean you could just duplicate the commands - putting them into external bash files might make life a bit easier there. Or create an AMI with the commands you used in the launch template and then use your custom AMI in the primary instance. You might be able to do something with conditionals too, but I think you'd have to be a bit more creative with that since I don't think you can use them directly in the user data itself.
Tim


text:
Q: how can i serialize json response for windows phone? I  am  having  following  Json  response
 string Response=  "" {
"category": [
    {
        "biller": [
            {
                "adhocPayment": "Y",
                "billPresentment": "N",
                "billerCategoryId": "05",
                "billerId": "BILLPAYTEST",
                "billerLogo": "#",
                "billerName": "Airtel Chennai",
                "displayLogoName": "#",
                "label1": "CONSUMER NO",
                "label2": "PHONE NO",
                "maxAmount": "10000",
                "minAmount": "10"
            },
            {
                "adhocPayment": "Y",
                "billPresentment": "N",
                "billerCategoryId": "05",
                "billerId": "VODFONE",
                "billerLogo": "#",
                "billerName": "VODOFONE",
                "displayLogoName": "#",
                "label1": "CONSUMER NO",
                "label2": "PHONE NO",
                "maxAmount": "10000",
                "minAmount": "10"
            }
        ],
        "categoryName": "Mobile Recharge",
        "totalRecords": 2
    },
    {
        "biller": [
            {
                "adhocPayment": "N",
                "billPresentment": "N",
                "billerCategoryId": "30",
                "billerId": "SUNTVDTH",
                "billerLogo": "#",
                "billerName": "SUN TV",
                "displayLogoName": "#",
                "label1": "Subscriber ID^10^10^N^N^N",
                "label2": "#",
                "maxAmount": "10000",
                "minAmount": "100"
            }
        ],
        "categoryName": "DTH Recharge",
        "totalRecords": 1
    }
],
"dcid": "01",
"startRecNo": "0001",
"totalRecord": 0,
"txnno": "0211151051285128"
}""

to  serialize  it  i am  following
Enclosing  classes
 public class RootObject
    {

        public List<Category> category { get; set; }
        public string dcid { get; set; }
        public object startRecNo { get; set; }
        public int totalRecord { get; set; }
        public string txnno { get; set; }
    }

    public class Category
    {
        public List<Biller> biller { get; set; }
        public string categoryName { get; set; }
        public int totalRecords { get; set; }
    }

    public class Biller
    {

        public string adhocPayment { get; set; }
        public string bankCode { get; set; }
        public string billPresentment { get; set; }
        public string billerCategoryId { get; set; }
        public string billerId { get; set; }
        public string billerLogo { get; set; }
        public string billerMnemoName { get; set; }
        public string billerName { get; set; }
        public string delChannelId { get; set; }
        public string label1 { get; set; }
        public string label2 { get; set; }
        public string label3 { get; set; }
        public string label4 { get; set; }
        public string label5 { get; set; }
        public string labelType { get; set; }
        public string maxAmount { get; set; }
        public string minAmount { get; set; }
        public string minimumPayment { get; set; }
        public string recordCount { get; set; }
    }

In  button click  event handler iam  serializing  like  this
foreach (var nit in rootelement.category)
        {

            for (int i = 1; i < nit.biller.Count; i++)
            {
              string b = nit.biller[i].billerName.ToString();
              string c=nit.biller[i].label1.ToString();
            }
        }

my requirement  is there  are  two  Labels(label1,label2)  in  response..based  on  that  i  will  create  two textbox  in  design  and  show  them..
number  of  Labels  in  response  is  dynamic,
every  time  it  changes ,how  to  check/get  labels  count from response.
based  on  that  i  need  to  show same  no  of  textbox's in  design..
please  help me  regarding  this..

A: dynamic collectionWrapper = new
{
    ppp = new RootObject()
    {
        dcid = "01",
        startRecNo = "0001",
        totalRecord = 0,
        txnno = "0211151051285128",
        category = new List<Category>
        {
            new Category()
            {
                categoryName = "Mobile Recharge",
                totalRecords = 2,
                biller = new List<Biller>
                {
                    new Biller()
                    {
                        adhocPayment="Y",
                        billPresentment="N",
                        billerCategoryId="05",
                        billerId="BILLPAYTEST",
                        billerLogo="#",
                        billerName= "Airtel Chennai",
                        displayLogoName= "#",
                        label1= "CONSUMER NO",
                        label2= "PHONE NO",
                        maxAmount= "10000",
                        minAmount= "10"
                    },
                    ......................
                }
            },
            new Category()
            {
                categoryName = "Mobile Recharge",
                totalRecords = 2,
                biller = new List<Biller>
                {
                    new Biller()
                    {
                        adhocPayment="Y",
                        billPresentment="N",
                        billerCategoryId="05",
                        billerId="BILLPAYTEST",
                        billerLogo="#",
                        billerName= "Airtel Chennai",
                        displayLogoName= "#",
                        label1= "CONSUMER NO",
                        label2= "PHONE NO",
                        maxAmount= "10000",
                        minAmount= "10"
                    }
                }
            },
            .....................
        }
    }
};

var output = JsonConvert.SerializeObject(collectionWrapper);

A: You can directly use JSON.NET to deserialize to json and deserialize from JSON. please, avoid doing it "by hand". You can convert your task in a single line of code:
string output = JsonConvert.SerializeObject(product);

Al the documentation that you need is available here.
You can install it in your project as a Nuget package.
In fact, you should be using Web API, which allows you to communicate between the device and a server using HTTP and JSON serialization in a very easy way.


text:
Q: Should a colon be used after "for example"? I am having difficulty deciding when a colon should be used in a sentence. I have a specific example that I was unable to resolve via browsing the web

The research centre will use confidence intervals as well as certainties to to convey their findings. For example: Average surface temperatures will increase by two degrees by 2020 (95% confidence interval).

Have I used a colon correctly in the above example?

A: *

*Either comma or colon is fine to use after the phrase "for example". Typically, a comma is used. When a more "significant" separation is desired, a colon may be used. Notably, if using a colon in your sample usage, the word that immediately follows should be capitalized since it starts a new sentence.

The research centre will use confidence intervals as well as numerical probabilities to to convey their findings. For example: Average surface temperatures will increase by two degrees by 2020 (95% confidence interval).

*Colons are generally unnecessary. They sit in a liminal space between commas and periods. No one will miss them if you don't use them. Many books contain colons only on the copyright page. Yet the first book I grabbed to check doesn't have any colons on that page.

*Semantically, your sample doesn't make sense because it's supposed to include "confidence intervals as well as numerical probabilities", but the "example" has neither. Confidence intervals would be expressed as ranges (eg, 1-3 degrees) or errors (eg, ± 1 degree). Probabilities would be expressed as percentages (eg, 75%), fractions (eg, 3/4), or ratios (eg, 3:1).
I would avoid using an example this way because it is meant to illustrate how data will be presented, yet appears like actual data. This potentially misleads readers into believing fictitious data.
The example sentence is also unclear. 2020 is about a month away. Is this 2-degree rise supposed to occur during the next month? Over this past year? Or some other period of time?


text:
Q: Read Data in a nested Json I have this very long json here: https://textup.fr/601885q4 and would like to read a data that is in one of the "payment_token_contract" specifically those with "id":1
My problem is that I don't get how to call the specific dictionary as they all have the same name. Is this even possible, I'm not used to manipulating such complex objects as I'm a beginner.
I would have tried something like:
["orders][x]["id":1]["base_price"]

with x being in a for loop that iterates through each "orders" present.
But I can't manage to put it all together. Thanks for your help !

A: You can use a for loop to iterate over the orders, you can check the value of the payment contract id and if its 1 then print the base price for that order
import json

jdata = "yourjson"
jdict = json.loads(jdata)

for order in jdict["orders"]:
    if order['payment_token_contract']['id'] == 1:
        print(order["base_price"])

I have omited the json data as its to long but you can image jdata is the string of your json
OUTPUT
149000000000000000000


text:
Q: k8ssandra Cassandra configuration problem I deployed k8ssandra followed officail instruction on site https://docs-v2.k8ssandra.io/install/local/single-cluster-helm/.
After the k8ssandra deployment, I create a big table on cassandra DB. While I'm query the row nubmer by "select count(*) from TABLENAME", cqlsh always got ERROR like "Coordinator node timed out waiting for replica nodes' responses". So I wanna change some cassandra configurations. Could you tell me how could I do it or where the cassandra yaml file is for k8ssandra cluster?

A: This isn't a K8ssandra issue. The problem with your query is that an unbounded COUNT() does a full table scan.
This means that Cassandra has to read ALL the partitions from ALL the nodes in order to count them. There is no amount of tuning that will get around that. I've explained why in this post -- Why is COUNT() bad in Cassandra?.
As a friendly note, a reminder that Stack Overflow is for getting help with coding, algorithm, or programming language problems. For future reference, you should post DB admin/ops questions on DBA Stack Exchange. Cheers!


text:
Q: Add WordPress shortcode which sends parameters On my WordPress page I have created a shortcode function which gets a parameters from the URL of the post. So, I have created this simple function and added the following code to the theme's file function.php:
function getParam($param) {
  if ($param !== null && $param !== '') {
    echo $param;
  } else {
    echo "Success";
  }
}

add_shortcode('myFunc', 'getParam');

And I know I have to add this shortcode to posts and pages using (in my case) [myFunc param=''].
Usually, I would get the value of the parameter from the URL using <?php $_GET['param'] ?>, but in this case I don't know how to send this PHP code to the shortcode function.
For example, I doubt I can write [myFunc param=$_GET['param']].

A: A shortcode like this:
[myFunc funcparam="param"]

Is not needed here, unless the called parameter is changing with the posts.
Let's say you have this URL:
http://example.com?param=thisparam

To get the value of 'param' by using the shortcode described above, your function in functions.php should look something like this:
function sc_getParam() {

    // Get parameter(s) from the shortcode
    extract( shortcode_atts( array(
        "funcparam" => 'funcparam',
    ), $atts ) );

    // Check whether the parameter is not empty AND if there is
    // something in the $_GET[]
    if ( $funcparam != '' && isset( $_GET[ $funcparam ] ) ) {

        // Sanitizing - this is for protection!
        $thisparam = sanitize_text_field( $_GET[ $funcparam ] );

        // Returning the value from the $_GET[], sanitized!
        return $thisparam;
    }
    else {
        // Something is not OK with the shortcode function, so it
        // returns false
        return false;
    }
}

add_shortcode( 'myFunc', 'sc_getParam' );

Look up these references:

*

*WordPress Shortcodes: A Complete Guide - tutorial on creating shortcodes

*Validating Sanitizing and Escaping User Data - sanitizing

A: If you need get the parameters you can:
function getParam($arg) {

    if (isset($arg) &&
        array_key_exists('param', $arg ) &&
        $arg['param'] != '')
    {
        return $_GET[$arg['param']]; // OR  get_query_var($arg['param']);
    }
    else
        return "Success";
}

add_shortcode('name', 'getParam');

A: Do it this way:
function getParam($data)
{
    $var = $_GET[$data['param']];

    if ($var !== null && $var !== '')
    {
        echo "True: " . $var;
    }
    else echo "False: " . $var;
}

And call it by: [myFunc param=whatever]
You shouldn't call a function in the shortcode.
For better understanding, I changed your code just a little bit, but beware this is not secure and clean.


text:
Q: GAPI - Google Analytics Sampling. I am using the GAPI API to access Google Analytics rather than do it myself directly (I know slightly lazy...). I've had a look at the class file but I can't see any built-in function for checking sampling. I was wondering if anyone who has used it has found a way to check if the results being returned are being sampled.
This is the code I am using.
    $this->load->config('gapi');

    $params = array('client_email' => $this->config->item('account_email'),
        'key_file' => $this->config->item('p12_key'));
    $this->load->library('gapi', $params);

    $this->gapi->requestReportData(
        $this->config->item('ga_profile_id'), //reportID
        array('date', 'transactionId', 'campaign'), //Dimensions
        array('transactionRevenue'), //Metrics
        '', //Sort Metric
        'medium==email', //Filters
        date('Y-m-01'), //Start Date
        date('Y-m-d'), //End Date
        1,
        500
    );

    $results = $this->gapi->getResults();

My plan is to run the report for a given date range, check to see if the data is sampled and if true, split the query into small parts to get around it.

A: The v3 API has 2 sampling-related response fields:

*

*Sample Size: number of data entries used

*Sample Space: number of data entries available

So if you do Sample Size / Sample Space you have your sampling ratio.
The v4 API has the same but named differently:

*

*samplesReadCounts: number of data entries used

*samplingSpaceSizes: number of data entries available

So if you do samplesReadCounts / samplingSpaceSizes you have your sampling ratio.
If gapi doesn't expose these fields in the response, then you should change API client (eg use the official client)


text:
Q: S3 Direct Upload doesnt upload files /config/intilializers/paperclip.rb
Paperclip::Attachment.default_options[:storage] = :s3
Paperclip::Attachment.default_options[:bucket] = 'xxx'
Paperclip::Attachment.default_options[:s3_permissions] = :public_read
Paperclip::Attachment.default_options[:s3_credentials] = { access_key_id: 'xxx' ,secret_access_key: 'xxx'}

/config/intilializers/s3_direct_upload.rb
S3DirectUpload.config do |c|
c.access_key_id = 'xx'       # your access key id
c.secret_access_key = 'xxx'
c.bucket = 'xxx'              # your bucket name
c.region = 's3-ap-southeast-1'
end

AWS.config({
:access_key_id => 'xxx',
 :secret_access_key => 'xxx',
:region => 'ap-southeast-1'
})

Ad.rb
has_attached_file :thumbnail, styles: { thumb: "50x50>" }
validates_attachment_size :thumbnail, :less_than => 100.megabytes
# validates_attachment_presence :thumbnail
validates_attachment_content_type :thumbnail, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]

_form.html.erb

        <%= s3_uploader_form callback_url: ads_url,
          id: "s3_uploader",
          callback_param: "ad[thumbnail_url]",
          expiration: 24.hours.from_now.utc.iso8601,
          max_file_size: 100.megabytes do %>
          <%= file_field_tag :file, multiple: true %>
        <% end %>

When I submit it doesn't upload anything on S3. Which thing am I missing?


text:
Q: python itertools product repeat to big I'm trying to make a python script to calculate some win/loss chances.
to do this i'm trying to get all possible combinations off wins and losses (K is the number of wins needed to win the game):
for combination in itertools.product(['W','L'], repeat=(K*2)-1):
    if ((combination.count('L') < K) and (combination.count('W') == K)):
        #calculate the chance of this situation happening

for some reason this works fine, until the repeat becomes to big (for instance if K=25)
Can someone give me some pointers on how to solve this?

A: Of course it fails when the repeat becomes large.  The loop
for combination in itertools.product(['W','L'], repeat=(K*2)-1):

iterates through 2**(K*2-1) elements, which becomes prohibitively large very quickly.  For example, when K=3, the loop executes 32 times, but when K=25 it executes 562949953421312 times.
You should not exhaustively try to enumerate all possible combination.  A little bit of mathematics can help you: see Binomial Distribution.
Here is how to use the Binomial Distribution to solve your problem:  If chance to win a single game is p, then the chance to lose is 1-p.  You want to know what is the probability of winning k out of n games.  It is:
(n choose k) * p**k (1 - p)**(n - k)

Here (n choose k) is the number of combinations that have exactly k wins.

A: The following gives you a clue:
>>> for K in range(1,11):
...     n = 0
...     for combination in itertools.product(['W','L'], repeat=(K*2)-1):
...         n+=1
...     print (K,n),
...
(1, 2) (2, 8) (3, 32) (4, 128) (5, 512) (6, 2048) (7, 8192) (8, 32768) (9, 131072) (10, 524288)
>>>

So you are going to have to wait a long time for a result at K=25. maybe it is time to work out your probability rather than simply calculating it!


text:
Q: TableLayout weight sum issues I'm trying to implement a 40/60 percent split in my TableLayout but I'm having no luck. When testing the code on my Android Device the left TextView still takes up what looks like 60%, instead of 40%.
    <TableLayout

    android:id="@+id/agentStatusTable"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_gravity="center|top"
    android:visibility="visible"
    android:background="@drawable/curvedbg"
    android:layout_marginLeft="10sp"
    android:layout_marginRight="10sp"
>

<TableRow android:id="@+id/webiprow" android:layout_marginTop="14sp" android:gravity="center_vertical" android:background="#e5e6e6" android:minHeight="45sp" android:weightSum="1">
<TextView android:paddingRight="10dp" android:id="@+id/webiptitle" android:text="@string/webip" android:textColor="#000000" android:textSize="15sp" android:layout_weight="0.40" android:gravity="right"></TextView>
<TextView android:paddingRight="10dp" android:id="@+id/webiptext" android:textColor="#000000" android:textSize="15sp" android:layout_weight="0.60" android:gravity="right"></TextView>
</TableRow>

<TableRow android:id="@+id/webportrow" android:layout_marginTop="6dp" android:layout_marginBottom="14sp"  android:gravity="center_vertical" android:minHeight="45sp" android:weightSum="1">
<TextView android:paddingRight="10dp" android:id="@+id/webporttitle"  android:layout_weight="0.40"  android:text="@string/webport" android:textColor="#000000" android:textSize="15sp" android:gravity="right"></TextView>
<EditText android:paddingRight="10dp" android:inputType="number"  android:layout_weight="0.60"  android:id="@+id/EditText01" android:text="@+id/EditText01"></EditText></TableRow>

</TableLayout>

A: In the TextTiew and EditText where you use layout_weight, set height to wrap_content and width to 0dp.
android:layout_width="0dp"
android:layout_height="wrap_content"


text:
Q: How to get value of the textarea in Gmail? I need to get the value of the Gmail's textarea (the textarea where one write the email body).
Since I need to perform some I/O ops on the value of the text area I need to text to be formatted correctly.
Since I noticed that the value of the textarea in gmail is oddly always undefined (see img below)..

.. I started to implement some internal utilities to get the right HTML node, transform it into a string and extract the text out of it. I thought I'd be able to reproduce the original text formatting by searching for <br> tags and
Unfortunately, it's much more nuanced than this, there are much more edge cases that are hardly predictable.
Does anybody know if this is actually a solvable problem and if so, how?

A: I don't know what you are trying to accomplish here but It seems like you need to change the content of a message and send it to using gmail message box and send the email
since you are using js you can try node js and try to scrape it using a web scraper
you will have to install node js and install "request" and "cheerio" dependencies and make a req to Gmail/compose mail and scrape that page and target the test area you want and append your message what ever you wan to do and internally post it


text:
Q: What's a simpler word for "several" in the meaning of "multiple" [Hello. I'm not a native English speaker, so please forgive me for my mistakes if there are any]
Suppose I wanted to say "I have in my class several people called Jim Smith". I'm under the impression that "several" is a bit too fancy for people with limited vocabulary. What's a simpler way do say that?
Suggestions:
 "There are a few people called Jim Smith". That's not perfect, as it puts stress on the existence of those people, rather than on the fact that several people share the same name.
"More than one person called Jim Smith". Sounds a bit awkward to me.
Thank you.

A: If you want something more informal, I'd suggest "a bunch". I feel like it expresses the same quantity and is less fancy.

A: Using user162286's answer as inspiration, 'a number' could also serve to indicate 'more than one' without committing to a fixed amount and without setting expectations as to how many there actually are.
Another way to get more people to read the sentence the way you want to them to read it is to rephrase the sentence in order to have it follow a more conventional structure (in writing at least):
For example: "I have in my class several people called Jim Smith" -> "There are a number of people called Jim Smith in my class."


text:
Q: Using SharePoint Online Migration Manager unable to sign in to DropBox I want to migrate my DropBox folders to a SharePoint Online document library.
now i did the following steps:-

*

*Go  to the migration manager >> click on sign to dropbox >>

*Sign in using google:-

*but i will be redirected to the same page (API Request Authorization):-

*and the Migration manager keep showing the following message:-

so any advice?
Thanks


text:
Q: Need help to develop simple Sharepoint 2013 app to upload excel files to a library I spun up a new windows 2012 Server R2, installed Sharepoint 2013, and Visual Studio 2019 with the Office/Sharepoint dev options on an old Dell server.  I'm trying to write and debug an app I found on the web to upload excel files from a shared drive to a sharepoint document library.  I'm at the point where everytime I try to run this app, I get an error stating:

The Web application at http://tcaserver01/my/MPR could not be found.
Verify that you have typed the URL correctly. If the URL should be
serving existing content, the system administrator may need to add a
new request URL mapping to the intended application.

I just need a bit of hand-holding to get things properly configured I think. However, when I put in the url in a web browser, it shows the empty library fine.
using System;
using System.IO;
using Microsoft.SharePoint;

namespace SPTest2
{
    class Program
    {
        [STAThread]
        static int Main(string[] args)
        {
            String site = "http://tcaserver01/my/MPR";      //URL of SharePoint site
            String library = "Review_Workbooks";            //Library Name
            String filePath = @"S:\MPR\MPR Template.xlsx";  //Entire path of file to upload

            try
            {
                using (SPSite spSite = new SPSite(site))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        //Check if file exists in specified path
                        if (!System.IO.File.Exists(filePath))
                            Console.WriteLine("Error - Specified file not found.");

                        //Get handle of library
                        SPFolder spLibrary = spWeb.Folders[library];

                        //Extract file name (file will be uploaded with this name)
                        String fileName = System.IO.Path.GetFileName(filePath);

                        //Read file for uploading
                        FileStream fileStream = File.OpenRead(filePath);

                        //Replace existing file
                        Boolean replaceExistingFile = true;

                        //Upload document to library
                        SPFile spfile = spLibrary.Files.Add(fileName, fileStream, replaceExistingFile);
                        spfile.CheckIn("file uploaded via code");
                        spLibrary.Update();
                    }
                }
                Console.WriteLine("File uploaded successfully !!");
                Console.ReadLine();
            }
            catch (Exception exp)
            {
                Console.WriteLine("Error uploading file - " + exp.Message);
                Console.ReadLine();
            }

            return 0;
        }
    }
}

A: Well, it seems when I logged in as the Sharepoint admin user account, I was able to move further in the app, successfully opening up the Sharepoint site.  So, when I was logged in as myself, I must not have had the appropriate permissions to open the site.  So, this question should be closed as I can now get past what was blocking me. Thanks for anyone who may have read this question already!


text:
Q: How to remove space from the xml which is now made as a String? Sample.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

Method:xmlToStringStreamExample()
public String xmlToStringStreamExample () {
    StringBuilder x = new StringBuilder();
    InputStream is =
      new ByteArrayInputStream(ClassName.Class().getClassLoader().
        getResource("Sample.xml")); // read it with BufferedReader
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line;
    try {
        while ((line = br.readLine()) != null) {
            x.append(line);
        }
    } catch(IOException e) {
        e.printStackTrace();
    }

    return x.toString();
}

This method and xml are correct. However while printing the value of x I'm getting spaces. And I want to remove these spaces. I tried x.repalceAll("\\\s", ""); but this did not work - the spaces were still there. I also tried x.replace(" ", ""); but this too did not remove the spaces. Could someone help me on this? Spaces are included when the next line includes tags.

A: You should use x.append(line.trim()); instead of x.append(line);
FileInputStream fi = new FileInputStream(file);
            byte[] downloadStream = new byte[(int) file.length()];
            fi.read(downloadStream);
            InputStream is = new ByteArrayInputStream(downloadStream); // read it with BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            String line;

            while ((line = br.readLine()) != null) {
                x.append(line.trim());
            }


text:
Q: Parse diff output with Java I am developing an app with JavaFX that compares two files and I am getting such outputs like in column Nr. 3
https://en.wikipedia.org/wiki/Diff_utility#Usage
Column Nr.3 shows the differences between column 1 and 2. Is there a way to do this? I could not find any libraries that could do that, and I thought maybe I can do this with regex, is that fine? or there is an easier way? so I can show the changes that have been made to files in a user friendly way.
P.S. cannot insert the text in here because it is parsed in a strange way.


text:
Q: c++: casting a parent class to a subclass and calling a subclass's function I have a parent class called A, and a subclass called B.
B has method printB();
Why can I c-style cast an A pointer to a B pointer and access method printB()? even though A doesn't have a printB() func?
class A {

};

class B: public A {
    public:
    void printB() {
        std::cout<<"testB"<<std::endl;
    }
};

int main()
{
    A a;
    A* aPtr;
    B b;
    B* bPtr;

    aPtr = &a;
    ((B*)aPtr)->printB();

    return 0;
}

main prints: testB


text:
Q: How to get the page id when user removed my application from page Am new to facebook application.
Basically i want to be notify when some one removed my application from his page.
using application > advanced > Deauthorize Callback: URl. i can able to receive signed_request.
But i needs to know the page id which page user has removed my application.
Since in my application user can add my app to multiple pages of his account.
so when he remove my app from any one of that page. i needs to know the page id.
looking forward to hear from your answers in this regards.

A: Unfortunately it is not possible just with "Deauthorize Callback". However, you can save current page id to your database and when your application have received this callback you'll have an idea what page what the last one.
Hope that helps.