text:
Q: Cant retrieve column value from Laravel's Eloquent when primary key is varchar I encountered an issue where my Laravel's Eloquent Model does not give me the value of the column called 'id' it just turn to be an integer (0) instead of a string. I though the column was somehow protected but in other Models where the 'id' is an intenger it return the value just fine.
Question: Can't I use VARCHAR for primary keys?

Note: I have to create more tables with respective models where the primary key need to be a string; I'm kinda new Laravel

Migration:
Schema::create('country', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->string('id', 5);
        $table->string('name', 45);
        $table->string('currency_symbol', 5);
        $table->string('currency_name', 45);
        $table->float('tax_rate');
        $table->string('url')->nullable();
        $table->string('support_email', 90);
        $table->string('noreply_email', 90);
        $table->boolean('active');
        $table->boolean('root');
        $table->primary('id');
    });

Model is really simple:
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    protected $table = 'country';
}

But when i try to retrieve it...
echo Country::find('ve')->first()->toJSON();
//Output:
{"id":0,"name":"Test","currency_symbol":"T".....

// And...
var_dump(Country::find('ve')->first()->id);
//Output:
int:0

But if I use print_r() function this is the output:
    App\Http\Models\Country\Country Object
    (
        [table:protected] => country
        [connection:protected] =>
        [primaryKey:protected] => id
        [perPage:protected] => 15
        [incrementing] => 1
        [timestamps] => 1
        [attributes:protected] => Array
        (
            [id] => ve
            [name] => Test
            [currency_symbol] => T
            [currency_name] => Test currency
            [tax_rate] => 12
            [url] =>
            [support_email] => support@example.com
            [noreply_email] => roreply@example.com
            [active] => 1
            [root] => 1
        )

        [original:protected] => Array
        (
            [id] => ve
            [name] => Test
            [currency_symbol] => T
            [currency_name] => Test currency
            [tax_rate] => 12
            [url] =>
            [support_email] => support@example.com
            [noreply_email] => roreply@example.com
            [active] => 1
            [root] => 1
        )

        [relations:protected] => Array
            (
            )

        [hidden:protected] => Array
            (
            )

        [visible:protected] => Array
            (
            )

        [appends:protected] => Array
           (
           )

        [fillable:protected] => Array
            (
            )

        [guarded:protected] => Array
            (
                [0] => *
            )

        [dates:protected] => Array
                             (
                             )

        [dateFormat:protected] =>
        [casts:protected] => Array
             (
             )

        [touches:protected] => Array
           (
           )

        [observables:protected] => Array
           (
           )

        [with:protected] => Array
            (
            )

        [morphClass:protected] =>
        [exists] => 1
        [wasRecentlyCreated] =>
    )

if necessary:

*

*Laravel version: 5.2

*PHP: 5.6.15

A: If your primary key is not an auto-incrementing value, then you need to let the model know that it's not. Otherwise, it automatically tries to convert the primary key into an integer.
So, try adding this to your model, and then retrieving the value.
public $incrementing = false;

Another thing to note is that you don't need to call first() when you use the find() method. Behind the scenes, it already does that for you so you can shorten it to this:
Country::find('ve')->id;


text:
Q: Override screen size in linux telnet Here's my predicament. I'm developing a perl telnet script that uses Expect to spawn a new telnet process and feed data (non-interactively) into it.
Everything works fine when I call the script from a terminal - however, if I start the script from cron I am unable to login to the remote device because the Window size negociation fails - as my client sends a window size of 0x0 (instead of 80x24).
Apparently telnet gets this window size from its master PTY - which isn't a TTY if it's called from cron. Most likely telnet is getting these settings using ioctl or some similar mechanism, because trying to override these settings by environment variables failed (ROWS=200 COLUMNS=80 telnet test).
I ran stty from cron and redirected the output to a file. Problem is stty complains when it's run from cron: /bin/stty: standard input: Invalid argument
Do you know any way to:
1) override the number of rows/columns telnet sends to the remote device
2) start a tty and start telnet inside that tty (from cron)
Thanks

A: update - I managed to solve my problem by using a workaround. The expect module has a function which copies the size of a TTY to the current "TTY" in which telnet runs. Problem was the default TTY was STDIN -  which has no dimensions when run from cron. I forced it to get its dimensions from /dev/tty0 instead:

 #we're running from cron or smth
$logger->debug("setting /dev/tty0 window size to 80x24:");
 `/bin/stty -F /dev/tty0 columns 80 rows 24`;
open TTY0, "/dev/tty0" or die "Can't open /dev/tty0: $!";
$session->slave->clone_winsize_from(*TTY0);

A: I found this post very useful as I ran into the same problem after migrating some Perl code away from using Net::Telnet to Expect (Expect has extremely useful debugging output in comparison).
However in my situation I had a /dev/tty0 that was pretty locked down (only root could read it) and I didn't want to change that:
crw--w----    1 root     tty        4,   0 Aug 30  2002 /dev/tty0

I looked at the Expect/IO::Pty/IO::Tty source and ended up hacking in the following - which essentially does the same thing (80 x 24) without needing to read from /dev/tty0.
use IO::Tty;
use IO::Tty::Constant;
my $winsize = pack('SSSS', 24, 80, 0, 0);
ioctl($exp->slave(), &IO::Tty::Constant::TIOCSWINSZ, $winsize);

A: In the start of the script:
set columns 80
set rows 24

redpajama_set_name: RedPajamaStackExchange


text:
Q: Random selection weighted against recent previous selections I'd like to select an element of a list where each element is weight by how long since it was last selected.
I could make an LRU (least recently used) list with the weighting a function based on the position in the queue, which would be elegant except for the fact that initially all elements should be weighted equally.
Just subtracting or dividing the weight by a certain amount after it has been selected doesn't seem intuitively right. Is there a better way perhaps using a mathematical concept such as logarithms or inverses? (not my strong point)

A: How about something like this:
Let n = number of elements, list = array of elements, watermark := 0.
r := random()
i := floor(r * n)

if i >= watermark :
    index := i
    watermark := watermark + 1  // weighted part grows
else :
    index := floor(weight(r * n / watermark) * watermark)
endif

move list[index] to list[0]     // shifting elements list[0..index-1] up one place
result := list[0]

Here we divide the list into two parts, weighted and uniform, with boundary tracked by watermark. Initially the weighted part is empty, but gradually it grows, in the end consuming the entire list.
random() is a function that returns a random number in [0.0, 1.0).
weight(x) is a function from [0.0, 1.0) into [0.0, 1.0) that defines required weighting behaviour.
The "r * n / watermark" as argument of weight() serves to normalize the argument range. Maybe this normalization is not needed for some choices of the weighting function.


text:
Q: Model for SelectList in MVC I'm building a POC app using MVC. Models are Employees, Departments, Locations, Vendors. Multiple Razor pages will need select lists for Employees. I know that I could create a model for Employees in each page folder. Could I instead create a model for Employees in the Models folder and use that for multiple pages? If so, how would I address that model in each page?
According to the tutorials, the syntax within the cshtml page is
    <select asp-for="Course.DepartmentID" class="form-control"
                    asp-items="@Model.DepartmentNameSL">
                <option value="">-- Select Department --</option>

which addresses the model within the page folder.
How would I code it to address the model in the models folder?
Should have included more code.:(
I have an Employee model and a Department model. The Department model has a field for the DepartmentManager which should contain the EmployeeID from the Employee model for the employee assigned as manager to that department.
    Employee Model................................
    public Guid EmployeeID { get; set; }
    public string EmployeeNumber { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }

    Department Model..............................
    public Guid DepartmentID { get; set; }
    public string DepartmentCode { get; set; }
    public string DepartmentName { get; set; }
    public Guid? DepartmentManager { get; set; }<-----This is EmployeeID in Employee Model

Thanks,
John

A: If your multiple pages need this drop-down list, you can create a general method to get it, and then pass it to the view through ViewData.
public SelectList GetSelect(ApplicationDbContext _context)
{
    return (SelectList)(ViewData["DepartmentNameSL"] = new SelectList(_context.Department.ToList(), "DepartmentID", "DepartmentName"));
}

Then in your action,you can use it:
public async Task<IActionResult> Index()
{
    GetSelect(_context);
    return View();
}

In your View:
<select name="Course_DepartmentID" asp-items="ViewBag.DepartmentNameSL">
</select>


text:
Q: miscalculated .length on click I was wondering if anyone could provide me with any pointers or advice. I have a list structure, similar to this on my website:

var $k = jQuery.noConflict();

 if ($k(".selected").length){

 $k(".token").click(function(e) {
    var n = $k( ".selected" ).length;
    $k( "#showcount" ).text( "There are " + n +
      "Tokens");

  });

} else {

     $(this).n(".selected").remove()
}

one

two

three

four

five

The problem I have is that, when I click on any number within the li, (The value is displayed as 1 within the "showcount" div - which is correct e.g. One
 is selected.
However, when I deselect the
, rather than the counter going back down to 0, the count increases to 2 rather than going to zero.
Ideally, I want to count the number of
 items which are selected. (I do have another plugin working in the background which is making the
 already clickable. I'm just trying to incorporate a counter to display a value of how many
 items are selected.

A: Details are commented in example

// Call after page is ready
selectTokens();

// Bind "click" event to all .token
$(".token").on("click", selectTokens);

/**
 * Toggle the .selected class on the .token clicked
 * Assign the count of .selected to div.count
 */
function selectTokens(e) {
  $(this).toggleClass("selected");
  $(".count").text(`There are ${$(".selected").length} selected items.`);
}

one

two

three

four

five


text:
Q: How to add commas or space for every 4 digits in swift 4? My case is a little special, I need to insert space or comma for every 4 digits.
Example:

18686305
1868,6305 or 1868 6305

How can I do in swift 4?

A: A NumberFormatter is designed to convert numerical values to String values based on a pre-defined format. In your case, the following will insert grouping separators every four digits:
import Foundation

let groupingSeparator = "," // determined based on user input, as per the question

let formatter = NumberFormatter()
formatter.positiveFormat = "####,####"
formatter.negativeFormat = "-####,####"
formatter.groupingSeparator = groupingSeparator

if let string = formatter.string(from: 18686305) {
    print(string) // prints "1868,6305"
}

The positiveFormat and negativeFormat variables follow the Unicode Technical Standard #35.


text:
Q: URI 1101 Sequence of Numbers and Sum #include <stdio.h>

int main() {

    int M,N,i=0,sum=0;

    while(M>0 || N>0){

        scanf("%d%d",&M,&N);

        if(M<=0 || N<=0){
            break;
        }

        else if(M==N){ printf("%d Sum=%d\n",N,M); }

        else if(M<N){
            for(i=M; i<=N; i++){
                printf("%d ",i);
                sum+=i;
            }
            printf("Sum=%d\n",sum);
            sum=0;
        }

        else if(M>N){
            for(i=N; i<=M; i++){
                printf("%d ",i);
                sum+=i;
            }
            printf("Sum=%d\n",sum);
            sum=0;
        }
    }

    return 0;
}

what is wrong with this code? URI judge saying 100% wrong answer but I tried all the test cases and it passed in those cases

A: I'm not sure, but before while loop you should get scanf("%d%d",&M,&N); one time.
Because the m and n is not defined.
Like this way :
scanf("%d%d",&M,&N);

while(M>0 || N>0){

    scanf("%d%d",&M,&N);

    if(M<=0 || N<=0){
        break;
    }

    ...


text:
Q: Using OpenLayers with QGIS? I'm a new user of QGIS and OpenLayers. I had used it some time ago, then I had to format my PC and reinstall all programs. After this operation, I've found I cannot use OpenLayers because the following window appears.

A: What I can see from your screenshot is that your project is not set to EPSG3857.
Try changing the project-crs to 3857.


text:
Q: torch7: Filtering out NaN values Given any general float torch.Tensor, possibly containing some NaN values, I am looking for an efficient method to either replace all the NaN values in it with zero, or remove them altogether and filter out the "useful" values in another new Tensor.
I am aware that a trivial way to do this is to manually iterate through all the values in the given tensor (and correspondingly replace them with zero or reject them for the new tensor).
Is there some pre-defined Torch function or a combination of functions which can achieve this more efficiently in terms of performance, which relies on the inherent CPU-GPU optimisations of Torch?

A: Well, it looks like there is no function in torch checking tensor for NaNs. But since NaN != NaN, there's a work around:
a = torch.rand(4, 5)
a[2][3] = tonumber('nan')
nan_mask = a:ne(a)
notnan_mask = a:eq(a)

print(a)
 0.2434  0.1731  0.3440  0.3340  0.0519
 0.0932  0.4067  nan     0.1827  0.5945
 0.3020  0.1035  0.5415  0.3329  0.7881
 0.6108  0.9498  0.0406  0.9335  0.3582
[torch.DoubleTensor of size 4x5]

print(nan_mask)
 0  0  0  0  0
 0  0  1  0  0
 0  0  0  0  0
 0  0  0  0  0
[torch.ByteTensor of size 4x5]

Having these masks, you can efficiently extract NaN/not NaN values and replace them with whatever you want:
print(a[notnan_mask])
...
[torch.DoubleTensor of size 19]

a[nan_mask] = 42
print(a)
  0.2434   0.1731   0.3440   0.3340   0.0519
  0.0932   0.4067  42.0000   0.1827   0.5945
  0.3020   0.1035   0.5415   0.3329   0.7881
  0.6108   0.9498   0.0406   0.9335   0.3582
[torch.DoubleTensor of size 4x5]


text:
Q: Increased count while finding matching recs using left join I know this must be basic but to some bizarre reason I'm not getting my counts right when I left join my table. so basically tbl1 with 100 rows and tbl2 with 30recs. I'm trying to tbl1 with 2 to see how many records got their website address. But I'm getting a count much more than 100 which is my left most table. I even used distinct on tbl2 while joining but it's not helping.
tbl1
id, name, url, data1

tbl2
id,data3,data4,data5,data6,data6,website

tbl2 contains the  website data of records which are missing in tbl1, so I'm trying to map these to get the table right.
My query
select
    t1.id, t1.name,
    coalesce(t1.url, t2.website) as url, t1.data1
from
    tbl1
left join
    (select disctinct id, website
     from tbl2) t2 on t1.id = t2.id

I'm getting a total of 110 rows, ideally I should be getting just 100. Is any assumption possible here from experts to see why am I getting it or should I pour more data?
Thank you.

A: Your outer join is matching multiple ID values.
To find the duplicate ID rows you can do
select *
from T2
where Id in (select Id from T2 group by Id having count(*)>1)

To get a 1:1 join in the example query you would need to group by the Id and also use an aggregate on the website column, or a top (1) clause if you have some other way of distinguishing, such as a Createdate column etc
eg
left join (select Id, max(website) from tbl2 group by Id)

A:
tbl2 contains the website data of records which are missing in tbl1, so i'm trying to map these to get the table right.

Then we don't really care about records treat join multiple times because you're looking for records that join zero times:
select *
from
  tbl1
  left join tbl2 on tbl1.id = tbl2.id
where
  tbl2.id is null

Or
select *
from
  tbl1 x
where
  NOT EXISTS(select null from tbl2 y where x.id = y.id)

It will give you all the tbl1 rows that have no matching tbl2 row
If you want to use them to patch up tbl2 you can:
insert into tbl2(some,columns,here)
select columns,for,table2
from
  tbl1 x
where
  NOT EXISTS(select null from tbl2 y where x.id = y.id)

A: Try this:
SELECT DISTINCT
        t1.id
    ,   t1.name
    ,   url =   COALESCE(t1.url, t2.website)
    ,   t1.data1
FROM        tbl1    T1
LEFT JOIN   tbl2    T2  ON  T2.id = T1.id


text:
Q: apache mod_rewrite is not resolving OK I have an Apache server (80 port) running ok as a Reverse proxy of local webserver (82 port) and mod_rewrite without any .htaccess files.
I can navigate OK to http://localhost/CONTACT.PRO, it shows me website located on local web server at http://localhost:82/cgi-vel/web/CONTACT.PRO
The problem is trying to create friendly URLs using mod_rewrite, it shows me an error from local webserver (not apache error), so I guess I am not sending the correct URL to local webserver (82 port)
Can you please help me to figure out what happens?
In Apache folder, I only have main / original httpd.conf with enable "LoadModule rewrite_module modules/mod_rewrite.so" and including "conf/extra/ABC.conf" where I put my config:
NameVirtualHost *
ExtendedStatus On

<virtualHost *>

ServerName www.ABC.com
ServerAlias 192.168.1.250
ServerAlias localhost
ServerAdmin webmaster@ABC.com
DirectoryIndex index.htm
ProxyPass /cgi-vel/web/  http://localhost:82/cgi-vel/web/
keepalive=on
ProxyPass /  http://localhost:82/cgi-vel/web/ keepalive=on
ProxyPassReverse /  http://localhost:82/cgi-vel/web/ keepalive=on
ProxyPreserveHost On
ErrorLog "logs/test_web_error.log"
CustomLog "logs/test_web-access.log" combined

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^contact$ /CONTACTAR.PRO?W-IDIOMA=EN [P]
RewriteRule ^item$   /ITEM.PRO
RewriteRule ^special /SALE.PRO?_sale=109

</virtualHost>

Thank you very much

A: As far as I can tell, ProxyPass is evaluated before RewriteEngine, so RewriteEngine never sees your URL.
Have a look at https://stackoverflow.com/questions/9003358/apache-rewrite-then-proxy-pass
You have to tell RewriteEngine to pass the URL back to the URL handler by adding [PT]


text:
Q: Remove deleted from from svn working copy directory My svn repo is /home/httpd/svn/project. The working copy is /home/httpd/svn/project_work. I am running a post-commit script that updates the working copy, then rsyncs with the test site. This works fine.
But I need to remove deleted files from the working copy directory as well. I know this this script works if I am currently in my working copy directory:
svn status | grep '^!' | sed 's/! *//' | xargs -I% svn rm %
But my post-script is running in the svn/hooks directory. How to I tell the above command to operate on the files in the working copy directory so that it can be part of my post-commit script?
My script looks like this:
$SVN update $HOST/$SITE_WORK --non-interactive --username xxxxx --password xxxx >> $LOG
$RSYNC -azv --exclude=.svn $HOST/$SITE_WORK/* /home/httpd/sites/$SITEDIR/doc-root >> $LOG

A: It is not possible for the SVN server to send commands to be executed on the client. You could alias svn on each client to both run svn and a custom script if you wish.
Also, files deleted with svn rm <filename> are deleted on all clients when they do svn up.
From your script I see that you find all status lines starting with ! which indicates that you've made changes to your working copy without using svn. From the manual

'!'
  Item is missing (e.g. you moved or deleted it without using svn). This
  also indicates that a directory is incomplete (a checkout or update
  was interrupted).

It sounds like you or your users are doing something wrong.
Edit: this is a transcript of a test session about deleting files:
I've checked out a repository into two working copies, they are called sof and sof2 on my disk.
On sof I've added aFile.txt and commited it. On sof2 I've just checked out that file. This is how it looks now:
$ svn info aFile.txt
Path: aFile.txt
Name: aFile.txt
URL: http://xp-dev.com/svn/sof/trunk/aFile.txt
Repository Root: http://xp-dev.com/svn/sof
Repository UUID: d3d45886-b759-4dae-a297-3c88720da0c3
Revision: 2
Node Kind: file
Schedule: normal
Last Changed Author: wederbrand
Last Changed Rev: 2
Last Changed Date: 2011-12-05 19:53:11 +0100 (Mon, 05 Dec 2011)
Text Last Updated: 2011-12-05 19:53:37 +0100 (Mon, 05 Dec 2011)
Checksum: e5bc1e83330bccc8efe0e884b79a1c43

Now I'll delete it on sof
$svn rm aFile.txt
D         aFile.txt
$ svn commit -m'file deleted'
Deleting       trunk/aFile.txt

Committed revision 3.
$ l
<no files left in directory>
$ svn info aFile.txt
aFile.txt:  (Not a versioned resource)

and the file is gone, now to sof2 where I'm about to get the latest updates
$ l
total 8
-rw-r--r--  1 raven  staff  36 Dec  5 19:53 aFile.txt
$ svn up
D    aFile.txt
Updated to revision 3.
$ l
<no files shown, it has been deleted>

If you get any other behavior than this stuff are really weird :)

A: I'm going to recommend you take a look at Jenkins. Jenkins is a continuous build system, but it also is great for doing just this type of task.
What I would recommend is a bit different from what you're doing -- especially if you are talking about httpd:

*

*Do an svn export to a new working directory. This is clean, and doesn't include the .svn directories (although SVN 1.7 doesn't plaster them everywhere as earlier versions did).

*Once the export is complete, rename the old working directory to a temporary name.

*Rename the new working directory with the name of the old working directory.

*Delete the old working directory.

This will prevent your working directory from being in an inconsistent state where old and new versions of the files exist at the same time in the same directory tree. Plus, this is self recovering. If for some reason the old update doesn't complete, a new build will put everything just right once again.
By using Jenkins to do this whenever it detects a new Subversion release, you no longer need the post-commit hook. The problem is that while that post-commit hook is running, your user has to sit at their desk twiddling their thumbs waiting for Subversion to pass a nay or yea on the post-commit work. Plus, you can always hit the rebuild button to rebuild the working directory in case there is a problem.

Here's how it will work:

*

*User commits their changes. There is no post-commit hook. User sees immediately whether or not their changes are good.

*Jenkins sees the changes, and does a svn export on the server to create a new working directory.

*Jenkins detects that the svn export is successful, and then moves the old working directory to another name, renames the new working directory to the old location, and then (optionally) deletes the old working copy. There is never a time that the old working directory is in an inconsistent state.

*Jenkins can send an email when the change takes place. Jenkins might also run some smoke testing to see if the code checked in is good, and not do an update if it detects a problem.


text:
Q: Discord c# - Check number of parameters in a command With my discord bot in c#, i tried to send an help message of command if there is 0 paramater sent.
Command: !onserver >> Send help message
Thank you for your help.
commands.CreateCommand("onserver")
 .Parameter("server", ParameterType.Required)
 .Hide()
 .Do(async (e) =>
 {
    int server = Convert.ToInt32(e.GetArg("server"));
    if (e.GetArg("server").Length == 0) //Show command help
     {
         await e.Channel.SendMessage("Help message blablabla");
     }
     if (server > 0)
     {
         await e.Channel.SendMessage($"Utilisateur lanceur: {e.Message.User}");
         await e.Channel.SendMessage($"Serveur choisi: {server}");
     }
 });

A: try:
   int server = Convert.ToInt32(e.Args[0]);


text:
Q: In R data.table conditionally remove rows based on elements in other columns with multiple conditions How do I remove rows in a data.table based on rows in that data.table?
Reproduceable Example:
To create the Data.table run this
library(data.table)
DT <- data.table(Subject=c("A","A","B","B"), Test=c("TEST_A","TEST_A","TEST_A","TEST_A"), Folder=c("D1","Screen","D1","Screen"), Date=as.Date(c("2001-10-22","2001-10-23","2001-10-23","2001-10-25")))
DT[3, Date := NA]
DT

This is a small example of a very large dataset
Here is my logic: For every SUBJECT Remove all rows where TEST_A & folder "D1" has no date but TEST_A & Folder "Screen" has  a date.
I know I can just write an if statement, but I am trying to keep this using only data.table for readability.

A: Try this:
DT[, .SD[ !(any(is.na(Date) & Test == "TEST_A" & Folder == "D1") &&
            any(!is.na(Date) & Test == "TEST_B" & Folder == "Screen")), ], by = Subject]

Your sample data does not contain the conditions you specified, so this does nothing here but should work with more representative data.

Here is some sample data that includes two subjects: one with a valid D1 (dates provided) and one an invalid D1 (no date).
DT <- data.table(Subject=c("A","A","B","B"), Test=c("TEST_A","TEST_B","TEST_A","TEST_B"), Folder=c("D1","Screen","D1","Screen"), Date=as.Date(c("2001-10-22","2001-10-23","2001-10-23","2001-10-25")))
DT[3, Date := NA]
DT
#    Subject   Test Folder       Date
#     <char> <char> <char>     <Date>
# 1:       A TEST_A     D1 2001-10-22
# 2:       A TEST_B Screen 2001-10-23
# 3:       B TEST_A     D1       <NA>
# 4:       B TEST_B Screen 2001-10-25

And the code above (unchanged):
DT[, .SD[ !(any(is.na(Date) & Test == "TEST_A" & Folder == "D1") &&
             any(!is.na(Date) & Test == "TEST_B" & Folder == "Screen")), ],
    by = Subject]
#    Subject   Test Folder       Date
#     <char> <char> <char>     <Date>
# 1:       A TEST_A     D1 2001-10-22
# 2:       A TEST_B Screen 2001-10-23


text:
Q: Rails ActiveRecord, User ID getting a List of datatable Not sure if this question is clear as i am trying find right word for clear on the Question
I am working on the Rails Active Record as trying to get a listing of data which own by User.
At the moment the pages display as you can see Screenshot "more equipment own by Ashford tools Hire

it's should show 5 different tools but I seem cannot get it, I am able to get all data in the display but unable to get the user list of tools, seems I have missed one or two small things
here is the code I wrote.

More equipment own by <%= @tool.user.company %>

          <%= image_tag @tool.images.first, class:"imgnear" if  @tool.images.attached? %>

          <%= link_to @tool.brand, target: :_blank %>

I have tried 'each do' function but keeping getting error
I have done current_user but it not practically

More equipment own by <%= @tool.user.company %>

    <% current_user.tools.each do |tool| %>

          <%= image_tag tool.images.first, class:"imgnear" if  tool.images.attached? %>

          <%= link_to tool.brand, tool, target: :_blank %>

    <% end %>

while in the Tools Controller
  def index
    @tools = current_user.tools

  end

  def new
    @tool = current_user.tools.build
  end

A: I believe that what you display in that screen is ToolsController#show action, not a ToolsController#index action. Probably your show method looks like this:
def show
  @tool = Tool.find(params[:id])
end

or similarly.
In order to have other tools displayed, you need to assign them to some variable inside the same controller action. What you can do is:
def show
  @tool = Tool.find(params[:id]) # or however that line looks
  @other_tools = @tool.user.tools.where("id != ?", @tool.id)
end

This way @other_tools will consist of all the tools belonging to owner of the selected tool, but it will exclude the selected tool (otherwise inside the "also owned by" you can see the same tool as displayed above the list)
One more thing, when you do current_user.tools in your view, you display the items owner by user who is logged in, not the user who owns the main displayed tool, you might not see the error if you log in as an owner, but if you log in as another user, you should see that the list shows wrong tools.


text:
Q: fixed-point free elements in transitive permutation groups Let $n = p^k$ be a power of a prime. Let $G$ be a transitive permutation group on $n$ letters. Show that there exists a fixed-point free element of order $p$.
I can show that there must be a fixed point:
The transitivity of the group implies that there is only $1$ orbit. Burnside's lemma then implies that the average number of fixed points for an element in the group is $1$. Since the identity fixes everything, there is a fixed point free element.
I can show that there exists an element of order $p$:
Again we use that the group is transitive and that there is therefore only one orbit. Since there is only one orbit, the order of the orbit of $x$ is $p^k$. By the orbit-stabilizer theorem, the order of the stabilizer of some element $x$ is equal to the order of the group divided by $p^k$. Since the order of a stabilizer is an integer, $p^k$ divides the order of the group. By Cauchy's theorem, there is an element of order $p$ in the group.
I cannot, however, show that there is an element of order $p$ with no fixed points. Does anyone have any hints?

A: As you ask only for hints, here are two:
Step 1: Show that some/any $p$-Sylow subgroup $P$ of $G$ acts transitively on the $n$ letters.
Step 2: Then consider the action of a central element of $P$ of order $p$.


text:
Q: Group similar words and replace with one word I am having data of 500thousand, I am trying to calculate the co-occurrence, I got a memory issue. Then I figured out there are words that represent a similar meaning. How do to replace those words with words and calculate the co-occurence.
                      0                   1                   2    \
0      product management                 rpm        progress 4gl
1         user experience  interaction design        3d rendering
2            social media               excel          powerpoint
3              government            research    economic history
4  continuous improvement     data governance  quality management

              3                4                    5    \
0              ip            camel   prince2 foundation
1           event             team       graphic design
2  microsoft word             word          real estate
3        planning           policy                 None
4            test  foreign affairs  capacity management

                      6                       7      8    \
0  continuous integration                 gsm(hlr   msc)
1             engineering  user experience design  sales
2                teamwork        microsoft office   None
3                    None                    None   None
4                    lean  industrial engineering   data

                    9    ...   99    100   101   102   103   104   105   106  \
0           programming  ...  None  None  None  None  None  None  None  None
1           3d modeling  ...  None  None  None  None  None  None  None  None
2                  None  ...  None  None  None  None  None  None  None  None
3                  None  ...  None  None  None  None  None  None  None  None
4  process optimisation  ...  None  None  None  None  None  None  None  None

    107   108
0  None  None
1  None  None
2  None  None
3  None  None
4  None  None

[5 rows x 109 columns]

For example, if word and Microsoft words represent the same meaning, how can I replace the words with one word and generate a new column name for them. I am very new to such a situation and am not sure how to proceed with the next step.
My approach is to replace those so that I can use this data for co-occurrence and word2vec and generate a graph for the community detection.


text:
Q: MVC4 Dynamic DateTime Value in Model I am trying to generate a dynamic warranty end date by calculation and I am getting nowhere with intelisense.  Any help will be appreciated.
   public int WarrantyMonths {get;set;}
   public DateTime DateIn{get;set;}
   public DateTime? WarrantyEnd
    {
        get { return DateTime.AddMonths(this.DateIn((this.WarrantyMonths))); }

    }

A: You should read the documentation on how to use a function if you don't understand it. What you probably want is:
get { return DateIn.AddMonths(WarrantyMonths); }


text:
Q: List parent item with all child item on child pages how can I list the parent item with the child item in WP?
I use this:
function wpb_list_child_pages() {
    global $post;
    $parent = "";
    if ( is_page() && $post->post_parent ) {
        $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' );
        $parent =  get_the_title($post->post_parent);
    } else {
        $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' );

        $parent = $post->post_title;
    }
    if ( $childpages ) {
        $string = '

' . $parent;
        $string .= '
' . $childpages . '
';
        $string .= '

';
    }

    return $string;
}
add_shortcode( 'wpb_childpages', 'wpb_list_child_pages' );

but I need this:

PARENT ITEM

CHILD ITEM 1

CHILD ITEM 2

CHILD ITEM 3

CHILD ITEM 4

A: function wpb_list_child_pages() {
    global $post;
    $parent = "";
    if ( is_page() && $post->post_parent ) {
        $parent = wp_list_pages( 'title_li=&include=' . $post->post_parent . '&echo=0' );
        $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->post_parent . '&echo=0' );
    } else {
        $childpages = wp_list_pages( 'sort_column=menu_order&title_li=&child_of=' . $post->ID . '&echo=0' );
        //$parent = $post->post_title;
    }

    if ( $childpages ) {
        $string = '
'. $parent . $childpages . '
';
    }

    return $string;
}
add_shortcode( 'wpb_childpages', 'wpb_list_child_pages' );

OUTPUT ON TOP LEVEL PAGE

       Child Page 1

       Child Page 2

       Child Page 3

OUTPUT ON A CHILD PAGE

       Parent page

       Child Page 1

       Child Page 2

       Child Page 3


text:
Q: grep doesn't allow me to write `[:alpha:]` when I mean `[:alph]` but other tools do I am trying to make a regular expression character class that matches strings that contain one or more of the following characters only, and does not contain any other character.

*

*:

*a

*l

*p

*h.

Of course, I can do something simple like this and it works.
$ printf "foo\nhal\npal\na:h\n" | grep '^[:alph]*$'
hal
pal
a:h

But if I try to do something like this, i.e. use redundant characters in the character class, I get an error.
$ printf "foo\nhal\npal\na:h\n" | grep '^[:alpha:]*$'
grep: character class syntax is [[:space:]], not [:space:]

Now, I know what is going on. grep "believes" I have mistakenly written [:alpha:] when I meant [[:alpha:]].
But isn't [:alpha:] a valid regular expression in POSIX? Should it really throw an error for a valid regular expression? Shouldn't it just warn me that I probably meant [[:alpha:]]?
In fact, sed doesn't complain at all if I use [:alpha:] in the regular expression. It behaves exactly like [:alph]. I believe sed does the right thing.
$ printf "foo\nhal\npal\na:h\n" | sed -n '/^[:alpha]*$/p'
hal
pal
a:h

Python does the right thing too.
>>> import re
>>> re.search('^[:alpha:]*$', 'foo')
>>> re.search('^[:alpha:]*$', 'hal')
<_sre.SRE_Match object at 0x7f33d4060f38>
>>> re.search('^[:alpha:]*$', 'pal')
<_sre.SRE_Match object at 0x7f33d4060920>
>>> re.search('^[:alpha:]*$', 'a:h')
<_sre.SRE_Match object at 0x7f33d4060f38>

It is only grep that tries to be smart and tell me that I didn't mean [:alpha:] but instead I meant [[:alpha:]].
What does the POSIX standard about it? Does it allow a regex engine to throw an error for [:alpha:] or does it require the engine to treat [:alpha:] as if it were [:alph]?
If could quote the relevant excerpts from the POSIX standard verbatim along with a URL to it , I would consider my question answered.

A: You're quite right that "grep [is trying] to be smart and tell me that I didn't mean [:alpha:] but instead I meant [[:alpha:]]" Personally, I don't think that's a terribly bad thing - if grep sees [:alpha:] in an expression, I'd say that it's much more likely that the person writing it is making a mistake, rather than actually meaning what is strictly written.
You're also right that this (arguably helpful) behaviour doesn't conform to POSIX. I note, though, that GNU grep is affected by the environment variable POSIXLY_CORRECT which changes its behaviour to make it POSIX-compliant. There is also a note on the man page which says:

If you mistakenly omit the outer brackets, and search for say,
  '[:upper:]', GNU grep prints a diagnostic and exits with status 2, on
  the assumption that you did not intend to search for the nominally
  equivalent regular expression: '[:epru]'. Set the POSIXLY_CORRECT
  environment variable to disable this feature.

Compare:
$ printf "foo\nhal\npal\na:h\n" | grep '^[:alpha:]*$'
grep: character class syntax is [[:space:]], not [:space:]

with.
$ printf "foo\nhal\npal\na:h\n" | POSIXLY_CORRECT=1 grep '^[:alpha:]*$'
hal
pal
a:h

So it looks as if you can switch off this "helpful" behaviour if you really don't want it.


text:
Q: Merge 's into one? I have a GPX file that contains multiple < trk > sections that follow each other.
Is there a Windows application that will join them into a single < trk > section?
I tried GPSBabel, and GpsTrackEditor, to no avail.

A: You can use any text editor. For combining tracksegments delete all occasions where a closing trkseg tag is followed by a starting trkseg tag. As a result you will have just one track segment. Then do the same for  followed by . There is a bit more to delete as well but you'll get the idea. Keep the one starting trk tag, the name of the first trk, the trackpoints, and closing trk tag. The resulting single track may have very odd jumps in time and location but I guess that you know it.
<trk>
  <name>TRACK_NAME</name>
  <trkseg>
    <trkpt lat="49.0" lon="2.0">
    </trkpt>
    <trkpt lat="50.0" lon="3.0">
    </trkpt>
  </trkseg>                           ***DELETE
  <trkseg>                            ***DELETE
    <trkpt lat="51.0" lon="3.0">
    </trkpt>
  </trkseg>                              ***ONCE TRK IS DELETED DELETE THIS
</trk>                                ***DELETE
<trk>                                 ***DELETE
  <name>TRACK_NAME2</name>            ***DELETE THIS ALSO
  <trkseg>                               ***ONCE TRK IS DELETED DELETE THIS
    <trkpt lat="49.0" lon="3.0">
    </trkpt>
  </trkseg>
</trk>


text:
Q: C# .NET MVC 5 / How do I create Quartz.NET jobs that use Ninject? I have a project with three-level architecture:

*

*project.Data

*project.Domain

*project.Web

I need to implement Quartz.Net to user interface level.
And use it following way:
 public class EmailSender : IJob
 {
     ISomeService _service;

     public EmailSender(ISomeService service)
     {
        _service = service;
     }

     public void Execute(IJobExecutionContext context)
     {
        _service.Create();
     }
 }

public class EmailScheduler
{
    public static void Start()
    {
        IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
        scheduler.Start();

        IJobDetail job = JobBuilder.Create<EmailSender>().Build();

        ITrigger trigger = TriggerBuilder.Create()
            .WithIdentity("trigger1", "group1")
            .StartNow()
            .WithSimpleSchedule(x => x
                .WithIntervalInMinutes(1)
                .RepeatForever())
            .Build();

        scheduler.ScheduleJob(job, trigger);
    }
}

In global.asax.cs
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        EmailScheduler.Start();
    }
 }

In project.Data
I use pattern of repositories. As I use few repositories for each entity, I use Unit of Work pattern to make easier connection to database.
public interface IUnitOfWork : IDisposable
{
    ISomeRepository SomeRepository { get; }
    void Save();
}

EFUnitOfWork class in constructor receives string with name of connection, which will be sent to data context constructor
So we will interact with database through EFUnitOfWork class.
public class EFUnitOfWork : IUnitOfWork
{
    private Context db;

    private SomeRepository _someRepository;

    public EFUnitOfWork(string connectionString)
    {
        db = new Context(connectionString);
    }

    public ISomeRepository SomeRepository
    {
        get
        {
            if (_someRepository == null)
                _someRepository = new SomeRepository(db);
            return _someRepository;
        }
    }
}

In project.Domain
ServiceModule is a special module Ninject, which is used for organizing dependencies matching.
It replaces EFUnitOfWork with IUnitOfWork.
public class ServiceModule : NinjectModule
{
    private string connectionString;
    public ServiceModule(string connection)
    {
        connectionString = connection;
    }
    public override void Load()
    {
        Bind<IUnitOfWork>().To<EFUnitOfWork>().WithConstructorArgument(connectionString);
    }
}

public interface ISomeService
{
    void Create();
}

public class SomeService : ISomeService
{
    IUnitOfWork Database { get; set; }

    public LetterService(IUnitOfWork uow)
    {
        Database = uow;
    }

    public void Create(){
    }
}

In project.Web
To set dependencies I use following class:
public class NinjectDependencyResolver : IDependencyResolver
{
    private IKernel kernel;
    public NinjectDependencyResolver(IKernel kernelParam)
    {
        kernel = kernelParam;
        AddBindings();
    }
    public object GetService(Type serviceType)
    {
        return kernel.TryGet(serviceType);
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        return kernel.GetAll(serviceType);
    }
    private void AddBindings()
    {
        kernel.Bind<ISomeService>().To<SomeService>();
    }
}

In App_Start folder
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(evenafter.WEB.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(evenafter.WEB.App_Start.NinjectWebCommon), "Stop")]

namespace project.WEB.App_Start
{
using System;
using System.Web;

using Microsoft.Web.Infrastructure.DynamicModuleHelper;

using Ninject;
using Ninject.Web.Common;
using Util;
using Ninject.Modules;
using Domain.Infrastructure;
using Quartz.Impl;

public static class NinjectWebCommon
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        // set connection string
        var modules = new INinjectModule[] { new ServiceModule("DefaultConnection") };
        var kernel = new StandardKernel(modules);
        try
        {
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            RegisterServices(kernel);
            return kernel;
        }
        catch
        {
            kernel.Dispose();
            throw;
        }

    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        System.Web.Mvc.DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }
}
}


text:
Q: Getting excel to put together split strings I'm trying to get excel to put together a series of text strings that haven't been formatted systematically, so that they end up split into different rows on a data sheet.
I'm aware this might've been solved elsewhere so sorry for that but I'm struggling to describe the issue, and I can't post images on it but basically it's

*

*Column 1 with a list of the entries, and

*Column 2 with text strings that are spread over 2 or more rows

Is it possible to write some kind of formula or macro that would be able to check the first column and then stitch together all entries in the second column going down until it found a new entry in the first column? I've got a feeling it might be possible using some sort of loop thing with index functions, but I've no idea where to start even.
Thanks,
Mike

A: Mike give this a ty
Sub appendValues()
'The sub is designed to loop through code and when ever there is a null value and column a it will take the value of what is in column B and appended to the row above it and delete the row.
Dim row As Integer
row = 1
'This code starts with row one but this can be changed at will.
Do Until ThisWorkbook.Sheets("sheet1").Cells(row, 2).Value = ""
'loop statement is designed to continue to Loop until there is a null value inside of you the value in the second column.
If ThisWorkbook.Sheets("sheet1").Cells(row, 1).Value = "" Then
ThisWorkbook.Sheets("sheet1").Cells(row - 1, 2).Value = ThisWorkbook.Sheets("sheet1").Cells(row - 1, 2).Value & ThisWorkbook.Sheets("sheet1").Cells(row, 2).Value
Rows(row).Delete
Else
'else statement is needed because there is an implied looping by decreasing the total number of rows after the delete.
row = row + 1
End If
Loop
End Sub
    Sub appendValues()
'The sub is designed to loop through code and when ever there is a null value and column a it will take the value of what is in column B and appended to the row above it and delete the row.

Dim row As Integer

row = 1

'This code starts with row one but this can be changed at will.

Do Until ThisWorkbook.Sheets("sheet1").Cells(row, 2).Value = ""

'loop statement is designed to continue to Loop until there is a null value inside of you the value in the second column.

If ThisWorkbook.Sheets("sheet1").Cells(row, 1).Value = "" Then

ThisWorkbook.Sheets("sheet1").Cells(row - 1, 2).Value = ThisWorkbook.Sheets("sheet1").Cells(row - 1, 2).Value & ThisWorkbook.Sheets("sheet1").Cells(row, 2).Value

Rows(row).Delete

Else

'else statement is needed because there is an implied looping by decreasing the total number of rows after the delete.

row = row + 1

End If

Loop

End Sub


text:
Q: Not able to post with PHP Twitter API I am using TwitterAPIExchange to publish tweets to Twitter. Over the last 4 months I had no problems until I switched from HTTP to HTTPS.
I did not think this would be a problem as I do not even see this as a setting within the Developers APP and I am doing all this through crontab.
I am using the identical code below on two different servers and the one with SSL I get a successful connection (no errors) but no posting of the tweet -- meanwhile on the server without SSL I get a successful connection and a successful post.
Can a IP get blocked and if so, how do I check it if is, or is SSL a problem -- what do I need to do to fix this?
require_once('TwitterAPIExchange.php');
$connection = array('oauth_access_token' => 'xxx', 'oauth_access_token_secret' => 'xxx', 'consumer_key' => 'xxx', 'consumer_secret' => 'xxx');
try {
    $twitter = new TwitterAPIExchange($connection);
    echo 'Connection success <br /> ';
    $response = $twitter->buildOauth('https://api.twitter.com/1.1/statuses/update.json', 'POST')->setPostfields(array('status' => 'Test Tweet'))->performRequest();
    $json = json_decode($response, true);
    if (!empty($json['id_str'])) echo 'Post success: '.$json['id_str'];
}
catch (Exception $ex) {
    echo $ex->getMessage();
}

A: Added CURLOPT_SSL_VERIFYPEER => false to TwitterAPIExchange


text:
Q: Vega: how to load data in ASP.NET I use Vega https://github.com/vega/vega.
That is how to load data:
var loader = vega.loader();
loader.load('data.json').then(function(data) {
  // do something with loaded data
}).catch(function(error) {
  // error handling here
});

How to load data using ASP.NET controller call or ajax request?


text:
Q: Mock a static method taking HttpServletRequest and Principal using Mockito and PowerMock I want to mock a static method taking two parameters, HttpServletRequest and Principal.
//Here is the method signature
public static String getRole(HttpServletRequest request, Principal principal)  throws Exception {
}

I am defining the security test config for injecting security credentials into the test class.
// security test config
@Configuration
@EnableWebSecurity
@EnableWebMvc
static class Config extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws    Exception {
         auth.inMemoryAuthentication().withUser("user").password("password")
        .roles("USER");
    }
}

I am writing the junit test case for a method that internally calls the above static method. How to write the expectation for the above static  method in the junit class?
when(StaticClassA.getRole(??????, ??????)).thenReturn("ROLE1");


text:
Q: what is the difference between virtual machine classic and virtual machine in azure? In Azure there are 2 options available to create virtual machines.
A. normal VM
B. Classic VM
Does anybody know what is the difference between both option? When do we use one over other?

A: Short answer to your question is Normal VM or Virtual Machines is the new way of deploying your Virtual Machines whereas Classic VM or Virtual Machines (Classic) is the old way of deploying them. Azure is pushing towards the new way of deploying resources so the recommendation would be to use it instead of old way. However please keep in mind that there're some features which are available in the old way that have not been ported on to the new way so you just have to compare the features offered and only if something that you need is not available in new way, you use the old way.
Now comes the long answer :)
Essentially there's a REST API using which you interact with Azure Infrastructure.
When Azure started out, this API was called Service Management API (SMAPI) which served its purpose quite well at that time (and to some extent today). However as Azure grew, so does the requirements of users and that's where SMAPI was found limiting. A good example is access control. In SMAPI, there was access control but it was more like all-or-none kind of access control. It lacked the granularity asked by users.
Instead of patching SMAPI to meet user's requirement, Azure team decided to rewrite the entire API which was much simpler, more robust and feature rich. This API is called Azure Resource Manager API (ARM). ARM has many features that are not there in SMAPI (my personal favorite is Role-based access control - RBAC).
If you have noticed that there are two Azure portals today - https://manage.windowsazure.com (old) and https://portal.azure.com (new). Old portal supports SMAPI whereas new portal supports ARM. In order to surface resources created via old portal into new portal (so that you can have a unified experience), Azure team ended up creating a resource provider for old stuff and their names will always end with (Classic) so you will see Virtual Machines (Classic), Storage Accounts (Classic) etc. So the resources you create in old portal can be seen in the new portal (provided the new portal supports them) but any resources you create in the new portal using ARM are not shown in the old portal.

A: The Azure Virtual Machine (classic) is based on the old Azure Service Management Model (ASM). Which revolved around the concept of a cloud service. Everything was contained inside a cloud service, and that was the gateway to the internet. While it is still used (extensively) Azure is now moving over to the Azure Resource Management Model (ARM).
ARM uses the concept of declarative templates to configure an entire solution (rather than individual components) So you can create an entire Sharepoint stack, rather than just a singular machine.
ARM also has a much more logical approach to networking. Instead of having a monolithic VM in an obscure cloud service. You have a VM, that you attach a network card to. You can then put the Network card into a VNet and attach a public IP (if you need one)
Unless you have a compelling reason to use ASM (classic) You should create your solution using ARM. As this is the MS recommendation going forward (todo find a link to that) It also means that you can create templates for your deployments, so you can have a repeatable solution.
On the negative, the old portal manage.windowsazure.com can not manage anything that is deployed using ARM, and there are still parts of ASM that haven't been migrated over to ARM yet. For instance you cannot configure Azure VM backup, since Azure backup is ASM and it can't 'see' ARM VMs
It very largely depends on your circumstances though, what it is you are planning for, the method you are going to deploy with. If you are just looking to stand a machine up to do a single task, it makes very little difference. If you are looking to deploy into an environment that will have some concepts of DevOps going forward, then ARM is the way to go.

A: The one big differences is for resource management. For that new version is called Azure Resource Manager VM (ARM VM).
ARM VM is better in terms of;

*

*Classic VM must be tied with Cloud Service, and Cloud Service consumes resource limitation and not-so-flexible network configuration.

*ARM VM is managed under Azure Resource Manager (ARM) which can be organized with/without other Azure services. ARM is like a folder of Azure services, and it gives you more fine-grained resource management.

Classic VM can be migrated to ARM VM version, but you have to afford service downtime. To migrate from classic VM, read the official article: Considerations for Virtual Machines.

A: Azure provides two deploy models now: Azure Resource Manager(Normal) and Azure Service Management(Classic) and some important considerations you should care when working Virtual Machines.

*

*Virtual machines deployed with the classic deployment model cannot be included in a virtual network deployed with Resource Manager.

*Virtual machines deployed with the Resource Manager deployment model must be included in a virtual network.

*Virtual machines deployed with the classic deployment model don't have to be included in a virtual network.


text:
Q: Redis pubsub in play I'm trying to have a redis client within my play application which will subscribe for updates from redis.
There isn't much on it on the net, I'm using this as reference:
https://github.com/pvillega/play21-redis-pubsub/blob/master/app/controllers/Application.scala
From what I understand it's much easier to accomplish this with scala than java, but I have no scala skills, and so I'm trying to understand things..
What I want is a singleton object through which I will be able to publish and get updates (using subscribers) from the entire application.
Here's what I came up with:
object Redis extends Actor {
    val channel = "myChannel"
    val plugin = Play.application.plugin(classOf[RedisPlugin]).get
    val pool = plugin.sedisPool
    val listener = new PubSubListener()
    val subscribers = mutable.ArrayBuffer.empty[Subscriber]

    Future {
        pool.withJedisClient { client =>
            client.subscribe(listener, channel)
        }
    }(Contexts.redisExecutionContext)

    def receive = {
        case _ => Logger.error("received unknown message")
    }

    def onMessage(message: String): Unit = {
        Logger.debug("MESSAGE FROM REDIS: " + message)

        Redis.subscribers.synchronized {
            for (subscriber <- Redis.subscribers) subscriber.receive(message)
        }
    }

    def addSubscriber(subscriber: Subscriber): Unit = {
        this.subscribers.synchronized {
            this.subscribers += subscriber
        }
    }
}

object Contexts {
    implicit val redisExecutionContext: ExecutionContext = Akka.system.dispatchers.lookup("akka.actor.redis-pubsub-context")
}

trait Subscriber {
    def receive(message: String): Unit
}

case class PubSubListener() extends JedisPubSub {
    def onMessage(channel: String, message: String): Unit = {
        Logger.debug("MESSAGE FROM REDIS: " + message)
        Redis.onMessage(message)
    }

    ...
}

This code does not work, it compiles and does not break in runtime, but it pretty much does nothing..
What it should do is to register for redis updates and that's it.
What am I missing (probably a lot!)?
Thanks!

A: There is a sample application (Scalable chat application with Play and WebSockets) which uses Redis Pub/Sub and the Play Framework 2.x in Java. The Redis client used is Jedis (Java). There are even instructions to directly deploy the application to Heroku.
If you want to run the application locally, install Redis, run the redis server and update the Redis configuration in conf/application.conf
#Redis configuration
redis.uri="http://localhost:6379"

Link to the tutorial of the sample application - https://devcenter.heroku.com/articles/play-java-websockets-advanced
Link to the github repository - https://github.com/heroku-examples/play-websockets-chat-sample


text:
Q: Error: 104 Failed to Obtain Version Information from CRPE32.dll - GetCRPEVersion I did a search and cannot find another question like this one. I'm getting this error with Delphi XE2 and Delphi XE3. I'm using Crystal Reports XI R1. I'm not sure why Delphi would care about the version, the error would need to be during initialization of crpe32.dll. I'm upgrading a Delphi 2006 app to XE3. Very little work required - the only barrier between me and success s this DLL error. Any insight would be appreciated. Many TIAs !
Best regards,
Brian

A: I had this error because on my machine I forgot to install Crystal Reports. I recently installed Win10 and if Crystal Reports was not installed, it gave me this error. Hope it helps!


text:
Q: SDL color "wheel" I'm trying to implement a simple color wheel in c using SDL. The program should print a sequence of different colored bars, that scroll across the screen and loop back to the beginning when they've traversed the whole screen, in effect making a sort of scrolling color "wheel". What I have doesn't quite work right, and also isn't particularly reusable. Can anyone advise me on how to fix what I have with a more compact solution? Here's what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <SDL2/SDL.h>

static const int width = 800;
static const int height = 600;
static const int rectW = width/4;

void sdlT()
{
    // Initialize SDL
SDL_Init(SDL_INIT_VIDEO);

// Create a SDL window
SDL_Window *window = SDL_CreateWindow("Hello, SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL);

// Create a renderer
SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

bool running = true;
SDL_Event event;
int x = 0;
int y = 0;
int count = 0;
while(running)
{
    // Check for events
    while(SDL_PollEvent(&event))
    {
        //close SDL if user clicks window 'x'
        if(event.type == SDL_QUIT)
        {
            running = false;
        }
    }

    // Clear screen
    SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
    SDL_RenderClear(renderer);

    SDL_Rect rect = {0, y, x < rectW ? x : x-rectW*count, height};
    SDL_Rect rect2 = {x, y, rectW, height};
    SDL_Rect rect3 = {x+rectW, y, rectW, height};
    SDL_Rect rect4 = {x+rectW*count, y, rectW, height};

    SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
    if(x < rectW){
        SDL_RenderFillRect(renderer, &rect);//fills w/ current color
    }else if(x >= rectW && x < (rectW *2)){
        SDL_RenderFillRect(renderer, &rect2);
    }else if(x>=(rectW *2) && x < (rectW *3)){
        SDL_RenderFillRect(renderer, &rect3);
    }else if (x>=(rectW *3) && x < (rectW *4)){
        SDL_RenderFillRect(renderer, &rect4);
    }

    SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
    if(x < rectW){
        SDL_RenderFillRect(renderer, &rect2);//fills w/ current color
    }else if(x >= rectW && x < (rectW *2)){
        SDL_RenderFillRect(renderer, &rect3);
    }else if(x>=(rectW *2) && x < (rectW *3)){
        SDL_RenderFillRect(renderer, &rect4);
    }else if (x>=(rectW *3) && x < (rectW *4)){
        SDL_RenderFillRect(renderer, &rect);
    }

    SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
    if(x < rectW){
        SDL_RenderFillRect(renderer, &rect3);//fills w/ current color
    }else if(x >= rectW && x < (rectW *2)){
        SDL_RenderFillRect(renderer, &rect4);
    }else if(x>=(rectW *2) && x < (rectW *3)){
        SDL_RenderFillRect(renderer, &rect);
    }else if (x>=(rectW *3) && x < (rectW *4)){
        SDL_RenderFillRect(renderer, &rect2);
    }

    SDL_SetRenderDrawColor(renderer, 0, 255, 255, 255);
    if(x < rectW){
        SDL_RenderFillRect(renderer, &rect4);//fills w/ current color
    }else if(x >= rectW && x < (rectW *2)){
        SDL_RenderFillRect(renderer, &rect);
    }else if(x>=(rectW *2) && x < (rectW *3)){
        SDL_RenderFillRect(renderer, &rect2);
    }else if (x>=(rectW *3) && x < (rectW *4)){
        SDL_RenderFillRect(renderer, &rect3);
    }

    // Show what was drawn
    SDL_RenderPresent(renderer);
    x++;
    if(x >= rectW){
        count++;
        x= 0;
    }
}

// Release resources
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();

}

A: I figured it out:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#include <SDL2/SDL.h>

static const int width = 800;
static const int height = 600;
static const int rectW = width/2;

int getColor(int count){
    if(count >=3){
        count = count-3;
    }
    return count;
}

void sdlT()
{
    // Initialize SDL
    SDL_Init(SDL_INIT_VIDEO);

    // Create a SDL window
    SDL_Window *window = SDL_CreateWindow("Hello, SDL2", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_OPENGL);

    // Create a renderer (accelerated and in sync with the display refresh rate)
    SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

    bool running = true;
    SDL_Event event;
    int x = 0;
    int y = 0;
    int count = 3;
    int arr[3][3] = {{0,0,255},{0,255,0},{255,0,0}};

    while(running)
    {
                // Process events
        while(SDL_PollEvent(&event))
        {
            if(event.type == SDL_QUIT)
            {
                running = false;
            }
        }

        // Clear screen with black
        SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
        SDL_RenderClear(renderer);

        SDL_Rect rect = {0, y, x < rectW ? x : rectW, height};
        SDL_Rect rect2 = {x, y, rectW, height};
        SDL_Rect rect3 = {x+rectW, y, rectW, height};

        SDL_SetRenderDrawColor(renderer, arr[getColor(count)][0], arr[getColor(count)][1], arr[getColor(count)][2], 255);
        SDL_RenderFillRect(renderer, &rect);

        SDL_SetRenderDrawColor(renderer, arr[getColor(count+1)][0], arr[getColor(count+1)][1], arr[getColor(count+1)][2], 255);
        SDL_RenderFillRect(renderer, &rect2);

        SDL_SetRenderDrawColor(renderer, arr[getColor(count+2)][0], arr[getColor(count+2)][1], arr[getColor(count+2)][2], 255);
        SDL_RenderFillRect(renderer, &rect3);

        // Show what was drawn
        SDL_RenderPresent(renderer);
        x++;
        if(x >= rectW){
            x= 0;
            count--;
        }
        if(count == 0){
            count = 3;
        }
    }

    // Release resources
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
}


text:
Q: How do I install the open-cv library for use in Pycharm IDE on a Ubuntu 16.04 system using pip? main.py : has line import cv2, but on running
python main.py and error is thrown.
EDIT:
pip install opencv-python installs cv2 package.

A: Have you installed the package? Try running
pip install opencv-python

in the command line prompt, the proceed with import cv2 in a python console.

A: Follow These Steps in this Tutorial:-
https://itsfoss.com/install-pycharm-ubuntu/


text:
Q: Creating a regular expression that will match requirements in a string The issue
I need to write a regular expression that will match the following requirements in a string with the structure {A/B}.
Requirements/Conditions:

*

*A and B can only be exactly one of [UGWRB].

*A structure where U or G do not appear is invalid.

*A structure where both characters are equal is invalid.

*U or G must appear in the combination at least once.

*The structure can repeat or continue infinite times, as long as each following instance is still valid when read alone. (see valid matches below)

Valid matches:

*

*{U/G}{U/G}{U/G}

*{W/G}{U/B}

*{U/G}{U/B}

*{U/G}

*{G/U}

*{U/B}

*...

Invalid matches:

*

*{U/U}{U/U}

*{U/U}{G/G}

*{U/G}{U/U}

*{U/G}{R/B}

*{G/G}

*{R/B}

*{W/R}

*{B/W}

*...

My attempt
This is what I have gotten so far, but out of all the combinations of UGWRB, I'm only getting 8 matches out of 14.
{([UG])(?(1)|\w)\/(?(1)\w|[UG])}

A: You have to work with lookaheads both negative and positive in order to accomplish the task:
^(?:{(?=[^{}]*[UG])([UGWRB])\/(?!\1)(?1)})+$

See live demo here
Note that m flag should be set.
Regex breakdown:

*

*^ Match start of input string

*(?: Start of non-capturing group

*

*{ Match { literally

*(?= Start of positive lookahead

*

*[^{}]*[UG] Look for [UG] in combination

*) End of lookahead

*([UGWRB]) Match and capture a letter from character class

*\/(?!\1)(?1) Match / and see if next char is not the same as recently captured one

*} Match } literally

*)+ End of group, repeat at least once

*$ Match end of input string

A: Try this regex:
^(?!.*{([UGWRB])\/\1})(?:{(?(?=[UG]).\/[UGWRB]|[WRB]\/[UG])})+$

Click for Demo
Explanation:

*

*^ - matches the start of the string

*(?!.*{([UGWRB])\/\1}) - negative lookahead to make sure that the structures like {G/G} or {U/U} or {R/R} are not present anywhere in the string

*{ - matches {

*(?(?=[UG]).\/[UGWRB]|[WRB]\/[UG]) - Regex Conditional. If the current position is followed by either U or G, then the match that character followed by / and the character class [UGWRB]. Otherwise, match the character class [WRB] followed by / followed by U or G

*} - matches }

*+ - matches 1+ occurrences of the above sub-sequence (?:{(?(?=[UG]).\/[UGWRB]|[WRB]\/[UG])})

*$ - matches the end of the string


text:
Q: Would service socket be closed before core dump or after it? If a service is crashed and generate a core dump, will the socket which the service listens be closed immediately or closed when the core dump is done.

A: What I see in my application is that a listening socket is not closed when a signal arrives and Linux starts writing a core file. It is only closed when the core file has been written.
In order to change this behavior it is possible to close a listening socket right in a signal handler. close() is async-signal-safe: http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html


text:
Q: How Do I Make Enemies In My Game Shoot Missles randomnly? So I'm trying to create space Invaders currently and i'm trying to make the aliens shoot at the player randomnly. I've made it so that one projectile or enemy missle is shot at the player, but I can't figure out how I can make this happen from random places where the aliens are located, and how I can make the enemy repeatedly shoot missles,as opposed to just once as it's doing right now. My code that i'm using is down below (variables related to the shooting of the enemy are enemMissleFire and enemymissles)....
import pygame
import sys
import time

#initialize pygame
pygame.init()
width = 800
height = 600
# set the size for the surface (screen)

screen = pygame.display.set_mode((width, height),pygame.FULLSCREEN)
width = screen.get_width()
height = screen.get_height()
print(width)
print(height)
# set the caption for the screen
pygame.display.set_caption("Space Invaders")

def checkCollision(missles, type, score):
    for missle in missles:
      collision = missle.collidelist((type))
      if collision > -1:
        type.pop(collision)
        missles.remove(missle)
      missle.move_ip(0,missleSpeed)
      pygame.draw.rect(screen, WHITE, missle,0)

# define colours  you will be using
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
YELLOW = (255,255,0)

clock = pygame.time.Clock()
FPS = 60
s = 25
#load and scale images
smallInvaderImg = pygame.image.load("images/smallinvader.png")
smallInvaderImg = pygame.transform.scale(smallInvaderImg,(s,s))
medInvaderImg = pygame.image.load("images/crabinvader.png")
medInvaderImg = pygame.transform.scale(medInvaderImg, (s,s))
bigInvaderImg = pygame.image.load("images/biginvader.png")
bigInvaderImg = pygame.transform.scale(bigInvaderImg, (s,s))
shipImg = pygame.image.load("images/ship.png")
shipImg = pygame.transform.scale(shipImg, (60,60))

smallInvaders = []
medInvaders = []
bigInvaders = []
enemiesMap = ["sssssssssss",
             "mmmmmmmmmmm",
             "mmmmmmmmmmm",
           "bbbbbbbbbbb"]
invadertype = [smallInvaders,medInvaders,bigInvaders]
dx = 1
dy = 0
x = 240
y = 0
gap = 10
for element in enemiesMap:
  for char in element:
    if char == "s":
      smallInvaders.append(pygame.Rect(x,y,s,s))
    elif char == "m":
      medInvaders.append(pygame.Rect(x,y,s,s))
    elif char == "b":
      bigInvaders.append(pygame.Rect(x,y,s,s))
    x += s + gap
  y += s + gap
  x = 240

score = 2

ship = pygame.Rect(width/2,525,60,60)

if ship.right == width:
  ship.right = width

#missles
maxMissles = 3
missleSpeed = -6
missleWidth = 5
missleHeight = 30
enemmissleWidth = 5
enemmissleHeight = 25
missles = []
missleFired = False
lives = 3

playbutton = pygame.Rect(width/2,height/2,155,90)
playbutton.center = (width/2,height/2)
quitbutton = pygame.Rect(width/2,height/2,155,90)
quitbutton.center = (width/2,height/2+110)
playagn = pygame.Rect(width/2,height/2,155,90)
playagn.center = (width/2,height/2)

playword = pygame.font.SysFont("comicsanms", 35)
title = pygame.font.SysFont("comicsanms", 90)
quitword = pygame.font.SysFont("comicsanms",35)
endscreen = pygame.font.SysFont("comicsanms", 90)
playagaintext = pygame.font.SysFont("comicsanms", 35)

enemMissleFire = False
enemmislist = []
enemymissles = (pygame.Rect(ship.centerx,y,enemmissleWidth,enemmissleHeight))

invaderDirSwapped = False
screenControl = 0

main = True
while main:
  clock.tick(60)
  for event in pygame.event.get():
     if event.type == pygame.QUIT:
      main = False

  for element in smallInvaders:
    element.move_ip(dx,dy)

  for element in smallInvaders:
    if element.right >= width or element.left <= 0:
      dx *= -1
      invaderDirSwapped = True

  for element in medInvaders:
    element.move_ip(dx,dy)

  if not invaderDirSwapped:
    for element in medInvaders:
      if element.right >= width or element.left <= 0:
        dx *= -1
        invaderDirSwapped = True

  for element in bigInvaders:
    element.move_ip(dx,0)

  if not invaderDirSwapped:
    for element in bigInvaders:
      if element.right >= width or element.left <=0:
        dx *= -1
        invaderDirSwapped = True

  key_input = pygame.key.get_pressed()
  if key_input[pygame.K_RIGHT] and ship.right < width:
    ship.move_ip(4,0)
  if key_input[pygame.K_LEFT] and ship.left > 0:
    ship.move_ip(-4,0)
  if key_input[pygame.K_SPACE] and not missleFired:
    missleFired = True
    missles.append(pygame.Rect(ship.centerx,ship.top,missleWidth,missleHeight))

  if screenControl == 0:
    screen.fill(BLACK)

    texttitle = title.render("SPACE INVADERS", True, WHITE)
    textrect = texttitle.get_rect()
    textrect.center = (width/2, 100)
    screen.blit(texttitle,textrect)

    if playbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
      screenControl = 1
    pygame.draw.rect(screen,WHITE,(playbutton), 0)

    if playbutton.collidepoint(pygame.mouse.get_pos()):
      pygame.draw.rect(screen,BLUE, (playbutton), 4)

    if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
      main = False
    pygame.draw.rect(screen,WHITE,(quitbutton), 0)

    if quitbutton.collidepoint(pygame.mouse.get_pos()):
      pygame.draw.rect(screen,BLUE,quitbutton,4)

    textplay = playword.render("PLAY", True, BLUE)
    textrect2 = textplay.get_rect()
    textrect2.center = (width/2,height/2)
    screen.blit(textplay,textrect2)

    textquit = quitword.render("QUIT",True,BLUE)
    textrect3 = textquit.get_rect()
    textrect3.center = (width/2,height/2+110)
    screen.blit(textquit,textrect3)

  if screenControl == 1:
    screen.fill(BLACK)

    if len(missles) > 0:
      if missleFired and missles[-1].bottom < (ship.top - 120) and not key_input[pygame.K_SPACE]:
        missleFired = False
    if len(missles) == 0:
      missleFired = False

    if enemMissleFire:
      enemymissles.colliderect(ship)
      enemymissles.move_ip(0,-missleSpeed)
      pygame.draw.rect(screen, WHITE, enemymissles,0)

    for invader in smallInvaders:
      screen.blit(smallInvaderImg, invader)
    for invader in medInvaders:
      screen.blit(medInvaderImg, invader)
    for invader in bigInvaders:
      screen.blit(bigInvaderImg, invader)
    screen.blit(shipImg,ship)

  #move and draw missles

  checkCollision(missles,smallInvaders,score)
  checkCollision(missles,medInvaders,score)
  checkCollision(missles,bigInvaders,score)

  if smallInvaders == [] and medInvaders == [] and bigInvaders == []:
    screenControl = 2

  if screenControl == 2:
    screen.fill(BLACK)

    if playagn.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
      screenControl = 0
    pygame.draw.rect(screen,WHITE,(playagn),0)

    if quitbutton.collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:
     main = False
    pygame.draw.rect(screen,WHITE, (quitbutton),0)

    if playagn.collidepoint(pygame.mouse.get_pos()):
      pygame.draw.rect(screen,BLUE,(playagn), 4)

    if quitbutton.collidepoint(pygame.mouse.get_pos()):
      pygame.draw.rect(screen,BLUE,(quitbutton),4)

    textend = endscreen.render("YOU WON!", True, WHITE)
    textrect4 = textend.get_rect()
    textrect4.center = (width/2, 150)
    screen.blit(textend,textrect4)

    textplayagn = playagaintext.render("PLAY AGAIN", True, BLUE)
    textrect5 = textplayagn.get_rect()
    textrect5.center = (width/2,height/2)
    screen.blit(textplayagn,textrect5)

    textquit = quitword.render("QUIT",True,BLUE)
    textrect3 = textquit.get_rect()
    textrect3.center = (width/2,height/2+110)
    screen.blit(textquit,textrect3)

  pygame.display.update()

Regardless, I can't figure out how I can make it so that projectiles can be shot from random aliens, over the course of the player shooting, and so any help would be appreicated.

A: Import Random and Time
this will get the random and time functions built in
from random import randint as ran
import time

Get the Number
this will get the time between the previous shot and the next
t = ran(Min_Time,Max_Time)

Get The Countdown
this will count a second between numbers
time.sleep(1)
t -= 1
print(t)

Shot!
shoot
if t == 0:
print('shot!')

FINAL CODE (trumpet fanfare)
from random import randint as ran
import time

def randshot(Min_Time,Max_Time):
    t = ran(Min_Time,Max_Time)
    print(t)
    while t:
        time.sleep(1)
        t -= 1
        print(t)
    if t == 0:
        print('shot!')
while True:
    randshot(5,10)

Hope this Helped!


text:
Q: fade a page in with jquery after a button is clicked with this jquery i can fade the page in after it loads:

now what i want to do is have it that function happen after a button is clicked. for example, when the user goes to the page, there would be a window with a clickable button. after the button was clicked then it would do that fade in jquery loading the page with a fade in.
i was thinking that it would be some kind of form, but the problem is it needs to hide the body when the page is loaded, and then fade in to the body after the button is clicked.
EDIT: i have something like this, however it wont load properly.

and for the body and body content

<button onclick="loadp()">Try it</button>

<bodycontent>
codehere
</bodycontent>

theoretically that is supposed to hide the body and fade the bodycontent in after the button is clicked. however the body is hidden but the bodycontent is not loaded.

A: DEMO
<button id="fadeContent">OK, fade!</button>

Page

Content

#bodyContent{
  display:none;
  position:absolute;
  top:0;      left;0;
  width:100%; height:100%;
  background:#cf5;
}

$(function() {

  $('#fadeContent').click(function(){
    $(this).hide();
    $('#bodyContent').fadeIn(1000);
  });

});

A: this is a fiddle of how i did it: http://jsfiddle.net/VTD9k/
the point is that you put the content inside a div inside the body : #main-wraper,
and the button in another div


text:
Q: Send POST data on redirect with JavaScript/jQuery? Basically what I want to do is send POST data when I change the window.location, as if a user has submitted a form and it went to a new page. I need to do it this way because I need to pass along a hidden URL, and I can't simply place it in the URL as a GET for cosmetic reasons.
This is what I have at the moment, but it doesn't send any POST data.
if(user has not voted) {

    window.location = 'http://example.com/vote/' + Username;

}

I know that you can send POST data with jQuery.post(), but I need it to be sent with the new window.location.
So to recap, I need to send api_url value via POST to http://example.com/vote/, while sending the user to the same page at the same time.

For future reference, I ended up doing the following:
if(user has not voted) {

    $('#inset_form').html('<form action="http://example.com/vote/' + Username + '" name="vote" method="post" style="display:none;"><input type="text" name="api_url" value="' + Return_URL + '" /></form>');

    document.forms['vote'].submit();

}

A: This is quite handy to use:
var myRedirect = function(redirectUrl, arg, value) {
  var form = $('<form action="' + redirectUrl + '" method="post">' +
  '<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
  $('body').append(form);
  $(form).submit();
};

then use it like:
myRedirect("/yourRedirectingUrl", "arg", "argValue");

A: Here's a simple small function that can be applied anywhere as long as you're using jQuery.
var redirect = 'http://www.website.com/page?id=23231';
$.redirectPost(redirect, {x: 'example', y: 'abc'});

// jquery extend function
$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {
            value = value.split('"').join('\"')
            form += '<input type="hidden" name="'+key+'" value="'+value+'">';
        });
        $('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
    }
});

A: Here is a method, which does not use jQuery.
I used it to create a bookmarklet, which checks the current page on w3-html-validator.
var f = document.createElement('form');
f.action='http://validator.w3.org/check';
f.method='POST';
f.target='_blank';

var i=document.createElement('input');
i.type='hidden';
i.name='fragment';
i.value='<!DOCTYPE html>'+document.documentElement.outerHTML;
f.appendChild(i);

document.body.appendChild(f);
f.submit();

A: If you are using jQuery, there is a redirect plugin that works with the POST or GET method. It creates a form with hidden inputs and submits it for you. An example of how to get it working:
$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

Note: You can pass the method types GET or POST as an optional third parameter; POST is the default.

A: per @Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..
var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
  '<input type="text" name="api_url" value="' + Return_URL + '" />' +
  '</form>');
$('body').append(form);
form.submit();

A: The answers here can be confusing so i will give you a sample code that i am working with.
To start with note that there is no POST parameter to java script windows.location function that you are referring to.
So you have to...

*

*Dynamically make a form with a POST parameter.

*Dynamically put a textbox or textboxes with your desired values to post

*Invoke the submit form you dynamically created.
And for the example.
     //---------- make sure to link to your jQuery library ----//

<script type="text/javascript" >

    var form = $(document.createElement('form'));
    $(form).attr("action", "test2.php");
    $(form).attr("method", "POST");
    $(form).css("display", "none");

    var input_employee_name = $("<input>")
    .attr("type", "text")
    .attr("name", "employee_name")
    .val("Peter" );
    $(form).append($(input_employee_name));

    var input_salary = $("<input>")
    .attr("type", "text")
    .attr("name", "salary")
    .val("1000" );
    $(form).append($(input_salary));

    form.appendTo( document.body );
    $(form).submit();

</script>

If all is done well, you shall be redirected to test2.php and you can use POST to read passed values of employee_name and salary; that will be Peter and 1000 respectively.
On test2.php you can get your values thus.
$employee_name = $_POST['employee_name'];
$salary = $_POST['salary'];

Needless to say , make sure you sanitize your passed values.

A: Construct and fill out a hidden method=POST action="http://example.com/vote" form and submit it, rather than using window.location at all.

A: Generic function to post any JavaScript object to the given URL.
function postAndRedirect(url, postData)
{
    var postFormStr = "<form method='POST' action='" + url + "'>\n";

    for (var key in postData)
    {
        if (postData.hasOwnProperty(key))
        {
            postFormStr += "<input type='hidden' name='" + key + "' value='" + postData[key] + "'></input>";
        }
    }

    postFormStr += "</form>";

    var formElement = $(postFormStr);

    $('body').append(formElement);
    $(formElement).submit();
}

A: var myRedirect = function(redirectUrl) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="parameter1" value="sample" />' +
'<input type="hidden" name="parameter2" value="Sample data 2" />' +
'</form>');
$('body').append(form);
$(form).submit();
};

Found code at http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/
Going to try this and other suggestions for my work.
Is there any other way to do the same ?

A: You can use target attribute to send form with redirect from iframe.
Your form open tag would be something like this:
method="post" action="http://some.url.com/form_action" target="_top"

A: SOLUTION NO. 1
 //your variable
    var data = "brightcherry";

    //passing the variable into the window.location URL
    window.location.replace("/newpage/page.php?id='"+product_id+"'");

SOLUTION NO. 2
//your variable
var data = "brightcherry";

//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id=" + product_id);

details


text:
Q: In tcsh, how can I keep '{' '}' in assigning a variable? I am making a simple shell script using the tcsh shell.
I assigned a variable as a command to use later.
But brackets within single quotes disappear.
set aaa = "test '10' '{}' ' " ; echo $aaa

Result shows
test '10' '' '

Why does this happen?
If I use {} and '' separately, it is ok.
set aaa = "test '10' {} '' ' " ; echo $aaa
test '10' {} '' '

A: I think it has something to do with csh doing brace expansion after parameter expansion. It does leave {} by itself alone, but it seems to remove the {} from e.g. foo{}. (I don't know why it doesn't just turn that into the empty string, even though there's basically an empty list between the braces. I think in other shells {} or {foo} with just one item inside doesn't trigger brace expansion.)
Quote the expansion to avoid that.
> set a = 'foo{a,b}'
> echo $a
fooa foob
> set b = '{}'
> echo $b
{}
> set c = 'foo{}'
> echo $c
foo
> echo "$c"
foo{}

And your particular case:
> set aaa = "test '10' '{}' ' "
> echo "$aaa"
test '10' '{}' '


text:
Q: how to extract the word before a certain word in a python string Let's say I have a df of python strings:
  string
0 this house has 3 beds inside
1 this is a house with 2 beds in it
2 the house has 4 beds

I want to extract how many beds each house has. I felt a good way to do this would be to just find the item before beds.
While attempting to complete this problem, I of course noticed strings are indexed by character. That means I would have to turn the strings into a list with str.split(' ').
Then, I can find the index of 'beds' in each of the strings, and return the previous index. I tried both a list comprehension and df.iterrows() for this and can't seem to figure out the right way to do it. My desired output is:
  string                            beds
0 this house has 3 beds inside        3
1 this is a house with 2 beds in it   2
2 the house has 4 beds                4

A: look at efficient way to get words before and after substring in text (python)
In your case, you could do
for index, row in df.iterrrows():
    row['beds'] = row['string'].partition('bed')[0].strip()[-1]

The partition function splits the string based on a word and returns a tuple
The strip function is just used to remove white spaces.
If everything works, then the number you are looking for will be at the end of the first value of the tuple. Hence the [0]
for index, row in df.iterrrows():
    row['beds'] = row['string'].partition('bed')[0].strip()[-1]

If the above code is broken down for better readability:
for index, row in df.iterrrows():
    split_str = row['string'].partition('bed')
    word_before_bed = split_str[0].strip()
    number_of_beds = word_before_bed[-1]
    row['beds'] = number_of_beds #append column to existing row

print(df.head())

The output df will have a 3 columns.
Note: this is a quick "hack". Notice there is no error checking in the loop. You should add error checking as you never know if the word "bed" shows up at all in the row.


text:
Q: Metadata loading was interrupted because of data fetching issues. For details, see the log I use AWS Schema Conversion Tool to migrate a data base source SQL Server to PostgreSQL, but the DB schema does not load and I get this error message " Metadata loading was interrupted because of data fetching issues. For details, see the log "
And on the log file I find this message:
" Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Unable to resolve the classification conflict between "French_CI_AS" and "SQL_Latin1_General_CP1_CI_AS" in the operation equal to."
I tried to change the collation of my DB using "ALTER DATABASE
COLLATE SQL_Latin1_General_CP1_CI_AS; " But it doesn't resolve the problem .
Can someone help me please ?


text:
Q: Single sql query to select a record from parent table only if all it's records in child table has values I've Table1 and Table2, Table1's PK is the FK of Table2. Now i need to perform a select from Table1 if and only if all the records in Table2 corresponding to a Table1 record has values (if any field value is null then skip).
ie, for an id in Table1 there have multiple sub ids in Table2. Out of those multiple ids if a particular field corresponds to any one id is null then select should be skipped.
Any one please help me out to write a single sql query for this requirement.

A: This is called an "anti-join" (or anti-semijoin). One way to write it in SQL is to use the NOT EXISTS construction:
SELECT t1.*
FROM Table1 AS t1
WHERE NOT EXISTS
      ( SELECT *
        FROM Table2 AS t2
        WHERE t2.FKcolumn = t1.PKcolumn
          AND t2.columnX IS NULL
      )

If - as your comment - you want a parent row (at Table1) not related to any child row (at Table2), to NOT be shown, add this (or join Table2 if you also want columns from the second table shown):
  AND EXISTS
      ( SELECT *
        FROM Table2 AS t2
        WHERE t2.FKcolumn = t1.PKcolumn
      )

A: select t1.* from table1 t1
where exists(select 1 from table2 t2 where t2.FKcolumn = t1.PKcolumn
             having count(*)=count(t2.columnX) and count(*)>0)


text:
Q: Major drawback of REST web service I am reading a Javascript book where it talks about web services but I find it hard to understand the following sentence as being a drawback of using REST (Representational State Transfer).

One of the biggest drawbacks to using REST is that some browsers
  support only GET and POST methods, whereas many firewalls allow
  passage of only GET and POST methods.

I don't really see how this is regarded as a drawback.
English is not my 1st language so it could be just me finding it hard.
Can someone elaborate on this?

A: REST supports PUT and DELETE methods as well as GET and POST - so if your app should run in a browser you're limited.
The convention is to use GET to retrieve information, POST to create new object/entity, PUT to update an existing object/entity and DELETE to delete...

A: Restful web service typically utilize many of the methods defined in the Http spec. So, Create methods use Http Post, Read methods use Http Get, Update methods Http Put, Delete methods use Http Delete.  See http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html and Which HTTP methods match up to which CRUD methods?.
The concern raised in the book is that Put and Delete may not be usable through firewalls or in some browsers. I don't know if this is a valid concern. I think the Internet infrastructure today handles this stuff pretty well.
The Crud methods Stack Overflow article mentioned above includes a helpful comment:

And since PUT and DELETE aren't yet supported by web browsers, it's
  considered okay to "overload POST" by adding a query string argument
  like method=PUT or method=DELETE on the URI being POSTed

A: It is a drawback in that if your application relies on DELETE or PUT requests not every client or network configuration will support that, meaning that there will be situations where you may not be able to deploy it (without workarounds).
I am not sure if this remains a real problem, though, and it is easily solved by having some filter rewrite requests for clients that cannot issue proper DELETE or PUT.

A: Well REST Web services uses the HTTP Request Methods: POST, GET, DELETE, PUT.
So this means that the PUT and DELETE HTTP Request methods are not supported. It is a draw back but there are ways to get around it by manipulating the DTO's. This however will mean that you don't follow the full REST approach.


text:
Q: How to transform POST body response to get the elements? I am making a web request using HTTPoison in Elixir:
HTTPpoison.post "http://localhost:3000/mymodels"," {\"param1\": \"#{value1}\" ,  \"param2\":\"#{value2}\"} ", [{"Content-Type", "application/json"}]

This is the response I get:
{:ok,
 %HTTPoison.Response{body: "{\"id\":46,\"result\":18,\"param1\":\"liqueur\",\"param2\":\"quif\"}",
  headers: [{"X-Frame-Options", "SAMEORIGIN"},
   {"X-XSS-Protection", "1; mode=block"}, {"X-Content-Type-Options", "nosniff"},
   {"Location", "http://localhost:3000/mymodels/46"},
   {"Content-Type", "application/json; charset=utf-8"},
   {"ETag", "W/\"05b8c75e0a5288c835651f48d4b8a80a\""},
   {"Cache-Control", "max-age=0, private, must-revalidate"},
   {"X-Request-Id", "1e8ae2d3-073a-4779-916a-edffc38f8b5a"},
   {"X-Runtime", "0.530440"}, {"Transfer-Encoding", "chunked"}],
  status_code: 201}}

I'm new to Elixir and my problem is I want to get the results element from the response.body
iex(3)> response.body
"{\"id\":46,\"results\":18,\"param1\":\"liqueur\",\"param2\":\"quif\"}"

I am not sure how to convert this string to an array/hash or stuple in Elixir. I have at Enum, but it doesn't seem to work

A: response.body is a JSON encoded string. You need to use a JSON parser to parse it to the appropriate Elixir data structure first. With Poison, you'd use Poison.decode!/1:
iex(1)> body = "{\"id\":46,\"results\":18,\"param1\":\"liqueur\",\"param2\":\"quif\"}"
"{\"id\":46,\"results\":18,\"param1\":\"liqueur\",\"param2\":\"quif\"}"
iex(2)> json = Poison.decode!(body)
%{"id" => 46, "param1" => "liqueur", "param2" => "quif", "results" => 18}
iex(3)> json["results"]
18


text:
Q: Compute $\sum_{n=1}^\infty (\frac34)^n \frac{7n+32}{n(n+2)}$
Question: Compute $$\sum_{n=1}^\infty \left(\frac34\right)^n \frac{7n+32}{n(n+2)}$$

I first did the partial fraction decomposition into:
$$\sum_{n=1}^\infty \left(\frac34\right)^n \frac{16}n - \sum_{n=1}^\infty \left(\frac34\right)^n \frac9{n+2}$$
Here I am stuck because I wrote out a couple terms and I don't see a way that terms can cancel out. Can I get some help?

A: There is no need to cancel terms across both series because of the $(3/4)^n$. Evaluating both series individually (using the Maclaurin series of $\log(1-x)$) gives
$$S=\frac{16}{\log4}-\left(-\frac{33}2+\frac{16}{\log4}\right)=\frac{33}2$$

A: Hint:
Let $\dfrac{7n+32}{n(n+2)}\cdot\left(\dfrac34\right)^n=f(n)-f(n-2)$
where $f(m)=\dfrac a{m+2}\cdot\left(\dfrac34\right)^m$
so that for $r\ge4,$ $$\sum_{n=2}^r\dfrac{7n+32}{n(n+2)}\cdot\left(\dfrac34\right)^n=\sum_{n=2}^r(f(n)-f(n-2))=f(r)+f(r-1)-f(1)-f(0)$$
$$f(n)-f(n-2)=\left(\dfrac34\right)^n\left(\dfrac a{n+2}-\dfrac an\cdot\dfrac{16}9 \right)$$
We need $\dfrac{7n+32}{n(n+2)}=\dfrac a{n+2}-\dfrac an\cdot\dfrac{16}9=-a\cdot\dfrac{7n+32}{9n(n+2)}\implies a=-9$

A: In this this type of problems just do telescoping now make the second terms in your partial fraction in powers of n+2 that is just divide and multiply by 16 in second term then do telescoping and possible answers are 33/2