text:
Q: MSBuild/WebDeploy - How to prevent it from deleting a folder and its contents We're using TeamCity to automate MSBuild to use WebDeploy to push our application to our various servers.
For the most part, we've got this working, and great.  One snag, though: we've got a folder that holds uploads that we don't want to have deleted during the publication.
How do I tell WebDeploy, "I know that folder's not in the compiled application.  Ignore it.  Just leave it alone."

A: If you're using the dirPath, filePath, or contentPath providers, you can specify the DoNotDelete rule to block deletions of files on the destination computer that do not exist on the source. The syntax to add to the command line would be -enableRule:DoNotDelete. For more information, see the provider articles mentioned and Web Deploy Rules.


text:
Q: Tweak the math for the new flag-ban system a little? A relatively recent change to the flagging system has been elimination of the flag "hell ban," in favor of a more transparent system that includes feedback.
This is a good thing.
The new system, however, doesn't seem to take into account a user's flagging history, and has a pretty low threshold for what triggers the temporary ban users from flagging.
This is a bad thing.
For example, this jerk.  2180 helpful flags total, but 3 of 15 flags since the 19th declined, and flag banned.  (I'm assuming it's 3 of 12 flags on posts, and a few comment flags thrown into the mix to make 15).
The effective threshold on bad flags one can throw before hitting a ban seems pretty low, at 2.5 (must have >= 10 flags, and >=25% declined), and it seems to me that a better approach would be to up the number of flags at which the system starts considering people for flag banning.
For example, if it were tweaked to start looking at 20 or 25 flags in a week (which is still pretty low, ~3/day), the lower threshold would be 5 or 6.  To me,  that seems like a threshold that's more in line with the intent of the new system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS PDFKit textfield form input I am currently developing a iOS app which can download PDF(Have form on it) from server to iPad, then user can fill in the form on the iPad.
The problem is we need to support chinese on the field input.
Here is the field.

When I use "Quick" input method to type any character, it repeat 3 times.

When I type one more time, it repeat again.

Do anyone have issues with typing Chinese in textfield using PDFKit on iOS?

Update, Add code work
For the server-side, just a endpoint can download pdf, the pdf already added textfield on it.
On client-side, pdf is downloaded in viewDidLoad() and set into pdfView as following code.
override func viewDidLoad() {
    super.viewDidLoad()

    if let code = self.code {
        let url = URL(string : API.pdf + "/" + code)
        let loading = self.showLoading()
        var request = URLRequest(url: url!)
        request.httpMethod = "GET"
        let task = URLSession.shared.dataTask(with: request, completionHandler: { (responseData: Data?, response: URLResponse?, error: Error?) in
            DispatchQueue.main.async {
                self.pdfView.document = PDFDocument(data : responseData!)
                self.pdfView.scaleFactor = 1
                self.pdfView.backgroundColor = UIColor.lightGray
                self.pdfView.autoScales = true
                loading.dismiss(animated: true, completion: nil)
            }
        })
        task.resume()
    }
}

In story board, it is just a UIView and set custom class as PDFView

Updated 2
After that, i do a simple testing.
I create a simple testing controller and load pdf with just a simple textfield annotation. Result is same.
   import UIKit
   import PDFKit

 class PDFTestViewController : ViewController {

@IBOutlet weak var pdfView: PDFView!

override func viewDidLoad() {
    super.viewDidLoad()
    if let url = Bundle.main.url(forResource: "4547315264964", withExtension: "pdf"),
        let doc = PDFDocument(url: url){
        self.pdfView.document = doc
        self.pdfView.scaleFactor = 1
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}


text:
Q: Randomly mix the order of lines in a file Suppose I have a file containing some lines:
line 1 ...
line 2 ...
...
line n ...

Is it possible to have another file where the order of the lines will be randomly mixed ?

A: The random module is your friend:
import random
with open("infile.txt") as f:
    lines = f.readlines()
random.shuffle(lines)
with open("outfile.txt", "w") as f:
    f.writelines(lines)

should do.

A: 1) read the file
2) store each line in a string array
3) shuffle string array
4) write file
I think that is what you're asking for?


text:
Q: Adding extenal library to compiler toolchain for ARM I have downloaded compiler tool chain for ARM Target.
My host machine: Linux
Target H/w : ARM7
But i need to add some additional library with that tool chain.
I need to know how to add new library to existing tool chain?
Thanks
Hari


text:
Q: How can I sign in and get access token of Microsoft Graph API for personal account using com.microsoft.graph.microsoft-graph? I want to ask a question about authentication of Microsoft Graph API.
I know that I have to get access token to use Microsoft Graph API.I want to get an access token so that it can be used with a personal Microsoft account,because I think about use of Microsoft Graph API in B to C usecase.
Therefore, I created a sample source code to acquire an access token by the following two methods.
(The language used is Kotlin.)

*

*(a) Method using com.microsoft.azure.msal4j

*(b) Method using com.microsoft.graph.microsoft-graph

Then, while the method (a) allowed me to sign in with a personal Microsoft account and obtain an access token, I couldn't sign in with a personal Microsoft account using method (b).When I execute the code in (b) and try to sign in, the following error is displayed on the screen.
Error Message:
You cannot sign in here with a personal account.
Please use your work or school account instead.

The implementation example of (a) is as follows. This implementation was created with reference to the following site.
site: https://github.com/AzureAD/microsoft-authentication-library-for-java/wiki/Acquiring-Token-Interactively
    fun getAccessTokenByMSAL(
        appId: String,
        scopes: List<String>
    ): String? {
        val scopeSet = HashSet<String>()
        scopes.stream().forEach { scope ->
            scopeSet.add(scope)
        }
        val app = PublicClientApplication
            .builder(appId)
            .authority("https://login.microsoftonline.com/common")
            .build();
        val params = InteractiveRequestParameters
            .builder(URI("http://localhost:8080"))
            .scopes(scopeSet)
            .build()
        val result = app.acquireToken(params).join()
        return result.accessToken()
    }

The implementation example of (b) is as follows. This implementation was created with reference to the following site.
site: https://learn.microsoft.com/ja-jp/graph/sdks/choose-authentication-providers?tabs=Java#InteractiveProvider
    fun getAccessTokenByGraphSdk(
        appId: String,
        scopes: List<String>
    ): String? {
        val credential = InteractiveBrowserCredentialBuilder()
            .clientId(appId)
            .redirectUrl("http://localhost:8080")
            .build()
        val authProvider = TokenCredentialAuthProvider(scopes, credential)

        return try {
            val url = URL("https://graph.microsoft.com/v1.0/me")
            authProvider.getAuthorizationTokenAsync(url).get()
        } catch (e: Exception) {
            println("Error occured")
            println(e)
            null
        }
    }

What I would like to ask this time is the difference in behavior between (a) and (b).
Why can't I sign in with my personal account in case (b)?
How can I personally sign in and get an access token using com.microsoft.graph.microsoft-graph?
I would appreciate it if you could answer.

A: Thanks to Jeevan_MSFT_Identity's Advice, finally I solve the issue.
I had to set authority host to 'https://login.microsoftonline.com/common' if I need to use personal account.
Fixed code is as follows.
    fun getAccessTokenByGraphSdk(
        appId: String,
        scopes: List<String>
    ): String? {
        val credential = InteractiveBrowserCredentialBuilder()
            .clientId(appId)
            .redirectUrl("http://localhost:8080")
            .authorityHost("https://login.microsoftonline.com/common") // Add this line
            .build()
        val authProvider = TokenCredentialAuthProvider(scopes, credential)

        return try {
            val url = URL("https://graph.microsoft.com/v1.0/me")
            authProvider.getAuthorizationTokenAsync(url).get()
        } catch (e: Exception) {
            println("Error occured")
            println(e)
            null
        }
    }


text:
Q: Reparenting a View in Android not working So I have code like such:
((LinearLayout) view.getParent()).removeView(view);
container.addView(view);

Now, correct me if I'm wrong, but that code should remove the view from its current ViewGroup, then add it to a new ViewGroup
However, the following exception is raised:
E/AndroidRuntime(31220): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

Any ideas on why this could be happening please?
EDIT: This only happens when android:animateLayoutChanges is set to true in the parent's XML tag

A: It doesn't work probably because the View has mParent field which is not being reset by calling removeView() on it's parent.
Instead, it.s probably better to inflate a new View.
Edit now that you've said about layoutTransition, you can try removing the layoutTransition from ViewParent while removing it. Never tried it myself though.
final ViewGroup parent = (ViewGroup) view.getParent();
final LayoutTransition transition = parent.getLayoutTransition();
parent.setLayoutTransition(null);
parent.removeView(view);
parent.setLayoutTransition(transition);
newParent.addView(view);

A: You should actually try casting it to ViewGroup:
((ViewGroup) childView.getParent()).removeView(childView);

A: Solved:
Due to the animation, the View isn't actually removed until the animation finishes, which takes about 300ms
So something like this should work fine (350ms timer just to make sure the animation has finished):
((ViewGroup) view.getParent()).removeView(view);
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    public void run() {
        container.addView(view);
    }
}, 350);


text:
Q: SAS scan function excluding numeric characters and other delimiters I am trying to extract words from the following string:
%let rule = %str(limit <= amount and debt > 5);

However, I want to extract only words limit amount and debt (names of my variables). How can I achieve this in SAS without extracting also and and 5 from the string?
Now I have:
%let var1 = %scan(&rule., 1, '= < >')

however, this also extracts and as the third variable and 5 as the fifth variable which I don't want. Do you know how to include also words and (or some other word e.g. or) and 5 (generally, all numeric characters) into the list of delimiters?

A: You will need to provide a list of all the variable names you're looking for and search for each one in turn, e.g. using the index function. Do you care if the same variable name comes up more than once in your string?
If the goal here is to provide some sort of input validation for your macro then rather than writing your own parser in macro logic, it might be simpler to try actually applying your &rule to a single row from the table you're querying,
E.g.
data _null_;
  set mytable(obs = 1);
  where &rule;
run;

If any of the required variables for &rule are not present, this should generate a fairly clear error message in the log.

A: You can use the TRNWORD function to replace/remove specific words like and or.
Be sure to include leading and trailing spaces so that you don't mess with variable name you want to keep untouched.
You can use the COMPRESS function to remove the operators, decimal points and all numbers.
This will work so long as your variable names do not contain numbers. If they do, drop the 'd' modifier from the COMPRESS function and amend the macro to use TRNWORD to remove numbers with leading spaces (e.g. ' 5'), as variables cannot start with digits.
the following macro will extract a specified word from your text string, report the result to the log, and provide the result in a macro variable :
%macro extract_word(txt_string, w_num);
    option nonotes;
    data _null_;
        _rule = "&txt_string.";
        _var1 = tranwrd(_rule, ' and ', ' ');
        _var2 = tranwrd(_var1, ' or ', ' ');
        _var3 = compress(_var2, '^=<>.', 'd');
        _word = scan(_var3, &w_num.);
        call symputx("word&w_num.", _word, 'G');
    run;
    options notes;
    %put NOTE: Word&w_num. = &&word&w_num..;
%mEnd extract_word;

Here are the results:
     %extract_word(%str(&rule.), 1);
NOTE: Word1 = limit
     %extract_word(%str(&rule.), 2);
NOTE: Word2 = amount
     %extract_word(%str(&rule.), 3);
NOTE: Word3 = debt


text:
Q: How to control sampling in Opentracing
I am new to opentracing and was trying it out.
Wanted to know is there a way to control sample rate and yes then how?
thanks,
Sandy

A: This depends entirely upon which implementation you use. For example, both Brave and Jaeger support sampling, and I would expect most other implementations do as well. That said, the OpenTracing spec does not cover sampling at this time-- it only handles the API for how to create traces, and doesn't cover what happens to traces after they created.


text:
Q: chrome bug display flex width 100 I have a little problem with my page.
view : https://user.oc-static.com/upload/2016/12/24/14826126993639_14825671380969_123.png
The problem is that the image is supposed to stay right completely BUT the image moves to the left when I change the resolution of the browser. The problem occurs with Chrome and Internet Explorer (not firefox)

html {
    height: 100%;
    background: black;
}
body {
    height: 100%;
    margin: 0;
    padding: 0;
}
table {
    border: 0;
    padding: 0;
    margin: 0;
}
#container {
    color: white;
    display: flex;
    overflow: hidden;
    height: 100%;
}
#global {
    width: 100%;
    height: 100%
    text-align: center;
}
#table {
    width: 100%;
    height: 100%;
}
#droite {
    height: 100%;
    text-align: right;
}
#image {
    height: 100%;
    display: block;
    width: inherit;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>test</title>

            d

A: If you add flex: 1 on the second element and flex: 0 on the first you should get the result you expect.
https://jsfiddle.net/wrmbh6qc/1/

html {
  height: 100%;
  background: black;
}

body {
  height: 100%;
  margin: 0;
  padding: 0;
}

table {
  border: 0;
  padding: 0;
  margin: 0;
}

#container {
  color: white;
  display: flex;
  overflow: hidden;
  height: 100%;
}

#global {
/*  width: 100%;*/
  height: 100%;
  text-align: center;
flex: 0;
}

#table {
  width: 100%;
  height: 100%;
}

#droite {
  height: 100%;
  text-align: right;
flex: 1;
width: -webkit-fill-available;
}

#image {
  height: 100%;
  width: auto;
}

          d

A: solution: delete the div with the id "Droite" and keep only the image.


text:
Q: SASS to CSS with ExtractTextPlugin I have been want to process my SCCS code to CSS in separated file, and to do that i have installed ExtractTextPlugin (css-loader, node-sass, sass-loader and style-loader were already installed)
npm install extract-text-webpack-plugin --save-dev

Then I added this code to config:
let path = require('path');
let ExtractTextPlugin = require('extract-text-webpack-plugin');

let conf = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'main.js',
        publicPath: 'dist/'
    },
    module: {
        rules: [

            {test : /\.scss$/, use: ExtractTextPlugin.extract({
                fallback: 'style-loader',
                use: ['css-loader', 'sass-loader']
              })}
        ]
    },
    plugins: [
        new ExtractTextPlugin('style.css')
    ]
};

module.exports = conf;

And then I tried to run it with npm run dev:
  "scripts": {
    "dev": "webpack --mode development"
  },

But after this i got this error:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'dev' ]
2 info using npm@6.4.1
3 info using node@v10.13.0
4 verbose run-script [ 'predev', 'dev', 'postdev' ]
5 info lifecycle webpack-learn@1.0.0~predev: webpack-learn@1.0.0
6 info lifecycle webpack-learn@1.0.0~dev: webpack-learn@1.0.0
7 verbose lifecycle webpack-learn@1.0.0~dev: unsafe-perm in lifecycle true
8 verbose lifecycle webpack-learn@1.0.0~dev: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\OSPanel\domains\webpack-learn\node_modules\.bin;C:\Users\bruce\bin;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\local\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\usr\bin;C:\Program Files\Git\cmd;C:\Program Files\Git\usr\bin;C:\Program Files\ConEmu\ConEmu\Scripts;C:\Program Files\ConEmu;C:\Program Files\ConEmu\ConEmu;C:\Python27;C:\Python27\Scripts;C:\ProgramData\Boxstarter;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Windows\System32\OpenSSH;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\Git\cmd;C:\Program Files (x86)\Skype\Phone;C:\Program Files\Microsoft VS Code\bin;C:\OSPanel\php;C:\PHP-5.5-x64;C:\ProgramData\ComposerSetup\bin;C:\PHP-7.2;C:\php;C:\HashiCorp\Vagrant\bin;C:\Program Files\PuTTY;D:\sync;C:\Program Files\MATLAB\R2018b\bin;C:\Program Files\MATLAB\R2014b\runtime\win64;C:\Program Files\MATLAB\R2014b\bin;C:\Program Files\MATLAB\R2014b\polyspace\bin;C:\Program Files\nodejs;C:\ProgramData\chocolatey\bin;C:\Users\bruce\AppData\Local\Microsoft\WindowsApps;C:\Users\bruce\AppData\Roaming\Composer\vendor\bin;C:\Users\bruce\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\bruce\AppData\Local\atom\bin;C:\Users\bruce\AppData\Roaming\npm;C:\Program Files\Git\usr\bin\vendor_perl;C:\Program Files\Git\usr\bin\core_perl
9 verbose lifecycle webpack-learn@1.0.0~dev: CWD: C:\OSPanel\domains\webpack-learn
10 silly lifecycle webpack-learn@1.0.0~dev: Args: [ '/d /s /c', 'webpack --mode development' ]
11 silly lifecycle webpack-learn@1.0.0~dev: Returned: code: 1  signal: null
12 info lifecycle webpack-learn@1.0.0~dev: Failed to exec dev script
13 verbose stack Error: webpack-learn@1.0.0 dev: `webpack --mode development`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:182:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:182:13)
13 verbose stack     at maybeClose (internal/child_process.js:962:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:251:5)
14 verbose pkgid webpack-learn@1.0.0
15 verbose cwd C:\OSPanel\domains\webpack-learn
16 verbose Windows_NT 10.0.17134
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "dev"
18 verbose node v10.13.0
19 verbose npm  v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error webpack-learn@1.0.0 dev: `webpack --mode development`
22 error Exit status 1
23 error Failed at the webpack-learn@1.0.0 dev script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

A: Why don't you do it with style-loader, css-loader and postcss-loader? Here is an example

{
  test: /\.scss$/,
  use: [{
      loader: 'style-loader' // creates style nodes from JS strings
    },
    {
      loader: require.resolve('css-loader'),
      options: {
        importLoaders: 1,
        modules: true,
        localIdentName: "[name]_[local]_[hash:base64:5]"
      },
    },
    {
      loader: 'sass-loader',
      options: {
        sourceMap: true,
        modules: true,
        localIdentName: "[name]_[local]_[hash:base64:5]"
      } // compiles Sass to CSS
    },
    {
      loader: require.resolve('postcss-loader'),
      options: {
        ident: 'postcss',
        plugins: () => [
          require('postcss-flexbugs-fixes'),
          autoprefixer({
            browsers: [
              '>1%',
              'last 4 versions',
              'Firefox ESR',
              'not ie < 9', // React doesn't support IE8 anyway
            ],
            flexbox: 'no-2009',
          }),
        ],
      },
    },
  ],
},

A: To convert a SCSS file to CSS you can do it in the terminal using this command:
sass example.scss newexample.css


text:
Q: Vim lines get off-by-one On Xubuntu 13.04, when I execute a VIM command command mode, like [esc] then :w. I'll occasionally find that a bunch of gobbly-gook stays in the very last line of the terminal. The text with the results of the command, ie
"test.txt" 6L, 36C written                 6,1 Bot

Will now appear on the second-to-last line of Vim instead of the very last line.
The problem is, when I'm returned to insert mode, the display is now one line off from what I'm editing. This only becomes apparent as I edit each character one-by-one. I'm not editing what is being displayed, and somehow everything is shifted up one line.
So somehow the Vim display buffer is getting corrupted, as if the EOL I type at the end of the command is not getting dealt with by vim (or the console?). As if the shell executes the EOL to scroll everything up a line when it shouldn't be, and now vim/the console is in a rather inconsistent state.
The only recourse is to restart vim.
Relevant versions:
vim 7.3.547
xfce-terminal 0.6.1


text:
Q: In javascript or jquery, what's the best way of running a function whose function name and parameters come in a json object? I'm receiving the following object for example:
var object = {
    functions: {
        0: 'myFunction',
        1: 'alert'
    },
    parameters: {
        0: {
            0: 'Testing myFunction...'
        },
        1: {
            0: 'Testing alert...'
        }
    }
}

After receiving object variable I want to run all the functions specified with the corresponding parameters.
That is, after receiving the object I want the following to happen:
myFunction('Testing myFunction');
alert('Testing alert');

Is there an elegant way of handling this or is stringconversion into eval the way to go? Some other methods I don't know about?

A: Simply loop over object.functions, and use .apply call it with its parameters from object.parameters.
for(var i in object.functions){
    if(object.functions.hasOwnProperty(i)){
        // Convert object.parameters[i] to an array
        var params = [];
        for(var j in object.parameters[i]){
            if(object.parameters[i].hasOwnProperty(j)){
                params.push(object.parameters[i][j]);
            }
        }
        // Call the function with an array of params
        window[object.functions[i]].apply(null, params);
    }
}


text:
Q: XFS drive unmounting on write I have a database backup script which does a mysqldump and copies the dump to an external hard drive with an XFS partition on it. Unfortunately partway through the copy, the drive dismounts and the device changes from say /dev/sdc to /dev/sdd. /dev/sdc1 will still be mounted, but the folder where it is mounted is not accessible. I unmount the drive and that's when the /dev/sdd (or whatever drive it decides to be) shows up. I mount that and it works just fine.
The dmesg output for when the backup script is running looks like this:
[328722.136119] usb 2-1: USB disconnect, address 69
[328722.172828] xfs_force_shutdown(sdc1,0x1) called from line 335 of file /build/buildd/linux-2.6.32/fs/xfs/xfs_rw.c.  Return address = 0xffffffffa030f9d3
[328722.172845] Filesystem "sdc1": I/O Error Detected.  Shutting down filesystem: sdc1
[328722.181694] Please umount the filesystem, and rectify the problem(s)
[328722.186817] xfs_force_shutdown(sdc1,0x1) called from line 335 of file /build/buildd/linux-2.6.32/fs/xfs/xfs_rw.c.  Return address = 0xffffffffa030f9d3
[328722.172845] Filesystem "sdc1": I/O Error Detected.  Shutting down filesystem : sdc1
[328722.181694] Please umount the filesystem, and rectify the problem(s)
[328722.186817] xfs_force_shutdown(sdc1,0x1) called from line 335 of file /build/buildd/linux-2.6.32/fs/xfs/xfs_rw.c.  Return address = 0xffffffffa030f9d3
[328734.520107] usb 2-1: new high speed USB device using ehci_hcd and address 70
[328734.675122] usb 2-1: configuration #1 chosen from 1 choice
[328734.675493] scsi322 : SCSI emulation for USB Mass Storage devices
[328734.675693] usb-storage: device found at 70
[328734.675697] usb-storage: waiting for device to settle before scanning
[328739.670293] usb-storage: device scan complete
[328739.672217] scsi 322:0:0:0: Direct-Access     Seagate  Desktop          0130

PQ: 0 ANSI: 4
I've ran some filesystem checks on the disk, it seems to come out ok. I've used the disk for other things as well and it also works. It seems like this happens every time I run the backup script.

A: Well, it says in your logs: USB disconnect. Could be a loose cable/connector or maybe ovecurrent on USB port if your backup script causes a lot of activity.
If you want to be absolutely sure it's not filesystem-type related you could re-format the external drive and see how it behaves with ext4/3, NTFS or VFAT.


text:
Q: (Android) Why i use SmsManager.getDefault().sendTextMessage but apps dont send sms? I have use SmsManager.getDefault().sendTextMessage but not send sms i want to method programmatically send sms Please see this code
EDIT CODE:
    public void sendEmail(View view){
            if (hasConnection() == false){
                Intent goPop = new Intent(getApplicationContext(),ShowPopup.class);
                startActivity(goPop);
                finish();
            }
            statusOfGPS = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // Set Email option
            final Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",OpsEmail, null));

            //Check Send SMS
            if (mSMSCheckbox.isChecked()){
                SMS = true;
            }else{
                SMS = false;
            }

            //Check GPs
            if (statusOfGPS == true){
                LocationBy = "GPS";

            }else{
                LocationBy = "INTERNET";
            }
            setUpAddress();
            //SMS true
            if (mLocationClient != null && mLocationClient.isConnected() && SMS == true) {
                //set massage to send
                DescribeText = "This is a Emergency message \n\n PLEASE HELP ME!!! at\n\n "+
                        addressText+ "\n Location("+LocationBy+"):("+mLocationClient.getLastLocation().getLatitude() + mLocationClient.getLastLocation().getLongitude()+
                        ") \n\n Please check maps here";

                //send SMS First
                String sent = "android.telephony.SmsManager.STATUS_ON_ICC_SENT";
                SmsManager smsManager = SmsManager.getDefault();
                PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(sent), 0);
                smsManager.sendTextMessage(OpsPhoneNumber, null, DescribeText, pi,null);

                //send email
                i.putExtra(Intent.EXTRA_SUBJECT, "Emergency Location");
                i.putExtra(Intent.EXTRA_TEXT,Html.fromHtml(DescribeText));
                try {
                    startActivity(Intent.createChooser(i, "Send mail..."));
                } catch (android.content.ActivityNotFoundException ex) {
                    Toast.makeText(getApplicationContext(), "There are no email clients installed.", Toast.LENGTH_LONG).show();
                }

             Log.d(TAG, "gps =" + statusOfGPS);
            }
}

Next line of //send SMS First
i use

SmsManager.getDefault().sendTextMessage(OpsPhoneNumber, null,
  DescribeText, null,null);

and in my manifest file i have:
<uses-permission android:name="android.permission.SEND_SMS"/>

My device to test is android 4.2.2 and 4.1.1
but apps don't send sms how to fix this?

A: SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("", null, "< message body>", null, null);

SmsManager require, SMS_SEND permission in your android mainfest.


text:
Q: Google Map API - setPanel - Cannot read property 'text' of undefined I have been trying this transit example. This is not the ZERO_RESULTS error.
When I am using direction API with TRANSIT mode. For specific locations, I do get a route, however there is an uncaught typeerror for SetPanel. I have attached one such example. This works well with most locations. However, for the route I have entered in the example, I do receive such errors. There are many such routes which result in this error.

Uncaught TypeError: Cannot read property 'text' of undefined

http://jsfiddle.net/zfz477e8/

<!DOCTYPE html>

    <title>Google Maps JavaScript API v3 Example: Transit</title>

      <button id="transit">Toggle transit layer</button>

Transit directions

          from:
          <input class="input" id="from" value="Grand Central 42, NY">

          to:
          51 St, New York, NY 10022, USA

Depart at <select id="depart"></select>

          <button id="go">Get Directions</button>

A: Looks like a bug in the release and experimental versions of the API

(experimental) v=3.exp or no version string     has the error
(release)      v=3                              has the error
???            v=3.22                           doesn't have the error
(frozen)       v=3.0 or v=3.21                  doesn't have the error

Issue in the issue tracker: Issue 9307: Google Map API - setPanel - Cannot read property 'text' of undefined

*

*fiddle v=3.21

*fiddle v=3.22

*fiddle v=3.23

*fiddle v=3
code snippet:

var directions = new google.maps.DirectionsService();
var renderer = new google.maps.DirectionsRenderer();
var map, transitLayer;

function initialize() {
  var mapOptions = {
    zoom: 13,
    center: new google.maps.LatLng(40.7482333, -73.8681295),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById('map'), mapOptions);

  google.maps.event.addDomListener(document.getElementById('go'), 'click',
    route);

  var input = document.getElementById('from');
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.bindTo('bounds', map);

  transitLayer = new google.maps.TransitLayer();

  var control = document.getElementById('transit-wpr');
  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);

  google.maps.event.addDomListener(control, 'click', function() {
    transitLayer.setMap(transitLayer.getMap() ? null : map);
  });

  addDepart();
  route();
}

function addDepart() {
  var depart = document.getElementById('depart');
  for (var i = 0; i < 24; i++) {
    for (var j = 0; j < 60; j += 15) {
      var x = i < 10 ? '0' + i : i;
      var y = j < 10 ? '0' + j : j;
      depart.innerHTML += '<option>' + x + ':' + y + '</option>';
    }
  }
}

function route() {
  var departure = document.getElementById('depart').value;
  var bits = departure.split(':');
  var now = new Date();
  var tzOffset = (now.getTimezoneOffset() + 60) * 60 * 1000;

  var time = new Date();
  time.setHours(bits[0]);
  time.setMinutes(bits[1]);

  var ms = time.getTime() - tzOffset;
  if (ms < now.getTime()) {
    ms += 24 * 60 * 60 * 1000;
  }

  var departureTime = new Date(ms);

  var request = {
    origin: document.getElementById('from').value,
    destination: '51 St, New York, NY 10022, USA',
    travelMode: google.maps.DirectionsTravelMode.TRANSIT,
    provideRouteAlternatives: true,
    transitOptions: {
      departureTime: departureTime
    }
  };

  var panel = document.getElementById('panel');
  panel.innerHTML = '';
  directions.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      renderer.setDirections(response);
      renderer.setMap(map);
      renderer.setPanel(panel);
      console.log(renderer.getDirections());
    } else {
      renderer.setMap(null);
      renderer.setPanel(null);
    }

  });

}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body {
  height: 100%;
  padding: 0;
  margin: 0;
  color: black;
  font-family: arial, sans-serif;
  font-size: 13px;
}
#map {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 50%;
}
#panel-wpr {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 50%;
  right: 0;
  overflow: auto;
}
#panel {
  font-family: arial;
  padding: 0 5px;
}
#info {
  padding: 5px;
}
#from {
  width: 90%;
  font-size: 1.2em;
}
.adp-directions {
  width: 100%;
}
.input {
  background-color: white;
  padding-left: 8px;
  border: 1px solid #D9D9D9;
  border-top: 1px solid silver;
  -webkit-border-radius: 1px;
  -moz-border-radius: 1px;
  border-radius: 1px;
}
.time {
  margin: 0;
  height: 17px;
  border: 1px solid;
  border-top-color: #CCC;
  border-right-color: #999;
  border-left-color: #999;
  border-bottom-color: #CCC;
  padding: 2px 15px 1px 1px;
}
button {
  border: 1px solid #3079ED;
  color: white;
  background-color: #4D90FE;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#4D90FE), to(#4787ED));
  background-image: -webkit-linear-gradient(top, #4D90FE, #4787ED);
  background-image: -moz-linear-gradient(top, #4D90FE, #4787ED);
  background-image: -ms-linear-gradient(top, #4D90FE, #4787ED);
  background-image: -o-linear-gradient(top, #4D90FE, #4787ED);
  background-image: linear-gradient(top, #4D90FE, #4787ED);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorStr='#4d90fe', EndColorStr='#4787ed');
  display: inline-block;
  min-width: 54px;
  text-align: center;
  font-weight: bold;
  padding: 0 8px;
  line-height: 27px;
  -webkit-border-radius: 2px;
  -moz-border-radius: 2px;
  border-radius: 2px;
  -webkit-transition: all 0.218s;
  -moz-transition: all 0.218s;
  -o-transition: all 0.218s;
  transition: all 0.218s;
}
#info div {
  line-height: 22px;
  font-size: 110%;
}
.btn {} #panel-wpr {
  border-left: 1px solid #e6e6e6;
}
#info {
  border-bottom: 1px solid #E6E6E6;
  margin-bottom: 5px;
}
h2 {
  margin: 0;
  padding: 0;
}

<title>Google Maps JavaScript API v3 Example: Transit</title>

  <button id="transit">Toggle transit layer</button>

Transit directions

      from:
      <input class="input" id="from" value="Grand Central 42, NY">

      to:
      51 St, New York, NY 10022, USA

Depart at
      <select id="depart"></select>

      <button id="go">Get Directions</button>


text:
Q: What kind of FEC is suitable for me? I'm sending over the air data block which is 144 bytes.
I can put additional 18 bytes of data for error correction.
The field for FEC looks very small and I can't find what I can use.
I have not requirements about BER, the number of bits to restore etc.
I need to fix as much as possible.
What FEC I can use for 162 bytes block where is 144 bytes data and 18 bytes FEC?

A: There are many out there.
If you are a newbie, I suggest you to read Texas Instruments DN504 for a clear explanation and for a software implementation.
This  document gives an overview of the FEC implementation in the CC11XX, and CC25XX RF transceivers families.
https://www.ti.com/lit/an/swra113a/swra113a.pdf?ts=1619516881539&ref_url=https%253A%252F%252Fwww.google.com%252F


text:
Q: How to Download MSI installer with argument for user-id I have a .NET C# application, wrapped inside MSI installer - "myprogram.exe". I have a PHP website and a specific page where user can download the program via a link.
I would like to be able to track certain events on the .NET app. For example - "Program Opened".
It's easy to send events to my server, however how do I grab the user-id from the php server, so I can know which user did what on the .NET app?
I thought about passing an argument (the user-id) to the MSI installer but could not find a way to that.
How do I link between the PHP user-id and the .NET app?
Clarification -
Many people offered to use a login system to bind between the server and app.
This is indeed the easiest solution, however on my website I do not force the user to login to download the app (nor I request login details in the .NET app - its optional). If we dont have to ask for login details, I think we shouldn't,  the experience for the user will be much better (far less steps to use the app) - greater chance for the user to download and use the Desktop app.
Consider that current flow is -> Webpage - Download click - Run - Use the app
(takes 10 seconds)
With login -> Webpage - Register (confirm email?) - Redirect - Download Click - run - app Login - Use the app
(takes 60-120 seconds for the user)

A: Please note its very likely this is not what you want to do. Never the less I'll explain a couple of ways to do it..
Using MST files with MSIs:
You can create MST files with a user-id property and generate these for each user when they download the msi and make them install the msi with a transform:
msiexec -i c:\temp\The.msi transforms=c:\temp\YourPerso.mst

See more info here: Install a transform using the command line.
MST files used a lot in large organisations, where all the MSI's have MST files with the serial numbers and etc embedded.
To make an MST file you need to download and install Microsofts Orca Tool, its part of the Microsoft Windows SDK.
Open Orca and create an MST file out of the MSI file. Basically you open the MSI file navigate to table "Property", there you see a list of parameters.
Note in MSI file you'll see parameters which require default value.
Before you add/change parameters, create a new Transformation by clicking in menu on "Transform" -> "New Transform".

Afterwards you can change parameters or add new ones as you want to. When you have finished the parameter changes use function "Generate Transform" in "Transform" menu to generate a MST file.

If you then open the mst file with a HexEditor you can see the property you just added:

You could edit the file for each download by simply editing the value, eg:

You can of course (and probably should) do this the proper way using the API of the WindowsInstaller.Installer. Here is an example:
private function createTransform(mstfile, msi, config)
    writeLog InfoLog, "Generating transform " & mstfile

    dim vars: set vars = configvars(config)

    dim createPropertyTable: createPropertyTable = "create table `Property` " & _
        "(`Property` char(72) not null, `Value` longchar localizable " & _
        "primary key `Property`)"
    dim addProperty: addProperty = "insert into `Property` (`Property`, `Value`) values (?, ?)"
    dim updateProperty: updateProperty = "update `Property` set `Value` = ? where `Property` = ?"

    dim wi: set wi = createObject("WindowsInstaller.Installer")
    dim base: set base = wi.openDatabase("base.msi", msiOpenDatabaseModeCreate)
    base.openview(createPropertyTable).execute
    dim tgt: set tgt = wi.openDatabase("tgt.msi", msiOpenDatabaseModeCreate)
    tgt.openview(createPropertyTable).execute
    dim props: set props = createObject("scripting.dictionary")
    dim view: set view = msi.openView("select `Property`, `Value` from `Property`")
    view.execute
    dim record: set record = view.fetch
    while not record is nothing
        props(record.stringdata(1)) = true
        base.openview(addProperty).execute record
        tgt.openview(addProperty).execute record
        set record = view.fetch
    wend

    set record = wi.createRecord(2)
    dim prop
    for each prop in properties_
        on error resume next
        dim val: val = expand(vars, prop(DepPropertyValueIdx))
        if err then
            writeLog ErrorLog, err.description
            exit function
        end if
        on error goto 0
        writeLog InfoLog, "Property " & prop(DepPropertyNameIdx) & "=" & val
        if props.exists(prop(DepPropertyNameIdx)) then
            record.stringdata(2) = prop(DepPropertyNameIdx)
            record.stringdata(1) = val
            tgt.openview(updateProperty).execute record
        else
            record.stringdata(1) = prop(DepPropertyNameIdx)
            record.stringdata(2) = val
            tgt.openview(addProperty).execute record
        end if
    next
    if not tgt.generateTransform(base, mstfile) then
        writeLog ErrorLog, "Failed to create transform"
        exit function
    end if
    tgt.createTransformSummaryInfo msi, mstfile, 0, 0
    createTransform = true
end function

Tip: To do this with managed code you're best off using the Microsoft.Deployment.WindowsInstaller.dll thats available as part of http://wix.codeplex.com/

Build an MSI for each user:
IMHO it would be far easier to do this with Nullsoft (WiX, InstallShield, INNO, etc) and build a MSI for each user. To do this you would embed a unique user id in for example an nsi script and kick off a MSI build for each download. During install the unique user id would be stored in a file, registry key or etc. I suggest you give this a go using this  NSIS Wizard Editor to quickly whip up a basic NSI install script and build the MSI via a command line: makensis.
Note: While "Including the user-id in MSI filename" is easier than building an MSI for each user, users can easily change the filename. Its much, much less likely a user will audit the MSI using Orca to find an inbuilt user id.

The easiest and most logical way:

It's easy to send events to my server, however how do I grab the
  user-id from the php server, so I can know which user did what on the .NET app?

Do what @Jhuliano Moreno and then @WouterHuysentruit recommended:
When your application starts up for the first time simply make the user login to the program using their website credentials and record their user id in a config file, registry key or database record. Basically creating a cookie so you'll know them next time the opens the program - or make them login everytime.

A: When the file is called send a parameter of the UserID, if you are using an MVC framework in your PHP you would need a new controller that gets the msi file, and renames it to name-userID.exe and then returns the file to download via the browser.

A: Login from the program
The best way is to let the user sign-in with the same credentials in your program. This way, your program can use secure OAuth2 authentication to communicate with your back-end API. This also makes it transparent to the user that the program is communicating with the internet.
Include user-id in filename
An other way is to add the user-id to the filename of the installer during download and extract it when the installer runs. You will have to check if your installer tool allows this. Also, only do this if you user-id's are UUID's or something similar as you don't want the user to guess other id's.
App.config
A third option is to add the user-id to the App.config file. There are two ways to do this:

*

*Create your .msi with App.config uncompressed, add a user-id setting with fixed UUID. Your PHP script can lookup the UUID and replace it in the .msi binary before sending it to the user. See code snippet under MST transform

*Build the .msi on demand with the custom App.config. This will only work if your webserver is running on Windows or you have a remote Windows build server that can do this job.

MST transform
You could also use an MST transform and use the same binary replace trick as I've explained for point 1 under App.config.
For both options, you could use a PHP script that uses binary-safe functions to replace the values in the installer and sends the file to the user as a download:
<?php
$userId = // TODO get userId from the session or database
$data = file_get_contents("./my-installer.msi");
// I would use UUID's for template and userId, this way the size of the installer remains the same after replace
$data = str_replace("{fe06bd4e-4bed-4954-be14-42fb79a79817}", $userId, $data);
// Return the file as download
header("Cache-Control: public"); // needed for i.e.
header('Content-Disposition: attachment; filename=my-installer.msi');
header('Content-Type: application/x-msi');
header("Content-Transfer-Encoding: Binary");
echo $data;
?>

Serial number
Last method I can think of is to let the program ask for a serial number on first startup and let your website generate a unique serial number for each user.


text:
Q: Zend Framework 1.8 Autoloading Zend_Gdata_YouTube VideoQuery.php I'm having issues with Zend_Gdata_YouTube.
It seems unable to locate the file VideoQuery.php despite the fact it is one of the directories mentioned in the warning messages.
Also I created a standalone version of the example just including 'Zend/Gdata/YouTube.php'. This works fine.
I've dropped the error messages then the class followed by the working example into a paste bin.
Paste Bin

A: I got the same error after I upgraded from ZF 1.8.0 to 1.8.4, after searching for a solution with no luck I posted my error on the ZF Gdata mail list and Trevor Johns was nice enough to get back to me with this response:
"This looks like this issue:
http://framework.zend.com/issues/browse/ZF-7013

This will be fixed in the next release of Zend Framework. If you don't
want to wait that long, you can either:

*

*Download a development snapshot from here:

hxxp://framework.zend.com/code/browse/~tarball=zip/Zend_Framework/standard/trunk/trunk.zip

*Use version 1.8.3:

hxxp://framework.zend.com/releases/ZendFramework-1.8.3/ZendFramework-1.8.3.tar.gz

*Don't use Zend_Loader's autoloader functionality. (This bug only
seems to show up if you're trying to autoload the classes.)"

I'll be rolling back my ZF version until the next release.
p.s. had to substitute http with hxxp because "new users can only post a maximum of one hyperlink" apparently.

A: The files Zend\Gdata\Media\Extension\VideoQuery.php and Zend\Gdata\YouTube\Extension\VideoQuery.php do not exist in the framework. I think the file you want is Zend\Gdata\YouTube\VideoQuery.php
Does this help? What code is using these classes, your code or the framework code?


text:
Q: Does c#/.net x.x have an implementation of a doubly linked list (that can be iterated over backwards)? I've been searching for the standard implementation of a doubly linked list in c# (so that I have a linked list I can iterate over backwards) and cannot find one. I feel like something so simple must have an implementation that I'm just missing.
If it does exist, for which version of c#/.net does it exist?
Reverse iteration in general seems to be something not intended to be done in c#. Is my mind just stuck too much in c++/stl mode or is this something sorely lacking in c#?
I'm aware of LinkedList but in failing to find a way to iterate over it backwards had assumed it was singly linked.
If LinkedList is doubly linked how does one go about iterating over it backwards (Efficiently)?

A: As well as the answers given here, you can write an extension method to LinkedList<T> to make it slightly easier to reuse:
public static IEnumerable<T> Backwards<T>(this LinkedList<T> list)
{
    LinkedListNode<T> node= list.Last;
    while (node != null)
    {
        yield return node.Value;
        node = node.Previous;
    }
}

Use with:
foreach (string x in list.Backwards())
{
    // ...
}

A: How about System.Collections.Generic.LinkedList()
Here are the docs on MSDN:
http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx
Version Info
.NET Framework: Supported in: 3.5, 3.0, 2.0
.NET Compact Framework: Supported in: 3.5, 2.0
XNA Framework: Supported in: 3.0, 2.0, 1.0
That said, I am with the others that it is generally preferrable to use a higher abstraction when working with such a rich framework.

A: The following code will efficiently iterate over a LinkedList in reverse:
        LinkedList<string> list = new LinkedList<string>
            (new[] {"cat", "dog", "frog", "antelope", "gazelle"});
        LinkedListNode<string> item = list.Last;
        do
        {
            Console.WriteLine(item.Value);
            item = item.Previous;
        }
        while (item != null);
        Console.ReadKey();

The key here is that a LinkedList contains reference to only the First and Last LinkedListNode instances of the list. Each LinkedListNode instance holds a reference to the next and previous item in the list (or null at each end of the list) and also a Value property. This means iteration from the first or last LinkedListNode is easy, but random access requires iteration from the first or last in the list.
If you need to make an insertion along the way, use LinkedList.AddBefore or AddAfter to insert a new LinkedListNode.

A: How about LinkedList?


text:
Q: Scores of black and white marks We have a connected (undirected) graph with $n$ vertices, and $b$ black and $w$ white marks with $b+w=n$ and $\max(b,w)\geq 2$. In a placement of the marks on the vertices, the "score" of a mark is the ratio of its neighbors of the same color to its total neighbors (this ratio is always well-defined due to connectivity). A placement is called "nice" if it is not possible to rearrange the marks so that every mark gets a better or same score as before, and at least one mark gets a better score.
Is it true that in any nice placement, the sum of the scores is at least $1$?
The score may be $1$, if the graph is a triangle and $b=2,w=1$.

A: The statement is true.
Let $G$ be our graph, $\{v_1, v_2, \dots, v_n\}$ be its vertices, and $(d_1, d_2, \dots, d_n)$ be the corresponding sequence of their degrees. Any placement $p$ of $b$ black and $w$ white marks also induces the corresponding sequence $(p_1, p_2, \dots, p_n)$, where $p_i$ is the number of vertices adjacent to $v_i$ and having the same color as $v_i$.
Definition 1. We say that a placement $q$ majorizes $p$, if it contains the same numbers of black and white marks as $p$ and induces the sequence $(q_1, q_2, \dots, q_n)$, where $\forall i \colon q_i \ge p_i$ and $q_i > p_i$ for at least one $i$.
The statement in question is equivalent to the claim that if
$$\frac {p_1}{d_1} + \frac {p_2}{d_2} + \dots + \frac {p_n}{d_n} < 1\,, \tag{1}$$
then there is a placement $q$ that majorizes $p$.
To prove it, first note that $(1)$ implies $\min(b,w) \ge 1$, otherwise every summand at the left-hand side of $(1)$ would be $1$ and the sum would be the natural number $n$. This also means that
$$n = b + w = \min(b, w) + \max(b, w) \ge 1 + 2 = 3\,. \tag{2}$$
Consider the spanning subgraph $H$ of $G$ that contains only edges connecting equally colored (by $p$) vertices of $G$. It breaks down into several connected components (whereas $G$ was connected). Note that each component contains only vertices of one color. We number the black components: $\mathcal B = \{B_1, B_2, \dots, B_t\}$. If $b_i = |B_i|$ are their sizes (in set theory terms), then $b_1 + b_2 + \dots + b_t = b$. Also do the same for the white components: $\mathcal W = \{W_1, W_2, \dots, W_s\}$. If $w_i = |W_i|$, then $w_1 + w_2 + \dots + w_s = w$. Let $k = t + s$ be the total number of components and $e$ be the total number of edges in $H$. Since a component with $r$ vertices contains at least $r - 1$ edges, summing this for all components, we obtain: $e \ge n - k$. On the other hand, $2e = p_1 + p_2 + \dots + p_n$. Since each $d_i \le n - 1$, from $(1)$ we have: $\frac {2e}{n - 1} = \sum_{i=1}^n \frac {p_i}{n - 1} \le \sum_{i=1}^n \frac {p_i}{d_i} < 1$, thus $2e < n - 1,$ $2n - 2k \le 2e \le n - 2$ and $$n \le 2k - 2\,. \tag{3}$$
Note that $k$ is the quantity of the numbers $b_i, w_i$ and $n$ is their sum. Thus $(3)$, in particular, implies that their average $\frac n k$ is less than $2$. Therefore, at least one of them is $1$. WLOG, $b_1 = 1$. Let $u \ge 1$ be the total number of units among $b_i$. The remaining $t - u$ numbers are $2$ or greater, hence $b = b_1 + b_2 + \dots + b_t \ge u + 2(t - u) = 2t - u$. Let $m = \min (w_1, w_2, \dots, w_s)$. Then $w = w_1 + w_2 + \dots + w_s \ge ms$. From this and $(3)$: $2(t + s) - 2 \ge b + w \ge (2t - u) + ms$, thus $u - 2 \ge (m - 2)s$. We conclude that the case $m > u$ is impossible since then $m - 2 > u - 2 \ge (m - 2)s$ and $0 > (m - 2)(s - 1)$, but $m \ge u + 1 \ge 2$ and $s \ge 1$. Therefore,
$$u \ge m\,. \tag{4}$$
The key part of the upcoming reasoning is based on the following definition and lemma.
Definition 2. A placement $p$ is called sub-balanced if there are two sets, $\mathcal B\,' \subseteq \mathcal B$ and $\mathcal W\,' \subseteq \mathcal W$ such that $\mathcal B\,' \cup \mathcal W\,'$ is a proper nonempty subset of $\mathcal B \cup \mathcal W$ and the total number of vertices in components from $\mathcal B\,'$ is equal to the total number of vertices in components from $\mathcal W\,'$.
Lemma. If $p$ is sub-balanced, then it isn't nice, i.e. there is another placement that majorizes it.
Proof. Let $p$ be sub-balanced. Denote by $V$ the set of all vertices contained in components from $\mathcal B\,' \cup \mathcal W\,'$. We compose the placement $q$ by simply changing colors of all vertices in $V$, i.e. from black to white in $\mathcal B\,'$ and from white to black in $\mathcal W\,'$. The ratio of black and white vertices remains unchanged. If $v_i$ was in some component $B_j$ or $W_j$, then all vertices counted by $p_i$ were in the same component. Its color may have changed, but all these vertices still have the same color in $q$, therefore $\forall i \colon q_i \ge p_i$. To prove that $q_i > p_i$ for some $i$, take two vertices, one of which is from $V$ and the other is not (this is possible because $V$ is a proper nonempty subset of $G$'s vertices). $G$ is connected, therefore we can connect these vertices by a path in $G$. There is an edge $(v_i, v_j)$ in this path such that $v_i \in V$ and $v_j \notin V\!.$ $v_i$ and $v_j$ were of different colors in $p$ because otherwise $v_j$ should have been in the same component as $v_i$ and therefore should have belonged to $V$. But now, as long as the color of $v_i$ has changed and the color of $v_j$ has not, $v_i$ and $v_j$ have the same color; hence $q_i > p_i$ and $q_j > p_j$. ∎
From this point on, we simply apply the lemma for the cases when $p$ is sub-balanced and exclude these cases from consideration. The first of such cases is $u > m$ — we take the white component of size $m$ as $\mathcal W\,'$ and $m$ black components of size $1$ as $\mathcal B\,'$; since $u > m$, there are still components remaining. The second case is $(u = m) \land ((t > u) \lor (s > 1))$ — we do the same to prove that $p$ is sub-balanced.
From $(4)$ it follows that the only remaining case is $u = m = t$, $s = 1$, i.e. $\mathcal W$ is a sole white component of size $t$, and $\mathcal B$ is a set of $t$ black components of size $1$. From $(2)$ it follows that $t > 1$. Let's prove that $t \le 3$. For this, we estimate the left-hand side of $(1)$ from below. The $t$ terms corresponding to black points are of no interest to us because $p_i = 0$ for them. Let $I$ be the set of the white vertex indices, $|I| = t$. For any $i \in I$, the difference $d_i - p_i$ is the number of black vertices adjacent to $v_i$ in $G$. It is at most $t$. Thus, $d_i = (d_i - p_i) + p_i \le t + p_i$ and $\frac {p_i}{d_i} \ge \frac {p_i}{t + p_i} = 1 - \frac t{t + p_i}$. Summing this for all $i \in I$ and using $(1)$, we get: $1 > t \left(1 - \sum_{i \in I} \frac 1{t + p_i}\right)$, hence
$$\sum_{i\,\in\,I} \frac 1{t + p_i} > \frac {t - 1}t\,. \tag{5}$$
$W_1$ is connected in $H$, therefore $\forall i \in I \colon p_i \ge 1$. Let's prove that $p_i > 1$ for at most one $i$. Indeed, otherwise $\frac {t-2}{t+1} + \frac 2{t+2} \ge \sum_{i \in I} \frac 1{t + p_i} > \frac {t - 1} t$ and we would get: $(t^3 - 4t) + (2t^2 + 2t)> t^3 + 2t^2 - t - 2$ and $2 > t$, whereas $t > 1$.
Now we know the structure of $W_1$, the subgraph induced in $G$ by the set of all white vertices: it is a star with $t$ vertices. If $t > 2$, and $v_i$ is its internal node, then $p_i = t - 1$ and $(5)$ turns into $\frac {t-1}{t+1} + \frac 1 {2t-1} > \frac {t-1}t$. From this, we conclude: $(2t^3 - 3t^2 + t) + (t^2 + t) > 2t^3 - t^2 - 2t + 1$, hence $3 > (t - 2)^2$ and $t = 3$.
What remains is to analyze 4-vertex and 6-vertex graphs of the designated structure. Note that each white vertex in them is adjacent to at least one black vertex because otherwise $d_i = p_i$ for some $i \in I$, which would contradict $(1)$. Moreover, at least one of the two white vertices for which $p_i = 1$, is adjacent to at least two black vertices because otherwise we would have two $\frac 1 2$ at the left-hand side of $(1)$. Let $x$ be such a vertex, $y$ be its white neighbour, and $z$ be a black neighbour of $y$. Since $x$ is adjacent to at least one black vertex different from $z$, we can swap the colors of $x$ and $z$ and obtain a placement that majorizes $p$. This concludes the proof.


text:
Q: Python: how does a dict with mixed key type work? I understand that the following is valid in Python: foo = {'a': 0, 1: 2, some_obj: 'c'}
However, I wonder how the internal works. Does it treat everything (object, string, number, etc.) as object? Does it type check to determine how to compute the hash code given a key?

A: You can answer this by opening a Python interactive prompt and trying several of these keys:
>>> hash('a')
12416037344
>>> hash(2)
2
>>> hash(object())
8736272801544

Does it treat everything (object, string, number, etc.) as object?

You are simply using the hash function to represent each dictionary key as an integer. This integer is simply used to index in the underlying dictionary array. Assuming a dictionary starts of with a pre-allocated size of 8, we use the modulus operator (the remainder) to fit it into an appropriate location:
>>> hash('a')
12416037344
>>> hash(object()) % 8
2

So in this particular case, the hashed object is placed in index 2 of the underlying array. Of course there can be collisions, and so depending on the underlying implementation, the underlying array may actually be an array of arrays.
Note that items that aren't hashable cannot be used as dictionary keys:
>>> hash({})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

Proof:
>>> d = {}
>>> d[{}] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

A: Types aren't used the same way in Python as statically types languages. A hashable object is simply one with a valid hash method. The interpreter simply calls that method, no type checking or anything. From there on out, standard hash map principles apply: for an object to fulfill the contract, it must implement both hash and equals methods.

A: Everything in Python is an object, and every object which has a __hash__ method can be used as a dictionary key. How exactly the method (tries to) return a unique integer for each possible key is thus specific to each class, and somewhat private (to use the term carelessly for humorous effect). See https://wiki.python.org/moin/DictionaryKeys for details.
(There are a couple of other methods your class needs to  support before it is completely hashable. Again, see the linked exposition.)

A: I think it would work as long, the object supports __hash__ method and the __hash__(self) of two objects return same values for which __eq__ returns True. hashable objects are explained here.
eg. Try following
a = []
a.__hash__ == None # True
aa = 'xyz'
aa.__hash__ == None # False
a = (1,1,) # A Tuple, hashable
a.__hash__ == None # False

Hope that helps

A: It might be easier to ignore dictionaries for a moment, and just think of sets. You can probably see how a set s might consist of {'a', 1, some_object}, right? And that if you tried to add 1 to this set, it wouldn't do anything (since 1 is already there)?
Now, suppose you try to add a another_object to s. another_object is not 1 or 'a', so to see if it can be added to s, Python will see if another_object is equal to some_object. Understanding object equality is a whole nother subject, but suffice it to say, there is a sensible way to go about it. If  another_object == some_object is true, then s will remain unchanged. Otherwise, s will consist of {'a', 1, some_object, another_object}.
Hopefully, this makes sense to you. If it does, then just think of dictionaries as special sets. The keys of the dictionary are the entries of the set, and values of the dictionary just hold a single value for each key. Saying d['and now'] = 'completely different' is just the same thing as deleting 'and now' from the set, and then adding it back it again with 'completely different' as its associated value. (This isn't technically how a dict handles __setitem__ , but it can be helpful to think of a dict as working this way. In reality, sets are more like crippled dicts than dicts are like extra powerful sets).
Of course, with dicts you should bear in mind that only hashable objects are allowed in a dict. But that is itself a different subject, and not really the crux of your question, AFAICT


text:
Q: Extra style attribute added by Apex in IFrame I am trying to open Oracle Apex application inside an iframe. I have an index.jsp which has the following code
<body>
     <iframe id="apexiFrame"
            width="100% !important" height="100% !important"
            src="http://localhost:9999/ords/f?p=101">
     </iframe>
</body>

If I change localhost to system name, login page loads fine but when I go to the next page after login and in all other subsequent pages, I can see an extra style attribute is getting added and hence apex application occupies only half of the iframe

I am not able to find from where this style attribute is getting added. Please help.
Update:
I added jquery to remove the extra style attribute on page load.
$('iframe').load( function() {

    $("iframe").removeAttr("style");

});

Though it does the trick still there is a delay of 1 second between the iframe loading (with style tag) and then removing it because of which the iframe width changing from 500px to 100% is noticeable. If there is a way to avoid the style tag getting added automatically, that will be the ideal solution I guess. Any leads please?

A: You are mixing up CSS inside your IFRAME HTML tag. The width= and height= should be either pixels width=500 or percentage height=100%.  That may be causing the issue.
You could try
 <iframe id="apexiFrame"
        style="height:100%;width:100%;"
        src="http://localhost:9999/ords/f?p=101">
 </iframe>

Not sure where the !important would go on the style tag.
Now, to see if you can get rid of APEX's style, open up your application in APEX Designer, App Builder tab, choose "Shared Components" and in the User Interface block, wander around the Themes and Templates links.

A: I added jquery to remove the extra style attribute on iframe load and restarted the server.

$('iframe').load( function() {

$("iframe").removeAttr("style");

});


text:
Q: Count and Joins with Where Customer
CustomerID Name
4001       John Bob
4002       Joey Markle
4003       Johny Brown
4004       Jessie Black

Orders
OrderID    Customer   Status
50001      4001       Paid
50002      4002       Paid
50003      4001       Paid
50004      4003       Paid
50005      4001       Paid
50006      4003       Paid
50007      4004       Unpaid

I tried this join
Select c.Customer, COUNT(o.OrderID) as TotalOrders
from Customer c
inner join Orders o
on c.Customer = o.Customer
Where o.Status = 'Paid'
Group by c.Customer

But here is the result.
Customer  TotalOrders
4001      3
4002      1
4003      2

The customer with unpaid is not included. How I will include all the customer ?
Customer  TotalOrders
4001      3
4002      1
4003      2
4004      0

A: Use a left join
Select c.Customer, COUNT(o.OrderID) as TotalOrders
from Customer c
left join Orders o
on c.Customer = o.Customer
Group by c.Customer

A: You will have to use a more complex left join in order to only count the Paid ones:
SELECT c.customerid, count(o.orderid) TotalOrders
FROM customer c
LEFT JOIN orders o
ON c.customerid = o.customer AND o.status = 'Paid'
GROUP BY c.customerid

Output:
| CUSTOMERID | TOTALORDERS |
|------------|-------------|
|       4001 |           3 |
|       4002 |           1 |
|       4003 |           2 |
|       4004 |           0 |

See the working fiddle here.

A: Select c.CustomerId, COUNT(o.OrderID) as TotalOrders
from Customer c
left join Orders o on c.CustomerId = o.Customer and o.[Status] = 'Paid'
Group by c.CustomerId

Try the above.


text:
Q: adding characters to a bash variable I got the following code:
color=`convert "${WPCURRENT}" -gravity east -crop 20%x100% -resize 1X1 -negate txt:- | tail -n1 |cut -d' ' -f4 | tr -d \#`

echo -n 'color = '$color''  > ~/.config/openbox/wallchange/color.txt
cat ~/.config/openbox/wallchange/color.txt

It outputs a hex color code
color = CC9ED2

Problem is that i require it to be like this:
color = 'CC9ED2',

How to do that? I already tried creating another variable and place the extra characters to no avail.

A: You can't put a single-quote in the single-quoted string. You can put it in a double-quoted string, and you should use double-quotes anyway, because variable references that aren't in double-quotes sometimes get parsed weirdly. So use this:
echo -n "color = '$color',"

Note that the double-quotes are shell syntax (telling the shell how to parse what's in them), but the single-quotes are just literal characters as far as the shell is concerned.
(You could also put the single-quotes in an unquoted section, and escape them with backslashes, like echo -n color = \'$color\',. But as I said, you want double-quotes for the variable, and you might as well use them on the single-quotes as well.)
But I have a couple of other recommendations: echo -n isn't portable, or even reliable. Some versions of echo just print "-n" literally as part of their output. I once had a bunch of my scripts break because an OS update changed echo's behavior, and suddenly they were printing "-n" rather than what they were supposed to do. To print things without a newline at the end, use printf instead of echo. Unfortunately, printf is more complicated to use correctly: its first argument is a "format string" that tells it how to print the rest of the arguments. Either of these would work:
printf '%s' "color = '$color',"
# or...
printf "color = '%s'," "$color"

I'd also recommend using $( ) instead of backticks to capture the output of a command (see BashFAQ #82):
color=$(convert "${WPCURRENT}" -gravity east -crop 20%x100% -resize 1X1 -negate txt:- | tail -n1 |cut -d' ' -f4 | tr -d \#)


text:
Q: Hyper-V Server Backup We are running a test install of Hyper-V Server 2008 (Stand Alone Free Version).
I was wondering if there is anyway to backup the VHD's using the command line as this is all you have.  I know you can use System Center Data Protection Manager but this costs a fortune.  We don't mind if they pause the VM's for a few minutes. :)
Any help would be great.
Thanks
Al

A: If you have Hyper-V Server 2008 R2 you can enable PowerShell (Link) and then use the PowerShell Management Library for Hyper-V available on codeplex.
The PowerShell library will allow you to script the pausing/shutdown of virtual machines before backing up the VHD files and restarting them automatically.  There are several commands in the library listed under, Backing up, exporting and snapshotting VMs.


text:
Q: Sequelize.js - column from junction table in "where" clause I have a project in Node.js using Sequelize as ORM.
I've created a Many-to-Many relationship and I need to make a query using some columns from the junction table in "where" clause.
I have the following models:
sequelize.define("User", {
    //some values
}, {
    "classMethods" : {
        "associate" : function (models) {
            User.hasMany(models.Book, { "through" : models.BorrowedBook });
        }
    }
});

sequelize.define("Book", {
    //some values
}, {
    "classMethods" : {
        "associate" : function (models) {
            Book.hasMany(models.User, { "through" : models.BorrowedBook });
        }
    }
});

sequelize.define("BorrowedBook", {
        //some other values
        "returnedAt" : DataTypes.DATE
    }
);

How can I use in "where" clause a column from "BorrowedBook"?
E.g. I want to get all users with books eagerly loaded that have at least 1 book and "BorrowedBook.returnedAt" is null.
Is there a way, something like this ?
db.Book
    .find({
        "include" : [
            db.User,
            { "model" : db.BorrowedBook, "where" : { "borrowedAt" : null } }
        ]
    })

A: You can't include the through model like that unless you have actually setup relations to the through model directly, but you still won't accomplish what you want.
The latest master of Sequelize should support something like:
db.Book.find({
  include: [
    {model: db.User, through: {
      where: {borrowedAt: null}
    }
  ]
})


text:
Q: Determine JDBC fetchSize on an a packaged based web application I have a particularly tricky situation here. I am supporting an java based packaged web application that runs on JBoss. The application is a packaged application so I don't really have access to any code or know how the code was developed.
What I am trying to find out is what the JDBC fetchSize is being set to.  I don't know where it is being set, meaning at the ResultSet level or Statement level etc..
Here is what I have tried so far:
1) I tried to configure tracing for the JDBC driver by downloading the ojdbc_g.jar file from Oracle and following the instructions that they provided.  Unfortunately, in those instructions, it states that I need to add this jar file to the CLASSPATH and I am not sure where that is being set in this application.  Needless to say, this path was not fruitful, as I was never able to successfully get a trace file output.
2)  I tried using WireShark to capture all TNS packets to see if I could find it out that way, and this again was fruitless because at that level, it is next to impossible to actually find how many rows are being passed each time.  There are so many other dependencies there, and I was unable to get the info I am after.
3)  The last thing I tried was configuring a database side trace of SQL Net calls to the database, but I am not sure whether I have to do this in the sqlnet.ora file or if I have to trace the listener.
This is where I am stuck now.  Again, all I want to do is find out what the application's JDBC fetchSize is being set (if its even being set at all).  I know that this can impact the performance of the application so that's why I want to find it.
Any guidance is appreciated.
Thanks.

A: unpack the jar file, try grepping for fetchSize in the class files, this will give you the class file. Then disassemble or decompile, or debug to see what it is set to.


text:
Q: Run single test data entry in Intellij in Spock Lets consider simple test case with some test data in Spock
def "numbers to the power of two"(int a, int b, int c) {
  expect:
      Math.pow(a, b) == c

  where:
      a | b | c
      1 | 2 | 1
      2 | 2 | 4
      3 | 2 | 9
  }

Is it possible with vanilla Intellij or with some plugin to run just single test data entry? For example just 1 | 2 | 1 without needing to comment out all others?

A: Is it possible with vanilla Intellij or with some plugin to run just single test data entry?
No


text:
Q: How can I find out the name of user who has asked the most questions on Stack Overflow I would like to know who has asked the most number of questions and how many they asked.

A: The Stack Exchange Data Explorer (SEDE) can answer such questions for you. Fortunately someone's already written such a query.
In fact quite a lot of people did so you can pick any of those queries that work for you and run them.
The query itself would look something like this...
SELECT
  u.Id, u.DisplayName, COUNT(*) AS NumPosts
FROM Posts p
  INNER JOIN Users u ON u.Id = p.OwnerUserId
WHERE
  p.PostTypeId = 1
GROUP BY U.Id, U.DisplayName
ORDER BY NumPosts DESC


text:
Q: Read k matrices size nxm from stdin in Python I need to read k matrices size nxm from stdin in Python.
In the first line there must be the number of matrices (k), and then - k descriptions of matrices: in the first line 2 integer numbers for size (n and m) devided by space, then the matrix.
Here's an example:
2
2 3
4 5 6
3 1 7
4 4
5 3 4 5
6 5 1 4
3 9 1 4
8 5 4 3

Could you please tell me how I can do this?
I could have done this only without considering m (for 1 matrix):
n = int(input())
a = []
for i in range(n):
    a.append([int(j) for j in input().split()])

I have found some similar questions but stdin is not used (e.g. reading from file is used) or the size of string in matrix is not set.

A: You are on a right way. try to break it in simple steps. Basically a  n X m  matrix is n rows and each row would have m elements (pretty obvious). what if we have n=1 then we have a line in which there would be m element. to take such input we would just
matrix = input().split()  #read the input
matrix = [ int(j) for j in matrix]   #matrix is now 1 x m list

or simplify this
matrix = [ int(j) for j in input().split() ]

now suppose we have n rows, that means we have to do this n times which is simply looping n times ,
matrix = [ [ int(j) for j in input().split() ] for i in n ]

a more pythonic way is using map,
matrix= [ list( map(int, input().split() ) ) for i in range(n) ]


text:
Q: HTML checkbox value is only return 'on' html
<FORM NAME="myForm" method="GET" action="{%url 'search_result'%}">
    Female<INPUT TYPE="checkbox" NAME="gender" ONCLICK="toggleShow(this)" value="F" id="0">

        <INPUT TYPE="checkbox" NAME="age" ONCLICK="toggleShow2(this)" vaule='10' id='10'>
        gender=10

            <INPUT TYPE="checkbox" NAME="category_name[]" value="c">
            1.c
            <INPUT TYPE="checkbox" NAME="category_name[]" value="a">
            2.a
            <INPUT TYPE="checkbox" NAME="category_name[]" value="d">
            3.d

    Male<INPUT TYPE="checkbox" NAME="gender" ONCLICK="toggleShow(this)" id='1' value='M'>

        <INPUT TYPE="checkbox" NAME="10">
        gender=10

         <input type="submit" value="search" id="search_button">
         </FORM>

css
    .subCats {
        display: none;
        margin-left: 20px;
    }

    .sub {
        display: none;
        margin-left: 20px;
    }

javascript
 function toggleShow(checkbox) {
        var id = 'subCats' + checkbox.id;
        var subCats =
            document.all ? document.all[id] :
                document.getElementById ? document.getElementById(id) :
                    null;
        if (subCats) {
            if (subCats.style.display == '' ||
                subCats.style.display == 'none')
                subCats.style.display = 'block';
            else
                subCats.style.display = 'none';
        }
    }
    function toggleShow2(checkbox) {
        var id = 'sub' + checkbox.id;
        var sub =
            document.all ? document.all[id] :
                document.getElementById ? document.getElementById(id) :
                    null;
        if (sub) {
            if (sub.style.display == '' ||
                sub.style.display == 'none')
                sub.style.display = 'block';
            else
                sub.style.display = 'none';
        }
    }

when click the submit,
gender and category_name[] return correct value.
for example, gender=F&age=on&category_name=b
But age value is only return 'on'. Even though set the value of the check box, only return 'on'.
what is problem..? Is the javascript code wrong?

A: It is a typo, the spelling of attribute 'value' is incorrect in age input and therefore the value for age tag is not specified.
Checkboxes uses 'on' as its default value when checked, that's why you are getting 'on' as value.
replace
<INPUT TYPE="checkbox" NAME="age" ONCLICK="toggleShow2(this)" vaule='10' id='10'>

with
<INPUT TYPE="checkbox" NAME="age" ONCLICK="toggleShow2(this)" value='10' id='10'>


text:
Q: How to access EF class properties from Service Layer I have an ASP.NET MVC3 in C# and Razor. The architecture of the application is divided in Data Access Layer (EF classes + Repository), Service Layer, Controller, ViewModels and View.
From my Service Layer ProductServices I call the method GetAllProducts exposed by my Repository ProductRepository , which has the following signature:
IQueryable<Products> GetAllProducts()

Therefore within ProductServices I call (productRepository is an instance of ProductRepository):
var products = productRepository.GetAllProducts();

that populates the variable products. Now I would like to access the name of the product ProductName from productServices. If I use this instruction:
var productNames = products.Select(m => m.ProductName).ToList();

I am creating coupling between ServiceLayer and the EF (bypassing the repository). That means I must add to ProductRepository a method with signature:
IQueryable<string> GetAllProductsName()

However, since I need other product information in my application, shall I create one method in productRepository for each field of the Product class? Is my reasoning correct? Thanks

A: Theres two schools of thought around this,

*

*A repository explicitly defines the way you interact with the database and should be tightly controlled. Therefore methods on the repository should provide enumerated data

*The repository breaks the strong coupling to a specific datasource type but does not need to provide detailed and enumerated datasets.

Personally i subscribe to the second, heres why:
my feeling is that when you get overly explicit within the repository it turns into business logic rather than a decoupling mechanism. I don't really like this as it means that you become more tightly linked to the repository implementation.
I also think that in some cases the repository isnt the right place to enumerate the data, for example I believe paging and sorting is a UI concern, however for performance you want queries to only relate to the current page/sort. this means you either need to let the UI contribute to the query compilation or the repository needs to understand paging and sorting.
Having said that providing un-enumerated datasources does open you up for issues later down the track, and even if you do provide them its very important to enumerate the set as soon as possible.
If you're interested heres my take on the repositories: http://blog.staticvoid.co.nz/2011/10/staticvoid-repository-pattern-nuget.html , all the code is also on github

A: You have all information in your productServices because you load all information from your Repository with the method productRepository.GetAllProducts(). If you need more information from an other entity then you need to extend your productServices with a new Service.

However, since I need other product information in my application,
  shall I create one method in productRepository for each field of the
  Product class? Is my reasoning correct? Thanks

In this situation normally I create Extensions method's for the service and not in the repository. The Repository have normally a CRUD Setup and nothing more.


text:
Q: Selecting a class within a used defs/symbol I'm trying to alter the colours of a multi-element defs, based on the enclosing CSS class. So far I've had zero success. I started out using a symbol, then changed it to a defs with a g in it.
I've put together an example codepen: addressing a class within a defs The square on the right should be green on top and yellow on the bottom.

.rect1 { fill: red; }
.rect2 { fill: yellow; }
.morph .rect1 { fill: green; }

rect { stroke: black; }
svg { background-color: lightblue; }
<svg viewBox="0 0 100 100">
  <defs>
    <g id="house-def">
      <rect class="rect1" x="10" y="10" width="20" height="10" />
      <rect class="rect2" x="10" y="20" width="20" height="10" />
    </g>
  </defs>
  <use xlink:href="#house-def" />
  <use xlink:href="#house-def" class="morph" transform="translate(30)" />

</svg>

Is this even possible?
Thanks for your help.

A: Instead of trying to change the color of the rect1 change the fill of the use elements:

use{ fill: red; }/*will fill red both use elements*/
.rect2 { fill: yellow; }/*will fill yellow the .rect2 inside defs*/
.morph { fill: green; }/*will fill green the second use element overwritting the fill:red from the first roule.*/

rect { stroke: black; }
svg { background-color: lightblue; }
<svg viewBox="0 0 100 100">
  <defs>
    <g id="house-def">
      <rect class="rect1" x="10" y="10" width="20" height="10" />
      <rect class="rect2" x="10" y="20" width="20" height="10" />
    </g>
  </defs>
  <use class="a" xlink:href="#house-def" />
  <use xlink:href="#house-def" class="morph" transform="translate(30)" />

</svg>


text:
Q: Already available Test cases for Android Is there any open source test cases codes available for android junit. Like, test cases for android media player, content providers etc? I have searched through Google and cannot find related links. I'm testing using my test cases now but I want to know whether test cases are already available. Planning to reuse those as well.

A: If you want the platform's unit tests or the CTS (Compatibility Test Suite), download android source code from AOSP, they are included. Unless you are trying to modify the platform though, those won't be to useful. No one can really create reusable tests for an app you are writing.


text:
Q: How to get specific stub on multiple matching URL with different queryParameter I have 2 WireMock mappings JSON files with same URL. In the first mapping JSON file, I only have a xDate as query parameter. In the 2nd mapping JSON file, I have the xDate and yType as query parameters.
How do I make the stub such that when I hit the URL with the 2 parameters, it will get the correct mapping/file information.
1st mapping json file:
"request" : {
    "customMatcher" : {
      "name" : "is-today",
      "parameters" : {
        "queryParamName" : "xDate",
        "dateFormat": "yyyy-MM-dd"
      }
    },
    "urlPathPattern" : "/myUrl",
    "method" : "GET"
  },
  "response" : {
    "status" : 200,
    "bodyFileName" : "body1.json",
    "headers" : {
      "Server" : "Apache-Coyote/1.1",
      "Content-Type" : "application/json"
    }
  }

2nd mapping json:
"request" : {
    "customMatcher" : {
      "name" : "is-today",
      "parameters" : {
        "queryParamName" : "xDate",
        "dateFormat": "yyyy-MM-dd"
      }
    },
    "queryParameters":{
      "yType" : {
        "equalTo": "Value"
      }
    },
    "urlPathPattern" : "/myUrl",
    "method" : "GET"
  },
  "response" : {
    "status" : 200,
    "bodyFileName" : "body2.json",
    "headers" : {
      "Server" : "Apache-Coyote/1.1",
      "Content-Type" : "application/json"
    }
  }

When I was testing it, it always hits the 1st mapping JSON. When I tried to hit the URL with 2 input parameters, it always go to the 1st mapping.
Tried putting the "priority" value on 1st and 2nd mapping file but somehow, its not working properly for me.


text:
Q: Is it advisable to install Ubuntu on btrfs or ext4? I used to install ubuntu on ext4 but I heard about btrfs. Is it advisable to use it for Ubuntu installation? What are the pros and cons?

A: What you want to use is a pure personal decision.
Basically btfrs is a filesystem where features ("Copy on Write" almost instant snapshots, subvolumes, and many many more) are more important than performance. 1 of the badass features is the snapshots: want to upgrade? Make a snapshot and if the upgrade kills you machine you are up and running on the old version within seconds.
So if you want a filesystem you can tinker with, do not care about performance (yet) and do not mind having to use the command line feel free to use btfrs.


text:
Q: What are the Yesod system requirements? I'm currently looking for a VPS to deploy a Yesod site on, I was wondering what the system requirements are for running Yesod? I will be using Nginx with Warp as the system configuration.

A: There are no hard-and-fast rules here, but I comfortably run about 5 Yesod-powered sites with Nginx and PostgreSQL and a micro EC2 instance (micro being the instance size, not a random adjective).

A: I had a VPS and I had trouble with the glibc version, mainly because a lot of hosting companies are quite conservative and don't offer the latest and greatest versions of the common Linux distributions. GHC won't work with older versions of glibc, although I haven't found anywhere an exact definition of how old is too old.
So one system requirement is: a recent Linux that doesn't have an ancient version of glibc.

A: I currently run one yesod app on Debian Lenny on VDS, with 500MHz CPU and 196Mb RAM. I do not compile app on the VDS, instead I upload compiled binary. It only needs recent libgmp, but I put one (libgmp*.so) from my desktop to the same directory as application and run
LD_LIBRARY_PATH=. ./my-yesod-app


text:
Q: Is it possible to clone an IEnumerable instance, saving a copy of the iteration state? I'd like to create a copy of an IEnumerator<T> so that I can restart the enumeration process from a particular location in the collection.  Clearly, there is no benefit to doing so for collections that implement IList, since we can remember the index of interest.
Is there a clever way to accomplish this task using a combination of yield statements and Linq functions?  I could not find a suitable Clone() method to copy the enumerator, and would like to avoid using Enumerable.Skip() to reposition a new enumerator to the desired resumption point.
Also, I'd like to keep the solutions as generic as possible, and not have to depend on state from any concrete collections.

A: The best you could do is write something that keeps a buffer (perhaps a Queue<T>) of the data consumed from one and not the other (which would get messy/expensive if you advanced one iterator by 1M positions, but left the other alone). I really think you would be better off rethinking the design, though, and just using GetEnumerator() (i.e. another foreach) to start again - or buffer the data (if short) in a list/array/whatever.
Nothing elegant built in.

Update: perhaps an interesting alternative design here is "PushLINQ"; rather than clone the iterator, it allows multiple "things" to consume the same data-feed at the same time.
In this example (lifted from Jon's page) we calculate multiple aggregates in parallel:
// Create the data source to watch
DataProducer<Voter> voters = new DataProducer<Voter>();

// Add the aggregators
IFuture<int> total = voters.Count();
IFuture<int> adults = voters.Count(voter => voter.Age >= 18);
IFuture<int> children = voters.Where(voter => voter.Age < 18).Count();
IFuture<int> youngest = voters.Min(voter => voter.Age);
IFuture<int> oldest = voters.Select(voter => voter.Age).Max();

// Push all the data through
voters.ProduceAndEnd(Voter.AllVoters());

// Write out the results
Console.WriteLine("Total voters: {0}", total.Value);
Console.WriteLine("Adult voters: {0}", adults.Value);
Console.WriteLine("Child voters: {0}", children.Value);
Console.WriteLine("Youngest vote age: {0}", youngest.Value);
Console.WriteLine("Oldest voter age: {0}", oldest.Value);

A: There's no general way to do this, since an iEnumerable may depend upon arbitrary aspects of system state which cannot be detected via Reflection or any other means.  For example, a PaperTapeReader class might implement an enumerator which reads characters from the tape until the sensor indicates there's no more tape in the machine.  The state of such an enumerator would be the physical location of the tape, which might be impossible to restore programmatically.
Given an iEnumerable, it would be possible to produce two or more iEnumerables, each of which would act like either the original or clone thereof.  MoveNext requests for the one that was 'furthest along' would read new data from the original iEnumerable and buffer it for the others.  Unless the original iEnumerable supports such 'hook' functionality, however, I don't think there'd be any way to latch onto its data as it comes in.

A: This is completely not an answer, but the thought experiment I found interesting...if you've got a yield-based IEnumerable, I suppose you know it's all compiler-generated magic. If you have such a beast, you could do something like this... ;)
class Program
{
    static void Main(string[] args)
    {
        var bar = new Program().Foo();

        // Get a hook to the underlying compiler generated class
        var barType = bar.GetType().UnderlyingSystemType;
        var barCtor = barType.GetConstructor(new Type[] {typeof (Int32)});
        var res = barCtor.Invoke(new object[] {-2}) as IEnumerable<int>;

        // Get our enumerator
        var resEnum = res.GetEnumerator();
        resEnum.MoveNext();
        resEnum.MoveNext();
        Debug.Assert(resEnum.Current == 1);

        // Extract and save our state
        var nonPublicMap = new Dictionary<FieldInfo, object>();
        var publicMap = new Dictionary<FieldInfo, object>();
        var nonpublicfields = resEnum.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
        var publicfields = resEnum.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach(var field in nonpublicfields)
        {
            var value = field.GetValue(resEnum);
            nonPublicMap[field] = value;
        }
        foreach (var field in publicfields)
        {
            var value = field.GetValue(resEnum);
            publicMap[field] = value;
        }

        // Move about
        resEnum.MoveNext();
        resEnum.MoveNext();
        resEnum.MoveNext();
        resEnum.MoveNext();
        Debug.Assert(resEnum.Current == 5);

        // Restore state
        foreach (var kvp in nonPublicMap)
        {
            kvp.Key.SetValue(resEnum, kvp.Value);
        }
        foreach (var kvp in publicMap)
        {
            kvp.Key.SetValue(resEnum, kvp.Value);
        }

        // Move about
        resEnum.MoveNext();
        resEnum.MoveNext();
        Debug.Assert(resEnum.Current == 3);
    }

    public IEnumerable<int> Foo()
    {
        for (int i = 0; i < 10; i++)
        {
            yield return i;
        }
        yield break;
    }

}

A: Do you want to be able to save the state, continue the enumeration, then return to the saved state, or do you want to simply be able to enumerate, do some other stuff, then continue the enumeration?
If it's the latter, something like the following might work:
public class SaveableEnumerable<T> : IEnumerable<T>, IDisposable
{
    public class SaveableEnumerator : IEnumerator<T>
    {
        private IEnumerator<T> enumerator;

        internal SaveableEnumerator(IEnumerator<T> enumerator)
        {
            this.enumerator = enumerator;
        }

        public void Dispose() { }

        internal void ActuallyDispose()
        {
            enumerator.Dispose();
        }

        public bool MoveNext()
        {
            return enumerator.MoveNext();
        }

        public void Reset()
        {
            enumerator.Reset();
        }

        public T Current
        {
            get { return enumerator.Current; }
        }

        object IEnumerator.Current
        {
            get { return enumerator.Current; }
        }
    }

    private SaveableEnumerator enumerator;

    public SaveableEnumerable(IEnumerable<T> enumerable)
    {
        this.enumerator = new SaveableEnumerator(enumerable.GetEnumerator());
    }

    public IEnumerator<T> GetEnumerator()
    {
        return enumerator;
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return enumerator;
    }

    public void Dispose()
    {
        enumerator.ActuallyDispose();
    }
}

Now you can do:
using (IEnumerable<int> counter = new SaveableEnumerable<int>(CountableEnumerable()))
{
    foreach (int i in counter)
    {
        Console.WriteLine(i);
        if (i > 10)
        {
            break;
        }
    }
    DoSomeStuff();
    foreach (int i in counter)
    {
        Console.WriteLine(i);
        if (i > 20)
        {
            break;
        }
    }
}

A: JerKimball had an interesting approach.  I try to take it to the next level.  This uses reflection to create a new instance and then sets the values on the new instance.   I also found this chapter from C# in Depth to be very useful.
Iterator block implementation details: auto-generated state machines
static void Main()
{
    var counter = new CountingClass();
    var firstIterator = counter.CountingEnumerator();
    Console.WriteLine("First list");
    firstIterator.MoveNext();
    Console.WriteLine(firstIterator.Current);

    Console.WriteLine("First list cloned");
    var secondIterator = EnumeratorCloner.Clone(firstIterator);

    Console.WriteLine("Second list");
    secondIterator.MoveNext();
    Console.WriteLine(secondIterator.Current);
    secondIterator.MoveNext();
    Console.WriteLine(secondIterator.Current);
    secondIterator.MoveNext();
    Console.WriteLine(secondIterator.Current);

    Console.WriteLine("First list");
    firstIterator.MoveNext();
    Console.WriteLine(firstIterator.Current);
    firstIterator.MoveNext();
    Console.WriteLine(firstIterator.Current);
}

public class CountingClass
{
    public IEnumerator<int> CountingEnumerator()
    {
        int i = 1;
        while (true)
        {
            yield return i;
            i++;
        }
    }
}

public static class EnumeratorCloner
{
    public static T Clone<T>(T source) where T : class, IEnumerator
    {
        var sourceType = source.GetType().UnderlyingSystemType;
        var sourceTypeConstructor = sourceType.GetConstructor(new Type[] { typeof(Int32) });
        var newInstance = sourceTypeConstructor.Invoke(new object[] { -2 }) as T;

        var nonPublicFields = source.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
        var publicFields = source.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
        foreach (var field in nonPublicFields)
        {
            var value = field.GetValue(source);
            field.SetValue(newInstance, value);
        }
        foreach (var field in publicFields)
        {
            var value = field.GetValue(source);
            field.SetValue(newInstance, value);
        }
        return newInstance;
    }
}

A: So what you really want is to be able to resume an iteration later, am I correct?  And cloning the enumerator or collection is how you think you'd do such a thing?
You could make a class which wraps an IEnumerable, and exposes a custom enumerator which, internally, clones the inner IEnumerable, and then enumerates over that.  Then, using GetEnumerator() would give you an enumerator which could be passed around.
This would create an extra copy of the IEnumerable for each Enumerator "in flight," but I think it would meet your needs.


text:
Q: Converting Obj-C print statement to Swift's native "\variable name" syntax I want to convert these two Obj-C statements to Swift. I'm not sure about the syntax since there are multiple object percent signs. I have converted most of the code except for the print strings with percent signs.
I want to use Swift's native print ("\variable") syntax.

self.validFrames.text = [NSString stringWithFormat:@"Valid Frames: %d%%", MIN(100, (100 * self.validFrameCounter)/MIN_FRAMES_FOR_FILTER_TO_SETTLE)];

validFrames.text = String.localizedStringWithFormat("Valid Frames: \min%%"(100, (100 * validFrameCounter) / minFramesForFilterToSettle))

self.rate.text=[NSString stringWithFormat:@"%0.0f", beat];

rate.text = String.localizedStringWithFormat("\beat 0.0f")
Please correct my Swift syntax.

A: *

*The interpolation syntax is \(expression):
let validFramesPercentage = MIN(100, (100 * self.validFrameCounter)/MIN_FRAMES_FOR_FILTER_TO_SETTLE)
self.validFrames.text = "Valid Frames: \(validFramesPercentage)%"

*You don't have any control over how Swift formats a float if you use interpolation syntax. Example:
let beat = Float(10.0/3)
self.rate.text = "\(beat)"
// text is 3.33333; you can't specify the number of digits

*If you want to use localized strings, you can't use \(...) interpolation. To perform interpolation, the compiler has to examine the string. Localized strings are loaded from a data file at runtime. The compiler doesn't look at them.

*Using format strings in Swift is 100% ok. They are part of the library, just like UIView (or NSView).

A: I'm afraid you cannot achieve the result you want using interpolation sintax.
You should use for Float:
var text = String.localizedStringWithFormat("%0.0f", 2.0) // result: 2

And for Int:
var text = String.localizedStringWithFormat("%d%%", 10) // result 10%