text:
Q: How to sinon stub a call to external module in a tested function I am testing a function. That function has a call to an external module which makes my test fail:
element.funcCall();

Where the function looks like this:
function funcCall() {
    external.a.b.c.doSomething();
}

It fails on: undefined is not an object (evaluating 'external.a.b.c.doSomething')
How can I stub or fake this so the call is not really make. I do not need it's functionality for this test.

A: Here's how I do this kind of thing:
var element  = require('element'),
    external = require('external'),
    sinon    = require('sinon'),
    expect   = require('chai').expect;

describe('element.funcCall()', function() {

    before(function() {
        this.doSomethingStub = sinon.stub(external.a.b.c, 'doSomething');
    });

    it('should do something external', function() {
        element.funcCall();
        expect(this.doSomethingStub.called).to.be.true;
    });

    after(function() {
        this.doSomethingStub.restore();
    });

});

A: Here is how I ended up solving this. Since I did not care about that external function being executed, I faked it like so:
var func = function() {};
external =
   { a:
      { b:
         { c:
            {doSomething: func}
          }
       }
   }

...
element.funcCall();
expect.....

This was the internal function call was redirected to en empty function and I could test the rest of the method


text:
Q: Gem::RemoteFetcher::FetchError bad response Unauthorized 401 sidekiqpro github actions Hi every one I have a problem when I executed my ci with github actions I received this problem.
Retrying download gem from https://gems.contribsys.com/ due to error (2/4): Gem::RemoteFetcher::FetchError bad response Unauthorized 401

this is my .yml file to github actions
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:13-alpine
        ports:
          - "5432:5432"
        options:
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        env:
          POSTGRES_DB: rails_test
    env:
      RAILS_ENV: test
      DATABASE_URL: "postgres://rails:password@localhost:5432/rails_test"
      SIDEKIQ_PRO_USER: ${{ secrets.SIDEKIQ_PRO_USER }}
      SIDEKIQ_PRO_PWD:  ${{ secrets.SIDEKIQ_PRO_PWD }}

  lint:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3
      - name: Install Ruby and gems
        uses: ruby/setup-ruby@8f312efe1262fb463d906e9bf040319394c18d3e # v1.92
        with:
          bundler-cache: true
      # Add or replace any other lints here
      - name: Security audit dependencies
        run: bin/bundler-audit --update |
          bundle config gems.contribsys.com ${secrets.SIDEKIQ_PRO_USER}:${ secrets.SIDEKIQ_PRO_PWD }
      - name: Security audit application code
        run: bin/brakeman -q -w2
      - name: Lint Ruby files
        run: bin/rubocop --parallel

in my gemfile I put this
gem 'sidekiq-pro', '~> 5.3', source: 'https://gems.contribsys.com'

For other hands, how I can print my ENV in console of github actions , I am not sure if the variable that I set is filled , any ideas?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update a column in a table using randomly picked unique values from another table Expanding my previous question to restrict it from updating duplicate values.

I have a table1 with columns:

refid
CompanyNumber
AddressID

xyz
230
null

yzf
239
null

I have another table table2 with columns

address Id
company

11223344
231

11223345
230

11223354
239

11223334
239

I would like to fetch a unique ID randomly from Table2 and update the column address ID in table1 on company number = company where Address ID is null?
Also, I will adding new rows in table1 daily, how can I restrict the duplicate address ID from getting fetched from table2?

A: You could do this by creating a trigger for inserting on table1.
Then you select all AddressId's from table2 that are not already set in table1, order them randomly and just pick the first one.
A working example of such a trigger:
CREATE TRIGGER TRIGGER1
BEFORE INSERT ON TABLE1
FOR EACH ROW /* Trigger for each new row inserted into table1 */
BEGIN
SELECT addressId INTO :new.ADDRESSID /* Set AddressId for new row in table1 */ FROM
(
   SELECT table2.addressId FROM table2
   LEFT JOIN table1 ON table1.CompanyNumber = table2.company AND table1.AddressID = table2.addressId
   WHERE table1.AddressID IS NULL /* Not already in table1 */ AND table2.Company = :new.COMPANYNUMBER /* Select all addressIds matching the company number */
   ORDER BY dbms_random.value /* order them randomly */
 ) hits
 WHERE ROWNUM = 1; /*Only pick the first randomly ordered one*/

EXCEPTION
  WHEN no_data_found THEN /* CompanyNumber not in table2 or no unique AddressId left */
     :new.ADDRESSID := NULL;
END;

A: You can use a MERGE statement:
MERGE INTO table1 dst
USING (
  SELECT t1.rid,
         t2.addressID
  FROM   (
           SELECT addressId,
                  company,
                  ROW_NUMBER() OVER (
                    PARTITION BY company ORDER BY DBMS_RANDOM.VALUE()
                  ) AS rn
           FROM   table2 t2
           WHERE  NOT EXISTS (
             SELECT 1
             FROM   table1 t1
             WHERE  t1.companyNumber = t2.company
             AND    t1.addressId = t2.addressId
           )
         ) t2
         INNER JOIN
         (
           SELECT ROWID AS rid,
                  companyNumber,
                  ROW_NUMBER() OVER (
                    PARTITION BY companyNumber ORDER BY DBMS_RANDOM.VALUE()
                  ) AS rn
           FROM   table1
           WHERE  addressId IS NULL
         ) t1
         ON ( t1.companyNumber = t2.company AND t1.rn = t2.rn )
) src
ON ( src.rid = dst.ROWID )
WHEN MATCHED THEN
  UPDATE
  SET addressId = src.addressId;

For your sample data:
CREATE TABLE table1( refid, CompanyNumber, AddressID ) AS
SELECT 'xyz', 230, CAST(null AS NUMBER) FROM DUAL UNION ALL
SELECT 'yzf', 239, null FROM DUAL;

CREATE TABLE table2( addressId, company ) AS
SELECT 11223344, 231 FROM DUAL UNION ALL
SELECT 11223345, 230 FROM DUAL UNION ALL
SELECT 11223354, 239 FROM DUAL UNION ALL
SELECT 11223334, 239 FROM DUAL;

Then after the merge then for each NULL addressId in table1 then a random unmatched addressId from table2 will be set and might (randomly) output:

REFID
COMPANYNUMBER
ADDRESSID

xyz
230
11223345

yzf
239
11223354

db<>fiddle here


text:
Q: How to remove group seperator from text file I have a text file that was created on a windows PC that I'm then opening on a debian machine. I open it in nano and at the bottom it says (Converted from DOS format).
When I grab a single line out of the file and look at it's binary representation using:
head -n1 filename.txt | xxd -b

It shows that two 00001101 characters have been added to the line. I'm trying to remove them with tr like this:
head -n1 filename.txt | tr -d "^]" | xxd -b

but that doesn't seem to be working.
Any idea how I can solve this issue? To create ^] I'm doing shift + ^ then ] do I need to do something else to generate the group separator control character?

A: use dos2unix utility, there are a lot of sed/perl/awk/other solutions if you do a quick search. I would be surprised if this question is not answered a couple of times already on this site.


text:
Q: local account s3 images not rendering in hipchat? I am pasting links to s3 images in hipchat room but they are not getting rendered, any idea why? I have my own AWS account in which i have hosted images in s3?
I think this might be because of access issues. Any ideas are appreciated.


text:
Q: Do commutation relations exist between superfields? To quantize a theory, Klein gordon field for example, commutation relations are stablished. Or anticommuting ones in the fermionic case.
If I have the Wess.Zumino model or the free model:
$$S~=~\int\Phi\Phi^\dagger d^8z.$$
Can I obtain in some way relations (commutation or anticommutation, I don't know) like this:
$$[\Phi(z),\Phi^\dagger(z^\prime) ]~=~?$$


text:
Q: Seg Fault at end Main, GDB output provided Sorry, I'm new to c programming
As the title says, The code runs perfectly till the end of main where it returns 0. It then gives a seg fault with no reason why. Some answers said that maybe I wasnt freeing all that I malloced but I did. So I tried using gdb to figure out why. This was the first time I've ever used it.
This is the output:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7644f1d in ?? () from /lib/x86_64-linux-gnu/libc.so.6
(gdb) bt
#0  0x00007ffff7644f1d in ?? () from /lib/x86_64-linux-gnu/libc.so.6
#1  0x00007ffff76450aa in ?? () from /lib/x86_64-linux-gnu/libc.so.6
#2  0x00007ffff760365b in ?? () from /lib/x86_64-linux-gnu/libc.so.6
#3  0x00007ffff76036f5 in exit () from /lib/x86_64-linux-gnu/libc.so.6
#4  0x00007ffff75eaecc in __libc_start_main ()
   from /lib/x86_64-linux-gnu/libc.so.6
#5  0x0000000000400bc9 in _start ()

My main:
int main(int argc, char *argv[]) {

    if(argv[1] == NULL)
    {
        printf("Please enter the path to the map generating file as an argument.\n");
        exit(0);
    }

    run(getName(), argv[1]);
    return 0;
}

My program is a ncurses program, which i can (I believe I am) succesfully create the screen and then close it. I've checked that all the malloced variables have been freed as well.
Run is in a diffrent c file where I draw the ncurses board.
Any help would be appreciated.

A: It's not sure that gdb will give you the exact location when the corruption really happens. (the backtrace suggests it's a stack-related one)
For this kind of errors, the best tool is Valgrind, run your app with it.
(In my experience memory corruption errors could be tracked down and eliminated within minutes with Valgrind)


text:
Q: Entity framework- Adding entities (and their navigation properties) with shared primary keys This is a simplified version of the problem I am trying to solve:
There are two entities:
Item
ItemID   (PK)
Other simple properties...
WorkItem    (navigation property)
WorkItem
ItemID     (PK)
Other Simple Properties...
Item        (Navigation property)

I need to create an Item, a WorkItem for it and I need to set both the navigation properties so the the two entities can point to each other, before saving.

This I can do:
  Item newItem = Item.CreateItem(0, blah,blah,blah);
  service.AddToItems(newItem);

  WorkItem newWorkItem = new WorkItem();
  service.AddToWorkItems(newWorkItem);

  //set the navigation properties
  newItem.WorkItem = newWorkItem;
  newWorkItem.Item = newItem;

Unfortunately, when it comes to saving, this fails. I believe EF, when trying to set WorkItem's Item association, tries to set WorkItem's primary key.
Can anybody enlighten me as to the correct way to achieve this please?

 Update:

So, I have tried building the model using inheritance. The model builds and validates.
Unfortunately, adding a WCF Data Service for my model and trying to view the service in a browser gives me this:
  ..... <m:message xml:lang="en-US">An error occurred while processing this request.    </m:message>
<m:innererror>
  <m:message>Navigation Properties are not supported on derived entity types. Entity Set 'app_Items' has a instance of type 'tempmodel.app_CostItem', which is an derived entity type and has navigation properties. Please remove all the navigation properties from type 'tempmodel.app_CostItem'.</m:message>
  <m:type>System.InvalidOperationException</m:type>
  <m:stacktrace>   at System.Data.Services.Serializers.SyndicationSerializer.WriteObjectProperties(IExpandedResult expanded, ......

CostItem being another entity, like WorkItem, which derives from Item.

A: Based on the example you gave, I believe you should use inheritance.  The WorkItem entity should inherit from the Item entity.  Then, in your code, you will only need to work with a WorkItem entity and it will have all of the properties of the Item entity as well.  Plus, the WorkItem entity will use the key from the Item entity.

A: I eneded up creating a dummy property in each of my client side partial "sub"-classes:
    private Item _BaseItem;
    [AtomIgnore]
    internal Item BaseItem
        {
        get
            {
            if (_BaseItem != null)
                return _BaseItem;
            else
                return this.Item;
            }
        set
            {
            _BaseItem = value;
            OnPropertyChanged("Item");
            }
        }

Code on the client side uses this BaseItem property to traverse the object graph in reverse. So the code to set up the relationships now looks like this:
 Item newItem = Item.CreateItem(0, blah,blah,blah);
 service.AddToItems(newItem);

 WorkItem newWorkItem = new WorkItem();
 service.AddToWorkItems(newWorkItem);

 //set the navigation properties
 newItem.WorkItem = newWorkItem;
 newWorkItem.**BaseItem** = newItem;

Note, the BaseItem property is declared internal; this is so that the serialiser will not attempt to serialise the property and send it to the server.
[AtomIgnore] is an attribute I created and look for in my handler for DataServiceContext.WritingEntity. The handler strips out properties marked with this attribute before they are sent to the server. This technique doesn't seem to work if the property is a ref type though, hence the use of internal.
Declaring it internal also means it cannot be bound to from XAML, fortunately i only needed to bind to a couple of properties so that work around was straightforward.


text:
Q: Prove inequality$\sum\limits_{n|i+j+k}x_{i}y_{j}z_{k}\le n^2$ Being given an integer $n\ge 2$, and $x_{i},y_{i},z_{i}\in \mathbb{R}$ ($i=1,2,\cdots,n$) such that
$$\sum_{i=1}^{n}(x^3_{i}+y^3_{i}+z^3_{i})=3n$$
show that
$$\sum_{i+j+k=n}x_{i}y_{j}z_{k}\le n^2.$$
I know  $a^3+b^3+c^3\ge 3abc$ if $a+b+c\ge 0$.

A: If you assume $x_i\geq 0$ start with $3x_i y_j z_k \leq x_i^3+ y_j^3+ z_k^3$.
Sum this over the triples $i,j,k$.  You get
$$3 \textrm{LHS}\leq \sum_i x_i^3\sum_{j+k=n-i} 1 + \textrm{sums for }y_i,z_i.$$
The key idea is the combinatorics here: counting how many times the term $x_i^3$ arises.  The conclusion is that
$$3 \textrm{LHS}\leq \sum_i (n-i-1)(x_i^3+ y_i^3+ z_i^3)$$.
Now apply the hypothesis and you should be done.


text:
Q: React + Laravel скачивание файлов Есть АПИ на Laravel, я использую библиотеку Laravel-Excel что бы сгенерировать xls файл, как его правильно отдать клиенту и как сделать на реакте скачивание файла?
На php делаю так:
  $this->makeExcel($logs, ContentLog::getActions(), 'logs.log_by_user_table', 'Logs:_' . $user->name);

Метод makeExcel:
private function makeExcel(Collection $data, array $actions, string $view, string $name)
{
    $excel = App::make('excel');
    $excel->create($name, function ($excel) use ($data, $actions, $view) {
        $excel->sheet('log', function ($sheet) use ($data, $actions, $view) {
            $sheet->loadView($view, ['log' => $data, 'actions' => $actions]);
        });
        $excel->store('xls')
            ->export('xls');
    });
}

Я использую axios для отправки запроса, например так:
static getFile(url, params) {
    return axios({
        method: 'GET',
        url: backendDomen + url,
        responseType: 'blob',
        params: params,
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('token'),
            Accept: 'application/vnd.ms-excel',
        }
    }).then(function (value) {
        console.log(value)
        FileDownload(value.data, 'report.xls')
        return value
    }).catch(function (reason) {
        console.log(reason)
        if (reason.response && reason.response.status === 401) {
            window.location.replace('/auth/login')
        } else {
            console.error(reason)
        }
    })
}

В консоль выводится ошибка
Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)
Хотя в браузере я вижу что приходит

A: Добавляем заголовок в конце
->export('xls', ['Access-Control-Allow-Origin' => '*']);
а на фронте меняем тип
  responseType: 'arraybuffer',


text:
Q: Is this possible with the Sneak Peak? I have gotten the possibility to get my hands on a pair of Google Glasses. Now I am trying to build a simple application with GDK that does the following:

*

*By voice command starts the app (WORKS)

*Search in an API for a question (WORKS)

*Displays the result in Static cards (WORKS)

*Load images from internet on cards (DO NOT WORK)

What does not work, and I am trying to figure out if its possible today is to display the result hits with images that I load from the internet. It seems like it can´t be done right now?
Is there any possibility to add a menu on each of these static cards? to have the possibility to for example navigate to the place in the result.
From what I can see, images can be loaded from the Mirror API, but that is data pushed out to the Google Glasses right? Or are there possibilities for me from inside the GDK to ask the Mirror API for data?
Thank you in advance for your help.
My code where I would like the image to load:
for (int i = 0; i < 10; i++) {
JSONObject advert = adverts.getJSONObject(i);
JSONObject address = advert.getJSONObject("address");
JSONObject companyInfo = advert.getJSONObject("companyInfo");
JSONObject coordinates =
advert.getJSONObject("location").getJSONArray("coordinates").getJSONObject(0);

String companyName = companyInfo.getString("companyName");
String road = address.getString("streetName");

Card card;
card = new Card(activity);

// Here I would like to have images from internet.

card.setText(i+1+". "+companyName);
card.setFootnote("Test");

mCards.add(card);

}

A: You could replicate the card ui using xml and then use LazyList to load them asynchronously. I've tried it and it works great!
The xml I am using is the following. It may be improved but it works. You'll also probably need to add a TextView for the footer since I didn't use it. You can find the metrics for everything here https://mirror-api-playground.appspot.com/assets/css/base_style.css or by inspecting the playground with firebug or similar https://developers.google.com/glass/tools-downloads/playground
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:id="@+id/llImages"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="360px"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:visibility="gone">

    <ImageView
        android:id="@+id/ivImage1"
        android:layout_width="240px"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"
        android:visibility="gone"/>

    <LinearLayout
        android:id="@+id/llSecondaryImages"
        android:orientation="horizontal"
        android:layout_width="240px"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:visibility="gone">

        <ImageView
            android:id="@+id/ivImage2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
            android:visibility="gone"/>

        <ImageView
            android:id="@+id/ivImage3"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
            android:visibility="gone"/>

    </LinearLayout>

</LinearLayout>

<TextView
    android:id="@+id/tvMainText"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="34sp"
    android:layout_toRightOf="@+id/llImages"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignWithParentIfMissing="true"
    android:layout_marginRight="40px"
    android:layout_marginTop="10px"
    android:layout_marginBottom="40px"
    android:layout_marginLeft="30px"
    android:maxLines="5"
    android:singleLine="false"
    android:ellipsize="end"/>

</RelativeLayout>

The only difference is that the main text is not resized depending on its length. I've tried with 3 different libraries but they didn't work as expected, but feel free to improve this if you want. You'll also notice that main text margin-top is set to 10px instead of 40px as playground css. That's because I see some additional margin there when wearing Glass.
Using it from the adapter is like the following. I know it could be improved, but it's just to give you an idea of how to do it ;)
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    View rowView = convertView;

    if(rowView == null)
    {
        LayoutInflater inflater = context.getLayoutInflater();

        rowView = inflater.inflate(R.layout.custom_card, null);

        CustomRowViewHolder viewHolder = new CustomRowViewHolder();
        viewHolder.tvMainText = (TextView) rowView.findViewById(R.id.tvMainText);
        viewHolder.ivImage1 = (ImageView) rowView.findViewById(R.id.ivImage1);
        viewHolder.ivImage2 = (ImageView) rowView.findViewById(R.id.ivImage2);
        viewHolder.ivImage3 = (ImageView) rowView.findViewById(R.id.ivImage3);
        viewHolder.llImages = (LinearLayout) rowView.findViewById(R.id.llImages);
        viewHolder.llSecondaryImages = (LinearLayout) rowView.findViewById(R.id.llSecondaryImages);

        rowView.setTag(viewHolder);
    }

    CustomClass cc = values.get(position);

    CustomRowViewHolder holder = (CustomRowViewHolder) rowView.getTag();

    holder.tvMainText.setText(cc.getDescription());

    if(!cc.getFiveLastPhotos().isEmpty())
    {
        holder.llImages.setVisibility(ImageView.VISIBLE);
        holder.ivImage1.setVisibility(ImageView.VISIBLE);

        ImageLoader.getInstance(context.getApplicationContext()).DisplayImage(cc.getFiveLastPhotos().get(0).getSrcPhoto(), holder.ivImage1, null, ImageLoader.NO_ANIMATION);

        if(cc.getFiveLastPhotos().size()>1)
        {
            holder.llSecondaryImages.setVisibility(ImageView.VISIBLE);
            holder.ivImage2.setVisibility(ImageView.VISIBLE);

            ImageLoader.getInstance(context.getApplicationContext()).DisplayImage(cc.getFiveLastPhotos().get(1).getSrcPhoto(), holder.ivImage2, null, ImageLoader.NO_ANIMATION);

            if(cc.getFiveLastPhotos().size()>2)
            {
                holder.ivImage3.setVisibility(ImageView.VISIBLE);

                ImageLoader.getInstance(context.getApplicationContext()).DisplayImage(cc.getFiveLastPhotos().get(2).getSrcPhoto(), holder.ivImage3, null, ImageLoader.NO_ANIMATION);
            }
            else
            {
                holder.ivImage3.setVisibility(ImageView.GONE);
            }
        }
        else
        {
            holder.ivImage2.setVisibility(ImageView.GONE);
            holder.ivImage3.setVisibility(ImageView.GONE);
            holder.llSecondaryImages.setVisibility(ImageView.GONE);
        }
    }
    else
    {
        holder.llImages.setVisibility(ImageView.GONE);
        holder.ivImage1.setVisibility(ImageView.GONE);
        holder.ivImage2.setVisibility(ImageView.GONE);
        holder.ivImage3.setVisibility(ImageView.GONE);
        holder.llSecondaryImages.setVisibility(ImageView.GONE);
    }

    return rowView;
}

I hope it helps you, and please post any suggestion you may have


text:
Q: How to get two SwiftUI sliders to update to and from a third value which represents the 'single source of truth' for their respective values I am very new to Combine and I am trying to get two SwiftUI sliders to update to and from a third value which represents the 'single source of truth' for their respective values.
Each slider has a range from 0…1 but uses a different function to determine its value. In the example below, if the true value is 0.5, the first slider sets and gets that directly (0.5) while the second slider uses the value squared (0.25).
The example works, but I get the impression that this isn't really the proper way to do it. I get infinite recursion if the guard statements are removed in the Model. Can anyone show me the correct way to do this? Thanks!
Here is the Model:
import SwiftUI

class Model : ObservableObject{

    @Published var trueValue: CGFloat = 0{
        didSet{
            slider1Value = trueValue
            slider2Value = trueValue * trueValue
        }
    }

    @Published var slider1Value: CGFloat = 0{
        didSet{
            guard oldValue != slider1Value else { return }

            trueValue = slider1Value
        }
    }

    @Published var slider2Value: CGFloat = 0{
        didSet{
            guard oldValue != slider2Value else { return }

            trueValue = slider2Value.squareRoot()
        }
    }
}

Here is the ContentView:

struct ContentView: View {
    @EnvironmentObject var model: Model

    var body: some View {
        GeometryReader{ geometry in
            VStack{
                ProportionalSlider(value: self.$model.slider1Value, width: geometry.size.width - 20)
                    .frame(width: geometry.size.width, height: 18)
                ProportionalSlider(value: self.$model.slider2Value, width: geometry.size.width - 20)
                    .frame(width: geometry.size.width, height: 18)
            }
        }
    }
}

And here is the ProportionalSlider:

struct ProportionalSlider: View {
    @Binding var value: CGFloat
    var width: CGFloat

    var body: some View{
        let gesture =  DragGesture(minimumDistance: 0)
            .onChanged({ mouse in
                let clamped = min(self.width, max(0, mouse.location.x))
                self.value = clamped/self.width
            })

        return GeometryReader{ geometry in
            ZStack{
                ZStack(alignment: .leading){
                    Capsule().fill(Color.blue).frame(width: self.width, height: 15)
                       .gesture(gesture)
                    Capsule().fill(Color.red).frame(width: self.value * self.width, height: 15)
                       .gesture(gesture)
                }
            }
        }
    }
}

A: Use one @Published property and one computed property:
class Model: ObservedObject {
    @Published var linearValue: CGFloat = 0

    var quadraticValue: CGFloat {
        get { linearValue * linearValue }
        set { linearValue = sqrt(newValue) }
    }
}

Bind one slider to $model.linearValue and bind the other to $model.quadraticValue.


text:
Q: Using Meteor's Match.Integer pattern with form input I'm learning how to use Meteor and am currently looking at using the check package to validate user input, using the tutorial at: http://meteortips.com/first-meteor-tutorial/methods/.
I'm trying to use the Match.Integer pattern inside a method (addPlayer, say) to ensure data entered into a particular field (passed to the addPlayer method via the initialScore parameter) is a valid integer, which works fine when calling addPlayer through the console. However, when entering data via the form (which calls addPlayer when submitted) this doesn't work properly since the entered data is of the String type.
I was considering applying the Number function to the entered data before using Match.Integer but am thinking this is a bad idea since some non-numerical values would be accepted.
Would it be a good idea to have my own isInteger function, such as:
function isInteger(n) {
  return n == +n && n == (n|0);
}

(from https://stackoverflow.com/a/3885844/3806231, but with === replaced with == to allow form data, of String type, to be checked)
and call this before applying the Number function as described above? For example:
Meteor.methods({

  'addPlayer': function(initialScore) {
    if (isInteger(initialScore)) {
      check(Number(initialScore), Match.Integer);
    }
  }

});

Something like this seems quite long-winded and expensive just to validate an integer. Before using Meteor, I would just call something like the isInteger method, but now I'm using Meteor I want to make use of the available packages to save writing some of this standard validation code myself.
Is there a better way of doing this?


text:
Q: Why do two USB sticks with same boot not boot the same way? I have two USB sticks with 32Gb each, NTFS, one is Sandisk and the other one is OCZ. Both have same bootable record inside (Grub4dos) and some ISOs.
I've tried both on different machines and while Sandisk works on all of them, the OCZ doesn't, only on some machines. On one of these machines, the BIOS labels the Sandisk as USB-FDD (if I remember correctly) and the OCZ as USB-HDD.
Today I used VirtualBox with RAW .vmdk linked to these USBs and again, the Sandisk work as expected but the OCZ worked improperly (see pictures below).
As VirtualBox has the same BIOS on both tests, I realized that there must be some differences between these two drives and I want to know what they could be.
I have checked these drives with driveman and both are labeled as fixed. I went to diskpart and the only difference I saw was that the OCZ has an active partition. I set it to inactive (so it matches with Sandisk), but the problem remains.
I still don't get why they have different behaviors, or to see the differences between both drives (what kind of tools would I need to use?).
Sandisk on Virtualbox working:

Sandisk on virtualbox working, commandline:

OCZ on Virtualbox not working properly:

OCZ on Virtualbox not working properly, commanline:


text:
Q: python geocoder for australian number not working I tried to get the geolocation coordinates of my mobile/cell phone number, I used phonenumbers and geocoder. the number information and carrier info came out good. but the location and region info are blank in the output. When I tried US numbers, they are fine. Is there any limitation of geocoder for cell phone numbers in Australia? If so is there any workaround or other packages available to return a phone's longitude and latitude? Many thanks.
import phonenumbers
from phonenumbers import geocoder, carrier

number = "+6104xxxxxxxx"
my_number = phonenumbers.parse(number, region='AUS')
Carrier = carrier.name_for_number(my_number, 'en')
Region = geocoder.description_for_number(my_number, 'en')
my_location = geocoder.description_for_number(my_number, "en", region='AUS')
print(my_number)
print(my_location)
print(Carrier)
print(Region)

A: please try :
enter code here

import phonenumbers
from num import number
from phonenumbers import geocoder
from phonenumbers import carrier

number = "+6104xxxxxxxx"
my_number = phonenumbers.parse(number, region='AUS')
Carrier = carrier.name_for_number(my_number, 'en')
Region = geocoder.description_for_number(my_number, 'en')
my_location = geocoder.description_for_number(my_number, "en", region='AUS')
print(my_number)
print(my_location)
print(Carrier)
print(Region)


text:
Q: Bamboo stage are disabled during release from Jira I've integrated Jira and Bamboo. And from Jira, I'm releasing the version by choosing "Build and Release" -> With build -> choosing the Plan(which list out the stages).
Problem here is I couldn't able to select the stages for the build.
Below page says that, we can choose the stage for the New build
https://confluence.atlassian.com/jirasoftwarecloud/running-a-bamboo-build-when-releasing-a-version-764478184.html
Note: I'm using Jira v8.5.2
Can anyone please help me on the above issue

A: Stages should be available for selection only if they're manual


text:
Q: how can I check modelview stack depth in OpenGL 1.0 (on Android)? I write a program for Android using OpenGL 1.0. I want to check what is modelview stack depth. I try to use glGetIntegerv, but in GL10 class I can't see GL_MODELVIEW_STACK_DEPTH constant - even though in GL11 class there is one. So, is it possible to check modelview stack depth in OpenGL 1.0 on Android?

A: It is because in GL10 class this constant is called GL_MAX_MODELVIEW_STACK_DEPTH.


text:
Q: Get first k values from HashMap I am trying to get first k values from a hashmap.
I know how to get all values from a hashmap and also how to iterate over all of them. Is there any short way to generate first k values from hashmap
for (Map.Entry<String, Integer> en : hmap.entrySet())
{
        System.out.println("Key = " + en.getKey() + ", Value = " + en.getValue());
}

A: The notion of the first elements is undefined for Map interface. How it was mentioned in comments you can use LinkedHashMap or TreeMap where the first item make sense.
If you just want to get some limit number of map values, you could use stream api with limit:
hmap.entrySet().stream()
    .limit(2)
    .collect(Collectors.toList());


text:
Q: Defining type and value aliases at the same time in scala Here is an example from Scala Cookbook:
package com.alvinalexander.myapp

package object model {

    // field
    val MAGIC_NUM = 42

    // method
    def echo(a: Any) { println(a) }

    // enumeration
    object Margin extends Enumeration {
        type Margin = Value
        val TOP, BOTTOM, LEFT, RIGHT = Value
    }

    // type definition
    type MutableMap[K, V] = scala.collection.mutable.Map[K, V]
    val MutableMap = scala.collection.mutable.Map

}

Aren't these two lines doing the same thing?
    type MutableMap[K, V] = scala.collection.mutable.Map[K, V]
    val MutableMap = scala.collection.mutable.Map

Or, can't I just
import scala.collection.mutable.{Map => MutableMap}

?

A:
Aren't these two lines doing the same thing?

type MutableMap[K, V] = scala.collection.mutable.Map[K, V]
val MutableMap = scala.collection.mutable.Map

They are not. type MutableMap[K, V] = scala.collection.mutable.Map[K, V] is a type alias.
scala> val m: MutableMap[String, Int] = scala.collection.mutable.Map("a" -> 1)
m: MutableMap[String,Int] = Map(a -> 1)

But the following would not work with the type alias alone:
scala> val m: MutableMap[String, Int] = MutableMap("a" -> 1)
<console>:11: error: not found: value MutableMap
       val m: MutableMap[String, Int] = MutableMap("a" -> 1)
                                        ^

val MutableMap = scala.collection.mutable.Map is simply creating a copy of mutable.Map's companion object. That is, it is a value, and not a type. It would also not work by itself:
scala> val m: MutableMap[String, Int] = MutableMap("a" -> 1)
<console>:11: error: not found: type MutableMap
       val m: MutableMap[String, Int] = MutableMap("a" -> 1)
              ^

In short, the difference is that one is for a type, and one a value.
import scala.collection.mutable.{Map => MutableMap} will alias both the type, and the value (companion object). Generally, this is what you would want.


text:
Q: csquotes: Footnotes after Block Quotes with Quotation Marks Pretty often, I come across a situation where I'd like to add a footnote to a block quote in order to comment on the passage quoted.
\documentclass{scrartcl}
\usepackage[english]{babel}
\usepackage{lmodern,csquotes,lipsum}
\begin{document}
\lipsum*[1]
\blockquote{\lipsum*[1]...}\footnote{bla...}
\lipsum*[1]
\blockquote{\lipsum*[1]...\footnote{bla...}}
\lipsum*[1]
\end{document}

As expected, the first arrangement is not going to work. The footnote mark will end up at the beginning of the paragraph following the quote (as \footnote is invoked after the \blockquote is closed). This can be fixed by including \footnote within \blockquote.
But this fix will stop working as soon as we apply certain changes to the appearance of our block quotes. Consider my modifications, which I find more pleasing than the LaTeX defaults. (I've disabled those parts of my modifications that aren't relevant to the problem.)
\documentclass{scrartcl}
\usepackage[english]{babel}
\usepackage{lmodern,csquotes,lipsum}

\renewcommand{\mkblockquote}[4]{\enquote{#1}#2\ifterm{\relax}{#3}#4}

%
%\renewenvironment{quote}
%{\list{}{\itemindent=0em
%         \listparindent=\parindent
%         \leftmargin=\parindent
%         \rightmargin=0em
%         \partopsep=0em
%         \topsep=0em
%         }%
% \item\relax}
%{\endlist}

\begin{document}
\lipsum*[1]
\blockquote{\lipsum*[1]...}\footnote{bla...}
\lipsum*[1]
\end{document}

This style (among other things) retains the quotation marks even for the block quotes. That's what the \mkblockquote line is about. The problem is: how can we can have the footnote mark come after the closing mark, but remain on the same line? I've experiment with things like \nobreak, but, being a layman when it comes to low-level things, to no avail. I've also tried working on the modified \mkblockquote: one might make the footnote an optional argument to \blockquote. But everything I tried still resulted in the footnote mark being pushed into the next paragraph.

Update
karlkoeller suggested using a re-defined \mkcitation for that purpose. This does indeed produce a footnote mark in the proper place, and provides a very elegant interface: \blockquote[footnote text]{quote text}. But it breaks as soon as there is a citation command somewhere in the footnote text -- which will happen quite often ...or, in my case, literally every time. For a simple block quote with no additional remarks in the footnote, I use \blockc(!)quote[123]{xyz}{quote text}, which generates the block quote, the footnote mark, and the citation in the footnote. What I'm after is a way to not only have a citation in the footnote, but additional text, which in turn may include more citations (see the picture, which I updated as well).
\documentclass{scrartcl}
\usepackage[english]{babel}
\usepackage[style=authoryear]{biblatex}
\usepackage{lmodern,csquotes,lipsum}

\renewcommand{\mkblockquote}[4]{\enquote{#1}#2\ifterm{\relax}{#3}#4}
\renewcommand{\mkcitation}[1]{\footnote{#1}}

\begin{document}
\lipsum*[1]
\blockquote[Says \cite[123]{xyz}. See also \cite[123]{xyz}.]{\lipsum*[1]...}
\lipsum*[1]
\end{document}

NB: using the postnote of \blockcquote, as in
\blockcquote[123... footnote text, more citations]{xyz}{quote text}
is not an option. It'll break as well, complaining about nested citation commands.

A: Note that the csquotes package allows to define an optional argument for citations in \blockquote and this one can be defined to be a footnote.
So, you just have to add
\renewcommand{\mkcitation}[1]{\footnote{#1}}

in the preamble
and use
\blockquote[bla...]{\lipsum*[1]...}

instead of
\blockquote{\lipsum*[1]...}\footnote{bla...}

Complete MWE
\documentclass{scrartcl}
\usepackage[english]{babel}
\usepackage{lmodern,csquotes,lipsum}

\renewcommand{\mkblockquote}[4]{\enquote{#1}#2\ifterm{\relax}{#3}#4}
\renewcommand{\mkcitation}[1]{\footnote{#1}}

\begin{document}
\lipsum*[1]
\blockquote[bla...]{\lipsum*[1]...}
\lipsum*[1]
\end{document}

Output

Update
Your issue in the update can be resolved in this way:
replace
\renewcommand{\mkcitation}[1]{\footnote{#1}}

with simply
\renewcommand{\mkcitation}[1]{#1}

and then use
\blockquote[\footnotemark]{\lipsum*[1]...}
\footnotetext{Says \cite[59]{companion}. See also \cite[59]{companion}.}

instead of
\blockquote[Says \cite[123]{xyz}. See also \cite[123]{xyz}.]{\lipsum*[1]...}

In this way, we've separated the \footnotemark from the \footnotetext and the problem doesn't arise.
Complete working MWE
\documentclass{scrartcl}
\usepackage[english]{babel}
\usepackage[style=authoryear]{biblatex}
\usepackage{lmodern,csquotes,lipsum}

\renewcommand{\mkblockquote}[4]{\enquote{#1}#2\ifterm{\relax}{#3}#4}
\renewcommand{\mkcitation}[1]{#1}

\addbibresource{biblatex-examples.bib}

\begin{document}
\lipsum*[1]
\blockquote[\footnotemark]{\lipsum*[1]...}
\footnotetext{Says \cite[59]{companion}. See also \cite[59]{companion}.}
\lipsum*[1]
\end{document}

Output

A: It breaks with nested citations because it sees the right square bracket and thinks that is the end of the manual citation. To avoid that, enter the entire footnote in curly brackets. Then you can simply use \renewcommand{\mkcitation}[1]{\footnote{#1}}
MWE:
\documentclass{scrartcl}
\usepackage[english]{babel}
\usepackage[style=authoryear]{biblatex}
\usepackage{lmodern,csquotes,lipsum}

\addbibresource{biblatex-examples.bib}
\renewcommand{\mkcitation}[1]{\footnote{#1}}

\begin{document}
\lipsum*[1]
\blockquote[{\cite[3]{aksin}. See also \cite[2]{aksin}}]{\lipsum*[1]...}
\lipsum*[1]
\end{document}

output:


text:
Q: How to build Http Request with IP address in Swift?(Moya) Can I build Http Request with ip address?
I try change url string:
    var baseURL: URL {
        return URL.init(string:("http://github.com/apple/swift"))!
    }

to
    var baseURL: URL {
        return URL.init(string:("http://140.82.113.3/apple/swift"))!
    }

But, Network not working :(

A: var baseURL: URL = URL(string: "http://github.com/apple/swift")

try this ?


text:
Q: Socket only accepts one Connection My Python socket chat with multithreading only accepts one connection. If I try to connect a second client it doesn't work. On the client side it seems like everything is okay but if i try to send a second message from client 2 the message doesn't arrive.
import socket
import threading

class TxtSocket:

    def __init__(self, host="127.0.0.1" , port=5555):
        self.host = host
        self.port = port
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((self.host, self.port))
        print("Socket was created")

    def server(self):
        self.s.listen()
        print("Server is listening")
        conn, addr = self.s.accept()
        print(f"{addr} is now connected.")
        while True:
            data = conn.recv(1024).decode("utf8")
            print(data)
            if not data:
                break

if __name__ == "__main__":
    txtsocket = TxtSocket()
    for i in range(0, 26):
        t = threading.Thread(target=txtsocket.server())
        t.start()

# Client
import socket

def Text():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(("127.0.0.1", 5555))
    print("Connected")
    while True:
        message = input("Deine Nachricht: ")
        message = message.encode("utf8")
        s.send(message)
Text()

A: Need couple mods to the server to handle multiple clients.

*

*Need main loop to keep accepting new connections and forking off the processing to a thread

*Create a new thread to handle client connection when socket gets a new connection.

The following server code works with multiple running clients as specified above.
# server
import socket
import threading

class TxtSocket:

    def __init__(self, host="127.0.0.1", port=5555):
        self.host = host
        self.port = port
        self.thread = 0
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.bind((self.host, self.port))
        print("Socket was created")

    def handle(self, conn, addr):
        self.thread += 1
        print(f"Thread-{self.thread} {addr} is now connected")
        while True:
            data = conn.recv(1024)
            if not data:
                break
            print(data.decode("utf8"))
        conn.close()

    def server(self):
        # specify the number of unaccepted connections that the server
        # will allow before refusing new connections.
        self.s.listen(5)
        print(f'Server listening on tcp:{self.host}:{self.port}')
        while True:
            conn, addr = self.s.accept()
            # create new thread to handle the client connection
            t = threading.Thread(target=self.handle, args=(conn, addr))
            t.start()

if __name__ == "__main__":
    txtsocket = TxtSocket()
    txtsocket.server()

Note that Python has a SocketServer module that can make some of this easier with a TCPServer that does much of the work. See server example.

A: you can use thread for close other connections
import socket
from _thread import start_new_thread

server = socket...
first_connection = None

def check_con_isalive():
    try:
        while True:
            first_connection.send(b"\0")
    except Exception:
        print("connnection was closed")
        first_connection.close()

def thread_con(con):
    global first_connection
    if not first_connection:
        first_connection = con
        start_new_thread(check_con_isalive, ())
        ...
    else:
        print("blocking new connections")
        con.close()

if __name__ == '__main__':
    while True:
        con, adr = server.accept()
        start_new_thread(thread_con, (con, ))


text:
Q: Search for data.frame indices according to multiple column criteria - how to speed up for large data sets? I have a large data.frame (50M rows) and need to find indices which match a multiple column criteria.
I made a toy example to illustrate the problem.
I read here that it's faster to search though data.tables than data.frames so I converted data.frame into a data.table object
cases<-c(1,3,5)
women<-c("Julia", "Judith", "Juno", "Jane", "Joanna")
data.df<-data.frame("id" = 1:5, "age" = c(20, 30, 40, 50, 60), "name" = c("Joanna","Joe", "Julia", "Juno", "John"))

library(data.table)
data.dt<-as.data.table(data.df)
setkey(data.dt, "id")

I want the results vector to contain age values of records which pass the multiple column criteria, in this case 20, 40, NA. I search using the for loop (which is probably a silly approach, any tips would be greatly appreciated here)
results<-vector()
for (i in 1:length(cases)){
which_id<-cases[i]
ind<-data.dt[id==which_id & name %in% women, which=TRUE]
if(length(ind)==0){results[i]<-NA}
else{results[i]<-data.dt$age[ind]}
}

This would do on a smaller data set but with 500K records in cases and 50M in data.df it is going to take an excess of 12 hours to run. There must be a simpler way, can anyone give a hint?

A: If I understand correctly, the OP wants to filter his dataset by id first and then to return age if the name is found in women (and NA otherwise).
Below are different data.table approaches which return the expected result
20 40 NA

for the example case. However, performance may vary for the production dataset.
1. Filtering by id, matching on women
setkey(data.dt, id)
data.dt[cases][name %in% women, Age := age][, Age]

Here, integer matching is used as name has been turned into factor by OP's call to data.frame(). (If name is of type character %chin% could have been used).
To make sure NA is returned in case of no matches, an update in place is used which puts NA by default.
Note that Cole's approach data.dt[J(cases)][name %in% women] would only return a  filtered dataset with 2 rows but not the expected result.
2. Filtering by id, joining with women
This is similar to above but uses a join instead of a match:
setkey(data.dt, id)
data.dt[cases][.(women), on = .(name = V1), Age := age][, Age]

3. Joining with women, then joining with cases
This approach selects the rows where name matches women first (by joining), then it right joins with cases so that each case will have its corresponding entry in the result vector:
setkey(data.dt, id)
data.dt[.(women), on = .(name = V1), nomatch = 0L][cases, age]

Discussion
The OP has pointed out that speed is a concern with a production dataset of 500k elements in cases and 50M rows in data.df. Which of above methods is the fastest for the production dataset may also depend on the number of entries in women.
Without proper benchmarking I am reluctant to recommend one of the methods.

A: I assume that you expect ind to be either of length 1 or 0 (meaning that the IDs are all different).
Then, you can use {dplyr} to do that very fast:
library(dplyr)
results2 <- data.df %>%
  slice(match(cases, id)) %>%
  mutate(res = ifelse(name %in% women, age, NA)) %>%
  pull(res)

A: Maybe you can try the following code
(v<-data.df[cases,])$age[match(v$name,women)>0]

or
(v<-data.dt[cases,])$age[match(v$name,women)>0]


text:
Q: SQLSTATE[23000] On non empty column [ANGULAR 5 & NODEJS] I'm using Angular 5 and a NodeJS API (using express).
I'm trying to save some data from a form to my "training" table but I'm getting this error:

code":"ER_BAD_NULL_ERROR","errno":1048,"sqlMessage":"The field
  'denivele_positif' cannot be null
  (null)","sqlState":"23000","index":0,"sql":"Insert into trainings
  values(NULL,20,'00:50:00',NULL,NULL,'2018-01-01',NULL)

I don't know why I get this error because the data are correctly sending, here's what I get with Firefox network debugger in the "Params" tab

Here's my table
I think the problem come from the API so here's my "router.post" function
router.post('/', function(req,res,next) {

Training.addTraining(req.body, function (err, count) {
    if (err) {
        res.json(err);     // Si une requete est fausse on retourne un JSON "satus: false"
    }
    else {
        res.json(
            {status: true}
        );      // Si une requete est vraie on retourne un JSON "satus: true"
    }
});

And my "addTraining" function:
addTraining:function(trainings,callback){
    console.log(trainings);
    return db.query("INSERT INTO `trainings` (`id`, `distance`, `temps`, `denivelePositif`, `deniveleNegatif`, `date`, `userEmail`) VALUES(?, ?, ?, ?, ?, ?, ?)", [trainings.id, trainings.distance, trainings.temps, trainings.denivelePositif, trainings.deniveleNegatif, trainings.date, trainings.userEmail],callback);
},

I did a console.log of my object "trainings" in my "addTraining" function** just before the "Insert into ..." and the "trainings" object contain all my value, so there's a problem with my SQL query (I think)...

Please tell me if you want anything.
Thanks you for your help
Regards,

A: Thanks @Barmar, it was some typos in my "addTraining" function, now it's:
addTraining:function(trainings,callback){
    console.log(trainings);
    return db.query("INSERT INTO `trainings` (`id`, `distance`, `temps`, `denivelePositif`, `deniveleNegatif`, `date`, `userEmail`) VALUES(?, ?, ?, ?, ?, ?, ?)", [trainings.id, trainings.distance, trainings.temps, trainings.denivPositif, trainings.denivNegatif, trainings.date, trainings.emailUser],callback);
},


text:
Q: Input data to a shell script How could I create a shell script with input data ?
Please enter names separated by a blank: John Marry Sanford Saunders
read names

A: AFAI understand you want to use an array:
read -r -a names

Example:
read -r -a names <<< "John Marry Sanford Saunders"
echo "${names[0]}" # John
echo "${names[1]}" # Marry
echo "${names[2]}" # Sanford
echo "${names[3]}" # Saunders


text:
Q: how to integrate powerbi dashboard in ios application swift javascript SDK Integration
how to html file in the asset xcode
Java Script SDk
var models = window["powerbi-client"].models;
var embedConfiguration = {
    type;: "report",
    id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
    embedUrl: 'https://app.powerbi.com/reportEmbed',
    tokenType: models.TokenType.Embed,
    accessToken: 'h4...rf',
    settings: {
            layoutType: models.LayoutType.MobilePortrait
        }
};


text:
Q: How do I create a DCG rule inverse to another in Prolog? I am writing a Commodore BASIC interpreter in Prolog, and I am writing some DCGs to parse it. I have verified the DCGs below to work except for the variable one. My goal is this: for anything which isn't a boolean, integer, float, or a string, it's a variable. However, anything that I give it via phrase just results in no.
bool --> [true].
bool --> [false].
integer --> [1]. % how to match nums?
float --> [0.1].
string --> [Str], {atom_chars(Str, ['"' | Chars]), last(Chars, '"')}.
literal --> bool; integer; float; string.

variable --> \+ literal.

I ran a stack trace like this (with gprolog)
main :- trace, phrase(variable, [bar]).

Looking at this, I cannot figure out why variable fails, given that it fails for each case in literal. I'm guessing that the error is pretty simple, but I'm still stumped, so does anyone who's good at Prolog have an idea of what I'm doing wrong?
| ?- main.
The debugger will first creep -- showing everything (trace)
      1    1  Call: phrase(variable,[bar]) ?
      2    2  Call: variable([bar],_321) ?
      3    3  Call: \+literal([bar],_348) ?
      4    4  Call: literal([bar],_348) ?
      5    5  Call: bool([bar],_348) ?
      5    5  Fail: bool([bar],_348) ?
      5    5  Call: integer([bar],_348) ?
      5    5  Fail: integer([bar],_348) ?
      5    5  Call: float([bar],_348) ?
      5    5  Fail: float([bar],_348) ?
      5    5  Call: string([bar],_348) ?
      6    6  Call: atom_chars(bar,['"'|_418]) ?
      6    6  Fail: atom_chars(bar,['"'|_418]) ?
      5    5  Fail: string([bar],_348) ?
      4    4  Fail: literal([bar],_348) ?
      3    3  Exit: \+literal([bar],_348) ?
      2    2  Exit: variable([bar],[bar]) ?
      1    1  Fail: phrase(variable,[bar]) ?

(2 ms) no
{trace}

A: You can detect a string of integers like this (I've added an argument to collect the digits):
integer([H|T]) --> digit(H), integer(T).
integer([]) -->  [].
digit(0) --> "0".
digit(1) --> "1".
    ...
digit(9) --> "9".

As for variable -- it needs to consume text, so you'd want something similar to integer above, but change digit(H) to something that recognizes a character that's part of a "variable".
If you want further clues (although sometimes using slightly advanced tricks): https://www.swi-prolog.org/pldoc/man?section=basics and the code is here: https://github.com/SWI-Prolog/swipl-devel/blob/master/library/dcg/basics.pl

A: To expand a bit on the other answer, the key problem is that a DCG rule like \+ literal does not consume items from the input. It only checks that the next item, if any, is not a literal.
To actually consume an item, you need to use a list goal, similarly to how you use a goal [1] to consume a 1 element. So:
variable -->
    \+ literal,  % if there is a next element, it's not a literal
    [_Variable]. % consume this next element, which is a variable

For example:
?- phrase(variable, [bar]).
true.

?- phrase((integer, variable, float), [I, bar, F]).
I = 1,
F = 0.1.

Having that singleton variable _Variable is a bit strange -- when you parse like this, you lose the name of the variable. When your parser is expanded a bit, you will want to use arguments to your DCG rules to communicate information out of the rules:
variable(Variable) -->
    \+ literal,
    [Variable].

For example:
?- phrase((integer, variable(Var1), float, variable(Var2)), [I, bar, F, foo]).
Var1 = bar,
Var2 = foo,
I = 1,
F = 0.1.


text:
Q: Handle false return from function. IF vs OR vs Ternary operators etc What's the "best" way to handle FALSE return from function, to call another function? For example I have "$stmt->execute();" from PDO and want to know when query execute failed.
Demo:
function test() {
    return false;
}

function error($err) {
    echo $err;
}

if (!test()) error('a'); // method 1
test() OR error('b'); // method 2
test() || error('c'); // method 3
test() ?: error('d'); // method 4

This will show "abcd". If I change test() return to true then nothing will show up so all 4 methods works. But what is the "best"? If all methods are the same "correct" in programming way, then what is more often used, nicer, modern, maybe more correct for coding standards like PSR? Maybe there is even another better method?

A: In this very simple instance, I think it's really a matter of choice. Because you have just one statement to execute if the test fails, and nothing to do if it passes, everything easily fits on one line.  Anything but the last line is easy to read and probably fine.
In most cases though, the result of the true/false test will lead to more than just one statement.  This binary branching is the whole purpose of the if-else construct, so I tend to use that.
if(test()){
    statement1();
    statement2();
    ...
}else{
    statement3();
    statement4();
    ...
}


text:
Q: The property of the homogeneous function Let $f(x)$ positive-homogeneous convex function ($f(cx)=cf(x)$ for all $c \geq 0$)
$A := \{ x \in \mathbb{R}^n : f(x)\leq 1\}$.
$A^{\circ}$ is polar set for $A$.
How to prove that $A^{\circ} = conv(\partial f(0) \cup \{0\})$?
/************************************************************/
I see that constraint $f(x)\leq 1$ actually can lead to polar set but I have no idea how to prove it.


text:
Q: "Canonical" form for gauge equivalence classes of matrices in $\mathfrak{gl}_n(x)$ Let $\mathfrak{gl}_n(x)= \mathfrak{gl}_n \otimes_\mathbb{C}\mathbb{C}(x)$ be the algebra of matrices taking values in rational functions.

Definition: Two matrices $A, B \in \mathfrak{gl}_n(x)$ are said to be gauge equivalent iff there exists an invertible matrix $P \in
 {GL}_n(\mathbb{C}(x))$ satisfying: $$B=PAP^{-1}+P'P^{-1}$$

The above is easily seen to be an equivalence relation on the matrices in $\mathfrak{gl}_n(x)$.
The classical Jordan decomposition for complex scalar matrices gives a canonical (modulo transposition of blocks) representative for every equivalence class of matrices for the equivalence relation of similarity. My question is basically "is there a similar thing for this case and if there is what is it?".

Question: Can one define a "canonical form" for matrices in $\mathfrak{gl}_n(x)$ modulo gauge equivalence? That is a sensible and computable assignment of a canonical representative matrix for every gauge equivalence class in $\mathfrak{gl}_n(x)$

If the above is some kind of extremely difficult untractable super-problem I'd appreciate an answer which explains why is this the case and additionally:

If the above is hopless can this be done at least for $\mathfrak{gl}_n \otimes_\mathbb{C}\mathbb{C}((x))$? With $P$ above lying in $GL_n(\mathbb{C}((x)))$ of course.

A: For your second question, you may want to look at "Jordan decomposition for a class of singular differential operators" by A. H. M. Levelt, https://projecteuclid.org/download/pdf_1/euclid.afm/1485896417
The only difference with your problem is that he allows gauge transformations by an extension of the Laurent series field.


text:
Q: AES-256 decryption with part of a key This is homework. Our professor encrypted a message with AES-256 in CBC mode (key is 256bits). Then he gave us the IV he used (randomized in my code), the encrypted message and second half of a key (keySuffix), key is in hexadecimal, IV too. We have to use brute-force and decrypt that message. The message is a few blocks of length 8 made of ones and zeroes with spaces in between (cryptogram). What I do is getting rid of the spaces, transforming cryptogram to byteArray (you can see in code how I do that). On the key I just do getBytes(), on IV I use DatatypeConverter.parseHexBinary() otherwise it's throwing an error about wrong IV length. When I get a message i return it as a String by using new String(myByteArray). Then I check if that message has all the normal characters (not some 'bushes').
Point is that I get no results. I have no idea what may be wrong here, my guess is that some conversions are done not the way they were supposed to be. I've been trying some things with unicodes etc., but brute-force takes so long time to complete and testing like this is troublesome. Can someone point my in the right direction, like how to make those conversions. Generating all possible Strings for the other side of the key works fine.
btw. PKCS5Padding is giving an error.
public class Main {
    private String randomized = "21232d0960a7b522d3e25141e54ecee6";
    private String keySuffix = "1dad418a";
    private String cryptogram = "00110001 01111000 01111101 01111100 01100001 11011110 10010010 01011011";
    private byte[] cryptogramBytes;
    private String pattern = "[a-zA-Z1-9\\s]*";
    private IvParameterSpec ivSpec = null;
    private Cipher cipher = null;

    public static void main(String... args){
        char[] elements = { 'a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
        char[] buff = new char[8];
        Main main = new Main ();
        byte[] convertedRandomized = DatatypeConverter.parseHexBinary(main.randomized);
        main.ivSpec = new IvParameterSpec(convertedRandomized);
        main.cryptogram = main.cryptogram.replaceAll("\\s", "");
        BigInteger bigint = new BigInteger(main.cryptogram, 2);
        main.cryptogramBytes = bigint.toByteArray();
        main.cipher = Cipher.getInstance("AES/CBC/NoPadding");
        main.permGen(elements, 0, 8, buff);
    }

    public void permGen(char[] s, int i, int k, char[] buff){
        if (i < k) {
            for (int j = 0; j < s.length; j++) {
                buff[i] = s[j];
                permGen(s, i + 1, k, buff);
            }
        } else {
            String result = decrypt(String.valueOf(buff) + keySuffix);
            if (result.matches(pattern))
                System.out.println("Key is: " + String.valueOf(buff) + keySuffix);
        }
    }

    public String decrypt(String key){
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
        return new String(cipher.doFinal(cryptogramBytes));
    }
}


text:
Q: How to re-run a specific task after its completed using ExecutorService I am trying to create a module that will submit a Callable to ExecutorService and waiting for response. If the callable returns null, this thread will pause itself until resume() is called. Or else it will process the result and resubmit same task again.
public class ScheduleManager implements Runnable {

    private ExecutorService executor = Executors.newSingleThreadExecutor();

    @Override
    public synchronized void run() {
        while (true) {
            Future<Schedule> future = executor.submit(new ScheduleRetriever());

            try {
                Schedule schedule = future.get();

                if (schedule == null) {
                    this.wait();
                } else {
                    //Do something with the schedule
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void resume() {
        this.notifyAll();
    }
}

I managed to come up with above solution but I am not sure if its reliability.
Is there anyway to do this better?


text:
Q: ATMega32, PetitFS, writing measurements to file I'm trying to write measurements from external sensor to the file (lets say 1 per second). I'm using ATMega32 and PetitFS. At this moment I'm able to write one measure:
int main(void){

    BYTE result;
    WORD s1;

    for(;;){
        sprintf(buff, "Measure: %d\r\n", mes);
        s1=4;
        result = pf_write(buff, sizeof(buff), &s1);
        write_close();
    }
}

Now I'm trying to extend above code with pf_lseek to append another measure after previous one. Can someone give me a hint/suggestion how to achieve this?

A: I think you did not post the whole code, as pf_mount and pf_open are also needed to get started.
First of all - just don't close the file, call pf_write again with another sample.
Second - if you want to append to an existing file - open the file with pf_open and then try pf_lseek perhaps with a very high number (UINT32_MAX). I think that it will just set the pointer to the end of the file (check the error code).


text:
Q: SQL - How to join on similar (not exact) columns I have two tables which get updated at almost the exact same time - I need to join on the datetime column.
I've tried this:
SELECT *
FROM A, B
WHERE ABS(DATEDIFF(second, A.Date_Time, B.Date_Time)) = (
    SELECT MIN(ABS(DATEDIFF(second, A.Date_Time, B2.Date_Time)))
    FROM B AS B2
)

But it tells me:

Multiple columns are specified in an aggregated expression containing an outer reference.  If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression.

How can I join these tables?

A: How about something like (assuming SQL 2005+) :
With RankedItems As
    (
    Select A.DateTime As ADateTime, B.DateTime As BDateTime
        , ROW_NUMBER() OVER ( PARTITION BY A.DateTime ORDER BY ABS( DateDiff(s, A.DateTime, B.DateTime) ) ) As ItemRank
    From A
        Cross Join B
    )
Select
From RankedItems
Where ItemRank = 1

In my solution, I'm using a common-table expression or CTE for short. In the CTE, I'm using a ranking function (ROW_NUMBER) which calculates for each row in the CTE expression. The ROW_NUMBER function will return provide a sequential integer for each DateTime value in table A via the PARTITION BY A.DateTime clause ordered by the absolute value of the "closeness" A.DateTime value to the B.DateTime value. Thus, I'm ranking the "closeness" using Abs(DateDiff(s,A.DateTime, B.DateTime) and choosing the highest rank (rank = 1, aka "closest" value) for each A.DateTime value. It will not matter if there is a tie as the ROW_NUMBER() function will return a unique list of numbers for each A.DateTime value.

A: Is this what you want? It will check for 1 second difference
    select * from
A, b --use a join next time
where   A.Date_Time
between DATEADD(s,-1,B.Date_Time) and DATEADD(s,1,B.Date_Time)

A: It might be better to first create a view that contains a column holding your computed datediff, and then construct a query from that.


text:
Q: Permissions confusion - one drive for business I am trying to figure out why I have access to everyone's files within ODFB as the owner and have come to a dead end.
I thought it was because I was a global admin but their are 6 other users who are also global admins.
When a user adds a file to their ODFB or creates a new file they show they are shared with 'Only you' on their computer, however I am also listed as the owner

The user has in no way shared this document with me. so I digged deeper...
It turns out I am the site collection administrator for every user account in the our tenant

We have hundreds of users and I certainly have not gone through one by one adding myself as the site collection administrator.
Is it because I am named as a site collection administrator for my.sharepoint.com? but if that was the case wouldn't company administrator also be listed as an owner on every users files in ODFB.

A: This should not happen, even if you are a site collection admin you should not be able to view other people's files unless they shared it with you.
ODFB is hosted in o365, so if you are an owner of the site where they drop their files to, definitely you have access for all site contents and this is what is happening in your case.
If users drops files in their o365 drive, you should not be able to view it.


text:
Q: How to pull user roles from database when wiring up OAUTH for ASP.NET Identity 2.0? I'm working on some Web APIs, and have been tasked with adding role based authorization to some of the endpoints using ASP.NET Identity 2.0.
I have created an API based administration structure for managing users and roles, and have hit a sticking point when attempting to implement authorization/authentication using OAUTH Bearer tokens.
(NOTE I read that JWT is better to use and makes supplying user data simpler, but the ask is for vanilla OAUTH)
So as for the code here is what I have so far, including the sticking point:
Startup.cs:
private static void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
    // Configure the db context, user manager and role manager to use a single instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

    // Create the options for the token authorization
    var oauthAuthorizationServerOptions = new OAuthAuthorizationServerOptions
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1),
        Provider = new SimpleAuthorizationServerProvider()
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(oauthAuthorizationServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

SimpleAuthorizationServerProvider.cs:
public sealed class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // We are not validating clients at this point, simply "resource owners" i.e. user / pass combos
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        using (var repo = new AuthorizationRepository())
        {
            var user = repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");

                return;
            }
        }

        // How do you pull the user data (including roles) from the database here, and place into a claim for API consumption??
    }
}

What I've found online is the following, but this only creates a default role for the user (or list of roles):
var identity = new ClaimsIdentity(context.Options.AuthenticationType);

identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
identity.AddClaim(new Claim("sub", context.UserName));

context.Validated(identity);

The above code is a problem because it will validate the user, but then assign EVERY user the role of admin in the generated token!
Any help would be appreciated and thank you for your help!

A: The issue is that you are not setting the claims up from the ApplicationUserManager, which can do a lot of the heavy lifting for you.  Further, you're just setting up a generic ClaimsIdentity which, as you already pointed out, will always return the same set of roles for all users.
In GrantResourceOwnerCredentials(), what you want to do is:
//
// Get an instance of the ApplicationUserManager that you've already registered
// with OWIN
//
var mgr = context.OwinContext.GetUserManager<ApplicationUserManager>();

//
// Have the ApplicationUserManager build your ClaimsIdentity instead
//
var identity = await mgr.CreateIdentityAsync(user,
                                             context.Options.AuthenticationType);

//
// Then here, you could add other application-specific claims if you wanted to.


text:
Q: Как изменить шрифт Listview? Всем привет! Второй день подряд пытаюсь найти место в коде для заученной уже наизусть комбинации команд:
TextView textView = (TextView) view.findViewById(R.id.menu_prop);
Typeface font = Typeface.createFromAsset(getAssets(), "segoe_print.ttf");
textView.setTypeface(font);

Итак, есть простой xml-файл для меню с ListView menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       ...
    <LinearLayout android:id="@+id/menu_top"
       ...
       </LinearLayout>
<ListView
          android:id="@+id/ListView_Menu"
          ...>
</ListView>
</LinearLayout>

Есть файл под Items и стрелочку в конце каждого пункта меню menu_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    ...
 <LinearLayout
    ...
    <TextView
android:id="@+id/menu_prop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="test string"/>
    </LinearLayout>
 <LinearLayout
    ...
    <ImageView
        android:id="@+id/imgArrow"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"/>
    </LinearLayout>
</LinearLayout>

Есть java-файл для меню Main_menu.java:
public class Main_menu extends Activity {
    private ListView menuList;
    @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);
        Calculator calc_data[] = new Calculator[]
                {   new Calculator("К1", R.drawable.arrow),
                    new Calculator("К2", R.drawable.arrow),
                    new Calculator("К3", R.drawable.arrow),
                    new Calculator("К4", R.drawable.arrow)
                };
        CustomAdapter adapter = new CustomAdapter(this, R.layout.menu_item, calc_data);
        menuList = (ListView)findViewById(R.id.ListView_Menu);
        menuList.setAdapter(adapter);
}}

Есть файл с адаптером CustomAdapter.java:
public class CustomAdapter extends ArrayAdapter<Calculator> {
    Context context;
    int layoutResourceId;
    Calculator data[] = null;
    public CustomAdapter(Context context, int layoutResourceId, Calculator[] data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        CalculatorHolder holder = null;
        if(view == null)
        {LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            view = inflater.inflate(layoutResourceId, parent, false);
            holder = new CalculatorHolder();
            holder.txtTitle = (TextView)view.findViewById(R.id.menu_prop);
            holder.imgIcon = (ImageView)view.findViewById(R.id.imgArrow);
            view.setTag(holder);        }
        else
        {holder = (CalculatorHolder)view.getTag();        }
        Calculator calculator = data[position];
        holder.txtTitle.setText(calculator.title);
        holder.imgIcon.setImageResource(calculator.icon);
        return view;    }
        static class CalculatorHolder
    {   ImageView imgIcon;
        TextView txtTitle;
    }
}

И есть еще какой-то вспомогательный адаптер - я пока не разобрался, как он работает )) Calculator.java:
public class Calculator {
    public String title;
    public int icon;
    public Calculator(){
        super();
    }
    public Calculator(String title, int icon) {
        super();
        this.title = title;
        this.icon = icon;
    }
}

Теперь вопрос - как мне изменить шрифт у элементов меню ListView? Пробовал в разные места файла CustomAdapter вставлять строку
    Typeface font = Typeface.createFromAsset(getAssets(), null);
но каждый раз приложение вылетает. Именно из-за этой строки. Без нее все работает.
Ответ дан, он помог, тему можно закрывать. Спасибо за помощь!
A: Использовать свои кастомные элементы.
Не так давно писал статью, как юзать кастомные шрифты.
Вот пример своего кастомного элемента:
public class TextViewPlus extends TextView {
//    private static final String TAG = "TextView";

    public TextViewPlus(Context context) {
        super(context);
    }

    public TextViewPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        setCustomFont(context, attrs);
    }

    public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setCustomFont(context, attrs);
    }

    private void setCustomFont(Context ctx, AttributeSet attrs) {
        TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
        String customFont = a.getString(R.styleable.TextViewPlus_customFont);
        setCustomFont(ctx, customFont);
        a.recycle();
    }

    public boolean setCustomFont(Context ctx, String asset) {
        Typeface tf = null;
        try {
//          LOG.d("asset = "+asset);
            tf = Typefaces.get(getContext(), asset);

        } catch (Exception e) {
            LOG.e("Could not get typeface: " + e.getMessage());
            return false;
        }

        setTypeface(tf);
        return true;
    }
}

В attr.xml ещё дописать:
<declare-styleable name="TextViewPlus">
    <attr name="customFont" format="string"/>
</declare-styleable>

В слое в .xml добавить это:
xmlns:MY="http://schemas.android.com/apk/res/ваш_пакет"

Юзать так:
    <пакет.TextViewPlus
                               android:layout_width="wrap_content"                          android:layout_height="match_parent"
MY:customFont = "мой_шрифт.ttf"
    />


text:
Q: How to Download current web-page i want to add a button to download  my html source code of a web page,
i was able to do it but the problem is when i add a localhost url it works but when i add live url it open's the url instead of downloading it. so far i tried this
 <a download  href="http://localhost/test-new/">Download Source Code</a>

i also tried this
<button onclick="clicker()">Click me</button>

<script type="text/javascript">

function clicker() {
    var anchorTag = document.createElement('a');
    anchorTag.href = "http://localhost/test-new/";
    anchorTag.download = "download";
    anchorTag.click();

    var element = document.getElementById('divContainer');
    element.appendChild(anchorTag);
}

</script>

both of this working in localhost but not for live url. please help me

A: You can use
document.querySelectorAll('*')

to get the source code of a web page

console.log(document.querySelectorAll('*'))

A: This code should work.
BUT there is one main restriction, that can prevent you from downloading other pages - CORS policy. You can not fetch data from another domain if this policy does not allow it. Modern browsers restricts this for security reasons.
But if you download the current page, no problems will rise. Just see at Dev-Tools Console output for the error:
Access to fetch at 'URL_HERE' from origin has been blocked by CORS...

const btn = document.querySelector('.download-btn');
btn.addEventListener('click', (e) => clicker(e.currentTarget.dataset.url), false);

function clicker(url) {
  fetch(url)
    .then(res => res.text())
    .then(html => downloadAsFile('My file name.txt', html));
}

function downloadAsFile(name, text) {
  const link = createDownloadableLink(name, text);
  const clickEvent = new MouseEvent('click');
  link.dispatchEvent(clickEvent);
}

function createDownloadableLink(fileName, content) {
  let link = document.createElement("a");
  link.download = fileName;
  link.href = `data:application/octet-stream,${content}`;
  return link;
}
<button
  class="download-btn"
  data-url="http://localhost:1234/"
>Click me if CORS allow</button>


text:
Q: A Term or Expression for Recursion in a Lucid Dream I occasionally have lucid "false awakening" dreams (the most recent occasion being this past night) where I know I'm dreaming, I have the conscious will to wake up, and when I attempt to wake up it seems as though I've succeeded, yet I remain dreaming.
After the false awakening, I spend time attempting to establish that I am awake (always with the strong expectation that this hypothesis is true). Either in the course of this analysis, or in a subsequent attempt to "go about my business", I shortly become aware that I'm still dreaming, I again attempt to wake up, and the process repeats itself (in some instances, such as the most recent, well over 20 times).
The process is frustrating and upsetting, although I wouldn't characterize it as a nightmare.
My question is whether there's a term or expression for this particular kind of lucid dreaming, perhaps from the scientific study of dreaming, or from mythology/antiquity, or from a pop culture reference to a story where "inability to wake from a dream" features prominently as a plot device?

A: Celia Green wrote a semi-interesting book on lucid dreaming in which she used the term "False Awakening" to describe what you have mentioned here.
I only find the work (and in general the topic) uninteresting due to the fact that I rarely experience the phenomenon of dreaming and never lucid dreaming. You may find it more interesting.
A rudimentary search for "False Awakening" on the internet shows that it is a common term with many varied analyses.


text:
Q: CasperJS inject javascript via this.evaluate Today I tried to inject some javascript logic into remote page using CasperJS with PhantomJS together.
Well, I'm quite surprised because of that:
casper.then(function() {
    console.log(this.evaluate(function() {
        function myMethod() {
            return 'Any thing?!';
        }
        return myMethod();
    }));
    console.log(this.evaluate(function() {
        return myMethod();
    }));
});

I tried many combinations... Like:
casper.evaluate(...)
this.evaluate(...)
casper.page.evaluate(...) <- directly to phantomJS
this.page.evaluate(...)   <- as above

First case gives me exactly what I want. But next call to evaluate act as an idiot, which never saw executed code above.
I just want to change variables, functions, and other over remote site js runtime.
Can anybody tell me why this is happening?
Greetings.

A: You cannot do what you are thinking. myMethod is private to the function that is passed to this.evaluate. It doesn't make sense that you would expect a private function to be available in another function, just because it was passed to the same method.
In your example, you could try
casper.then(function() {
    function myMethod() {
        return 'Any thing?!';
    }
    console.log(this.evaluate(function() {
        return myMethod();
    }));
    console.log(this.evaluate(function() {
        return myMethod();
    }));
});

But that is probably not what you are looking for? Or is it?
Or are you trying to attach code to the page itself? Maybe the following?
casper.then(function() {
    console.log(this.evaluate(function() {
        // Just creating a variable won't attach it to the window, it will
        // be local to the function. However, you can attach it to the window
        // object, which is in the scope chain
        window.myMethod = function () {return 'anything'};
    }));
    console.log(this.evaluate(function() {
        return myMethod(); // or window.myMethod();
    }));
});


text:
Q: Como parsear una cadena json dentro de succes Hola estoy trabajando con columnas dinámicas y necesito parsear mi cadena data para convertirlo en un arreglo de objetos y asi poder acceder a sus elementos mediante un ciclo for. Pero al ejecutarlo muestra error en la consola. Espero me puedan ayudar a parsear  esta cadena.
Esta es la cadena que devuelve mi webMethod solo es una porción de la cadena ya que esta es muy larga.
"[\r\n  {\r\n    \"id_Persona\": 1,\r\n    \"Sucursal\": \"Mexico\",\r\n    \"Nombre\": \"Pedro\",\r\n

Este es mi WebMethod
[WebMethod]
public static string Persona(int id_Persona, string Sucursal, int id_Rol)
{

    Transacciones t = new Transacciones();
    DataSet ds = new DataSet();
    DataTable tabla_Intervalo = new DataTable();
    DataTable tabla_imagenIntervalo = new DataTable();
    ds = t.Mostrar_Intervalo(id_Intervalo, Sucursal, id_Rol);
    tabla_Intervalo = ds.Tables[0];
    tabla_imagenIntervalo = ds.Tables[1];

    string datos = JsonConvert.SerializeObject(tabla_Intervalo, Formatting.Indented);

    return datos;

}

Esta es mi función que contiene a mi ajax

function obtener_intervalo() {

    var persona = 1;
    var Sucursal = "";
    var id_Rol = 1;

    if (persona != 0) {

    var valores;
    var datafields_bonos = new Array();
    var columns_bonos = new Array();
    var columnsArray = [];

    $.ajax({
        type: "POST",
        dataType: "json",
        url: "frmPersona.aspx/Persona",
        contentType: "application/json; charset=utf-8",
        data: '{id_Persona:"' + persona + '",Sucursal:"' + Sucursal + '",id_Rol:"' + id_Rol + '"}',
        async: false,

        success: function(data) {
            alert("Entro correcto");

            if (data != '') {
                valores = jQuery.parseJSON(data); // Aqui cuando lo ejecuto me marca error en la consola.
                for (var i in valores[0]) {
                    datafields_bonos.push({ name: i });//No me regresa ningun valor
                    columns_bonos.push({ text: i, datafield: i, width: 200 });//No me regresa ningun valor
                }

                for (var j = 1; j < columns_bonos.length; j++) {
                    columnsArray.push(columns_bonos[j]);
                    console.log(columnsArray);//No me retorna el resultado
                }

            }

            var gridSource =
                {
                    localdata: valores,
                    datatype: 'json'

                };

Este es el error en consola
Uncaught SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) at Function.jQuery.parseJSON (jquery-1.11.1.js:8482) at Object.success (Prueba.js:91).

Cuando veo la estructura de data en concola (console.log(data)) me muestra esto.

[↵  {↵    "id_Persona": 1,↵    "Sucursal": "Mexico",↵    "Nombre": "Pedro",↵ ...

A: Hola creo que es porque estas usando mal la función, podrías intentar realizando lo siguiente:
valores = JSON.parse(data); // esto convierte la cadena en un objeto

Espero te sea de utilidad, podrías ver el siguiente link si tienes mas dudas, saludos.
https://stackoverflow.com/questions/17785592/difference-between-json-stringify-and-json-parse

A: Como te dice Pikoh en los comentarios los \r\n tienen toda la pinta de ser los culpables.
Podrías tratar de eliminarlos o escaparlos a la hora generar el JSON, o podrías utilizar una solución similar a la de https://stackoverflow.com/questions/22723077/does-the-output-of-jsonconvert-serializeobject-need-to-be-encoded-in-razor-view .

A: Lo he solucionado colocando esto:
 valores = data.d;
 valores = JSON.parse(valores);


text:
Q: Automatically installing Ubuntu with preseed file on VM I would like to install Ubuntu for my virtual machine unattendedly and won't wanna make a customized ISO as follows:

*

*Create a .flp file;

*in an existed Ubuntu, run grub-mkrescue to build a floppy image with preseed file (preseed.cfg) and a kickstart file (ks.cfg);

*configure the grub.cfg to enable booting from cdrom with the installation configuration files attached

i.e.,
insmod ata
set root=(ata0)
linux /casper/vmlinuz ks=floppy:/ks.cfg file=floppy:/pressed.cfg boot=casper only-ubiquity
initrd /casper/initrd.lz
boot

Then create a VM with cdrom and floppy inserted (e.g. ubuntu10.04.iso, grub-ubuntu.flp) and start the VM.
However, the configuration window for installation is always shown to ask for doing actions like selecting language, partitioning disk. Thus the boot program apparently cannot find the kickstart file.
I also tried ks=floppy, ks=/floppy/ks.cfg, ks=/dev/floppy/0/ks.cfg, ks=hd:fd0:/ks.cfg, ks=fd0:/ks.cfg, ks=/dev/fd0/ks.cfg, none of them works. The same for preseed/file option.
How can I make the kernel load floppy and the kickstart file to install Ubuntu automatically?

A: I followed the directions on this page and it worked great.
Here's an example of the kernel boot instructions as found on that page:

append file=/cdrom/preseed/ubuntu-server.seed initrd=/install/initrd.gz ks=cdrom:/ks.cfg preseed/file=/cdrom/ks.preseed --


text:
Q: Zend_Currency Displaying Extra Character I was trying to use Zend_Currency to format my currency outputs and i face this queer problem. An illegal character(Â) gets displayed along with the output of the currency data. The code i used is:
  $currency = new Zend_Currency('en_IN');
  echo $currency->toCurrency(100);

And the output is:
 Rs 100.00

I dont know from where the "Â" comes up. I found out that this problem occurs for certain locales only. It is working fine for en_US and some others but output this extra char  in many other. Some one please help.

A: Put this in your layout header, this is an regular encoding issue.
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

A: To expand on Elzo's answer, I have this in my Bootstrap.php:
$this->bootstrap('view');
$view = $this->getResource('view');
$view->headMeta()->setHttpEquiv('Content-Type', 'text/html; charset=utf-8');

This is in my layout:
<head>
    <?php echo $this->headMeta(); ?>
    <?php echo $this->headTitle(); ?>
    <?php echo $this->headLink(); ?>
    <?php echo $this->headScript(); ?>
</head>


text:
Q: Unsupervised Neural Network to Maximize a Function? Suppose I have vectors of dimension 1 x N {X_1...X_n} and {X_1' ...X_n'} where each X and X' are related but the relation is not able to be modeled by a function. I want to train a neural network by feeding it X_i and outputting Y_i with dimension N x 1, such that norm((X_i')(Y_i)) is maximized. The constraint is that Y_i has a norm of 1 (otherwise I will just use as large numbers as possible in Y_i).
I do not use X_i' as the inputs because they are not available in real life. I hope that when I test the neural network by feeding it {X_n+1 ... X_k}, it will output {Y_n+1 ... Y_k} where norm((X_n+1')(Y_n+1)) are maximized. Again, note that I only have {X_n+1'...X_k'} when testing, but not in real life where the neural network will be used.
I tried defining custom tensorflow or keras loss functions, but they don't seem to work. Also I tried using a neural network to first predict X_i' from X_i, but the performance is not very good.
A difficulty in this is to define a loss function that has no labels, and make neural network do backprop using this loss function.  Any ideas how this may be achieved?


text:
Q: Find difference between two consecutive rows of same column in mysql I'm having a situation where I need to calculate the difference between two consecutive rows of same column. Here is my table named 'orders' structure.
orderid   type     productsales
1002      Order    120
1002      Refund   -35
1003      Order    199
1003      Refund   -50
1004      Order    245
1005      Order    80

Now, what I want to Select only those records where the 'productsales' difference between the same orderids of order type 'Order' & 'Refund' is greater than 0

A: select orderid
from orders
group by orderid
having sum(case when `type` = 'Order' then productsales else 0 end) +
       sum(case when `type` = 'Refund' then productsales else 0 end) > 0

You need to subtract the values from another. But since you stored the - in the refund I used +.


text:
Q: AngularJS & Google Maps API V3 Cannot Geocode an Address in a Loop I am trying to geocode markers for each one in an AngularJS scope which can be picked up by using $scope.locations
I keep receiving the following error TypeError: Cannot call method 'geocode' of undefined
I have set var geocoder, geocode, geocode_results; at the top of my file
In an example, $scope.location has the following data when I console.log it.
$$hashKey: "009"
desc: "Closest test"
gps: "ab42 2dl"
title: "A place"

The code I am using to try run through the loop of locations is the following.
$scope.plotmarkers = function() {
    console.log($scope);
//          var temp_addresses = document.getElementById("gps").value.split("\n");
            var temp_addresses = $scope.locations;
            console.log(temp_addresses);

            for(var i=0;i<temp_addresses.length;i++){
        //      addresses.push(temp_addresses[i]);
console.log(temp_addresses[i].gps);
                geocoder.geocode( { 'address': temp_addresses[i].gps}, function(response, status) {
                    geocode_results[i] = new Array();
                    geocode_results[i]['status'] = status;
console.log('2')
                    if (!response || status != google.maps.GeocoderStatus.OK) {
                        if(status == google.maps.GeocoderStatus.ZERO_RESULTS){
                            geocode_results[i]['lat'] = 0;
                            geocode_results[i]['lng'] = 0;
                        } else {
                            timeouts++;
                            if(timeouts>6){
                                alert("You have reached the limit of of requests that you can make to google from this IP address in one day.");
                            }
                        }
                    } else {
                        timeouts = 0;
                        top_location = response[0];
                        var lat = Math.round(top_location.geometry.location.lat() * 1000000)/1000000;
                        var lng = Math.round(top_location.geometry.location.lng() * 1000000)/1000000;
                        geocode_results[i]['lat'] = lat;
                        geocode_results[i]['lng'] = lng;
                        geocode_results[i]['l_type'] = top_location.geometry.location_type;
                        marker = new google.maps.Marker({
                            icon: mapIcon,
                            position: new google.maps.LatLng(lat,lng),
                            map: map
                        });
                        arrayLocation.push(top_location.address_components[0].long_name);
        //              console.log(top_location.address_components[0].long_name);
                    }
                });
            }

    };

A: I was missing
var geocoder = new google.maps.Geocoder();


text:
Q: GCM notifications not being recieved when app in foreground I am trying to setup push notifications to my app containing both data and notification payloads as described in the official reference. I want both payloads so that I will get an automatic notification when my app is in the background, and the app can handle things itself while in the foreground.
The onMessageReceived() method in my GcmListenerService is not called when both payloads are included and the app is in the foreground. I have to leave out the notification payload for it to work.
When the app is in the background, it works fine. I get a notification and can open the app when the notification is clicked and do whatever I want from there.
I have looked at this question, but they were trying to get a notification when the app is in foreground. I realize I won't get a notification in that case, I just want to get the data.
Relevant portion of AndroidManifest.xml:
<receiver
    android:name="com.google.android.gms.gcm.GcmReceiver"
    android:exported="true"
    android:permission="com.google.android.c2dm.permission.SEND">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="arkenterprises.garage_o_matic.gcm" />
    </intent-filter>
</receiver>
<service
    android:name=".MyGcmListenerService"
    android:enabled="true"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    </intent-filter>
</service>

MyGcmListenerService.java:
public class MyGcmListenerService extends GcmListenerService {

    private static final String TAG = "MyGcmListenerService";

    @Override
    public void onMessageReceived(String from, Bundle data) {
        Log.d(TAG, "Data: " + data);
        String message = data.getString("message");
        String doorStatus = data.getString("DoorStatus");
        String time = data.getString("time");
        Bundle notification = data.getBundle("notification");
        Log.d(TAG, "From: " + from);
        Log.d(TAG, "Message: " + message);
        Log.d(TAG, "DoorStatus: " + doorStatus);
        Log.d(TAG, "Time: " + time);
        Log.d(TAG, "Notification: " + notification);
}

Server code that sends the message:
nowString = datetime.datetime.now().strftime("%c")
gcmSendURL = 'https://gcm-http.googleapis.com/gcm/send'
gcmHeaders = {'Authorization': 'key=' + API_KEY, 'Content-Type': 'application/json'}
gcmDataPayload = {'message': 'Garage door opened', 'DoorStatus': 'Open', 'time': nowString}
gcmNotificationPayload = {'title': 'Garage Door Has Opened', 'body': 'Garage door opened at {}'.format(nowString), 'icon': 'ic_door_open_notification2'}
print('Garage door opened at {}'.format(nowString))
gcmPayload = {'to': regIDs[0].strip(), 'priority': 'high', 'delay_while_idle': False, 'time_to_live': 86400, 'data': gcmDataPayload}
# gcmPayload = {'to': regIDs[0].strip(), 'priority': 'high', 'delay_while_idle': False, 'time_to_live': 86400, 'notification': gcmNotificationPayload}
# gcmPayload = {'to': regIDs[0].strip(), 'priority': 'high', 'delay_while_idle': False, 'time_to_live': 86400, 'content_available': True, 'data': gcmDataPayload, 'notification': gcmNotificationPayload}
print("\nPayload: {}".format(gcmPayload))
r = requests.post(gcmSendURL, headers=gcmHeaders, json=gcmPayload)
print("\nRequest response: " + r.text)

A: Yes, you can send messages that have both notification and data payloads.
I found this Stack overflow ticket related to your inquiry, It says that Intent filters will always fire your manifested application as per standard android behavior. Make sure that your logic flow is able to handle the fact that your launch may come from places. Try to implement  'GcmMessageHandler' your application must check saved state and sees if user needs to see screen and automatically show notifications.

A: I had some strange behaviour with samples, but in final I resolved that by removing implementation of GcmListenerService and adding implementation of GcmReceiver.
public class MyGcmReceiver extends GcmReceiver {

  @Override
  public void onReceive(Context context, Intent intent)
  {
  }
};

and manifest
<receiver
   android:name=".MyGcmReceiver"
   android:exported="true"
   android:permission="com.google.android.c2dm.permission.SEND" >
   <intent-filter>
      <action android:name="com.google.android.c2dm.intent.RECEIVE" />
   </intent-filter>
</receiver>


text:
Q: What is the meaning of this method calcWrappedOffset () A method in a queue, offer I don't quite understand the effect of this method
:
  @Override
public boolean offer(final T e) {
    if (null == e) {
        throw new NullPointerException("Null is not a valid element");
    }
    // local load of field to avoid repeated loads after volatile reads
    final AtomicReferenceArray<Object> buffer = producerBuffer;
    final long index = lpProducerIndex();
    final int mask = producerMask;
    final int offset = calcWrappedOffset(index, mask);
    .......
 }

calcWrappedOffset() method:
   private static int calcWrappedOffset(long index, int mask) {
    return calcDirectOffset((int)index & mask);
}
private static int calcDirectOffset(int index) {
    return index;
}

A: What is that you don't understand?
This is from the SpscLinkedArrayQueue I presume which uses circular buffers with power of 2 size. Due to being power of 2, wrapping the index around requires a simple and fast binary 'and' with the mask = size - 1 value instead of the heavy modulo operator.
The original JCTools version allowed spanning out items in the array to reduce the false-sharing effects but RxJava decided to not support that in order to reduce memory consumption, hence the calcDirectOffset returning the unaltered index.