text:
Q: Vue.js build with different environment variables I've used official Webpack template for Vue.js. It uses separate configuration for different environments. They offer test, development and production. However, I need another one as we have two production servers (one production and one staging).
What is the best practice to have different configurations for different production environments? I would think of something like npm run build --URL:http://some-url.com --PORT:80 ....
Any advice is welcome!

A: There is a simple way. In config/prod.env.js append your variables like this:
module.exports = {
  NODE_ENV: '"production"',
  MY_URL: JSON.stringify(process.env.MY_URL || 'http://example.com')
}

Then run your build like this: MY_URL=http://example.org npm run build
Your variable will be available in main.js as process.env.MY_URL

A: This is more like a webpack question rather then Vue.js,
I wanna share our previous setup for handling different build files and environments.
first of all, we keep our config in separated folder.
config/index.js
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')

const CDN = 'https://cdnURL.com/'

module.exports = {
  build: {
    env: require('./prod.env'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: CDN,
    productionSourceMap: true,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    productionBundleAnalyze: process.env.ANALYZE ? true : false
  },
  dev: {
    env: require('./dev.env'),
    port: 8080,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: process.env.npm_package_config_proxy,
        logLevel: 'debug',
        changeOrigin: true,
        onProxyRes(proxyRes, req, res) {
          // http-proxy-middleware
          proxyRes.headers['Content-Type'] = proxyRes.headers['content-type']
          delete proxyRes.headers['content-type']
        }
      }
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  },
  projects: {
    main: {
      entry: './packages/home/index.js',
      devPath: 'main.html',
      target: 'web',
      buildPath: path.resolve(__dirname, '../dist/index.html'),
      testPath: '../packages/home/__test__/index.js'
    },
    desktop: {
      entry: './packages/desktop/index.js',
      devPath: 'desktop.html',
      target: 'electron-renderer',
      buildPath: path.resolve(__dirname, '../../static/desktop.html'),
      assetsRoot: path.resolve(__dirname, '../../'),
      assetsSubDirectory: 'static',
      assetsPublicPath: '../',
      testPath: '../packages/desktop/__test__/index.js'
    },
    login: {
      entry: './packages/login/index.js',
      devPath: 'login.html',
      target: 'web',
      buildPath: path.resolve(__dirname, '../dist/login.html'),
      testPath: '../packages/login/__test__/index.js'
    },
    setting: {
      entry: './packages/setting/index.js',
      devPath: 'setting.html',
      target: 'web',
      buildPath: path.resolve(__dirname, '../dist/setting.html'),
      testPath: '../packages/setting/__test__/index.js'
    },
    playground: {
      entry: './packages/playground/index.js',
      target: 'web'
    }
  }
}

config/dev.env.js
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_ROOT: '"/api"'
})

config/prod.env
module.exports = {
  NODE_ENV: '"production"',
  API_ROOT: '"http://test.example.co/api"'  //staging server
  // API_ROOT: '"http://127.0.0.1:8787/api"'  //mock-up server
}

incase of where we wanna work we change API root in here.
and our webpack.base.conf.js look like this.
build/webpack.base.conf.js
var path = require('path')
var config = require('../config')
var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../')

const isProduction = process.env.NODE_ENV === 'production'

module.exports = {
  entry: utils.entrys(),
  output: {
    path: config.build.assetsRoot,
    publicPath: isProduction ? config.build.assetsPublicPath : config.dev.assetsPublicPath,
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'src': path.resolve(__dirname, '../src'),
      'assets': path.resolve(__dirname, '../src/assets'),
      'components': path.resolve(__dirname, '../src/components')
    },
    unsafeCache: true
  },
  target: config.projects[process.env.npm_package_config_dev].target,
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          postcss: [
            require('postcss-cssnext')(),
            require('lost')()
          ],
          cssModules: {
            localIdentName: isProduction ? '[path][name]---[local]---[hash:base64:5]' : '[path][name]--[local]',
            camelCase: true
          },
          loaders: Object.assign({}, utils.cssLoaders()),
          preLoaders: {
            html: 'inline-svg-loader'
          }
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: projectRoot,
        exclude: /node_modules/,
        query: {
          cacheDirectory: true
        }
      },
      {
        test: /\.json$/,
        loader: 'json-loader'
      },
      {
        test: /\.html$/,
        loader: 'vue-html-loader'
      },
      {
        test: /\.(png|jpe?g|gif)(\?.*)?$/,
        loader: 'url-loader',
        query: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        query: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  }
}

and finally our package.json is look like this
...
...
...
    "scripts": {
      "dev": "webpack-dashboard -- node build/dev-server.js",
      "dev:login": "npm config set mesh:dev login && npm run dev",
      "dev:setting": "npm config set mesh:dev setting && npm run dev",
      "dev:main": "npm config set mesh:dev main && npm run dev",
      "dev:desktop": "npm config set mesh:dev desktop && node build/dev-server.js",
      "dev:playground": " npm config set mesh:dev playground && cross-env PORT=9000 npm run dev"
     }
...
...
...

we used this setup for bundle our app for electron, web, and webkit while using shared components.
but still later on we had issue of scalling. and we started to use lerna if you need something more moduler. I recommend you to check that one out.
Best regards.

A: PROD: config/prod.env.js append your VAR='"value"'
'use strict'
module.exports = {
  NODE_ENV: '"production"',
  API_URL: '"https://production URL"'
}

DEV: config/dev.env.js append your VAR='"value"'
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_URL: '"http://localhost"'
})

Your variable will available as process.env.API_URL or process.env.VAR_NAME

A: The variable process.env.NODE_ENV always has two values:
development - production.
With this variable you can determine which url to use.
for example:
const API_URL = {
  development: "http://localhost/api/",
  productrion: "https://api.example.com/api/",
};
const baseURL = API_URL[process.env.NODE_ENV];


text:
Q: C# Assign a subclass of a property type to the property? I did over an hour of searching on StackOverflow and elsewhere, and could not find an answer to this exact question.
In Unity 2020.1, I have a State() class with a StateLogic property. There are several subclasses of StateLogic to handle the game logic for different states, such as IdleStateLogic and MoveToStateLogic. The idea is that State() itself is generalized, and different scriptable objects for game logic, sensing, and transitions can be added in the inspector (this is heavily based on the "Pluggable AI" architecture).
However, the StateLogic property is unique in that it needs to be able to be assigned subclasses of StateLogic(). However, currently subclassed StateLogic() classes cannot be assigned to the property:
public class State : ScriptableObject
{
    [field: SerializeField]
    public virtual StateLogic stateLogic { get; set; }

    ...

The StateLogic() base class is defined with public abstract class StateLogic : ScriptableObject. And its subclass IdleStateLogic() is defined with public class IdleStateLogic : StateLogic.
How do I modify the StateLogic property on State(), such that I can assign a StateLogic() subclass to it like IdleStateLogic()?
EDIT:
Here is the simplest possible minimal reproducible example I could make:
The StateController has a currentState:
public class StateController : MonoBehaviour
{
    public State currentState;
}

The currentState State is a ScriptableObject that hold references to its game logic StateLogic, its Actions, and its Transitions (all of these are separate classes):
public class State : ScriptableObject
{
    [field: SerializeField]
    public virtual StateLogic stateLogic { get; set; }
    public Action[] actions;
    public Transition[] transitions;
}

The stateLogic property is visible in the inspector, but nothing can be assigned to it. The goal is to be able to assign subclasses of StateLogic to the stateLogic property of State in the inspector. Subclasses like IdleStateLogic:
public class IdleStateLogic : StateLogic
{
    /// <summary>
    /// Note that we're taking UnitStateController instead of the base class' StateController, so this is not
    /// an override method.
    /// </summary>
    /// <param name="c"></param>
    public void Enter(UnitStateController c)
    {
        Debug.Log("Enter IdleStateLogic");
    }
}

So the question is, why can't I assign anything to the stateLogic property in the inspector? Shouldn't IU be able to drag and drop a subclass of StateLogic to that property? The problem persists when stateLogic is declared instead as public StateLogic stateLogic;
I simply don't understand why it can't be assigned to.

A: You can't assign to stateLogic in the inspector because it is a property, not a field. Try this:
public class State : ScriptableObject
{
    public StateLogic stateLogic;
    public Action[] actions;
    public Transition[] transitions;
}

A consequence of this is that it also can't be virtual. That seems a bit over-engineered for your use case anyway, though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML to NSAttributedString and NSAttributedString to HTML I want to convert a html string to NSAttributedString and then work on the string like (change colors, fontsizes, fontfamily, background- , foreground-color...) and then convert the string back to plain html from the NSAttributedString.
Converting isn't a problem, but on each time I convert html to NSAS and back the fontsize getting bigger and bigger...
Sample playground:
// Playground - noun: a place where people can play
// NSAS: - NSAttributedString

import UIKit

class Wrapper {

    //MARK: fields
    let apiHtml = "
Dies ist eine formatierte Karte die es zu Übernehmen gilt
"

    var newGeneratedHtml = ""
    var textView : UITextView!

    //MARK: constructor
    init() {
        //init textview
        textView = UITextView(frame: CGRectMake(0, 0, 500, 300))

        //convert html into NSAS and set it to textview
        if let attributedText = getAttributedTextFromApiHtmlString(apiHtml) {
            textView.attributedText = attributedText
        }

        //get html text from textfields NSAS
        if let htmlText = getHtmlTextFromTextView() {
            newGeneratedHtml = htmlText
            println(htmlText)
        }

        //set the converted html from textfields NSAS
        if let attributedText = getAttributedTextFromApiHtmlString(newGeneratedHtml) {
            textView.attributedText = attributedText
        }

        //get html text from textfields NSAS
        if let htmlText = getHtmlTextFromTextView() {
            newGeneratedHtml = htmlText
            println(htmlText)
        }
    }

    //MARK: methods
    func getAttributedTextFromApiHtmlString(text : String) -> NSAttributedString? {
        if let attributedText = NSAttributedString(data: text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil, error: nil) {
            return attributedText
        }
        return nil
    }

    func getHtmlTextFromTextView() -> String? {
        let attributedTextFromTextView = textView.attributedText
        if let htmlData = attributedTextFromTextView.dataFromRange(NSMakeRange(0, attributedTextFromTextView.length), documentAttributes: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], error: nil) {
            if let htmlString = NSString(data: htmlData, encoding: NSUTF8StringEncoding) {
                return htmlString
            }
        }
        return nil
    }
}

var w = Wrapper()

This is the playground result. You can see that the second text is bigger as the first text but I didn't change the font size anywhere.
Is this a bug or had I have to set a fix font size?

UPDATE:
I accept @Lou Franco answer. I don´t know why NSAS convert px to pt and back but here is my workaround:
func getAttributedTextFromApiHtmlString(text : String) -> NSAttributedString? {
        if let attributedText = NSAttributedString(data: text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil, error: nil) {

            var res : NSMutableAttributedString = attributedText.mutableCopy() as NSMutableAttributedString
            res.beginEditing()
            var found : Bool = false;
            res.enumerateAttribute(NSFontAttributeName, inRange:NSMakeRange(0, res.length) ,options:NSAttributedStringEnumerationOptions.allZeros, usingBlock: {(value:AnyObject!, range:NSRange, stop:UnsafeMutablePointer<ObjCBool>) -> Void in
                if ((value) != nil) {
                    let oldFont = value as UIFont;
                    let newFont = oldFont.fontWithSize(15)
                    res.removeAttribute(NSFontAttributeName, range:range)
                    res.addAttribute(NSFontAttributeName, value: newFont, range: range)
                    found = true
                    }
                })
            if !found {
                // No font was found - do something else?
            }
            res.endEditing()
            return res
        }
        return nil
    }

The only disadvantage of this is that you lose different text heights in your NSAS....
If anybody has the solution or better work around feel free to post your answer.

A: I solved this by applying 0.75 ratio on each fond size in your string. Say if you have multiple fonts in your attributed string, when you looping though all of them, simple apply the ratio and then you are all set. Here is my code in swift 3.0:
yourAttrStr.beginEditing()
yourAttrStr.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, yourAttrStr.length), options: .init(rawValue: 0)) {
        (value, range, stop) in
        if let font = value as? UIFont {
            let resizedFont = font.withSize(font.pointSize * 0.75)
            yourAttrStr.addAttribute(NSFontAttributeName, value: resizedFont, range: range)
        }
}
yourAttrStr.endEditing()//yourAttrStr will be the same size as html string

This is the piece of code that is running in my application
extension String {
    func htmlAttributedString() -> NSAttributedString? {
        guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
        guard let html = try? NSMutableAttributedString(
            data: data,
            options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
            documentAttributes: nil) else { return nil }
        html.beginEditing()
        html.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, html.length), options: .init(rawValue: 0)) {
            (value, range, stop) in
            if let font = value as? UIFont {
                let resizedFont = font.withSize(font.pointSize * 0.75)
                html.addAttribute(NSFontAttributeName,
                                         value: resizedFont,
                                         range: range)
            }
        }
        html.endEditing()
        return html
    }
}

To use it:
let htmlStr: String = "font aFont b"
let attriStr: NSAttributedString? = htmlStr.htmlAttributedString()

A: In Swift 3 taking @fangming's solution, that worked for me:
func newAttrSize(blockQuote: NSAttributedString) -> NSAttributedString
{
    let yourAttrStr = NSMutableAttributedString(attributedString: blockQuote)
    yourAttrStr.enumerateAttribute(.font, in: NSMakeRange(0, yourAttrStr.length), options: .init(rawValue: 0)) {
        (value, range, stop) in
        if let font = value as? UIFont {
            let resizedFont = font.withSize(font.pointSize * 0.75)
            yourAttrStr.addAttribute(.font, value: resizedFont, range: range)
        }
    }

    return yourAttrStr
}

A: It's probably rounding errors in the round-trip. Try using integer point sizes (with pt instead of px)
Ok, looking at your console output, it's translating your px to pt, so maybe you can hack it by taking the HTML that comes from the conversion and changing pt back to px.


text:
Q: How does this inequality of a complex function hold I cannot figure out how $\Re[g(\lambda)]\leq |\lambda|$ implies $|g(\lambda)|\leq|2 r-g(\lambda)|$ where $\lambda$ is an arbitrary complex number s.t. $|\lambda|\leq r$, and $g$ is an entire function.  I tried all the elementary inequalities used in complex analysis, but I couldn't prove. Could anyone give me a hint? This is from the following lemma of Rudin's Functional Analysis. I don't think we need deep knowledge in functional analysis or properties of entire function to prove this.

A: Put $\;x:=\text{Re}(g(\lambda))\;,\;\;y:=\text{Im}(g(\lambda))\;$ , then
$$|g(\lambda)|=\sqrt{x^2+y^2}$$
OTOH
$$|2r-g(\lambda)|=\sqrt{\left(2r-x\right)^2+y^2}=\sqrt{4r^2-4rx+x^2+y^2}$$
Thus, we have
$$|g(\lambda)|\le|2r-g(\lambda)|\iff x^2+y^2\le4r^2-4rx+x^2+y^2\iff x\le r$$
which is true since we're given
$$x=\text{Re}(g(\lambda))\stackrel{\text{given}}\le|\lambda|\stackrel{\text{given}}\le r$$


text:
Q: How to change navbar colour after scrolling? I am trying to chnage the colour of my navbar from transparent to black after the user scrolls down. However, my javascript does not seem to work as nothing happens. I have looked at several videos and similar questions and none have worked
HTML

        <input type="checkbox" />

Home

Submit Image

Search Image

Login/Sign up

JS

CSS
.bg-transparent{
  height: 90px;
  }

.bg-transparent.scrolled{
  background: black !important;
}

A: Your JavaScript code is incorrect.
Test with this code :
  window.onscroll = function () { scrollHeaderHandler() };

  function scrollHeaderHandler() {
    if (window.pageYOffset > 100) {
      $('nav').addClass('scrolled');
    } else {
      $('nav').removeClass('scrolled');
    }
  }


text:
Q: .htaccess RewriteRule not working, bad flag delimiters My site previously uses URL's like this: /folder/page
Previously, you could prepend 'panel' in the URL to edit the current page: /panel/folder/page
We upgraded our CMS, and the new URL to edit the page is in this format: /panel/#/pages/show/folder/page
I am trying to add a rewrite rule so that we can still use the old way, but can't get it to work:
RewriteCond %{REQUEST_URI} !^/panel/#/
RewriteRule /panel(.*) /panel/#/pages/show/$1

Is there a way to do this? A 301 redirect should work too, I think.
Edit: here is my existing .htaccess:
RewriteEngine on

RewriteBase /

# make panel links work
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^panel/(.*) panel/index.php [L]

# make site links work
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*) index.php [L]

A: Since "panel" is already used, I ended up using this redirect rule:
RedirectMatch 301 /admin(.*) /panel/#/pages/show/$1


text:
Q: How do I configure an Azure Function App to authenticate to an Azure Artifact Feed with pip? I have a Python project that I want to deploy to an Azure Function App.  The project has a dependency on a package that's available from a private Azure Artifact Feed.
I can build the project locally by setting the --index-url flag in my requirements.txt to the artifact feed and authenticating with artifact-keyring.  I just had to add my user as an owner, although I assume being a reader would have worked as well.  When I try to deploy the project from Visual Studio Code or from the Azure CLI, the deployment hangs on the pip installation.  I assume that pip is waiting for authentication.
Does anyone know how to configure authentication for Azure Function Apps, pip, and an Azure Artifact Feed so that a project can be deployed via the Azure CLI?

A: Navigate to your Function App in Azure, and select Configurations from the left-hand blade.
Under Application Settings add:
Key                 | Value
PIP_EXTRA_INDEX_URL | URL to Index from Artifact Feed (i.e https://pkgs.dev.azure.com/....)
Finally in your requirements.txt file add the package:
package-name==0.1.5
When you deploy your function app you'll see it's able to find the index (however it will get stuck because it needs to authenticate).
This is where you need basic authetication or a pip authentica


text:
Q: Search for specific key and value from dictionary, in python dic = {"Name":"Test1","Age":"23"},{"Name":"Test2","Age":"24"},{"Name":"Test3","Age":"21"}

Search for Test3 and print 21

A: You probably want your dictionaries to be inside of a list, like this:
dic = [{"Name":"Test1","Age":"23"},{"Name":"Test2","Age":"24"},{"Name":"Test3","Age":"21"}]

Now we can find Name with value "Test3" and print Age.
for d in dic:
    if d["Name"] == "Test3":
        print("Age is: " + d["Age"])

A: Based on the syntax you have given, python will treat it as tuple of dict objects. Let's see:
>>> dic = {"Name":"Test1","Age":"23"},{"Name":"Test2","Age":"24"},{"Name":"Test3","Age":"21"}
>>> type(dic)
<type 'tuple'>  # type as "tuple"
>>> dic  # lets print the content
    ({'Age': '23', 'Name': 'Test1'}, {'Age': '24', 'Name': 'Test2'}, {'Age': '21', 'Name': 'Test3'})
#   ^ All "dict" objects wrapped in `(...)`

You need to just iterate over the tuple (which are similar to list as far as iteration is considered), and check for the Name value as Test3. Sample code:
>>> for item in dic:
...     if item["Name"] == "Test3":
...         print(item["Age"])
...
21


text:
Q: Groovy Postbuild do not execute scripts on Jenkins I've written simple groovy script, but I don't know how to execute it on Jenkins.
Look at this simple script:
String jbN = System.getenv('JOB_NAME')
println  jbN
println "Hello"

I would except that I will reveived at least "Hello". Script give no return. I've just received Build step 'Groovy Postbuild' marked build as failure(or success)
It seems that script is not executed.
EDIT:
I didn't add it, but I have already script which will analize logs, so I need it to execute it post-build.
The problem is bigger then I thought. Plugins: "Scriptler" or "Groovy Plugin" do not print anything.
Script which I'm trying to print out:
String jbN = System.getenv('JOB_NAME')
println  jbN

A: I found the solution:
Script was executed but wasn't printed to console output.
To print result to console output you need to write:
manager.listener.logger.println("Some string") instead of println.
To make it shorter do:
logger = manager.listener.logger.&println
 // and call like this:
 logger("test log message")

EDIT: add in logger example and to describe how to get env vars (and how to not get them) and to hopefully save people some debugging time . . . this is simple but awkward stuff.
To get the workspace you can go through the manager object. Like this:
manager.build.workspace
To get env vars, this does not work:
String jbN = System.getenv('JOB_NAME')
It shows jbN is null.
That makes sense as JOB_NAME is not an actual system environment var.
This also does not work to get env vars, an exception is thrown:
${manager.envVars['WORKSPACE']}
This does work to get jenkins job "env vars" like WORKSPACE, JOB_NAME, BUILD_NAME:
def build = Thread.currentThread().executable
 workspace = build.getEnvVars()["WORKSPACE"]

Example of use, you can call a groovy script in workspace like this:
evaluate(new File(manager.build.workspace.toString() + "/dirinworkspace/scriptname.groovy"))

A: In your case you want to use the Groovy plugin rather than the Groovy Postbuild plugin.
The Groovy Postbuild plugin is made to change the build result (postbuild).
The Groovy plugin is made to run simple Groovy scripts inside your job.

A: Click Manage Jenkins-->Script Console


text:
Q: Problems in installation of Joomla Hi there everyone im a newbie so can anyone of u help me solve this problem im having in the installation of joomla when im clicking joomla folder for installing it is giving the message: Unable to open WampServer's config file, please change path in index.php file so plz help me to solve this issue coz index.php is in some different lang thanks in advance

A: You could try http://bitnami.org/ for some easier installations? And possibly compare those installs with your own manual ones

A: The way to install joomla on your localhost would be to
1) extract the folder to your www folder. (eg: c:\wamp\www\j15 ).
2) go to the path (127.0.0.1/j15) from a browser.
3) Fairly simple from there.
4) Delete the installation folder.
If you've got issues with WAMP try reinstalling it. If still giving you issues. let us know the errors.


text:
Q: Contextual menu on only certain items in a "Source List" I have a window with a Source List (NSOutlineView). My source list has just two levels. Level one is header and level two is data. I want to have a contextual menu on some of the data cells. Not all.
First, I try to attach a menu on the table cell view who represents the data cell -> nothing happens.
Second, I attach a menu on the Outline View in IB -> the contextual menu opens on each cells (header and data). I search for stopping the opening of the menu, but I don't find anything.
Do you have some ideas ?
Thank you
OS X 10.8.2 Lion, Xcode 4.5.2, SDK 10.8

A: If you subclass NSOutlineView, you can override menuForEvent: to return a menu only if the user clicked on the correct row. Here's an example:
- (NSMenu *)menuForEvent:(NSEvent *)event;
{
    //The event has the mouse location in window space; convert it to our (the outline view's) space so we can find which row the user clicked on.
    NSPoint point = [self convertPoint:[event locationInWindow] fromView:nil];
    NSInteger row = [self rowAtPoint:point];

    //If the user did not click on a row, or is not exactly one level down from the top level of hierarchy, return nil—that is, no menu.
    if ( row == -1 || [self levelForRow:row] != 1 )
        return nil;

    //Create and populate a menu.
    NSMenu *menu = [[NSMenu alloc] init];
    NSMenuItem *delete = [menu addItemWithTitle:NSLocalizedString( @"Delete", @"" ) action:@selector(delete:) keyEquivalent:@""];

    [self selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];

    //Set the Delete menu item's represented object to the clicked-on item. If the user chooses this item, we'll retrieve its represented object so we know what to delete.
    [delete setRepresentedObject:[self itemAtRow:row]];

    return menu;
}

This assumes we're compiling with ARC, so you don't need to autorelease the menu object being created.

A: This extension + subclass (both NSOutlineView and NSTableView) does the sensible thing of seeing whether a menu is attached to a cell view or row view. Just a general, reusable subclass!
Set the menu on the cell view in outlineView:viewForTableColumn:item: – menu is a NSResponder property.
(Below is in Swift)
// An extension lets us both subclass NSTableView and NSOutlineView with the same functionality
extension NSTableView {
    // Find a cell view, or a row view, that has a menu. (e.g. NSResponder's menu: NSMenu?)
    func burnt_menuForEventFromCellOrRowViews(event: NSEvent) -> NSMenu? {
        let point = convertPoint(event.locationInWindow, fromView: nil)
        let row = rowAtPoint(point)
        if row != -1 {
            if let rowView = rowViewAtRow(row, makeIfNecessary: true) as? NSTableRowView {
                let column = columnAtPoint(point)
                if column != -1 {
                    if let cellView = rowView.viewAtColumn(column) as? NSTableCellView {
                        if let cellMenu = cellView.menuForEvent(event) {
                            return cellMenu
                        }
                    }
                }

                if let rowMenu = rowView.menuForEvent(event) {
                    return rowMenu
                }
            }
        }

        return nil
    }
}

class OutlineView: NSOutlineView {
    override func menuForEvent(event: NSEvent) -> NSMenu? {
        // Because of weird NSTableView/NSOutlineView behaviour, must set receiver's menu otherwise the target cannot be found
        self.menu = burnt_menuForEventFromCellOrRowViews(event)

        return super.menuForEvent(event)
    }
}

class TableView: NSTableView {
    override func menuForEvent(event: NSEvent) -> NSMenu? {
        // Because of weird NSTableView/NSOutlineView behaviour, must set receiver's menu otherwise the target cannot be found
        self.menu = burnt_menuForEventFromCellOrRowViews(event)

        return super.menuForEvent(event)
    }
}

A: It's not clear from your question whether your outline is view based or cell based.  That's important.
If you're view based, then your view instances can implement
- (NSMenu *)menuForEvent:(NSEvent *)theEvent

and return the menu appropriate to that item -- or nil f you don't want a menu at all.
If you're cell based, or if you don't want to handle this in the view class for some reason, you'll need to subclass NSOutlineView and implement - (NSMenu *)menuForEvent:(NSEvent *)theEvent there.  Again, you'll figure out which cell is hit or active, and decide from that what menu you want.

A: - (void)rightMouseDown:(NSEvent *)event

An NSView will not pass this to the next view, This method looks to see that the current class has a menuForEvent:, if it does then it is called. If it does not then it is finished and nothing else will happen. This is why you will not see an NSTableCellView respond to a menuForEvent: because the table view swallows the rightMouseDown:.
You may subclass the tableview and handle the rightMouseDown: event and call the NSTableCellView's rightMouseDown: and handle displaying your menu that you have constructed in your storyboard and hooked up to your NSTableViewCell.
Here is my solution in a subclassed NSTableView:
- (void)rightMouseDown:(NSEvent *)event
{
    for (NSTableRowView *rowView in self.subviews) {

        for (NSView *tableCellView in [rowView subviews]) {

            if (tableCellView) {
                NSPoint eventPoint = [event locationInWindow];
//            NSLog(@"Window Point:     %@", NSStringFromPoint(eventPoint));

                eventPoint = [self convertPoint:eventPoint toView:nil];
                eventPoint = [self convertPoint:eventPoint toView:self];
//            NSLog(@"Table View Point: %@", NSStringFromPoint(eventPoint));

                NSRect newRect = [tableCellView convertRect:[tableCellView bounds] toView:self];
//            NSLog(@"Rect: %@", NSStringFromRect(newRect));

                BOOL rightMouseDownInTableCellView = [tableCellView mouse:eventPoint inRect:newRect];
//            NSLog(@"Mouse in view: %hhd", mouseInView);

                if (rightMouseDownInTableCellView) {
                    if (tableCellView) {
                        // Lets be safe and make sure that the object is going to respond.
                        if ([tableCellView respondsToSelector:@selector(rightMouseDown:)]) {
                            [tableCellView rightMouseDown:event];
                        }
                    }
                }
            }
        }
    }
}

This will find where the right mouse event occurred, check to see if we have the correct view and pass the rightMouseDown: to that view.
Please let me know if this solution works for you.


text:
Q: What does "l. s. d." stand for? Here is the original text from Lord Macaulay's History of England:

They are the men of double entry, magnifying routine. In business they have added mechanical device to mechanical device, they have put wind, water, steam, and electricity into subjection; they have done most of the reckoning in England, and their brains are hieroglyphed with l. s. d.

Source: Macaulay, Thomas Babington. The History of England from the Accession of James the Second. Boston and New York: Houghton, Mifflin and Company, 1901. xviii. Print.

A: The correct form is £sd, for Pounds Shillings and Pence. £ is the symbol for pounds sterling, in the same way that $ is the symbol for dollars. I am an old, ex bookkeeper, I would write £ dozens of times a day, 5 days a week, in ledgers the size of my desk top.

A: Pounds-shillings-and pence
To make it more confusing (for some), we should look at the amounts in each.
12 pennies in a shilling - 20 shillings in a pound, which gives us 240 pennies in a pound.
Ireland had a similar system some years ago until they changed to the Euro.
One last bit of confusion, there was a halfpenny, and in fact, a farthing (quarter penny), not sure about this but I think the halfpenny and farthing are gone.

A: L.S.D. was the standard abbreviation for "Pounds, shillings, and pence".
  See wikipedia.
Note that wikipedia claims it was usually written £sd and "sometimes" as Lsd.  That was not my experience - I would have said "l. s. d." was at least as common.  (Source: I was 13 when the UK decimalized).

A: Given the location and the period, I think it's likely to be a commonly-used variant of "£sd" for "pounds, shillings, and pence" - that is, money. The abbreviation comes from the Latin librae, solidi, denarii.


text:
Q: Possible to maintain bind w/ delegate after removal then recreation of element I am creating bindings to all Anchors under LI in a UL. (I am using Delegate because I am at 1.6 jQuery version at work). Anyways, for a reason I remove a texts anchor. Then reapply it at a later time.
In short, is there a way to bind an Anchor tag with delegate, remove anchor tag because of some condition. Reapply anchor (via wrap), and then get back that binding?
Just so I am clear, I am using "delegate" - but once I unwrap the anchor tag, the binding is lost of good - even when I re-wrap it. ala.
jQuery(pc).delegate("li > a",'click', function(){
    showit(jQuery(this).closest('li').index());
    pc.find("li:not(:has(a))").wrap('<a href="#">'); <-- this is when I add it lateron
    jQuery(this).replaceWith(jQuery(this).text()); <-- this is when I remove it.
});

EDIT::: Perhaps this could help someone in the future. DELEGATE does work as intended. If you review my code, you will see that I wrap the "LI" , NOT the text in the li. That is why the event did NOT retain its bind. When I wrapped the text of the LI with an anchor, bingo - it worked.
I apologize for sidetracking peoples time. So, the solution is "wrapInner", not "wrap" in this case.

A: Do you mean something like this  ?
   if(new Date().getTime() % 2 == 0)
     {
        $("body").on('click','ul>li a', doWork);
     }
     else
    {
        $("body").off('click');
    }

     //...
     //...
     // later , ReBind the event ...

function doWork()
{
        alert('mod2');
}

jsbin

A: For more information, please see the "delegate" area of jQuery's on:
http://api.jquery.com/on/
If you apply your binding to the document, it should handle your adding and removing anchors:
jQuery(document).on('click', 'ul li a', function(event){
  // Check event here
  // Do something here
});


text:
Q: Using 'for' to analyze multiple cross sections of a matrix on RStudio I have a dataset of about 144 entries and 93 variables, where each column correspond to a municipality and the variables account for yearly measurements of environmental data (e.g: temperature, vegetated area, rainfall, etc). As said before, the variables are divided yearly, so I have one column named rainfall_2004, another one for rainfall_2005 and so on. The entire dataset has a timespan of 10 years. Here's a picture to better illustrate:

I wanted to develop a script where I could create a GLM for each municipality at each year. Luckily, I found Zuur's book, "Mixed Effect Models and Extensions in Ecology with R", which provides such code in one of his examples. I tried adapting it to my dataset, but something went wrong. My knowledge with R is a bit limited, so I'm missing something but I can't quite find it.
Here's Zuur's code:
library(AED); data(RIKZ)

Beta <- vector(length = 9)
for (i in 1:9) {
    Mi <- summary(lm(Richness ∼ NAP, subset = (Beach==i), data=RIKZ))
    Beta[i] <- Mi$coefficients[2, 1]
}

Now here's mine:
count <- dados_ampliados[, 1]
View(count)

for (i in count) {
    RA <- summary(glm(dados_ampliados$infect_2004 ~ dados_ampliados$mmax_2004 +
                                                    dados_ampliados$mmin_2004 +
                                                    dados_ampliados$mprec_2004 +
                                                    dados_ampliados$mumid_2004 +
                                                    dados_ampliados$prop_for_2004 +
                                                    dados_ampliados$prop_urb_2004 +
                                                    dados_ampliados$prod_2004,
                     family = poisson(),
                     subset = (dados_ampliados$Geocode==i),
                     data = dados_ampliados))

    count[i] <- RA$coefficients[2, 1]
}

Yet my code returns:
Error in `[<-.data.frame`(`*tmp*`, i, value = 0.357095537720183) :
  new columns would leave holes after existing columns

Any ideas as why is this happening? Thanks in advance.
Some observations:
File used in this code can be obtained here. This is a WeTransfer file, so it won't last forever.
In his text, Zuur explains that he's creating that model to analyze data on 9 different beaches. In his code, he compares the value of the 1:9 vector to the beach value, therefore I'm assuming the beaches aren't named, but numbered instead. So, for each value of the vector, he's going to model the corresponding beach. My data however isn't organized like that, but with geocodes provided by the Brazilian Institute of Statistics and Geography, therefore my adaption consisted on creating a vector of 144 entries, one for each row, and each one is populated by the municipalities' geocode. This and the substition of lm for glm were my main adaptations.
For the troubleshooting, I already tried changing the values of RA$coefficients from 2,1 to 1,1 or 1,2. The error remained.


text:
Q: Eclipse shortcuts on MacOS please teach me some shortcuts

*

*line swapping with above or below

*rename variables consistent which has same names
(It's Alt+Shift+R on windows Eclipse)

A: Take a look at this cheat sheet for eclipse on mac os.
Very easy to find by just searching for eclipse shortcuts mac cheat sheet on google ;-)
(so don't hesitate to use google)


text:
Q: how to change one array into another while canceling the recurring variables? I'm new to programing and was given a task of making a function that puts one array into the other with the following criteria: a variable in the destination array will repeat only once and the source and destination array will be of the same size.
the function i came up with is:
int RemoveDup (int src[],int dst[])
//recive two array compare them and copy the src array to dst,and only the none reacuring
//numbers,the arrays must be from the same size

{
int size_src;
int size_dst;
int i,n=0;
size_src = sizeof(src)/sizeof(int);//determine the size of source array
size_dst = sizeof(dst)/sizeof(int);//determine the size of destination array
if (size_src = size_dst);//checks that the array are in the same size
{
for(i = 0;i < size_src;i++)//the loop for advancing the copying process
{
dst[i] = src[i];
}
while (i<size_dst)
{
dst[i] = dst[i++];

if (dst[i] = dst[i++])//relay on the fact that if the function will find a similar varibale, the tested varibale will be set to 0 and the other one will come out clean in the check
dst[i] = 0;//eliminating the varibale in that specific address
}
}

return dst [i];

but it doesn't seems to work and have no idea where it is going wrong.
any help or clue will be appreciated .

A: I noticed that you're using sizeof(src) within a function that takes int src[] as a parameter. This is not doing what you think it is doing. In C, the size of arrays is not passed to functions along with the array itself (unlike some other languages you may be familiar with). You will have to pass the actual size as a separate parameter.
Also, some printf() statements will definitely help your debugging efforts. Make sure values are what you think they should be. Hopefully you have access to an interactive debugger, that would probably be really useful for you too.

A: In C you cannot declare a function that takes a parameter that is an array. When you use an array declarator as a function parameter the type is silently adjusted to the corrsponding pointer type. Any explicit array size (if specified) is discarded.
In other words, when you use this:
int RemoveDup (int src[],int dst[])

it is exactly equivalent to this:
int RemoveDup( int *src, int *dst )

It should now be obvious why sizeof(src)/sizeof(int) doesn't do the calculation that you wanted it to do.

A: well in fact it is possible to make a function recieve an array and not a pointer (given of course the size of the array is pre-defined).
so you can use:
int RemoveDup(int src[M],int dst[N]){
     .
     .
     .
return whatever;

I will agree though that using pointers is better.
In my opinion you should write a recursive function to do that using of course pointers.
so that the next call is (*src+1) so you look at the next cell.
the exit condition is then:
if (sizeof(src) == 0) {
 //exit recursion statement.
}


text:
Q: Android instrumentation: Pass test options using interpolation I am trying to pass some test options to my Android Instrumentation tests as below:
export value1="abcd"
export value2="pqrs"
export value3="xyz"

adb shell 'CLASSPATH=$(pm path androidx.test.services) app_process / \
  androidx.test.services.shellexecutor.ShellMain am instrument -r -w -e \
  targetInstrumentation com.example.test/com.example.runner.CustomAndroidRunner \
  -e class com.example.TestingDemo#testWithoutApiInvocation \
  -e clearPackageData true -e debug false \
  -e myKey1 "$value1" \
  -e myKey2 "$value2" \
  -e myKey3 "$value3" \
  androidx.test.orchestrator/androidx.test.orchestrator.AndroidTestOrchestrator'

In my test code, I am getting empty values for myKey(1)(2)(3).
As per my understanding, bash variables are not expanded inside the single quotes. So, when I included above command in double quotes, it is not running.
Is it possible to pass variable values to the tests as I am doing above?

A: Answering my own question. After debugging a bit more, I was able to get it working as below.
adb shell 'CLASSPATH=$(pm path androidx.test.services) app_process / \
  androidx.test.services.shellexecutor.ShellMain am instrument -r -w -e \
  targetInstrumentation com.example.test/com.example.runner.CustomAndroidRunner \
  -e class com.example.TestingDemo#testWithoutApiInvocation \
  -e clearPackageData true -e debug false \
  -e myKey1' "$value1" '\
  -e myKey2' "$value2" '\
  -e myKey3' "$value3" '\
  androidx.test.orchestrator/androidx.test.orchestrator.AndroidTestOrchestrator'


text:
Q: Image URLs stopped working due to Permalinks? I've been changing my Permalinks and changing my site the the "www" version (Which I think has broken my image and video links). All my images are "red x" now, both inside the library and the posts themselves. I have been looking in my cpanel and all the file paths are correct, but if I try to view them through WP or even just copy the url and try it within my browser, it appears broken.
Is there a way to fix this at all? Other than reload everything back up. :-(
To update: I just re-uploaded an image and it was saved as header1.png, so WP can see that there is another image in there. It's strange because all the paths seem to match in my library to where they are stored within cpanel.
I feel that because I cahnged the permalink structure to %category%/%postname% that that is affecting the image structure which is wp-content/uploads/%year%/%month%/%imagename% by the looks of it.

A: if you've monkeyed with your www structure you can change the image URLs (since they are hard-coded in the img src) using the following plugin:
http://wordpress.org/extend/plugins/velvet-blues-update-urls/

A: I had similar problem and could only fixed as:

*

*Copy the problem image to same directory.

*Delete the original

*Rename the copied file to original name.

Let's say it is named as "xyz.jpg", then once you copy it, you will have "xyz - copy.jpg"
Remove the "xyz.jpg" and rename the "xyz-copy.jpg" to "xyz.jpg"
I am pretty sure it is not the best solution. But it worked for me.


text:
Q: How can i binding the textBox font size to the textbox height? I want to do binding the font size in the textbox to the textbox height.
I want to have the possibility to change the page size and the font will grow / shrink according to the textbox size change.

A: I'm not sure if it's doable internally with the textbox, but you could write a converter, bind it for the text size and work the value out in relation to the page size in code.


text:
Q: Override Eloquent model where() method I'm trying to cache my models to avoid repeated database lookups. I was able to easily override the find method as follows:
<?php

namespace App\Concerns;

use Illuminate\Support\Facades\Cache;

trait CachesModels
{

    protected function findInCache(...$args)
    {
        $id = $args[0];
        if (is_numeric($id)) {
            $key = self::class . "|" . $id;
            $timeout = config("app.cache_seconds");
            return Cache::remember($key, $timeout, function() use ($args) {
                return $this->forwardCallTo($this->newQuery(), "find", $args);
            });
        }
        return $this->forwardCallTo($this->newQuery(), "find", $args);
    }

    public static function find(...$args)
    {
        return (new static)->findInCache($args);
    }
}

By using this trait on my models, I'm able to cache the results of the find() method. However, this doesn't account for the other related methods (e.g. findOrFail) and, more importantly, doesn't use the cache for dependency injection on my controller methods.
After going through the middleware and tracing code, it looks like I can use the cache in all these cases by overriding the where() method. As with find(), this isn't a defined method on the parent class, and can also be called statically or on an instance. So I tried the following code:
<?php

namespace App\Concerns;

use Illuminate\Support\Facades\Cache;

trait CachesModels
{
    protected function whereInCache($parameters)
    {
        // only cache simple calls, e.g. where('id', 123)
        if (count($parameters) === 2 && is_numeric($parameters[1]) && $parameters[0] === $this->getKeyName()) {
            $key = self::class . "|" . $parameters[1];
            $timeout = config("app.cache_seconds");
            return Cache::remember($key, $timeout, function() use ($parameters) {
                return parent::where(...$parameters);
            });
        }
        return parent::where(...$parameters);
    }

    public function __call($method, $parameters)
    {
        if ($method === "where") {
            return $this->whereInCache($parameters);
        }
        return parent::__call($method, $parameters);
    }

    public static function __callStatic($method, $parameters)
    {
        if ($method === "where") {
            return (new static)->whereInCache($parameters);
        }
        return parent::__callStatic($method, $parameters);
    }
}

However, when I try running this code, I get a recursion error:
PHP Error:  Maximum function nesting level of '256' reached, aborting!
    in vendor/laravel/framework/src/Illuminate/Container/Container.php on line 1161

I've also tried replacing return parent::where(...$parameters); with return $this->forwardCallTo($this->newQuery(), "where", $parameters); as used in the Model::__call() method, but that gives me a different error:
Exception with message 'Serialization of 'Closure' is not allowed'

On the cache closure return line. Not sure about this error since the method should return an instance of Illuminate\Database\Eloquent\Builder.
Any thoughts on where I'm going wrong?

A: I ended up being able to replicate the recursion error with this simple code:
<?php

class A {
    public static function foo() {
        echo "3";
    }
}

class B {
    public function __call($m, $p) {
        echo "2";
        A::foo();
    }
}

class C extends B {
    public function foo() {
        echo "1";
        parent::foo();
    }
    public function __call($m, $p){
        echo "x";
        $this->foo();
    }
}

(new C)->foo();
// output: 1x1x1x1x1x1x...

This output is unexpected – it appears calling an unreachable method on B is triggering C::__call() instead of B::__call(). Replacing the call to parent::foo() with parent::__call("foo", null) resolves this error, and gives the expected output of 123. An excellent reminder why "magic" methods are a nightmare.

Having resolved that, I'm back to Serialization of 'Closure' is not allowed. As mentioned in the question, the function should return an instance of Illuminate\Database\Eloquent\Builder, however this object does contain a closure and there's no way around that problem.
My solution is to override Illuminate\Database\Eloquent\Model::resolveRouteBinding(), as well as the find and findOrFail methods. It's still not ideal, but covers most cases where I'm hitting the database repeatedly. A simple event listener refreshes the cache entry if the model is updated:
<?php

namespace App\Concerns;

use Illuminate\Support\Facades\Cache;

trait CachesModels
{
    public static function bootCachesModels()
    {
        static::updated(function($model) {
            $key = $model->getCacheKey();
            $timeout = $model->getCacheTimeout();
            Cache::forget($key);
            Cache::put($key, $model, $timeout);
        });
        static::deleted(function($model) {
            $key = $model->getCacheKey();
            Cache::forget($key);
        });
    }

    private function getCacheKey(int $id = null)
    {
        return self::class . "|" . ($id ?? $this->getKey());
    }

    private function getCacheTimeout()
    {
        return config("app.cache_seconds");
    }

    private function findInCache($args)
    {
        $id = $args[0];
        if (is_numeric($id)) {
            $key = $this->getCacheKey($id);
            $timeout = $this->getCacheTimeout();
            return Cache::remember($key, $timeout, function() use ($args) {
                return $this->forwardCallTo($this->newQuery(), "find", $args);
            });
        }
        return $this->forwardCallTo($this->newQuery(), "find", $args);
    }

    private function findOrFailInCache($args)
    {
        $id = $args[0];
        if (is_numeric($id)) {
            $key = $this->getCacheKey($id);
            $timeout = $this->getCacheTimeout();
            return Cache::remember($key, $timeout, function() use ($args) {
                return $this->forwardCallTo($this->newQuery(), "findOrFail", $args);
            });
        }
        return $this->forwardCallTo($this->newQuery(), "findOrFail", $args);
    }

    public static function find(...$args)
    {
        return (new static)->findInCache($args);
    }

    public static function findOrFail(...$args)
    {
        return (new static)->findOrFailInCache($args);
    }

    public function resolveRouteBinding($value, $field = null)
    {
        // only cache when route binding is based on primary key
        if ($field !== null && $field !== $this->getKeyName()) {
            return parent::resolveRouteBinding($value, $field);
        }
        $key = $this->getCacheKey($value);
        $timeout = $this->getCacheTimeout();
        return Cache::remember($key, $timeout, function() use($value, $field) {
            return parent::resolveRouteBinding($value, $field);
        });
    }
}

A: The first issue is an infinite recursion (something calling itself over and over again, until it bugs out after 256 levels of recursion); and the second one is based upon, that anonymous functions (aka Closure) cannot be serialized (at least not by default, in order to prevent code injection).
It may well be that the Laravel framework is calling a method, not necessarily your code.eg. when listening for Model on-update and than trying to save the Model in there. In such situations, one has to use DB instead of Model, in order not to create an infinite recursion.


text:
Q: How do a flexLayout auto width? I want to make the flexlayout auto adjust it's width.
When I do not use flexlayout but only lable
    <Frame BackgroundColor="#5fb878" Padding="10" HasShadow="false" HorizontalOptions="EndAndExpand" Margin="0" Grid.Column="1">
        <Label Text="测试员013号" TextColor="#ffffff" FontSize="18"/>
</Frame>

Yes it auto fits the lable's size.but when I add the flexlayout it auto take the max width as it's width:
<Frame BackgroundColor="#5fb878" Padding="10" HasShadow="false" HorizontalOptions="EndAndExpand" Margin="0" Grid.Column="1">
                                        <FlexLayout Direction="Row">
                                            <Label Text="测试员013号" TextColor="#ffffff" FontSize="18"/>
                                        </FlexLayout>
                                    </Frame>

since I will add several views in the frame not only a lable.
Is there anyway to make the frame auto fit the total width of all the views?

A: It seems you used Grid to display this Frame directly and it will make it take all the space of the second column. You can wrap it with an extra StackLayout to fix that:
<ContentPage.Content>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="auto"/>
        </Grid.ColumnDefinitions>
        <StackLayout Orientation="Horizontal">
            <Frame BackgroundColor="#5fb878" Padding="10" HasShadow="false" HorizontalOptions="EndAndExpand" Margin="0" Grid.Column="1">
                <FlexLayout Direction="Row">
                    <Label Text="测试员013号" TextColor="#ffffff" FontSize="18" />
                </FlexLayout>
            </Frame>
        </StackLayout>
    </Grid>

</ContentPage.Content>

However, I noticed that you only utilized the FlexLayout's Direction feature, I think StackLayout may be a better choice:
<ContentPage.Content>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="auto"/>
        </Grid.ColumnDefinitions>
        <Frame BackgroundColor="#5fb878" Padding="10" HasShadow="false" HorizontalOptions="EndAndExpand" Margin="0" Grid.Column="1">
            <StackLayout Orientation="Horizontal">
                <Label Text="测试员013号" TextColor="#ffffff" FontSize="18" />
                <Label Text="second label"/>
            </StackLayout>
        </Frame>
    </Grid>

</ContentPage.Content>


text:
Q: MySQL arithmetic calculation result differs between Windows and Linux I have run this sql in windows & Linux version of mysql, and get the different result:
select (((((237803.3300+1659482.4400)/2.00)/1182208.5700)*30.00*6)+
(0.50*`(((((((1159248.2000+687984.6000)/2.00)/1527268.4000)*30.00*6)+
((((457300.0000+1707654.0300)/2.00)/1182208.5700)*30.00*6))
-(((((360.00*((1527268.4000-1182208.5700)-((2587.0000-((5354427.3100*0.0400*6)/12.00))
+99354.4800+10550.5600)))/((((((1159248.2000+687984.6000)/2.00)/1527268.4000)*30.00*6)+
((((457300.0000+1707654.0300)/2.00)/1182208.5700)*30.00*6))*0.5))-(0.50*((2587.0000-
((5354427.3100*0.0400*6)/12.00))+99354.4800+10550.5600)))*
(((((1159248.2000+687984.6000)/2.00)/1527268.4000)*30.00*6)+
((((457300.0000+1707654.0300)/2.00)/1182208.5700)*30.00*6)))/1182208.5700))-
((((237803.3300+1659482.4400)/2.00)/1182208.5700)*30.00*6)))) AS YF`

Windows version of mysql result: 105.93639914104807268662689486
Linux version of mysql result: 144.43789669025999363208811782
And I've been check this expression in some of other platform like java, excel, get the approximately value about: 105.93....., so I thought about that the calculation on linux mysql is incorrect or some of mysql variable set incorrect? Can anybody tell me why?
my linux version of mysql (At cloud server):
mysql>SHOW VARIABLES LIKE "%version%"

+-------------------------+---------------------------------+
| Variable_name           | Value                           |
+-------------------------+---------------------------------+
| innodb_version          | 1.1.8-20.1                      |
| protocol_version        | 10                              |
| slave_type_conversions  |                                 |
| version                 | 5.5.18.1-Alibaba-rds-201406-log |
| version_comment         | Source distribution             |
| version_compile_machine | x86_64                          |
| version_compile_os      | Linux                           |
+-------------------------+---------------------------------+

A: I did not look closely, but you are not selecting FROM anywhere
try this:
select (((((237803.3300+1659482.4400)/2.00)/1182208.5700)*30.00*6)+(0.50*(((((((1159248.2000+687984.6000)/2.00)/1527268.4000)*30.00*6)+((((457300.0000+1707654.0300)/2.00)/1182208.5700)*30.00*6))-(((((360.00*((1527268.4000-1182208.5700)-((2587.0000-((5354427.3100*0.0400*6)/12.00))+99354.4800+10550.5600)))/((((((1159248.2000+687984.6000)/2.00)/1527268.4000)*30.00*6)+((((457300.0000+1707654.0300)/2.00)/1182208.5700)*30.00*6))*0.5))-(0.50*((2587.0000-((5354427.3100*0.0400*6)/12.00))+99354.4800+10550.5600)))*(((((1159248.2000+687984.6000)/2.00)/1527268.4000)*30.00*6)+((((457300.0000+1707654.0300)/2.00)/1182208.5700)*30.00*6)))/1182208.5700))-((((237803.3300+1659482.4400)/2.00)/1182208.5700)*30.00*6)))) AS YF
FROM DUAL

Answer: 105.936399141048
Fiddle: http://sqlfiddle.com/#!2/a2581/32503/0


text:
Q: Atom comments are incorrect When I toggle comments in PHP with Atom, it always comment as HTML, even if the file extension is PHP. Example :
<!-- <?php echo "Test"; ?> -->

instead of
// <?php echo "Test"; ?>

Is there a way to fix that? I tried in atom --safe mode, but it doesn't help. Thanks!

A: I think that it is a normal behaviour. Because all around php tags is html code.


text:
Q: Is there a way to represent $\frac{\int_0^1 x^{a-1} (1-x)^{b-1} dx}{\int_0^1 exp(-x^2)x^{a-1} (1-x)^{b-1} dx} $ in terms of a, b? We are asked to find the supremum of $\frac{exp(-x^2) \int_0^1 x^{a-1} (1-x)^{b-1} dx}{\int_0^1 exp(-x^2)x^{a-1} (1-x)^{b-1} dx}$ for $x \in (0, 1)$. I'm thinking since $\frac{\int_0^1 x^{a-1} (1-x)^{b-1} dx}{\int_0^1 exp(-x^2)x^{a-1} (1-x)^{b-1} dx}$ should be a fixed value, the supremum should just be $\frac{\int_0^1 x^{a-1} (1-x)^{b-1} dx}{\int_0^1 exp(-x^2)x^{a-1} (1-x)^{b-1} dx}$. But then I don't know how to simplify that.
I know that $\int_0^1 x^{a-1} (1-x)^{b-1} dx$ is just $B(a, b)$, and our instructor told us there is no need to calculate $\int_0^1 exp(-x^2)x^{a-1} (1-x)^{b-1} dx$, so I'm wondering is there anyway I can simplify that?

A: By expanding the exponential into a series and integrating then it will be found that
$$ \int_{0}^{1} e^{-x^2} \, x^{a-1} \, (1-x)^{b-1} \, dx = B(a,b) \, {}_{2}F_{2}\left(\frac{a}{2}, \frac{a+1}{2}; \, \frac{a+b}{2}, \frac{a+b+1}{2}; \, -1 \right). $$
This leads to
$$\frac{ e^{-x^2} \, \int_{0}^{1} x^{a-1} \, (1-x)^{b-1} \, dx}{\int_{0}^{1} e^{-x^2} \, x^{a-1} \, (1-x)^{b-1} \, dx} = \frac{e^{-x^2}}{{}_{2}F_{2}\left(\frac{a}{2}, \frac{a+1}{2}; \, \frac{a+b}{2}, \frac{a+b+1}{2}; \, -1 \right)}. $$
The hypergeometric function is a constant which gives the form
$$\frac{ e^{-x^2} \, \int_{0}^{1} x^{a-1} \, (1-x)^{b-1} \, dx}{\int_{0}^{1} e^{-x^2} \, x^{a-1} \, (1-x)^{b-1} \, dx} = \frac{1}{c_{0}} \, e^{-x^2}. $$


text:
Q: Is a number divisible by any number in array I'm trying to see if a number is divisible by any given numbers in an array.
 I've seen a lot of answers with the number1 % number2 == 0 answer but I haven't found any with an array of numbers and I'd rather not write out each number in the array myself (that would be working too hard).
So here is what I'm trying to figure out. As you can see the only way this works currently is if the  last number I give it is true otherwise the else statement kicks in and evaluates number1_result to false.
int square_numbers[10] = { 4, 9, 25, 36, 49, 64, 81, 100, 121, 144 };
int number1;
bool number1_result;

cin >> number1;

for (int i = 0; i < 10; i++) {
    if(number1 % square_numbers[i] == 0)
        number1_result = true;
    else
        number1_result = false;
}

How do I make sure that if the loop ever evaluates to true once, it is true. If its not true at least one time, it is false.
Let me know if you need more info and thank you!

A: Break the loop once you find a divisor.And use = instead of == for assignment.    Correct solution is-
int square_numbers[10] = { 4, 9, 25, 36, 49, 64, 81, 100, 121, 144 };
bool number1_result=false;

for (int i = 0; i < 10; i++) {
    if(number1 % square_numbers[i] == 0) {
        number1_result = true;
        break;
    }
}

Problem with your code is that it overwrites number_result even if it is already true.
Consider the example, number1=4, square_number={2, 3}
In your loop num_result will become true at first comparison but it will again become false on next comparison with 3.

A: With std:
bool number1_result = std::any_of(std::begin(square_numbers),
                                  std::end(square_numbers),
                                  [&](auto e){ return number % e == 0; });

A: The problem is you are assigning number1_result which should check inside the loop but instead you have to input number1:
cin >> number1_result; // redundant

The answer:
int square_numbers[10] = { 4, 9, 25, 36, 49, 64, 81, 100, 121, 144 };
bool number1_result = false;

int number1;
cin >> number1;

for (int i = 0; i < 10; i++) {
    if(number1 % square_numbers[i] == 0){
        number1_result = true;
        break;
    }
}


text:
Q: How to share code between recipes I have a recipe that loops through a bunch of data defined in the attributes:
node["repos"].each do |repo, data|
  ...do stuff...
end

the ...do stuff... section is fairly long, and I would like to re-use it in multiple recipes, the only difference being that data set in the attributes is different.
I tried moving the inside of the loop to another recipe and including it like this:
node["repos"].each do |repo, data|
   include_recipe "other_recipe"
end

But when it tried to run other_recipe, the data variable did not exist.
What is the "proper" way of sharing code between recipes?

A: The simplest thing would be is moving this do stuff to library.
my_cookbook/libraries/myhelper.rb:
module Myhelper
  def do_stuff( repo, data )
    [...you can use all kinds of resources here as in recipe...]
  end
end

Then you can use this module in recipes like that:
another_cookbook/recipes/some_recipe.rb:
extend Myhelper
do_stuff( node[:attribute1], node[:attribute2] )

Just make sure you add a dependency on my_cookbook in metadata:
another_cookbook/metadata.rb:
depends 'my_cookbook'

A: Unfortunately this doesn't work because include_recipe both doesn't allow passing parameters and is "debounced" meaning it only runs once for a given recipe.
The simplest option these days for this kind of thing is to make a custom resource. Other options include definitions and helper methods but I would start with a custom resource and go from there. The inputs to the block of stuff (repo and data in this case) become resource properties and the chunk of recipe code goes in the resource's action method.


text:
Q: Discord bot that moves people based on game activity Hello everyone I'm new to coding but I want to code the bot mentioned in the title so my questions are:
-Is there a command that reads the game activity?
-What is the command that makes the bot move someone?
I set the basics up but don't really know where to go from here:
const Discord = require('discord.js');

const client = new Discord.Client();

client.once('ready', () => {
    console.log('Online');
});

client.login('*the token*');

A: All of a user's game activities are stored as an array, activities, within the presence property of your user object.
For example, if you want to get the game statuses of the author of a message, you can use <message>.author.presence.activities to get that array.  However, since a user may have multiple statuses (custom statuses, games, Rich Presences, etc), you'll generally want to get a specific activity.
If you need to check if the name of the status is a certain one, you'll need to get the specific index first, such as <message>.author.presence.activities[0].name.  If you want to check each status and see if any of them align with a needed name, you can use a for...of loop.
For more information, here is the documentation on the presence of a user.
As for "moving someone," you are not giving any more explanation as to what you mean, so that should be implemented once your bot can properly detect certain games.
In the meantime, try following a guide on how to turn user input into actual commands, and then this may make more sense if you are still facing issues.


text:
Q: How to split voltage from a DC power supply? Given a 12V 4A DC power supply that's connected from a wall outlet to a V59 Universal LCD Controller, can the voltage be split from this power supply to power another device with 5V 1200mA power requirements?  If so, how exactly should the wiring be connected and what other components such as resistors might be needed?

A: You need a 12V to 5V DC-DC step-down converter (also look for: switching regulators). You can find plenty of them in the usual electronics parts vendors.
You could also consider a linear voltage regulator, but that would mean a maximum power dissipation in it of about \$ P_d = (12-5) \cdot 1.2 = 8.4W \$, which will (almost surely) either fry it or drive it into thermal shutdown. Also, it's very inefficient power-wise. Not recommended at all.

A: Use a high efficiency D.C.-D.C. Converter, these devices are used in hobby remote controls where they are termed a battery eliminator circuit (BEC).  Forget about 7805, too much waste heat.  No other components needed., 12v in, 5v out, very reliaable.
Eg http://www.dx.com/s/Bec?PriceSort=up


text:
Q: Can someone look at the solution to this question and explain it more clearly the following is the solution.

Here is my question.. what is the "positive quantity" and how did $x + \frac{36}{x} \ge 13$ become $x^2 - 13x + 36 \ge 0$?
Thank you!

A: The "positive quantity" is $x$, since we are considering the case $x > 0$.  Multiplying the original inequality by this quantity (i.e., by $x$), we get
$$
x^2 + 36 \geq 13 x.
$$

A: The "positive quantity" referenced in the solution is $x$. The author places this emphasis on $x$ being positive because the techniques that follow are only valid when $x$ is a positive real number.
Given that $x>0$, we have
$$
x + \frac{36}{x} \geq 13 \iff x^2 + 36 \geq 13x \iff x^2 - 13x + 36 \geq 0
$$
as desired.


text:
Q: How do i add a new line in html format in android? I have to add text to a button bolding the first line and unbolding the second but i cant figure out which new line character it is.
b.setText(Html.fromHtml("" + st + "<\b>" + "\n" + cursor.getString(1)));

ive also tried
b.setText(Html.fromHtml("" + st + "<\b>" + "
" + cursor.getString(1)));

the second one works but both lines are bolded.
Thanks in advance

A: wrong end tag:
b.setText(Html.fromHtml("" + st + "" + "
" + cursor.getString(1)));

A: Rather than using HTML to format your text (which is relatively slow) you could use Spans which give you much tighter control, and are more efficient. I wrote a blog post about the use of spans which may help you to get started.


text:
Q: Java extends generic prototype I have few classes that implements some interface. Now I want to create new class, which can extend one of them, based on runtime calculation while using interfaces methods. Let's talk in code:
public interface Interface {
    public void doSomething();
}

public class A implements Interface {
    @Override
    public void doSomething() {
        System.out.println("hello");
    }
}

public class B implements Interface {
    @Override
    public void doSomething() {
        System.out.println("hi");
    }
}

These are existing classes, so now I need to do something like this (which is not working of course):
public class C<T extends Interface> extends T {
    public void doSomethingElse() {
        this.doSomething();
    }

    public static void main(String[] args) {
        C c;
        if(isSomethingLoaded) {
            c = new C<A>();
        } else {
            c = new C<B>();
        }
        c.doSomethingElse();
    }
}

Is it possible somehow, except the way that I pass argument Interface other to C's constructor and store to class property..?

A: A class cannot extend from its type parameter.
Use composition instead of inheritance:
public class C<T extends Interface> {
    private final T foo;

    public C(T foo){
       this.foo = foo;
    }

    public void doSomethingElse() {
        foo.doSomething();
    }

    public static void main(String[] args) {
        C<?> c;
        if(isSomethingLoaded) {
            c = new C<>(new A());
        } else {
            c = new C<>(new B());
        }
        c.doSomethingElse();
    }
}

You might even not need the type parameter here, but just use the interface type as argument/ member type.

A: I think it's situations like this which show why we have the rule of favouring composition over inheritance. Consider this solution using composition:
public class Test {
    public interface Interface {
        void doSomething();
    }

    public static class A implements Interface {
        @Override
        public void doSomething() {
            System.out.println("Doing A");
        }
    }

    public static class B implements Interface {
        @Override
        public void doSomething() {
            System.out.println("Doing B");
        }
    }

    public static class C implements Interface {
        private Interface composedWith;

        public C(Interface i) {
            this.composedWith = i;
        }

        @Override
        public void doSomething() {
            this.composedWith.doSomething();
        }
    }

    public static void main(String[] args) {
        C c;
        if(isSomethingLoaded) {
            c = new C(new A());
        } else {
            c = new C(new B());
        }
        c.doSomething();
    }
}

Personally, I feel this is a clearer and move flexible way of achieving what you are trying to do.


text:
Q: Doubt with json response I have this code:
$.getJSON('../encomendasanexos.php?campo=idencomendas&nome=imagem&id='+id_int,
     function(registro){
        var imghtml = [];
        imghtml = '';
        $this.parent().find("#conteudoanexo").html(imghtml,join(''));
});

And the returned json:
[{"id":"400","img":"..\/imagens\/encomendas\/aspire_1309790504.jpg"},
{"id":"401","img":"..\/imagens\/encomendas\/casa_1309790507.jpg"},
{"id":"402","img":null}]

I wanna do a for loop with values received by json, where +registro.id+ is id and +registro.i+ is a key in 1st json array level.

A: $.getJSON('../encomendasanexos.php?campo=idencomendas&nome=imagem&id='+id_int,
     function(registro){
        var container = $this.parent().find("#conteudoanexo").empty();
        $.each(registro, function(idx, item ){
            var img = $('', {
                               'src'  : 'http://www.usedprice.com/images/button_edit_grey.gif',
                               'class': 'imagelink w16'
                });
            img.click(function(){
                window.open('editImagem.php?tabela=anexos&id='+item.id+'&ordem='+item.i, '_blank', 'width=750,height=550,scrollbars=no,status=yes');
            });
            container.append(img);
        });
    });

demo at http://jsfiddle.net/gaby/GCzxS/1/

A: You should do:
$.getJSON('../encomendasanexos.php?campo=idencomendas&nome=imagem&id='+id_int,
     function(registros){
        var imghtml = [];
        for(var i=0; i<registros.length; i++){
            var registro = registros[i];
            imghtml.push('');
        }

        $this.parent().find("#conteudoanexo").html(imghtml,join(''));
});

Hope this helps. Cheers


text:
Q: Executing StoredProcedure takes incredible amount of time in EF6 I am running EF6 (v6.2.0) in ASP.NET MVC5.
When executing a certain StoredProcedure via EF6's SqlQuery() function I have to wait for about 2 minutes(!) to get the result in memory.
The StoredProcedure takes about 9 - 12 seconds in the database due to some complex calculations and is called with 11 parameters:
exec sp_Calculation @q, @y, @gn, @gesa, @rg, @cl, @yc, @vlv, @vlb, @ugv, @ugb

The result is about 2.1 MB of data (~9000 rows, 49 columns).
Total execution time: 00:00:11.711
In code I call it like this:
dbContext.Database.Log = s => Trace.Write(s);
return await dbContext.Database.SqlQuery<CalculationResult>("exec sp_Calculation @q, @y, @gn, @gesa, @rg, @cl, @yc, @vlv, @vlb, @ugv, @ugb", parameters).ToListAsync(token);

Trace:
exec sp_Calculation @q, @y, @gn, @gesa, @rg, @cl, @yc, @vlv, @vlb, @ugv, @ugb

-- @q: 'null' (Type = Int32, IsNullable = false)
-- @y: '1101' (Type = Int16, IsNullable = false)
-- @gn: 'null' (Type = Int32, IsNullable = false)
-- @gesa: '1' (Type = Byte, IsNullable = false)
-- @rg: 'null' (Type = Int32, IsNullable = false)
-- @cl: '4' (Type = Byte, IsNullable = false)
-- @yc: '17' (Type = Int16, IsNullable = false)
-- @vlv: 'null' (Type = Int16, IsNullable = false)
-- @vlb: 'null' (Type = Int16, IsNullable = false)
-- @ugv: 'null' (Type = Int16, IsNullable = false)
-- @ugb: 'null' (Type = Int16, IsNullable = false)
-- Executing asynchronously at 19.07.2018 18:27:23 +02:00
-- Completed in 114479 ms with result: SqlDataReader

My first guess was the network as a bottleneck, but calling the StoredProc on the Webserver via SSMS is also very fast. So network should not be the problem.
Here is the Call Stack from dotTrace with the big bottleneck:

What is weird is the extremely long execution times of the native assemblies.
Can someone clarify what exactly is going on there and how to resolve the issue?
EDIT:
I just found a question with a similar problem and will try to find out some more about it. Maybe it is the network.
EDIT 2:
I do need all the data in memory due to some preprocessing before creating a csv file from it. The bottleneck seems to be in the SNINativeMethodWrapper. I do not need help to perform my task with other libraries. I just want to get the data faster in memory.

A: I had the same issue, and offcourse SSMS will execute faster.
The problem is that all records are assigned to the respective POCO and its properties it iterates through every value until it produces a huge set of object.
What i did to address the issue :
I created a pagination in the sproc (sql level paging).
No one can view 9000+ records at a time unless you are a CYBORG.
So just get 10-100 records from the result set when the store procedure is executed.
Updated :
If you need to retrieve result set for creating an excel, i would suggest the possible ways to do so :

*

*Create excel file directly from the sql, taking the result set
from db to C# is time consuming.

*If you still need it in server side
then i would suggest you use EPPlus or any other well maintained
third party libraries to generate excel for you at server side (EPPlus is what i use
and it does not take longer than 5 secs for me excluding SP execution
time)

*Switching back to ado.net for report generation is viable, due to performance difference between EF and ADO

*Optimize your query, refine it.

*If your hands are still tied up by the client, then bear with the loading time you are currently experiencing ;)

A: The issue was heavy load between the database and linked servers.
The native API had a hard time to push the whole record set through the SQL Network Interface. So there is no problem with the code itself.
Everything works as fast as expected when load between linked servers was low.


text:
Q: get image and upload/save it in server location I have an beego application in which i have a requirement of uploading a image from client for to server location.

//Till now I have tried the following script
$("#fileupload").on("click",function(){
  $("#my_file").click();
  userImage = document.getElementById('fileupload');
  imgData = getBase64Image(userImage);
  localStorage.setItem("imgData", imgData);
});

  .Hii vijay

<input type="file" id="my_file" style="display: none;" />

using this script, when i click on empty image(click here to add) it is displaying a browse file option.After selecting the image no action taking place.
My requirement is on selection of image from browse option, the selected image should be saved in server location.

A: localStorage that you are using is something like cookies and would never be saved in server. It is per domain saved on the client side.
Also when you want to save the bit to server, you need to do a form post and you should be having some sort of server side code with handles the saving part like where to save and in which format.
Try exploring Php or ASP.NET or Jsp file upload - saving on server.
With out server side code it would not be possible to push data using HTML and Javascript alone, as they are only client side scripts.
Update 1:
html
<form action="/post/save" method="POST" enctype="multipart/form-data">
    <input type="file" name="images">
</form>

Controller
file, header, err := this.GetFile("images")
if err != nil {
    log.Println("error", err)
} else {
    log.Println("filename", header.Filename)
}

Try some docs on Beego GetFile method. But there seems to be a limitation there like by default, you cannot handle multiple uploaded files at a time.

A: See additional notes on bottom...
Relevant template markup:
<input type='file' id="imageInput" name="imageInput" accept="image/*"/>

Relevant JavaScript:
$('#imageInput').change(function(){
    var frm = new FormData();
    frm.append('imageInput', input.files[0]);
    $.ajax({
        method: 'POST',
        address: 'url/to/save/image',
        data: frm,
        contentType: false,
        processData: false,
        cache: false
    });
});

Beego controller handling the upload:
// relevant code
// file upload handling
file, header, er := this.GetFile("imageInput")
if file != nil {
    // some helpers
    // get the extension of the file  (import "path/filepath" for this)
    extension := filepath.Ext(header.Filename)
    // full filename
    fileName := header.Filename
    // save to server`enter code here`
    err := this.SaveToFile("imageInput", somePathOnServer)
}

JavaScript:
Once the change event fires a new FormData object is being created. The file data is being appended to the form object, finally the code executes a POST request using Ajax.
Beego controller:
By using the .GetFile() method with "imageInput" as argument which is the HTML input control element you can get the file data.
By using the .SaveToFile() method with "imageInput" and a path as arguments, you can save the file to the server.
Note this refers to the controller. I create my Beego controllers using func (this *MainController) ControllerName ()


text:
Q: Call a data from a database in a .ini file I have a little problem about my .ini file. I am using LabVIEW to pilot a Power Supply GPD-2303. And I have to configure the Voltage and the Current searched for each cards. These datas are in a Database but I have only a read access on it.
Voltage, Name, AlphaNumCode... Are not a problem because it will probably never change so my code is looking like:
[AlphaNumCode]
VSET_1=VALUE
VSET_2=VALUE
CSET_1=VALUE
CSET_2=VALUE
Assembly_PN=VALUE

That's to set Voltage, Current at the start of the execution on LabVIEW and give an Assembly PN "IF KQG then AssemblyPN= 1633".
That's the situation. The problem is there:
[Assembly PN]
CURRENT1_PROG_SEARCHED=VALUE
CURRENT2_PROG_SEARCHED=VALUE
CURRENT1_BLANK_SEARCHED=VALUE
CURRENT2_BLANK_SEARCHED=VALUE

I want to transform it, because if this value is not a fix value. I am looking for Something like:
[Assembly PN]
CURRENT1_PROG_SEARCHED="VALUE IN COLON W, LINE X"
CURRENT1_PROG_SEARCHED="VALUE IN COLON W, LINE X"
CURRENT2_PROG_SEARCHED="VALUE IN COLON X, LINE X"
CURRENT1_BLANK_SEARCHED="VALUE IN COLON Y, LINE X"
CURRENT2_BLANK_SEARCHED="VALUE IN COLON Z, LINE X"

I have found: https://support.microsoft.com/en-us/kb/149090
But it show how to interact with the colon but not with a specific case. Is there a command?
That's the last thing I have to do in my Internship to end this project and I do not like let things unfinished.
Hope someone can help me or give me documents to learn how to do it, it will be great :)
Edit:
Yes, this article show how to access data by a text file, and the text file is linked to the data in the database, I was thinking that could work.
I am clearly new about database so I am sorry about the lack of knowledge I will try to do my best, but using SQL server and System DSN to Access it in LabVIEW.
The ini File is read in a LabVIEW Program
By"COLON" I mean "COLUMN
Edit:
I send you my Sub VI and a picture of my code, that's what I want. still having 2 days to end it so I hope you can read me guys!
[1630]LINE=WHERE (OC=1630);
[1631]LINE=WHERE (OC=1631);
[1632]LINE=WHERE (OC=1632);
[1633]LINE=WHERE (OC=1633);
[1635]LINE=WHERE (OC=1635);

LabVIEW Picture of the Sub VI 25/07/16 using  DB Select Tool Kit
Best regards,
Robin.

A: I have found a solution, in fact I am using a .ini file to send a condition:
Just to know: (OC = Assembly Number)
In my .ini I have:
[1633]
OC=WHERE(OC=1633);
Then I send it to the condition in DB Select Tool Kit and I enter the column / table where is the data I am looking for.
Then if a new card need to be test they just need to make a new line in the .ini file:
[XXXX]
OC=WHERE(OC=XXXX);
Thanks for your help that problem is resolve, I hope it can help someone that want to make communication between LabVIEW / .ini / Database
Best regards,
Robin


text:
Q: Best supporting argument for refactoring Currently I am working on a code best described as C code living in C++ body. However I haven't been able to convince power that be to re-factor on ground of ease of maintenance.
What in your opinion is the best argument for refactoring the code.

A: Just do it as you go. In my experience, very few projects warrant a wholesale re-factoring of the code as a separate project. If there are pieces of the code you would never get to because they don't need modification, then the value of refactoring them is probably dubious anyway.

A: You don't tell the taxi driver how to drive his car.
You don't tell the hairdresser how to cut your hairs.
You don't tell a coder how to work with his code.
If you think your code needs refactoring. Refactor it.

A: I can think of three arguments for refactoring that I have used that have actually convinced sceptical directors.

*

*Architectural change to allow additional types of desirable features.

*Removing a block of code that has an established track record of bugs combined with a history of fixing a bug and a new bug appears.

*Poor security / Poor performance that is affecting sales.

Using arguments like "the code is badly written" and "its really hard to understand the code" do not typically work.

A: The only way to get a business to agree to a refactor is to show them it will save them money. I dont mean just tell them, you need to be able to say we will save x days on bug type y saving us z pounds.Or in terms of savings when it comes to adding features.
It's all about the money.
Edit: I'm assuming this code is now live or late stage development. Refactoring during dev is a whole different question.

A: Most reasons are dealing with probabilities which makes them difficult to count, especially if the willingness to take risks is high. Better maintenance? If nothing goes wrong, you won't have to touch it. Better portability? If we never change the running system, we won't need it. Guaranteed future? Who knows if we will need the functionality of this code in a few years time at all? Code's a dead end? Who knows if we will ever build code on top of that crap. Security issues? We don't believe in evil hackers. Programmers having fun to make something bright and shiny? We don't pay them to have fun. Easier to manage? So we would need less qualified programmers, paying them less money? Ahh, now you've got a point...!
The last argument was a joke, but I think you will need to tackle your request with real benefits and depending on what's high on the agenda of your bosses you will need different arguments. My list above is maybe useful as a starting point...

A: Writing code is much like growing a garden - it needs to be pruned and tendered while growing often or it will just turn into an ugly mess which no one will want or even touch with fear some twig will break and crash the whole bush.

A: As with everything examples are the best way. Some examples you can give:

*

*Hard to change code: Bug X took 3 days to fix caused by code issues a,b,c

*Tight coupling: Fixing Bug Y introduced bug G, fixing both causes bug F

*Hard to read: It took 1 whole day to investigate bug C

*Bad cohesion: Introducing feature D required dependency on F, which is unrelated. This causes problems such as circular dependency problem a, build time increase b etc...

To put this simply if you can draw a cause and effect line and illustrate with bug tracker records, e-mails and other forms of proof that indicate that there is a problem that should motivate refactoring quite easily. "It shouldn't have taken 2 weeks to implement feature X!"
There are tools out there that can help you motivate your refactoring too. They can draw dependency graphs or show code complexity, duplication etc. If a tool reports thousands of warnings and management ignores it then there is no hope for management.
These focus on code structure changes. Small refactorings like naming conventions and pulling up into base classes are things that I consider part of my job, and I don't ask permission to do it. If it's going to impact productivity or delivery date significantly then it is worth asking permission.


text:
Q: Solving Linear Partial Differential Equation Find the general solution of $$z(z^2+xy)(px-qy)=x^4$$ Let   $F(x,y,z,p,q)=z(z^2+xy)(px-qy)-x^4$. This gives
$$F_p=zx(z^2+xy)$$
$$F_q=-yz(z^2+xy)$$
$$F_r=x^4$$
The Auxiliary equation for the given Linear Pde is $$\frac{dx}{zx(z^2+xy)}=\frac{dy}{-zy(z^2+xy)}=\frac{dz}{(x^4)}$$
But I can't seem to find anything afterwards to get the general solution.
Thanks for the help!!

A: As the homogeneous
$$
x F_x-y F_y = 0
$$
has as solution
$$
F=\Phi(z, xy)
$$
choosing the change of variables
$$
\cases{
u=x\\
v=x y\\
w= z}
$$
we get at
$$
F(x,y,z)=G(u,v,w)
$$
and
$$
G_u(u,v,w) = \frac{u^3}{w(v+w^2)}
$$
with solution
$$
G(u,v,w) = \frac{u^4}{4w(v+w^2)}+\Psi(v,w)
$$
or
$$
F(x,y,z) = \frac{x^4}{4z(xy+z^2)}+\Psi(x y,z)
$$


text:
Q: How can I change the unit test directory in VS 2012 by which I mean the directory returned by
   this.TestContext.TestDir

inside a unit test.
Only VS2012 is concerned.
I tried VS test settings, but the folder one can configure did not affect the TestDir value and in addition MS highly recommends not to use .testsettings files anymore.
We consider setting this directory manually from an environment variable that has to be set up on build/dev machines, better workarounds also welcome.


text:
Q: PHP 7.4 Configuration File on CentOS 7 I have PHP 5.6 on my server with nginx, and want to install PHP 7.4 to do some tests in advance. I followed this guide (changing PHP 7.1 to 7.4) and now I have my default PHP 5.6 and PHP 7.4.
The problem is, there is no php-fpm74.sock socket file in the /var/run/php-fpm directory. And I couldn't manage to find configuration files for PHP 7.4. There is path /opt/remi/php74/root/ where the configs supposed to be but the folder is empty. I've tried to copy php-fpm.conf and php-fpm.d there but it doesn't help.


text:
Q: Is there a way to force a lower specificity in CSS? I have a CSS template where I want to use a minimal amount of attributes within some HTML markup, while allowing for easy customization of that markup via classes (not IDs) later, if needed.

A

B

The problem is that due to CSS specificity, I am faced with either making all of my selectors classes anyway, or else forcing any stylesheet modification of my content to be extremely specific:

vs

A

B

Is there a way to force a specificity yield without using !important, for example hypothetically:
@yield to classes {
  [data-role = "a"] { }
  [data-role = "a"] > :first-of-type { }
  [data-role = "a"] > :last-of-type { }
  /* etc */
}

or
@specify('[data-role="a"] > :last-of-type' , 10) { ... } where 10 is the lowest internal specificity assigned, etc.
Or am I just forced to use classes everywhere?

A: The MDN has an interesting tip to bail you out without using !important:
Using a selector twice:
#myId#myId span { color: yellow; }
.myClass.myClass span { color: orange; }

https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity
Recently support for the :where() pseudo class was added to the major browsers. It allows managing specificity better. The selectors within do not contribute to the specificity of the overall selector:

:where(aside.where, footer.where) a {
  color: orange;
}

footer a {
  color: blue;
}

Here is my aside content. This also contains a link.

This is my footer, also containing a link.

https://developer.mozilla.org/en-US/docs/Web/CSS/:where
Further note that according to an approach called BEM (Block, Element, Modifier) using classes (one class for any element) might not be the worst choice anyway.

A:
Is there a way to force a specificity yield without using !important? ... or @specify('[data-role="a"] > :last-of-type' , 10) { ... } where 10 is the lowest internal specificity assigned

No, there is not.
Not sure what else you are looking for out of an answer since you seem to understand how specificity works in general -- with just the small HTML you provided there at least dozens of ways you could write rules involving elements, classes, attributes, etc. to get your desired styling. Though if you're looking for a simple, well-written write-up on specificity I've always found this one to be the most useful:
https://css-tricks.com/specifics-on-css-specificity/ (continually updated since 2010!)


text:
Q: text file read from remote systems Hi Scripting Experts....
Looking for your help on below code....RemoteServersList.Txt and i wanted to call every system like \RemoteServerName\E$\V2\log.Txt I am missing few lines of code ...
kindly help me ....
Thanks lot....
Set Fso = CreateObject("Scripting.FileSystemObject")

Set InFile = fso.OpenTextFile("RemoteServersList.Txt")

Const ForReading = 1

Do While Not (InFile.atEndOfStream)

strComputer = InFile.ReadLine

today = Date()

Set fso = CreateObject("Scripting.FileSystemObject")

strFilePath = "\\" & strComputer & "\E$\V2\" ' This is wrong 'here I am missing a 'code.. looking for your help

Set InputFile = fso.OpenTextFile("strFilePath\log.txt", 1)  ' This is wrong here I am 'missing a code.. looking for your help

Set out = fso.OpenTextFile("error.log", 2)

    Do Until InputFile.AtEndOfStream
      line = InputFile.ReadLine
      If Left(line, Len(today)+1) = "[" & today Then

    WScript.Echo "Hello" ' I need to append this to output file
    out.WriteLine line & vbTab & InputFile.ReadLine & vbTab & strComputer

            If InStr(line, "error") > 0 Then
        ' line contains "error"
        out.WriteLine line & vbTab & InputFile.ReadLine & vbTab & strComputer

        End If
    End If

    Loop

InputFile.Close
out.Close

Loop

A: RemoteServerList.txt is a txt file that contains a list of server, written as this:
server-1
server-2
server-3
etc.

and on each server you have to read this text file:
\\server-1\e$\V2\log.txt
\\server-2\e$\V2\log.txt

?
The first problem I see in your code is in the string assignment, this should be correct:
strFilePath = "\\" & strComputer & "\E$\V2\"
Set InputFile = fso.OpenTextFile(strFilePath & "log.txt", 1)

but where do you want to write the error.log file? localy or on the remote machine?
If you want it on the local machine, it's better if you open the file only once, at the beginning of your script, just below Set Inifile.
And you have to use CreateTextFile or open it with fso.OpenTextFile("error.log", 2, True) if the file does not already exist:
Set Fso = CreateObject("Scripting.FileSystemObject")
Set InFile = fso.OpenTextFile("RemoteServersList.Txt")
Set out = fso.CreateTextFile("error.log")

Const ForReading = 1

Do While Not (InFile.atEndOfStream)
  strComputer = InFile.ReadLine
  today = Date()
  Set fso = CreateObject("Scripting.FileSystemObject")
  strFilePath = "\\" & strComputer & "\E$\V2\"

  Set InputFile = fso.OpenTextFile(strFilePath & "log.txt", 1)
  Do Until InputFile.AtEndOfStream

    If (condition) Then
      out.WriteLine [write something to output file]
    End If

  Loop
  InputFile.close

Loop

out.Close
InFile.Close


text:
Q: Access VBA for checkboxes I'm currently working on a project that gave me a lot of raw data I am trying to filter in a continuous form. I have one field that has a possibility of five letters (GRUBW) with each multiple letters per entry. The goal is to filter the form with a checkbox for each letter. Am I missing something or going about this the wrong way?
Below is the coding I'm attempting to use and when trying to debug I keep getting an error of an undefined variable. As you can see in the coding, I have a lot of ways I want to filter. I have a feeling that I'm missing some double quotes somewhere or my understanding of the way checkboxes are to be coded is totally wrong. I've only been working with VBA for a few months, so I may be out of my depth here. Thanks.
Option Compare Database
Option Explicit
    Private Sub CBTN_CLICK()
Dim ctl As Control
For Each ctl In Me.Section(acHeader).Controls
Select Case ctl.ControlType
Case acTextBox, acCheckBox
ctl.Value = Null
End Select
Next
Me.FilterOn = False
    End Sub
    Private Sub requeryform()
Dim strwhere As String
Dim lnglen As Long

If Not IsNull([Forms]![sbx]!CTB) Then
    strwhere = strwhere & "([CARD] LIKE ""*" & [Forms]![sbx]!CTB & "*"") AND "
End If
If Not IsNull([Forms]![sbx]!OTB) Then
    strwhere = strwhere & "([ORACLE] LIKE ""*" & [Forms]![sbx]!OTB & "*"") AND "
End If
If Not IsNull([Forms]![sbx]!ARTB) Then
    strwhere = strwhere & "([ORACLE] LIKE ""*" & [Forms]![sbx]!OTB & "*"") AND "
End If
If Not IsNull([Forms]![sbx]!TTB) Then
    strwhere = strwhere & "([ctype] LIKE ""*" & [Forms]![sbx]!TTB & "*"") AND "
End If
If Not IsNull([Forms]![sbx]!CTTB) Then
    strwhere = strwhere & "([ORACLE] LIKE ""*" & [Forms]![sbx]!OTB & "*"") AND "
End If
If Me.RC = True Then
    strwhere = strwhere & "([color] LIKE ""*" & R & "*"") AND "
End If
If Me.UC = True Then
    strwhere = strwhere & "([color] LIKE ""*" & u & "*"") AND "
End If
If Me.BC = True Then
    strwhere = strwhere & "([color] LIKE ""*" & b & "*"") AND "
End If
If Me.GC = True Then
    strwhere = strwhere & "([color] LIKE ""*" & g & "*"") AND "
End If
If Me.WC = True Then
    strwhere = strwhere & "([color] LIKE ""*" & w & "*"") AND "
End If
lng = Len(strwhere) - 5

If lnglen <= 0 Then
Else
strwhere = Left$(strwhere, lnglen)
Debug.Print strwhere
Me.Filter = strwhere
Me.FilterOn = True
End If
End Sub
Private Sub STBN_CLICK()
requeryform
End Sub

A: Undefined variable error is due to not enclosing literal text within quote marks and using lng instead of lnglen. Consider revised code:
Dim strGRUBW As String

If Not IsNull([Forms]![sbx]!CTB) Then
    strwhere = strwhere & "([CARD] LIKE ""*" & [Forms]![sbx]!CTB & "*"") AND "
End If
If Not IsNull([Forms]![sbx]!OTB & [Forms]![sbx]!CTTB & [Forms]![sbx]!ARTB) Then
    strwhere = strwhere & "([ORACLE] LIKE ""*" & [Forms]![sbx]!OTB & "*"") AND "
End If
If Not IsNull([Forms]![sbx]!TTB) Then
    strwhere = strwhere & "([ctype] LIKE ""*" & [Forms]![sbx]!TTB & "*"") AND "
End If
With Me
strGRUBW = IIf(.RC, "r,", "") & IIf(.UC, "u,", "") & IIf(.BC, "b,", "") & IIf(.GC, "g,", "") & IIf(.WC, "w,", "")
End With
If strGRUBW <> "" Then strwhere = strwhere & "[color] LIKE '*[" & strGRUBW & "*]' AND "
lnglen = Len(strwhere) - 5