text:
Q: useReducer value not being updated properly I'm trying to update a state of a component with useReducer. I'm grabbing some info from mongodb in useEffect and there I am calling my useReducer dispatch so I can set my state as soon as the component mounts. Unfortunately, my state isn't being affected and my UI isn't changing. The console.log statement at the end of my useEffect statement shows my state to still have the initial values set in useReducer call. Can anybody tell me where I am going wrong here? Also, I plan on later adding to the state and to the dependency array in useEffect. Before when I was working on this, I was getting an infinite useEffect loop so for now I have an empty error. I'd like to update the state though and have my UI reflect the changes. Anways, here is the code of the functional component containing the useEffect call.
EDIT: my_player object should originally be this object for the user I am currently using with mongodb {health_percent: 100, hunger_percent: 100, hydration_percent: 100}
const change_progress_color = (pet_percentage: any) => {
    // change the attribute's color depending on pet_attr value
    // PROGRESS_COLORS IS JUST AN ENUM OBJ WITH COLOR CODES
    let color;
    if (pet_percentage < .10)
        color = PROGRESS_COLORS[1];
    else if (pet_percentage < .30)
        color = PROGRESS_COLORS[2];
    else if (pet_percentage < .50)
        color = PROGRESS_COLORS[3];
    else if (pet_percentage < .75)
        color = PROGRESS_COLORS[4];
    else if (pet_percentage < .90)
        color = PROGRESS_COLORS[5];
    else
        color = PROGRESS_COLORS[6];
    return color;
};

const Player: React.FC = () => {
    const [player, setPlayer] = useState<any>();
    const [state, dispatch] = useReducer<React.Reducer<State, Actions>>(reducer,
        {health: 0, hydration: 0, hunger: 0});

    useEffect(() => {
        console.log("running useEffect");
        (async () => {
            var my_player = await getPlayer();
            if (my_player)
                if (my_player.length > 0) {
                    const p: any = my_player[0];
                    setPlayer(p);
                    console.log("here is my player", p);
                    dispatch({type: "ChangeHealth", diff: p.health_percent});
                    dispatch({type: "ChangeHunger", diff: p.hunger_percent});
                    dispatch({type: "ChangeHydration", diff: p.hydration_percent});
                    console.log("Here is my state", state);
                }
        })();
    }, []);
    return (
            <IonPage>
                <IonHeader>
                    <IonToolbar>
                        <IonTitle>My Player</IonTitle>
                    </IonToolbar>
                </IonHeader>
                <IonContent>
                    <IonHeader collapse="condense">
                        <IonToolbar>
                            <IonTitle size="large">My Player</IonTitle>
                        </IonToolbar>
                    </IonHeader>
                    <IonList>
                        <IonItem>
                            <IonLabel position="floating">
                                Health
                            </IonLabel>
                            <IonProgressBar
                                value={state.health}
                                color={change_progress_color(state.health)}/>
                        </IonItem>
                        <IonItem>
                            <IonLabel position="floating">
                                Hunger
                            </IonLabel>
                            <IonProgressBar
                                value={state.hunger}
                                color={change_progress_color(state.hunger)}/>
                        </IonItem>
                        <IonItem>
                            <IonLabel position="floating">
                                Hydration
                            </IonLabel>
                            <IonProgressBar
                                value={state.hydration}
                                color={change_progress_color(state.hydration)}/>
                        </IonItem>
                    </IonList>
                </IonContent>
            </IonPage>
    );
};

export default Player;

Here is my code outside the react function with my types and reducer function.
type State = {
    health: number;
    hunger: number;
    hydration: number;
};

type ChangeHealth = {
    readonly type: "ChangeHealth";
    readonly diff: number;  // this number is going to need to be divided by 100
}

type ChangeHunger = {
    readonly type: "ChangeHunger";
    readonly diff: number; // this number is going to need to be divided by 100
}

type ChangeHydration = {
    readonly type: "ChangeHydration";
    readonly diff: number; // this number is going to need to be divided by 100
}

type Actions = ChangeHealth | ChangeHunger | ChangeHydration;

function reducer(state: State, action: Actions): State {
    switch (action.type) {
        case "ChangeHealth":
            return (() => {
                console.log("running func");
                console.log("here is the diff ", action.diff);
                let new_health = (state.health + action.diff) / 100;
                console.log(new_health);
                if (new_health > 1)
                    new_health = 1;
                return {...state, health: new_health};
            } )();
        case "ChangeHunger":
            return (() => {
                let new_hunger = (state.hunger + action.diff) / 100;
                if (new_hunger > 1)
                    new_hunger = 1;
                return {...state, hunger: new_hunger};
            } )();
        case "ChangeHydration":
            return (() => {
                let new_hydration = (state.hydration + action.diff) / 100;
                if (new_hydration > 1)
                    new_hydration = 1;
                return {...state, hydration: new_hydration};
            } )();
    }
}

Any help would be greatly appreciated. Thanks

A: You make only one request. For what reason do you split data to useState and useReduce?
MB code bellow helps you.

import React, { useEffect, useState } from 'react';

const Player: React.FC = () => {
  const [player, setPlayer] = useState({
    health: 0,
    hydration: 0,
    hunger: 0,
  });

  useEffect(() => {
    getPlayer()
      .then((response) => {
        const [player] = response;

        if (player) {
          setPlayer((prevState) => {
            const health = (prevState.health + player.health_percent) / 100;
            const hunger = (prevState.hunger + player.hunger_percent) / 100;
            const hydration = (prevState.hydration + player.hydration_percent) / 100;

            return ({
              health: health > 1 ? 1 : health,
              hunger: hunger > 1 ? 1 : hunger,
              hydration: hydration > 1 ? 1 : hydration,
            });
          });
        }
      })
      .catch(({ message }) => {
        console.error(message);
      });
  }, []);

  return null;
};

A: Your useEffect and Reducer code is fine, state is Updated as you expected, the reason why the last console.log was not logging the new state is because, dispatch method is not synchronous, it causes re-render and on the next render new state will be updated. I think your problem is displaying the state
             <IonProgressBar value={state.hydration} color={change_progress_color(state.hydration)}/>.


text:
Q: Detecting Control + D in my code also triggers add bookmark keyboard shortcut in Chrome, is there any way to prevent this? Is there anyway to disable the browsers keyboard shortcut from going off too?  The google chrome keyboard shortcut happens AFTER my code.  i just dont want it to go off at all.
handleKeyDown( e ) {
if ( e.ctrlKey && e.keyCode === 68 ) {  // ctrl + d
    // this works, BUT it also triggers Google Chrome's bookmark shortcut
}

A: You should prevent the event's default action, like this:
function handleKeyDown( e ) {
  if ( e.ctrlKey && e.keyCode === 68 ) {  // ctrl + d
      // this works, BUT it also triggers Google Chrome's bookmark shortcut
      console.log('Ctrl+D');
  }
  e.preventDefault();
}

https://jsfiddle.net/a5wbd3o9/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reload UITableView from a NSObject I have a question concerning iOS. I couldn't find an answer to my question online but maybe one of you know the answer.
Im working on an app which pulls data from an online database. A NSObject Class is called by a timer in the background of the app. I want it to tell one of my view controller to reload its tableview if it finds new data. Like it is supposed to check for data not caring in which view controller im in. But when I'm in the specific one with my table view it should reload the table view if it found new data.
I've tried to create an instance of the tableviewcontroller in my NSObject and call the reload table view function front there, but that doesn't work :/
I apologise for my poor explanation, I'm not a native speaker.
Thank you very much :)

A: You can use two approaches:

*

*post a NSNotification in your class that gets more data and observes
this notification in your class that the TableView is initialized.

*make a delegate approach between the two classes and fire a method when you have the new data.

I would go with the first option:
a. in your data loading class:
NSNotification *notification = [NSNotification notificationWithName:@"newDataFetched" object:anyObject];
[[NSNotificationCenter defaultCenter] postNotification:notification];

b. in your listener class:
[[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(aMethodToReloadTheTableView:)
               name:@"newDataFetched"
             object:nil];


text:
Q: ExecutorService invokeall threadpool issue I am struggling with a use case where one of the tasks submitted to invokeall() throws CancellationException forcing program NOT to terminate. How can make sure this program will terminate properly in case of CancellationException ?
How I am finding out my program not terminated clean? I am using netbeans and shows progress bar at bottom right if program doesn't terminate.
Here is code:
        int poolSize = Runtime.getRuntime().availableProcessors();
        ExecutorService pool = Executors.newFixedThreadPool(poolSize);
        Set<Callable<Object>> tasksSet = new HashSet<>();
        tasksSet.add(new Task1());
        tasksSet.add(new Task2());
        tasksSet.add(new Task3());

       List<Future<TrendLineStatisticsVO>> resultSet = pool.invokeAll(tasksSet, 1, TimeUnit.MINUTES);
        for (Future<Object> future : resultSet) {
            Object result;
            try {
                   result = future.get(5, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
                Logger.getLogger(CallableDemo.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                ex.printStackTrace();
                Logger.getLogger(CallableDemo.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TimeoutException ex) {
                ex.printStackTrace();
                Logger.getLogger(CallableDemo.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        pool.shutdown();

And Task1 code:
public class Task1 implements Callable<Object> {

    @Override
    public Object call() throws Exception {
       //This for sure takes days to complete, so should through Cancellation exception because    timeout on invokeall set to 1 minute
        long val = 0;
        for (long i = 0; i < Long.MAX_VALUE - 5000; i++) {
            val += i;
        }
        return "Sucessfull Task1 object...";
    }

}

Task2 and Task3 code also same except these two classes use Integer.MAX_VALUE in for loop check.

A: There are two issues:
1)
Per the Javadoc:

tasks that have not completed are cancelled.

So you will have to code your Task to be responsive to interruption.  What is happening in the background is similar to future.cancel(true) if the tasks don't complete in the time specified, the true in the argument says to interrupt() the thread running the task.  Like I mentioned, your tasks will have to look out for interruption.  Something similar to:
@Override
public Object call() throws Exception {
   //This for sure takes days to complete, so should through Cancellation exception because    timeout on invokeall set to 1 minute
    long val = 0;
    for (long i = 0; i < Long.MAX_VALUE - 5000; i++) {
        if(Thread.interruped()){
            throw new RuntimeException("Did not complete in time: " + i);
        }
        val += i;
    }
    return "Sucessfull Task1 object...";
}

How I am finding out my program not terminated clean? I am using netbeans and shows progress bar at bottom right if program doesn't terminate.

Without my update above the program will never end as the thread pool is still running.  shutdown will do nothing as the tasks haven't completed (event with cancel).
2)
A task that is cancelled, by definition, did not complete (or even start) so invoking get on the Future will fail quickly.  You could ask the future if it's cancelled Future#isCancelled.


text:
Q: MongoDB aggregate by date using _id What I'm trying to do should be relatively simple. My document is called "clicks", and looks like this:
{
     "_id":"5dcc53f30666eacfdb9d9f59"
,     "productID":"5dcc4c47a0d861ec6a0b432b"
,     "userIP":"XX.XX.XX"
}

I just want to get back the number of clicks per day, using _id and (I assume) GetTimestamp() to figure out the date:
[
{
     "date":"2019-11-01"
,    "clicks":"125"
}
,{
     "date":"2019-11-02"
,    "clicks":"153"
}]

I thought that I could do something like this, but it's not working:
db.clicks.aggregate([
    {"$group" : {_id: ObjectId(_id).getTimeStamp(), count:{$sum:1}}}
])

All the examples I'm seeing (eg: group by dates in mongodb ) have an element in the document containing a date element-- how do I do this JUST with the _id?

A: I have to go, but here's a starting point that solves your question. Can likely be optimized.
[
  {
    $addFields: /** * newField - The new field name. * expression - The new field expression. */ {
      date: { $toDate: '$_id' }
    }
  },
  {
    $addFields: /** * newField - The new field name. * expression - The new field expression. */ {
      year: { $year: '$date' },
      month: { $month: '$date' },
      day: { $dayOfMonth: '$date' }
    }
  },
  {
    $addFields: /** * newField - The new field name. * expression - The new field expression. */ {
      yearString: { $toString: '$year' },
      monthString: { $toString: '$month' },
      dayString: { $toString: '$day' }
    }
  },
  {
    $addFields: /** * newField - The new field name. * expression - The new field expression. */ {
      monthYear: { $concat: ['$yearString', '-', '$monthString'] }
    }
  },
  {
    $addFields: /** * newField - The new field name. * expression - The new field expression. */ {
      fullDate: { $concat: ['$monthYear', '-', '$dayString'] }
    }
  },
  {
    $group: /** * _id - The id of the group. * field1 - The first field name. */ {
      _id: '$fullDate',
      ids: { $push: '$_id' }
    }
  },
  {
    $project: /** * specifications - The fields to *   include or exclude. */ {
      totalClicks: { $size: '$ids' }
    }
  }
];

A: Cause MongoDB has $dateToString function, here's a more clean version with timezone:
[
  {
    $group: {
      _id: {
        $dateToString: {
          date: '$_id',
          format: "%Y-%m-%d",
          timezone: "Asia/Shanghai"
        }
      },
      ids: { $push: '$_id' }
    }
  },
  {
    $project: {
      totalClicks: { $size: '$ids' }
    }
  },
  { $sort: { _id: -1 } }
]

A: I'm going to give Christian credit for the answer, but for anyone who comes across this down the line, here's a cleaner version of it:
db.clicks.aggregate(
  [

  {
    $group:  {
      _id: { $substrCP: [ {$toDate: '$_id' }, 0, 10 ]
        },
      ids: { $push: '$_id' }
    }
  },
  {
    $project:  {
      totalClicks: { $size: '$ids' }
    }
  },
  {$sort: {_id: 1} }
]  )

The primary difference is that, rather than using $addFields to build the date string, I just use $toDate, then take a substring that gives me YYYY-MM-DD-- this works because $toDate happens to return a format that's close to what I want, if you wanted May 13, 2019, then you'd have to do most converting.
Since time is stored in UTC, here's one way to convert it back to your local time zone-- this is hard-coded to Pacific (8) and doesn't account for DST, but should at least give you an idea of how to mess with it.
db.clicks.aggregate(
  [

  {
    $group:  {
      _id: { $substrCP: [ {$subtract: [{$toDate: '$_id' }, 1000*60*60*8]}, 0, 10 ]
        },
      ids: { $push: '$_id' }
    }
  },
  {
    $project:  {
      totalClicks: { $size: '$ids' }
    }
  },
  {$sort: {_id: 1} }
]  )


text:
Q: Realm : ArrayIndexOutOfBoundsException rowIndex > available rows: 0 > 0 I try to read mydata with Realm in android calling two database like this
Realm myRealm = Realm.getDefaultInstance();
    RealmResults<ChapterRealm> rsChap = myRealm.where(ChapterRealm.class)
            .equalTo("subj_id",subj_id)
            .equalTo("name",holder.main_title.toString())
            .findAll();

    RealmResults<QuestionRealm> rsQues = myRealm.where(QuestionRealm.class)
            .equalTo("chapter_id",rsChap.get(position).getId())
            .findAll();

and it shows below error at RealmResults
java.lang.ArrayIndexOutOfBoundsException: rowIndex > available rows: 0 > 0

Help me to solve this please.


text:
Q: Exporting to csv: Romanian Language character failure Helo I have a problem with diacritics .. in Mysql it's fine i set the utf8_general_ci  you cand see in this picture

in my website it's fine you can see

But when i export to csv file don't work..
Another file with diacritic reads my excel but this not.

I use this code for export
function doCsv(){

    var table = document.getElementById("exportTable").innerHTML;
    var data = table.replace(/
/g,'').replace(/<\/thead>/g,'')
    .replace(/
/g,'').replace(/<\/tbody>/g,'')
    .replace(/
/g,'').replace(/
/g,'').replace(/<\/tr>/g,'\r\n')
    .replace(//g,'').replace(/<\/th>/g,';')
    .replace(//g,'').replace(/<\/td>/g,';')
    .replace(/\t/g,'').replace(/\n/g,'');
    var link = document.createElement('a');
    link.download = "exportToCSV.csv";
    link.href = "data:application/csv," + escape(data);
    link.click();

And if i put the alert it keeps well see :

Anyone to help me?

A: See the %u0218?  That means that something is converting to Unicode.  You don't want that.  You want utf8 (or utf8mb4).
Select the HEX from the table.  For these letters: ĂÎŞŢÂ, you should get this hex if it is properly encoded in UTF-8:  C482 C38E C59E C5A2 C382.  Note that each accented letter turns into 2 hex bytes.
Your second attempt came back with ĂÎŞŢÂ, which is "Mojibake" for ĂÎŞŢÂ.  It's hex is C384E2809AC383C5BDC385C5BEC385C2A2C383E2809A.
I discuss Mojibake and point out what was done wrong in Trouble with UTF-8 characters; what I see is not what I stored .
Somehow, your Excel code needs to say to export UTF-8, not unicode.
And your table must be utf8, not latin1.
And the import must declare that the data is utf8.


text:
Q: ApplicationBar Foreground color not applying I am working on Windows Phone 8 application.
I have Application Bar with icon, I have set the Background and Foreground color to the icons as well.
ApplicationBar.BackgroundColor // Orange

ApplicationBar.ForegroundColor // White

So now the Application bar looks like this :

Now my phone theme settings i have set the Accent color as pink so when i tap on the icon it looks like this :

But when i tap on the icon i want the effect to be is like this, even if my Phone setting Accent color is pink or some other color and background is set to light or dark.

A: It is not possible to change the behaviour of the ApplicationBar in the way you describe.
The ApplicationBar is not a regular control and it is not possible to alter it's behaviour in this way.
If you really, really want to get the behaviour you're after you'll need to create your own replacement for the ApplicationBar.


text:
Q: Passing a value between services in Angular5 using RxJs I am trying to pass an access_token , which is declared in userService service, and its value is set in register.component.ts. Then I need to access the value of the access_token in another service (httpService). I decided to use BehavioralSubject for that matter but somehow i cannot retrieve updated value of the token in httpService. The code excerpt below.
User.service.ts -> here i declare the access_token
 access_token = new BehaviorSubject<string>('');

Register.component.ts -> here i successfully assign the value to access_token
 onRegister(form){
    this.httpService.registerByEmail(this.email, this.password )
    .subscribe(
      response => {
        this.popupService.popupScreen.next('messenger');
        this.httpService.loginByEmail(this.email, this.password)
        .subscribe(response1 => {
          this.userService.access_token.next(response1['access_token']);
          console.log('access_token Component', this.userService.access_token);    --> here it console.logs the correct token
        },
        error => {
          console.log('error', error);
        }
      )
      },
      error => {
        if (error.error.status === false) {
          this.emailError =  error.error.errors.email;
          this.passwordError =  error.error.errors.password;
        };
      }

    )
  }

Http.service.ts -> here is where i need to retrieve the updated value of the token
  access_token;

   getSubject(){
        this.userService.access_token.subscribe(
            token => {
                this.access_token = token
            });
        return this.access_token;
    }

  setLogin(): Observable<any[]> {
        this.getSubject();
        const url = 'http://url';
        const httpHeaders = new HttpHeaders()
            .set('Authorization', 'Bearer ' + this.access_token);

            return this.httpClient.post<any[]>(url, { headers: httpHeaders });
    }

A: You need to treat the this.userService.access_token as asynchronous all the time.
When the return this.access_token; is called, this.access_token = token has not been called yet.
You need to chain on this subscription to be able to make the request with the token.
setLogin(): Observable<any[]> {

    const url = 'http://url';

    return this.userService.access_token
        .take(1)
        .concatMap((access_token) => {
            const httpHeaders = new HttpHeaders()
                .set('Authorization', 'Bearer ' + access_token);

            return this.httpClient.post<any[]>(url, { headers: httpHeaders });
        });
}

You could also wrap things up into separate methods to make things looks nicer, but this should work for you.
take(1) will make sure that this only happens once. Since you use BehaviorSubject for the token, it should already be there and happen instantly.
Inside concatMap() then the call is made and the concatMap makes sure that the result get's propagated back same way as it would if you just returned a this.httpClient.post() result.
Edit - a note:
When calling setLogin() you need to subscribe to returned value, otherwise it won't get called.
this.httpService.setLogin().subscribe();

If you don't want to receive any value from the function or to know when it finished, you could also .subscribe() right after concatMap(). You'd need to remove the first return.
RXJS pipes are "lazy" and won't produce any value until the pipe is subscribed to. The access_token would not produce any value, therefore the post() to the server is not being called.


text:
Q: In Python is there any way to define the default value of a parameter to be based in other given parameter? I'm trying to do something like this:
def some_func(a, b = a):
    if not a:
        return b
    return a + b + some_func(a-1)

so, because it's called recursively, I can't get b inside the function, I want b to be the value of a at the first time the function is called. But I don't know how to do this because the way I tried it can't reach the value of a in the default assignment

A: would something like this work?
a = 1
b = 2
def some_func(a, b):
    if not a:
        return b
    return a + b + some_func(a-1, b)
some_func(a, b)

A: I've reached what I wanted doing
def some_func(a, b = None):
    if b is None:
        b = a
    if not a:
        return b
    return a + b + some_func(a-1, b)

this way it only assigns b at the first time the function is called, like if some_func(7) is called, then b will be 7 until the end of the recursion, thanks for the comments y'all


text:
Q: How many subsequences are there for a permutation of these letters? On an exam of mine, we had the following question:

A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence $<A, B, D>$ is a subsequence of $<A, B, C, D, E, F>$ obtained after removal of elements E, C and F.
Assume that each permutation of the letters A, B, C, D, E, F, G, H defines a sequence. How many of these sequences contain the subsequences of $<C, A, B>$ or $<B, E, D>$?

And here's my solution:

First, it's important to note that they can contain both, like so:
CABED, so we'll need to apply inclusion-exclusion.
We consider how many ways we can permute with the chunks "CAB" / "BED"
and the other letters.
CAB + D, E, F, G, H: 6 units to permute = 6!
BED + A, C, F, G, H: 6 units to permute = 6!
CABED + F, G, H: 4 units to permute = 4!
By inclusion-exclusion, there are this many sequences with "CAB" or
"BED" as substrings:
Answer = 6! + 6! - 4! = 1416

I lost a few points on this, but the professor didn't yet clarify why. Could someone please help me understand what I did wrong? I retraced my steps and couldn't figure it out.

A: You counted only strings where "CAB" or "BED" appear contiguously. But the definition allows letters to be placed in between. For example "CDEFABGH" contains "CAB" as a substring but 'C' isn't next to 'A'.


text:
Q: How to purge big MySQL database old entries from single column? I need to remove old database entries payload, while keeping other data (id and other properties) of same entries.
Table in question has message_id column (which consists of a datestamp concatenated with other info), content column (which is BLOB, and it makes over 90% of database total size) and some other columns that we have no use for in this case.
I've first tried running simple update with condition:
UPDATE LOW_PRIORITY repository SET content="" WHERE SUBSTR( message_id, 6, 6 )<201601 AND message_box = "IN";

I extract a YYYYMM from every entry message_id, and if it's older than a chosen cutoff month - I replace content with an empty string.
Database is over 25GB in size, and holds almost 2KK entries in my table, and is running on a very modest hardware, and my query failed with error after running for some time:
ERROR 2013 (HY000): Lost connection to MySQL server during query

Usually I try to avoid changing database variables, but i knew this error also pops up when you try restoring database from a large dumpfile, therefore I went and updated setting to handle 100MB packet size:
set global max_allowed_packet=104857600;

Re-running my UPDATE query resulted in a new error:
ERROR 2013 (HY000): Lost connection to MySQL server during query

As I have mentioned before - my MySQL server runs on a very modest hardware, and I'd prefer not to modify settings that could make server exceed available resources, therefore instead of increasing all available timeout database variables, I've decided to run my query in smaller chunks with a query like this:
UPDATE LOW_PRIORITY repository SET content="" WHERE message_id in (select message_id from(select message_id from repository where SUBSTR( message_id, 6, 6 )<201603 AND message_box = "IN" limit 0, 1000)as temp);

This query fails with an error:
ERROR 1206 (HY000): The total number of locks exceeds the lock table size

It also fails with a same query when limited even to single line with "limit 1"!
Do I use pagination incorrectly, or is there another better way of doing this?
*DB is running an a virtual Ubuntu server with dual core Intel CPU with 1GB of RAM and 100GB HDD. I't completely adequate for it's daily tasks, and I'd really like not to increase specs for just this one query.

A: You are trying to trick mysql into doing something it doesn't want (using limit in an in-statement) in a complicated way (complicated = more resources). That is not wrong, but you can just write
UPDATE LOW_PRIORITY repository SET content=""
WHERE content <> ""
and SUBSTR( message_id, 6, 6 ) < 201603 AND message_box = "IN"
limit 1000;

This will update the first 1000 old rows that still have content in it.

A: I would imagine your #1 problem here is that your WHERE condition will not be able to use an index on message_id field.
Why not simply do:
WHERE message_id < 20160100* ...

Assuming this is integer field, 201512** would be less the 201601** anyway so there would be no change in your outcome.  But removing the substring function would allow you to use index on that field.


text:
Q: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver (jar file already linked and placed in WEB-INF/lib) The solutions I found for this error were "add the jar file via build path" and "put the jar file containing the driver in WEB-INF/lib" (and similar formulations) but I already tried the two of them.
Back to my problem. Here is my Code:
jsp-file
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="db.DBAccess" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>

<jsp:useBean id="dba" class="db.DBAccess"></jsp:useBean>

<jsp:setProperty name="dba" property="selection" value="s" />

</body>
</html>

javabean
package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBAccess {

    public DBAccess() {
    }

    private String selection = "";

    public void setSelection(String s) {

        final String driver = "com.mysql.jdbc.Driver";

        String url = "jdbc:mysql://localhost:3306/test";
        String user = "user1";
        String pswd = "user1pswd";

        Connection con = null;
        Statement stmt = null;

        try {
            // initialize connection
            Class.forName(driver);
            con = DriverManager.getConnection(url, user, pswd);
            stmt = con.createStatement();
            // execute select
            ResultSet results = stmt.executeQuery("SELECT * FROM t");
            results.next();
            selection =  results.getString(1);
            // close connection
            stmt.close();
            con.close();
        } catch (ClassNotFoundException cnfe) {
            System.out.println(cnfe.toString());
        } catch (SQLException e) {
            System.out.println(e.toString());
            }

    }
}

The content of t is one column with the label "string" and the content "hello world"
Why am I getting this exception even though I linked the jar file correctly?

A: Did you insert your jar file to lib folder of Webinf?


text:
Q: Bazel: how to create a define for cc_library with absolute path to file? I'm trying to embed a ML file in my cc_library using incbin and it needs the full path to it. In my cc_library I want to add
defines =  ['SELFIE_SEGMENTATION_MODEL_PATH=' + '/path/to/model.tflite'],

but as a relative path. How could I change '/path/to/model.tflite' for a relative path in my repo that resolves to the absolute path in the define passed to the compiler? I need the absolute path because the assembler needs it at link time.
In CMakeLists.txt it is as simple as:
add_definitions(-DSELFIE_SEGMENTATION_MODEL_PATH=${CMAKE_CURRENT_SOURCE_DIR}/models/model.tflite)


text:
Q: How to Run a plecebo regression for the non treatment years and then compare the result with the current year? To check the identification design, run placebo regres- sions for the non-treatment years 2002, 2003 and compare with the results for the treatment year 2004. What results do you expect and what do you find? this is the actual question i want to get the code for this.
I have started to write some code when it comes to placebo regression but i dont know if i am on the right track


text:
Q: Accessing Web service using Python I have been trying to connect to a web service using SUDS and Zeep. Neither of them work and throws different errors.
The server is using a wsHTTP_endpoint and a AXMS_endpoint, I can connect to the later but the endpoint does not provide me with the accurate access so I need the wsHTTP endpoint.
Working Code for AXMS:
from suds.client import Client
client = Client(wsdl)
x =client.service['AXMS'].Method({'datapoint':23})

What I have tried with SUDS:
from suds.client import Client
client = Client(wsdl)
x =client.service['wsHttp_Endpoint'].Method({'datapoint':23})

Exception: (415, "Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'.")

I even tried client.set_options(headers = {'Content-Type': 'application/soap+xml;charset=UTF-8'})
But then I got a bad request error. Exception: (400, 'Bad Request')
What I have tried with Zeep (same code as above with zeep client):
from zeep import Client
from zeep.wsse.username import UsernameToken
client = Client(wsdl)

error: The message could not be processed. This is most likely because the action XXXXX is incorrect or because the message contains an invalid
or expired security context token or because there is a mismatch between
bindings. The security context token would be invalid if the
service aborted the channel due to inactivity.
To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.

This give me an error on the binding.


text:
Q: remove duplicate across foreach loop In my result I have some duplicate content inside my dropdown. Do you know how to resolve it?
Bu an array_unique ?
thank you
example :
<select name="boxtal_operator" id="sortDropDownListByText" class="form-control">
    <option value="0">--- Select ---</option>
    <option value="CHRP-1456S">AGAY / L'ATELIER FLORAL D'AGAY / 125 BD DE LA PLAGE / CHRP-1456S</option>
    <option value="CHRP-1456S">AGAY / L'ATELIER FLORAL D'AGAY / 125 BD DE LA PLAGE / CHRP-1456S</option>
    <option value="CHRP-1456S">AGAY / L'ATELIER FLORAL D'AGAY / 125 BD DE LA PLAGE / CHRP-1456S</option>
    <option value="SOGP-I3171">AGAY / PROXI / 1318 BD DE LA 36EME DI DU TEXASLE DRAMONT / SOGP-I3171</option>
    <option value="SOGP-I3171">AGAY / PROXI / 1318 BD DE LA 36EME DI DU TEXASLE DRAMONT / SOGP-I3171</option>
    <option value="SOGP-I3171">AGAY / PROXI / 1318 BD DE LA 36EME DI DU TEXASLE DRAMONT / SOGP-I3171</option>
</select>

below the php code allow to make this result.
$operator_code = ['POFR', 'MONR', 'SOGP', 'Chrono', 'CHRP', 'IMXE', 'UPSE', 'PUNT'];

$result_carrier_code[] = ['id' => '0', 'text' => Core::getDef('text_select')];

    foreach ($operator_code as $operator)
    {
        $list_point = $this->boxtaleShop->getListPoint($country_iso, $code_postal, $city, $operator);

        foreach ($list_point as $carrier)
        {
            if (is_array($carrier)) {
                foreach ($carrier as $item)
                {
                    if (is_array($item['points'])) {
                        foreach ($item['points'] as $points)
                        {
                            if (is_array($points)) {
                                $result_carrier_code[] = [
                                    'id' => $points['code'],
                                    'text' => $points['city'] . ' / ' . $points['name'] . ' / ' . $points['address'] . ' / ' . $points['code']
                                ];
                            }
                        }
                    }
                }
            }
        }
    }

Array example (it's a big)
array(496) { [0]=> array(2) { ["id"]=> string(1) "0" ["text"]=> string(14) "--- Select ---" } [1]=> array(2) { ["id"]=> string(10) "MONR-08915" ["text"]=> string(57) "FREJUS / CULTURE INDOOR / ROUTE DE MALPASSET / MONR-08915" } [2]=> array(2) { ["id"]=> string(10) "MONR-06124" ["text"]=> string(57) "FREJUS / CULTURE INDOOR / ROUTE DE MALPASSET / MONR-06124" } [3]=> array(2) { ["id"]=> string(10) "MONR-05847" ["text"]=> string(63) "FREJUS / OLI'VAP / 2040 RUE DES COMBATTANTS D'AFRI / MONR-05847" } [4]=> array(2) { ["id"]=> string(10) "MONR-03415" ["text"]=> string(79) "BAGNOLS EN FORET / CARREFOUR CONTACT / DEPARTEMENTAL 4 LA ROUVIERE / MONR-03415" } [5]=> array(2) { ["id"]=> string(10) "MONR-05850" ["text"]=> string(53) "FREJUS / SOS PHONE / 169 RUE JEAN JAURES / MONR-05850" } [6]=> array(2) { ["id"]=> string(10) "MONR-94030" ["text"]=> string(88) "FREJUS / FITNESS BOUTIQUE FREJUS / 129 RUE ALERT EINSTEIN, FACE A DAFY MOTO / MONR-94030" } [7]=> array(2) { ["id"]=> string(10) "MONR-99539" ["text"]=> string(75) "SAINT-RAPHAEL / WELDOM ST RAPHAEL / 1205 BOULEVARD JEAN MOULIN / MONR-99539" } [8]=> array(2) { ["id"]=> string(10) "MONR-04322" ["text"]=> string(78) "ST RAPHAEL / AVADI BOUTIQUE CADEAU / 80 AVENUE DU GENERAL LECLERC / MONR-04322" } [9]=> array(2) { ["id"]=> string(10) "MONR-03980" ["text"]=> string(68) "ST RAPHAEL / PHARMACIE DES GENETS / 1416 BD JEAN MOULIN / MONR-03980" } [10]=> array(2) { ["id"]=> string(10) "MONR-03457" ["text"]=> string(55) "FREJUS / COLOR-LAB / 229 RUE ROLAND GARROS / MONR-03457" } [11]=> array(2) { ["id"]=> string(10) "MONR-63070" ["text"]=> string(73) "PUGET SUR ARGENS / AGENCE MONDIAL RELAY / 577 BD DU COMMERCE / MONR-63070" } [12]=> array(2) { ["id"]=> string(10) "MONR-04715" ["text"]=> string(92) "FREJUS / MINERAUX & MERVEILLES / 362 RUE VICTOR REYBAUD, SQUARD LIBERATION PARK / MONR-04715" } [13]=> array(2) { ["id"]=> string(10) "MONR-12297" ["text"]=> string(60) "FREJUS / TABAC PRESSE / 355 RUE HIPPOLYTE FABRE / MONR-12297" } [14]=> array(2) { ["id"]=> string(10) "MONR-04478" ["text"]=> string(61) "STRAPHAEL / EPICERIE / 144 BD GEORGES CLEMENCEAU / MONR-04478" }


text:
Q: Where does Yii Store the user in Sample Web Apps In the sample application created using yiic, yii has two users demo/demo and admin/admin, where does yii stored the user information? what if i wish to add more users and I would want to add it to the database myDB of table myUser, which contains two fields, user name and password?

A: The user info is defined in the components/UserIdentity.pho in an array. So it's super simple at the moment. But if you have a user table, you can easily add a User model look up instead of checking in the users array.

A: If you want to have more users in your app try using user extension for registration and management users accounts. Please follow the instruction in the link and enjoy.

http://www.yiiframework.com/extension/yii-user/


text:
Q: JavaFx program is not responding? when i run this code java not responding with java Result: -805306369 .
this code try to unrar a rar file with junrar.
what is java Result: -805306369 ?
is this error for low memory?
how can i solve it?
thanks.
 String filename = importFile.getAbsolutePath();
    File f = new File(filename);
    Archive a = null;
    try {
        a = new Archive(f);
    } catch (RarException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    if (a != null) {
        FileHeader fh = a.nextFileHeader();
        while (fh != null) {
        try {
                        if(fh.getFileNameString().endsWith(".jml")){
                                    Path tempJml=Files.createTempFile("jml",".jml");
                                    FileOutputStream outJml=new FileOutputStream(tempJml.toFile());
                                    InputStream in=a.getInputStream(fh);
                                     int lenj;
                                      while ((lenj = in.read(buffer))>0 ) {
                                      outJml.write(buffer, 0, lenj);
                                       }
                                    outJml.close();
                                     in.close();
                                  ZipFile zpjml=new ZipFile(tempJml.toFile());
                                   zpjml.stream().forEach((jmlEntry)->{
                                   System.out.println(jmlEntry.getName());
                                   if(jmlEntry.getName().endsWith(".xml")){
                                try {
                                    InputStream x = null;
                                    try {
                                        x = zpjml.getInputStream(jmlEntry);
                                    } catch (IOException ex) {
                                        Logger.getLogger(ConvertController.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                    List<Card> xml = convertXml(x);
                                    if(xml!=null){
                                         xmlPat = createNewXml(xml,jmlEntry.getName());
                                    }
                                    ZipEntry newZe=new ZipEntry(jmlEntry.getName().substring(0,jmlEntry.getName().lastIndexOf("."))+".xml");
                                    zos.putNextEntry(newZe);
                                    InputStream inXml=new FileInputStream(xmlPat);

                                    int len;
                                    while ((len = inXml.read(buffer))>0 ) {
                                        zos.write(buffer, 0, len);
                                    }
                                    zos.closeEntry();
                                    inXml.close();
                                    x.close();
                                    Path temp=Paths.get(xmlPat);
                                    Files.deleteIfExists(temp);
                                } catch (DocumentException ex) {
                                    Logger.getLogger(ConvertController.class.getName()).log(Level.SEVERE, null, ex);
                                } catch (IOException ex) {
                                    Logger.getLogger(ConvertController.class.getName()).log(Level.SEVERE, null, ex);
                                }
                             }else if(jmlEntry.getName().startsWith("images")){
                                 try (InputStream inImag = zpjml.getInputStream(jmlEntry)) {
                                     ZipEntry newZe=new ZipEntry(jmlEntry.getName());
                                zos.putNextEntry(newZe);
                                   int len;
                                   while ((len = inImag.read(buffer)) > 0) {
                                       zos.write(buffer, 0, len);
                                   }

                                   zos.closeEntry();
                                   inImag.close();
                               } catch (IOException ex) {
                                    Logger.getLogger(ConvertController.class.getName()).log(Level.SEVERE, null, ex);
                                }
                             }

                        });

                        }
                    else if(fh.getFileNameString().endsWith(".xml")){
                                    InputStream in=a.getInputStream(fh);
                                    List<Card> xml = convertXml(in);
                                    if(xml!=null){
                                     xmlPath = createNewXml(xml,fh.getFileNameString());
                                    }
                                    ZipEntry newZe=new ZipEntry(fh.getFileNameString().substring(0,fh.getFileNameString().lastIndexOf("."))+".xml");
                                    zos.putNextEntry(newZe);
                                    InputStream inXml = new FileInputStream(xmlPath);
                                       int len;
                                       while ((len = inXml.read(buffer))>0 ) {
                                           zos.write(buffer, 0, len);
                                       }
                                       in.close();
                                       zos.closeEntry();
                                       inXml.close();
                                    }
                    else if(fh.getFileNameString().startsWith("images")){
                                     ZipEntry newZe=new ZipEntry(fh.getFileNameString());
                                     zos.putNextEntry(newZe);
                                       InputStream inFile=a.getInputStream(fh);
                                        int len;
                                          while ((len = inFile.read(buffer))>0 ) {
                                            zos.write(buffer, 0, len);
                                        }

                                        inFile.close();
                                        zos.closeEntry();

                                }else{
                        continue;
                    }
                            }catch(RarException | IOException e){
                                e.printStackTrace();
                            }
            fh = a.nextFileHeader();
        }

    }

             zos.close();


text:
Q: Table showing each JQueryMobile version and its compatibility with JQuery versions? Given that JQueryMobile uses JQuery, I'm looking for a definitive table that lists JQueryMobile versions and which earliest and latest versions of JQuery they can use.
To my great surprise JqueryMobile.com does not seem to have this table, except for the latest version of JQueryMobile and what it is paired with, on the site front landing page.
People will want to use JQueryMobile earlier versions for a number of good reasons, e.g. if there is regression in later versions, other compatibility issues or just not ready to move up to the latest version (risks to project for example).


text:
Q: MySQL (+), the meaning? SELECT d.deptname, d.deptlocation, e.empname
FROM payroll.employee e, payroll.department d
WHERE e.deptno(+) = d.deptno
ORDER BY d.deptname, e.empname;

What does the (+) mean? Is that mean from employee table deptno Can be null?

A: this is an old ORACLE-syntax to create OUTER JOINs. in your case, it means the same as
[...]
FROM
  payroll.department d
LEFT OUTER JOIN
  payroll.employee e
ON
  e.deptno = d.deptno
[...]

as others said in the comments, it's not valid in MySQL.


text:
Q: SonarQube VSTS Marketplace Extension I downloaded the extension from
https://marketplace.visualstudio.com/items?itemName=SonarSource.sonarqube#review-details,
for TFS 2015 on premise, installed it in my collection and created and end point. Then I configured 2 steps as indicated before and after my build, I am getting the following error

[error]The MSBuild.SonarQube.Runner executable could not be found. Check that the build definition includes a SonarQube Pre-Build step

My sonar server Version is 5.6.3 running on Linux fedora. Do I need to install any other tools? I understand that The SonarQube Extension embeds its own version of the SonarQube Scanner for MSBuild. The first step before the build executes correctly, the build succeed but the end step fails.
Thanks in advance for your help


text:
Q: Camel RabbitMQ creates a generated queue in addition to the routing the msg to the queue I have an exchange setup amq.topic and in there I have a routing key that is pointing to my key.
I have a route defined with a rest endpoint.  I make a call to that endpoint with a body as json {"sample" : "sample"}.
  rest("myendpoint")
                .post()
                .route()
                .routeId(ROUTE_ID)
                .log(ROUTE_ID + " started.")
                .convertBodyTo(String.class)
                .log("Receiving request with body=${body}")
                .to("rabbitmq://rabbiturl:port/amq.topic?connectionFactory=rabbitmqConnectionFactory&autoDelete=false&routingKey=myroutingkey&declare=false&exchangeType=topic")
                .log(ROUTE_ID + " ended.")
                .end();

This accomplishes what I want to: the body of my rest call will be sent to the topic exchange of which will go to my queue based on the routing key.
The problem: It also create an auto-generated queue
 [                qtp86171426-28] RabbitMQProducer               INFO  Starting reply manager service RabbitMQReplyManagerTimeoutChecker[amq.topic]
[                qtp86171426-28] ReplyManagerSupport            INFO  Using temporary queue name: amq.gen-JGF0CKioQ6_MLA9uBNIOOQ
[                qtp86171426-28] CorrelationTimeoutMap          INFO  in putIfAbsent with key Camel-ID-L-VC-10050-58983-1467158153454-0-3
[nagerTimeoutChecker[amq.topic]] TemporaryQueueReplyHandler     INFO  in onTimeout with correlationId= Camel-ID-L-VC-10050-58983-1467158153454-0-3
[nagerTimeoutChecker[amq.topic]] ReplyManagerSupport            WARN  Timeout occurred after 20000 millis waiting for reply message with correlationID [Camel-ID-L-VC-10050-58983-1467158153454-0-3] on destination amq.gen-JGF0CKioQ6_MLA9uBNIOOQ. Setting ExchangeTimedOutException on (MessageId: ID-L-VC-10050-58983-1467158153454-0-2 on ExchangeId: ID-L-VC-10050-58983-1467158153454-0-1) and continue routing.

I have tried skipqueuedeclare & skipexchangedeclare and am running out of ideas of why it is generating the queue.  Does anyone have any ideas?

A: Set ExchangePattern to InOnly.
The temporary and reply queue is because the route expects a reply back so creates the temporary queue to wait for a response.
So if your rest endpoint does not return anything set the ExchangePattern to Inonly at the rest call and it should be ok. Alternatively set it at .to().


text:
Q: Define variable and echo in function I'm creating a WordPress plugin to bring in fields from a XenForo forum and display them in WordPress.
I have a file called xf_connector.php which has the following code:
<?php

$startTime = microtime(true);
$fileDir = 'C:\Domains\xxxx.com\httpdocs\forums';

require($fileDir . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader($fileDir . '/library');

XenForo_Application::initialize($fileDir . '/library', $fileDir);
XenForo_Application::set('page_start_time', $startTime);

XenForo_Session::startPublicSession();

$visitor = XenForo_Visitor::getInstance()->toArray();
?>

And then a separate file called xf.php which has the following code:

Hello <?php $xf_userId = $visitor['user_id'];
$xf_username = $visitor['username'];
echo "$xf_username" ?> welcome to this web page.

Hello <?php $xf_userId = $visitor['user_id'];
$xf_username = $visitor['username'];
echo "$xf_username" ?> welcome to this web page.

This works fine in a blank document but does not work in the WordPress plugin. My plugin file is currently:
include_once( plugin_dir_path( __FILE__ ) . '/includes/xf_connector.php' );

function xenfield_shortcode() {
  ob_start(); ?>

<?php $xf_userId = $visitor['user_id'];
$xf_username = $visitor['username'];
echo "$xf_username" ?>

  <?php    return ob_get_clean();
}
add_shortcode( 'xenfield', 'xenfield_shortcode' );

This displays nothing on the WordPress page and if I look at the HTML it just shows empty
 tags.
How can I define a variable and echo it in the same file so it displays in WordPress?

A: $visitor is not defined in your function xenfield_shortcode(). I guess that this will work:
include_once( plugin_dir_path( __FILE__ ) . '/includes/xf_connector.php' );

function xenfield_shortcode() {
  $visitor = XenForo_Visitor::getInstance()->toArray();

  ob_start(); ?>

<?php $xf_userId = $visitor['user_id'];
$xf_username = $visitor['username'];
echo "$xf_username" ?>

  <?php    return ob_get_clean();
}
add_shortcode( 'xenfield', 'xenfield_shortcode' );

And while we are at it, this makes it much more readable:
include_once( plugin_dir_path( __FILE__ ) . '/includes/xf_connector.php' );

function xenfield_shortcode() {
    $visitor = XenForo_Visitor::getInstance()->toArray();

    $output = '
';
    $output .= $visitor['username'];
    $output .= '
';

    return $output;
}
add_shortcode( 'xenfield', 'xenfield_shortcode' );


text:
Q: Autodesk Revit in particular doesn't work in WMR desktop I'm trying to use Revit in VR while inside a realtime rendering of the model. WMR desktop doesn't let me click on the toolbars but SteamVR desktop does.
See this link to a video of the issue: https://www.dropbox.com/s/5inunjyj9jx8w0i/WMR%20Issue.mp4?dl=0
Thanks


text:
Q: CMAKE MinGW Compiler flag -finstrument-functions I am trying to debug a flow and for which I am trying to make use of -finstrument-functions compiler option. I have successfully written up below method and created trace.o object file:
void __cyg_profile_func_enter(void* this_fn, void* call_site)
__attribute__((no_instrument_function));
void __cyg_profile_func_exit(void* this_fn, void* call_site)
__attribute__((no_instrument_function));

It works well with sample code and I get function address logged in file from where I can extract file:function name.
In our project code there around 1500 files so I have added the below code in my CMakeLists.txt file:
SET(GCC_COVERAGE_COMPILE_FLAGS "-finstrument-functions")
add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})

The above config ensures that all my source code files are compiled with -finstrument-functions compiler flag.
To ensure that I link trace.o file I am trying the below method:
SET(OBJS
  /c/work/trace.o #path to trace.o in my system
)

SET_SOURCE_FILES_PROPERTIES(
  ${OBJS}
  PROPERTIES
  EXTERNAL_OBJECT true
  GENERATED true
)

But during compilation of my project code I get below error:
    Test.cpp.obj: In function `cc::cppx::cMethod(int, int*, int&)':
    Test.cpp:16: undefined reference to `__cyg_profile_func_enter'
    Test.cpp:17: undefined reference to `__cyg_profile_func_exit'
    Test.cpp.obj: In function `__gthread_active_p':
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/x86_64-w64-mingw32/bits/gthr-default.h:304: undefined reference to `__cyg_profile_func_enter'
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/x86_64-w64-mingw32/bits/gthr-default.h:304: undefined reference to `__cyg_profile_func_exit'
    Test.cpp.obj: In function `__exchange_and_add_single':
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/ext/atomicity.h:66: undefined reference to `__cyg_profile_func_enter'
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/ext/atomicity.h:68: undefined reference to `__cyg_profile_func_exit'
    Test.cpp.obj: In function `forward<cc::cppx::TestInvoke_lambda_with_args_byvalue_ptr_ref_Test::TestBody()::<lambda(int, int*, int&)>&>':
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/bits/move.h:76: undefined reference to `__cyg_profile_func_enter'
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/bits/move.h:76: undefined reference to `__cyg_profile_func_exit'
    Test.cpp.obj: In function `operator()':
    Test.cpp:54: undefined reference to `__cyg_profile_func_enter'
    Test.cpp:56: undefined reference to `__cyg_profile_func_exit'
    Test.cpp.obj: In function `__exchange_and_add':
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/ext/atomicity.h:49: undefined reference to `__cyg_profile_func_enter'
    C:/tools/mingw64/x86_64-w64-mingw32/include/c++/ext/atomicity.h:49: undefined reference to `__cyg_profile_func_exit'
    Test.cpp.obj: In function `__tcf_0':

I am trying hard to find ways how to achieve my objective but it is not sorting the issue - is there a way the same can be setup?


text:
Q: How to create a monad using StateT, ContT, and ReaderT? How do I create a monad which uses State, Cont, and Reader transformers? I would like to read an environment, and update/use state. However, I would also like to pause/interrupt the action. For example, if a condition is met, the state remains unchanged.
So far I have a monad using ReaderT and StateT, but I cannot work out how to include ContT:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Test where
-- monads
import   Data.Functor.Identity (Identity, runIdentity)
import   Control.Monad.State
import   Control.Monad.Reader
import   Control.Monad.Cont

-- reader environment
type In = Integer

-- cont: if true then pause, else continue
type Pause = Bool

-- state environment:
newtype StateType = StateType { s :: Integer }

newtype M r = M {_unM :: ReaderT In (ContT Pause (StateT StateType Identity)) r}
  deriving ( Functor, Applicative, Monad
           , MonadReader In
           , MonadCont   Pause
           , MonadState  StateType
           )

-- run monadic action
runM :: In -> Pause -> StateType -> M r -> StateType
runM inp pause initial act
  = runIdentity             -- unwrap identity
  $ flip execStateT initial -- unwrap state
  $ flip runContT   pause   -- unwrap cont
  $ flip runReaderT inp     -- unwrap reader
  $ _unM act                -- unwrap action

This gives the error:
* Expected kind `* -> *', but `Pause' has kind `*'
* In the first argument of `MonadCont', namely `Pause'
  In the newtype declaration for `M'
  |
24|         , MonadCont  Pause
  |

Ok, but why does Pause need kind * -> *?... I'm drowning in types, in need of explanation. What form does Pause have to take, a function? How does ContT integrate? Ultimately, I plan to use Cont for a control structure.

A: Unlike MonadReader and MonadState, the MonadCont type class takes only one parameter.  Since that parameter m must be a Monad, it must have kind * -> *.
In your deriving clause, you want MonadCont, not MonadCont Pause.
added in response to followup question:
ContT is defined as:
newtype ContT r m a = ContT { runContT :: (a -> m r) -> m r }

Note that the r in your definition of newtype M r is passed as the final (a) parameter to ContT.  Plugging in the variables, you have
ContT Bool (State StateType) a = ContT {
    runContT :: (a -> State StateType Bool) -> (State StateType Bool)
  }

This provides a computational context in which you can manipulate the StateType, and use delimited continuations.  Eventually, you will construct a ContT Bool (State StateType) Bool.  Then you can run the continuation (with evalContT), and return to the simpler State StateType context.  (In practice, you may unwrap all 3 of your monad transformers in the same part of your program.)


text:
Q: PECL OAuth-1.2.2 for Windows I'm trying to get PECL OAuth to work on a Windows dev box (using WAMP). I found two dlls for older versions at Pierre's site but neither of them seem to work.
Adding the DLL to the relevant wamp\bin\php\php5.x.x\ext directory and then ticking the option in the PHP extensions flyout does not add anything OAuth related to the output of phpinfo() and if I try to instantiate an OAuth object I get a "Class 'OAuth' not found" error.
Is there anywhere (or any way) that I can get hold of working DLLs (ideally for the latest 1.2.2 version of OAuth, but any 1.0 or higher stable version will do). The maching in question is running 32bit Windows (Vista).
I hope somebody can help where Google has failed me so far...!
Thanks in advance,
Christian

A: I'm just barely beginning to delve into this whole thing, so I'm not quite sure which way is up, but does this article on  oAuth, Xampp, and Windows, scroll down for the English, do the trick?
Let me know as I'm eager to figure all this out too!
And/or would one be able to  build it with windows?


text:
Q: Building Android in ionic failed with transformClassesWithDexBuilderForDebug for process okhttp-3.13.1.jar While trying to build an android platform in ionic 2 after updating android studio this error started showing up.
  Ionic Info:

   ionic (Ionic CLI)  : 4.3.0 (/usr/local/lib/node_modules/ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.1.9

Cordova:

   cordova (Cordova CLI) : 8.1.2 (cordova-lib@8.1.1)
   Cordova Platforms     : android 6.4.0
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 1.2.1, (and 15 other plugins)

System:

   NodeJS : v8.12.0 (/usr/local/bin/node)
   npm    : 6.4.1
   OS     : macOS Sierra
   Xcode  : Xcode 8.3.2 Build version 8E2002

FAILURE: Build failed with an exception.
What went wrong:
Execution failed for task ':transformClassesWithDexBuilderForDebug'. >

com.android.build.api.transform.TransformException:
  com.android.builder.dexing.DexArchiveBuilderException:
  com.android.builder.dexing.DexArchiveBuilderException:
Failed to process /.gradle/caches/modules-2/files-2.1/com.squareup.okhttp3/okhttp/3.13.1/b49cf3799bd473199e96c4fb9987e9e08395a1c0/okhttp-3.13.1.jar

Found that Dexbuilder error is related to Java version 8.

A: Modifying these options in "Build.Gradle" file inside /platforms/android folder solved the issue
compileOptions {
   sourceCompatibility JavaVersion.VERSION_1_8
   targetCompatibility JavaVersion.VERSION_1_8
}


text:
Q: Nuget package installed even if it is not included in project I have npgsql and npgsql.entityframeworkcore.postgresql nuget packges being installed every time when I build my solution although they are not included in my project.
They are creating me problem because there are some ambiguous extension methods so I would like to remove them.
The question is, are they maybe installed as dependency by some other library that I use and is there way that I could check that?


text:
Q: How to fix Fedora Yum Repo I'm tyring to do this
$ sudo yum install gnome-tweak-tool

And I get this instant response:
Loaded plugins: langpacks, presto, refresh-packagekit
http://yum.postgresql.org/9.1/redhat/rhel-18-x86_64/repodata/repomd.xml: [Errno 14] HTTP Error 404 - Not Found : http://yum.postgresql.org/9.1/redhat/rhel-18-x86_64/repodata/repomd.xml
Trying other mirror.
Error: failure: repodata/repomd.xml from pgdg91: [Errno 256] No more mirrors to try.
http://yum.postgresql.org/9.1/redhat/rhel-18-x86_64/repodata/repomd.xml: [Errno 14] HTTP Error 404 - Not Found : http://yum.postgresql.org/9.1/redhat/rhel-18-x86_64/repodata/repomd.xml

I think I messed up the yum repo, is there a way to fix this?


text:
Q: Increase space between axis titles and axis using tmap in R I'm having an issue with finding answers for a fairly simple question. I just need to move the axis titles (xlab and ylab) away from the axes. I haven't uploaded reproducible data since the files are large shapefiles, but I can upload it if needed (I figure it's a fairly straightforward answer). I have attached the code I've used so far as well as the map I'm struggling with:
LandUseMap <- tm_shape(LandUseshape, ylim = c(50.45, 50.68), xlim=c(-105,
-104.7), projection = "longlat") +
tm_fill("COVTYPE", title = "Land Cover Type",style="fixed",breaks=c(20,30,34,50,110,121,122,220,230),
      labels=c("Water","Non-Vegetated Land","Developed","Shrubland","Grassland","Annual Cropland","Perennial Crops/Pasture","Broadleaf","No Data"),
      palette=manualpal)  +
tm_borders("grey") +
tm_legend(outside = TRUE, text.size = .65) +
tm_layout(frame = FALSE,asp =NA, outer.margins = c(0.05,0.1,0,0), inner.margins = c(0.05,0.05,0.01,0.05))+
tm_grid(y=c(50.45, 50.50, 50.55, 50.60, 50.65), x=c(-105.0,-104.9,-104.8,-104.7),labels.inside.frame = FALSE, col = "#00ff0000",
      labels.size =0.8)+
tm_xlab("Longitude", size = 1)+
tm_ylab("Latitude", size = 1)+
tm_scale_bar(size = 1, position = c(0,0.8)) +
tm_compass(size=2.5,north = 0,position = c(0,0.9))
LandUseMap

Here's the map:


text:
Q: tableViewSelectionDidChange does not work in Xcode 8 After upgrading to MacOS Sierra, and consequently for Xcode 8, the tableViewSelectionDidChange function does not work anymore. I think my code is correct.
func tableViewSelectionDidChange(_ notification: Notification) {

if let selectedRow = (notification.object as AnyObject).selectedRow {
    if ( selectedRow > -1 ) {
        selectedItem = data[selectedRow]
        if let nome = selectedItem?.value(forKey: "nome") as? String {
            nomeField.stringValue = nome
        } else {
            blankOutField(nomeField)
        }

override func viewDidLoad() {
    super.viewDidLoad()
    let appDelegate = NSApplication.shared().delegate as! AppDelegate
    managedContext = appDelegate.managedObjectContext
    tableView.delegate = self
    tableView.dataSource = self
    fetchDataAndRefreshTable()
}

func fetchDataAndRefreshTable() {
    let fetchRequest = NSFetchRequest<NSFetchRequestResult> (entityName: "CadastroPacientes")
    let sortDescriptor = NSSortDescriptor(key: "nome", ascending: true, selector: #selector(NSString.localizedStandardCompare(_:)))
    fetchRequest.sortDescriptors = [sortDescriptor]
    do {
        data = try managedContext!.fetch(fetchRequest) as! [NSManagedObject]
    } catch {
        Swift.print(error)
    }
}

I cannot find the solution because it seems that the line is not selected, nothing happens when I click the line in the TableView.
The program is using Core Data. Everything worked perfectly before.

A: Change selectedRow > -1 to selectedRow >= -1 because Binary operator '>' cannot be applied to operands of type Int.... NEXT If you can change selectedItem to selectedRow Those are the main errors that I get when I try and run your code


text:
Q: Convergence in Probability and in Quadratic Mean for a sequence of random variables I have been trying to determine whether a sequence of random variables, $X_1,X_2,\ldots,X_n$, such that
$$P\left(X_n= \frac{1}{n}\right)=1-\frac{1}{n^2}\\ \text{and}\\ P\left(X_n=n\right)=\frac{1}{n^2}$$
converges in probabily and in quadratic mean. I know that convergence in qm implies convergence in probability but what would be a limit candidate for that case? Also, how can I prove or disprove the convergence in probability independently of the convergence in qm?
Thank you.

A: *

*For convergence in m.s check that $E[|X_n - 0|^2] = n^2.\frac{1}{n^2} + \frac{1}{n^2}(1 - \frac{1}{n^2} )$ which tends to $1$ as $n \rightarrow \infty$. Therefore, it does not converge to $0$ in m.s.

*For, convergence in probability, note that for any $\epsilon > 0$ for $n > \frac{1}{\epsilon}$ , $Pr(|X_n - 0| > \epsilon)  = \frac{1}{n^2} $. This goes to $0$ as $n \rightarrow \infty$. Therefore $X_n \rightarrow 0$ in probability.


text:
Q: Why are the Fourier's coefficient on $0,2\pi$ and $-\pi,\pi$ the same? I was given the Following Fourier's coefficient and I was happy with it:
$$\left\{
    \begin{array}{ll}
a_n(f)=\frac{1}{\pi} \int_{0}^{2\pi} f(x) \cos\left(nx\right)\,\mathrm{d}x\\
b_n(f) = \frac{2}{\pi} \int_{0}^{2\pi} f(x) \sin\left(nx\right)\,\mathrm{d}x
    \end{array}
\right.$$
but I had an exercise:

Let be the function $f$ with a period of $2\pi$ defined for all $x\in[-\infty,\infty[$ by $f(x)=x$. Find the Fourier's coefficient associated to $f$.

and the formulas used in the correction were:

$$\left\{
    \begin{array}{ll}
a_n(f)=\frac{1}{\pi} \int_{\pi}^{-\pi} f(x) \cos\left(nx\right)\,\mathrm{d}x\\
b_n(f) = \frac{2}{\pi} \int_{\pi}^{-\pi} f(x) \sin\left(nx\right)\,\mathrm{d}x
    \end{array}
\right.$$

I feel that its the same formulas. But I can't see it...
Can you help me see why are they alike?

Okay, from Wikipedia it is:
$$\left\{
    \begin{array}{ll}
a_n(f)=\frac{2}{T} \int_{-T/2}^{T/2} f(t) \cos\left(nt\frac{2\pi}{T}\right)\,\mathrm{d}t\\
b_n(f) = \frac{2}{T} \int_{-T/2}^{T/2} f(t) \sin\left(nt\frac{2\pi}{T}\right)\,\mathrm{d}t
    \end{array}
\right.$$

A: The functions are periodic, so the integral over an interval of period length does not depend on the choice of endpoints:
$$\int_a^{a+2\pi} f(t)dt = \int_0^{2\pi} f(t)dt $$
for any real $a$, in case the period is $2\pi$. To prove this look at the coordinate transformation $t\mapsto t+a$ and make use of $f(t)=f(t+2\pi).$


text:
Q: Xcode Unit Test: Assert async throw/nothrow I have an object which accepts an block as call back, like this
@interface MyObject

@property(nonatomic, copy) (void(^)()) callback;
- (void)trigger;

@end

When trigger is called, callback will be called asynchronously in 1 second, I want to write a test to make sure that if I set nil to callback, it won't crash due to calling a nil block.
How to do this?


text:
Q: Python script making multiple web requests to update values using threading.Timer I am currently writing a python script that needs to stay running on a linux server. The main function of the script called calculateValues() is responsible for running every 30 seconds and using the latest values of value1, value2, value3 in its actions such as sending notifications based on thresholds.
Each one of the values will have a different update frequency. Notice how one of them needs to make an api request and be updated every 100 seconds, another every 5000 seconds, and another every 84000 seconds. Regardless of when these values update the calculateValues function will be running every 30 seconds and using whatever the current value1, value2, value3 values are at that time in its work.
A few questions I have:

*

*Am I going about this the correct way using threading.Timer? I noticed there is also a sched feature that seemed pretty cool, but didn't see the point in using it since it looked like it is mostly used for delaying a certain amount of time and then running a function.

*In order to run this script on a linux box 24/7 would the best way just be to move the code to it and run the main python file in terminal and just leave it open? Or should I be packaging this up as an actual python application?

*Any recommendations on how this code is structured/written would be helpful as well. Something seems off about this global variable approach I am taking.
Below is a sample of the script:
#!/usr/bin/env python3

import threading

value1 = None
value2 = None
value3 = None

def calculateValues():
    threading.Timer(30, calculateValues).start()
    print('Value 1: ' + str(value1))
    print('Value 2: ' + str(value2))
    print('Value 3: ' + str(value3))

    # Do something with these values here every 30 seconds

def updateValue1():
    threading.Timer(100, updateValue1).start()
    # make request to web api to get latest value1
    valueFromRequest = 1000
    # update global var value1
    global value1
    value1 = valueFromRequest

def updateValue2():
    threading.Timer(5000, updateValue2).start()
    # make request to web api to get latest value2
    valueFromRequest = 1000
    # update global var value2
    global value2
    value2 = valueFromRequest

def updateValue3():
    threading.Timer(84000, updateValue3).start()
    # make request to web api to get latest value3
    valueFromRequest = 1000
    # update global var value3
    global value3
    value3 = valueFromRequest

updateValue1()
updateValue2()
updateValue3()
calculateValues()

A:
Am I going about this the correct way using threading.Timer? I noticed there is also a sched feature that seemed pretty cool, but didn't see the point in using it since it looked like it is mostly used for delaying a certain amount of time and then running a function.

This SO answer seems to discuss about the difference and need for sched and threading.Timer

In order to run this script on a linux box 24/7 would the best way just be to move the code to it and run the main python file in terminal and just leave it open? Or should I be packaging this up as an actual python application?

If you're using threading.Timer just for scheduling the next job, the best would be adding a cron job in the linux box and let the cron handle the work.

Any recommendations on how this code is structured/written would be helpful as well. Something seems off about this global variable approach I am taking.

If you're going with the cron job way of executing, it would be best to pass some arguments to the file and execute the required method and there wouldn't be a need for Timer itself.


text:
Q: Mac Joining Active Directory Still Prompts For Authentication My Mac is joined to an Active Directory domain. What I expected to see was the same ease of access to file shares and internal websites that Windows computers joined to the domain experience (i.e., no authentication needed; it just uses Windows Integrated Authentication). Instead I am asked for credentials each time I try to access those shares and protected websites (e.g. SharePoint).
Is this normal behavior, or is something wrong with my Mac that it prompts me for my username and password for the domain when I access Windows file shares or intranet sites protected by NTLM/Kerberos?
Machines include:

*

*MacBook Pros running Mountain Lion

*MacBook Pros running Lion

*MacServer running Lion Server

A: No, for shared drives (smb) you should not have to authenticate as long as you log in to OS X with a domain account (not a local machine account).  You should be able to Finder->Go->Connect To Server and specify an address such as smb://hostname/sharename to connect.
As for website authentication, it's a little trickier.  I know on windows certain browsers do not attempt to authenticate automatically, ie Firefox.  You have to configure it.  Internet Explorer & Chrome both do this automatically out of the box.
I verified on OS X, Safari does use the login credentials to authenticate, but if you have a self-signed ssl certificate, you must add it as a trusted certificate.  Otherwise it prompts for the password.  Chrome does not do this authentication, you'll have to do some research, it might be possible to get 3rd party browsers to authenticate with login credentials on OS X, but it doesn't work without configuration.


text:
Q: What does "to be golfed-out" mean? What does "to be golfed-out" mean in the dialog below ?

*

*I'm going to the golf tomorrow morning, do you want to join ?

*Thanks! But I'm pretty golfed-out! Just back from Thailand after 2
  weeks of golf 12 games .

A: "I'm pretty golfed-out!" means "Right now, I have done enough golfing, so I am too tired (of golfing) to do more."  Person 2 in the quoted dialog is giving an explanation in order to politely refuse Person 1's offer/suggestion.
An expression like "(I am all) X-ed out" can be used as a slangy or informal way of saying "I have done enough of X". This may have arisen by analogy with the expressions "tired out" and "worn out". Other examples:

*

*"All Gamed Out?" in the sense "tired of games/not feeling like playing games"

*"all photoed out" in the sense "tired of taking photos" : description of this image, body of this blog post

*"all oystered out" in the following article: "The Foodist's 10 Favorite Oyster Bars Across America", by Andrew Knowlton

A: It means that you have played all the golf that you can.
Metaphorically, you don't have anything golf left in you still to play.
This meaning of the word comes from one of the senses of the definition of out:

[Merriam-Webster]
adverb
3 a : to the point of depletion, extinction, or exhaustion
// the food ran out
// turn the light out
// all tuckered out

It's the last example in particular that's relevant. The construction of this type of expression is I'm all [verbed] out. (Although a noun can also be used.)


text:
Q: Men In Black:  After Agent K's retirement, why was Agent J left as senior partner? From my limited understanding, generally police-type agencies partner an experienced senior agent/detective with a junior one.
However, at the end of "Men In Black" movie, Agent K announces that he's ready to retire and he has been training Agent J as replacement:

I haven't been looking for a partner. I've been looking for a replacement.

Now, Agent J is a brand new green rookie - he was hired just a couple of days before (based on my understanding of movies' timeline); and doesn't know anything; see the scenes with Agent K explains obvious beginner type stuff to J, including how to identify a bug, or general methods and mission of MIB, or hell, the starting-off on the job:

Kay: Cool, whatever you say, slick, but I need to tell you something about all your skills. As of right now, they mean precisely... dick.

So, how come Agent J ends up being the senior partner once Agent K retires, instead of being partnered up with another senior agent till he stops being such a rookie?
NOTE: I'm specifically asking about the very end of MIB1, where Agent J is a senior partner to agent L - not about eventual MIB2 where J is obviously more experienced and more likely qualifies to be a senior partner.

A: This is dealt with in the official novelisation. Although the film cuts immediately to the next scene, in reality there has been a pretty reasonable gap since Jay flashy-thing'd Kay. During this interregnum, Jay has evidently been receiving one-on-one tutoring from Zed and has become something of an expert in MiB's daily operations:

The summer was winding down, he'd learned a whole bunch of stuff from
Zed in a real short time, and things were looking better. No more
bugs, at least, the A's and B's had taken their galaxy and gone home.
At least the world didn't depend on his next move. Not today, anyhow.
Now, he was doing a little research

...

"How long do we keep doing this? I mean, without letting the secret out?"
"Long as the neuralyzers work, I guess."
"Come on, Jay. You know what I mean."
He nodded. Yeah, he knew. He shook his head. "I don't know. Kay and I weren't together too long and not really much into policy, being kinda busy and all. We're just the street cops. I guess we just keep plugging the holes in the dike until somebody upstairs decides the world is ready to know there really are aliens among us."

Although she's extremely book-smart, obviously Elle is going to be the junior partner in their team given her relative lack of policing experience.

A: I don't have any concrete canon information to back this up, but:
My guess would be that there are a limited number of people who they (the MiB org) would consider as a field agent, as the field agents likely get exposed to a slew of more exotic experiences than the people who work on base. Therefore they would need people who can handle all the weirdness on a constant basis and not break down. Secondly, they would also want an agent that is already familiar with the retiring agent's patrol region; in this case NYC and the surrounding area. This would limit agent's getting lost when on duty or making cultural gaffes when trying to make up new histories for the people they flash.
Considering the two above points, which may or may not be valid, it may take a considerable amount of time to find someone who can work in the field. After all, by the start of MiB2 agent J had retired a number of candidates and was in the process of washing another. Zed, while upset at having lost another candidate, was not overly discouraged, which would seem to indicate that it was not uncommon for it to take a while to find agents. Add to this that the field agents seem to work in pairs (at the start of MiB there was only K and his partner) there just may have not been another unpaired senior agent available in the NYC area.

A: Agent J was accepted into the MiB - despite the obvious advantages of all his competition - because of his skills.
K's statement that his skills meant 'dick' was a way of telling the newbie "Listen, punk, don't think you're hot shit.  You're still too green."  It was not a way of saying, "Everyone else here is just as good."
J is still among the best of the best.  He lacks book knowledge, but he has good instincts, a strong leadership drive, and a charismatic personality that allows him to function effectively in situations where he isn't entirely sure what to do.  While he may make mistakes on occasion, he DOES learn from them.
The situation faced in MiB1 is portrayed as a fairly serious one.  J is integral in stopping it, learning a significant amount of the upper-tier fieldcraft in the process.
Most likely, J was partnered with L, and they were teamed up with a more experienced pair 'to train L' (and, by osmosis, J) with J as nominal leader.  By the end of L's tenure in the MiB, J would have gained the experience required for his actual position.
Zed didn't get to be the leader of the MiB by being oblivious to personality types, the subtleties of complex social interactions, and the need for experience.  J was hand-selected by his best field agent as his most likely successor, and Zed would have taken care to put him into situations where J could make mistakes without causing problems - helping him gain the experience he'd need.
As we can see in MiB2, it apparently worked.

A: One answer: MiBII is five years after MiB.  In that time, presumably J has gained enough experience to lead a team.  K, by contrast is out of practice, and may need bringing back up to speed.  For this purpose he was assigned to a partner he was familiar with.
Another answer: "If you're wondering how he eats and breathes, or other science facts, repeat to yourself 'It's just a show, I should really just relax'."  Or rather the way in which it was arranged was chosen mostly for the convenience of setting up the film, and the logic of it may not survive too much close examination.

A: You could presume that Zed trusted Kay's judgement, I really do think its as simple as that. He probably had to do some formal training or something but I think it would take a special kind of person to be an agent and Zed and Kay could recognize it.


text:
Q: C++ Build warning in GCC ARM but not MS x86 I use the Airplay SDK which is a platform for building C++ apps for smartphones. It also has a x86 simulator which uses MS Visual C++ IDE + compiler.
Now, I have this class :
namespace Fair {

    class Bitmap : public Sprite {

    public:

        const CIw2DImage* const& getBitmapData() { return bitmapData; }; // warning: returning reference to temporary

    private:

        CIw2DImage* bitmapData;
    };

}

I get the above warning if I build with GCC (ARM) Debug. I don't get a warning with (x86) Debug.
I asked elsewhere and I got this reply :

Because `const CIw2DImage* const' is a
  const pointer to const CIw2DImage, and
  Bitmap::bitmapData is a pointer to
  non-const CIw2DImage compiler
  automatically casts pointer to
  non-const to const, so here's a
  temporary. The following code might be
  generated by a "typical" compiler:
const CIw2DImage* const& getBitmapData() {
    const CIw2DImage* const tmp = bitmapData;
    return tmp;
}

Probably (x86) compiler doesn't detect
  this problem.
You might want to remove reference
  symbol (&) from the prototype (why do
  you want use a reference in this
  case?)

If a compiler does that, then it's totally wrong practice..? Making the value returned more "strict" is simply at compiler-level, to prevent "abuse". (x86) doesn't detect because it doesn't "cause" the problem in the 1st case..?
I return a reference to a pointer for the sole reason to "save" 32 bits of memory, i.e. use the same block of memory as the bitmapData pointer but within a different context.
Any comments please?

A: The compiler is quite correct to do that. A reference must refer to an object of the correct type; here you have an object of type CIw2DImage*, and you need a reference to a different type, const CIw2DImage*. The only way to do this is to create a temporary of the correct type (which is possible here, since const T* can be implicitly converted to T*), and return a reference to that.
Unfortunately, that results in a reference to a temporary object in the scope of the function, which is no longer valid once the function returns.
The simplest solution is to return the pointer by value; this will be more efficient (as it avoids an unnecessary level of indirection), as well as avoiding this problem.

A: You won't save any memory at all returning a reference, it's just a pointer internally. In addition, const occurs completely at compile-time, there's no reason for any temporary to be produced- and even if it was, a const reference to it would be valid.
That code looks terrible to me personally but it's not undefined in any way.


text:
Q: On which Stack Exchange site should I ask a question about GitLab/StackEdit? I just created a GitLab application to connect it with StackEdit.io. I had to create the GitLab application with api scope and I had to uncheck confidential due to 1 and 2. I'm not very familiar with OAuth and was wondering about the privacy risks.

api Grants complete read/write access to the API, including all groups and projects, the container registry, and the package registry.

confidential The application will be used where the client secrets can be kept confidential. Native mobile apps and single-page applications are considered non-confidential.

A: GitLab is a web application and we have a Web Applications site. It even has a gitlab tag.

For questions about GitLab - a repository manager which lets teams collaborate on code.

There's also an Information Security site if your questions are specifically about security. That site has an oauth tag.

OAuth is an open standard for authorizing access to data. It is a service that is complementary to, but distinct from, OpenID.

As always check the site's help centres (https://webapps.stackexchange.com/help and https://security.stackexchange.com/help) and maybe look at the existing questions in those tags to see if your question is a good fit.


text:
Q: Determine the straight line which starts at $(1,2,3)$ when $t=1$ and passes through $(1,-7,21)$ when $t=10$ Can someone please explain highlighted steps? $\color{red}{*}$
A direction vector of line is given by $$v=(1,-7,21)-(1,2,3) \Rightarrow (0,-9,18)$$
The equation of line is $$r=(1,2,3)+\lambda(0,-9,18)$$
Setting $t_0=1$ and $t_1=10$ and choosing $\color{red}{*}$
$$\lambda=\frac{t-t_0}{t_1-t_0} \Rightarrow \frac{t-1}{9}\color{red}{*}$$
gives the result: $$r=(1,2,3)+\frac{t-1}{9}(0,-9,18)$$

A: I think $t_0$ represent initial point and $t_1$ point through which line is passing.
After that is formula to find $\lambda$.

A: When $\lambda=0$, $r=(1,2,3)$, and when $\lambda=1$, $r=(1,-7,21)$. We replace $\lambda$ by $at+b$, so we have to find $a$ and $b$ such that when $t=t_0=1$, $\lambda=0$ and when $t=t_1=10$, $\lambda=1$. This gives you a pair of linear equations in the unknowns $a$ and $b$, from which simple algebra will lead you to the solution $a=\frac1{t_1-t_0}$, $b=-{t_0\over t_1-t_0}$, which means that $\lambda={t-t_0\over t_1-t_0}$.


text:
Q: python nlp - how to start token id from 1 after a blank line for every sentence I have tokenized text in a .txt file as follows:
token_1
token_2
token_3

token_4
token_5

Tokens 1, 2 and 3 constitute the first sentence and token 4 and 5 constitute the second sentence. There are two blank lines between the last token of the first sentence and the first token of the second sentence. (Actually I have two versions of that file, one has two blank lines between the sentences and the other one has no blank lines)
I need the token id to start from 1 for every sentence.
My output should be as follows:
1 token_1
2 token_2
3 token_3

1 token_4
2 token_5

I know I could get an incrementing id for all by
id = 0
for token in doc:
id += 1

but the id continues as 4 and 5 in the second sentence.
Thanks in advance.

A: Just reset your counter at the end of a sentence. You may find the end of a sentence using a sentence detector (or two blank lines in your case).
In,
for token in doc:
  id=id+1

if the detected token is a newline, reset the id to 1.


text:
Q: Show existence and find the value of the limit Show that $$\frac{\tanh(x)-1}{e^{-2x}}$$ has a limit for $x \rightarrow \infty$ and the method to finding it.
I am guessing I have to use epsilon-delta-definitions for limits and then find a inequality that narrows the limit down. I am having such a hard time using the definitions to find the limit as it does not intuitively make sense to me and the ammount of notation throws me off as I can not use a generel method to solving such a problem.

A: $$L=\lim_{x \to \infty} \frac{\tanh x-1}{e^{-2x}}=\lim_{x\to \infty} \frac{-2e^{-x}}{e^{-2x}(e^{x}+e^{-x})}=\lim_{x\to \infty} \frac{-2}{(1+e^{-2x})}=-2.$$


text:
Q: Is there a usable Queuable interface anywhere in the .NET BCL? The Queue<T> type in .NET has a method
void Enqueue(T item);

But there is no interface that wraps this method. Is there a (preferably single method) interface with the same type signature elsewhere in the BCL? I'd like to be able to develop two packages, one which defines data structures that implement the abstraction and one which uses the abstraction and avoid creating an abstractions package required by both.

A: The only interface that really matches this is IObserver<T>, which is a little more complex (it supports error notification and termination).
The Channels API supports ChannelWriter but that's an abstract class. As observed above, Action also works if you don't need to be able to configure easily via IoC.


text:
Q: Two-way binding between controller and directive with $watch in controller not working I've come across a quite a few similar questions and tried them all with no success. I'm not sure if I'm doing this the "Angular way" so I might need to change my approach. In short I'm initialising a scoped variable from within a controller, the variable is then shared with the directive's scope. However when this value is changed as part of a user interaction the new value is not being synchronised with the controllers variable. My abbreviated code follows:
Controller
The $watch method is only called once i.e. when the page loads.
.controller('NewTripCtrl', ['$scope', function($scope) {
  $scope.pickupLocation;
  $scope.dropoffLocation;

  $scope.$watch('dropoffLocation', function(oldVal, newVal) {
    console.log('dropofflocation has changed.');
    console.log(oldVal);
    console.log(newVal);
  });
}])

HTML

  <input ion-google-place type="text" class="ion-google-place" autocomplete="off" service="places" placeholder="Pickup Address" location="pickupLocation"></input>

  <input ion-google-place type="text" class="ion-google-place" autocomplete="off" service="places" placeholder="Dropoff Address" location="dropoffLocation"></input>

Directive
angular.module('ion-google-place', [])
  .directive('ionGooglePlace', [
    '$ionicTemplateLoader',
    '$ionicBackdrop',
    '$q',
    '$timeout',
    '$rootScope',
    '$document',
    function ($ionicTemplateLoader, $ionicBackdrop, $q, $timeout, $rootScope, $document) {
      return {
        restrict: 'A',
        scope: {
          location: '=location'
        },
        link: function (scope, element, attrs) {
          scope.locations = [];
          console.log('init');
          console.log(scope);
          console.log(attrs);
          // var geocoder = new google.maps.Geocoder();
          var placesService = new google.maps.places.AutocompleteService();
          var searchEventTimeout = undefined;

          var POPUP_TPL = [
        '
',
        '
',
        '',
        '',
        '<input class="google-place-search" type="search" ng-model="searchQuery" placeholder="' + 'Enter an address, place or ZIP code' + '">',
        '',
        '<button class="button button-clear">',
        'Cancel',
        '</button>',
        '
',
        '<ion-content class="has-header has-header">',
        '<ion-list>',
        '<ion-item ng-repeat="l in locations" type="item-text-wrap" ng-click="selectLocation(l)">',
        '{{l.formatted_address || l.description }}',
        '</ion-item>',
        '</ion-list>',
        '</ion-content>',
        '
'
          ].join('');

          var popupPromise = $ionicTemplateLoader.compile({
            template: POPUP_TPL,
            scope: scope,
            appendTo: $document[0].body
          });

          popupPromise.then(function (el) {
            var searchInputElement = angular.element(el.element.find('input'));

            // Once the user has selected a Place Service prediction, go back out
            // to the Places Service and get details for the selected location.
            // Or if using Geocode Service we'll just passing through
            scope.getDetails = function (selection) {
              //console.log('getDetails');
              var deferred = $q.defer();
              if (attrs.service !== 'places') {
                deferred.resolve(selection);
              } else {
                var placesService = new google.maps.places.PlacesService(element[0]);
                placesService.getDetails({
                    'placeId': selection.place_id
                  },
                  function(placeDetails, placesServiceStatus) {
                    if (placesServiceStatus == "OK") {
                      deferred.resolve(placeDetails);
                    } else {
                      deferred.reject(placesServiceStatus);
                    }
                  });
              }
              return deferred.promise;
            };

            // User selects a Place 'prediction' or Geocode result
            // Do stuff with the selection
            scope.selectLocation = function (selection) {
              // If using Places Service, we need to go back out to the Service to get
              // the details of the place.
              var promise = scope.getDetails(selection);
              promise.then(onResolve, onReject, onUpdate);
              el.element.css('display', 'none');
              $ionicBackdrop.release();
            };

            function onResolve (details) {
              console.log('ion-google-place.onResolve');

              scope.location = details;

              $timeout(function() {
                // anything you want can go here and will safely be run on the next digest.
                scope.$apply();
              })

              if (!scope.location) {
                element.val('');
              } else {
                element.val(scope.location.formatted_address || '');
              }
            }
            // more code ...
      };
    }
  ]);

The $watch function only detects a change when the page loads but never again. What is the correct way to provide the controller with the value that the user enters into the directive's input element?

A: Here are your options
Option#1 using ng-model
with watch function in parent controller
<input ion-google-place type="text" class="ion-google-place" autocomplete="off" service="places" placeholder="Dropoff Address" ng-model="dropoffLocation"></input>

and in directive
scope: {
          location: '=ngModel'
        },

You don't need Watch here.
Option#2 Through Object literal
.controller('NewTripCtrl', ['$scope', function($scope) {

 $scope.locationChanged = function(location){
    //you watch code goes here
 }

}

 <input ion-google-place type="text" class="ion-google-place" autocomplete="off" service="places" placeholder="Dropoff Address" location="dropoffLocation" location-changed="locationChanged(location)" ></input>

//directive scope
scope: {
          location: '=',
      locationChanged: '&'
        }

//in link function invoke parent controllers method as
scope.locationChanged({location:scope.location});

Option#3 Through Function reference
controllect and directives scope same as option#2
<input ion-google-place type="text" class="ion-google-place" autocomplete="off" service="places" placeholder="Dropoff Address" location="dropoffLocation" location-changed="locationChanged" ></input>

//in link function invoke parent controllers method as

scope.locationChanged()(scope.location);

Option#2 is recommended for better readability.
watching variables should be avoided as much as possible.

A: As angular docs says:

Scope inheritance is normally straightforward, and you often don't even need to know it is happening... until you try 2-way data binding (i.e., form elements, ng-model) to a primitive (e.g., number, string, boolean) defined on the parent scope from inside the child scope.

This is a common issue when doing 2-way data binding with primitives. Try doing this same but try to share an object instead of a primitive.
i.e:
.controller('NewTripCtrl', ['$scope', function($scope) {
    $scope.pickupLocation = {location: ''};
    $scope.dropoffLocation = {location: ''};
    ...


text:
Q: Cannot read properties of undefined (reading 'subscribe') I've been trying to subscribe to a particular observable(i am a beginner to rxjs), but I keep failing.
here is my code

here I need to assign the first element of usergroups array element to this.currentGroup
const selectedUserGroups$ =
this.userGroupsService.getUserGroupsWithUsers(this.selectedUserGroupIds).pipe(shareReplay());

this.selectedUserGroups$.subscribe( (usergroups: UserGroup[]) =>
this.currentGroup = usergroups[0]);

if(this.currentGroup.users?.length >0)
{
  this.showUsersList();
}

but this won't work as i expected, Appreciate your help regarding this

A: const selectedUserGroups$ = // assignment here
this.selectedUserGroups$.subscribe( //...

Those are two different objects: the variable in the function scope selectedUserGroups$ and the object property this.selectedUserGroups$.
Remove this. from the second line, for example. Or replace const selectedUserGroups$ =  with this.selectedUserGroups$ =.