text:
Q: fix vertical scrollbar position to 2nd row in div(cshtml)? I have a div with a scroll bar which displays 15 months with 3 of the min each row, When the page loads I want to fix the scroll bar position to 2nd row as shown in my screenshot.As in the scroll bar should to be fixed to the position shown in my screenshot as opposed to top of the div.The reason for this requirement is we are displaying previous 3 months, but the user should see the current month when the page loads. I hope I have made it clear
I am using
<div id="key_dates" style ="overflow:scroll;width:960px;height:500px">

Can you guys please help?
Thanks,
Adarsh

A: You need to use JavaScript for this:
<!--
     Place this script before closing </body> tag so that
     DOM (HTML elements tree) is already built when the script is running
-->
<script>
// create a closure to not pollute global scope
!function () {
  // cache reference to keyDates element
  var keyDates = document.getElementById('key_dates');
  // set scroll to the height of one row
  keyDates.scrollTop = 150; // substitute `150` with height of one row
} ();
<script>

Here is the documentation of element.scrollTop
If you are using jQuery, you do it like this (and here are the docs);
<script>
$('#key_dates').scrollTop( 150 );
</script>

An example with jQuery: http://jsfiddle.net/gryzzly/CjdwX/

A: It seems I can't demonstrate this properly with jsfiddle, but here is a sample of code which works if you test it in a browser. Using anchors on each row, we can anchor the window to a specified location either using href or the url.
For example, if you implemented this code at www.address.tld/calendar, to show row two, you'd enter www.address.tld/calendar#row2.
You can use only an anchor on row two, and you could place it either statically or programmatically depending on your needs. It's a pretty straight forward solution, but some people don't like the hash and anchor name being in the url. It doesn't bother me.


text:
Q: Изменить background пунктов меню при переходе на внутреннюю страницу Есть пункты меню в heder, они имеют прозрачный background. При переходе на внутреннюю страницу надо поменять background этих пунктов меню но только на определённой внутренней странице(не на всех страницах). Подскажите, пжл., как это можно сделать на чистом css? Как-то находил решение, где используется "#страница_о_нас.html" в файле style.css для изменения стили блока для страницы "#страница_о_нас.html".
https://jsfiddle.net/4m7y0a3y/4/

A: В css есть псевдокласс :target. Работает он так. На на странице у вас есть элемент с неким id. Допустим такой код в index.html:
Show me

Text

И такой css:
#someid {
   color: red;
}
#someid:target {
   color: green;
}

При нажатии на ссылку, вы будете перемещены на ту же самую страницу, в то ее место где находится
Text
. При этом сам текст, ранее бывший красным, станет зеленым, а в адресной строке браузера будет значится index.html#someid.
В целом можно сделать рабочий вариант того что вы хотите, но побочные эффекты - скачки по странице и ее перезагрузка убивают все преимущества простоты css.
Предлагаю подумать над решением на js, либо php.

redpajama_set_name: RedPajamaStackExchange


text:
Q: php regex to separate out characters stuck to left, right or in the middle Looking for a php regex that will allow me to separate out certain characters from words (if they're sticking to the left or right of the word, or even anywhere within the word).
For example,
hello. -> hello .
.hello -> . hello
hello.hello -> hello . hello

I have the below code but it won't work for all cases. Please note that $value could be '.', '?', or any character.
$regex = "/(?<=\S)\\" . $value . "|\\" . $value . "(?=\S)/";
$this->str = preg_replace_callback($regex, function($word) {
    return ' ' . $word[0];
}, $this->str);

Also, please help with specifying the part where I can turn on (or off) the 3rd condition.
[UPDATE]
I think there might be confusion about exact requirements. Let me try to be more specific. I want a regex which will help me seperate out certain characters which are either at the end or the beginning of a group of text. What is group of text? Group of text could be any length (>=1) and contain any characters however it must begin with a-z or 0-9. Again, would be nice if this aspect would be highlighted in solution so that if we want group of text to begin&end with more characters (not just a-z or 0-9) it's possible.
$character = '.', string is ".hello.world." => ". hello.world ."
$character = '.', string is ".1ello.worl2." => ". 1ello.worl2 ."
$character = '.', string is ".?1ello.worl2." => ".?1ello.worl2 ."
$character = '.', string is "4/5.5" => "4/5.5"
$character = '.', string is "4.?1+/5" => "4.?1+/5"
$character = '.', string is ".4/5.5." => ". 4/5.5 ."
$character = '/', string is ".hello?.world/" => ".hello?.world /"
$character = '/', string is ".hello?.worl9/" => ".hello?.worl9 /"

Hope, its more clear now.

A: You can use 3 alternatives each captured into its own capture group, and use a preg_replace_callback to apply the corresponding replacement:
$wrd = ".";
$re = '~(?<=\S)(' . preg_quote($wrd) . ')(?=\S)|(?<=\S)(' . preg_quote($wrd) . ')|(' . preg_quote($wrd) . ')(?=\S)~';
$str = "hello.\n.hello\nhello.hello";
$result = preg_replace_callback($re, function($m) {
    if (!empty($m[1])) {
        return " " . $m[1] . " ";
    } else if (!empty($m[2])) {
        return " " . $m[2];
    } else return $m[3] . " ";
}, $str);
echo $result;

See the IDEONE demo
The regex will be
(?<=\S)(\.)(?=\S)|(?<=\S)(\.)|(\.)(?=\S)
       | 1|             | 2|  | 3|

See regex demo
The first group is your Case 3 (hello.hello -> hello . hello), the second group is your Case 1 (hello. -> hello .) and the third group singals your Case 2 (.hello -> . hello).
UPDATE (handling exceptions)
If you have exceptions, you can add more capturing groups. E.g., you want to protect the dot in float numbers. Add a (\d\.\d) alternative, and check inside the callback function if it is not empty. If not, just restore it with return $m[n]:
$wrd = ".";
$re = '~(\d\.\d)|(?<=\S)(' . preg_quote($wrd) . ')(?=\S)|(?<=\S)(' . preg_quote($wrd) . ')|(' . preg_quote($wrd) . ')(?=\S)~';
$str = "hello.\n.hello\nhello.hello\nhello. 3.5/5\nhello.3\na./b";
$result = preg_replace_callback($re, function($m) {
    if ( !empty($m[1])) {         // The dot as a decimal separator
        return $m[1];             // No space is inserted
    }
    else if (!empty($m[2])) {     // A special char is enclosed with non-spaces
        return " " . $m[2] . " "; // Add spaces around
    } else if (!empty($m[3])) {   // A special char is enclosed with non-spaces
        return " " . $m[3];       // Add a space before the special char
    } else return $m[4] . " ";    // A special char is followed with a non-space, add a space on the right
}, $str);
echo $result;

See an updated code demo
Another code demo - based on matching locations before and after the . that are not enclosed with spaces (and protecting a float value) (based on @bobblebubble's solution (deleted)):
$wrd = ".";
$re = '~(\d\.\d)|(?<!\s)(?=' . preg_quote($wrd) . ')|(?<=' . preg_quote($wrd) . ')(?!\s)~';
$str = "hello.\n.hello\nhello.hello\nhello. 3.5/5\nhello.3\na./b";
$result = preg_replace_callback($re, function($m) {
    if ( !empty($m[1])) {         // The dot as a decimal separator
        return $m[1];             // No space is inserted
    }
    else return " ";   // Just insert a space
}, $str);
echo $result;

SUMMARY:

*

*You cannot use \b since your . / ? etc. can appear in mixed "word" and "non-word" contexts

*You need to use capturing and preg_replace_callback since there are different replacement schemes

A: From what I understand the . can be any non-word character. If that's the case, try this:
$patron = '/(\W+)/';
$this->str = trim(preg_replace($patron, ' $1 ', $this->str));

A: (\s?[.]\s?)
If you use the above regex, you can simply replace all the matches with " . "
How it works:
I used \s? to capture a leading and trailing whitespace, if there is any.
[.] is a char class, so you should add all of the "certain characters" you want to find.

A regex that catches the first 2 conditions and never the third is (\s[.]\s?|\s?[.]\s). (Again, you'll need to replace the capture with  " . ", and also add your "certain characters" to the char classes.)
You can then choose which regex you will use.

A: You can use a regex based on word boundaries.
\b(?=\.(?!\S))|(?<=(?<!\S)\.)\b

Would match the boundary (zero-width) between a word and a literal dot if not followed by a non-whitespace \S or not preceded by a non-whitespace using lookarounds to check.
See demo at regex101. Use in a PHP function with value parameter and replace with space.
// $v = character
function my_func($str, $v=".")
{
  $v = preg_quote($v, '/');
  return preg_replace('/\b(?='.$v.'(?!\S))|(?<=(?<!\S)'.$v.')\b/', " ", $str);
}

PHP demo at eval.in


text:
Q: How Do I access header information in an array First off I am new to PowerShell and have written code in many different languages. Most of my experience was from java so typically I format my code from that background so I apologize it if it looks crazy.
I am trying to make a script that I can run against a CSV that will load each of the objects into an array. I want to then check each object to make sure it has an e-mail address, Firstname, and Lastname attached to it. We are currently deleting invalid entries by hand.
I have the following code below that I am working with. I am attempting to import the CSV. I want to read each element in the array and remove the entries that are not meeting my criteria, I then want to export that to a CSV.  I am confused on what the objects look like in the array, how to check if the information in each object is null. Any assistance on logic would be nice. The CSV has the headers listed below, but I only care about the onces listed above. Thanks,
'
    $csv = Read-Host "enter file path to CSV"
$CsvArray = Import-Csv $csv -Header Lastname,Firstname,Department,Phonenumber,Email

  foreach ($i in $CsvArray)
   {
     Write-Host $CsvArray($i)

  if(Lastname -eq $NULL) -or (firstname -eq $NULL) -or (Email -eq $NULL)
     {
       Delete $i from array
      }
  else
     {
     $i
     }
 }

 $csvArray | Export-Csv c:\emaillist.txt -force

 Write-Host "Press any key to continue ..."

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

`

A: $CsvArray = Import-Csv $csv -Header Lastname,Firstname,Department,Phonenumber,Email |
Where-Object { $_.Lastname -ne $null -and $_.Firstname -ne $null -and $Email -ne $null } |
Export-Csv C:\emaillist.txt -force


text:
Q: How to store multiple form data values to a single key in local storage I have an html form when i submit the form the values are get stored in local storage but what i would like to do is whenever the form is submitted it should store the values in the same local storage but what happens is when i try to do the above approach it takes the last submitted value can anyone tell me how could i use the local storage to use the same key for multiple values.
function addToCSVFile() {
    // Collecting the names
    var name = document.getElementById('firstName').value;
    var middlename = document.getElementById('middleName').value;
    var lastname = document.getElementById('lastName').value;
    var data = {name: name, middlename: middlename, lastName: lastname};
    console.log('Data is', data);
    // alldata.push(data);
    localStorage.setItem('Data', JSON.stringify(data));
    clearData();
    alert("Data Added Successfully", JSON.stringify(data));

}

A: Use an array and push new values to the array.
The sequence would be something like:
var array = JSON.parse(localStorage.getItem('Data') || '[]');
array.push(dataObject);
localStorage.setItem('Data', JSON.stringify(array));


text:
Q: What is the downside of using SQL alongside BQL in Acumatica I have a very specific user request I have been working on. The end goal is to change a user defined field on FSServiceOrder, FSSODet, FSAppointment, FSAppointmentDet based upon inventory availability in INLocationStatus.
I have a processing screen for this, since it needs to run on demand, or on a schedule. Note: the user never really interacts with anything on the processing screen. He will always simply click: "Process All"
Using BQL for this seems to be working against the grain.
Using a Join in my Processing event:
    public PXProcessingJoin<INLocationStatus,
         LeftJoin<InventoryItem, On<INLocationStatus.inventoryID,
         Equal<InventoryItem.inventoryID>>>>   Processing;

Isn't very helpful as a starting place.
I cannot even get the value from the joined table without running a separate BQL inside of the processing event. (If I understand correctly. I found no way of doing it, and this SO seems to indicate that it is not possible.)
So I have to run a BQL inside of my processing Delegate, just to get the inventory information. I have to also do several BQLs as I process each of my DACs -- and I have to create several PXGraphs as well.
This seems like a LOT of overhead -- when all I am really doing is reading data into a memory cache, processing it, and then setting a user defined field.
I understand that the value in using BQL is it ensures all of the business logic is performed, but in my case, that doesn't apply. There is no business logic that needs to be run, that I can determine. I am simply running through rows of data, calculating my own available inventory value in memory, and then setting a usr defined flag in the database.
Wouldn't I be better off just calling to SQL directly, getting my data, and then updating the flags? If I do that, does it cause issues I am not considering? Or does it create huge problems down the road?
Has anyone else mixed BQL and SQL in a processing screen?

A: Mark,
If you are confident that updating your user defined fields will not trigger unintended consequences, then I wouldn't worry about it. If you need to get your code certified by Acumatica however they will not support it. I think the only unintended consequence by updating the database directly will be that it will not notify the application cache that a change has been made (Unless the PXDatabase functions do that and I just didn't realize) and another user might get a "Another processes has updated the ... record" error when they try to edit the same record.

A: Acumatica uses timestamps to verify caches before persisting them to the Database. Why not use Linq queries to get the data, set them against the graph and let the standard persisting methods handle them by using the Save.PressButton?
I have tried to update the tables before, but then when going into the screen to load the data got the error the "Another process has update the PX...".
I know it seems like a lot of work, but I would rather do that than sit hours trying to fix time stamps again.


text:
Q: Failed to resolve: support-fragment error when add google architecture component dependency I want to use Google architecture components in my app, but after updating android studio to version 3.1.1 when I add android.arch.lifecycle:extensions:1.1.1 dependency into app.gradle file, it will show Failed to resolve: support-fragment
My gradle version is 4.4

This is app gardle:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "ir.apptori.myapplication"
        minSdkVersion 17
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
 "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    implementation "android.arch.lifecycle:extensions:1.1.1"
}

Please guid me how to fix it, Thanks

A: I had a similar error and changing the repositories order so that google() comes before jcenter() fixed it.
I had to change the order for the repositories within buildscript and allprojects in the top level build.gradle file.
Please see this commit:
https://github.com/kunadawa/ud851-Exercises/commit/9f6720ef4d52c71b206ddaa8477f2cf6e77a66f4

A: I also had to remove the maven url from the project build.gradle as in:
 buildscript {
        repositories {
            google()
            jcenter()
          //  maven { url 'https://maven.google.com' }
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.1.3'

        }
    }

    allprojects {
        repositories {
            google()
            jcenter()
        }
    }

This now works for me.

A: add these two to   build.gradle -> repositories
{
mavenCentral()
google()
}

and add to these are to allprojects
allprojects {
repositories {
mavenCentral()
google()
}
}

A: i add this line in build.gradle and fixed bug :
implementation 'androidx.fragment:fragment:1.2.5'

A: This just happened to me with a project I cloned from github.
I updated my SDK and buildtools and had to double check all the dependencies to match the buildToolsVersion and the compileSdkVersion from the project.
The error message wasn't very clear when I tried to sync the project, it only gave me a more explicit error when I tried to run and it failed.
Could not find support-fragment.jar (com.android.support:support-fragment:27.0.2).
Good Luck!

A: for a similar issue its solved by changing material implementation from alpha2 version to alpha 7 in the app build.gradle file
implementation 'com.google.android.material:material:1.1.0-alpha07'


text:
Q: Mercurial repository and files with strange names I have a mercurial repository, and inside it a file that ends with '>>'.  When doing a hg clone from this windows repository, I get the following error:
abort: The filename, directory name, or volume label syntax is incorrect: C:\Users\Path\To\Repos/More/Path/file>>
Is there a way to fix it?  It seems to do with the '>>' being confused for a redirect, although I'm also unsure of why it switched from using \ to /.

A: The problem is that on Windows, a filename can't contain the > symbol.  You should probably try and find the push to the repository that added the file in question and do a partial rollback to get rid of that file.  Then, never name a file that way again :)
EDIT:  You might try performing a pull from a Linux machine or VM if you have it, and then renaming the file without the weird characters, then commit and push back to the repository.  I'm not sure if you tried that already.


text:
Q: Extracting data from multi-line blocks of text to generate one line each using UNIX tools I'm trying to extract specific parts of a file such as below:
name = "Account - UU ",
source = "1-account",
destination = "account-manager12",
other = 111111

name = "Account - PP,
source = "2-account",
destination = "account-manager1234",
other = 1212

name = "Account - GG ",
source = "3-account",
destination = "account-manager12345",
other = 44444

name = "Account - QQ,
source = "4-account",
destination = "account-manager123456"
other = 23232323

my expected output is
  name = "Account - UU" | source = "1-account" | destination = "account-manager12"
  name = "Account - PP" | source = "2-account" | destination = "account-manager1234"
  name = "Account - GG" | source = "3-account" | destination = "account-manager12345"
  name = "Account - QQ" | source = "4-account" | destination = "account-manager123456"

Is there any way i can achieve the same using grep/awk commands ? I really appreciate any suggestion. Thanks.

A: See this running at https://ideone.com/0O8t3U:
#!/usr/bin/env bash

shopt -s extglob  # enable extended globbing, of which @(one|two|three) is an example

output=""
while IFS= read -r line; do
  case $line in
    @(name|source|destination)" = "*)  # "name = " or "source = " or "destination = "
      output+="${line%,} | " ;;        # strip trailing comma before appending to output
    "")                                # matches only an empty line
      printf '%s\n' "${output%' | '}"  # print our output, without the last " | "
      output=""                        # ...then reset that output to empty
      ;;
  esac
done
# finally, print anything that didn't have a blank line after it (last block of input)
[[ $output ]] && printf '%s\n' "${output% | }"

A: If we don't really have to deal with missing quotes and trailing blanks in $1:
$ awk -v RS= -F',?\n' -v OFS=' | ' '{print $1, $2, $3}' file
name = "Account - UU " | source = "1-account" | destination = "account-manager12"
name = "Account - PP | source = "2-account" | destination = "account-manager1234"
name = "Account - GG " | source = "3-account" | destination = "account-manager12345"
name = "Account - QQ | source = "4-account" | destination = "account-manager123456"

or if we do:
$ awk -v RS= -F',?\n' -v OFS=' | ' '{gsub(/^"? *| *"?$/,"\"",$1); print $1, $2, $3}' file
"name = "Account - UU" | source = "1-account" | destination = "account-manager12"
"name = "Account - PP" | source = "2-account" | destination = "account-manager1234"
"name = "Account - GG" | source = "3-account" | destination = "account-manager12345"
"name = "Account - QQ" | source = "4-account" | destination = "account-manager123456"

A: Could you please try following, written and tested with shown samples in GNU awk.
awk '
BEGIN{
  OFS=" | "
}
/^ +name/{
  if(val){
    print val
    val=""
  }
  found=1
}
found{
  val=(val?val OFS:"")$0
}
/^ +other/{
  found=""
}
END{
  if(val){
    print val
  }
}'  Input_file

A: Use a combination of two Perl one-liners and paste:
perl -lne 'print for /^\s*((?:name|source|destination)\s*=\s*[^,]*)/' input_file | paste - - - | perl -pe 's/\t/ | /g'

The Perl one-liners use these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-p : Loop over the input one line at a time, assigning it to $_ by default. Add print $_ after each loop iteration.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
The first Perl one-liner prints all groups captured by parenthesis in this regex, which create the output table cells, 1 cell per line:
/^\s*((?:name|source|destination)\s*=\s*[^,]*)/ : The beginning of the line, followed by 0 or more whitespace, followed by key = value pair where the key is specified inside the non-capturing parentheses (?:PATTERN). The value is a stretch of 0 or more non-comma characters ([^,]*)
The second Perl one-liner replaces all tabs with | using /g (multiple matches) regex modifier.
paste - - - : Join every 3 lines of the input on TAB and print as a single line.
SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlre: Perl regular expressions (regexes)
perldoc perlre: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups
perldoc perlrequick: Perl regular expressions quick start


text:
Q: Why Angular seed app showing Angular seed app: v0.1 I used angular seed with satellizer. I started the app with the command: npm install and run the project on browser by typing: http://localhost:8080/app/#/auth, but I see the browser is showing [view1] [view2]
Angular seed app: v0.1.
I have used the following codes in app.js:
'use strict';
angular.module('myApp', [
'ui.router',
'myApp.view2',
'myApp.auth',
'myApp.version',
'satellizer'
]).
config(['$stateProvider', '$urlRouterProvider', '$authProvider',
function($stateProvider, $urlRouterProvider, $authProvider) {
$authProvider.loginUrl = 'http://localhost:8000/adminlogin/showLogin';
$urlRouterProvider.otherwise('/auth');
}]);

I have used the below codes for auth.js within "view_auth":
'use strict';
angular.module('myApp.auth', [])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider,
$urlRouterProvider) {
$stateProvider
.state('auth', {
url: '/auth',
views: {
  'jokesContent': {
    templateUrl: "view_auth/auth.html",
    controller: 'AuthCtrl as auth'
  }
}
})
}])
.controller('AuthCtrl', ['$auth', '$state', '$http', '$rootScope', function($auth, $state, $http, $rootScope) {`

  var vm = this;

    vm.loginError = false;
    vm.loginErrorText;

    vm.login = function() {

        var credentials = {
            email: vm.email,
            password: vm.password
        }

        $auth.login(credentials).then(function() {
            $http.get('http://localhost:8000/api/v1/authenticate/user').success(function(response){
                var user = JSON.stringify(response.user);
                localStorage.setItem('user', user);
                $rootScope.currentUser = response.user;
                $state.go('jokes');
            })
            .error(function(){
                vm.loginError = true;
                vm.loginErrorText = error.data.error;
                console.log(vm.loginErrorText);
            })
        });
    }
}]);

The view file (auth.html) under view_auth is below:

 Login

                <form class="form-horizontal" role="form">

                        Email

                            <input type="email" class="form-control" id="inputEmail3" placeholder="Email" required="" ng-model="auth.email">

                        Password

                            <input type="password" class="form-control" id="inputPassword3" placeholder="Password" required="" ng-model="auth.password">

                            <button type="submit" class="btn btn-success btn-sm"  ng-click="auth.login()">Sign in</button>
                            <button type="reset" class="btn btn-default btn-sm">Reset</button>

                </form>

`
My index.html looks like:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
  <link rel="stylesheet" href="app.css">

view1

view2

Angular seed app: v

But after running the project, the view appear as like:

I need to show the screen like: https://i0.wp.com/baljeetsingh.in/wp-content/uploads/2015/11/2015-11-13_22-24-06.png?ssl=1
Any help appreciated.

A: Finally, I solved this issue. I replaced the codes

 in index.html as


text:
Q: How to initialize and run Mersenne Twister Random Generator inside kernels in PyCuda I wanted to use Mersenne Twister random generator inside pyCuda kernels for numerical experiment. Via Internet I found no simple examples of how to do it, so, I tried to construct something from Cuda documentation and pyCuda examples (pyCuda code below).
How it can be done correctly?
Thank you.
code = """
    #include <curand_kernel.h>
    #include <curand_mtgp32_host.h>
    #include <curand_mtgp32dc_p_11213.h>

    const int nstates = %(NGENERATORS)s;

    __device__ curandStateMtgp32 *devMTGPStates[nstates];
    __device__ mtgp32_kernel_params *devKernelParams;

    curandMakeMTGP32Constants(mtgp32dc_params_fast_11213, devKernelParams);
    curandMakeMTGP32KernelState(devMTGPStates, mtgp32dc_params_fast_11213, devKernelParams, 64, %(seed)s);

    extern "C"
    {
        __global__ void generate_uniform(int N, int *result)
        {
            int tidx = threadIdx.x + blockIdx.x * blockDim.x;

            if (tidx < nstates)
            {
                curandState_t s = *states[tidx];
                for(int i = tidx; i < N; i += blockDim.x * gridDim.x)
                {
                    result[i] = curand_uniform(&s);
                }
                *states[tidx] = s;
            }
        }
    }
"""

seed = 0
N = 256 * 64
nvalues = int(10**3)
mod = SourceModule(code % { "NGENERATORS" : N, "seed": seed}, no_extern_c=True)

CompileError: nvcc compilation of C:\Users\limen\AppData\Local\Temp\tmpspxyn4h9\kernel.cu failed
[command: nvcc --cubin -arch sm_50 -m64 -Ic:\program files (x86)\microsoft visual studio\shared\anaconda3_64\lib\site-packages\pycuda\cuda kernel.cu]
[stdout:
kernel.cu
]
[stderr:
kernel.cu(10): error: this declaration has no storage class or type specifier

kernel.cu(10): error: declaration is incompatible with "curandStatus_t curandMakeMTGP32Constants(const mtgp32_params_fast_t *, mtgp32_kernel_params_t *)"
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin/../include\curand_mtgp32_host.h(367): here

kernel.cu(10): error: a value of type "mtgp32_params_fast_t *" cannot be used to initialize an entity of type "int"

kernel.cu(10): error: expected a ")"

kernel.cu(11): error: this declaration has no storage class or type specifier

kernel.cu(11): error: declaration is incompatible with "curandStatus_t curandMakeMTGP32KernelState(curandStateMtgp32_t *, mtgp32_params_fast_t *, mtgp32_kernel_params_t *, int, unsigned long long)"
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin/../include\curand_mtgp32_host.h(481): here

kernel.cu(11): error: a value of type "curandStateMtgp32 **" cannot be used to initialize an entity of type "int"

kernel.cu(11): error: expected a ")"

kernel.cu(21): error: identifier "states" is undefined

9 errors detected in the compilation of "C:/Users/limen/AppData/Local/Temp/tmpxft_00001aa8_00000000-10_kernel.cpp1.ii".
]

A: I did  the following:
import pycuda.curandom
print(dir(pycuda.curandom))

This gives all attributes that are present in the Python module pycuda.curandom. There was no mention of any Mersenne-Twister(MT) or MT-based Pseudo Random Number Generator. This indicates that MT isn't implemented in PyCUDA.


text:
Q: MVC3 C# custom validation message sending from server side Good day. May be it is wrong way but it was the fastest way. So:
I have a model which store IP address (NetworkMask) as long (integer) (stored in mssql table)
And then I need to implement entering and correcting IP address
I added not mapped field (IPv4NetworkMask) into model:
    [NotMapped]
    public string IPv4NetworkMask{
        get{
            return ExtIP.LongToIPv4(NetworkMask);
        }
        set{
            NetworkMask=ExtIP.StringToIPv4(value);
        }
    }

and into view:

            @Html.LabelFor(model => model.NetworkMask)

            @Html.EditorFor(model => model.IPv4NetworkMask)
            @Html.ValidationMessageFor(model => model.IPv4NetworkMask)

Now everything works fine and when user entered incorrect network address I got an Exception inside StringToIPv4 and execution goes out of controller by
        if (!ModelState.IsValid)
            return View(NewModelObj);

But on client side I got message: "The value 'fdgdfgdf' is invalid."
How can I change this message to something else?

A: If you want to do it on the business layer, you can use a custom validator.
for example:
public static ValidationResult ValidateIP(string inputIP)
{
   bool isValid = false;

    try {
        ExtIP.StringToIPv4(inputIP);
        isValid = true;
    }
    catch {
    }

    if (isValid)
    {
      return ValidationResult.Success;
    }
    else
    {
      return new ValidationResult(
          "Ip is not in a correct format.");
    }
  }

A: I found the simplest way:
@Html.ValidationMessageFor(model => model.IPv4NetworkMask, "You have entered incorrect IP")


text:
Q: Does Geb support multi browser testing? I would like to ask if Geb supports multi browser testing. i.e. testing same scenario at a time in two different browser on one execution?

A: geb is built on top of Selenium WebDriver which supports most browsers. See here for geb config for various browsers

A: I just posted and example app for this. you can create a gradel task to spin through and execute the tests for each browser in the gebconfig. Firefox is a bit of a mess at the moment. link why is provided in the sample gebconfig
https://github.com/basejump/grails3-geb-example


text:
Q: Flutter Android Studio Gradle Build Failed Error When I try to run a flutter application it gives this build error
FAILURE: Build failed with an exception.

*

*What went wrong:
Task 'assembleAarRelease' not found in root project 'at_backupkey_flutter'.

Exception: The plugin at_backupkey_flutter could not be built due to the issue above.
These are my plugins ------------------------------
dependencies:
flutter:
sdk: flutter
flutter_nearby_connections: ^1.0.10
url_launcher: ^5.0.2
shared_preferences: ^0.5.12+4
path_provider: ^1.6.7
flutter_spinkit: ^2.1.0
curved_navigation_bar: ^0.3.7
at_onboarding_flutter: 1.0.0+1

A: If you want to use at_backupkey_flutter plugin, You should add dependency as below.
at_backupkey_flutter: ^1.0.0


text:
Q: Using GPS to get current location i just use this following code But i dont get a Toast msg Like My current location is:? Using GPS to get current location i just use this folowing code But i dont get a Toast msg ?
i just want to massage Like " My current location is: "
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    LocationListener mlocListener = new MyLocationListener();

    mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

    }

    /* Class My Location Listener */

    public class MyLocationListener implements LocationListener

    {

    public void onLocationChanged(Location loc)

    {

    loc.getLatitude();

    loc.getLongitude();

    String Text = "My current location is: " + "Latitud = " + loc.getLatitude() +"Longitud = "  + loc.getLongitude();

    Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();

    }

    @Override

    public void onProviderDisabled(String provider)

    {

    Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();

    }

    @Override

    public void onProviderEnabled(String provider)

    {

    Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();

    }

    @Override

    public void onStatusChanged(String provider, int status, Bundle extras)

    {

    }

A: your code is fine but if you are testing on device you need to move your device out in open space and if you are testing on emulator you need to provide kml file for mock locations.

A: Go to the Eclipse Toolbar Click on Window-> Show view -> DDMS -> Emulator control in the emulator control manually enter location Longitude and Latitude , then check
hope it works fine !!!


text:
Q: MS SQL Index column sort order matters? I have a database where I run profiler and database advisor to improve the performance of the database. I did and so far so good, the advisor presented me lots of indexes and statistics that can be created to get better performance.
But reading the statements I ran into this:
CREATE NONCLUSTERED INDEX [_dta_index_xinfobaseacl_11_397426127__K3_K7_K1_K5] ON [dbo].[xinfobaseacl]
(
    [lviewid] ASC,
    [lparentid] ASC,
    [lid] ASC,
    [xlactor] ASC
)WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
go

CREATE NONCLUSTERED INDEX [_dta_index_xinfobaseacl_11_397426127__K7_K5_K1_K3] ON [dbo].[xinfobaseacl]
(
    [lparentid] ASC,
    [xlactor] ASC,
    [lid] ASC,
    [lviewid] ASC
)WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
go

Same table, same columns, same parameters, just other sort order of the columns...
So I am confused, does the sort order really matters in index creation???

A: Yes the order of the columns in a composite index matters.
Both of them will work equally well for an equality predicate on all 4 columns.
But the first one will additionally support queries like
WHERE lviewid =  1 AND lparentid 1 AND lid = 1
ORDER BY xlactor

And the second one will support queries such as
WHERE parentid =  1 AND xlactor = 1
ORDER BY lid, xlactor

Whether or not you should create both indexes depends on your workload. Did you feed the DTA a representative workload including data modification statements?

A: You're confusing terminologies.  The sort order doesn't have a great, if any, affect, but the order of the columns in the index can be important.
The correct order of columns for a compound index depends on your query, but as a rule of thumb, the column with the fewest different values should be first.


text:
Q: Ищу аналог функции WebBrowser из WindowsForms (С#) в Intellij Idea, в Swing редакторе Ищу аналог функции WebBrowser из WindowsForms (С#) в Intellij Idea (Java), в Swing редакторе, из предустановленных ничего нет, вот я думаю может есть какие-нибудь модуль расширения для этого, в частности мне нужно создать форму содержащее информацию из интернета. Ядро любое можно (не только IE6 как там ^_^), просто не могу найти подобного в сети, плохо ищу, может кто-нибудь посоветует?)

A: Например:

*

*JxBrowser (на движке Chromium)

*Браузер из состава DJProject

A: Тоже советую насчет DJProject, в отличие от JxBrowser, они бесплатны.
И легко вставляются в swing приложение:
JWerBrowser webBrowser = new JWebBrowser();
webBrowser.navigate(WebServer.getDefaultWebServer().getClassPathResourceURL(getClass().getName(), "start.html"));
webBrowser.setBarsVisible(false);
add(webBrowser, BorderLayout.CENTER);

Если будут проблемы с js - для таких случаев есть Rhino.

A: Как вариант, в JavaFX есть WebView. Вот ссылка на хабр, где довольно подробно показаны примеры его использования. Входит в Java SE.


text:
Q: how to use on_ready from discord.py? Hello I have trouble using the API discord.py, I try to display in the console the message received, but every time the function on_reday returns no message.
#imports
import discord

TOKEN = "TOKEN"

client=discord.Client()

@client.event
async def on_message(message):

    try:
        print(message.content)

    except IndexError: #This IndexError is used to return when there is no Embed
        print("failure to read the message")
        return

    print(message.content)

client.run(TOKEN, bot=False)

A: @client.event
async def on_ready():
    await client.change_presence(status=discord.Status.online,
                                 activity=discord.Game("?help"))
    print("Bot is ready")

this will print ready when the bot will be online, it will change the  status and it will put the bot game(For me, it is ?help)
and import: from discord.ext import commands


text:
Q: Same piece of code works on one page & doesnt work on other Page, asp.net nesting of image inside a LinkButton shows image on one page & doesn't show image on another page below are two sample code from two different pages in the same root director.It works fine on one page but on the other page is doesn't show any download image rather shows the text download in place of image.
I have done troubleshooting for sometime and replace the code also but it doesnt show download image for any reason on the second page..
<asp:LinkButton ID="lnkbtnDownload" runat="server"  onclick="lnkbtnDownload_Click" meta:resourcekey="lnkbtnDownloadResource1">
<asp:Image ID="imgDownload" runat="server" ImageUrl="~/images/download.png" meta:resourcekey="imgDownloadResource1"  />
</asp:LinkButton>

<asp:LinkButton ID="lnkbtnDownload" runat="server"  onclick="lnkbtnDownload_Click" meta:resourcekey="lnkbtnDownloadResource1">
<asp:Image ID="imgDownload" runat="server" ImageUrl="~/images/download.png" meta:resourcekey="imgDownloadResource1"  />
</asp:LinkButton>

HTML OUTPUT
HTML for above two code sample render as below

Download

Both Pages are in the same root directory...

A: The problem probably comes from a discrepancy in your resource files or missing a resource file completely for the second page. Obviously you have one for the first, but possibly not for the other which has different naming.
If you are using meta:resourcekey, there are some things you have to considerate.

Make sure that your local resource files meet the following criteria:

*

*They are in an App_LocalResources folder.

*The base name matches the page name.

  For example, if you are working with the page named Default.aspx, the
  resource files are named Default.aspx.resx (for the default
  resources), Default.aspx.es.resx, Default.aspx.es-mx.resx, and so on.
The resources in the file use the naming convention
  resourcekey."property". For example, key name Button1."Text".

Source: MSDN


text:
Q: How to concatenate column data in SQL Server 2016? I have a complicated query which returns this:
MyID  col1  col2  col3
1     A:11
1     A:21
1     A:31
1                 C:13
1                 C:23
2           B:21
2           B:22

I saved the result set of this query in a temp table #tt to make things simpler later on.
What I want to achieve is this:
MyID  col1              col2        col3
1     A:11__A:21__A:31              C:13__C:23
2                       B:21__B:22

But the final query returns this:
MyID  col1                col2          col3
1     A:11__A:21__A:31__  ________      ____C:13__C:23
2     __                  B:21__B:22    __

This is the query:
select
    MyID,
    col1= stuff((select N'__' + col1 from #tt where MyID = x.MyID for xml path(''), type ).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'' ),
    col2= stuff((select N'__' + col2 from #tt where MyID = x.MyID for xml path(''), type ).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'' ),
    col2= stuff((select N'__' + col3 from #tt where MyID = x.MyID for xml path(''), type ).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'' )
from #tt as x
group by MyID

As you can see, there are a lot of underscores being returned. Since I am showing a smaller sample of the data, there will be more unneeded underscores when I ran on entire table. It does appear that I am doing some tiny mistake which I cannot figure out. How can I fix the issue?
If I was using SQL Server 2017 or later, string_agg() might have helped a lot.

A: Filter out the empty or NULL values in your subqueries.
... from #tt where MyID = x.MyID AND col1 IS NOT NULL AND col1 <> '' ...

(And analog for col2 and col3.)

A: Is this where you're trying to get to?
SELECT
    MyID,
    col1 = ISNULL(STUFF((SELECT N'__' + NULLIF(col1, '') FROM #tt WHERE MyID = x.MyID FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N''), ''),
    col2 = ISNULL(STUFF((SELECT N'__' + NULLIF(col2, '') FROM #tt WHERE MyID = x.MyID FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N''), ''),
    col2 = ISNULL(STUFF((SELECT N'__' + NULLIF(col3, '') FROM #tt WHERE MyID = x.MyID FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N''), '')
FROM
    #tt x
GROUP BY
    MyID;


text:
Q: calling non constexpr function from constexpr allowed in some conditions Coming from that question:
 How to build a custom macro that behaves differently when used as constexpr (like assert)?
I wonder why it is possible to call a non constexpr function if it is conditional.
void bla( )
{
    std::cout << "bla called!" << std::endl;
}

constexpr bool check(bool condition)
{
    //bla(); // can not directly be called -> not constexpr!
    condition ? void (0) : bla(); // compiles and runs even if condition is true or false!

    // if condition is const, it did not compile because it
    // directly force execution of non constexpr function
    true ? void(0): bla(); // also that compiles!, ok, directly evaluated
    //true ? bla(): void(0); // that did not compile;)

    //false ? void(0): bla(); // that did not compile;)
    false ? bla(): void(0); // compiles, ok, directly evaluated

    return 0;
}

int main()
{
    check( false );
    check( true );
}

Can someone explain which rules are given from the standard?
As commented from W.F.: If result is used in constexpr term like an
template parameter, it fails if condition results in evaluation
of non constexpr function.
That makes assert to complain directly while compiling if result is
used in constexpr term.

A: A constexpr function implies that it is possible to evaluate the value of the function at compile time. Since this is possible for the input true the function is a valid constexpr. Remember that a constexpr function can have an address just as a regular function, it does not need to be compile time, only when used as a compile time function (which you do not in your example).
As mentioned on the constexpr page on cppreference:

A constexpr function must satisfy the following requirements:

*

*it must not be virtual

*its return type must be LiteralType

*each of its parameters must be LiteralType

*there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression (for constructors, use in a constant initializer is sufficient) (since C++14). No diagnostic is required for a violation of this bullet. (Emphasis mine)

Your function fulfils all of the above requirements: it is not virtual, it returns a literal type, the parameter is literal. And more interestingly last bullet point: there exists at least one set of argument values for which the function is actually fully compile time. (hence my emphasis of the last bullet)
As W.F. mentioned in the comments, the function can be used compile time, but only for valid inputs, that is, inputs that does not lead to a sub expression that is not compile time constant. So the input true will work, but false will not since it will lead to bla being evaluated.
This is also stated in the standard: §10.1.5.5:

For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression (8.20), or, for a constructor, a constant initializer for some object (6.6.2), the program is ill-formed, no diagnostic required.
constexpr int f(bool b)
{ return b ? throw 0 : 0; }   // OK

constexpr int f()
{ return f(true); }           // ill-formed, no diagnostic required

See the examples from the standard document in particular.


text:
Q: import PCB components into KiCAD which are sold in the electronics industry When drawing a schematic in Eeschema Editor in KiCAD, there is a button to "Run CvPcb to associate components and footprints", so a schematic symbol on the *.sch file can be associated to a physical component to generate the Netlist and be soldered on the PCB when manufacturered.  The component list in this library is kind of small relative to the number of components available for sale online.  Is it possible to import components into KiCAD that users of the program have already created, so you don't have to build them from scratch using the Editor?  Where can I find them, and how do I import them?  I've only been using KiCAD for a week, because I learned it in Ham Radio Club.  So I've never drawn a schematic before this week.

A: The Kicad philosophy is: There are components and there are footprints, and you need to match the component with the footprint. Why? Because the same component might be available in different footprints. AFAIK, all common footprints are already present in Kicad. Only footprints I have had to make were of heatsinks and connectors.
After you draw the schematic (and have run annotate), you have to run CvPCB. This will pull up the browser where you can select your footprints. Only after all components have been assigned footprints, should you create the netlist. Then start the board editor and import netlist. If some components do not have footprints assigned yet, the board editor will issue warnings when you import the netlist there. Go to the schema editor, and run CvPCB to fix that.
The issue with components and footprints also extends to the schematic editor. There are devices and there are components and you need to match the device to the components. e.g. there are 3 leg transistors, 4 leg transistors etc... and you need to match your part with the correct schematic, and then again match the correct footprint with that schematic. Only constraint is the number of pins on the schematic and footprint must match, and they must be numbered the same. You need to check that the numbering is in correct order. e.g. there are transistors with BCE, CBE, ECB... and all of them have pins numbered 123. You will need to make sure 1,2 and 3 correspond to the correct transistor leg. There is a footprint viewer from CvPCB, which will show you which pad corresponds to which pin number. The schematic editor already shows the pin number.
All this is unlike eagle, where footprints are hardcoded with the component. In Kicad, it is perfectly possible to assign a capacitor footprint to a diode, intentionally, or by mistake. Very flexible.
PS: CVPCB may need internet to run. There is a way to force it to use the already installed libraries. Open the settings from CvPCB, and change the KGithub to KISYSMOD. Hope you're using the latest version of Kicad.

A: There are a lot of places where you can import custom-made components that manufacturers provide. For instance, Macrofab, a company here in Houston where I live, has instructions on how to do what you're asking.
Assuming that the manufacturer has components you can import into KiCAD, here are the instructions on how to do so. You may need to contact the manufacturer of the component to see if they have a component for KiCAD. Otherwise, you'll have to end up making it yourself and specifying its characteristics. I know at my job, I typically ask for the vendor if they have any SPICE or CAD components of their own products that I can import into the software and they typically do.
Otherwise, I have two options if they don't have what I am looking for: 1) Don't use their products and move on to the next product that I can use to get the job done... or 2) Ask for a specifications sheet along with its architecture (if I'm dealing with FPGAs or ASICs) and create it on the software... which isn't exactly a lot of fun.
But I'm digressing (but it is important if you're dealing with manufacturers)... Here the steps you can take to import what you need into KiCAD.
1) Open KiCAD
2) On the program/tool list, go to Eeschema.

3) Click Select -> Preferences -> Library.

4) Click Add and choose the newly exported ".lib" file.

5) You're finished!
Now if you want to import the footprints and patterns, then you need to follow these steps:
1) On the program/tool list, go to Pcbnew.

2) Follow the same steps as you would importing symbols, only this time select the ".mod" file.

3) You're done!
This is where I got this tutorial and pictures from.


text:
Q: Get ID of inserted row with Propel ORM when not using autoincremented IDs Using Propel, I can save an object using
$user = new User;
$user->setName('Test');
$user->save();

$user->getId() will contain the ID of the inserted object. But this will only work if I use autoincremented ID values.
Is there any way I can get this to work when the IDs are generated by a function?
I can append RETURNING id to the end of the insert queries to return the ID, but I'm not sure whether I can get this data back into the Propel User object.

A: You should be able to retrieve the missing (externally created) values by calling reload() on the object you wish to hydrate.
//hydrates fields by database values
$user->reload();
//should return the postgresql-generated-value
$user->getId();

edit: typos

A: If you're having a function or trigger in MySQL that creates for you a ID automatically on each insert then you need to save this generated value per session/connection. For example using last_insert_id(new_id), so you can fetch this value using SELECT last_insert_id(); through the current connection in PHP. There's no other logical way to fetch such generated IDs by functions/triggers.


text:
Q: Ubuntu One Account not working Yesterday I wanted to try out the Ubuntu One storage feature and logged in. I couldn't sync anything from either Windows or Ubuntu.
In Windows nothing really happens.
In Ubuntu I get a File Sync error. (auth failed (AUTH_FAILED)) error.
If I log onto the website it gives me a "Something has gone wrong" error. If I go to my account page it says I'm not subscribed to the file storage and if I click on the sign up button it goes to the "Something has gone...." page.
I tried deleting every device via the homepage. Changing my password didn't work.
My girlfriend created an account and it works perfectly on her machine and mine.
Does anyone have an idea on how to solve this?

A: There is a current service disruption for some users.
Ubuntu One Service Status

A: Was able to access the cloud after emailing them. Didn't get any confirmation email from them but got a 'Welcome to Ubuntu One' email, and it has worked ever since.


text:
Q: Two definition of sheaves: thoughts? This might be a naive question. However, as a absolute noob picking up cohomology theory I am deeply confused by these two definitions of sheaf that I have encountered. I definitely lack some knowledge in category theory or algebra to fully understand sheaf cohomology.
Definition 1. Defined as a presheaf (of abelian group) satisfying sheaf axioms. In particular, I perceive a sheaf as a family of abelian groups along with a family of group homomorphisms $(\mathscr{F}, ρ)$. An element of $\mathscr{F}$ has the property of "looking like a function" and the group homomorphism is called a section.
Definition 2. Let $X$ be a topological space, then $π \colon \mathcal{F} \to X$ is a sheaf of abelian groups if and only if:

*

*$π$ is a local homeomorphism.

*For each $x \in X$, the fiber $\mathcal{F}_x := π^{−1}(x)$ is an abelian group.

*The zero section $x \to 0_x$ is continuous.

*The mapping $α$ on the fiber product $\mathcal{F} \times_π \mathcal{F} = \{ (v, w) \in \mathcal{F} \times \mathcal{F} : π(v) = π(w) \}$ by $α(v, w) = v + w$ is continuous.

*The mapping $β \colon \mathcal{F} \to \mathcal{F}$ defined by $β(v) = −v$ is continuous.
In this definition the sheaf becomes a topological space $\mathcal{F}$ characterized by $\pi \colon \mathcal{F} \to X$. So Definition 1 and Definition 2 seems somehow unrelated to me. In particular, a canonical example of Definition 1 is $\mathcal{C}(X)$, where as for Definition 2 a canonical example is $\mathcal{F} = X \times \mathbb{Z}$. When can we treat the sheaf as a topological space? What happened to the sections?

A: The first definition is what I will call a sheaf (of Abelian groups). The second definition I will call an etale space (of Abelian groups).
The two categories are equivalent. Let's begin with an etale space. We can construct a sheaf by defining $\mathscr{F}(U) = \{f : U \to \mathcal{F} \mid f$ is continuous and $\pi \circ f = 1|_U\}$. Here, $1|_U : U \to X$ is the inclusion function. Such an $f : U \to X$ is said to be a "partial section" of $\pi$, and $\mathscr{F}$ is said to be the "sheaf of sections of $\pi$". We then define the group operations in the obvious way. Note that this construction doesn't require $\pi$ to be a local homeomorphism. $\DeclareMathOperator{colim}{colim}$
To go the other way, we begin with a sheaf $\mathscr{F}$. Then we define $\mathcal{F}$ as follows. The underlying set is $\coprod\limits_{x \in X} \colim\limits_{x \in U} \mathscr{F}(U)$. Recall that for a fixed $x$, $\colim_{x \in U} \mathscr{F}(U)$ is the set of stalks at $x$. So this space is the space of all stalks. The map $\pi : \mathcal{F} \to X$ is defined in the obvious way, sending a stalk at $x$ to point $x$. And the topology on $\mathcal{F}$ has basic open sets of the form $\{(x, [S]) \mid x \in V\}$, where $V \subseteq X$ is open and $S \in \mathscr{F}(V)$. The group operations are just the stalkwise group operations. Note that this construction doesn't require $\mathscr{F}$ to be a sheaf, merely a presheaf.
These constructions are inverse equivalences of the category of sheaves and the category of etale spaces.

A: Edit: Let me first describe how $Sh(X)$ is equivalent to $Etale/X$, where $Etale/X$ denotes the full subcategory of $Top/X$ with objects the etale morphisms (local homeomorphisms) into $X$. You can also find more detailed accounts of that equivalence in almost any book about topos theory (Sheaves  in Geometry and Logic e.g.). By $Sh(X)$ I mean sheaves which take values in $Set$. The equivalence between sheaves which take values in $Ab$ and etale bundles with a fibrewise abelian group structure then follows from the fact that they are the internal abelian group objects in $Sh(X)$ and $Etale/X$ respectively, as stated below.
The advantage is, that this approach generalizes to other kinds of algeraic structures: For example a sheaf $\mathcal F$ which takes values in $Ring$ is the same thing as an internal ring object in $Sh(X)$, which in turn is the same data as a fiberwise continuous ring structure on the etale bundle associated to $\mathcal F$. As an important example, you may consider the ring sheaf $C^0(-,\mathbb R)$ of continuous functions on $X$.
The construction is in essence the same as in Mark Savings answer, only that we do not need to take care of the abelian group structure. Given a sheaf $\mathcal F$, we form a bundle $F\to X$ by taking as an underlying set $F = \bigsqcup_{x\in X}\mathcal F _x$. We topologize the bundle by taking subsets of the form $\{ s_x|x\in U\}$, where $s\in \mathcal F(U)$ as a basis. One has to check that this turns the canonical map $F\to X$ into a local homeomorphism. Note that each $s\in \mathcal F(U)$ in this way defines a section $U\to F, x\mapsto s_x$ of the etale bundle $F\to X$. In fact, the sheaf condition will imply that each section of $F\to X$ arises in that way, so that the map of sheaves $\mathcal F\to \Gamma(-,F)$ which I have just described is in fact an isomorphism.
More generally: we can associate to each object in $Top/X$ its sheaf of sections. This yields a functor $\Gamma:Top/X \to Sh(X)$. The construction above shows how to construct from each sheaf $\mathcal F$ a bundle $B\mathcal F$ over $X$. This yields a functor $B:Sh(X)\to Top/X$. One can check that $\Gamma$ is right adjoint to $B$. The canonical map $\mathcal F\to \Gamma(-,B\mathcal F)$ which I have described above is in fact the unit of that adjunction. It is a general fact that each adjunction between to categories induces an adjoint equivalence between the full subcategories of fixpoints of both sides (fixpoints are those objects for which the unit respectively counit is an isomorphism). One can then show that every sheaf is a fixpoint on the $Sh(X)$ side, and that on the $Top/X$ side the fixpoints are precisely the etale bundles. This then gives the equivalence.
First version: Here is a different way to see that both definitions describe the same thing. It is well-known that the category of $\mathrm{Set}$-valued sheaves on a space $X$ is equivalent to the category of étale spaces over $X$. Now a sheaf of abelian groups (your first definition) is nothing but an abelian group internal to the category $\mathrm{Sh}(X)$, while your second definition describes precisely an abelian group internal to the category $\mathrm{Étale}/X$.


text:
Q: Would I benefit from applying move semantic or return-value-optimization will be performed for function that returns file content as string? I have some load(..) method that loads the file's content into std::wstring. It usually process quite big files (up to few MB) and I use it extensively so I look for optimization possibilities (without breaking the simplicity of "load the file content into string" and without generating additional dependencies to other libraries).
Should I use move semantic here (I'm not quite familiar with it)? Or the way I've written it is close to the most time-optimal because of return-value-optimization that compiler will perform?
inline static std::wstring load(std::wstring filePath) {
    std::wifstream file(filePath.c_str());
    if(file){
        std::wstring fileString;
        fileString.reserve((size_t)file.tellg());

        file.seekg(0);
        while(!file.eof()){
            fileString += file.get();
        }
        file.close();
        return fileString;
    }
    file.close();
    ERROR_HANDLE(L"File could not be open:\n" + filePath);
    return L"";
}

A: The code as implemented will keep allocating new memory for the strings storing the file's content. For the size of strings quoted the actual allocation overhead is likely to be negligible. However, there is a fair chance that the memory is not mapped to any cache and accessing it may correspondingly be relatively expensive: already mapped memory needs to be evicted. Assuming code calling load() essentially just processes the content of the string, keeping the same string may have a performance advantage. A corresponding implementation could look like this:
inline bool load(std::string const& path, std::wstring& content) {
    std::wifstream in(path.c_str());
    if (in) {
        content.assign(std::istreambuf_iterator<wchar_t>(in),
                       std::istreambuf_iterator<wchar_t>());
        return true;
    }
    else {
        return false;
    }
}

There shouldn't be any need to reserve() memory as the content should quickly settle on a capacity sufficient for the files being processed.
Sticking with the original interface, i.e., returning a string, will easily move the string anyway: when returning a temporary object or a named variable a move constructor will be used. Ideally, the move is avoided, too, by laying out the implementation to be viable for copy-elision. For example, you could always return the same object. Copy-elision normally happens even for compilers not implementing rvalue references or for classes without move constructors. I'd implement your function like this:
inline std::wstring load(const std::string& path) {
    std::wifstream in(path.c_str());
    std::wstring   result;
    if (in) {
        // possibly result.reserve() capacity
        result.assign(std::istreambuf_iterator<wchar_t>(in),
                      std::istreambuf_iterator<wchar_t>());
    }
    return result;
}


text:
Q: Finding Installed Browsers. Microsoft Edge I'm trying to check for installed browsers on a client's PC as a means of enabling those browsers for use in the application. I've found that all browsers have information in the registry under

HKEY_LOCAL_MACHINE\Software\Clients\StartMenuInternet

and

HKEY_LOCAL_MACHINE\Software\Wow6432Node\Clients\StartMenuInternet
  (64-bit)

with the exception of Microsoft Edge.
Its app settings are stored under

Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer\Storage\microsoft.microsoftedge_8wekyb3d8bbwe\MicrosoftEdge\Main

according to someone here.
but I was hoping to find a neater solution that would encapsulate all browsers so am looking for ideas from people in the know.

A: Since Microsoft Edge is the default browser, you can count that for granted and then you will find the remaining installed browsers from the registry.
HKEY_LOCAL_MACHINE\Software\Clients\StartMenuInternet
 You can also use the following code snippet to detect the default browser.
@"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice";


text:
Q: Which bean can I use as a alternative one of http-outbound-gateway? I am changing spring-integration 3.x to 4.x.
And I should change every xml configuration to the java file.
But, I can't find the bean that can be replaced in place of the followings.
<int-http:outbound-gateway url="http://www.google.com/ig/api?weather={city}"
                           http-method="GET"
                           expected-response-type="java.lang.String"
                           request-factory="requestFactory"
                           request-channel="requestChannel"
                           reply-channel="replyChannel">
    <int-http:uri-variable name="city" expression="payload"/>
</int-http:outbound-gateway>

<bean id="requestFactory"
      class="org.springframework.http.client.SimpleClientHttpRequestFactory">
    <property name="connectTimeout" value="5000"/>
    <property name="readTimeout"    value="5000"/>
</bean>

I tried using the HttpRequestExecutingMessageHandler for it.
@Bean
    HttpRequestExecutingMessageHandler httpGateway() {
        HttpRequestExecutingMessageHandler gateway
        = new HttpRequestExecutingMessageHandler(gitlabUri);
        gateway.setOutputChannel(requestChannel());
        return gateway;
    }

But it doesn't have the request channel as a parameter.
Help me..

A: The XML parser creates 2 beans for outbound endpoints; a Consumer bean (event-driven or pollable, depending on the input channel type) and the message handler, which is injected into the consumer. A ConsumerEndpointFactoryBean is used to generate the appropriate consumer.
So, you can either wire up the 2 beans yourself, or, use a @ServiceActivator annotation and the framework will take care of creating the the consumer for you...
@ServiceActivator(input-channel="toHttp")
@Bean
HttpRequestExecutingMessageHandler httpGateway() {
    HttpRequestExecutingMessageHandler gateway
        = new HttpRequestExecutingMessageHandler(gitlabUri);
    gateway.setOutputChannel(requestChannel());
    return gateway;
}

See the reference manual for more details. It uses the HTTP endpoint as an example.


text:
Q: From matrix of community co-occurences to the index of community for every node I have an n x n matrix X_{ij} where the i-j-th entry is 1 if node i and node j in a graph belong to the same cluster and 0 otherwise. That matrix is a result of an optimization algorithm to find communities in a graph.
I want to transform that matrix in a list with n entries, where for every i-th entry I can associate an integer that represent the separate cluster that the i-th node belongs to.
For example, in python, my matrix is the following (in this case nodes 0 and 1 belong to community A, while nodes 2 and 3 belongs to community B)
matrix([[ 0.,  1.,  0.,  0.],
    [ 1.,  0.,  0.,  0.],
    [ 0.,  0.,  0.,  1.],
    [ 0.,  0.,  1.,  0.]])

that means that node 0 belong to the same community (nodes are from 0 to n-1)
How is possible to extract from that matrix a list like this:
[A,A,B,B]

where the i-th element of the list represent the index of the community the node belongs?
(I'm using A and B just for being more clear, but those indices are in fact integers)

A: Assuming this relation you have is symmetric (X_{ij} = X_{ji}) and transitive (X_{ij} = 1, X_{jk}= = 1 -> X_{ik} = 1), you can regard your matrix as a graph G=(V,E) where each index i=1,...,n is a node, and (i,j) is in E if and only if X_{ij} = 1.
So, your "communities" are actually connected components of the graph.
Finding connected components is fairly easy with any graph discovery/traversal algorithm such as BFS and DFS using the following high-level pseudo code:
X = V //all nodes initially in X
count = 1
while X is not empty:
   choose random x in X
   do BFS from x, let the set of discovered nodes be U
   for each node u in U:
        yield (u,count) //u is in the community labeled as count
   count = count + 1
   X = X \ U //remove all nodes in U from X


text:
Q: Protocol for remote logging of temperature, gas/electricity consumption So, I'm managing a series of rented holiday homes, which all have dynamic IP, ADSL Internet connections.
We've wanted to keep track of a few types of data, e.g. per-room electricity usage, hot water temperature, thermostat setting, gas usage, network bandwidth usage, etc etc, and keep these centrally so we can perform analytics and graph them in real-time.
I'm comfortable building the hardware required to log these variables every 1-5 seconds and get them into e.g. a Raspberry Pi, but I'm wondering what kind of framework would be suitable for transferring and storing the data on the server side.
My initial thought was something like SNMP, but a) this doesn't seem designed for non-network uses, b) it's not very secure, and c) I'm looking for something agent-to-server (so I don't have to know the IP of the agent, and it'll also traverse NAT, so I can have multiple devices logging different things on the same network.)
My second thought was something using a REST API, but making potentially hundreds of API calls per second via different TCP connections seems a bit wasteful.
I came across Cubism but this seems to have the same disadvantages as some sort of REST API; there's a lot of redundant data transmitted every connection, if I were to send the data every 5 seconds per sensor.
Names like AMQP and MQTT come up, though none of these seem particularly suited (natively) to travelling over the public Internet without configuring VPNs etc.
Thoughts?
[This doesn't seem like a particularly niche problem, now I think about it - weather logging, share price, etc etc... although this is probably a smaller interval]

A: I have an geospatial/environment monitoring background and can tell you something about two major standards which are used today in environmental/infrastructural (electricity and water supply networks) monitoring sensor networks.

*

*Proprietary one: Most sensors simply store time series measurements in their own local data format. A server process calls every sensor from time to time to gather the time series data (in most cases via a simple GPRS uplink), transforms it into an exchange Format and then stores it into a centralized database where you can work with the data. One of the industry leader companies is Kisters AG and their exchange format ZRXP. So this is simply storing time series data in an ASCII Format (i.e.ZRXP), and import that into a database by calling the sensor over any connection.

*Open Geospatial Standard: Sensor Observation Service and SensorML which I think does more fit your needs, because these are Web Service Specifications whilst the proprietary stuff above is a complete system solution built by one vendor. There exists a nearly ready to use java reference implementation of SOS provided by 52 north which should be easily runnable on a Pi. Although the SOS specification has a very strong geospatial background, that does not mean,that it can't be adopted for your purpose I think. At least SensorML should give you some ideas.


text:
Q: What is the best way to work with a huge address database for autosuggest? I have a database of about 300,000,000 addresses for a country. This data is supposed to be used for auto-suggest in a form, i.e: if the address is 1900 Country Hill Road, user would type Count (assuming at least 3 characters to trigger auto-suggest is good idea), and the form may offer user with the first 10 results, i.e:
165 Countable Road
1890 Countable Road
44 Counting Circle
900 Country Drive
13 Country Hill Road
1900 Country Hill Road
344 Country Mountain Place
etc.

Choosing address also fills in the City and ZIP.
Note: This is in a country that format addresses as Street ##/##, so the actual name is the first thing to be typed.
Doing a SELECT * FROM addresses WHERE street LIKE 'Count%' LIMIT 10 query takes about 3 seconds on average. Selecting just the street, house_number, city, zip is slightly faster. Each row has 19 columns. I have added an index on one of the columns based on some MySQL guides, but that didn't help noticably. I want to get under 500ms per request.
What would be the best way to resolve this? Things that have come to mind are:

*

*dividing the database table into multiple tables based on the streets' first letters and selecting the table based on what the user types. This would mean I would end up with about 26 tables.

*converting everything into multiple JSON files

*further looking into optimizing the database

A: Let me step through the analysis.

*

*You are searching for street address that starts with the given string, correct?

*WHERE street LIKE 'Count%', together with INDEX(street) is reasonably optimal.  No separate table, no JSON, no initial letter, etc.

*LIMIT 10 will find the first 10 such items efficiently.  Note:  Adding an ORDER BY could wreck performance.

*SELECT street finds the result in the index's B+Tree.  Since this is all you need, use it.  SELECT <<some columns>> or SELECT * has to do an extra action to get the other column(s).

Such an index will drill down the B+Tree to the first occurrence of "Count...", then it will scan forward from there.  Even if the dataset cannot be cached in RAM, there would be effectively only one disk hit, which would take millisecond(s).  If you need extra columns, then the extra action would probably require 10 more disk hits (due to LIMIT 10).
So, it is important that the INDEX contain exactly what you need to receive for the autosuggest.
ORDER BY would be OK only if you say ORDER BY street (or ORDER BY street DESC).  Otherwise, it must find the thousands (millions?) of streets starting with "count", sort this list, then deliver 10.
Based on that analysis, the "minimum of 3 characters" is not important.  However, my UI gut feeling is that 3 is reasonable.
Oh, another issue.  Since there is probably "1 Main St" in thousands of towns, auto select for "Main" is likely to show 10 copies of the same "1 Main St".
Oh, I have not handled something that you imply from you example.  street includes the street number.  Or maybe you have two columns -- street_name (useful for searching) and street_number.  So...
Have two columns:

*

*One for autosuggest ("Main St")

*One for display ("1 Main St, Acron OH")

Then have INDEX(auto_suggest, display).  This will give you the efficiency of minimal effort to get the autosuggest values, but allows equally efficient display of the full address.
But that still has the problem of dup addresses.  OK, I am now forced to recommend an extra table.  It would contain all the unique street names, no street_number, etc.
CREATE TABLE AutoSuggest (
    street VARCHAR(99) NOT NULL,
    PRIMARY KEY(street)
) ENGINE=InnoDB;

Note that, in MySQL, a PRIMARY KEY is a B+Tree index clustered with the data and is UNIQUE.  This table might be about 1GB for 200M addresses, after compensating for dups, overhead, etc.  After your app has run for some time, most of the table would be cached in the buffer_pool.  This makes the typical autosuggest lookup be about 1 millisecond.
But, that only give you the street name, not the address, etc.  Perhaps you want a second column called full_street (and change to PRIMARY KEY(street, full_street)):
INSERT INTO AutoSuggest (street, full_street)
    VALUES
    ("Main St", "1 Main St");

This provides most of the benefits and few of the drawbacks mentioned before.
Ponder my comments with the idea of tradeoffs between your two goals:

*

*Fast autosuggest;

*What the UI presents during the autosuggest.


text:
Q: Does this proof that $\mathbb{D}$ is countable work? I am trying to prove that the set $\mathbb{D}$ of finite decimals is countable. My proof seems too simple to work out - I simply list the all of the decimals with $N$ digits for all $N\geq 1$, starting with $N=1$ and working up from there.
It seems like I would reach every single decimal eventually and end up with a bijection with $\mathbb{N}$, as there are only a finite number of decimals with $N$ digits. Does this proof work?


text:
Q: Hybris - ItemType of Relation concept Lately I have come across instances where people have itemtypes of a relation. Could someone please explain me the concept of this structure?
Also I have generated a relation, but am unable to find getters/setters for this. I believe, this is because no classes are generated for a relation.
For a specific project requirement I had to add a collection of relations to another Model, but could not find the setters and getters generated even for the collection, I think because the elementtype is a relation. I also checked the extensionmanager, but no getters and setters were generated there either.
Could someone please let me know if with such a structure I could getters and setters for collection of relations?
Thanks,
Farhan

A: First you should use Relation instead of Collection whenever it's possible. In hybris Collection stores the values as CSV in one field, hence it's limited by the max size of a field and it may be truncated.
Then for Relation, you won't have a Java model generated, but only a specific DB table.
The getter and setter will actually be generated in the target and source model depending on your cardinality.
If we take an example - EmailMessage2ToAddressesRel
    <relation code="EmailMessage2ToAddressesRel" .... >
        .
        .
        .
        <sourceElement type="EmailMessage" qualifier="toMessages"
            cardinality="many" collectiontype="list" />
        <targetElement type="EmailAddress" qualifier="toAddresses"
            cardinality="many" collectiontype="list" />
    </relation>

It map many toMessages as source to many toAddresses as target.
If you look at EmailMessageModel and EmailAddressModel you will find respectively the getter and setter for toAddresses and toMessages.


text:
Q: New ios4 Format not a string literal I need to create a string using results of a textfield.
I use :
>     NSString *username = [NSString stringWithFormat:myTextField.txt];

but i get the warning :
Format not a string literal and no format arguments.
Everything works but like i use more than 10 times this syntax i would like to erase this warning.
thanks to all !

A: In iOS 4 you must do as follows in order to get rid of the warning:
NSString *username = [NSString stringWithFormat:@"%@", myTextField.txt];

A: That's... not really what -stringWithFormat: is for. Use
NSString *username = [NSString stringWithString:myTextField.text];

or
NSString *username = [[myTextField.text copy] autorelease];


text:
Q: How to store multiple pages data in the last page using C#, ASP.Net I want to save a application which has multiple pages. But I dont want to save it in each step. Rather I want to see the summary of multiple pages in the last page and then only I want to save the application. Can you please help on the same.
Thanks,
vsari

A: Use the ASP.NET Wizard Control and save data from each wizard step into Session state, then retrieve from Session at the end:
Walkthrough: Advanced Use of the ASP.NET Wizard Control


text:
Q: How configure Spring / Woodstox jaxws to strip out CTRL-CHARs from a proxy SOAP service response I have been looking to find a solution to alter/strip out the SOAP response from a proxy service before it hits to Woodstox's DeserializationException. Below is the exception I am getting. Before giving out straigt answers like CTRL-CHAR's are not valid for XML, creating a custom SOAP Message handler some facts:

*

*This is a java desktop application, so no Tomcat

*Have the wsdl and stubs are generated through JAX-WS RI 2.2.8

*The Web Service Client configuration is as follow :
<bean id="serviceProxy" class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
    <property name="serviceInterface" value="local generated stub"/>
    <property name="wsdlDocumentUrl" value="--wsdl URL--"/>
    <property name="namespaceUri" value="urn:address"/>
    <property name="serviceName" value="proxyService"/>
    <property name="portName" value="Some_Wsi_HandlerPort"/>
    <property name="lookupServiceOnStartup" value="false" />
</bean>

I tried the following configuration, but it didn't work :
<jaxws:client id="localService">
    <jaxws:properties>
       <entry key="javax.xml.stream.XMLOutputFactory">
            <ref bean="xmlOutputFactory"/>
        </entry>
     </jaxws:properties>
</jaxws:client>

<bean id="invalidCharHandler"   class="com.ctc.wstx.api.InvalidCharHandler$ReplacingHandler">
    <constructor-arg value=" "/>
</bean>

<bean id="xmlOutputFactory" class="com.ctc.wstx.stax.WstxOutputFactory"/>

<beanclass="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject">
        <ref bean="xmlOutputFactory" />
    </property>
    <property name="targetMethod">
        <value>setProperty</value>
    </property>
    <property name="arguments">
        <list>
             <util:constant static-field="com.ctc.wstx.api.WstxOutputProperties.P_OUTPUT_INVALID_CHAR_HANDLER"/>
             <ref bean="invalidCharHandler" />
        </list>
    </property>
</bean>

I also tried creating custom SOAPHandler and LogicalHandler but they didn't help either.
I know there are methods to search and replace the unicode chars from the response body and consume it after manupulating the response body, but what I am looking for is a filter just like in the WstxOutputProperties.P_OUTPUT_INVALID_CHAR_HANDLER config above, which didn't work :( so without breaking the request and reponse to this proxy service, I just want the Woodstox or Spring or  anything that I can inject customized to filter the invalid chars from the reponse before throwing an error and breaking the communication.

org.springframework.remoting.RemoteAccessException: Could not access remote service at [null]; nested exception is com.sun.xml.ws.encoding.soap.DeserializationException: Failed to read a response: javax.xml.bind.UnmarshalException
   - with linked exception:
  [com.ctc.wstx.exc.WstxUnexpectedCharException: Illegal character ((CTRL-CHAR, code 31))
   at [row,col {unknown-source}]: [91,222]]
      at org.springframework.remoting.jaxws.JaxWsPortClientInterceptor.doInvoke(JaxWsPortClientInterceptor.java:565)
      at org.springframework.remoting.jaxws.JaxWsPortClientInterceptor.invoke(JaxWsPortClientInterceptor.java:541)
      at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
      at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
      at com.sun.proxy.$Proxy42.salesOrderInfo(Unknown Source)

A: If you did control output side, the method you found (explained here) would work. But it sounds like something else is writing/adding invalid characters.
If so, I think you will need to implemented a java.io. FilterInputStream that just strips out such control characters: they are relatively easy to find, esp. if you only have trouble with 0x1F.


text:
Q: How to detect if a character from a string is upper or lower case? I'm expanding a class of mine for storing generic size strings to allow more flexible values for user input. For example, my prior version of this class was strict and allowed only the format of 2x3 or 9x12. But now I'm making it so it can support values such as 2 x 3 or 9 X 12 and automatically maintain the original user's formatting if the values get changed.
The real question I'm trying to figure out is just how to detect if one character from a string is either upper or lower case? Because I have to detect case sensitivity. If the deliminator is 'x' (lowercase) and the user inputs 'X' (uppercase) inside the value, and case sensitivity is turned off, I need to be able to find the opposite-case as well.
I mean, the Pos() function is case sensitive...

A: try using these functions (which are part of the Character unit)

*

*Character.TCharacter.IsUpper

*Character.TCharacter.IsLower

*IsLower

*IsUpper
UPDATE
For ansi versions of delphi you can use the GetStringTypeEx functions to fill a list with each ansi character type information. and thne compare the result of each element against the $0001(Upper Case) or $0002(Lower Case) values.
uses
  Windows,
  SysUtils;

Var
  LAnsiChars: array [AnsiChar] of Word;

procedure FillCharList;
var
  lpSrcStr: AnsiChar;
  lpCharType: Word;
begin
  for lpSrcStr := Low(AnsiChar) to High(AnsiChar) do
  begin
    lpCharType := 0;
    GetStringTypeExA(LOCALE_USER_DEFAULT, CT_CTYPE1, @lpSrcStr, SizeOf(lpSrcStr), lpCharType);
    LAnsiChars[lpSrcStr] := lpCharType;
  end;
end;

function CharIsLower(const C: AnsiChar): Boolean;
const
  C1_LOWER  = $0002;
begin
  Result := (LAnsiChars[C] and C1_LOWER) <> 0;
end;

function CharIsUpper(const C: AnsiChar): Boolean;
const
  C1_UPPER  = $0001;
begin
  Result := (LAnsiChars[C] and C1_UPPER) <> 0;
end;

begin
  try
    FillCharList;
    Writeln(CharIsUpper('a'));
    Writeln(CharIsUpper('A'));
    Writeln(CharIsLower('a'));
    Writeln(CharIsLower('A'));
  except
    on E:Exception do
      Writeln(E.Classname, ': ', E.Message);
  end;
  Readln;
end.

A:    if myChar in ['A'..'Z'] then
    begin
      // uppercase
    end
   else
      if myChar in ['a'..'z'] then
      begin
        // lowercase
      end
      else
        begin
          // not an alpha char
        end;

..or D2009 on..
   if charInSet(myChar,['A'..'Z']) then
   begin
      // uppercase
   end
   else
     if charInSet(myChar,['a'..'z']) then
     begin
       // lowercase
     end
     else
        begin
          // not an alpha char
        end;

A: Delphi 7 has UpperCase() and LowerCase() functions for strings. There's also UpCase() for characters.
If I want to search for a substring within another string case insensitively, I do this:
if Pos('needle', LowerCase(hayStack)) > 0 then

You simply use lower case string literals (or constants) and apply the lowercase function on the string before the search. If you'll be doing a lot of searches, it makes sense to convert just once into a temp variable.
Here's your case:
a := '2 x 3';  // Lowercase x
b := '9 X 12'; // Upper case X

x := Pos('x', LowerCase(a)); // x = 3
x := Pos('x', LowerCase(b)); // x = 3

To see if a character is upper or lower, simply compare it against the UpCase version of it:
a := 'A';
b := 'b';

upper := a = UpCase(a); // True
upper := b = UpCase(b); // False

A: The JCL has routines for this in the JclStrings unit, eg CharIsUpper and CharIsLower. SHould work in Delphi 7.

A: AnsiPos() is not case-sensitive. You can also force upper or lower case, irrespective of what the user enters using UpperCase() and LowerCase().
Just throwing this out there since you may find it far more simple than the other (very good) answers.


text:
Q: Need to wrap text on an excel 2003 form I created a form in Excel 2003 using a tutorial online but I had a different use case and now have run into a minor problem. I know very little VB and my searches have not produced anything helpful. I have a text input field and it won't wrap the text which would be preferred so the user can see what he/she wrote to prof read or edit before submitting. My guess is this code block requires something to specify that the text should wrap in that text box. Thank you in advance for any help you can provide.
Private Sub txtopportunity_Change()

End Sub

A: You don't have to do this in code. You can set the textbox to always wrap like this:
In Designer mode right click your text box and open it's 'Properties'
One of the peoperties is called 'WordWrap' Set it to True. AND set the 'MultiLine' property to True
If you really need to enable/disable this via VBA it would look something like
    Me.txtopportunity.WordWrap = True
    Me.txtopportunity.MultiLine = True


text:
Q: Passing SqlConnection to class loses its connectionstring after dispose I have following simple class definition (a windows console application):
SAMPLE as Expected
using System;

namespace ConsoleApplication1 {

    class Test: IDisposable {
        string Text;

        public Test(string str) {
            Text = str;
        }

        public void print() {
            Console.WriteLine("Text: " + Text);
        }

        public void Dispose() {
            Text = "";
        }
    }

    class Program {
        static void Main(string[] args) {
            string TeXT = "Data Source=localhost;Initial Catalog=master;";

            using (Test test = new Test(TeXT)) {
                test.print();
            }

            using (Test test = new Test(TeXT)) {
                test.print();
            }

            Console.ReadKey();
        }
    }
}

in above example I pass a string to a IDisposable class test. As soon as code goes out of scope it is disposed. As expected the local variable TeXT is not touched after disposing the test for the first time and it is accessible for second instance of test class the same way it was.
Now here is the real scenario that made me scratch my head for hours.
Actual Result
using System;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApplication1 {

    class Test: IDisposable{
        SqlConnection dbConn;

        public Test(SqlConnection connection){
            dbConn = connection;
        }

        public void print(){
            Console.WriteLine("Connection" + dbConn.ConnectionString);
        }

        public void Dispose() {
            dbConn.Dispose();
        }
    }

    class Program {
        static void Main(string[] args) {
            SqlConnection sqlConn = new SqlConnection("Data Source=localhost;Initial Catalog=master;");

            using(Test test = new Test(sqlConn)){
                test.print();
            }

            using(Test test = new Test(sqlConn)){
                test.print();
            }

            Console.ReadKey();
        }
    }
}

Same as before I pass a SqlConnection to first instance of test class. After disposing the first instance, SqlConnection looses the connection string. which makes it unavailable for next instance of class.
Question
Why in second case I lose ConnectionString? Is this a bug or intentional? Is there any solution to avoid this except making multiple connections to DB Server? should I stop disposing the internal connection instance?
Note
SqlCommand-SqlConnection Using Disposing issue does not answer my question

A: You're disposing of the SqlConection when you dispose of the Test - but you're then trying to use it again.
The best approach is almost always to create a new SqlConnection each time you need one - and dispose of it as soon as you're finished with it. You're already doing the second part, but you should create a new SqlConnection instance for the second operation.
Note that that doesn't mean making multiple connections to the server, necessarily - the .NET connection pool will handle how many actual network connections are needed.

A:
Why in second case I lose ConnectionString?

Because your two examples have very little in common.
In your first class's Dispose() method, you set Text = "";. This will alter the reference that your class holds, but not the reference from Main(), nor its value. So TeXT from Main() will still hold your connection string.
In your second example, you call Dispose() on the same instance, namely the sqlConn you pass from Main().
When you Dispose() an object, this doesn't mean you can't call methods or access properties. What exactly a class does when you dispose it differs per type. For SqlConnection, it apparently sets its ConnectionString property to an empty string, among other things like returning the connection (if any) to the connection pool.


text:
Q: Automating a users web application I want to help users change privacy settings in a third party web application.
My first thought was loading the web application in an iframe and interacting with it via JavaScript. But the same-origin policy would prohibit that.
To avoid the same-origin restriction I could use a web proxy, but I doubt many users would trust logging in.
I could build a browser extension, but that makes it more cumbersome to use and harder to support all browsers.
Any suggestions?

A: You can use OAuth redirect mechanism to support your use case.


text:
Q: Inserting date in database datofreg is of type datetime
my command is
SqlCommand cmd = new SqlCommand("insert into stud(datofreg) values('"+DateTime.Now+"'",conn);

when i execute it says Incorrect syntax near '1/6/2014 12:45:17 AM'.

A: Your problem is you are missing ) at the end of your query but don't use this way..
"insert into stud(datofreg) values('" + DateTime.Now + "')"
                                                        ^^here

You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
For example;
SqlCommand cmd = new SqlCommand("insert into stud(datofreg) values(@date)", conn);
cmd.Parameters.AddWithValue("@date", DateTime.Now);
cmd.ExecuteNonQuery();


text:
Q: Wagatil multi styled paragraph What is the preferred way to achieve a multi style text paragraph (without a fixed structure)?
I was thinking about extending the RichTextField with a b and c classes?

p {
  font-size: 20px;
}

.a {
  font-size: 200%;
  color: red;
  font-wight: bold;
}

.b {
  font-size: 80%;
  color: blue;
}

.c {
  font-size: 140%;
  color: green
}

  Multistyle
  Site
  claim
  are terrible, but necessary.

A: I believe you are looking for a StructBlock. However, I would make sure to ask: what are you using these different colored text fields for? Wagtail might already have a predefined field for your use case, such as a BlockQuoteBlock. If not, you can make your own block.
In your app model, you would add a block class that looks something like this:
class ParagraphBlock(blocks.StructBlock):
    red_paragraph = blocks.TextBlock(required=False)
    blue_paragraph = blocks.TextBlock(required=False)
    green_paragraph = blocks.TextBlock(required=False)

    class Meta:
       icon = 'text'
       # if desired, you can add a block template
       # template = 'paragraph_block.html'

If you need more customization, you can also create a custom template for the block.
See also the answer to this question, which is similar to what you are looking for.


text:
Q: How to add html content generated by json call to page generated html code? I have a page. Which contain json method to load data. I call this method on page load. It works properly. The problem is when I view source of that page I don't see the generated code.
My concern is the search engine will never see the content even if end user see it.
Is there anyway to add it? If so how it can be done?
Here is the example of code I use
    $(function(){

    //Call to the server to get data.

    var content = "Some data"; //from the json call

    $("#content").html(content);

    });

});

A: Most if not all search engines will not recognize content inserted into a page from Ajax/Javascript, this is why you need to load this content with in the page if you want the search engine to recognize it.

A: Your question seems to me a copy of what's asked over here and in Is there anyway of making json data readable by a Google spider?
So, Progressive enhancement and Unobtrusive JavaScript are the way out..
In addition to these, optionally, but importantly, test the crawlability of your app: see what the crawler sees with "Fetch as Googlebot".


text:
Q: Run a process every alternate x hours I have a python script which I am running like this as shown below:
python3 ./bin/abc.py --log_file ./web/prr.log

Now I need to make sure that above process runs after every 3 hours. Below is the flow:

*

*If the process is running already, then kill the process and sleep for 3 hours.

*After sleeping for 3 hours, if process is not running, start the process again by executing above python command and then sleep for three hours.

*Repeat the above process.

So meaning, I need to make sure that my process is running every alternate 3 hours so I need to find a way to kill the process after every 3 hours. I was thinking to use watch command here but not sure how can I use it here. I am working with Ubuntu 14.
Note: I can't modify the python script so I need to do it from outside of it.

A: This seems like an ideal use case for crontab. I'd write 2 bash scripts that run every 3 hours via cron. So something like the following:
#ScriptA.sh
ifProcessRunning
    KillProcess

#ScriptB.sh
ifProcessNotRunning
    StartProcess

#CronTab
0,6,12,18 * * * * ScriptA.sh
3,9,15,21 * * * * ScriptB.sh

For killing the process you can use any normal unix command, so piping a ps aux and running kill within the shell script could work.
Hopefully this helps -- comment if you want me to flesh things out more!

A: You can create a single bash script to get check if the python script is running. If it is, it will kill the script. If not, it will start the script.
#!/bin/bash
if pgrep -f <program name> > /dev/null
    then
         echo "Process is running. Killing"
         kill -9 $(pidof <program name>)
    else
         echo "Process is not running. Starting"
         python <location of the file>
    fi


text:
Q: How to interpret band structures I'm currently taking a Solid State Physics class, and is currently reading about the quantum mechanical description of solids.
I then came across the following figure:

It's supposed to be the band structure for aluminium. My question is basically: How do I interpret these band structures ? I can't even see why they cut of the region from $X$ to $\Gamma$ at the dotted line in the first figure, and not in the second :/ Why is the last bit of $X$ to $\Gamma$ that you see in figure 2, not important in figure 1 ?
I understand that, the $X$, $\Gamma$, $K$, $L$ and $W$ are points of symmetry on the brillioun zone. But what does it mean for the electron(s) ? Only that they have higher energies at some points ?
I'm just having some trouble understanding what this band structure tells me, and what I'm able to see/do with it ?
So can anyone maybe explain it, maybe even easily, what I actually have to understand when I see this ?
Thanks in advance.

A: As you have already stated, the polyeder in the upper part of the figure is plotted in 3D k-space and visualizes the first Brillouin zone. The dotted line nicely visualizes a closed (one-dimensional) path in k-space that -- by convention -- runs through the special points you already mentioned. Now, this closed path is precisely the horizontal axis in the lower part of the figure (this is why it starts and ends with $\Gamma$) and what is plotted in this figure is the energy dispersion $E(\vec{k})$.
As stated in the answer of user D-K, this is done to capture some important features in a 2D plot because we don't know how to conveniently draw a 4D plot on a sheet of paper ;) .

A: To fully present the dispersion relation E(k) needs a 4D space, which cannot be intuitive.
Instead, we can use a 2D band diagram to show the most important features (along high-symmetry directions) of the band structure.
Another way is to give the constant-E isosurfaces, such as Fermi surface. Many such isosurfaces will give you a 3D feeling of what the band structure is like.