text:
Q: read 9th column from text file and replace 11th column to the same file I want to read 9th column of text file with '~' delimiter and need to retrieve data from for the corresponding 11th column which resides in a table. that data i need to replace in 11th column of the file which is having NULL values currently.
How to achieve this in unix.
col1~col2~col3~col4~col5~col6~col7~col8~col9~col10~col11~col12~col13

data1~data2~data3~data4~data5~data6~data7~data8~data9~data10~~data12~data13

in the data data11 is null . so i want to take the corresponding value for data9 and replace the data11.
Thanks

A: If you want only to copy column 9 to column 11 this can be done with script like this:
awk 'BEGIN {FS="~"; OFS="~"}{$11=$9; print}' <filename>

If the first file have only one line you can do something like:
awk -v val=$(awk -F\~ '{print $9}' <filename b>) 'BEGIN {FS="~"; OFS="~"}{$11=val; print}' <filename a>

A: Not sure I fully understand. Would this come close?
awk -F~ '!$11 {$11 = $9}1' OFS="~" file
col1~col2~col3~col4~col5~col6~col7~col8~col9~col10~col11~col12~col13
data1~data2~data3~data4~data5~data6~data7~data8~data9~data10~data9~data12~data13


text:
Q: numberOfRowsInSection called but not cellForRowAtIndexPath in MultipleDetailViews sample of apple If you download this sample (ipad): http://developer.apple.com/library/ios/#samplecode/MultipleDetailViews/Introduction/Intro.html
and you set a breakpoint at numberOfRowsInSection and also at cellForRowAtIndexPath and you start in landscape then i have the following question:
First: the app comes twice in numberOfRowsInSection -> "why 2 times? Because there are 2 sections.. oké, but where did they define that there are 2 sections?"
Second: the app comes twice in numberOfRowsInSection and then calls cellForRowAtIndexPath -> no questions here... this is normal
Third: when i change to portrait mode and press the popoverbutton the app calls numberOfRowsInSection 3 times and never called cellForRowAtIndexPath -> "why 3 times? Why dont he call cellForRowAtIndexPath"?
Thanks in advance!

A: From glancing at the code, it looks like there is only one section in the root view controller, and that section has two rows (the comment in tableView:numberofRowsInSection: is wrong).
It's anybody's guess as to why tableView:numberOfRowsInSection: is called multiple times, and tableView:cellForRowAtIndexPath: is not called.  It's up to the internal implementation of the tableview to determine when it needs to call those methods to lay out its content.  And if you implement those methods correctly, it doesn't matter how many times they're called.

redpajama_set_name: RedPajamaStackExchange


text:
Q: align floated article tags evenly regardless of content - WITHOUT CSS grid I originally wanted to do this in grid but due to reasons I have to resort to the possibility of floats...
Does the
 tag work differently with floating? I have 4 blocks that need to be aligned with each other irregardless of content/title length inside them.
See what I mean:

.blog-side {
    padding: 1.5em 0 1.5em;
    border-top: 1px solid #e5e5e5;
    border-bottom: 1px solid #e5e5e5;
    display: table;
}

article[class*="post-"] {
    margin: 0em 1em 1em 0em;
    display: table-cell;
}

.blog-side article {
    width: 48%;
    float: left;
}

.blog-side article:nth-child(even) {
    width: 48%;
    float: right;
}

img {
    height: auto;
    max-width: 100%;
}

                    most popular

Sed mollitia tenetur dolor

                 by Author <time class="entry-date published" datetime="2018-11-27T23:21:34+00:00">November 27, 2018</time><time class="updated" datetime="2019-01-03T18:28:27+00:00">January 3, 2019</time>

                    most popular

io huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrfio huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrfio huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrfio huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrf

                 by Author <time class="entry-date published" datetime="2018-11-27T22:54:11+00:00">November 27, 2018</time><time class="updated" datetime="2019-01-03T18:28:27+00:00">January 3, 2019</time>

                    most popular

io huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrfio huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrf

                 by Author 1 <time class="entry-date published" datetime="2018-11-27T21:48:13+00:00">November 27, 2018</time><time class="updated" datetime="2019-01-03T18:28:28+00:00">January 3, 2019</time>

Provident enim necessitatibus excepturi voluptatum distinctio huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrf

                 by Author <time class="entry-date published" datetime="2018-11-27T21:05:30+00:00">November 27, 2018</time><time class="updated" datetime="2019-01-03T18:29:00+00:00">January 3, 2019</time>

(you need to expand to "full width" to see the result) but the images should always be aligned no matter how much content is in them.
I tried both inline-block and vertical-align middle like a lot of similar questions say. I also did table and table-cell (as attached) too but it didn't work.
Do article tags behave differently? DO they ignore these rules or something?
I can't anything that suggests otherwise...

A: you must use grid. i deleted child
 and added two line css code.

.blog-side {
    padding: 1.5em 0 1.5em;
    border-top: 1px solid #e5e5e5;
    border-bottom: 1px solid #e5e5e5;
    display: table;
}

article[class*="post-"] {
    margin: 0em 1em 1em 0em;
    display: table-cell;
}

.blog-side article {
    width: 48%;
    float: left;
}

.blog-side article:nth-child(even) {
    width: 48%;
    float: right;
}

img {
    height: auto;
    max-width: 100%;
}

/* i added following code only */

section {
  display:grid;
  grid-template-columns:1fr 1fr;

}

                    most popular

Sed mollitia tenetur dolor

                 by Author <time class="entry-date published" datetime="2018-11-27T23:21:34+00:00">November 27, 2018</time><time class="updated" datetime="2019-01-03T18:28:27+00:00">January 3, 2019</time>

                    most popular

io huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrfio huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrfio huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrfio huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrf

                 by Author <time class="entry-date published" datetime="2018-11-27T22:54:11+00:00">November 27, 2018</time><time class="updated" datetime="2019-01-03T18:28:27+00:00">January 3, 2019</time>

                    most popular

io huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrfio huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrf

                 by Author 1 <time class="entry-date published" datetime="2018-11-27T21:48:13+00:00">November 27, 2018</time><time class="updated" datetime="2019-01-03T18:28:28+00:00">January 3, 2019</time>

Provident enim necessitatibus excepturi voluptatum distinctio huhuhuhuh  dggeycgeydgyegdyeg deftdfwyjdtdxfbtyxfbetwyfdx xndtewfbdtewfd bxfeutwbfyt3fntcrf

                 by Author <time class="entry-date published" datetime="2018-11-27T21:05:30+00:00">November 27, 2018</time><time class="updated" datetime="2019-01-03T18:29:00+00:00">January 3, 2019</time>


text:
Q: wordpress: submitted data from a form working only depending on the redirect url I read a lot of posts talking about issues concerning redirection after form submit but I didn't find any that seems to solve my problem.
I create a quiz website with wordpress.
Each single.php template contains a question.
I use a form to post the data (in the database) which are chosen by the user.
I use the action attribute of the form to redirect to the next post (next question). So far everything works properly, data are stored in the database and users are redirected to the next post.
But when I reach the last post I've set a condition to redirect to a specific page. The redirection works nicely but the data of this last question are not submitted in my database...
Here is my code :
<?php $redirect_url = 0;
    if ($currentID !== $nextID):
        // NEXT POST
        $redirect_url = get_permalink($nextID);
    else:
        // SPECIFIC PAGE (END QUIZ)
        $redirect_url = get_permalink(24);
    endif;
?>

<form method="post" action="<?php echo $redirect_url; ?>" id="stat_form" class="hidden">
    <input type="radio" name="choice" id="c1" value="1">
    <input type="radio" name="choice" id="c2" value="2">
    <input type="number" name="replay" id="replay" value="<?php echo strip_tags($_POST['replay']); ?>">
    <input type="number" name="question_id" id="question_id" value="<?php echo $currentID; ?>"/>
    <input type="submit" name="submit_form" value="submit" />
</form>

<?php
// SAVE INFO IN DATABASE
// ---------------------
if ( isset( $_POST["submit_form"] ) ) {
    $table = $wpdb->prefix."stats_questions";
    $question_ID = strip_tags($_POST['question_id']);
    $choice = strip_tags($_POST['choice']);
    $replay = strip_tags($_POST['replay']);
    $wpdb->insert(
        $table, array(
            'question_ID' => (int) $question_ID,
            'choice' => (int) $choice,
            'replay' => (int) $replay,
        )
    );
}
// ---------------------
?>


text:
Q: Google Speech API Deprecated? I've been looking around for a speech recognition API to use in my application. It is not a mobile or web app and instead needs to integrate with cloud speech from native code such as Java, C# or C++.  Looking around the web it appears that Google had an experimental API available in API console but I cannot seem to find it.  I'm wondering if it has been deprecated?  I couldn't find anything from Google confirming this hypothesis.
Any suggestions on where to get high quality cloud speech?

A: You need a TTS api?
here is it, you can read the code and write in your likely language.
https://github.com/hiddentao/google-tts

A: Join the https://groups.google.com/a/chromium.org/forum/?fromgroups#!forum/chromium-dev
Then you can get a API key from console.cloud.google.com after you joined the group.


text:
Q: Not able to update complication in watch OS 4 I have updated my code to latest version.I have an issue regarding update complication in watch OS4.Before updation of the code its working fine.
My mobile app contains two languages english and chinese. User is able to update the app language from the app. When i first launch the watch app the complication show in the same language. but if i update the language from app then the complication language is never updated.
In the previous version of the swift, I had implemented the same functionality and that was working fine.I was using the following code for update the complication icon/text in the pervious version.
 func requestedUpdateDidBegin() {
    let server = CLKComplicationServer.sharedInstance()
    for complication in server.activeComplications! {
        server.reloadTimeline(for: complication)
    }
}

I was manually calling the above function in the previous version code. I don't know how to update the complication in the latest version and also didn't found any solution/tutorial regarding this. Please let me know if any one have any idea about this.


text:
Q: Why is there no way to unbind an HttpApplication event handler out of IHttpModule initialization scope Let's say we want to execute some action only once or a couple of times after web application has started and during a web request.
public class WebApp : HttpApplication
{
    public override void Init()
    {
        base.Init();

        this.BeginRequest += new EventHandler(this.OnFirstBeginRequest);
    }

    private void OnFirstBeginRequest(object sender, EventArgs e)
    {
        // do some action and if everything is OK, unbind this handler,
        // because we need it executed only once at the first web request
        this.BeginRequest -= new EventHandler(this.OnFirstBeginRequest);
    }
}

The following exception will be thrown:

Event handlers can only be bound to
  HttpApplication events during
  IHttpModule initialization.

A: It wouldn't make sense to use event handlers in an HttpApplication instance to execute some code on the first request to your application, because each time a new HttpApplication instance is created it's going to rebind those events and the code in the event handlers will run again.
Multiple HttpApplication instances are created by the ASP.NET worker process. They are pooled for performance purposes, but there can definitely be more than one instance of the HttpApplication servicing requests for your web app.
Here's a pretty good article on the subject.


text:
Q: Can CoreMotion continue to collect data in the background with iOS 11? I've been trying to pull all of the CoreLocation data in the background and have been having trouble. I'm running it with CoreLocation, but every time I put the app into the background, the data stops being collected. I saw a few other posts around this topic, but no definitive answer. Is this possible with the current version of iOS? Is there a limit to what data in CoreMotion can be gathered in the background?
Thanks in advance!


text:
Q: Can not run Redis commands using StackExchangeRedis Hello i am trying to connect to a Redis database  from a ASP NET Core 3.1 application and i keep getting this error when i issue a command.
> 'No connection is active/available to service this operation: SET a; A
> blocking operation was interrupted by a call to
> WSACancelBlockingCall., mc: 1/1/0, mgr: 10 of 10 available,
> clientName: [ClientName], IOCP: (Busy=2,Free=998,Min=8,Max=1000),
> WORKER:

I think it has something to do with the library StackExchangeRedis since until now it worked, up until it stopped working randomly.I have updated to the last version, restarted pc, whatever and nothing.
I can connect to my local redis and issue commands with both the Redis-Cli and using telnet 127.0.0.1 6379 , so that is why i think the culprit is the library.
ConnectionString
localhost:6379,ssl=True,allowAdmin=True,abortConnect=False,defaultDatabase=0

How i use it:
var con=ConnectionMultiplexer.Connect(connectionString); //passes
con.GetDatabase().StringSet("a","a"); //throws

A: If just using it for localhost development purposes you can try disabling ssl : localhost:6379,**ssl=false**,allowAdmin=True,abortConnect=False,defaultDatabase=0


text:
Q: Drupal form template suggestion I'm trying to create a drupal form suggestion using :
function pfe_theme_suggestions_form_alter(array &$suggestions, array $variables) {
    $suggestions[] = 'form__'. $variables['element']['#id'];
}

but after creating the form--user-login-form.html.twig , drupal doesn't take this template in consideration but it always uses form.html.twig.
This is the html comment :
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form' -->
<!-- FILE NAME SUGGESTIONS:
   * form--user-login-form.html.twig
   x form.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/form/form.html.twig' -->

After adding the HOOK_theme() :
function pfe_theme_suggestions_form_alter(array &$suggestions, array $variables) {
   $suggestions[] = 'form__'.$variables['element']['#id']; //form--user-login-form.html.twig
}

function pfe_theme($existing, $type, $theme, $path) {

  return [
    'form__user-login-form' => [
      '#theme' => 'form--user-login-form',
      'render element' => 'form',
    ],
  ];

}

I get this error :

Twig_Error_Loader: Template "themes/pfe/templates/form--user-login-form.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "themes/pfe/templates/form--user-login-form.html.twig" in the Drupal theme registry.). in Twig_Loader_Chain->getCacheKey() (line 43 of /home/marwen/workspace/pfe/themes/pfe/templates/block/block--userlogin.html.twig).

A: Replace "-" with "_" using "str_replace", example:
$suggestions[] = 'form__' . str_replace('-','_', $variables['element']['#id']);


text:
Q: pass a choice value by default to a form before saving it in django so the idea is thrt you can make a user able to create new services after activating is_staff in django admin panel for it's user acccount then he will become a distributor
this is the linked models for the service and the distributor:
models.py
class Distributor(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,null=True, blank=True)
service_ch =[('credit','credit'),('games','games')]
name = models.CharField(max_length=200,null=True,blank=False)
phone = PhoneNumberField(null=True,blank=False)
address = models.CharField(max_length=200,null=True,blank=False)
facebook = models.CharField(max_length=200,null=True,blank=False)
ccp = models.BigIntegerField(null=True,blank=False)
key = models.IntegerField(null=True,blank=False)
def __str__(self):
    return self.name

class Service(models.Model):
type_ch = [('credit','credit'),('game','game')]
currency_ch = [('€','€'),('$','$'),('DZD','DZD'),('Unit','Unit')]
distributor = models.ForeignKey(Distributor,on_delete=models.SET_NULL,null=True,blank=False)
model = models.CharField(choices=type_ch,max_length=20,null=True,blank=False)
name = models.CharField(max_length=200,null=True,blank=False)
price = models.FloatField(default=0.00)
currency = models.CharField(choices=currency_ch,max_length=20,null=True,blank=False)
available = models.FloatField(null=True,blank=False)
image = models.ImageField(default='defser.png')
def __str__(self):
    return self.name

the ServiceForm for creating a new service works fine if i choose the distributor manually
forms.py
class ServiceForm(forms.ModelForm):
class Meta():
    model = Service
    fields = ['distributor','model','name','price','currency','available','image']

def __init__(self, *args, **kwargs):
    super(ServiceForm, self).__init__(*args, **kwargs)
    self.fields['model'].widget.attrs['class'] = 'form-control-account'
    self.fields['name'].widget.attrs['class'] = 'form-control-account'
    self.fields['distributor'].widget.attrs['class'] = 'form-control-account'
    self.fields['price'].widget.attrs['class'] = 'form-control-account'
    self.fields['currency'].widget.attrs['class'] = 'form-control-account'
    self.fields['available'].widget.attrs['class'] = 'form-control-account'

views.py
def service_create(request):
user = request.user
if user.is_staff:
    if request.method == "POST":
        form = ServiceForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request,'Service has been added successfully.')

        return HttpResponseRedirect(reverse('saller'))
else:
    raise PermissionDenied()
form = ServiceForm()
return render(request, 'app/service_form.html', {'form': form})

the problem is the user with the distributor privilege should not be able to choose the distributor,
because now he is able to create services by the name of other distributors,all he has to do is to choose the name of a different distributor which comes as a choice list exposing all the distributors names in the database!!
how do i prevent this and make the form choose the current login distributor as the distributor for that newly created service by default????
is there such a thing or a way around this?

A: If the user must login:
from django.contrib.auth.decorators import login_required

@login_required
def service_create(request):
user = request.user
if request.method == "POST":
    if user.is_staff:
        form = ServiceForm(request.POST, request.FILES)
        if form.is_valid():
           db = form.save(commit=False)
           db.name = request.user
           db.save()
           messages.success(request,'Service has been added successfully.')
           return HttpResponseRedirect(reverse('saller'))
        else:
           error = form.errors.as_data()
           return render(request, 'app/service_form.html', {'form': form, 'error':error,})
     else:
        raise PermissionDenied()
else:
     form = ServiceForm()
     return render(request, 'app/service_form.html', {'form': form})

Form.py:
   you can remove 'name' from fields


text:
Q: How to change rect color on mouse click Python (pygame) I created a window with a width and height of 800 pixels using pygame then drew rectangles with size 32 to make the window a 25x25 grid. What I want to do is change the color of the rectangle I click to change.
My Code:
def createGrid():
    SCREEN_WIDTH = 800
    SCREEN_HEIGHT = 800
    BLOCK_SIZE = 32
    WHITE = (255,255,255)

    pygame.init()
    frame = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("PathFinder")
    frame.fill(WHITE)
    for y in range(SCREEN_HEIGHT):
            for x in range(SCREEN_WIDTH):
                rect = pygame.Rect(x*BLOCK_SIZE, y*BLOCK_SIZE, BLOCK_SIZE - 1, BLOCK_SIZE - 1)
                pygame.draw.rect(frame, (0,250,0), rect)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

A: First you should create list with all rects and they colors.
Next you should draw all rect inside while loop.
And finally you have to use event.MOUSEBUTTONDOWN to get mouse click and compare mouse position with every rect on list and change color on list.
import pygame
import sys

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
BLOCK_SIZE = 32
WHITE = (255,255,255)

pygame.init()

frame = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("PathFinder")

# create list with all rects
all_rects = []
for y in range(0, SCREEN_HEIGHT, BLOCK_SIZE):
    row = []
    for x in range(0, SCREEN_WIDTH, BLOCK_SIZE):
        rect = pygame.Rect(x, y, BLOCK_SIZE-1, BLOCK_SIZE-1)
        row.append([rect, (0, 255, 0)])
    all_rects.append(row)

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # check which rect was clicked and change its color on list
            for row in all_rects:
                for item in row:
                    rect, color = item
                    if rect.collidepoint(event.pos):
                        if color == (0, 255, 0):
                            item[1] = (255, 0, 0)
                        else:
                            item[1] = (0, 255, 0)

    # draw all in every loop

    frame.fill(WHITE)

    for row in all_rects:
        for item in row:
            rect, color = item
            pygame.draw.rect(frame, color, rect)

    pygame.display.flip()

Eventually you could draw all rects before loop and use event to draw new rect on clicked rect. But you still need list with all rects to check which rect was click and what is its color.

A: It depends on what your code is intended to do? This example shows how to paint to the primary display surface but doesn't keep track of which colour is where.
import pygame

white = (255, 255, 255)
red = (255, 0, 0)

size = 32

pygame.init()
s = pygame.display.set_mode((800, 800))
s.fill(white)

# press escape to exit example
while True:
    e = pygame.event.get()
    if pygame.key.get_pressed()[pygame.K_ESCAPE]: break

    x = int(pygame.mouse.get_pos()[0] / size) * size
    y = int(pygame.mouse.get_pos()[1] / size) * size

    if pygame.mouse.get_pressed()[0]:
        pygame.draw.rect(s, red, (x, y, size, size), 0)

    pygame.display.update()
    pygame.time.Clock().tick(60)
pygame.quit()


text:
Q: Using Map multiple times in one command Is there a way to reproduce the effect of
Table[i ** j, {i, list1}, {j, list2}]

using Map instead of Table?  Specifically, I want to write something along the lines of
#2 ** #1 & /@ list2 & /@ list1

but tell Mathematica that the first Map (/@ list2) should map list2 into #1 and the second Map (/@ list1) should map list1 into #2.  In other words, I basically want Mathematica to evaluate the first Map (/@ list2) like this:
temp = {# ** list2[[1]], ..., # ** list2[[-1]]}&

and then evaluate the second Map (/@ list1) and return
temp /@ list1

which should be equivalent to the Table command above.

A: If you insist on using Map, then you can nest it using its explicit form, as
Map[Function[t, Map[t ** # &, list2]], list1]

where you have to use an explicit Function call to avoid the confusion you note.
... but as mentioned by march in the comments, the natural way is to use Outer, as
Outer[NonCommutativeMultiply, list1, list2]

Another clean alternative is to use Tuples and @@@, as
NonCommutativeMultiply @@@ Tuples[{list1, list2}]

as pointed out by belisarius, which will yield a flat list.


text:
Q: My website isn't logging the ips? Here is my code. I'm trying to get it so that every time a person loads my website, that it will save their ip to the txt file. But for some reason that when I load my webpage, then go check ip.txt file, it's a empty txt file and nothing is being saved. How do I fix this.

<?php
    $ip = getenv("REMOTE_ADDR");
    $date = date("d") . " " . date("F") . " " . date("Y");
    $intofile = $ip . "n" . $date;
    $hfile = fopen("ip.txt", "w+");
    fwrite($hfile, $intofile);
    fclose($hfile);
?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
  <link rel="shortcut icon" href="favicon.ico" type="image/vnd.microsoft.icon">
  <link rel="stylesheet" href="stylesheet.css" type="text/css">
  <style type="text/css">

  </style>
  </head>
  <body>
<?php
 $ip=$_SERVER['REMOTE_ADDR'];
 echo "IP: <em>$ip</em>";
?>

<!-- javascript on load page -->
  <script type="text/javascript">
   function autorun()
   {

   }
   if (window.addEventListener) window.addEventListener("load", autorun, false);
   else if (window.attachEvent) window.attachEvent("onload", autorun);
   else window.onload = autorun;
  </script>
  </body>
</html>


text:
Q: Prove that $X^{\phi{(n)}}-[1]$ has exactly $\phi{(n)}$ roots in $\mathbf{Z} / n \mathbf{Z}$. Prove that $X^{\phi{(n)}}-[1]$ has exactly $\phi{(n)}$ roots in $\mathbf{Z} / n \mathbf{Z}$, and they are the elements of $(\mathbf{Z} / n \mathbf{Z})^\times$.
I know that $(\mathbf{Z} / n \mathbf{Z})^\times =\{ [a] \in \mathbf{Z} / n \mathbf{Z} :  \gcd(a,n)=1 \}$, and ...
For any $[a] \in (\mathbf{Z} / n \mathbf{Z})^\times$, then $[a]^{\phi{(n)}}=[1]$.
Can I use any of these two facts to prove this statement.

A: You know that $[a]^{\phi(n)} = [1]$ or equivalently that $[a]$ is a root of $X^{\phi(n)} - [1]$ for any $[a] = (\mathbb{Z}/n\mathbb{Z})^{\times}$. You probably also know that a polynomial of degree $k$ can have at most $k$ distinct roots? If so we are done. We have $X^{\phi(n)} - [1]$ a polynomial of degree $\phi(n)$ and we have found $\phi(n)$ roots. Thus me have all the roots and they are exactly what we are looking for.
CORRECTION: The above works in $\mathbb{Z}/p\mathbb{Z}$ for $p$ a prime, and hence we are in a field. Otherwise we need a different argument. See AWertheim's comment below.


text:
Q: Does wxPython's text widget support custom text decorators? I'm looking for a cross-platform rich text widget that supports non-trivial markup including the following, and I wonder if wxPython's text widget can be extended to do them:

*

*set text background color

*draw lines over and under text

*draw borders around text

*decorate content by overlaying lines and shapes (e.g., filled circles)

*indicate items in a gutter

To give you an idea, look at the middle pane here:

I found wxRichTextCtrl, but I can't tell whether these kinds of decorators are supported of not.
Thanks very much.

A: You can check out the wxPython demo package to see what all it supports. However I can tell you right now that it does not do everything you want. You can probably do what you want by creating a custom widget or just by drawing everything yourself though.
If these are hard requirements, I would recommend checking out another Python GUI toolkit


text:
Q: Install Google Maps 4.7 on Conda Environment I would like to to install the latest Google Maps (Version 4.7 as of today) in a conda environment.
The question is, how to do it in the configuration file (The YAML file) which defines the environment without using the command line
I tried looking for the latest version of Google Maps on conda-forge. Yet it is of the 2.x branch.

A: By looking at the answer for Using Pip to install packages to Anaconda Environment you may do something like:
name: YourName
channels:
  - conda-forge
dependencies:
  - python=3.11
  - numpy
  - scipy
  - pip
  - pip:
    - googlemaps==4.7


text:
Q: How to define a specific version of Office.JS in an addin I developed an Excel add-in that's been in use internally for about a year. Recently the add-in stopped working even though no changes were made to the code. I assume this is related to the new version of the API (1.12), which must have changed something that I was using.
On the documentation I can only find explanations on how to use the CDN, which provides the latest version. How can I determine the exact version I want to use?

EDIT
Based on the documentation here, I'm trying to use Webpack to copy all office.js files from node_modules to the dist directory. I can see that Webpack finds the files, due to the following output:
...
../../../../../../../dist/office/ta-in/outlook_strings.debug.js   15.3 KiB
 [emitted]
...

But the files do not appear on the dist directory. Below is the relevant export from my webpack.config.js:
frontConf = {
  entry: [ './src/js/index.js' ],
  output: {
    path: path.join(__dirname, 'dist'),
    publicPath: '/',
    filename: '[name].js'
  },
  target: 'web',
  resolve: {
    extensions: ['.html', '.js']
  },
  node: {
    fs: 'empty',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: "babel-loader",
      },
      {
        // Loads the javacript into html template provided.
        // Entry point is set below in HtmlWebPackPlugin in Plugins
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            //options: { minimize: true }
          }
        ]
      },
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      },
      {
       test: /\.(png|svg|jpg|gif)$/,
       use: ['file-loader']
      }
    ]
  },

  plugins: [
    new CopyPlugin({
      patterns: [
        {from:'node_modules/@microsoft/office-js/dist',
        to:'/dist/office'}
      ]
    }),
    new HtmlWebPackPlugin({
      template: "./src/html/index.html",
      filename: "./index.html",
      excludeChunks: [ 'server' ]
    })
  ]
}

Any suggestions on how to configure Webpack for this?


text:
Q: Find type, vertex, focus, and directrix of the conic with equation $x^2-2\sqrt {3}xy+3y^2+y=0$
Given the conic section equation
$$x^2-2\sqrt {3}xy+3y^2+y=0$$
determine its type, and find its vertex, focus, and  directrix.

My try :
$$\text{discriminant} = B^2-4AC=12 - 4\cdot 1\cdot 3 = 0$$
since $\text{discriminant}=0$ , the conic section is a parabola.

Now, how can I write the above parabola in standard form so that I can get all needed information?

Thank you

A: Notice that
$$
x^2−2\sqrt3xy+3y^2=(x-\sqrt3y)^2=
4\left(x\cos{\pi\over3}-y\sin{\pi\over3}\right)^2.
$$
The expression inside the last parentheses is the resulting $x$ coordinate when point $(x,y)$ is rotated by $\pi/3$ counterclockwise. Introducing then the rotated coordinates:
$$
X=x\cos{\pi\over3}-y\sin{\pi\over3},
\quad
Y=y\cos{\pi\over3}+x\sin{\pi\over3},
$$
your equation becomes
$$
Y=-8X^2+\sqrt3X,
$$
which is in standard form.
You can then find focus, vertex, and so on, for this parabola and then rotate back by $-\pi/3$ to the original $(x,y)$ coordinate system.


text:
Q: How do I use Powershell to return VM Name, TagName, TagValue in Azure? I'm not very good with parsing and displaying values in hash tables in PowerShell yet.
I want to use command to show the VM name, a specific Tag's name and the value of that tag for that VM.
Something like one of these (even though I know these commands don't work, it's what I'm trying to do):

Get-AzResource -Name SYSTEM* -ResourceType "Microsoft.Compute/virtualMachines" -TagName BuiltBy | Select Name,TagName,TagValue

Name      TagName   TagValue
----      -------   --------
SYSTEM1   BuiltBy   Frank
SYSTEM2   BuiltBy   Frank
SYSTEM3   BuiltBy   Betty
SYSTEM4   BuiltBy   Frank

Get-AzResource -Name SYSTEM* -ResourceType "Microsoft.Compute/virtualMachines" -TagName BuiltBy | Where {$.TagValue -eq 'Betty'} | Select Name,TagName,TagValue

Name      TagName   TagValue
----      -------   --------
SYSTEM3   BuiltBy   Betty

Get-AzResource -Name SYSTEM* -ResourceType "Microsoft.Compute/virtualMachines" -TagName BuiltBy | Where {$.TagValue -ne 'Frank'} | Select Name,TagName,TagValue

Name      TagName   TagValue
----      -------   --------
SYSTEM3   BuiltBy   Betty

A: Below is the PowerShell script for finding VM Name, Tag Name and Tag Value
$vmlist=Get-AzResource -ResourceType 'Microsoft.Compute/virtualmachines'
foreach( $item in $vmlist){ if($item.Tags.Keys -eq 'CreatedDate' -and $item.Name -eq 'shbhost'){

get-azvm -Name $item.Name |select -Property Name,Tags

}}

Output


text:
Q: remove similar dictionary's from list in python I have a list of dictionary's that are similar but not completely identical and I want to keep one of them
example:
my_list = [
{"name" : "A","id" : 2,"value" : 279},
{"name" : "A","id" : 3,"value" : 463},
{"name" : "B","id" : 8,"value" : 508},
{"name" : "A","id" : 2,"value" : 647},
{"name" : "A","id" : 2,"value" : 969},
{"name" : "C","id" : 5,"value" : 384}]

I want to remove the dictionary's that share "name" and "id" but keep the one with higher "value
example of what I want it to be like
my_list = [
{"name" : "A","id" : 3,"value" : 463},
{"name" : "B","id" : 8,"value" : 508},
{"name" : "A","id" : 2,"value" : 969},
{"name" : "C","id" : 5,"value" : 384}]

the values that got removed are
{"name" : "A","id" : 2,"value" : 279},
{"name" : "A","id" : 2,"value" : 647}

because {"name" : "A","id" : 2,"value" : 969} have more "value"
{"name" : "A","id" : 3,"value" : 463} didn't get removed because the "id" is different
how can i do that?
i tried looking at some questions like
How to remove duplicate elements of, list of dictionaries in python

A: Try:
my_list = [
    {"name": "A", "id": 2, "value": 279},
    {"name": "A", "id": 3, "value": 463},
    {"name": "B", "id": 8, "value": 508},
    {"name": "A", "id": 2, "value": 647},
    {"name": "A", "id": 2, "value": 969},
    {"name": "C", "id": 5, "value": 384},
]

out = {}
for d in sorted(my_list, key=lambda k: k["value"]):
    out[(d["name"], d["id"])] = d

print(list(out.values()))

Prints:
[
    {"name": "A", "id": 2, "value": 969},
    {"name": "C", "id": 5, "value": 384},
    {"name": "A", "id": 3, "value": 463},
    {"name": "B", "id": 8, "value": 508},
]

A: import itertools

my_list.sort(key=lambda d: (d["name"], d["id"], -d["value"]))

for _key, group in itertools.groupby(
  my_list,
  key=lambda d: (d["name"], d["id"])
):
  print(next(group))

A: see below
from collections import defaultdict

my_list = [
    {"name": "A", "id": 2, "value": 279},
    {"name": "A", "id": 3, "value": 463},
    {"name": "B", "id": 8, "value": 508},
    {"name": "A", "id": 2, "value": 647},
    {"name": "A", "id": 2, "value": 969},
    {"name": "C", "id": 5, "value": 384}]

data = defaultdict(list)
for entry in my_list:
    data[entry['name'], entry["id"]].append(entry)
new_data = []
for k, v in data.items():
    new_data.append(max(v, key=lambda x: x['value']))
print(new_data)

output
[{'name': 'A', 'id': 2, 'value': 969}, {'name': 'A', 'id': 3, 'value': 463}, {'name': 'B', 'id': 8, 'value': 508}, {'name': 'C', 'id': 5, 'value': 384}]

A: If you don't mind using pandas (a little overkill) you can create a DataFrame, sort by value and then drop duplicates on just name and id.
import pandas as pd

df = pd.DataFrame(my_list)
out_list = (
    df.sort_values("value", ascending=False)
    .drop_duplicates(["name", "id"], keep="first")
    .to_dict(orient="records")
)

Which outputs:
[{'name': 'A', 'id': 2, 'value': 969},
 {'name': 'B', 'id': 8, 'value': 508},
 {'name': 'A', 'id': 3, 'value': 463},
 {'name': 'C', 'id': 5, 'value': 384}]

A: First sort them such that all same (name, id) are adjacent, then from each group take the max value element
from itertools import groupby
from operator import itemgetter
my_list = [
{"name" : "A","id" : 2,"value" : 279},
{"name" : "A","id" : 3,"value" : 463},
{"name" : "B","id" : 8,"value" : 508},
{"name" : "A","id" : 2,"value" : 647},
{"name" : "A","id" : 2,"value" : 969},
{"name" : "C","id" : 5,"value" : 384}]
# sorting priority 1 key is name,priority 2 key is its id
my_list.sort(key=itemgetter('name', 'id'))

# from each name, id group take largest value element
[max(g, key=itemgetter('value')) for _, g in groupby(my_list, itemgetter('name', 'id'))]


text:
Q: Single writer memory visibility guarantee on single processor For the below C++ code
volatile bool keepRunning = true;

void run() {
    while (keepRunning) {
        doSomeWork();
    }
}

void stop() {
    keepRunning = false;
}

suppose one thread executes stop() and multiple threads are executing run()
I believe this kind of construct (one writer, no synchronization primitives) is quite prevalent in embedded systems. Is this guaranteed to work, assuming there's no multiple processors/cores?
Thanks

A: No, memory barriers are not imposed in your code, so the compiler is free to re-order volatile access with non-volatile ones, which might lead to incorrect behavior. 'volatile' has very little to do with multi-threading, for more information look at Arch Robison's blog post.
Also this is irrelevant if this is a single CPU platform or multiple CPU one, if the code is correct, then store-with-release will propagate to other CPUs/threads through cache coherency protocol and all will be fine.

A: Yes, because on a unicore machine there is only one CPU and one CPU-cache.
Another reason: To the CPU, it looks like there is only one thread running. The CPU is obliged to present the application a view of memory which is equivalent to single-threaded execution because the CPU can't even tell that there are multiple threads.


text:
Q: json decode to php variable example needed Hi I have the following field which is saved as a field called attachment.
[
   {
    "name":"ClientFiles\/POL02, Impartiality Policy Statement,Rev0_wg1t36oh.pdf",
    "usrName":"POL02, Impartiality Policy Statement,Rev0.pdf",
    "size":172223,
    "type":"application\/pdf",
    "searchStr":"POL02, Impartiality Policy Statement, Rev0.pdf,!:sStrEnd"
   }
]

Could someone please tell me how I would write a json_decode code in order to save an element from it as a variable.
for example:
$seachStr = json_decode[attachment->"searchStr"]
Thanks.

A: $attachmentArr  = json_decode($attachment,true); // convert the json to php array variable
echo '
', var_dump($attachmentArr), '
';// OUTPUT
$searchStr = $attachmentArr['searchStr'];// Pick the desired element out of the array
echo '
', var_dump($searchStr), '
';// OUTPUT


text:
Q: STM32F0 SPI programming of MAX7219 I am new in the world of embedded software. But I was having normal challenge in blinking LED and SPI bridge communication on STM32F0-Discovery. All this work fine. Now I was planing to go to next level, but for sure I do not really understand some things.
To program I am using STM32Cube for configuration ( 8 Bit datasize, 187,5KBits/s and MSB first) as usual.
For testing I define:
uint8_t display[8] = {0,0x7F,0xFF,0xCC,0xCC,0xCC,0xFF,0xF}; //A

For sending the data, as through the STM32Cube all the initialization is done, I wrote the following code in the while-loop:
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_4, GPIO_PIN_RESET); //here is chip select
trasnmit = HAL_SPI_Transmit_IT(&hspi1, display, 8);
receive = HAL_SPI_Receive_IT(&hspi1, Rxbuff, 8);
//HAL_GPIO_WritePin(GPIOC, GPIO_PIN_4, GPIO_PIN_SET);
HAL_Delay(5);
HAL_GPIO_WritePin(GPIOC,GPIO_PIN_4, GPIO_PIN_SET);

Of course I am getting my CLK on the oscilloscope but no data at the DIN-Pin of the MAX7219 (see: https://www.ebay.de/i/273605021101?chn=ps)
While debugging, I can see that the transmit function is being skipped, what could be the cause? But the return value is always on HAL_OK.
Could somebody help me with a step by step config of the MAX7219 based on STM32, so that I can better understand where my problem is.

A: The code wants to write over SPI using interrupts, does not wait for transmission completion and immediately wants to receive over SPI using interrupts again. That should answer why it does not work.

A: First, try to send data in polling mode (without IRQ) with:
HAL_SPI_Transmit


text:
Q: Does Python have a pre-existing class called 'object'? I am learning to make classes using template codes and one of them is coded with what looks like inheritance syntax:
class KNNLearner(object):
What is the purpose of (object) here?

A: In python everything is an object, an object is an object. You can also create Meta-classes to change some behavior of your objects/object to implement something.
In you case KNNLearner(object)  the (object) permits you to pass the class that you want to KNNLearner to inherit.


text:
Q: For any positive integer $n$, let $f_n:[0,1] \to\mathbb R$ be defined by $f_n(x)=\frac x{nx+1}$ for $x \in [0,1]$. For any positive integer $n$, let $f_n:[0,1] \to\mathbb R$ be defined by $f_n(x)=\frac x{nx+1}$ for $x \in [0,1]$. Then
(a) The sequence $\{f_n(x)\}$ is uniformly converges to $[0,1]$
(b) The sequence $\{f_n'(x)\}$ of derivative of $\{f_n\}$ is uniformly converges
(c) The sequence $\{\int_{0}^1 f_n(x) dx\}$ is convergent
(d) the sequence $\{\int_0^1 f_n'(x) dx\}$ is convergent

A: Hint
I correct only the first question and the other are not very different. First we should determinate the point-wise limit. It's simple to see that the sequence $(f_n)$ is point-wise convergent to the zero function $f$. Now to we should compute
$$\lim_{n\to\infty}\sup_{x\in[0,1]}|f_n(x)-f(x)|$$
so notice that
$$f'_n(x)=\frac{1}{(nx+1)^2}>0$$
so the function $f_n$ is increasing and then
$$\sup_{x\in[0,1]}|f_n(x)-f(x)|=f_n(1)=\frac1{n+1}\xrightarrow{n\to\infty}0$$
so the convergence is uniform.


text:
Q: can i say that $x=y$ if both have the same terms? If I got that,
$$x=\dfrac{y^3+1}{2}\textrm{ and }y=\dfrac{x^3+1}{2}$$
then can I say that $x=y$ ? it looks correct but I'm not sure why.
Thanks.

A: Yes, you can certainly say so (contrary to what others have answered), provided you're interested only in real solutions. Not in general, but in this particular case, I mean.
If this system had a solution $(a,b)$ with $a\ne b$, we would have
$$
2a=b^3+1,\quad 2b=a^3+1
$$
from which we get $2(a-b)=b^3-a^3=(b-a)(b^2+ab+a^2)$ and, since $a\ne b$,
$$
a^2+ab+b^2=-2
$$
that has no real solution, a contradiction.
So the intersections of these curves can also be computed as the solutions of
$$
\begin{cases}
2y=x^3+1\\
y=x
\end{cases}
$$
and the resolvent equation is $x^3-2x+1=0$, which factors as $(x-1)(x^2+x-1)=0$ giving
$$
x=1
\qquad\text{or}\qquad
x=\frac{-1-\sqrt{5}}{2}
\qquad\text{or}\qquad
x=\frac{-1+\sqrt{5}}{2}
$$

More generally, if we have equations $y=f(x)$ and $x=f(y)$, where $f$ is a polynomial, we can certainly write
$$
y-x=f(x)-f(y)
$$
and, since $f(x)-f(y)$, as a polynomial in two variables, is divisible by $x-y$, we have
$$
x=y \qquad\text{or}\qquad \frac{f(x)-f(y)}{x-y}=-1
$$
where the fraction denotes the quotient polynomial.
This can be done unless the equation $y-x=f(x)-f(y)$ is trivial, that is, when $f(x)-f(y)=y-x$ as polynomials. This is exactly the case when $f(z)=k-z$, which is the one mentioned by Hagen von Eltzen.
Of course things are more complicated if non polynomial functions are involved.

A: ![you can solve a system of equation and find the solution(s) . or ,you can put x from 1st relation into 2nd relation ,to find roots then you have x,y .the picture may help you ][2]
or ,you can put x from 1st relation into 2nd relation ,to find roots then you have x,y .the picture may help you .try this

A: No you can't. You have $x=f(y)$ ans $y=f(x)$ for some function $f$. If you had (simpler) $x=10-y$ and $y=10-x$ you could not say $x0y$ either. After all it might be that $x=3$ and $y=7$.
(At least $x$ (and $y$) are fixed points of the iterated function $x\mapsto f(f(x))$.)

A: Rewriting the expression gives:
$$
x=\frac{Y^3+1}{2} \Rightarrow \\
Y = \left\{
\begin{array}{rc}
\sqrt[3]{2x-1} & \mbox{for } x \ge 1/2 \\
-\sqrt[3]{1-2x} & \mbox{for } x < 1/2
\end{array}
\right.
$$
Compare this with
$$
y=\frac{x^3+1}{2}
$$
which should be different in general.

The plot indicates three common points, which have to lie on the identity line.

A: No, you cannot. Solve for $x$ and $y$ for both functions. When doing so, you'll get $y=\sqrt [3]{2x-1}$ which does not equal ${x^3 + 1}\over 2$. And $x=\sqrt [3] {2y-1}$ which does not equal ${y^3 + 1}\over 2$.

A: Yes, you can say this, and this applies more generally to any increasing function:
If $f$ is an increasing function and $f(x)=y$ and $f(y)=x$, then $x=y$.
$\underline{Pf}$ Suppose instead that $x\ne y$, so WLOG we can assume that $x<y$.
$\;\;\;\;$Then $f(x)<f(y)\implies y<x$, which gives a contradiction; so $x=y$.

A: Yes the graphs cut along $ x=y $ with real roots/ intersections.


text:
Q: What is a Command Bus? It seems many implementations of CQRS implement a mechanism  called Command Bus, which is used for subscribing handlers to command.
a) Is Command Bus an implementation of Distributed Command pattern or perhaps a Message Bus pattern?
b) I've also noticed the term Message Bus being used in reference to CQRS. Are Message Bus and Command Bus just different names for the same mechanism or are the two different?
thanks

A: The CommandBus is the MessageBus which you use to send Commands. It implies that there is another implementation of a MessageBus for handling other types of Messages.


text:
Q: How to perform ElasticSearch query on records from only a certain user (Rails Tire gem) I have a Mongoid model which I perform ElasticSearch search queries on. Very standard:
class ActivityLog
  include Mongoid::Document
  include Mongoid::Timestamps
  include Tire::Model::Search
  include Tire::Model::Callbacks

  field :extra, type: Hash

  belongs_to :user, :inverse_of => :activity_logs

  def self.search(params, user)
    tire.search(load: true, page: params[:page], per_page: 5) do
      query { string params[:query], default_operator: "AND" } if params[:query].present?
      sort { by :created_at, "desc" }
    end
  end

I am having a hard time understanding the documentation on how to do more advanced stuff, and currently I'm stuck in how to work into my search query that search should be restricted to ActivityLog objects that belongs to the user only.
Could anyone show me how to work the user._id match requirement into the search query?

A: Working with ElasticSearch, there are 2 parts: mapping and search
So, if you want to search by a field of association table (users table), right. There are many ways, but this one I often use for my project:
Inside the ActivityLog model
  mapping do
    indexes :id, type: 'integer'
    indexes :name, type: 'string', analyzer: 'snowball', boost: 5
    indexes :description, type: 'string', analyzer: 'snowball'
    indexes :description_latin, as: 'description.sanitize', type: 'string', analyzer: 'snowball'
    indexes :user_id, as: 'user.id', type: 'string', index: :not_analyzed
    indexes :user_name, as: 'user.name', type: 'string'
    indexes :created_at, type: 'date'
    indexes :slug, index: :not_analyzed
    indexes :publish, type: 'boolean', index: :not_analyzed
  end

Notify the user_id and user_name, the above definition of mapping method will map the user.id to the user_id, and user.name to user_name.
So now in search method, you can do some similar code like
filter :terms, user_id: params[:search][:user_id]
Hope this help

A: One correction to the above, ElasticSearch has dropped the type string and now uses text.


text:
Q: Defining a header style for acknowledgements (saying no to Chapter*{} !!!) I'm using \documentclass{book} and I have also redefined my \chapter and \part heading styles. However, these styles do not apply to the heading of the Acknowledgements page (the word "Acknowledgements ") or other similar pages. Is there a way to redefine a style so that I can avoid using \chapter*{}. Here is an MWE. Please take a look at the heading of the acknowledgement. I want them to have the same style as the chapter heading excluding the number!
\documentclass[draft]{book}
\usepackage[table]{xcolor}
\usepackage{epigraph}
\usepackage[explicit]{titlesec}
\usepackage{type1cm}

\setlength\epigraphwidth{.6\textwidth}

\titleformat{\chapter}[display]
{\normalfont\Large\rmfamily}
{\sffamily\flushright\fontsize{100}{0}\textbf{\textcolor{black!25}{\thechapter\vskip-10pt}}}{-10pt}
{\flushright\fontsize{25}{0}{#1}\vskip60pt}
\titlespacing*{\chapter}
 {0pt}{-40pt}{0pt}

\titleformat{\part}[display]
  {\normalfont\Large\rmfamily}
  {\sffamily\flushright\fontsize{100}{0}\textbf{\textcolor{black!25}{\thepart\vskip-10pt}}}{-10pt}
  {\flushright\fontsize{25}{0}{#1}\vskip60pt}
\titlespacing*{\part}
  {0pt}{-40pt}{0pt}

\begin{document}

\chapter*{Acknowledgments}
\addcontentsline{toc}{chapter}{Acknowledgments}
Let's acknowledge those who answer this question!

\tableofcontents
\cleardoublepage

\chapter{A Test Chapter Title}

\end{document}

A: You have to use the numberless key from titlesec to format \chapter*. I improved and simplified a little your code, using titlesec's tools. I added the geometry package with option showframe to visualize more precisely the resulting layout.
\documentclass[draft]{book}
\usepackage[table]{xcolor}
\usepackage{epigraph}
\usepackage[explicit]{titlesec}
%\usepackage{fix-cm}
\usepackage{lmodern}
\usepackage[nomarginpar, showframe]{geometry}

\setlength\epigraphwidth{.6\textwidth}

\titleformat{\chapter}[display]
{\filleft}
{\sffamily\fontsize{100}{0}\selectfont\bfseries\color{black!25}\thechapter}{10pt}
{\Huge#1}
\titlespacing*{\chapter}
 {0pt}{-8.6pt}{60pt}

\titleformat{name=\chapter, numberless}[display]
{\filleft}
{}{68.5pt}
{\Huge#1\vskip60pt}
\titlespacing*{name=\chapter, numberless}
 {0pt}{-8.6pt}{-30pt}

\titleformat{\part}[display]
{\filleft}
{\sffamily\fontsize{100}{0}\selectfont\bfseries\color{black!25}\thechapter}{10pt}
{\Huge#1}
\titlespacing*{\part}
 {0pt}{-8.6pt}{60pt}

\begin{document}

\chapter*{Acknowledgments}
\addcontentsline{toc}{chapter}{Acknowledgments}
Let's acknowledge those who answer this question!

\tableofcontents
\cleardoublepage

\chapter{A Test Chapter Title}

Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text.

\end{document}


text:
Q: Unable to get all changed files details using GITLAB API I have 29 changed files in one commit id and when I try to get all the details using below GitLab API then I am not getting all the files.
I am getting only 18 file details.
I tried with per_page=100&page=1 parameter but still not getting all changes.
GET /projects/:id/repository/commits/:sha/diff

A: Considering the GET /projects/:id/repository/commits/:sha/diff API is for getting the diff of a commit, check first locally (using git show --pretty) if you do see  29 or 18 files in the same commit present on your local cloned repo:
git show --compact-summary <SHA1>

If you don't see all the files there (meaning locally, not through GitLab) then some of some files were changed in other commits.


text:
Q: Animating Monte Carlo Method Pi color dots diferently I want to have an animation of my plot of my results of the mc method calculating pi; but having the inner circle dots colored differently than the others. How can I do that?
This is my code so far:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

def punkt_im_quadrat(a,N): #a is length of square, N number of dots
"""generates random point in [0,a)x[0,a)"""
    x = a * np.random.random_sample((N,2))
    return x #[x,y]

def kreis(radius):
    return np.sqrt(radius - x**2)
x = np.linspace(0,1,100)

#create array of N=10 dots
punkte = punkt_im_quadrat(1,10) #a=1, so radius of circle is one

treffer = [i for i in punkte if i[1] <= np.sqrt(1 - i[0]**2)] #dots in circle
treffer = np.array(treffer)

außerhalb = [i for i in punkte if i not in treffer] #dots not in circle
außerhalb = np.array(außerhalb)

pi = 4 * len(treffer) / np.shape(punkte)[0]

fig = plt.figure()
fig, ax = plt.subplots()
ax.plot(x,kreis(1))
ax.set_xlim(0,1)
ax.set_ylim(0,1)
ax.set(title=r"MC Sampling for $\pi$",
      ylabel="y-axis",
      xlabel="x-axis")
#colors = ["r" if [punkte[i][0],punkte[i][1]] in treffer else "b"]
graph, = ax.plot([],[], "ro")

def animate(i):
    graph.set_data((punkte[:i,0],), (punkte[:i,1],))
    return graph,

animation = FuncAnimation(fig, func=animate, frames = range(np.shape(punkte)[0]), interval=20, repeat = False)
plt.show()

As you can see, I have tried to change the colors by using the commented color if statement; but it then says
IndexError: arrays used as indices must be of integer (or boolean) type
I then thought I could do an if statement in the animated-function, to determine where the dot is. But when using graph.set_color it changes all dots color.
I'd be really happy if someone can help me.
Thanks in advance!

A: All the markers in a plot have the same color, so that cannot work. If you want different colors for different points, you need to use scatter()
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation

def punkt_im_quadrat(a,N): #a is length of square, N number of dots
    """generates random point in [0,a)x[0,a)"""
    x = a * np.random.random_sample((N,2))
    return x #[x,y]

def kreis(radius):
    return np.sqrt(radius - x**2)
x = np.linspace(0,1,100)

#create array of N=10 dots
punkte = punkt_im_quadrat(1,10) #a=1, so radius of circle is one

treffer = [i for i in punkte if i[1] <= np.sqrt(1 - i[0]**2)] #dots in circle
treffer = np.array(treffer)

außerhalb = [i for i in punkte if i not in treffer] #dots not in circle
außerhalb = np.array(außerhalb)

colors = np.array(["r" if i[1] <= np.sqrt(1 - i[0]**2) else "b" for i in punkte])

pi = 4 * len(treffer) / np.shape(punkte)[0]

fig, ax = plt.subplots()
ax.plot(x,kreis(1))
ax.set_xlim(0,1)
ax.set_ylim(0,1)
ax.set(title=r"MC Sampling for $\pi$",
      ylabel="y-axis",
      xlabel="x-axis")
graph = ax.scatter([],[], marker='o', s=30)

def animate(i):
    graph.set_offsets(punkte[:i,:])
    graph.set_facecolor(colors[:i])
    return graph,

animation = FuncAnimation(fig, func=animate, frames = range(np.shape(punkte)[0]), interval=20, repeat = False)


text:
Q: "Harrass over X" vs. "harrass for X"

*

*She harassed me for days over mistake.

*They would have teased me for not being brave.

Both prepositions indicate the reason for harrassment. What is the difference in meaning? Can they be used interchangeably?

A: It could come down to personal choice, as the meanings are so close to the point of being interchangeable. But if you want to convey a more subtle meaning, you might use "She harassed me for days over this and that" when you want to express a particular type of exasperation, particularly if the mistake was, in your view, small.
"Over", in this case, expresses something that is absurd or disproportionate for the situation. Conversely, imagine how awkward it would be to hear someone say "The politician was harassed by the press over his misogynistic statements" as opposed to "The politician was harassed by the press for his misogynistic statements". If you used "over", it would sound like the statements were small fries and the harassment was disproportionate to his crime.
If you used "She harassed me for days for saying that.", it would not necessarily imply that the harassment was undeserved - at least not so much in writing. If, when speaking, you put the emphasis on days ("She harassed me for days for saying that") that would convey the same frustration as when you used "over" instead of "for". But if you put the emphasis elsewhere, and used "for", you could leave it up to the listener (or reader) whether the harassment was merited.

A: To see the difference, we need to find an example where they don't both work. "She nagged me over the dirty laundry/*She nagged me for the dirty laundry." Second one doesn't work for me at all because it sounds like the laundry put her up to it.
I'll argue, then, that "over" indicates purpose while for indicates cause. That is, "over" attributes the reason for the action to the subject of the sentence while "for" attributes the reason for the action to the object of the preposition.


text:
Q: How to export JavaFX Projects in JDKj11 When I use JDK 11 to make javafx projects, my code works well and run perfectly but when I try to export this project, happen this error:
(I'M USING IntellIJ IDEA)
Error:Java FX Packager:
BUILD FAILED
C:\Users\rapph\.IdeaIC2018.2\system\compile-server\calculator_51b9fd91\_temp_\build.xml:3: Problem: failed to create task or type javafx:com.sun.javafx.tools.ant:fileset
Cause: The name is undefined.
Action: Check the spelling.
Action: Check that any custom tasks/types have been declared.
Action: Check that any <presetdef>/<macrodef> declarations have taken place.
No types or tasks have been defined in this namespace yet
Total time: 0 seconds


text:
Q: How to run java code from javascript? I have some java class files that I would like to run from javascript. They take in a string and spit out a string. I am trying to figure out the best/easiest way to execute them the class files from javascript so I can get/use its response. So as far as I know now here are my options.

*

*Javascript ajax request to php then maybe exec() the jar

*Javascript ajax request to my class files re implemented as servlet

*Rewriting the class files as javascript and call it a day

1 is not ideal because I don't avoid using php, if I can. 2 sucks cause I don't want to run Apache Tomcat. 3 sucks naturally.
Long story short, I wrote a beautiful implementation of A* in java and I want to use it in a game I wrote in js without rewriting it. What would you do?

A: It isn't possible to run Java through Javascript completely independently without using HTML. However, it isn't impossible.
You will first need to convert your Java game (.JRE file) into an applet. To do that, you might take the public static main void and replace it with an Applet initialization (how to use applets). It might seem tedious, but when you actually do it, it won't be that difficult.
Then, using Javascript's HTML Document Object Model (learn more), you can easily do something like this:
document.write('<embed src="foo.class">');

Also, keep in mind that the <applet> tag is NOT supported in HTML5. Like shown above, you can use the <embed> tag or also the <object> tag.
Sincerely, PD.


text:
Q: Spring Security - java.lang.IllegalArgumentException: You must provide a configuration attribute I was unable to run my grails project suddenly and I'm getting this error. Please see full stacktrace below. How do I solve this error?
boot.SpringApplication              Application startup failed

java.lang.IllegalArgumentException: You must provide a configuration attribute
    at org.springframework.util.Assert.hasText(Assert.java:181)
    at org.springframework.security.access.SecurityConfig.<init>(SecurityConfig.java:40)
    at sun.reflect.GeneratedConstructorAccessor78.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrConstructorNewInstance(ReflectiveInterceptor.java:1076)
    at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:83)
    at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrapNoCoerce.callConstructor(ConstructorSite.java:105)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:247)
    at grails.plugin.springsecurity.ReflectionUtils.buildConfigAttributes(ReflectionUtils.groovy:163)
    at grails.plugin.springsecurity.ReflectionUtils.buildConfigAttributes(ReflectionUtils.groovy)
    at grails.plugin.springsecurity.InterceptedUrl.<init>(InterceptedUrl.groovy:40)
    at grails.plugin.springsecurity.web.access.intercept.AnnotationFilterInvocationDefinition.findActionRoles(AnnotationFilterInvocationDefinition.groovy:470)
    at grails.plugin.springsecurity.web.access.intercept.AnnotationFilterInvocationDefinition.findAnnotations(AnnotationFilterInvocationDefinition.groovy:427)
    at grails.plugin.springsecurity.web.access.intercept.AnnotationFilterInvocationDefinition.findAnnotations(AnnotationFilterInvocationDefinition.groovy)
    at grails.plugin.springsecurity.web.access.intercept.AnnotationFilterInvocationDefinition.findControllerAnnotations(AnnotationFilterInvocationDefinition.groovy:384)
    at grails.plugin.springsecurity.web.access.intercept.AnnotationFilterInvocationDefinition.initialize(AnnotationFilterInvocationDefinition.groovy:225)
    at grails.plugin.springsecurity.web.access.intercept.AnnotationFilterInvocationDefinition$initialize.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:149)
    at grails.plugin.springsecurity.SpringSecurityCoreGrailsPlugin.initializeFromAnnotations(SpringSecurityCoreGrailsPlugin.groovy:770)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166)
    at grails.plugin.springsecurity.SpringSecurityCoreGrailsPlugin.doWithApplicationContext(SpringSecurityCoreGrailsPlugin.groovy:651)
    at org.grails.plugins.DefaultGrailsPlugin.doWithApplicationContext(DefaultGrailsPlugin.java:523)
    at org.grails.plugins.AbstractGrailsPluginManager.doPostProcessing(AbstractGrailsPluginManager.java:224)
    at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy:251)
    at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:883)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:83)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:387)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:374)
    at grails.boot.GrailsApp$run.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at ifs.Application.main(Application.groovy:8)

A: It looks like one of your @Secured annotations has no roles or expressions, e.g.@Secured(''). Search through your controllers and make sure that all of the annotations have correct values.


text:
Q: PHP file download with no changes to the file I am trying to make a file download by using PHP but the file downloaded is a clean mp3 file without tags/metadata and not the one that is on my server.
Here's a detailed explanation:
I have a mp3 file with saved ID3 tags and all information on my server.
I run this code to start the download:
header('Content-Type: application/mp3');
header('Content-Disposition: attachment; filename="file.mp3"');
header('Pragma: no-cache');
readfile("file.mp3");

This starts a file download, but the file that is downloaded loses all its meta data, including any info and album art. Is there a way around this?
For example opening the file url and right clicking -> Save As, downloads it and preserves all the information stored in the file.
How can I prevent the deletion of all the metadata? Thanks for your help

A: Just add these two lines:
ob_end_clean();

flush();

readfile("file.mp3");


text:
Q: Repository Methods vs. Extending IQueryable I have repositories (e.g. ContactRepository, UserRepository and so forth) which encapsulate data access to the domain model.
When I was looking at searching for data, e.g.

*

*finding a contact whose first name
starts with XYZ

*a contact whose birthday is after
1960
(etc),
I started implementing repository methods such as FirstNameStartsWith(string prefix) and YoungerThanBirthYear(int year), basically following the many examples out there.
Then I hit a problem - what if I have to combine multiple searches? Each of my repository search methods, such as above, only return a finite set of actual domain objects. In search for a better way, I started writing extension methods on IQueryable<T>, e.g. this:
public static IQueryable<Contact> FirstNameStartsWith(
               this IQueryable<Contact> contacts, String prefix)
{
    return contacts.Where(
        contact => contact.FirstName.StartsWith(prefix));
}

Now I can do things such as
ContactRepository.GetAll().FirstNameStartsWith("tex").YoungerThanBirthYear(1960);

However, I found myself writing extension methods (and inventing crazy classes such as ContactsQueryableExtensions all over, and I lose the "nice grouping" by having everything in the appropriate repository.
Is this really the way to do it, or is there a better way to achieve the same goal?

A: @Alex - i know this is an old question, but what I would be doing would be letting the Repository do really simple stuff only. This means, get all records for a table or view.
Then, in the SERVICES layer (you are using an n-tiered solution, right? :) ) i would be handling all the 'special' query stuff there.
Ok, example time.
Repository Layer
ContactRepository.cs

public IQueryable<Contact> GetContacts()
{
    return (from q in SqlContext.Contacts
            select q).AsQueryable();
}

Nice and simple. SqlContext is the instance of your EF Context .. which has an Entity on it called Contacts .. which is basically your sql Contacts class.
This means, that method basically is doing: SELECT * FROM CONTACTS ... but it's not hitting the database with that query .. it's only a query right now.
Ok .. next layer.. KICK ... up we go (Inception anyone?)
Services Layer
ContactService.cs

public  ICollection<Contact> FindContacts(string name)
{
    return FindContacts(name, null)
}

public ICollection<Contact> FindContacts(string name, int? year)
{
   IQueryable<Contact> query = _contactRepository.GetContacts();

   if (!string.IsNullOrEmpty(name))
   {
       query = from q in query
               where q.FirstName.StartsWith(name)
               select q;
   }

   if (int.HasValue)
   {
       query = from q in query
               where q.Birthday.Year <= year.Value
               select q);
    }

    return (from q in query
            select q).ToList();
}

Done.
So lets recap. First, we start our with a simple 'Get everything from contacts' query. Now, if we have a name provided, lets add a filter to filter all contacts by name. Next, if we have a year provided, then we filter the birthday by Year. Etc. Finally, we then hit the DB (with this modified query) and see what results we get back.
NOTES:-

*

*I've omitted any Dependency Injection for simplicity. It's more than highly recommended.

*This is all pseduo-code. Untested (against a compiler) but you get the idea ....

Takeaway points

*

*The Services layer handles all the smarts. That is where you decide what data you require.

*The Repository is a simple SELECT * FROM TABLE or a simple INSERT/UPDATE into TABLE.

Good luck :)

A: I realize this is old, but I've been dealing with this same issue lately, and I came to the same conclusion as Chad: with a little discipline, a hybrid of extension methods and repository methods seems to work best.
Some general rules I've been following in my (Entity Framework) application:
Ordering queries
If the method is used only for ordering, I prefer to write extension methods that operate on IQueryable<T> or IOrderedQueryable<T> (to leverage the underlying provider.) e.g.
public static IOrderedQueryable<TermRegistration> ThenByStudentName(
    this IOrderedQueryable<TermRegistration> query)
{
    return query
        .ThenBy(reg => reg.Student.FamilyName)
        .ThenBy(reg => reg.Student.GivenName);
}

Now I can use ThenByStudentName() as needed within my repository class.
Queries returning single instances
If the method involves querying by primitive parameters, it usually requires an ObjectContext and can't be easily made static. These methods I leave on my repository, e.g.
public Student GetById(int id)
{
    // Calls context.ObjectSet<T>().SingleOrDefault(predicate)
    // on my generic EntityRepository<T> class
    return SingleOrDefault(student => student.Active && student.Id == id);
}

However, if the method instead involves querying an EntityObject using its navigation properties, it can usually be made static quite easily, and implemented as an extension method. e.g.
public static TermRegistration GetLatestRegistration(this Student student)
{
    return student.TermRegistrations.AsQueryable()
        .OrderByTerm()
        .FirstOrDefault();
}

Now I can conveniently write someStudent.GetLatestRegistration() without needing a repository instance in the current scope.
Queries returning collections
If the method returns some IEnumerable, ICollection or IList, then I like to make it static if possible, and leave it on the repository even if it uses navigation properties. e.g.
public static IList<TermRegistration> GetByTerm(Term term, bool ordered)
{
    var termReg = term.TermRegistrations;
    return (ordered)
        ? termReg.AsQueryable().OrderByStudentName().ToList()
        : termReg.ToList();
}

This is because my GetAll() methods already live on the repository, and it helps to avoid a cluttered mess of extension methods.
Another reason for not implementing these "collection getters" as extension methods is that they would require more verbose naming to be meaningful, since the return type isn't implied. For example, the last example would become GetTermRegistrationsByTerm(this Term term).
I hope this helps!

A: I have been thinking about this a lot lately, after starting at my current job. I am used to Repositories, they go the full IQueryable path using just bare bones repositories as you suggest.
I feel the repo pattern is sound and does a semi-effective job at describing how you want to work with the data in the application domain. However the issue you are describing definitely occurs. It gets messy, fast, beyond a simple application.
Are there, perhaps, ways to rethink why you are asking for the data in so many ways? If not, I really feel that a hybrid approach is the best way to go. Create repo methods for the stuff you reuse. Stuff that actually it makes sense for. DRY and all that. But those one-offs? Why not take advantage of IQueryable and the sexy things you can do with it?  It is silly, as you said, to create a method for that, but it doesn't mean you don't need the data. DRY doesn't really apply there does it?
It would take discipline to do this well, but I really think it's an appropriate path.

A: Six years later, I am certain @Alex has solved his problem, but after reading the accepted answer I wanted to add my two cents.
The general purpose of extending IQueryable collections in a repository to provide flexibility and empower its consumers to customize data retrieval. What Alex has already done is good work.
The primary role of a service layer is to adhere to the separation of concerns principle and address command logic associated with business function.
In real world applications, query logic often needs no extension beyond the retrieval mechanics provided by the repository itself (ex. value alterations, type conversions).
Consider the two following scenarios:
IQueryable<Vehicle> Vehicles { get; }

// raw data
public static IQueryable<Vehicle> OwnedBy(this IQueryable<Vehicle> query, int ownerId)
{
    return query.Where(v => v.OwnerId == ownerId);
}

// business purpose
public static IQueryable<Vehicle> UsedThisYear(this IQueryable<Vehicle> query)
{
    return query.Where(v => v.LastUsed.Year == DateTime.Now.Year);
}

Both methods are simple query extensions, but however subtle they have different roles. The first is a simple filter, while the second implies business need (ex. maintenance or billing). In a simple application one might implement them both in a repository. In a more idealistic system UsedThisYear is best suited for the service layer (and may even be implemented as a normal instance method) where it may also better facilitate CQRS strategy of separating commands and queries.
Key considerations are (a) the primary purpose of your repository and (b) how much do you like to adhere to CQRS and DDD philosophies.


text:
Q: Why does the limit for $\lim \limits_{x \to 0} x^{-2}(x-3)^3$ not exist? I have been told that the limit of $\lim \limits_{x \to 0} x^{-2}(x-3)^3$ does not exist.
However, it seems to me that after two applications of l'Hôpital, the limit should be $-9$
$$\lim \limits_{x \to 0} {{(x-3)^3}\over{x^2}}$$
$$\lim \limits_{x \to 0} {3{(x-3)^2}\over{2x}}$$
$$\lim \limits_{x \to 0} {6{(x-3)}\over{2}}=-9$$
What am I doing wrong?

A: You are applying L'Hopital's rule to a quotient which is not an indeterminate form, since $\lim_{x\to0}(x-3)^3=-27$.
As a simpler example, consider$$\lim_{x\to0}\frac{x-1}{x-2}.$$I suppose that you agree that this limit is $\frac12$. But if you apply L'Hopital's rule, then you will get $1$.

A: You cannot use L'Hôpital because $(x-3)^3$ doesn't go to 0 as $x\to0$.
In order to use L'Hôpital, you need that both the numerator and denominator go to $0$ or $\infty$ as $x\to0$.
This limit does not exist because the numerator goes to $-27$ and the denominator goes to $0$. Thus, the function is not bounded and the limit does not exist.

A: This is a proper rational function (i.e., a quotient of two polynomials with no common factors), and for these types of functions, finite limits fail to exist wherever they are undefined (i.e., whenever the denominator vanishes). This happens because for these types of rational functions, the numerator approaches a nonzero quantity while the denominator approaches zero at the point where they fail to exist, so that the quotient approaches $\pm\infty$ at such points, the appropriate sign of $\infty$ depending on other factors.
L'hopitals is useful only for calculating indeterminate limits; i.e., when both numerator and denominator approach $0,$ or both approach $\pm\infty,$ like the (improper) rational function $$\frac{x-1}{x-1}$$ near $1,$ for example, where both terms approach $0,$ but L'hopitals is not actually needed here since this is the function that is constantly $1$ everywhere except $1,$ where it is not defined. Thus, the limit at $1$ is obviously $1$. However, L'hopitals is used for cases where such observations are not so obvious; i.e., non-elementary indeterminate limits.


text:
Q: Converting boost::function to std::function I'm updating some of our old code to use C++11 features in place of boost equivalents. However not everything is a simple namespace replacement like unordered containers and smart pointers.
For example boost::function has methods empty() and clear() but std::function does not.
There is an operator() defined for std::function that I've been using to replace empty() references but what should I use to replace clear() references?
I've considered using the std::function assignment operator and assigning nullptr to clear it but I'm worried that might have unintentional side affects of clearing not only the underlying function but rendering the object unusable.
Obviously, the better solution would be default initialization of any reusable member function objects that way there is always a valid callback which can simply be updated with a user provided one but I'm just aiming for a direct replacement of the previous usage right now not a code review.

A:
There is an operator() defined for std::function that I've been using to replace empty()

Do you mean an operator! ?
For empty use that operator to test it in a boolean context:
if (f.empty())

becomes:
if (!f)

Or
if (!f.empty())

becomes:
if (f)

(That also works with boost::function, which also has operator! and operator bool.)
For clear assign nullptr to it, which doesn't render it unusable, it just sets it to a default-constructed state:
f.clear();

becomes
f = nullptr;

Or (thanks to Paul Groke for the suggestion):
f = {};

That's equivalent to:
f = decltype(f){};

but is more efficient, and much easier to type and easier to read!


text:
Q: Why do I get 'does not implement abstract member' warning while using kotlinx.android.parcel.Parcelize? I am getting this error while trying to read the bundle from another fragment where I am sending the NewVehicle object.
Error : Class 'NewVehicle' is not abstract and does not implement abstract member public abstract fun describeContents(): Int defined in android.os.Parcelable
NewVehicle.kt
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize

@Parcelize
data class NewVehicle(
    @SerializedName("av_se")
    val avSe: String,
    .....
    @SerializedName("vh_ob")
    val vhOb: String,
    @SerializedName("zo_in")
    val zoIn: String
):Parcelable{}

A: I got it resolved by adding this in my build.gradle(app) inside the android block.
androidExtensions {
    experimental = true
}

A: In my case I forgot to add apply plugin: 'kotlin-parcelize' in gradle

A: In my case just apply these plugins in this order:
Make sure that you call kotlin-parcelize first then kotlin-kapt
plugins {
    id 'kotlin-parcelize'
    id 'kotlin-kapt'
}

A: Please remove {} after Parcelable.
@Parcelize
data class NewVehicle(
    @SerializedName("av_se")
    val avSe: String,
    .....
    @SerializedName("vh_ob")
    val vhOb: String,
    @SerializedName("zo_in")
   val zoIn: String
): Parcelable


text:
Q: Django Python arrange json into a single node I'm working with a legacy database which has 2 records, the data in each record contain the following values: Name, Email, Company, Phone
These 2 records contain the same data value except the value for Phone which is different.
When I retrieve them in JSON I get the following output:
"results": [
        {
            "Name": "Mack",
            "Email": "Mack@email.com",
            "Company": "Company Name",
            "Phone": "123456789"
        },
        {
            "Name": "Mack",
            "Email": "Mack@email.com",
            "Company": "Company Name",
            "Phone": "1111111"
        }
    ]

My question: As you can see there is some duplicate data in the output above, so is there a way to arrange the JSON output to the following:
"results": [
        {
            "Name": "Mack",
            "Email": "Mack@email.com",
            "Company": "Company Name",
            "Phone": "123456789"
            "Phone 2": "1111111"
        }
    ]

Here is the code for Views.py file:
class DataView(viewsets.ModelViewSet):
    queryset = DataList.objects.all()

    serializer_class = DataSerializer

Here is the code for Serializers.py file:
class DataSerializer(serializers.ModelSerializer):
    data_details = serializers.SerializerMethodField()

    class Meta:
        model = DataList
        fields = 'data_details'

    def get_data_details(self, obj):
        return [{
            'name': obj.name,
            'email': obj.email,
            'company': obj.company,
            'phone': obj.phone,

        }]

Here is the code for models.py file:
class Data(models.Model):
    name = models.CharField(db_column='name', primary_key=True, max_length=50)
    email = models.CharField(db_column='email', max_length=50)
    company = models.CharField(db_column='company', max_length=100)
    phone= models.TextField(db_column='phone')

    class Meta:
        managed = False
        db_table = 'data_table'

Thank you.


text:
Q: how can I make pulseaudio accept connections again In my arch system, only the headphone outputs audio. the notebook speakers are muted.
My first thought was to engage the pavucontrol utility, which gets stuck trying to connect to the pulse server.
with further investigation I narrowed down to these commands that seem reproduce the core problem:
~ $ pulseaudio -k && pulseaudio -D -v
I: [pulseaudio] main.c: Daemon startup successful.
~ $ ps aux |grep pulse
ninrod    7920  0.0  0.0 199388  6904 ?        S<l  11:11   0:00 pulseaudio -D -v
ninrod    7921  0.0  0.0  82768  3556 ?        S    11:11   0:00 /usr/lib/pulse/gconf-helper
ninrod    7945  0.0  0.0  10800  2240 pts/0    S+   11:12   0:00 grep pulse
~ $ pactl info
Connection failure: Connection refused
pa_context_connect() failed: Connection refused
~ $

Seems that my pulse server is not allowing connections from pactl or any external clients.
What can I do to make it behave again?
edit: here's the output of pulseaudio -k && pulseaudio -vvvv:
$ pulseaudio -k && pulseaudio -vvvv
I: [pulseaudio] main.c: setrlimit(RLIMIT_NICE, (31, 31)) failed: Operação não permitida
I: [pulseaudio] main.c: setrlimit(RLIMIT_RTPRIO, (9, 9)) failed: Operação não permitida
D: [pulseaudio] core-rtclock.c: Timer slack is set to 50 us.
D: [pulseaudio] core-util.c: RealtimeKit worked.
I: [pulseaudio] core-util.c: Successfully gained nice level -11.
I: [pulseaudio] main.c: This is PulseAudio 10.0
D: [pulseaudio] main.c: Compilation host: x86_64-unknown-linux-gnu
D: [pulseaudio] main.c: Compilation CFLAGS: -march=x86-64 -mtune=generic -O2 -pipe -fstack-protector-strong -Wall -W -Wextra -Wno-long-long -Wno-overlength-strings -Wuns
afe-loop-optimizations -Wundef -Wformat=2 -Wlogical-op -Wsign-compare -Wformat-security -Wmissing-include-dirs -Wformat-nonliteral -Wpointer-arith -Winit-self -Wdeclarat
ion-after-statement -Wfloat-equal -Wmissing-prototypes -Wredundant-decls -Wmissing-declarations -Wmissing-noreturn -Wshadow -Wendif-labels -Wcast-align -Wstrict-aliasing
 -Wwrite-strings -Wno-unused-parameter -ffast-math -fno-common -fdiagnostics-show-option -fdiagnostics-color=auto
D: [pulseaudio] main.c: Running on host: Linux x86_64 4.11.9-1-ARCH #1 SMP PREEMPT Wed Jul 5 18:23:08 CEST 2017
D: [pulseaudio] main.c: Found 4 CPUs.
I: [pulseaudio] main.c: Page size is 4096 bytes
D: [pulseaudio] main.c: Compiled with Valgrind support: no
D: [pulseaudio] main.c: Running in valgrind mode: no
D: [pulseaudio] main.c: Running in VM: no
D: [pulseaudio] main.c: Optimized build: yes
D: [pulseaudio] main.c: FASTPATH defined, only fast path asserts disabled.
I: [pulseaudio] main.c: Machine ID is 5f605d1f46a347c1b8e8193eb8d378ed.
I: [pulseaudio] main.c: Session ID is c1.
I: [pulseaudio] main.c: Using runtime directory /run/user/1000/pulse.
I: [pulseaudio] main.c: Using state directory /home/ninrod/.config/pulse.
I: [pulseaudio] main.c: Using modules directory /usr/lib/pulse-10.0/modules.
I: [pulseaudio] main.c: Running in system mode: no
I: [pulseaudio] main.c: System supports high resolution timers
D: [pulseaudio] memblock.c: Using shared memfd memory pool with 1024 slots of size 64,0 KB each, total size is 64,0 MB, maximum usable slot size is 65472
I: [pulseaudio] cpu-x86.c: CPU flags: CMOV MMX SSE SSE2 SSE3 SSSE3 SSE4_1 SSE4_2
I: [pulseaudio] svolume_mmx.c: Initialising MMX optimized volume functions.
I: [pulseaudio] remap_mmx.c: Initialising MMX optimized remappers.
I: [pulseaudio] svolume_sse.c: Initialising SSE2 optimized volume functions.
I: [pulseaudio] remap_sse.c: Initialising SSE2 optimized remappers.
I: [pulseaudio] sconv_sse.c: Initialising SSE2 optimized conversions.
I: [pulseaudio] svolume_orc.c: Initialising ORC optimized volume functions.
D: [pulseaudio] database-tdb.c: Opened TDB database '/home/ninrod/.config/pulse/5f605d1f46a347c1b8e8193eb8d378ed-device-volumes.tdb'
I: [pulseaudio] module-device-restore.c: Successfully opened database file '/home/ninrod/.config/pulse/5f605d1f46a347c1b8e8193eb8d378ed-device-volumes'.
I: [pulseaudio] module.c: Loaded "module-device-restore" (index: #0; argument: "").
D: [pulseaudio] database-tdb.c: Opened TDB database '/home/ninrod/.config/pulse/5f605d1f46a347c1b8e8193eb8d378ed-stream-volumes.tdb'
I: [pulseaudio] module-stream-restore.c: Successfully opened database file '/home/ninrod/.config/pulse/5f605d1f46a347c1b8e8193eb8d378ed-stream-volumes'.
D: [pulseaudio] protocol-dbus.c: Interface org.PulseAudio.Ext.StreamRestore1 added for object /org/pulseaudio/stream_restore1
I: [pulseaudio] module.c: Loaded "module-stream-restore" (index: #1; argument: "").
D: [pulseaudio] database-tdb.c: Opened TDB database '/home/ninrod/.config/pulse/5f605d1f46a347c1b8e8193eb8d378ed-card-database.tdb'
I: [pulseaudio] module-card-restore.c: Successfully opened database file '/home/ninrod/.config/pulse/5f605d1f46a347c1b8e8193eb8d378ed-card-database'.
I: [pulseaudio] module.c: Loaded "module-card-restore" (index: #2; argument: "").
I: [pulseaudio] module.c: Loaded "module-augment-properties" (index: #3; argument: "").
I: [pulseaudio] module.c: Loaded "module-switch-on-port-available" (index: #4; argument: "").
D: [pulseaudio] module.c: Checking for existence of '/usr/lib/pulse-10.0/modules/module-udev-detect.so': success
D: [pulseaudio] module-udev-detect.c: /dev/snd/controlC0 is accessible: yes
D: [pulseaudio] module-udev-detect.c: /devices/pci0000:00/0000:00:1f.3/sound/card0 is busy: yes
I: [pulseaudio] module-udev-detect.c: Found 1 cards.
I: [pulseaudio] module.c: Loaded "module-udev-detect" (index: #5; argument: "").
D: [pulseaudio] module.c: Checking for existence of '/usr/lib/pulse-10.0/modules/module-jackdbus-detect.so': failure
D: [pulseaudio] module.c: Checking for existence of '/usr/lib/pulse-10.0/modules/module-bluetooth-policy.so': failure
D: [pulseaudio] module.c: Checking for existence of '/usr/lib/pulse-10.0/modules/module-bluetooth-discover.so': failure
D: [pulseaudio] module.c: Checking for existence of '/usr/lib/pulse-10.0/modules/module-esound-protocol-unix.so': success
I: [pulseaudio] module.c: Loaded "module-esound-protocol-unix" (index: #6; argument: "").
D: [pulseaudio] module.c: Checking for existence of '/usr/lib/pulse-10.0/modules/module-gconf.so': success
I: [pulseaudio] module.c: Loaded "module-gconf" (index: #7; argument: "").
I: [pulseaudio] module-default-device-restore.c: Saved default sink 'auto_null' not existent, not restoring default sink setting.
I: [pulseaudio] module-default-device-restore.c: Saved default source 'auto_null.monitor' not existent, not restoring default source setting.
I: [pulseaudio] module.c: Loaded "module-default-device-restore" (index: #8; argument: "").
I: [pulseaudio] module.c: Loaded "module-rescue-streams" (index: #9; argument: "").
D: [pulseaudio] module-always-sink.c: Autoloading null-sink as no other sinks detected.
I: [pulseaudio] sink.c: Created sink 0 "auto_null" with sample spec s16le 2ch 44100Hz and channel map front-left,front-right
I: [pulseaudio] sink.c:     device.description = "Saída fictícia"
I: [pulseaudio] sink.c:     device.class = "abstract"
I: [pulseaudio] sink.c:     device.icon_name = "audio-card"
D: [pulseaudio] core-subscribe.c: Dropped redundant event due to change event.
I: [pulseaudio] source.c: Created source 0 "auto_null.monitor" with sample spec s16le 2ch 44100Hz and channel map front-left,front-right
I: [pulseaudio] source.c:     device.description = "Monitor of Saída fictícia"
I: [pulseaudio] source.c:     device.class = "monitor"
I: [pulseaudio] source.c:     device.icon_name = "audio-input-microphone"
D: [null-sink] module-null-sink.c: Thread starting up
D: [pulseaudio] module-device-restore.c: Could not set format on sink auto_null
I: [pulseaudio] module.c: Loaded "module-null-sink" (index: #11; argument: "sink_name=auto_null sink_properties='device.description="Saída fictícia"'").
I: [pulseaudio] module.c: Loaded "module-always-sink" (index: #10; argument: "").
I: [pulseaudio] module.c: Loaded "module-intended-roles" (index: #12; argument: "").
D: [pulseaudio] module-suspend-on-idle.c: Sink auto_null becomes idle, timeout in 5 seconds.
I: [pulseaudio] module.c: Loaded "module-suspend-on-idle" (index: #13; argument: "").
D: [pulseaudio] module.c: Checking for existence of '/usr/lib/pulse-10.0/modules/module-console-kit.so': success
I: [pulseaudio] module.c: Loaded "module-console-kit" (index: #14; argument: "").
D: [pulseaudio] module.c: Checking for existence of '/usr/lib/pulse-10.0/modules/module-systemd-login.so': success
I: [pulseaudio] client.c: Created 0 "Login Session c1"
D: [pulseaudio] module-systemd-login.c: Added new session c1
I: [pulseaudio] module.c: Loaded "module-systemd-login" (index: #15; argument: "").
I: [pulseaudio] module.c: Loaded "module-position-event-sounds" (index: #16; argument: "").
D: [pulseaudio] stream-interaction.c: Using role 'phone' as trigger role.
D: [pulseaudio] stream-interaction.c: Using roles 'music' and 'video' as cork roles.
I: [pulseaudio] module.c: Loaded "module-role-cork" (index: #17; argument: "").
I: [pulseaudio] module.c: Loaded "module-filter-heuristics" (index: #18; argument: "").
I: [pulseaudio] module.c: Loaded "module-filter-apply" (index: #19; argument: "").
D: [pulseaudio] dbus-util.c: Successfully connected to D-Bus session bus c86d14444a13fcff6d4aad36596cbfd9 as :1.160
D: [pulseaudio] main.c: Got org.PulseAudio1!
D: [pulseaudio] main.c: Got org.pulseaudio.Server!
I: [pulseaudio] main.c: Daemon startup complete.


text:
Q: What would be the probability distribution to simulate K events randomly assigned to N individuals? I am trying to randomly simulate a population of $N$ individuals among which a predefined number $K$ of them have an outcome. The trick is that I want to assign different probabilities to the individuals such that some are more 'at risk' than the others.
To give an example, let's say that I have $N = 10$ individuals and I know that $K = 4$ of them have the outcome. Besides, let's say that individuals 6 to 10 are twice as likely than the others to have the outcome, which means that a vector of probability would be $(1, 1, 1, 1, 1, 2, 2, 2, 2, 2) / 15$. How do I simulate such populations?
I tried using the R function sample without replacement to draw the indices of individuals having the outcome. However, for some reason, the obtained proportions in the end are not quite right.
Another way to put the problem is that I would like a distribution such as the multinomial one, but for which the count can't be larger than one for each category.
Is there such a distribution?

A: If each individual from the population has a probability $p_i$ to have a certain characteristic, draw the outcome for each of the $N$ individuals and accept the result if exactly $K$ enjoy the outcome. Something like
while(sum(o=(runif(N)<p)!=K){}

A: I think you might want something like this:
set.seed(16)
# we have 4 events, and 10 people of which 5 of them should be twice as likely
# that's the same as having 15 people of which 5 belong to one group and 10 to the other
sample.fun <- function(){sample(1:15, size=4, replace=F)}
samples <- replicate(1e4, sample.fun())

# check whether that worked out ...
sum(colSums(samples < 6)) / (sum(colSums(samples < 6))+sum(colSums(samples >= 6)))
# the proportion of events in individuals 1-5 is 0.3335

We can further check whether the events per individual do make sense
samples <- ifelse(samples==11,6,
                      ifelse(samples==12,7,
                             ifelse(samples==13,8,
                                    ifelse(samples==14,9,
                                           ifelse(samples==15,10,samples)))))
table(samples)
#    1    2    3    4    5    6    7    8    9   10
# 2674 2653 2704 2590 2719 5267 5370 5388 5330 5305

I bet the recode part could be done much better than my inelegant ifelse()-structure.

A: You can do it by computing a randomly variating probability for each individual to have the condition.
n1 = 10 # Number in Group 1
n2 = 10 # Number in Group 2
pop = c(rep(1,n1),rep(2,n2)) # Create a population of 1 and 2
prob = rnorm(length(pop),pop*.33,.2) # For each individual, compute a probability to have the condition
cond = rep(0,length(pop)) # Set conditions to 0
cond[prob>.5]=1 # If prob>0.5: The condition occurs
par(mfrow=c(1,2))
plot(as.factor(pop),prob)
plot(table(pop,cond))

This example gave the output below from which you can see that group 2 has a higher probability of getting the condition and also has visibly more cases. You can change the function for the random variation and the threshold for getting the condition to adjust the simulation to your needs.