text:
Q: Crashing app after implementation Sceneform I'm struggling with a strange issue.
I tried everything to find a solution to why my app crashes.
The reason is "implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.7.0' ".
When I add this implementation I get error:
java.lang.RuntimeException: Unable to instantiate activity
 ComponentInfo{com.example.myarcore/com.example.myarcore.MainActivity}:
 java.lang.ClassNotFoundException: Didn't find class
 "com.example.myarcore.MainActivity" on path: DexPathList[[zip file
 "/data/app/com.example.myarcore-Aw

This is my app gradle code:
 apply plugin: 'com.android.application'
apply plugin: 'com.google.ar.sceneform.plugin'
apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.myarcore"
        minSdkVersion 26
        targetSdkVersion 28
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

According to MultiDex documentation if app min sdk is higher than 21 then to enable MultiDex all I need is to put  multiDexEnabled true as I did.

A: SOLVED,
My min SDK was set to 26.
Just add this to your app gradle, even when documentation says that is necessary in min SDK lower than 26.
 compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}


text:
Q: Are the shrine names supposed to mean something? While watching a speedrun, I've come across something weird between versions of Breath of the Wild. Between languages, it seems the shrine names change. Not completely, but to me it is a weird change.

On the left is the GameGrumps playthrough, in English. The first shrine in the game is named 'Oman Au'.
On the right, is a speedrun, using the French version. The first shrine in the game is named 'Ma'Ohno'.
It would be a weird thing to change in localisation, letting me think that Shrine names might mean more than just names.
So is it just a localisation thing, or is there more meaning to the shrine names I'm not seeing?

A: Shrines (and their corresponding monks) can be linked to Zelda staff members.
According to this wiki page on gamepedia:
Oman Au is an anagram of Aonuma.
Eiji Aonuma is the lead producer for The Legend of Zelda series.
The Japanese name of the shrine is    マ・オーヌの祠 (Ma Ōnu no Hokora),   meaning Ma Ōnu Shrine
The Italian name of the shrine is     Sacrario di Mau Ona,              meaning Mau Ona Shrine.
The French name of the shrine is  Sactuaire de Ma'Ohnu,             meaning Ma Ohnu Shrine.
These are all anagrams of different translations / romanizations of the name Aonuma.
Quoting from this video of DidYouKnowGaming:

Aonuma is not the only developer that was referenced in this way:
  Other monks and shrines are also named after zelda staff:
Zalta Wa Shrine   -> Satoru Takizawa ( Art Director )
  Sasa Kai Shrine
  -> Hiroshi Sakasai ( Designer )
  Katosa Aug Shrine -> Katsuhisa Sato ( Physics Programmer )
Naming each shrine and monk after a member of the staff was actually
  suggested by Satoru Takizawa himself.

Based on these examples, not all shrine names are direct anagrams of staff member names, which might make correlating more names to staff members a bit more difficult.
It is still unclear to me whether such a link does indeed exist for every shrine/monk, or that this was only suggested but never fully realized.
Following the sources in the description of the DidYouKnowGaming video,
I came back to gamepedia, which has a page with namesakes for many more monks.
Interesting to note is that on the same day I originally posted this answer, a user named TriforceTony added a lot more names to this list!

redpajama_set_name: RedPajamaStackExchange


text:
Q: avaudiorecorder interruption in background In my application I am using AVAudioRecorder for recording. Its works fine. but while I am recording in background if a device audio is played my recording get interrupted. I have the delegate function in my code. But its not getting called.

A: An app that plays audio continuously (even while the app is running in the background) can register as a background audio app by including the UIBackgroundModes key (with the value audio) in its Info.plist file. Apps that include this key must play audible content to the user while in the background.
Check below links
  Link 1
You need to make couple of changes in plist file.
1) Set Required background mode to App plays audio
2) set Application does not run in background to YES.
3) Add following code to AppDelegate
NSError *setCategoryErr = nil;
NSError *activationErr  = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];


text:
Q: exclude a meta_key from replace query for all meta_value I have to change the word $15 in all meta_value except 1 meta_key name : pricing_tier
UPDATE postmeta SET meta_value = REPLACE(meta_value, '$15', '$10');

I couldn't find anyway to exclude pricing_tier ACF field from the query.
any help will be appreciated.


text:
Q: Meteor: Trying to serve a static file outside of /public TLDR;
How can one serve a static file through iron router? If I place a file in /public it bypasses all the hooks I could use in iron router.
Long version:
I need to log all requests to an image file. Specifically I'd like to persist to Mongodb the querystring in every request such as 'a=1&b=2' from http://domain.com/cat.png?a=1&b=2.
I don't see a way of doing this in Meteor. But I could use the iron router hooks such as params.query . Except that any static files in /public get served by Meteor's handler, and bypasses iron router.
(I'm looking to use up to date apis. There are lots of posts here pre meteor 1.0 and pre ironrouter)

A: Of course it is possible. You have full access to the request and response objects of the HTTP request, and you can even wire up arbitrary connect middleware.
Here is my solution using the latter, serving from the /tmp directory:
var serveStatic = Meteor.npmRequire('serve-static');

if (Meteor.isClient) {
}

if (Meteor.isServer) {
    var serve = serveStatic('/tmp');
    // NOTE: this has to be an absolute path, since the relative
    // project directories change upon bundling/production

    Router.onBeforeAction(serve, {where: 'server'});

    Router.route('/:file', function () {
        this.next();
    }, {where: 'server'});
}

To make this work you'll also need the npm package:
meteor add meteorhacks:npm

And you'll need to add serve-static to your packages.json file:
{
    "serve-static": "1.10.0"
}

Afterwards, any file /tmp/x.xyz will be available on your /x.xyz URL.

A: You can use fs to server any file:
Router.route('/static/:filename', function (){
  var fs = Npm.require('fs'),
      path = '/tmp/' + this.params.filename; // make sure to validate input here

  // read the file
  var chunk = fs.createReadStream(path);

  // prepare HTTP headers
  var headers = {}, // add Content-type, Content-Lenght etc. if you need
      statusCode = 200; // everything is OK, also could be 404, 500 etc.

  // out content of the file to the output stream
  this.response.writeHead(statusCode, headers);
  chunk.pipe(this.response);
});


text:
Q: Encrypt files in background while using the application (Design Problem) I've to design a functionality which encrypts and decrypts files(around 30) based on user input.
During the encryption, I want the user to be still able to use the system just like before.
(which means that files can be updated during the encryption process)
I'm looking to find the best approach to implement it.
There are few different approaches (that are still incomplete) which I want to discuss.
Simple Approach:

*

*Start encrypting 30 files in parallel.

*If user updates one of the file, the change will be missed in the encrypted file as the change was not there when encryption was called.

Cons: Dirty read = data loss. (failed)
2nd Approach:

*

*save all operations that can change the files (difficult to achieve).

*wait for encryption to complete.

*when encryption completes, perform all those operations manually.

Cons: User updates are not reflected during the process, as we're only saving operations and not performing them unless process is completed.
3rd Approach:

*

*When encryption starts:

*

*use current files as "old".

*current system works fine as old (updates saved in old files if any change)

*start encrypting files and save them with different name.

*

*when all files are encrypted, there are two cases:

*

*No file was updated during process (best case). -> replace encrypted files name and delete old files.

*Files changed. Find out which files change(easy to check) and only encrypts those again. (with the hope user doesn't update again, if he does keep repeating the process unless he stops)

Cons: Can end up in an infinite loop if user doesn't stop updating files.
Pros: User can use the system just like before and data won't be lost.
I'd love to read better approaches from you guys.
I'll be using AWS KMS to encrypt S3 files inside lambda function.


text:
Q:  width & height I have a background image repeating in a div after the body tag.
I gave both body and div a width and height of 100% because even if there is not enough content to show I want that image to show on the entire browser.
And this works if there is not scrollbars on the page, if there is many content showing and I need to scroll down the background image gets broken and after that is white.
Any help?

A: background-attachment: fixed;

background-attachment:fixed will keep your background at a fixed position, so that the background does not disappear when you scroll down.
Update:
In your case, the background is not attached to , but two nested child elements. I propose two possible solutions:
Method 1: Without changing HTML
Current document structure:

Suggested CSS for this:
html, body { margin:0;padding:0; } /*Included in answer, because it's important*/
#mainbg {
    height: 100%;
    overflow: auto;
}
#bg {
    min-height: 100%;
}

Method 2: Recommended solution:
Move the background (image) property to the  element, and remove
.

CSS:
html, body { margin:0;padding:0; }
body {
    background: url(../images/main-bg-pat.png) 0 0;
}
#bg {
    min-height: 100%;
}


text:
Q: TypeError: Cannot read property 'payload' of undefined I am trying to get data from a object named initialState and console.log it, but the object is coming back empty.. related files below  thanks in advance!
basketReducer.js
import { ADD_PRODUCT_BASKET, GET_NUMBERS_BASKET } from '../actions/types'

const initialState = {
    basketNumbers: 0,
    cartCost: 0,
    products: {

        blackOne: {
            name: "Black One",
            price: 120,
            numbers: 0,
            inCart: false
          },

          blackThree: {
            name: "Black Three",
            price: 120,
            numbers: 0,
            inCart: false
          },

          blackFour: {
            name: "Black Four",
            price: 120,
            numbers: 0,
            inCart: false
          }
    }
}

export default (state = initialState, action) => {
    switch(action.type) {
        case ADD_PRODUCT_BASKET:
          let addQuantity = { ...state.products[action.payload] }
          console.log(addQuantity)

            return {
              ...state,
              basketNumbers: state.basketNumbers + 1
            }
        case GET_NUMBERS_BASKET:
            return {
                ...state
            }
        default:
            return state
    }
}

addAction.js

import { ADD_PRODUCT_BASKET} from './types'

export const addBasket = (productName) => {
    return (dispatch) => {
        console.log('Adding to Basket')
        console.log('Product:', productName)
        dispatch({
            type: ADD_PRODUCT_BASKET,
            payload: productName
        })
    }
}

types.js
export const ADD_PRODUCT_BASKET = 'ADD_PRODUCT_BASKET'
export const GET_NUMBERS_BASKET = 'GET_NUMBERS_BASKET'

FilterPanel.js
Note: I'm not focused on data from the state. For now I'm only using the onClick method in the render method to get this.props.addBasket(item.name)
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addBasket } from '../actions/addAction'
import axios from 'axios'
import './FilterPanel.css'

export class FilterPanel extends Component {
    constructor(props) {
        super(props)

        this.state = {
            color: "",
            shoes: []
        }

        this.handleColorChange = this.handleColorChange.bind(this)
    }

    componentDidMount() {
        axios.get('http://localhost:4000/shoes')
            .then(res => {
                const shoeData = res.data
                this.setState({
                    shoes: shoeData
                })
            })
            .catch((error) => {
                console.log(error)
            })
    }

    handleColorChange(e) {
        const color = e.target.value
        console.log(color)
        this.setState({
            color: color
        })
    }

    render() {
        console.log(this.props)
        const { shoes } = this.state
        const colors = ["Black", "Blue", "Brown", "Gray", "Green", "Red", "White"]
        const shoesToShow = shoes.map(item => {
            if (item.mainColor === this.state.color) {
                return

{item.name}

${item.price}

 this.props.addBasket(item.name)} className="basket-p" >Add to cart

            } else {
                return null
            }
        })

        console.log(this.props)

        return (
            <React.Fragment>

                    <form>
                        {colors.map((color, index) => (

                                {color}
                                <input
                                    value={color}
                                    checked={this.state.color === color}
                                    onChange={this.handleColorChange}
                                    type="radio"
                                />

                        ))}
                    </form>

{shoesToShow}

            </React.Fragment>
        )
    }
}

export default connect(null, { addBasket })(FilterPanel)

I would like the button click to lead to the cart page with the data info Added.
Here is the Real Data I want to use for my add to cart button:
shoe.model.js (Shoe schema):
const mongoose = require('mongoose')
const Schema = mongoose.Schema

let Shoe = new Schema({
    image: {
        type: String
    },
    cartImage: {
        type: String
    },
    name: {
        type: String
    },
    color: {
        type: String
    },
    price: {
        type: Number
    },
    mainColor: {
        type: String
    },
    midImage: {
        type: String
    },
    heroFeatured: {
        type: Boolean
    },
    message: {
        type: String
    }
})

module.exports = mongoose.model('Shoe', Shoe)

shoe.route.js (shoe route):
const express = require('express')
const shoeRouter = express.Router()

const Shoe = require('./shoe.model')

shoeRouter.route('/shoes').get((req, res) => {
    Shoe.find((err, shoes) => {
        if(err) {
            console.log(err)
        } else {
            res.json(shoes)
        }
    })
})

shoeRouter.route('/shoes/:id').get((req, res) => {
    let id = req.params.id
    Shoe.findById(id, (err, shoe) => {
        res.json(shoe)
    })
})

module.exports = shoeRouter

server.js (database connection / routes)
const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
const shoeRouter = require('./shoe.route')
const userRouter = require('./user.route')
const emailRouter = require('./email.route')
//const routes = express.Router()

const PORT = 4000

app.use(cors())
app.use(express.urlencoded({ extended: false }))
app.use(express.json())

mongoose.connect('mongodb connection...', { useUnifiedTopology: true, useNewUrlParser: true })
const connection = mongoose.connection

connection.once('open', () => {
    console.log("MongoDB database connection established successfully")
})

app.use('/', shoeRouter)
app.use('/', userRouter)
app.use('/', emailRouter)

app.listen(PORT, () => {
    console.log('Server is running on port ' + PORT);
})

I didn't know how to implement a shopping cart so I followed a tutorial.
The initialState object from(basketReducer.js) is fake data i modeled after my real data.
I tried to add the fake data model from a tutorial (just added a copy of the real data)
How can I achieve this with my original data from (filterPanel.js state)?? Thanks!

A: I think this mapDispatchToProps is missing from your FilterPanel component.
Please try adding this -:
// old code from component

{shoesToShow}

            </React.Fragment>
        )
    }
}
function mapDispatchToProps(dispatch){
    return {
        addBasket: (param) => dispatch(addBasket(param))
    }
}
export default connect(null, mapDispatchToProps)(FilterPanel)


text:
Q: Creating a pandas Dataframe from a list of Dictionaries, dictionary keys as columns not sure if the title is explanatory enough.
I have a list of dictionaries from which I want to create a dataframe. For simplicity the list is:
list=[]

DIC1={'value': 69.0, 'time': 10, 'from': 'Mexico', 'signal_name': 'Part1'}
DIC2={'value': 65.0, 'time': 10, 'from': 'Mexico', 'signal_name': 'Part2'}
DIC3={'value': 60.0, 'time': 11, 'from': 'Mexico', 'signal_name': 'Part1'}
DIC4={'value': 67.0, 'time': 10, 'from': 'Mexico', 'signal_name': 'Part3'}
DIC5={'value': 69.0, 'time': 11, 'from': 'Mexico', 'signal_name': 'Part2'}
DIC6={'value': 70.0, 'time': 12, 'from': 'Mexico', 'signal_name': 'Part1'}
DIC7={'value': 68.0, 'time': 12, 'from': 'Mexico', 'signal_name': 'Part2'}
DIC8={'value': 71.0, 'time': 11, 'from': 'Mexico', 'signal_name': 'Part3'}
DIC9={'value': 50.0, 'time': 12, 'from': 'Mexico', 'signal_name': 'Part3'}

list=[DIC1,DIC2,DIC3,DIC4,DIC5,DIC6,DIC7,DIC8,DIC9]
#Convert to Dataframe
df=pd.DataFrame(list)

If I simply convert the list of dictionaries to a dataframe like in the example above I get a dataframe like:
    from    signal_name time    value
0   Mexico  Part1       10      69.0
1   Mexico  Part2       10      65.0
2   Mexico  Part1       11      60.0
3   Mexico  Part3       10      67.0
4   Mexico  Part2       11      69.0
5   Mexico  Part1       12      70.0
6   Mexico  Part2       12      68.0
7   Mexico  Part3       11      71.0
8   Mexico  Part3       12      50.0

But I'm trying to get a filtered table, I guess kind of a pivot table? Something like:
    time    from    part1(value)    part2(value)    part3(value)
0   10      Mexico      69.0            65.0            67.0
1   11      Mexico      60.0            69.0            71.0
2   12      Mexico      70.0            68.0            50.0

Is this possible?

A: With the help of pivot table
df.pivot_table(index=['from','time'],columns=['signal_name'],values=['value']).reset_index()

Output:

               from time value
signal_name              Part1 Part2 Part3
0            Mexico   10  69.0  65.0  67.0
1            Mexico   11  60.0  69.0  71.0
2            Mexico   12  70.0  68.0  50.0

If you dont want value as separate header then pass values parameter as a string i.e
df.pivot_table(index=['from','time'],columns=['signal_name'],values='value').reset_index()

signal_name    from  time  Part1  Part2  Part3
0            Mexico    10   69.0   65.0   67.0
1            Mexico    11   60.0   69.0   71.0
2            Mexico    12   70.0   68.0   50.0

A: Solution from unstack
df.set_index(['from','signal_name','time']).unstack(-2)
Out[437]:
            value
signal_name Part1 Part2 Part3
from   time
Mexico 10    69.0  65.0  67.0
       11    60.0  69.0  71.0
       12    70.0  68.0  50.0


text:
Q: python updating and deleting data file = open(test , 'a')
file.write(str(name + " : " ))
file.write(str(score))
file.write('\n')
file.close()

my txt file look like this:
helen:0
helen:4
jyp:7
helen:6
helen:8
john:7
helen:9

how do I print out the latest 3 scores of (Helen) and how do I delete the old scores?

A: Generally, it is reccomended that you show what you have tried so far and what specific problem you are running into. See the asking questions section or the site tour.https://stackoverflow.com/tour. That being said, you will also want to use .read() to read in the data. You can loop over the line read in and use methods for strings to help you in finding helen(I would reccomend find() and/or index()). See the documentation here.https://docs.python.org/2/library/string.html


text:
Q: Password encryption in Sonar I'm using Yale's CAS to integrate my sonar system and I have problems validating my login username and password, Since I have known that sonar uses crypted_password and salt to store original password, but I can't figure out how sonar generates crypted_password with original password and the random salt. What I need are the encryption algorithm and encryption srategy.
Any of your reply will be highly appreciated.

A: All the encryption-related classes are located in the sonar-plugin-api module. See https://github.com/SonarSource/sonar/tree/master/sonar-plugin-api/src/main/java/org/sonar/api/config


text:
Q: How do I sort the values in a column in Impala SQL? Is there a way that I can order the values in a column?
Sample Table 1

Column A
Column B

Cell 1
a,c,d,b

Cell 2
b,a,c,d

Expected Output

Column A
Column B

Cell 1
a,b,c,d

Cell 2
a,b,c,d


text:
Q: Instantiate UI object in Unity and doesn't show in the screen? I have a code like this in Unity (CSharp):
public GameObject button;
public GameObject panel;

void Start () {
    button.transform.SetParent (panel.transform);
    Sprite shape = Resources.Load<Sprite>("Logo");
    var img = button.transform.GetComponent("Image") as Image;
    img.sprite = shape;
    img.color = new Color (50, 50, 50, 50);
}

Now, this is how my scene looks before Play:
The button in the left side is the one i will try to instantiate in my code and "Albumes" is the Panel.
Then, when I press the Play Button I get this:
I can see in the inspector that the sprite was successfuly loaded
Can somebody give me any clue about this behavior?

A: Well, it seems like that the way you are assigning sprite is not correct. Sprite assigns through Sprite.Create. You can try this,
public GameObject button;
public GameObject panel;

void Start () {
    button.transform.SetParent (panel.transform);
    Sprite shape = Resources.Load<Sprite>("Logo");
    var img = button.gameObject.GetComponent<Image>();
    img.sprite = Sprite.Create(shape.texture,img.sprite.rect,new Vector2(0.5f,0.5f));
    img.color = new Color (50, 50, 50, 50);
}


text:
Q: "iterator cannot be defined in the current scope" error I am a novice C++ programmer working through a simple problem to print out name-and-score pairs together. Here I have used a std::unordered_set for the names and a vector for the scores (to accept duplicate scores, but not names) and that works fine.
But one thing puzzles me about the result, and that's that if I try to initialize the iterator in the for loop, the compiler gives me an error that says

the iterator "cannot be defined in the current scope."

This gives the error:
for (int i = 0, std::unordered_set<std::string>::iterator it = names.begin();
                                                i < names.size(); i++, it++)
{
    std::cout << *it << ", " << scores[i] << '\n';
}

But moved outside the loop, it works fine:
std::unordered_set<std::string>::iterator it = names.begin();
for (int i = 0; i < names.size(); i++, it++)
{
    std::cout << *it << ", " << scores[i] << '\n';
}

Why must the iterator be initialized outside the loop here? Sorry for the simple question, I've searched elsewhere and have not found a clear answer for this.

A: In C++ for-loop
for ( declaration-or-expression(optional) ; declaration-or-expression(optional) ; expression(optional) )
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

init-statement

*

*either an expression statement (which may be a null statement ";")

*a simple declaration, typically a declaration of a loop counter variable with initializer, but it may declare arbitrary many variables
Note that any init-statement must end with a semicolon ;, which is why it is often described informally as an expression or a declaration followed by a semicolon.

Therefore, you can either declare the variable of the same type; ex:
for (int i = 0, j = 1; ... ; i++, j++) {...}
     ^^^^^^^^^^^^^^^^

or initialize the variables of any type that you have declared previously. Ex
std::unordered_set<std::string>::iterator it;
int i;
for (it = names.begin(),  i = 0; i < names.size(); i++, it++) { ... }
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^

Hence, your attempt is failed.


text:
Q: подключение ts файла в html как подключить ts файл в html.Как подключить js файл я знаю но ts нет.

A: насколько я понимаю, браузеры еще не умеют выполнять ts, они выполняют js. Поэтому ts нужно скомпилить в js и подключить уже js.

A: Вот так:
  var canvas = <HTMLCanvasElement> document.getElementById('myCanvas');


text:
Q: How can I impersonate an admin user from Google API in Javascript? I am trying to make a request for gapi.client.directory.users.list with the following parameters:
'customer': 'my_customer',
'maxResults': 100,
'orderBy': 'email'

getting a success result when my account is an admin of the domain. When I do the same request using a non-admin account, it return a 403 result.
I went to https://admin.google.com/AdminHome?chromeless=1#OGX:ManageOauthClients and added the _______.apps.googleusercontent.com as client and https://www.googleapis.com/auth/admin.directory.user.readonly as scope. Even this way I got a 403 result.
I saw some 'impersonating' functions in Java and Python... but nothing for Javascript in a browser context, not NodeJS.
Can someone help me to allow the request to list users in admin directory api for common users of my domain?

A: After some browsing, the parameter viewType is required to allow non-admin users to fetch directory data.
gapi.client.directory.users.list({
    'viewType': 'domain_public',
    'customer': 'my_customer',
    'maxResults': 100,
    'orderBy': 'email'
}

I found it in the docs: https://developers.google.com/admin-sdk/directory/v1/reference/users/list#domain_public after @jay-lee answer: Non-admin read-only access to Google Admin SDK


text:
Q: how should my mysql database structure be in this case? this is the screenshot from reddit. how can i make connection with the topic and answers in a pecking order?

A: If i understand the question correctly, then the answers table would be something like this.
id | user_id | answer | question_id | answer_parent_id

Basically you store the main question id along with the answer and store the parent id of the answer, if its a reply/nested answer. If its a top level answer, it would be 0.

A: In addition to what Sabeen Malik said, if you're storing nested/hierarchical data, you should look at storing it as a Tree Structure.


text:
Q: Validate file extensions and file size on Drupal 7 file field using the form API I am using Drupal 7 and have a custom module that creates a form that has a file upload field:
$form['resume_file'] = array(
  '#type' => 'file',
  '#title' => t('Resume Upload'),
);

I need to make sure the file extensions are one of the following: doc, docx, pdf, txt and rtf and that the file size is no larger than 2MB
I am not finding a clear way in the docs to accomplish this. I saw one place that said use this:
$form['resume_file'] = array(
  '#type' => 'file',
  '#title' => t('Resume Upload'),
  '#upload_validators'  => array("file_validate_extensions" => array("doc docx pdf txt rtf")),
);

but that didn't do anything as far as blocking the wrong filetype and giving an error message. Do I need to do something else like have something extra in my hook_form_validate() function?
I also saw this:
$form['resume_file'] = array(
  '#type' => 'file',
  '#title' => t('Resume Upload'),
);

$form['resume_file']['#upload_validators']['file_validate_extensions'][0] = 'doc docx pdf txt rtf';

Which also did not do anything. How do I validate for file size and extensions?

A: It should work actually. We just need to mention file_validate_extensions & file_validate_size under upload_validators.
Example:
'#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
  ),

A: The file upload control in form api in druapl 7 with extension and size validation
'resume'=>array(
  '#type'   => "managed_file",
  '#title'  => t("Upload Resume in Word Format"),
  '#descripion' => t("Only doc or docx format Files are allowed."),
  '#upload_location'    => "public://resume/",
  "#upload_validators"  => array("file_validate_extensions" => array("doc docx")),
  '#required'=>TRUE,

),

A: The #upload_validators is part of the non-standard form element properties for a managed file form element.
$element = array(
  '#type' => 'managed_file',
  '#title' => t('Resume Upload'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
  ),
);

For more information on the managed file element type see the Drupal Form API reference


text:
Q: Meteor --production not running on https://localhost:3443 but defaults to localhost:3000 I am running meteor from the console (not using mup)
Development:
ROOT_URL=https://localhost:3443  meteor --settings=settings.json

Production:
ROOT_URL=https://localhost:3443  meteor
--settings=settings.json
--production

I want production to run in https://localhost:3443 but it only shows up on localhost:3000. Both use the same settings.json file
The settings.json has this (shown below) and a couple other things:
"dev": {
        "ssl": {
            "key": "localhost.key",
            "crt": "localhost.crt",
            "port": 3443
        }
},

A: Try below command
meteor run --port 3443


text:
Q: can not understand with null and clear statement in this example Sorry for my poor english, I test the List object with clear method and to assign null value
here is code
public class TestList {
private List<String> list;
private List<List<String>> mainList;

public TestList(){
    list = new ArrayList<String>();
    mainList = new ArrayList<List<String>>();
}
public static void main(String arg[]){
    String[] mylist = {"sunday","monda","tuesday","wednesday","thurday","friday","saturday"};

    TestList tl1 = new TestList();

    for(String s : mylist)
        tl1.list.add(s);

    tl1.mainList.add(tl1.list);

    //tl1.list.clear(); // here if clear then not getting the list

    tl1.list = null; ///// but here to assign null still getting list

    System.out.println("after clear");
    System.out.println();
    for(List<String> list : tl1.mainList){
        for(String s : list){
            System.out.println(s);
        }
    }

}
 }

so my question is when I clear the tl1.list using tl1.list.clear(); and then print the value it's clear but when I assing null to this tl1.list then it will print the value how?

A: tl1.list.clear() clears the list list which was added to mainList as well. As Java is object-oriented list and mainList.get(0) reference exactly the same object. If you set tl1.list to null, you only dereference the object, it is still available in mainList.
I'm not sure if I understood your question, but I guess this is what you asked...

A: Assigning a null to any collection does not mean that the elements associated with it will be removed. It only means that you no longer require that object anymore. Now it is up to garbage collector who then dereference this object. If there are lots of statements between the null assignment and print statements this may cause a problem since GC may get time to dereference it.
I hope my answer will help you understand this.

A: It's not clear what you are asking, maybe you think clear() deletes the object - that's not true, it makes the list empty.


text:
Q: Problem with Installing/Running GraalVM on Mac I am using a MacOS Catalina 10.15.7 machine running behind a firewall.
I started evaluating Micronaut and Quarkus as an alternative to Spring boot and one of the main reasons for this is the ability to compile to native image.
To be able to do this I had to install GraalVM. I followed the instructions from here GraalVM Community Edition 20.3.0 and downloaded graalvm-ce-java11-darwin-amd64-20.3.0.tar.gz, I unzipped it in a folder of my choice then exported /Users/myId/work/dev/graalvm/graalvm-ce-java11-20.3.0/Contents/Home/ as GRAALVM_HOME and added GRALLVM_HOME\bin in my path.
After this I went to https://code.quarkus.io/ and uploaded a Hello World Quarkus project to be build with gradle (6.8).
When I run gardle build everything builds OK.
When I run gradle quarkusDev the application starts OK and I can hit the Hello World end point.
However when I am trying to build the native image with gradle build -Dquarkus.package.type=native I am getting the below exception
java.lang.RuntimeException: Cannot find the `native-image` in the GRAALVM_HOME, JAVA_HOME and System PATH. Install it using `gu install native-image`

Trying to run gu install native-image results in a window popping up on my screen saying
"graalvm-ce-java11-20.3.0" is damaged and can't be opened. You should move it to the Bin.

The same error window pops up when I am trying to run the jar build with either gradle build -Dquarkus.package.type=uber-jar or just gradle build
I don't think my GraalVM download is corrupted as the unpacked file looks all right and it seems to have the proper structure.
Any help or hint would be appreciated. Thank you in advance.

A: In MacOS catalina , you can get around this by executing this:
xattr -d com.apple.quarantine <PATH TO GRAALVM INSTALLATION>

It's a know issue. More information can be found at the following links:
https://github.com/oracle/graal/issues/1724
https://github.com/graalvm/homebrew-tap/issues/6


text:
Q: C++ Compilation failure with Boost library I recently cross compiled Boost library for PowerPC and generated the thread and system library. Then to test the library on my target, tried one of the sample code in Boost library and tried to build the binary using the previously built boost library but got the below compilation errors
.
.
GNU C++ version 4.2.2 (powerpc-linux)
compiled by GNU C version 2.96 20000731 (Red Hat Linux 7.3 2.96-113).
GGC heuristics: --param ggc-min-expand=98 --param ggc-min-heapsize=128176
Compiler executable checksum: dd5a9a41381fa3b9978b2738b80f5a75
In file included from /shared/deps/powerpc/include/boost/config/platform/linux.hpp:15,
             from /shared/deps/powerpc/include/boost/config.hpp:53,
             from /shared/deps/powerpc/include/boost/thread/detail/platform.hpp:14,
             from /shared/deps/powerpc/include/boost/thread/thread.hpp:12,
             from helloworld.cpp:7:
4.2.2/cstdlib:106: error: '::div_t' has not been declared
4.2.2/cstdlib:107: error: '::ldiv_t' has not been declared
4.2.2/cstdlib:109: error: '::abort' has not been declared
4.2.2/cstdlib:110: error: '::abs' has not been declared
4.2.2/cstdlib:111: error: '::atexit' has not been declared
4.2.2/cstdlib:112: error: '::atof' has not been declared
4.2.2/cstdlib:113: error: '::atoi' has not been declared
.
.

Below is the sample program given with Boost library
#include <boost/thread/thread.hpp>
#include <iostream>

void helloworld()
{
    std::cout << "Hello World!" << std::endl;
}

int main()
{
    boost::thread thrd(&helloworld);
    thrd.join();
}

Make file:
CC=ppc_4xx-gcc
CPP=ppc_4xx-g++
CFLAGS=-c -g -Wall -static -v
LDFLAGS_TARGET=-$(LDFLAGS_PowerPC)
LIBS_TARGET=$(LIBS_PowerPC)
CPPFLAGS=$(CPPFLAGS_COMMON) $(CPPFLAGS_PowerPC)
INCLUDES=-I/opt/ELDK/4.2/ppc_4xx/usr/include/ -I. -I/opt/ELDK/4.2/ppc_4xx/usr/src/u-boot-1.3.1/board/xilinx/common/ -I/opt/ELDK/4.2/ppc_4xx/usr/src/linux-2.6.24/arch/powerpc/boot/ -I4.2.2/

DEPSROOT=/shared/deps
COMMON_INCLUDES = $(DEPSROOT)/common/include
PowerPC_INCLUDES=$(DEPSROOT)/powerpc/include
CPPFLAGS_PowerPC=-I$(PowerPC_INCLUDES)
CPPFLAGS_COMMON = -I$(COMMON_INCLUDES)
PowerPC_LIBS=$(DEPSROOT)/powerpc/lib
LDFLAGS_PowerPC=-L$(PowerPC_LIBS)
LIBS_PowerPC=-lboost_thread -lboost_system

all: helloworld

helloworld: helloworld.o
$(CPP) -g helloWorld.o -o helloworld -static

helloworld.o: helloworld.cpp
$(CPP) $(CFLAGS) $(CPPFLAGS) $(INCLUDES) $(MODS) helloworld.cpp

clean:
rm -rf *.o helloWorld

The error is in the file cstdlib in the below location
.
.
_GLIBCXX_BEGIN_NAMESPACE(std)

using ::div_t;
using ::ldiv_t;
using ::abort;
.
.

The macro _GLIBCXX_BEGIN_NAMESPACE is setting the namespace as std with certain visibility. I am new to this so couldn't follow it completely.
Has anyone faced similar problem ? I read in some posts that the namespace is missing causing this error but I am not sure if that's the issue in my case.

EDIT
I got more information on the problem. First I thought the problem was with the namespace, so I manually changed the namespace to std but it didn't help. Then I added the definition of the structure div_t just before the statement using ::div_t; and one of the errors decreased (i.e the statement was compiled). So the problem was with the missing definition of div_t structure.
Now the structure div_t is defined in the file stdlib.h which is included in the current file cstdlib. When I did a locate on the file name stdlib.h, I found the below references
/opt/ELDK/4.2/ppc_4xx/usr/include/stdlib.h
/opt/ELDK/4.2/ppc_4xx/usr/include/bits/stdlib.h
/opt/ELDK/4.2/ppc_4xx/usr/include/c++/4.2.2/tr1/stdlib.h
/opt/ELDK/4.2/ppc_4xx/usr/include/freetype2/freetype/config/ftstdlib.h
/opt/ELDK/4.2/ppc_4xx/usr/src/linux-2.6.24/arch/powerpc/boot/stdlib.h
/opt/ELDK/4.2/ppc_4xx/usr/src/linux-2.6.24-xenomai/arch/powerpc/boot/stdlib.h

Only the first file has the definition of div_t and not the others. The file under discussion cstdlib is in the folder ../include/c++/4.2.2/, now if the file stdlib.h is included here which one of the multiple stdlib.h is included ? The location /opt/ELDK/4.2/ppc_4xx/usr/include is present in my include path.
BTW how do I know which file is being included ?

A: The problem was the same as Cross Compile Boost library for PowerPC architecture. The include path which had the definition of dev_t was omitted and the next include path was used. Unfortunately it also had a file stdlib.h which didn't have the definition of dev_t structure. I created soft links and made sure the compiler picked up the correct stdlib.h file.


text:
Q: Can a page inside an iframe "see" cross domain if the iframe element itself is visible or not? If I load a page in an iframe from a different domain, is there anyway for the contained page to see if the iframe element or it's parent element is visible (e.g. using jquery's is(':hidden'))?
I have control over both domains -- I can set CORS, attributes, whatever. Everything I try still gives me something like:
Uncaught SecurityError: Blocked a frame with origin "http://s-college.mydomain.com" from accessing a frame with origin "http://qaf.ng.mydomain.com". Protocols, domains, and ports must match.
If it helps, the base domains are actually the same, just the sub-domains are different.

A: If they are both on the same high level domain (e.g. foo.example.com and bar.example.com) you can set document.domain in JavaScript.
document.domain = 'example.com';

This will allow cross frame communication.
CORS only applies to (mostly AJAX) requests so it is not applicable here.
Just in case anyone else finds this question that doesn't have them on the same higher level domain: If they are on different domains you would need to use window.postMessage in order to communicate cross frame.


text:
Q: how to change a text of element in a parent tag using xslt I want to replace the element tag name using xslt. I have an output like this:
<gl-cor:documentInfo>
    <gl-cor:entriesType contextRef="journal_context">DocumentID</gl-cor:entriesType>
    <gl-cor:uniqueID contextRef="journal_context">RevisionID</gl-cor:uniqueID>
</gl-cor:documentInfo>
<gl-cor:entityInformation>
    <gl-cor:entityPhoneNumber>
        <gl-cor:phoneNumber contextRef="journal_context">779633</gl-cor:phoneNumber>
    </gl-cor:entityPhoneNumber>
    <gl-cor:entityFaxNumberStructure>
        <gl-cor:entityFaxNumbercontextRef="journal_context">1234-56-89</gl-cor:entityFaxNumber>
    </gl-cor:entityFaxNumberStructure>
</gl-cor:entityInformation>

And, I want my output to be looks like this:
<gl-cor:documentInfo>
    <gl-cor:entriesType contextRef="journal_context">DocumentID</gl-cor:entriesType>
    <gl-bus:uniqueID contextRef="journal_context">RevisionID</gl-cor:uniqueID>
</gl-cor:documentInfo>
<gl-cor:entityInformation>
    <gl-bus:entityPhoneNumber>
        <gl-bus:phoneNumber contextRef="journal_context">779633</gl-bus:phoneNumber>
    </gl-bus:entityPhoneNumber>
    <gl-bus:entityFaxNumberStructure>
        <gl-bus:entityFaxNumbercontextRef="journal_context">1234-56-89</gl-bus:entityFaxNumber>
    </gl-bus:entityFaxNumberStructure>
</gl-cor:entityInformation>

All the children of <gl-cor:entityInformation> should replace instead of gl-cor, it should be gl-bus. Is it possible to do this?
I tried to create a sample xslt but it didn't work. The error occurs in the <gl-bus:phoneNumber>, because I think it is contain a special characters? like "-" and ":".
    <xsl:template match="@*|node()">
<xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>

<xsl:template match="gl-cor:entityInformation/gl-cor:entityPhoneNumber/gl-cor:phoneNumber">
<gl-bus:phoneNumber>
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</gl-bus:phoneNumber>
</xsl:template>

Can someone help me solve this problem? Thanks alot.

A: First of all gl-cor and gl-bus are namespace prefixes. Namespace prefixes are written before an XML element and seperated from the XML element with a :. So your problem is not because of the characters - and :, these are all valid characters, please also read these articles/tutorials:
http://www.w3schools.com/xml/xml_namespaces.asp
http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML
To answer your problem we need to know what the namspace URIs are for gl-cor and gl-bus, but it should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:gl-cor="http://example.org/gl-cor" xmlns:gl-bus="http://example.org/gl-bus">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[ancestor::gl-cor:entityInformation]">
        <xsl:element name="gl-bus:{local-name()}">
            <xsl:apply-templates select="@*|node()" />
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

The template *[ancestor::gl-cor:entityInformation] will match on all (grand)children of gl-cor:entityInformation.
NOTE
The namespaces in the XSLT should be updated and match to your input XML:
xmlns:gl-cor="http://example.org/gl-cor"
xmlns:gl-bus="http://example.org/gl-bus"


text:
Q: Como insertar un textformfield al final de la página en flutter necesito insertar un textformfield al final de mi página con un botón a la derecha.
En esta página y dentro del build widget, tengo un listview con un tamaño fijo y deseo que al final se pueda ingresar un texto.

@override
Widget build(BuildContext context) {
return new Scaffold(
    appBar: new AppBar(
      title: new Text("Mensajes de trabajo"),
      backgroundColor: Colors.deepOrange,
    ),
    body: Container(
      height: 450,
      child: FutureBuilder(
        future: _capturaComuna(),
        builder: (BuildContext context, AsyncSnapshot snapshot){
          if (snapshot.data == null){
            return Container(
              child: Center(
                child: Text("Cargando...")
              )
            );
          } else {
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index) {
                return Card(
                  child: ListTile(
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(snapshot.data[index].imagen_mensaje),
                    ),
                    title: new Text(snapshot.data[index].nombre_persona + '   ' + snapshot.data[index].fecha_mensaje),
                    subtitle: Text(snapshot.data[index].texto_mensaje),
                  )
                );
              },
            );
          }
        }
      )
    )
  );
}

A: Aquí hice un ejemplo de como debería ser, usando MediaQuery para no tener que poner un tamaño fijo en el Container, solo reemplaza por tu snapshot.
  @override
    Widget build(BuildContext context) {
      return Scaffold(
          appBar: new AppBar(
            title: new Text("Mensajes de trabajo"),
            backgroundColor: Colors.deepOrange,
          ),
          body: Container(
            height: MediaQuery.of(context).size.height,
            child: FutureBuilder(
                future: _capturaComuna(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.data == null) {
                    return Container(child: Center(child: Text("Cargando...")));
                  } else {
                    return Stack(
                      children: [
                        ListView.builder(
                          padding: EdgeInsets.only(bottom: 60),
                          itemCount: snapshot.data.length,
                          itemBuilder: (BuildContext context, int index) {
                            return Card(
                                child: ListTile(
                              title: new Text(snapshot.data[index]),
                              subtitle: Text(snapshot.data[index]),
                            ));
                          },
                        ),
                        Positioned(
                          bottom: 0.0,
                          left: 0.0,
                          right: 0.0,
                          child: Container(
                            color: Colors.white,
                            child: Row(
                              children: [
                                Expanded(
                                  child: Padding(
                                    padding: const EdgeInsets.all(8.0),
                                    child: TextFormField(
                                      decoration: InputDecoration(
                                          hintText: "Ingresa texto aquí"),
                                    ),
                                  ),
                                ),
                                RaisedButton(
                                  child: Text("Enviar"),
                                  onPressed: () {},
                                ),
                              ],
                            ),
                          ),
                        )
                      ],
                    );
                  }
                }),
          ));
    }

Con esto, cuando el teclado aparece empuja tu barra inferior para que puedas ver que ingresas en el TextField.


text:
Q: Upload image using PHP and forms I have a problem with uploading a picture using forms and displaying it on another page, the basic problem is I can't find the picture on the path where I save it.
This is the form.php:
            <form role="form"  id="equipe" action="editEquipe.php" method="get">

                  id Equipe
                  <input type="text" class="form-control" id="id_equipe"  name="id_equipe">

                  Télécharger le logo

                  <input type="file" id="logo"   name="logo">

                <button type="submit"  value="" class="btn btn-primary">Modifier</button>

            </form>

And this is my action.php:
if(isset($_GET['id_equipe'])  &&  isset($_GET['logo']))

   {
       $id_equipe= $_GET['id_equipe'];

       $logo =  $_GET['logo'];

    $imgname = "logo_".$id_equipe;
  $logoImage=$imgname.".png";
   $link = "http://.../LogoImages/".$imgname.".png";

if ($conn->connect_error) {
$response["error"] = -1;
$response["message"] = "cannot connect to the server please try          again";
  }

 else
    {

    $sql = "UPDATE equipe set
    nomEquipe='$nom_equipe',
    logoEquipe=' $link',
    idChampionnat='$nom_championnat'

    where idEquipe='$id_equipe' ";

    $updatedispo = $conn->query(sprintf($sql));
    if($updatedispo)
    {

     $imsrc = base64_decode($logoImage);

     $path ="http://.../LogoImages/".$imgname.".png";

     $path = str_replace('\/','/',$path);

    $fp = fopen($path, 'wb');
    var_dump($fp);

    if(is_readable($fp)) echo 'readable ';
    else echo "no redable ";

    if(is_writable($fp)) echo 'writable ';
        else echo "no writable";

    fwrite($fp, $logoImage);
     // var_dump($fp);

      fclose($fp);

                     $response["error"] = 0;
                     $response['picture'] = $path;

                     $response['message'] =  "Image uploaded in ".$path;
                     $response['id_image'] = $id_equipe;
                     $response["message"] = " equipe updated";

    }

    else
    {
                    $response["error"] = -1;
                    $response["message"] = "error requete";
    }
   }
    }

   else
      {
         $response["error"] = 100;
         $response["message"] = "Some params are missing";
       }
     echo json_encode($response);

        ?>

A: As mentioned, you have to use POST as method. Then the path to the uploaded image can be found in the $_FILE varibale.
$tmp_path = $_FILES['logo']['tmp_name'];
$filesize = $_FILES['logo']['size'];
//filesize is bigger then 0 if the logo was set

You can move the file into your www-folder (http://php.net/manual/en/function.move-uploaded-file.php), but better check, if this file is valid!, but this was not the question.

A: add this in form enctype="multipart/form-data"
like
<form role="form" id="equipe" enctype="multipart/form-data" action="editEquipe.php" method="get">

this will be used for image upload.


text:
Q: How can SELECT statement return different groups by row number? I wasn't sure what the title would be, so apologies beforehand.
Let's say I have a simple TSQL statement that looks like SELECT City from Cities. This returns one result with 26 rows:
City
New York
Los Angeles
Chicago
Houston
Philadelphia
Phoenix
San Antonio
San Diego
Dallas
San Jose
Austin
Indianapolis
Jacksonville
San Francisco
Columbus
Charlotte
Fort Worth
El Paso
Memphis
Seattle
Denver
Washington
Boston
Nashville
Baltimore
Oklahoma City

Now, let's say that I want to divide this result into 3 groups of 10 rows each. In other words, when I run the query, the result will display three "different" rows sets, the first two with 10 rows and the last one with the remainder of 6. It's as if I had run these 3 queries at once: a top(10), a middle(10), and a What's Left. If I were to run this query from a .Net app, the dataset would have 3 datatables.
The issue here is that there's nothing I can use to group the data. Even if I did, I don't want to. I want to specify how many datatables this query will return and how many rows each datatable will have.

A: I think you want to use row-number() and some arithmetic:
select ((seqnum  - 1) / 10) as grp, city
from (select city, row_number() over (order by (select NULL)) as seqnum
      from cities
     ) c;

Note that the ordering is not guaranteed.  You really need a specific column to specify the order, because SQL tables represent unordered sets.
EDIT:
It is unclear exactly what you want to do.  This divides the rows into groups of 10, which seems to be what you want to do.  Of course, this returns only one result set -- any SQL query only returns one result set.

A: If you are using SQL Server 2012 or above you can use the OFFSET/FETCH keywords:
So this would get your first 10 cities:
SELECT City
FROM Cities
ORDER BY City
    OFFSET 0 ROWS
    FETCH NEXT 10 ROWS ONLY

And this would get the next 10:
SELECT City
FROM Cities
ORDER BY City
    OFFSET 10 ROWS
    FETCH NEXT 10 ROWS ONLY

Also you can substitute these numbers with variables:
DECLARE @PageSize INT = 10
DECLARE @PageNumber INT = 5

SELECT City
FROM Cities
ORDER BY City
    OFFSET @PageNumber * @PageSize ROWS
    FETCH NEXT @PageSize ROWS ONLY

A: You need a Cursor or maybe a WHILE loop. I'll flesh out the code when I'm on break in about 30 minutes, but for now suffice to say that you need to combine it with a windowing function to divide the set into groups of 10, and then select each group out 1-by-1.
Summat like this:
declare @paginator int = 0
declare @totalPages int = (select count(*) from cities) / 10 + 1

while @paginator <= @totalPages
begin
    select city
    from (
        select
            city,
            row_number() over (order by city) as rownumber
      from cities)
    where rownumber <= @paginator * 10 + 10
    AND rownumber > @paginator * 10

    set @paginator = @paginator + 1
end

A: I think the best solution would be a combination of loop and offset clause in a dynamic query. There it goes:
create table city(
  name varchar(100)
)

insert into city values ('City')
insert into city values ('New York')
insert into city values ('Los Angeles')
insert into city values ('Chicago')
insert into city values ('Houston')
insert into city values ('Philadelphia')
insert into city values ('Phoenix')
insert into city values ('San Antonio')
insert into city values ('San Diego')
insert into city values ('Dallas')
insert into city values ('San Jose')
insert into city values ('Austin')
insert into city values ('Indianapolis')
insert into city values ('Jacksonville')
insert into city values ('San Francisco')
insert into city values ('Columbus')
insert into city values ('Charlotte')
insert into city values ('Fort Worth')
insert into city values ('El Paso')
insert into city values ('Memphis')
insert into city values ('Seattle')
insert into city values ('Denver')
insert into city values ('Washington')
insert into city values ('Boston')
insert into city values ('Nashville')
insert into city values ('Baltimore')
insert into city values ('Oklahoma City')

DECLARE @TOTAL INT
        ,@GROUP INT
        ,@STR VARCHAR(10)

SELECT
    @GROUP=0
    ,@TOTAL=COUNT(*)
FROM CITY

WHILE @GROUP < @TOTAL
BEGIN
   SELECT @STR=CAST(@GROUP AS VARCHAR(10))

   EXEC('SELECT Name '+
        'FROM City '+
        '    OFFSET '+@STR+' ROWS '+
        '    FETCH NEXT 10 ROWS ONLY')

    SELECT @GROUP += 10;
END

Hope it helps!

A: There is nothing native to any version of SQL server* that allows you to say "return N > 1 datasets based on the following criteria" in a single T-SQL statement. As per the (so far 3) other replies, you'd have to build N different and carefully constructed queries.
(Ok, I have not worked with 2012 or 2014, but I'll be greatly surprised--and downvoted--if they do have such syntax.)


text:
Q: Are C functions slower in .m files than in the .c files? Are C functions slower in .m files than in the .c files? Does someone know any performance tests?

A: Files are not fast or slow. They are compiled, and linked in a binary. I assume you are asking about the speed of an executable compiled from such files.
The problem is, then, the compiler. If you compile your code from the .c files with the same compiler than the .m files, and it is optimised, the result will be the same.

A:
Are C functions slower in .m files than in the .c files? Does someone
  know any performance tests?

Well, let me sort of interpret your question to mean "Are C-functions slower or faster than Objc-Messages?"  And the answer is....
It depends.  Mike Ash does a great speed comparison between ObjC and C++ and C here.


text:
Q: Derived Safe Class from NSObject class for JSON parsing in iOS Swift In JSON parsing, model class must need to key coding compliant with JSON response. So following answer must be helpful to preventing it from crashing the iOS App at runtime and print the missing key compliant in console.

A: //
// MARK:- SafeJsonObject
//
@objcMembers
class SafeJsonObject: NSObject {

    override func setValue(_ value: Any?, forKey key: String) {

        let uppercasedFirstCharacter = String(key.first!).uppercased()
        let range = NSMakeRange(0, 1)
        let selectorString = NSString(string: key).replacingCharacters(in: range, with: uppercasedFirstCharacter)

        let selector = NSSelectorFromString("set\(selectorString):")
        let responds = self.responds(to: selector)

        if !responds {
            print("\n\n\n*******--->\(selector) key is missing in API response...<---*******\n\n\n")
            return
        }
        super.setValue(value, forKey: key)
    }
}

PC & reference: https://www.youtube.com/watch?v=3Xv1mJvwXok&list=PL0dzCUj1L5JGKdVUtA5xds1zcyzsz7HLj


text:
Q: A condition that implies two numbers to be coprime? Consider the natural number $n=2^r\cdot s+1$, where $s$ is odd and suppose $a\in \mathbb N$ with $1<a<n$ is such that: $\exists j\in \mathbb N: j<r \wedge a^{2^j\cdot s}\equiv -1 \pmod n$.
Does this implies that $\gcd(a,n)=1$?

A: $a^k \equiv - 1 \mod n$  is impossible unless $\gcd(a,n) = 1$.  (Because $a^k - mn = -1 \implies \gcd(a,n)[\gcd(a,n)^{k-1}\frac{a}{\gcd(a,n)}^{k} - m\frac{n}{\gcd(a,n)}] = -1\implies \gcd(a,n) = 1$).
So this is actually simpler than you imply.

A: A power of $a$ is congruent to $-1\pmod n,$ which is prime to $n.$ I think this is enough for $a$ to be prime to $n,$ as every common divisor of $a$ and $n$ must divide $-1.$
Hope this helps.


text:
Q: Neo4j linked list performance when retrieving by date I dont think the title exactly represents the question I have in mind.
I am currently designing an app which for all intents and purposes is exactly like an RSS feed reader. I am using neo4j because of social features which will be integrated later in the life of the app.
The way I have structured my app is like so:
user:USER -[:HAS_FEED]-> feed:FEED
feed:FEED -[:HAS_SUBSCRIPTION]-> subscription:SUBSCRIPTION
subscription:SUBSCRIPTION -[:NEXT_POST]-> post:POST -[:NEXT_POST]-> post:POST etc etc

Essentially, each subscription has a linked list of posts. Each post has a date (unix time).
The reasons for which I originally decided to build a linked list is because the posts are organized by date and retrieved by date as well (for obvious reasons). For not so obvious reasons, RSS feeds are not always necessarily ordered by the date of their containing posts however, and since I want to display their feeds in order they were release and not in the order I retrieved them, it made me question performance issues as the app grows and linked list could have tends of thousands of posts under each subscription (a feed can also be made up of many subscriptions, which might further affect performance.
Currently i fetch the feeds using the following cypher query
START feed = node({id})
OPTIONAL MATCH feed -[:HAS_SUBSCRIPTION]-> (subscriptions:SUBSCRIPTION) <-[:NEXT_POST*1..]- posts
WHERE HAS (posts.date) AND posts.date > 00000000000000
RETURN DISTINCT posts
ORDER BY posts.date DESC
LIMIT 100

Essentially I am wondering how efficient is this query.
My first question is - Will neo4j necessarily travel the entire linked list, get every post, and then filter by date ?
My second question is - How will this scale with feeds that have a hundred or more subscription with subscriptions which may have tens of thousands of posts.
My third question is - Will it be more efficient, in this case, to ditch the linked list and instead connect each post directly to its subscription (i.e subscription:SUBSCRIPTION -[:HAS_POST]-> post:POST) ?
If you have alternatives as to how i can organize this I am open to suggestion, however, ditching neo4j is not an options (particularly since I spent the time to write my own neo4j driver for node.js for this particular project!)
I am using neo4j > 2.0

A: In this case, yes, Neo4j will traverse the entire list, filtering things out by the date predicate. If you select very small date ranges and you have very large linked lists or heavy load, this may become an issue.
Fundamentally, with the data structure you lay out here, any implementation will have to scan the whole list. Since the dates are not sorted, you can never know if you've found the last entry with the given date until you've looked at all entries.
There are two things you can do here:

*

*You add some second date property that you can order, like separating between "createDate" and "publishDate", where publishDate is sorted. Because cypher does not know publishDate is sorted, you will still need to use something like the traversal framework to write an imperative traversal through this chain that stops at the right point.

*You add a time index structure to the graph, one for each feed, which you can then use to match sections of a feed by arbitrary time spans. With this approach you can use cypher, but will need to keep the time index up to date. See this SO questions for details on this approach: Time-based data in neo4j


text:
Q: How do I count records if condition (size) I have a 2 models: User and Activity
I want to count all users not admin who have more than 5 activities. I can get non admin users but I need to preform some calculation/evaluation before counting records
Here is what I have so far.
a=User.where(:admin => false)
a.joins(:activities).size

However I only want users with more than 5 activities. How do I accomplish such thing with Ruby? Thanks
My User model goes like this
has_many :activities, :through => :projects

Also an array is returned when I expect a single result even with .size at the end. Please advise.
// To the Mods - I'm editing the question for the 3rd time why is the update removed all the time? Why can I not post a comment either? //

A: User model:
class User < ActiveRecord::Base
  has_many :activities
end

To get list of all non-admin users with more than 5 activities:
users = User.where(:admin => false).joins(:activities).group('"activities"."user_id"').having('COUNT(activities.id) > 5')

If you add .size to the end you will get ordered hash with counter per user.


text:
Q: How can the sides of a triangle be maximised given base and height? I've encountered a problem in which I want to maximise the lengths of the sides of a triangular structure while still fitting within an area of 220 x 100. This reduces to maximising the lengths of the sides of triangle with base 220 and height 100.
How could the maximised lengths be calculated?
Edit:- Adding clearer bounds to the problem
The triangle must fit in an area bounded by sides of 300 & 100.

A: This is not a rigorous proof, but I hope is on the right track. If you have two triangle corners fixed somewhere in the rectangle (incl. the edge), and you are looking for where to put the third one to maximise the perimeter, you are in essence trying to find the largest ellipse with those two corners as focus points, which still intersects the rectangle (and then pick one of the intersecting points). Thus, it is fairly obvious that this ellipse will catch a corner of the rectangle, i.e. the third point must be at the corner of the rectangle. By applying the same argument, you conclude that all three corners of the triangle must coincide with the corners of the rectangle. Thus, your maximum is achieved on a right-angled triangle having two sides of the rectangle as its own sides.


text:
Q: Script to search specific string with within a directory I am new to this site and shell scripting.  I am still very much a novice and haven't had much success scripting because I am "attempting"  to learn on my own.  I was hoping one of you script guru's could get me on the right track.  Here's the situation:  I am a network engineer and often I need to find specific lines of code within 100's of files.  For instance I might need to find out which devices are running specific code. Typically what I will do is the following which does exactly what I need it to do.
fgrep -w "" * | sort -t/ -k5 -n
I normally have to go to the directory where my configuration files are located and then pop whatever I am looking for in between the quotations to get my search result.  What I would like to do is write a script that will ask me what I am searching for, then search the directory I am in, and then return the results.  Any help would be greatly appreciated.
Many Thanks,
Diz

A: Add this to your .bashrc file, or whatever config file is loaded when you login:
mygrep() { fgrep -w "$1" * | sort -t/ -k5 -n; }
export -f mygrep

This sets up an alias that you can then use to search - use double quotes if you have a search string with spaces in:
$ mygrep SEARCH_PATTERN
$ mygrep "SEARCH WITH SPACES"

A: You can do by as follows
#!/bin/bash
read -p "Enter string you want to search?" str

find . -type f -exec grep "${str}" {} \;


text:
Q: binary search in array with all elements equal I got a problem with binary search. What I am doing is following:-
Given a sorted array arr[ ] and a number x counts the occurence of x in arr[ ] the function to implement this logic in an efficient way would take????
The answer is O(log(n)) as I use binary search,but what is I have an array arr[] with all elements equal,then I will not be able to get my answer in O(log(n)) time. It will take O(n) time.
Now I claim that an efficient algorithm to implement this problem takes O(n) time. Does my claim holds??

A: Well, the efficient algorithm is:

*

*find the index of the first occurrence of x.

*find the index of the last occurrence of x.

*the answer is (2) - (1) + 1

And that's still O(log n).


text:
Q: jQuery scrollTop() stops working I have the following jQuery code:
$('#staff_list').scroll(function(){
    var dif = scrollPrev - $('#staff_list').scrollTop();
    scrollPrev = $('#staff_list').scrollTop();
    var pos = parseInt($('.selected').css('margin-top')) + dif;
    var limit = $('.selected').position().top + parseInt($('.selected').css('margin-top'));

    if( limit < 474 ) {
        $('.selected').css('margin-top',pos + 'px');
    }

});

The code is suppose to ensure $('.selected') moves with $('#staff_list') when the list is scrolled. However, I want to limit how much $('.selected') moves and keep at a bound at the bottom of the list.
Everything works, except when I reach the bottom limit, the $('.selected') stops moving (as it should), but then completely stops! So even if I scroll back up, it no longer moves. It is as though when it reaches the limit, then it forever stays there, no matter what I do!
What could cause this unexpected behavior?

A: The code appears to determine whether to move the element based on where the element is. So once that element reaches a point where it's not supposed to move, it simply stops moving (either direction).
Try calculating whether .selected should move based on the scrollTop of #staff_list instead.
edit - Try changing
var limit = $('.selected').position().top + parseInt($('.selected').css('margin-top'));
To
var limit = pos + parseInt($('.selected').css('margin-top'));

A: The problem is here:
var limit = $('.selected').position().top + parseInt($('.selected').css('margin-top'));

if( limit < 474 ) {
    $('.selected').css('margin-top',pos + 'px');
}

Once limit is greater than 474, you will never change the position, hence limit will never be less than 474. Perhaps you meant if(pos < limit)?


text:
Q: AppEngine Billing: Difference between Total, Active and Billed Instances I'm trying to understand why my app engine application is billing me so high...
I have just one F1 instance up, and app engine is billing me 4 instances, why? Someone can explain me how google do this count?
Instances Graph:

Active Instances:

Configuration:


text:
Q: Optimizar SQL Server (Tengo muchos waiting tasks) Tengo un problema con mi base de datos (Microsoft SQL Server), tenemos muchos usuarios usando nuestra API y esta API hace muchas consultas a nuestra base de datos (es normal porque estamos guardando datos de seguimiento), estamos usando un load balancer para nuestra API para que podamos manejar muchas solicitudes pero esto nos dio el problema que es que por la mañana todo funciona bien pero cuando pasa el día todo va muy lento, revisé el monitor de actividad (no soy un DBA pero el equipo no tiene uno) y noté que cuando va lento es cuando aumentan las tareas de espera (waiting tasks), siempre es mayor a 500 (las tareas de espera siempre están alrededor de 500-800), por eso hablé con mi gerente que tampoco es técnico y alquilamos un servidor que solo ejecutará la base de datos (al principio todo estaba en el mismo servidor que la API), estas son las especificaciones:

*

*128 ram,16 vcpus

PERO EL PROBLEMA NO SE RESOLVIÓ, seguimos igual:

Revisé el task manager y me di cuenta que la base de datos ni está usando el 100% de CPU NI RAM.

Me gustaría que un experto me recomiende qué hacer porque tengo el hardware y no está mejorando :(, gracias de antemano.
Información extra:

*

*Nuestra API está usando entity framework, escuché que usar ADO.NET puede mejorar esto, ¿es cierto?

*¿Comprar una instancia de AZURE (SQL AZURE DATABASE) con el tier business-critical puede resolver nuestro problema? Claro, tendría que migrar todo a la nube pero si esa es la solución lo haría porque ya me cansé.

*SQL Standard edition

*Propiedades de la  SQL INSTANCE:

A: Logré resolverlo, reduje las waiting tasks de 500 a 10-25 sin modificar el load balancer de mi API, la solución fue simple y efectiva:
USE master
GO

/**
 * Cut off live connections
 * This will roll back any open transactions after 30 seconds and
 * restricts access to the DB to logins with sysadmin, dbcreator or
 * db_owner roles
 */
ALTER DATABASE DBNAME SET RESTRICTED_USER WITH ROLLBACK AFTER 30 SECONDS
GO

-- Enable RCSI for MyDB
ALTER DATABASE DBNAME SET READ_COMMITTED_SNAPSHOT ON
GO

-- Allow connections to be established once again
ALTER DATABASE DBNAME SET MULTI_USER
GO

-- Check the status afterwards to make sure it worked
SELECT is_read_committed_snapshot_on
FROM sys.databases
WHERE [name] = 'DBName'

Lo que pasa es que SQL SERVER por default le da prioridad a la consistencia de datos y cuando un usuario escribe sobre las tablas las bloquea y si en tus queries no consideraste esto (con el hint(nolock)) y le diste prioridad a la consistencia de datos es por eso que se encola todo. Es por eso que el CPU ni la RAM se estában usando al 100% porque la mayoría del tiempo tiene tareas pendientes, haciendo el cambio con el código le cambia el modo de "me importa la consistencia" a "me importa velocidad aunque me traigas datos que no pueden estar al 100% actualizados", lo que hace es que crea otra db llamada tempdb y cada que hagas una inserción se hace una copia a esa base y si por alguna razón se encuentra bloqueada la tabla la base de datos automaticamente toma el registro de tempdb, es como un estilo de replicación y si mejoró muchísimo, de hecho LAS BASES DE AZURE DB UTILIZAN ESA CONFIGURACIÓN POR DEFAULT y en las bases tradicionales hay que hacerlo manual
para que ya empiece utilizar esa configuración, les recomiendo ver el siguiente vídeo:
Video que explica los tipos de ISOLATION de las bases de
datos incluido el de  COMMITED_SNAPSHOT
Resultados:


text:
Q: Postback fires before validation when using CustomValidator I have made a simple project to explain my problem.
This is my Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
        <asp:CustomValidator    ID="cusDate"
                                runat="server"
                                ValidateEmptyText="true"
                                OnServerValidate="DateValidate"
                                ValidationGroup="DateVal"
                                ControlToValidate="txtDate"
                                ErrorMessage="Date error"></asp:CustomValidator>

        <asp:ImageButton        ID="btnSaveDate"
                                CausesValidation="true"
                                ValidationGroup="DateVal"
                                ImageUrl="~/Images/save_32.png"
                                runat="server" />
    </div>
</form>
</body>
</html>

And this is my Default.aspx.cs
using System;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)  <<<<<<BREAKPOINT 1 HERE
            {
            }
        }

        protected void DateValidate(Object source, ServerValidateEventArgs args)
        {
            args.IsValid = false;  <<<<<<BREAKPOINT 2 HERE
        }
    }
}

I set two breakpoints, as shown above, and run the application. When I click "btnSaveDate" it first stops at breakpoint 1 and then at breakpoint 2. I thought it would stop at breakpoint 2 first, then reload the page and then stop at breakpoint 1.
Is there something wrong in the code or should it behave like this?
I have read many articles about this and tried a lot of different solutions, but no one has worked so far.

A: According to the ASP.NET Page Life Cycle, the Postback event handling happens after the Load event.

If the request is a postback, control event handlers are called. After
  that, the Validate method of all validator controls is called, which
  sets the IsValid property of individual validator controls and of the
  page. (There is an exception to this sequence: the handler for the
  event that caused validation is called after validation.)

A postback means that a client is making an http request to the server and, every time a request arrives to the server, the Page Life Cycle stages are executed in this exact order. So the second answer is no, is not possible to enter in the breakpoint 2 then before entering the breakpoint 1.


text:
Q: Meshing a thin tube I'd like to mesh a thin tube. The following gives a strange result when thickness becomes too small:
height = 3;
radius = 1;
thickness = .06;

ir = ImplicitRegion[(radius - thickness)^2 <= x^2 + y^2 <= radius &&
    0 <= z <= height, {x, y, z}];
mesh = ToElementMesh[
  ir, {{-radius, radius}, {-radius, radius}, {0, height}},
  "MeshOrder" -> 1, MaxCellMeasure -> 0.0003]

As you can see it is not quite a cylinder...
Ideally, I'd like to mesh cylinders with thicknesses as small as 0.005. How can it be done?

A: This can sometimes happen if the region bounds intersect with the region it self. If you look at the output of the ElementMesh you will see that it's bounds do not go from -radius to radius.
mesh["Bounds"]
{{-0.995306, 0.995306}, {-0.995306, 0.995306}, {0., 3.}}

The fix is easy: just enlarge the bounding box a bit:
height = 3;
radius = 1;
thickness = .06;
rt = radius + 0.1;

Needs["NDSolve`FEM`"]
ir = ImplicitRegion[(radius - thickness)^2 <= x^2 + y^2 <= radius &&
    0 <= z <= height, {x, y, z}];
mesh = ToElementMesh[ir, {{-rt, rt}, {-rt, rt}, {0, height}},
  "MeshOrder" -> 1, MaxCellMeasure -> 0.0003];

Look at the bounds:
mesh["Bounds"]
{{-1., 1.}, {-1., 1.}, {0., 3.}}

Look at the mesh:
mesh["Wireframe"]

Update:
Another option is to manually generate the a hex element based mesh for this case:
Needs["NDSolve`FEM`"]

nx = 100; ny = 5; nz = 100;
coordinates =
  Flatten[ Table[{r Cos[\[Theta]], r Sin[\[Theta]], h}, {h, 0.,
     3., (3 - 0)/(nz - 1)}, {r, 1. - 0.05,
     1., (1. - (1 - 0.05))/(ny - 1)}, {\[Theta], 0.,
     2 Pi, (2 Pi - 0.)/(nx - 1)}], 2];

mkIncidents =
  Compile[{{nx, _Integer, 0}, {ny, _Integer, 0}, {nz, _Integer, 0}},
   Flatten[
    Table[Block[{p1 = (j - 1)*nx + i, p2 = j*nx + i, p3 = p2 + 1,
       p4 = p1 + 1, p5, p6, p7, p8},
      {p5, p6, p7, p8} = {p1, p2, p3, p4} + k*nx*ny;
      {p1, p2, p3, p4} += (k - 1)*nx*ny;
      {p1, p2, p3, p4, p5, p6, p7, p8}], {i, 1, nx - 1}, {j, 1,
      ny - 1}, {k, 1, nz - 1}], 2]
   ];

incidents = mkIncidents[nx, ny, nz];

mesh =
 ToElementMesh["Coordinates" -> coordinates,
  "MeshElements" -> {HexahedronElement[incidents]}]

ElementMesh[{{-0.999497, 1.}, {-0.999874, 0.999874}, {0.,
   3.}}, {HexahedronElement["<" 39204 ">"]}]

mesh["Wireframe"]

Playing with the nx,ny and nz allows you to influence the the quality which you can inspect with:
Histogram[mesh["Quality"]]


text:
Q: ANSIBLE0013 Use shell only when shell functionality is required In a Ansible role, I do this:
- name: update trusted ca
  shell: "{{ in_ca_dict[ansible_os_family]['update']['shell'] }}"

with:
package_name: ca-certificates
  RedHat:
    path:
      6: /usr/local/share/ca-certificates
      7: /etc/pki/ca-trust/source/anchors
    update:
      shell: /bin/update-ca-trust
  Debian:
    path: /usr/local/share/ca-certificates
    update:
      shell: /usr/sbin/update-ca-certificates
      cache: "no"

but ansible-lint tells me through molecule:
[ANSIBLE0013] Use shell only when shell functionality is required

When should shell functionality is required and when is it not required ?
How should be the alternate way, my code seems fine to me.

A: I just replaced
shell:

with
command:

Here is the doc: https://blog.confirm.ch/ansible-modules-shell-vs-command/
And I solved this


text:
Q: iOS9: duplicated lines in crash reports are causing symbolicatecrash to get stuck This is not a question because I have already found a workaround. I am publishing it so that others can take advantage on the hours I was spending on it, and use my suggested workaround.
I have got some strange crash reports - a single line was duplicated many times:
...
0x190e08000 -        0x190e49fff  Notes arm64  <f45c09ce977b3282ab0e879252dfebee> /System/Library/PrivateFrameworks/Notes.framework/Notes
0x190f9c000 -        0x190fa6fff  NotificationsUI arm64  <73dcb247ed183ce7bb330d7bb55f93bd> /System/Library/PrivateFrameworks/NotificationsUI.framework/NotificationsUI
0x190fa8000 -        0x190faafff  OAuth arm64  <c2658cb3208b342dbe1e91cea30ebdd5> /System/Library/PrivateFrameworks/OAuth.framework/OAuth
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x191900000 -        0x191903fff  ParsecSubscriptionServiceSupport arm64  <c70467637c9332c7b0be897200c9ccb1> /System/Library/PrivateFrameworks/ParsecSubscriptionServiceSupport.framework/ParsecSubscriptionServiceSupport
0x1919c8000 -        0x1919ebfff  Pegasus arm64  <82f60f2d5ad73b5fa89d283a4e992e88> /System/Library/PrivateFrameworks/Pegasus.framework/Pegasus
0x191a30000 -        0x191a57fff  PersistentConnection arm64  <8d0b7602daee3aa588c37704a6e3a206> /System/Library/PrivateFrameworks/PersistentConnection.framework/PersistentConnection
...

it caused the symbolicatecrash (perl) script to get stuck.
The reason is that the script was originally intended to chain similar entries, assuming they have a different base address. However that code was never working because it has a bug:
# add ourselves to that chain
$images{$nextIDKey}{nextID} = $image{base};

# and store under the key we just recorded
$bundlename = $bundlename . $image{base};

The bug is that the first line should actually be:
$images{$nextIDKey}{nextID} = $bundlename . $image{base};

However I'm suggesting a workaround that will ignore these duplicated lines by adding a next command a bit above this code, i.e.
# frameworks and apps (and whatever) may share the same name, so disambiguate
if ( defined($images{$bundlename}) ) {
    next;

this is not a clean solution because we are missing some protection here, but a least it will work for most of the cases.
Anyway hoping for Apple to remove these duplications soon.

A: You can use the following shell script which will patch symbolicatecrash to fix it:
curl -o /tmp/t.patch https://raw.githubusercontent.com/zqxiaojin/OptSymbolicatecrash/master/fix_dead_loop.patch && cd `xcode-select -p`/../SharedFrameworks/DTDeviceKitBase.framework/Versions/A/Resources/ && sudo patch symbolicatecrash  /tmp/t.patch && cd -

Or copy the symbolicatecrash from my github https://github.com/zqxiaojin/OptSymbolicatecrash


text:
Q: How to do: underline, bold, italic, strikethrough, color, background, and size in Gnome Terminal? How to do: underline, bold, italic, strikethrough, and color in Gnome Terminal?
Bold
Italic
u̲n̲d̲e̲r̲l̲i̲n̲e̲
s̶t̶r̶i̶k̶e̶ ̶i̶t̶ ̶l̶i̶k̶̶e̶ ̶i̶t̶s̶ ̶h̶o̶t
Color
background
font < (its mono if you couldn't tell)
size

A: To extend Sylvain's answer, some helper functions:
ansi()          { echo -e "\e[${1}m${*:2}\e[0m"; }
bold()          { ansi 1 "$@"; }
italic()        { ansi 3 "$@"; }
underline()     { ansi 4 "$@"; }
strikethrough() { ansi 9 "$@"; }
red()           { ansi 31 "$@"; }

Then

A: GNOME Terminal 3.28 (VTE 0.52), debuting in Ubuntu 18.04 LTS, adds support for a few more styles including curly and colored underlines as seen in Kitty, overline as seen in Konsole, and finally everyone's much loved or much hated blink attribute as well.
These also automatically work in any other VTE-based terminal emulator (e.g. Tilix, Terminator, Xfce4-terminal, Guake etc.), given that VTE is at least at version 0.52.
Here's a list demonstrating the standard escape sequences, as well as GNOME Terminal's (VTE's) additions. Note that for every opening sequence I'm also showing the closing sequence of that property only, rather than the generic \e[m or \e[0m that disables all special modes.
echo -e '\e[1mbold\e[22m'
echo -e '\e[2mdim\e[22m'
echo -e '\e[3mitalic\e[23m'
echo -e '\e[4munderline\e[24m'
echo -e '\e[4:1mthis is also underline (new in 0.52)\e[4:0m'
echo -e '\e[21mdouble underline (new in 0.52)\e[24m'
echo -e '\e[4:2mthis is also double underline (new in 0.52)\e[4:0m'
echo -e '\e[4:3mcurly underline (new in 0.52)\e[4:0m'
echo -e '\e[5mblink (new in 0.52)\e[25m'
echo -e '\e[7mreverse\e[27m'
echo -e '\e[8minvisible\e[28m <- invisible (but copy-pasteable)'
echo -e '\e[9mstrikethrough\e[29m'
echo -e '\e[53moverline (new in 0.52)\e[55m'

echo -e '\e[31mred\e[39m'
echo -e '\e[91mbright red\e[39m'
echo -e '\e[38:5:42m256-color, de jure standard (ITU-T T.416)\e[39m'
echo -e '\e[38;5;42m256-color, de facto standard (commonly used)\e[39m'
echo -e '\e[38:2::240:143:104mtruecolor, de jure standard (ITU-T T.416) (new in 0.52)\e[39m'
echo -e '\e[38:2:240:143:104mtruecolor, rarely used incorrect format (might be removed at some point)\e[39m'
echo -e '\e[38;2;240;143;104mtruecolor, de facto standard (commonly used)\e[39m'

echo -e '\e[46mcyan background\e[49m'
echo -e '\e[106mbright cyan background\e[49m'
echo -e '\e[48:5:42m256-color background, de jure standard (ITU-T T.416)\e[49m'
echo -e '\e[48;5;42m256-color background, de facto standard (commonly used)\e[49m'
echo -e '\e[48:2::240:143:104mtruecolor background, de jure standard (ITU-T T.416) (new in 0.52)\e[49m'
echo -e '\e[48:2:240:143:104mtruecolor background, rarely used incorrect format (might be removed at some point)\e[49m'
echo -e '\e[48;2;240;143;104mtruecolor background, de facto standard (commonly used)\e[49m'

echo -e '\e[21m\e[58:5:42m256-color underline (new in 0.52)\e[59m\e[24m'
echo -e '\e[21m\e[58;5;42m256-color underline (new in 0.52)\e[59m\e[24m'
echo -e '\e[4:3m\e[58:2::240:143:104mtruecolor underline (new in 0.52) (*)\e[59m\e[4:0m'
echo -e '\e[4:3m\e[58:2:240:143:104mtruecolor underline (new in 0.52) (might be removed at some point) (*)\e[59m\e[4:0m'
echo -e '\e[4:3m\e[58;2;240;143;104mtruecolor underline (new in 0.52) (*)\e[59m\e[4:0m'

(*) Truecolor values for underlines are slightly approximated.
And a bit odd one that doesn't quite fit in this picture, as it's more of a functionality than a style, yet is probably worth mentioning here, is hyperlink support co-designed with iTerm2, available since GNOME Terminal 3.26 (VTE 0.50):
echo -e '\e]8;;http://askubuntu.com\e\\hyperlink\e]8;;\e\\'

Here's a screenshot demonstrating the result:

A: Something that has not been covered yet is the combination of two or three parameters, e. g. bold and underline, in a predefined color. This is achieved by a 3-way syntax, for instance:
~$ printf "\e[3;4;33mthis is a test\n\e[0m"

will cause "this is a test" to be printed in yellow color (33m), italic (3m) AND underlined (4m).
Note that it is not necessary to repeat the \e[ every time.
Note too that (alike to Sylvain) I also added a \e[0m to reset settings every time, because otherwise the yellow color and the font style will remain active in terminal! Needless to say that you absolutely have to watch out for these to get reset in scripts, because users who use your scripts may dislike it if your script permanently modifies their color + style settings in terminal!

A: Replace these hard-coded sequences by:
tput smul # set underline
tput rmul # remove underline

tput smso # set bold on
tput rmso # remove bold

tput setaf 1 #red
tput setaf 2 #green
...
tput cup 0 0 # move to pos 0,0

Refer to "man terminfo" and "man tput" for complete descriptions of these commands.
Example :
function f_help
{
  c_green=$(tput  setaf 2      2>/dev/null)
  c_reset=$(tput  sgr0         2>/dev/null)
  c_bold=$(tput smso           2>/dev/null)
  echo "${c_bold}DESCRIPTION${c_reset} : .... ${c_green}My green text${c_reset}My plain text"
}

A:
The ANSI/VT100 terminals and terminal emulators are not just able to
  display black and white text; they can display colors and formatted
  texts thanks to escape sequences. Those sequences are composed of the
  Escape character (often represented by "^[" or "Esc") followed by
  some other characters: "Esc[FormatCodem".

In Bash, the  character can be obtained with the following syntaxes:
\e
\033
\x1B

The commands (for easy copy-paste):
echo -e "\e[1mbold\e[0m"
echo -e "\e[3mitalic\e[0m"
echo -e "\e[3m\e[1mbold italic\e[0m"
echo -e "\e[4munderline\e[0m"
echo -e "\e[9mstrikethrough\e[0m"
echo -e "\e[31mHello World\e[0m"
echo -e "\x1B[31mHello World\e[0m"

Source (including all types of foreground/background color codes): http://misc.flogisoft.com/bash/tip_colors_and_formatting


text:
Q: Making a module a vector space Let $G$ be an abelian group whose elements are all of prime order $p$.  Naturally, $G$ is a  $\Bbb Z$-module.  Now take a maximal ideal $(p)$ and divide the scalar ring with it.  Then one can consider $G$ as a vector space whose scalars are from the field $\Bbb Z/(p)$.
Does this kind of construction of a vector space have a name or is it based on some general principle?

A: You can always start with a ring $R$ and an $R$-module $M$. Considering the localization $M_{\mathfrak p}$ of the module $M$ at the prime ideal $\mathfrak p$ (which can be realized as $R_{\mathfrak p} \otimes_R M$), you can assume the ring local. Then you can consider the tensor product $R_{\mathfrak p}/\mathfrak p R_{\mathfrak p} \otimes_{R_{\mathfrak p}} M_{\mathfrak p}$, which is naturally a $\kappa(\mathfrak p)$-module (where $\kappa(\mathfrak p) = R_{\mathfrak p} / \mathfrak p R_{\mathfrak p}$).
For instance, if I start with a finite abelian group $G$, $\mathbb Z/p\mathbb Z$ is already a field, so no need to localize (this is because $\mathbb Z$ is a PID, so all non-zero prime ideals are maximal ; if you had done this construction with $(0)$, you would have no need to quotient, just to localize). If you write
$$
G = \bigoplus_{i=1}^n \mathbb Z/p_i^{n_i} \mathbb Z, \quad n_i \ge 1
$$
then $\mathbb Z/p\mathbb Z \otimes_{\mathbb Z} G$ is a $\mathbb Z/p \mathbb Z$-vector space with dimension equal to the number of $p_i$'s equal to $p$.
If you apply this construction to the $R$-module $R$, you get the residue fields $\kappa(\mathfrak p)$. Examples where this construction is relevant are a bit more complicated to explain and I don't know your background so I can't think of anything relevant at the moment.
Hope that helps,


text:
Q: Google sheet : Find-and-replace/remove using formula I have Col A2 -> Contains Reviews
Col B2 -> contains parasite text
The Col C2 should be same as col A2 (Reviews) except that whatever parasite/text in B2 has to be removed from it.
Please look at a sample below.

Col A
Col B
Col C

The car is good  one
one
The car is good

A proper place to stay
stay
A proper place to

Is there a forumla that can achieve this functionality  ?

A: =REPLACE(A2,FIND(B2,A2),LEN(B2),"")

*

*FIND gives you the starting position of the parasite string in Col A.

*LEN gives you the length of the parasite string

*REPLACE removes from Col A the parasite string and replaces it with an empty string

Please note that this will not trim whitespace characters (e.g. there is an extra space at the end of Col C).


text:
Q: solving a piecewise ODE In mechanics the simple equation $\ddot{x}+2\zeta\omega_n\dot{x}+\omega_n^2x=0$ is often used to model a mass-spring-damper system where no external force is used and the solution to this equation is very easy to calculate and well known, then ICs can just be inputted and its sorted. However, I was wondering what I can do in this situation if I were to model the damper more realistically, that is the damper constant is not the same both directions of motion:
$$c=\begin{cases}c_1&\dot{x}>0\\0&\dot{x}=0\\c_2&\dot{x}<0\end{cases}$$
this is defined in the equation as:
$$\zeta=\frac{c}{2m\omega_n},\omega_n=\sqrt{\frac km}$$
any sorces on this kind of modelling or approaching this problem would be appreciated, Thanks!


text:
Q: Class constructor defining inherited classes constructor syntax error in header file I have the below code giving me a syntax error on the BindingSocket definition, my understanding was if I wanted to define an inherited classes constructor I continue the BindingSocket definition with BindingSocket(...):Socket(...);, however this gives me a standard syntax error output.
#ifndef NETWORKING_BINDINGSOCKET_HPP_
#define NETWORKING_BINDINGSOCKET_HPP_

#include <stdio.h>
#include "Socket.hpp"

namespace HDE
{
    class BindingSocket: public Socket
    {
        public:
            BindingSocket(...) : Socket(...);
    };
}

and then within my main cpp file I can write:
HDE::BindingSocket::BindingSocket(...): Socket(...)
{

Strangely enough if I add a {} at the end of the header definition for the class I get no syntax error.

A: The inheritance is given by class BindingSocket: public Socket.
The : Socket(...) after the constructor calls the parent constructor and belongs to the definition and not to the declaration.
So it has to be:
namespace HDE
{
    class BindingSocket: public Socket
    {
        public:
            BindingSocket(...);
    };
}

And:
HDE::BindingSocket::BindingSocket(...): Socket(...)
{


text:
Q: Incoming calls are not being initiated using Twilio Node Server ( Not sending VoIP notifications ) - Fixed I'm trying to initiate calls on my mobile app (Inbound call ) through my node server. I have set up all credentials in the env file and cross-checked them many times. I'm doing so using the Twiml.
I'm sending the below the Twiml response to Twilio but the call just keeps routing back to the Webhook URL. How can I route the call on the device if this is not the right way to do it.
Twiml Response :
  <Response>
    <Dial>
      <Number>+12528881526</Number>
    </Dial>
  </Response>

My Node.js code
  let twimlResponse = new VoiceResponse()
  const dial = twimlResponse.dial()
  dial.number({}, "+1234567891")
  console.log(twimlResponse.toString())
  return response.send(twimlResponse.toString())

Solution:
We need to initiate calls using the identity and Twilio will start sending VoIP notifications
  let twimlResponse = new VoiceResponse()
  const dial = twimlResponse.dial()
  dial.client({}, "alice")
  console.log(twimlResponse.toString())
  return response.send(twimlResponse.toString())

A: I believe the process you use is to redirect a received call to another number "new VoiceResponse()", i believa to you to originate a call you should use the code below. Please let me know if tha works.
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);

client.calls
      .create({
         twiml: '<Response><Say>Ahoy there!</Say></Response>',
         to: '+15558675310',
         from: '+15552223214'
       })
      .then(call => console.log(call.sid));

A: On Twilio you can create a new project,select you want to do calls and they will provide you the right code,just copy it and use node index.js in your application.Also if you have a trial version you can only call numbers you verified.


text:
Q: Do proxy in Dart by using noSuchMethod? I have many service classes which simply do the http requests, and I want to count the number of currently running http requests. My naive idea is to use a proxy like -
int currentRunHttpRequestCounter = 0;

class MyProxy {
  noSuchMethod() {
    currentRunHttpRequestCounter+=1;
    magically_call_the_original_class(...);
    currentRunHttpRequestCounter-=1;
  }
}

However, I do not know how to magically_call_the_original_class? In other words, how do I create a proxy that passes every method call down to the original class?
Thanks!

A: create one abstract HTTP service with static counter.
inside that abstract service use counter and logging inside your HTTP methods.
Then extend that service into mocked or real service, and every time you call it it will update the counter.

class Counter {
  var getCount = 0;
}

abstract class HttpService {
  static Counter counter = Counter();

  Future<dynamic> get(Map<String, dynamic> query) {
    counter.getCount++;
    // use for logging ect
  }
}

class HttpMockedService extends HttpService {
  @override
  Future get(Map<String, dynamic> query) {
    // TODO: implement get
    super.get(query);
  }
}

class HttpRealService extends HttpService {
  @override
  Future get(Map<String, dynamic> query) {
    // TODO: implement get
    super.get(query);
  }
}

This is simplified solution, but you can play with many approaches to it.


text:
Q: Is there a way to attach documents to Google Sheets? I am trying to manage a set of documents with Google Sheets.
I tried service like Evernote but I prefer displaying those document in a table form.

A: If the documents are Google docs, you can attach the internet address of the Google doc in the sheet.

A: what do you mean by attach? I mean, what behavior do you expect?
Anyway, the only way I think is to upload this document, if it's not already an online document, you want to attach to somewhere online accessible, e.g. your Google Docs, and place the document link on a cell.