text:
Q: VScode automatic indentation & indent guides, and tabulation size (editor.tabSize) I have file using an indentation level of 4 columns, and assuming that a tabulation character corresponds to 8 spaces, like this (I use . to represent a space, and <------> for a tabulation character):
class Foo {
....void bar() {
<------>if (boz) {
<------>....return x;
<------>}
....}
}

This is common for certain coding styles like Oracle coding conventions for Java:

Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).

I'm having trouble rendering this properly with VSCode:

*

*If I set editor.tabSize to 4, then it renders badly as

class Foo {
....void bar() {
<-->if (boz) {
<-->....return x;
<-->}
....}
}

*

*If I set editor.tabSize to 8, then the text is rendered properly, but the indentation guides are incorrect (a guide is missing for the void bar() indentation level):

More importantly, automatic indentation (pressing the "tab" key, or on-the-fly indentation when pressing "return" after a { character) now indents with 8 columns, making the editor barely usable.
An obvious workaround is to use only spaces for indenting, but this is not applicable when opening a pre-existing file.
Is there a way to configure the indentation guides to be displayed every 4 columns, while still rendering tabs every 8 columns?
In the editorconfig cross-editor configuration file specification, this corresponds to the tab_width and indent_size properties, that I would like to be able to change independently.
I'm a former Emacs-user, and this would correspond to tab-width and c-basic-offset for example.

A: The issue mentioned in the comments in 2020, microsoft/vscode issue 10339, has finally been closed in Nov. 2022(!)
PR 155450 enables having separate values for indentation and the display width of tab characters, which is a common requirement of some older projects and/or coding styles.

In addition to adding support for an editor.indentSize property, the indentation options on the status bar have been updated to allow independently configuring editor.indentSize and editor.tabSize.

So:
editor.indentSize: The number of spaces used for indentation or 'tabSize' to use the value from editor.tabSize.
This setting is overridden based on the file contents when editor.detectIndentation is on.
This should be available soon in VSCode Insiders and released with VSCode 1.74 (Nov. 2022).

A: Unfortunately, as of now there is no setting or extension that is based only on (spaces/tabs-at-the-current-tab-size).


text:
Q: Stats test which test of the NULL that a distribution is uniformally distributed I'm looking for a statistical test which tells the probability that a given sample comes from a uniform distribution.
Shapiro test wether a sample comes from a normal distribution. I'm looking a similar test which test wether a sample comes from a uniform distribution.
Thank you

A: You could try a Kolmogorov-Smirnov test of your data against a uniform distribution.

A:
I'm looking for a statistical test which tells the probability that a given sample comes from a uniform distribution.

No frequentist test will tell you that probability.

Shapiro test wether a sample comes from a normal distribution. I'm looking a similar test which test wether a sample comes from a uniform distribution.

Do you mean continuous or discrete uniformity?
Is this a fully specified uniform, or one where the lower and upper limits aren't known (must be estimated)?
There are several suitable tests for fully specified continuous uniformity, including Kolmogorov-Smirnov, Cramer-von Mises and Anderson-Darling. There's also the Neyman-Barton-type Smooth tests (e.g. see Rayner and Best's books and articles on smooth tests). There are other such tests. If you know likely/interesting alternatives, that helps in the choice of test.
If you like the Shapiro-Wilk, it's possible to construct a similar kind of test for uniformity with unspecified bounds.
Alternatively, at the cost of two data points, you can exploit the properties of the uniform distribution to turn the previous fully-specified tests into tests where the bounds on the uniform are unspecified:
If $a=X_{(1)}$ and $b=X_{(n)}$ are the smallest and largest observations, just calculate $U_i = \frac{X_i - a}{b-a}$ for all the observations except you throw out the smallest and largest and test against fully-specified-uniformity on the remaining $n-2$ data values.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I use a prompt's user input to update the page accordingly? Okay so In my last question it said to make my variables into strings which I did but it still doesn't work, as I sad before the point of this is tohave the prompt coe up where a user will set there mood from 1-10. If they pick between 1-3 the image will be sadface, 4-7 neutral face, and 8-10 happy face. but it isn't working the prompt shows up but it still does not work the javascript has been placed within the header:

Waiting...

Please tell me what I'm doing wrong here everything comes with no errors but my output the image stays neutral if some can try this project and test it and prove it works please send me the code.

A: First of all, you're trying to access the DOM (document object model) before the page has loaded, so no HTML is live yet. In other words, you're interacting with a blank page. You'll have to put the script before the  tag (which ensures that all HTML above the


text:
Q: material-table add multiselect to lookup I am using Material-Table to easily manage my data. It is fantastic, but for one feature. With the below code I get a select menu. I would like to have a multiselect menu, so i can save more then one id, ideally an array.
Current Select

Implementation
columns = [
  {
    title: 'Game Systems',
    field: 'gameSystemIds',
    type: 'numeric',
    lookup: {1: "40k", 2: "Fantasy"},
  },
]

<Table
   columns={columns}
   data={allManufacturers}
</>

Is it possible to use a multi select box?

A: Yes, you can simply override the editComponent prop of the columns to render your custom view ( here a multi select) and update the data yourself.
Here is a sandbox on how you could do it.


text:
Q: Display BLOB image from Oracle in Jasper Report I am trying to show image from BLOB data in Jasper Reports.
Database : Oracle 12c
Jasper : Jasper iReport 4.7.1
I follow these steps :

*

*Change the field class of the column fetched from Database .
Field Class = java.io.InputStream

*Add a image in the report and change the expression class to : java.awt.Image
Still doesn't work.
It says that :
Error displaying report page. See the console for details.
Then when I check iReport console it doesn't show anything.
How can I fix this?


text:
Q: _pickedTime.format(context) not working in real device flutter(TimeOfDay to String) I always get this error
Trying to read   from 08:43 at position 6 whenever am converting from TimeOfDay to String using _pickedTime.format(context). It throws the error on my real device but works perfectly on my emulator. How do I solve this error. Below is more codes fo review:
DateTime date = DateFormat.jm().parse(task.startTime.toString());
        var myTime = DateFormat("HH:mm").format(date);
        notificationService.scheduleNotification(
          hour: int.parse(myTime.toString().split(":")[0]),
          minutes: int.parse(myTime.toString().split(":")[1]),
          task: task

Then on my time conversion this:
String _endTime = '9:30PM';
  String _startTime = DateFormat('hh:mm a').format(DateTime.now()).toString();

  _getTimeFromUser({required bool isStartTime}) async {
    var pickedTime = await _showTimePicker();
    String formattedTime = pickedTime.format(context);
    if(isStartTime == true) {
      setState(() {
        _startTime = formattedTime;
      });
    }else if(isStartTime == false) {
      setState(() {
        _endTime = formattedTime;
      });
    }else if(pickedTime == null) {
      debugPrint('Time Cancelled');}
  }

  _showTimePicker() {
    return showTimePicker(context: context,
        initialEntryMode: TimePickerEntryMode.input,
        initialTime: TimeOfDay(
            hour: int.parse(_startTime.split(':')[0]),
            minute: int.parse(_startTime.split(':')[1].split(' ')[0])));
  }


text:
Q: Conditionally match, but without extra space This regex: http://regexr.com/3a9id matches correctly:
create 5 pages
create 5

But it does include an space, like this: " pages".
How can I avoid that space, but also match on create 5?
Using this regex:
/create ([1-9]{1,3})([^\s]|.*)/ig

See: http://regexr.com/3a9ij
Bonus question: how can I make it only work with positive integers? i.e. not match on create 0?

A: Maybe like this:
/create ([1-9]{1,}(?:[0-9]{0,})) ?(.*)/g
Example: http://regexr.com/3a9iv
([1-9]{1,}(?:[0-9]{0,})) Matches a single digit number (from 1 to 9), maybe followed by other digits (to match numbers > 9) in a non-capturing group.
?(.*)
Matches a space if present, followed by anything.

A: create 0*([1-9]\d*) *(.*)

only matches if the number is greater than 0.
regex101 demo.


text:
Q: How do I provide dimensions of an array to be reshaped as a vector variable? I want to reshape the array G in every iteration, and the shape for new dimensions are coming from vector (say) tensorSize. But the MATLAB reshape command does not accept the below given method,
tensorSize = [5,6,7,9,3,4];
r=[1,5,25,225,45,9,1];
G1(1) = {randn(1,tensorSize(1),r(2))};
G1(2) = {randn(r(2),tensorSize(2),r(3))};
G1(3) = {randn(r(3),tensorSize(3),r(4))};
G1(4) = {randn(r(4),tensorSize(4),r(5))};
G1(5) = {randn(r(5),tensorSize(5),r(6))};
G1(6) = {randn(r(6),tensorSize(6),1)};

for j = 1:length(tensorSize)-1
    if j == 1
        G = G1(j);
    end
    G = reshape(G,[],r(j+1));
    H = reshape(G1(j+1),r(j+1),[]);
    G = G*H;
    G = reshape(G,tensorSize(1:j+1),[]);
end

I have also tried to use other alternatives like:
str2num(regexprep(num2str(tensorSize(1:j+1),),'\s+',','))
str2num(strjoin(cellstr(tensorSize(1:j+1)),','))

but they create a string and when converted to num, they are not comma separated. So the reshape option does not accept it.
Is there any work around?

A: Thanks to @beaker in the comment section below, for proposing this solution!
    tensorSize = [5,6,7,9,3,4];
    r=[1,5,25,225,45,9,1];
    G1(1) = {randn(1,tensorSize(1),r(2))};
    G1(2) = {randn(r(2),tensorSize(2),r(3))};
    G1(3) = {randn(r(3),tensorSize(3),r(4))};
    G1(4) = {randn(r(4),tensorSize(4),r(5))};
    G1(5) = {randn(r(5),tensorSize(5),r(6))};
    G1(6) = {randn(r(6),tensorSize(6),1)};
    tensorSizeCell = {zeros(1,length(tensorSize))};

    for i = 1:length(tensorSize)
        tensorSizeCell(i) =  {tensorSize(i)};
    end

    for j = 1:length(tensorSize)-1
        if j == 1
            G = cell2mat(G1(j));
        end
        G = reshape(G,[],r(j+1));
        H = reshape(cell2mat(G1(j+1)),r(j+1),[]);
        G = G*H;
        G = reshape(G,tensorSizeCell{1:j+1},[]);
    end


text:
Q: "case when" going wrong I want to create a column "Cured" that takes value 1 when the customer left have1 either on the day or in the two following days after appearing in have2. Data have1 is a dataset that defines when a client entered and left certain status. have2 shows when the client was contacted.
This is the code I made:
proc SQL;
create table want2 as
select b.*
,     case when b.Outcome = "Answered" or
                b.Outcome = "Answerphone Message Left" or
                b.Outcome = "Answerphone Message Not Left" or
                b.Outcome = "No Answer"
                and
                a.Start_date <= b.Date <= a.End_date
                and
                a.End_date <= b.Date+2
                then 1 else 0 END as Cured

from have1  a, have2 b
where a.ID=b.ID;
quit;

The datasets I'm working with are:
data have1;
infile datalines dlmstr=' | ';
input ID  Start_date :ddmmyy10. End_date :ddmmyy10.;
format date start_date date9.;
datalines;
ID | Start_date | End_date
1  | 01/01/2021 | 03/01/2021
1  | 20/01/2021 | 21/01/2021
2  | 05/01/2021 | 07/01/2021
3  | 10/01/2021 | 30/01/2021
3  | 25/01/2021 | 25/01/2021
;;;
run;

data have2;
infile datalines dlmstr=' | ';
input ID  Date :ddmmyy10. Outcome ;
format Date date9.;
datalines;
ID | Date       | Outcome
1  | 01/01/2021 | Answered
2  | 05/01/2021 | Asnwerphone Message Left
3  | 12/01/2021 | Answerphone Message Left
3  | 25/01/2021 | No Answer
;;;
run;

In this case I should get the following:
ID | Date       | Outcome                   | Cured
1  | 01/01/2021 | Answered                  | 1
2  | 05/01/2021 | Asnwerphone Message Left  | 1
3  | 12/01/2021 | Answerphone Message Left  | 0
3  | 25/01/2021 | No Answer                 | 1

ID1 cured because he left have1 2 days after 01/01
ID2 also cured because they left have1 2 days after 05/01
ID3 didn't cure because they left have1 more than 15 days after 12/01
ID3 cured because they left have1 on the same day
This is the result with that code:
ID| Date      | Outcome  | Cured
1   01JAN2021   Answered    1
1   01JAN2021   Answered    0
2   05JAN2021   Asnwerph    0
3   12JAN2021   Answerph    0
3   25JAN2021   No Answe    0
3   12JAN2021   Answerph    0
3   25JAN2021   No Answe    1

Which is not right: first of all it duplicates observations, but it doesnt accurately selects those that should be 1 in Cured (ID 2).
Any idea what might be wrong/missing?

A: I suspect that you want:
select b.*,
       (case when b.Outcome in ('Answered', 'Answerphone Message Left',
 'Answerphone Message Not Left', 'No Answer') and
                  a.Start_date <= b.Date and
                  b.Date < a.End_date and
                  a.End_date <= b.Date+2
             then 1 else 0
        end) as Cured

I also wonder if you really want a Cartesian product.  Usually, you would want join with a specific join condition.

A: In any programming code (beyond SAS and SQL), whenever you use OR with AND, always separate conditions with parentheses:
CASE
   WHEN (b.Outcome = "Answered" OR
         b.Outcome = "Answerphone Message Left" OR
         b.Outcome = "Answerphone Message Not Left" OR
         b.Outcome = "No Answer")
        AND
        (a.Start_date <= b.Date < a.End_date)
        AND
        (a.End_date <= b.Date+2)
   THEN 1
   ELSE 0
 END AS Cured

Better yet, use IN operator for collection of values and avoid need of OR:
CASE
   WHEN b.Outcome IN ("Answered",
                      "Answerphone Message Left",
                      "Answerphone Message Not Left",
                      "No Answer")
        AND
        a.Start_date <= b.Date < a.End_date
        AND
        a.End_date <= b.Date+2
   THEN 1
   ELSE 0
 END AS Cured

A: Sounds like you want to GROUP the results and set CURED=1 if ANY of the end dates for that ID meet your criteria.  So use the MAX() aggregate function.
I am not sure why you are testing the values of OUTCOME since there are no values in your example that are not included in your list of values to test for.
data have1;
  input ID  Start_date :yymmdd. End_date :yymmdd.;
  format Start_date End_date yymmdd10.;
datalines4;
1 2021-01-01 2021-01-03
1 2021-01-20 2021-01-21
2 2021-01-05 2021-01-07
3 2021-01-10 2021-01-30
3 2021-01-25 2021-01-25
;;;;

data have2;
  input ID  Date :yymmdd. Outcome $40.;
  format Date yymmdd10.;
datalines4;
1 2021-01-01 Answered
2 2021-01-05 Answerphone Message Left
3 2021-01-12 Answerphone Message Left
3 2021-01-25 No Answer
4 2021-01-25 No Answer
;;;;

proc SQL;
create table want2 as
select b.id
     , b.date
     , b.outcome
     , max(
         case when (a.Start_date <= b.Date <= a.End_date)
               and (a.End_date <= b.Date+2) then 1
         else 0
       end
       ) as Cured
from have1 a
 right join have2 b
 on a.id=b.id
group by b.id,b.date,b.outcome
;
quit;

Result:
Obs    ID          Date    Outcome                     Cured

 1      1    2021-01-01    Answered                      1
 2      2    2021-01-05    Answerphone Message Left      1
 3      3    2021-01-12    Answerphone Message Left      0
 4      3    2021-01-25    No Answer                     1
 5      4    2021-01-25    No Answer                     0

PS Displaying dates in D-M-Y or M-D-Y order will just confuse half of your audience.

A: Complex logic generally needs parentheses to properly group expressions.
The SQL logic operator AND has precedence over OR
A linearly coded logic statement such as
P OR Q or R OR S AND X AND Y AND Z

evaluates as
P or Q or R or (((S and X) and Y) and Z)

and generally needs to be corrected to
(P OR Q or R OR S) AND X AND Y AND Z

As stated by @Parfait, you can use IN operator when P Q R S are all expressions dealing with matching a single character variable with a number of different terms.  Use IN: to match term prefixes.


text:
Q: canWrite() to SD returns false When I use a debugger, the sd.canWrite() statement returns false and doesn't run the rest of the code. I tried it with an emulator and an actual samsung tablet.
I have
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

in my manifest.
public void exportDatabse(String databaseName) {
        try {
            File sd = Environment.getExternalStorageDirectory();

            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
                String backupDBPath = "backupname.db";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);
                Log.d("file", "file copied2");

                if (currentDB.exists()) {
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    FileChannel dst = new FileOutputStream(backupDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
                Log.d("file", "file copied3");
            }
        } catch (Exception e) {
            Log.d("file", "file not copied");

        }
        Log.d("file", "method runs");
    }

A: Please check if the External storage is write protected -
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {

}

A: If You are using A Emulator or System running on  Android 6.0 or Above You have to Add Run Time Permission for Critical or Dangerous Permissions
Make sure that your activity implements OnRequestPermissionResult . Then Do
boolean permission = isStoragePermissionGranted();
if(permission){
     //DO YOUR TASK HERE
}

public  boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG,"Permission is granted");
            return true;
        } else {
            Log.v(TAG,"Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    }
    else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG,"Permission is granted");
        return true;
    }
}

Callback Function
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}

Refer This to know more


text:
Q: TokenMismatchException during AJAX polling in Laravel In my Laravel application, I have a notification system. This is run using AJAX polling techniques (i.e. a ajax post function is run every 5 seconds or so) similar to:
$.ajaxSetup({
    headers: {
        'X-CSRF-Token': CSRF_TOKEN
    }
});

(function pollForNewNotifications() {
    setTimeout(function () {
        $.ajax({
                type: 'POST',
                url: 'http://example.com/get-notifications',
                dataType: 'json',
                data: {
                    // data that is sent
                },
                success: function (data) {
                    // add new notifications if data is not empty logic
                    pollForNewNotifications();
                }
            })
            .fail(function (xhr, status, err) {
                console.error(xhr.responseText)
            });
    }, 5000);
})();

Now this works most of the time.
However, the issue is that I sometimes find that over long period of inactivity I get a TokenMismatchException in VerifyCsrfToken.php error and automatically logged out.
I believe that this is the case because the CSRF token changes or longer is valid (I may be wrong).
How can I solve this issue?

A: Change the session's lifetime:
https://github.com/laravel/laravel/blob/a282304/config/session.php#L32

A: You can remove token check to this particular url so it can make request without checking csrf token. Go to app/Http/Middleware/VerifyCsrfToken.php
place this
protected $except = [
   'get-notifications',
];


text:
Q: Why the argument of recursive code in 8th line is 'string[:i] + string[i + 1:]' but not 'string' It's about a permutation problem. I tried to understand the code below but feel a little confusing finally.
Why the argument of  recursive code in 8th line is 'string[:i] + string[i + 1:]' but not 'string'.
I know that 'string' argument to recursive will return RuntimeError.
But why?
permutation link: https://www.codewars.com/kata/permutations/python
def permutations(string):
    result = set([string])
    if len(string) == 2:
        result.add(string[1] + string[0])
    elif len(string) > 2:
        for i, c in enumerate(string):
            print "1.c = %s and i is %d"%(c,i)
            for s in permutations(string[:i] + string[i + 1:]):
                print "2.string[:i] + string[i + 1:] is %s and i is %d"%((string[:i] + string[i + 1:]),i)
                result.add(c + s)
                print "3.result is %s"%result
    return list(result)

A: Note that string[a:b] means a [a b) (including a and excluding b) substring of the string. So string[:i] + string[i + 1:] means the whole string without ith character.


text:
Q: How to convert .mp4 video file to .yuv (YUV420) and vice-versa using FFmpeg and subprocess module in python? I have to convert a .mp4 video file to .yuv (YUV420) and vice versa in my python program. How do you do this using FFmpeg and subprocess module in python?

A: Try this:
from subprocess import Popen

# create command to use ffmpeg to convert mp4 to yuv
cmd = ['ffmpeg', '-i', 'video.mp4','video.yuv']
# execute command in "shell"
process = Popen(cmd, shell=True)

Explaination in code comment.
Make sure FFMPEG is added to your system PATH or else call by its path i.e.
from subprocess import Popen

# create command to use ffmpeg to convert mp4 to yuv
cmd = ['C:/ffmpeg/bin/ffmpeg', '-i', 'video.mp4','video.yuv']
# execute command in "shell"
process = Popen(cmd, shell=True)

As @llogan mentioned to convert from yuv to mp4 use:
cmd = ['ffmpeg', '-video_size', '1280x720', '-pixel_format', 'yuv420p', '-framerate', '25', '-i', 'video.yuv', 'output.mp4']


text:
Q: Trying to set up admob in Android Studio I have been following this tutorial here:
Android Studio - Importing external Library/Jar
I downloaded the jar and placed it in my lib folder for my project. I then added this line to my build.gradle:
compile files('libs/android-support-v4.jar', 'libs/GoogleAdMobAdsSdk-6.4.1.jar')

So my whole build.gradle file now looks like this:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
        compile files('libs/android-support-v4.jar', 'libs/GoogleAdMobAdsSdk-6.4.1.jar')
    }
}
apply plugin: 'android'

dependencies {
}

android {
    compileSdkVersion 17
    buildToolsVersion "17"

    defaultConfig {
        minSdkVersion 11
        targetSdkVersion 17
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        instrumentTest.setRoot('tests')
    }
}

I then did a build->rebuild project and I got this error:
Gradle: A problem occurred evaluating root project 'freeBP'.
> No signature of method: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.compile() is applicable for argument types: (org.gradle.api.internal.file.collections.DefaultConfigurableFileCollection) values: [file collection]
  Possible solutions: module(java.lang.Object)

Any ideas what I might be doing wrong, so I can get ads to work in my free version of my app?

A: I think you're declaring the dependency in the wrong place. Try with this:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.7.+'
    }
}
apply plugin: 'android'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17"

    defaultConfig {
        minSdkVersion 11
        targetSdkVersion 17
    }
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        instrumentTest.setRoot('tests')
    }
}

A: Try to follow the Following steps:-
1) Check in the Sdk extras the Goolgle Play Service and Google repository is installed or not if not the install it.
2) Now make new Project and go to File->Project Structure->Dependencies->(+)com.google.android gms:play-service-ads:7.5.0
3) Go to Gradle Script and edit build.gradle(Module: app) this should look like this->
apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.example.lalit.firsttest"
        minSdkVersion 15
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
    compile 'com.google.android.gms:play-services-ads:7.5.0'
}

4) Now change the Manifest File-->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lalit.firsttest" >
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <activity
            android:name=".Login"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

5) Now go to Tools->Android->sync project with gradle files..
    hope this should work....


text:
Q: Maximum flow in graph whose vertices are all subsets of set $\{1,..,k\}$ Let $N$ be a net whose vertices are all subsets of set $\{1,..,k\}$ and an egde connect only these two subsets that differ in exactly one element. If this element is $x$ then this edge has capacity $2^x$ and is directed to the bigger subset. Find maximum flow from the source $z=\emptyset$ to the sink $s=\{1, . .  , k\}$.
I know that the number of vertices is $2^k$ and every path from source to sink is$k$ long. On every of these paths there is an edge with capacity $2^1,..,2^k$.
The answer is that the maximum flow equals $2^k$ but I don't know how to come to this solution
The idea is to prove it by induction of $k$ but I don't know how. Help will be
appreciated.$k=2,3$ with capacity of edges">

A: To prove that more than $2^k$ is impossible, it suffices to find a cut with that capactiy. Let $S$ be the set of vertices whose subset does not contain $1$, and let $T$ be the vertices who do contain $1$. There are $2^{k-1}$ edges from $S$ to $T$, each with capacity $2^1$, so the capacity is $2^k$.
To prove that $2^k$ is possible, it suffices to find a flow. Here is the basic idea. You have $2^k$ units of stuff at the source, $\varnothing$. Send half of that to $\{k\}$. Now there is $2^{k-1}$ at $\varnothing$ and $2^{k-1}$ at $\{k\}$. Next, recursively send the $2^{k-1}$ at $\varnothing$ to $\{1,2,\dots,k-1\}$, and recursively send the $2^{k-1}$ at $\{k\}$ to $\{1,2,\dots,k-1,k\}$. Finally, reunite the two halves by sending the $2^{k-1}$ at $\{1,2,\dots,k-1\}$ to $\{1,2,\dots,k\}$.


text:
Q: Using an UltraSharp 27 4K USB-C Monitor: U2720Q display with a Insprion 5579 Can I simply plug the USB-C cable of a UltraSharp 27 4K USB-C Monitor: U2720Q into a Insprion 5579 USB 3.0 Type A port with and adapter and use all of the display features except PD? Or alternatively Just use the connected USB Devices and connect video over HDMI?

A: For passing display through USB you need USB Alternate Mode.
This is defined by Wikipedia
as:

An Alternate Mode dedicates some of the physical wires in a USB-C 3.1 cable for direct device-to-host transmission of alternate data protocols.

The answer is negative : You need USB-C 3.1 on both ends, but you don't have it
on even one of the two.

A: No, you cannot. USB-C DisplayPort Alt Mode output is only possible with USB-C. You indicate you have a type A connector. Of course, a USB-C port still has to support it. The port being USB-C is not enough.
USB should work though, since the monitor has no other USB upstream port.


text:
Q: Incorrect output. C++ primer 1.4.4 the following program is supposed to count the number of times a user inputs a integer. example: user inputs 42 42 10 10. the program is supposed to out put : 42 occurs 2 times, 10 occurs 2 times.
the problem: the code will not output the last result for the number 10 until you input another number. i have pasted the code below. this code comes from c++ primer. 1.4.4
#include <iostream>
int main()
{
    // currVal is the number we're counting; we'll read new values into val
    int currVal = 0, val = 0;

    // read first number and ensure that we have data to process
    if (std::cin >> currVal)
    {
        int cnt = 1;  // store the count for the current value we're processing

        while (std::cin >> val)
        { // read the remaining numbers

            if (val == currVal)   // if the values are the same
                ++cnt;            // add 1 to cnt
            else
            { // otherwise, print the count for the previous value
                std::cout << currVal << " occurs " << cnt << " times" << std::endl;
                currVal = val;    // remember the new value
                cnt = 1;          // reset the counter
            }

        }  // while loop ends here

        // remember to print the count for the last value in the file
        std::cout << currVal <<  " occurs " << cnt << " times" << std::endl;
    } // outermost if statement ends here

    return 0;
}

A: Your program as-written appears correct for a series of numeric inputs separated by whitespace.
You need to give an end-of-file indication to the program so that it will exit the while loop and print the count for the final data.  In Windows, you can do that by entering [Ctrl]-[Z] as the first character on a new line.  In Linux, UNIX and Mac OS X, [Ctrl]-[D] serves a similar purpose.
Alternately, you can put your set of values into a text file and use redirection to feed your program.  Suppose, for example, you put your data in a file named data.txt in the same directory as your executable.  In a terminal window, you can run your program as follows:
myprogram < data.txt

As some others have noted, a non-numeric input will also work in place of end of file.  For example, you could enter 42 42 10 10 fred, and it'll output what you expect as well.  That doesn't appear to be the intent of the program, though.  For example, if you input 42 42 10 10 fred 37, the program stops at fred and won't see 37.


text:
Q: Export hardware specifications to a spreadsheet for Windows Server I have a bunch of servers : Windows 2003 and 2008. I just wanted to export these hardware specs to a spreadsheet:
cpus : num processors, clock speed, etc
total hard disk space
total used disk space
computer model
I started writing a script to do this via diskpart, systeminfo, and wmic. But before I get too crazy and reinvent the wheel, just wondering if someone knows of a powershell, vb script, or something else that could do this.

A: Couple of options via VBS or PS, can be easily found of the net.
http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/
http://www.powershellpro.com/powershell-forum/hardware/computer-inventory-script/


text:
Q: CartoDB, problem with infowindows When I share my CartoDB-map, in other words,  use the link to my map, I can't get the info windows to appear. It says "there has been an error..." Why? How can i fix this?

A: If you're connected to the Internet behind a proxy/firewall, it's probable that the infowindow requests are being blocked. In these cases, I recommend you to access your visualization by using HTTPS instead of HTTP, which usually solves the issue.


text:
Q: Replace last newline character in file with a semicolon I have taken a dump of a mysql table, and I'm appending several create tables in a row - only problem is there is no semi-colon at the end of each create table.
What I'd like to do is as I capture each individual "show create table" is replace the very last "\n" with a ;
Can someone please suggest how I do this?
#!/bin/bash

> master_file.sql
> tmp.sql

while read line
do
    mysql --skip-column-names -u root -pxxxxxxxxxx test -e "show create table $line" > tmp.sql
    sed -i 's/\\n/\n/g' tmp.sql
    #echo ';' >> tmp.sql
    cat tmp.sql >> master_file.sql
    echo "" >> master_file.sql
done < table_list

My output is as follows:
hours   CREATE TABLE `hours` (
) DEFAULT CHARSET=latin1
;

user_session_view       CREATE TABLE `user_session_view` (
) DEFAULT CHARSET=utf8
;

The semicolon should be immediately to the right of "latin1" or "utf8" in this case, but it isn't.

A: Taking advantage of the fact that "process substitution" removes last newline:
printf %s "$(< tmp.sql);" > tmp2.sql

In your case, you can combine sed and this:
printf %s "$(< tmp.sql);" | sed 's/\\n/\n/g' >> master_file.sql

Note that the output file should be different than the input file.

A solution with awk could be:
awk 'NR>1 {print l} {l=$0} END{ORS=""; print($0 ";")}' tmp.sql >> master_file.sql

A: You can do something with sed
test.txt
create table (
) default charset=latin1

create table (
) default charset=utf8

test

sed and result
sed -r 's|(charset=)(.*)|\1\2;|g' test.txt > newtest.txt

cat newtest.txt

create table (
) default charset=latin1;

create table (
) default charset=utf8;

test


text:
Q: CSS z-index not working I created a user hovercard but i have z-index problem.
If you can check this demo then you can see there are tree avatar = DEMO
So hover over any image then hovercar will open but Hovercard is far below the picture below. How can i fix it anyone can help me here ?

CSS
.summary-mask {
    margin: 50px auto 0;
    width: 50px;
    height: 50px;
    position: relative;
    z-index: 1;
}
.loaded .summary-mask {
    z-index: -1;
}
.profile-ava {
    width: 50px;
    height: 50px;
    background-image: url(http://gravatar.com/avatar/3913c4e14034c0a7f28db2c632290c21?s=80);
    border-radius: 3px;
    background-size: 50px 50px;
    display: block;
}
.summary a:hover:before {
    content:'';
    position: absolute;
    display: block;
    bottom: -10px;
    left: 0;
    height: 10px;
    width: 100%;
    z-index: 2;
}
.p-tooltip {
    position: absolute;
    margin-top: 10px;
    top: 100%;
    left: 50%;
    margin-left: -140px;
    width: 280px;
    max-height: 120px;
    border-radius: 5px;
    overflow: hidden;
    background-color: #F0F0F0;
    visibility: hidden;
    opacity: 0;
    transition: all 0.5s ease;
}

A: This should work:
http://jsfiddle.net/sw4ev8b4/14/
Remove all the fancy z-index styling you have in there and just add a positive z-index z-index:999; to your tooltip:
.summary {
    margin: -50px auto 0;
    width: 50px;
    height: 50px;
    position: relative;
}
.summary-mask {
    margin: 50px auto 0;
    width: 50px;
    height: 50px;
    position: relative;
}
.p-tooltip {
    position: absolute;
    margin-top: 10px;
    top: 100%;
    left: 50%;
    margin-left: -140px;
    width: 280px;
    max-height: 120px;
    border-radius: 5px;
    overflow: hidden;
    background-color: #F0F0F0;
    visibility: hidden;
    opacity: 0;
    transition: all 0.5s ease;
    z-index:999;
}


text:
Q: '\0' evaluates false, "\0" evaluates true Inspired by a program described in K&R section 5.5:
void strcpy(char *s, char *t)
{
    while(*s++ = *t++);
}

C program
if ('\0') { printf("\'\\0\' -> true \n"); }
else      { printf("\'\\0\' -> false\n"); }

if ("\0") { printf("\"\\0\" -> true \n"); }
else      { printf("\"\\0\" -> false\n"); }

prints
'\0' -> false
"\0" -> true

Why do '\0' and "\0" evaluate differently in C?

clang version 3.8.0

A: First of all, you need to keep in mind that in C,

*

*Zero is false and non-zero is true.

*For pointer types, NULL is false and non-NULL is true.

'\0', as others have said, is the same as the integer literal 0 and hence is false (See first bullet point above to know why).
"\0" is a string literal that contains two \0 characters (One which you have explicitly added and the other, which is implicit and will be added by the compiler). The string literal will be stored somewhere in read-only memory. When you use "\0", it gets converted to a pointer to its first element†. This is commonly referred to as "array decay". (This is the reason why stuff like char* str = "string"; works).
So, you are effectively checking the address of the first character of the string literal. Since the address of the string literal will always be non-NULL, the if will always be true (See second bullet point above to know why).

†: This "decay" of arrays does not always happen. See Exception to array not decaying into a pointer?

A: First, looking at the two conditions, '\0' is a constant of type integer, which denotes the null character C, which is the same as 0. While "\0" is a string literal, which contains 2 bytes, the one specified and the null terminator byte implicitly added. Being a string literal, the pointer cannot be NULL.
Second, in C, for the condition of if statement, everything non-zero is evaluated as true, and zero is evaluated as false.
According to this rule, it will be clear that '\0' is false, and "\0" evaluated as true.

A: First of all, please note that the hexadecimal value of False is 0x00 and True is any other value than 0x00.
"\0" is a string with a character and Null Terminator '\0' at the end. So it is a character pointer, pointing to an array of 2 bytes: ['\0', '\0']. In this array, the first one is the character and the other one is the null terminator.
After compiling (without optimizing), this character pointer is temporarily assigned to an address in the memory pointing to the first byte of these two bytes. This address might be, for example, 0x18A6 in hexadecimal. So the compiler (most of them) actually writes these two values to the memory. Because a string is actually the address of the first byte of that string, our expression is interpreted as 0x18A6 != false . So, it is clear 0x18A6 != 0x00 is True.
'\0' is simply 0x00 in hexadecimal. 0x00 != 0x00 is False.
This answer is written for 8-bit data architecture with 16-bit addressing. I hope that helps.

A: '\0' is a number: 0, so it is evaluated as false (0 = false, !0 = true).
But "\0" is a pointer to a read-only section where the actual string is stored, the pointer is not NULL ergo it's true.

A: Recall how string literals work in C - "\0" is a character array containing two zero bytes (the one you asked for, and the implicit one at the end). When evaluated for the if test, it decays into a pointer to its first character. This pointer is not NULL, so it's considered true when used as a condition.
'\0' is the number zero, equivalent to just 0. It's an integer which is zero, so it's considered false when used as a condition.

A: '\0' is a null character which has the value of 0. It is used to terminate a string of characters. So it's consider false.
"\0" is a null or empty string. The only character in the string is the null character which terminates the string.So it's consider true.

A: '\0' is a char that is equal to number zero. "\0" is a string and we usually add '\0' at the end of a string. Don't use '\0' or "\0" in a conditional statements because it's quite confusing.
The following usage is suggested:
if (array[0] != 0)
{

}

if (p != 0)
{

}

if (p != NULL)
{

}

A: Check out this with examples..
#include <stdio.h>

int main()
{
printf( "string value\n" );

//the integer zero
printf( "0.........%d\n" , 0 );

//the char zero, but chars are very small ints, so it is also an int
//it just has some special syntax and conventions to allow it to seem
//like a character, it's actual value is 48, this is based on the
//ASCII standard, which you can look up on Wikipedia
printf( "'0'.......%d\n" , '0' );

//because it is an integer, you can add it together,
//'0'+'0' is the same as 48+48 , so it's value is 96
printf( "'0'+'0'...%d\n" , '0'+'0' );

//the null terminator, this indicates that it is the end of the string
//this is one of the conventions strings use, as a string is just an array
//of characters (in C, at least), it uses this value to know where the array
//ends, that way you don't have to lug around another variable to track
//how long your string is. The actual integer value of '\0' is zero.
printf( "'\\0'......%d\n" , '\0' );

//as stated, a string is just an array of characters, and arrays are tracked
//by the memory location of their first index. This means that a string is
//actually a pointer to the memory address that stores the first element of
//the string. We should get some large number, a memory address
printf( "\"0\".......%d\n" , "0" );

//a string is just an array of characters, so lets access the character
//in position zero of the array. it should be the character zero, which
//has an integer value of 48
printf( "\"0\"[0]....%d\n" , "0"[0] );

//and the same thing for the empty string
printf( "\"\\0\"[0]...%d\n" , "\0"[0] ); //equal to '\0'

//we also said a string is just a pointer, so we should be able to access
//the value it is pointing to (the first index of the array of characters)
//by using pointers
printf( "*\"0\"......%d\n" , *"0" );

return 0;
}

A: The simple thing is ATLEAST 0 (int) and 0.0 (float or double) have FALSE value in C.
'\0' is integer 0.
"\0" is an array of characters. It does not matter that INSIDE the array how many Characters are there or what are those characters.
So, '\0' evaluates to 0 like 77-77 evaluates to 0.
And 0 is false.
int x;
x = '\0';
printf("X has a value : %d");

Output:

x has a value : 0
And the code:
if(0){printf("true");}

else{printf("false");}

Output:

false


text:
Q: How to delete files via FTP when directory has over 100,000 files? I went to upload a new file to my web server only to get a message in return saying that my disk quota was full...  I wasn't using up my allotted space but rather my allotted FILE QUANTITY. My host caps my total number of files at about 260,000.
Checking through my folders I believe I found the culprit...
I have a small DVD database application (Video dB By split Brain) that I have installed and hidden away on my web site for my own personal use. It apparently caches data from IMDB, and over the years has secretly amassed what is probably close to a MIRROR of IMDB at this point. I don't know for certain but I did have a 2nd (inactive) copy of the program on the host that I created a few years back that I was using for testing when I was modifying portions of it. The cache folder in this inactive copy had 40,000 files totalling 2.3GB in size. I was able to delete this folder over FTP but it took over an hour. Thankfully it also gave me some much needed breathing room.
...But now as you can imagine the cache folder for the active copy of this web-app likely has closer to 150000 files totalling about 7GB worth of data.
This is where my problem comes in... I use Flash FXP for my FTP client and whenever I try to delete the cache folder, or even just view the contents it will sit and try to load a file list for a good 5 minutes and then lose connection to the server...
my host has a web based file browser and it crashes when trying to do this... as do free online FTP clients like net2ftp.com. I don't have SSH ability on this server so I can't login directly to delete either.
Anyone have any idea how I can delete these files? Is there a different FTP program I can download that would have better success... or perhaps a small script I could run that would be able to take care of it?
Any help would be greatly appreciated.

A:
Anyone have any idea how I can delete
  these files?

Submit a support request asking for them to delete it for you?

A: It sounds like it might be time for a command line FTP utility.  One ships with just about every operating system.  With that many files, I would write a script for my command-line FTP client that goes to the folder in question and performs a directory listing, redirecting the output to a file.  Then, use magic (or perl or whatever) to process that file into a new FTP script that runs a delete command against all of the files.  Yes, it will take a long time to run.
If the server supports wildcards, do that instead and just delete ..
If that all seems like too much work, open a support ticket with your hosting provider and ask them to clean it up on the server directly.
Having said all that, this isn't really a programming question and should probably be closed.

A: We had a question a while back where I ran an experiment to show that Firefox can browse a directory with 10,000 files no problem, via FTP.  Presumably 150,000 will also be ok.  Firefox won't help you delete, but it might be helpful in capturing the names of the files you need to delete.
But first I would just try the command-line client ncftp.  It is well engineered and I have had good luck with it in the past.  You can delete a large number of files at once using shell patterns.  And it is available for Windows, MacOS, Linux, and many other platforms.
If that doesn't work, you sound like a long-term customer---could you beg your ISP the privilege of a shell account for a week so you can remote login with Putty or ssh and blow away the entire directory with a single rm -r command?

A: If your ISP provides ssh access, you can use one rm command to remove the files.
If there is no command line access, you can have a try with some powerful FTP client like CrossFTP. It works on win, mac, and linux. When you select to delete the huge amount of files on your server, it can queue in the delete operations, so that you don't need to reload the folder again. When you restart CrossFTP, the queue can also be restored and continued.


text:
Q: python smtp not setting subject/html for some reason the following code does not set the Subject field properly, and certainly does not render the email in HTML... ie, the  and  tags are gone when email is received.
Thanks!
def sendEmail (self,remove):

        message = """From: From Postmaster <%s>
        To: To Person <%s>
        MIME-Version: 1.0
        Content-type: text/html
        Subject: blahblah
        This is HTML message.

The following email addresses have been removed

        %s
        """ %(self.sender,self.receivers,remove)

        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(self.sender, self.receivers, message)
        print "Successfully sent email"

A: MIME has specific rules for how whitespace is handled in its headers. In particular, lines that begin with whitespace are treated as continuation lines for the previous header. In your example, since each line (after the first) begins with whitespace, all of the content will be treated as the value of the From header. In addition, as @TokenMacGuy pointed out MIME requires a blank line between the headers and the payload of the message. If you reformat your message follows, it should be interpreted correctly:
message = """From: From Postmaster <%s>
To: To Person <%s>
MIME-Version: 1.0
Content-type: text/html
Subject: blahblah

This is HTML message.

The following email addresses have been removed

%s
""" %(self.sender,self.receivers,remove)

Should address the problems you're seeing.
Alternatively, you could use the email package and avoid managing the format of the message yourself:
import email.mime.text

message = """
This is HTML message.

The following email addresses have been removed

%s
""" % remove
message = email.mime.text.MIMEText(message, 'html')
message['From'] = 'From Postmaster <%s>' % sender
message['To'] = 'To Person <%s>' % receivers[0]
message['Subject'] = 'blahblah'

A: From the docs: "Here's an example of how to create an HTML message with an alternative plain text version:" http://docs.python.org/library/email-examples.html#id5


text:
Q: Check if any property in a object is empty I have the following function in a class:
public function __construct()
    {
        $this->api_url = env('SUPRE_API');
        $this->token = env('SUPRE_TOKEN');
        if($this->api_url == null || $this->token == null){
            throw new \Exception("Could not gather the Token or URL from the .env file. Are you sure it has been set?");
        }
    }

However I would like to check if any property in the $this object is empty in a dynamic way, without using an If, considering this will have more properties later.

A: You can iterate over $this and throw your exception on first empty property found:
public function __construct()
{
    $this->api_url = env('SUPRE_API');
    $this->token = env('SUPRE_TOKEN');

    foreach ($this as $key => $value) {
        if ($value == null) {
            throw new \Exception("Could not find {$key} value. Are you sure it has been set?");
        }
    }
}


text:
Q: Complex values of the cube root I just learned that the cube root has 2 complex roots. For example, the cube root of 8 has : 2 , -1 plus or minus square root of 3 *i
I was wondering, how do you find those conjugate complex values ??? Is the method the same for all odd roots? Thankyou!

A: Whilst its certainly true that you see more structure if you pursue a "modulus and argument" approach to this sort of question, a more primitive methodology is also possible.
Let $(a+ bi)^3 = 8$ where $a, b\in \mathbb{R}$. Now, $$(a+ bi)^3 = a^3 + 3a^2bi + 3ab^2 i^2 + b^3 i^3 = (a^3 - 3ab^2) + (3a^2 b -b^3)i = 8 + 0i.$$
Equating imaginary parts, we have $b(3a^2 - b^2) = 0$. So we have two cases: either $b=0$, the root is real, and $(a+bi)^3 = a^3 = 8$, so $a = 2$; or $3a^2 = b^2$, $b = \pm \sqrt{3} a$, $a^3 -9a^3 = -8a^3 = 8$ and $a = -1$. So the roots are $2, -1 +\sqrt{3}$ and $-1-\sqrt{3}$.
Now, like I said, there are more structurally informative techniques, but sometimes just banging on with the techniques you already have can get you the answers you seek. I'd recommend doing some more calculations yourself before you dive into the whole "modulus and argument" deal. You'll get a stronger feel for the domain, and be more confident in finding things out for yourself.

A: Using Euler's formula, any complex number can be written in the form
$$ x+iy = r\cos{\theta}+ir\sin{\theta} = re^{i\theta}. $$
Any complex number of the form
$$ z_k = a^{1/n} e^{2\pi i k/n}, $$
where $k$ is an integer, is an $n$th root of a real number $a$, because
$$ (a^{1/n}e^{2\pi i k/n})^n = ae^{2\pi i k} = a. $$
Then Euler's formula tells you that the real and imaginary parts of $z_k$ are
$$ a^{1/n} \cos{(2\pi k/n)}, \quad a^{1/n} \sin{(2\pi k/n)}, $$
respectively.

A: Complex roots come in pairs, so if $z$ is a root then $\bar{z}$ is another root (where $\bar{z}$ is the complex conjugate of $z$). In general, you can obtain all the roots of a rational number by multiplying by powers of the primitive roots of unity $\zeta^i$, keeping in mind that $\zeta^n = 1$ where $n$ is the root you are considering. For example $x^3 - 2 = 0$ has three solutions, $x = 2^{\frac{1}{3}}$ (the real root), $\zeta 2^{\frac{1}{3}} $ and $\zeta^2 2^{\frac{1}{3}}$. I'm not sure how much you know about complex numbers but the primitive $n$-th root of unity can be expressed in terms of the exponential as $e^{\frac{2ki\pi}{n}}$, where $1 \le k < n$.


text:
Q: How to get Google contact images with Google contacts API? Working with Google contacts API using Node.js
I am getting all the contacts except images by Google feed API
https://www.google.com/m8/feeds/photos/media/faizy04%40gmail.com/ya29.ZAFTNcQ6sEue40gFqH5h8h91k8LO8Bwvf50NUgQKKmsD5fipWg9XvN5GeHmyref_TK1xJZVrB9Ubuw
For getting contacts I have passed the following scope with passport.js
passport.authenticate('google', { scope : ['profile', 'email','https://www.google.com/m8/feeds'] })
everything is working fine.
Now I want to get all the images of related contacts.
Do I need to pass something else with parameter in scope variable Or Need to send another GET  request for that?

A: You need to send one authenticated GET request for each contact image that you want to retrieve. The contacts image endpoint is in the same authorization scope as the one used to get contacts.
For more information, refer to: Retrieving a contact's photo in the API docs.


text:
Q: IsAuthenticated is true but HttpContext.Current.User.Identity.IsAuthenticated is False We are trying to implement Single sign on (sso) using SAML 2.0 using ADFS with our customer site.I have successfully set up ADFS and when i access ../adfs/ls/idpinitiatedsignon.aspx page it shows "Sign in to this site" radio button and it redirect to customer site and asks for Username and password and once entered customer's site user name and password then it brings back to idpinitiatedsignon.aspx and says "You are signed in" and shows sign out button.But i'm unable to get the logged in user's details from HttpContext.Current.User in idpinitiatedsignon.aspx because HttpContext.Current.User.Identity.IsAuthenticated is false but IsAuthenticatedis true. So how can i get the logged in user information ?

A: Because when you call FormsAuthentication.SetAuthCookie(txtUsername.Value, true); you store the key on the client's cookies. For this you need to do a response to the user. And for HttpContext.Current.User.Identity to be filled with cookie you need one more request.
In short your scheme looks like this:

*

*Client sends his UserName and Password.

*Server gets and checks it.

*If they are valid the server sends Set-Cookie header to the client.

*Client receives and stores it. For each request client sends cookies back to the server.


text:
Q: Tick boxes are too far from their text Text seems a little far away from its related tickbox as of late:

I'm willing to bet this was introduced while fixing Private beta "send as" tick boxes need better spacing - if it's intentional that's fine, I'll get used to it :)

A: I work at the pixel disposal unit here at Stack Exchange, and I've got to say, we're a little put off by this. First, do you know just how many darn empty pixels we receive every day? It's quadtrillions, easily - we just stop counting there.
Someone has got to do something with all of those empty pixels. We're a responsible company, so we don't do what other more evil companies do like send the pixels off to landfills, or bundle them up in heavy containers to be sunk into the ocean where they just leak out forever and pixelate coal reefs. We have to get rid of them somehow, so we work really hard to find places where a few extra pixels wouldn't really make a difference, and dispose of them that way, like scattering rock shavings out in the yard when you're breaking out of prison so the guards don't get wise.
I hate to do this, but I have to ask - given that you don't seem to appreciate the process that we go through, why do you hate the environment so much? C'mon man, we've all got to live here.


text:
Q: Using HtmlUnit produces a long list of errors What I am trying to do is go to a website, select items from two drop down lists, type something into a box, and then press a button. I then want to get the resulted text that will be in a box that you can't type in.
The site I want to use is http://www.worldlingo.com/en/products_services/worldlingo_translator.html and here is my code that does everything I'm trying to do except getting the final text (as I don't know how to do that yet).
try {
        final WebClient webClient = new WebClient();
        Page page = webClient.getPage("http://www.worldlingo.com/en/products_services/worldlingo_translator.html");

        HtmlSelect select = ((HtmlSelect) page).getElementById("SelSrcLang");
        HtmlOption option = select.getOptionByValue("English");
        select.setSelectedAttribute(option, true);

        HtmlSelect select2 = ((HtmlSelect) page).getElementById("SelTrgLang");
        HtmlOption option2 = select2.getOptionByValue("French");
        select.setSelectedAttribute(option2, true);

        final HtmlForm form = ((HtmlPage) page).getFormByName("form");
        final HtmlSubmitInput button =  form.getInputByName("Translate");
        final HtmlTextInput textField =  form.getInputByName("wl_ft_print_text");
        textField.setValueAttribute("How are you?");

        page = (HtmlPage) form.getInputByValue("Translate").click();

        System.out.println("Finished");

    } catch (FailingHttpStatusCodeException e) { } catch (MalformedURLException e) { } catch (IOException e) { }

EDIT: After changing
Page page = webCLient...

to
HtmlPage page = webCLient...

I get no errors but when I run I get the following error

Exception in thread "main" com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[option] attributeName=[value] attributeValue=[English]
      at com.gargoylesoftware.htmlunit.html.HtmlSelect.getOptionByValue(HtmlSelect.java:437)
      at maple.Main.main(Main.java:43)

Line 43 is
HtmlOption option = select.getOptionByValue("English");

A: 80% of the "errors" you're talking about are actually warnings. Those are mostly JavaScript unconformities that you might probably disregard (or correct in the server if you actually have access to the code, which I guess you don't as it seems you're webscraping the page).
19% of the actual errors are related to Flash objects not being able to be created. This makes sense, as HtmlUnit can't handle flash. Check this other similar question: Faster page processing with HtmlUnit. Anyway, you should also disregard those errors as they should actually be informational messages.
1% is the actual error that is not allowing you run your code:

Exception in thread "main" java.lang.ClassCastException:
    com.gargoylesoftware.htmlunit.html.HtmlPage cannot be cast to
    com.gargoylesoftware.htmlunit.html.HtmlSelect
    at maple.Main.main(Main.java:42)

Altough I can't tell which is line 42 I bet it is this one:
HtmlSelect select = ((HtmlSelect) page).getElementById("SelSrcLang");

There you have an HtmlPage object and you are casting it to an HtmlSelect. That would produce the exception above. Probably you were trying to do this:
HtmlSelect select = (HtmlSelect) page.getElementById("SelSrcLang");

Note this will only work if you use an HtmlPage not a Page object. See JavaDoc.
I hope this remote debugging session has helped :)


text:
Q: Connected_Slaves Metric When Using Slave of Slave in Redis When using the replication features of Redis in an environment with slaves of slaves, would the connected_slaves counter increase for the master, the slave which is acting as a master, or both? Refer to the example diagram: https://imgur.com/Ge1WLzX
In the image, there is a master with two slaves, each slave having its own two slaves. In this instance would the master's connected_slaves value be 6? Would the connected_slaves value of the first pair of slaves be 2 each?
I have looked through Redis's documentation and have found nothing describing this.

A: To find the solution, I set up a virtual environment with seven Redis servers running simultaneously. They were set with sequential port numbers, with the default Redis port (6379) instance being the master. I configured two instances to be slaves to Instance_6379, and configured two more slaves each for Instance_6380 and Instance_6381, respectively. I then checked the redis-cli info output of each, taking note of the connected_slaves metric.
Here is what I found:
Masters will only report those slaves that are DIRECTLY CONNECTED to them. Slaves of slaves will NOT count towards the total number of slaves connected to the master.
In the example image referenced in the question, the leftmost Redis server would have only two connected_slaves and each of its children would also show two connected_slaves.
I hope this answer will be of use to someone.


text:
Q: Appell Sequences as Group under Addition I was wondering if infinite polynomials sequences such as Appell Sequences could be groups under addition.
Take a polynomial sequence $\{p_n(x)\}$ where the following condition is imposed:
$$p'_n(x)=np_{n-1}(x)$$
Then if I take two sequences $\{p_n(x)\}$ and $\{q_n(x)\}$ and add them under the operation
$$\{p_n(x)\}+\{q_n(x)\}=\{(p+q)_n(x)\}$$
which is just point wise addition of corresponding sequence terms then it would be closed under this addition since
$$(p+q)'_n(x)=p'_n(x)+q'_n(x)=np_{n-1}(x)+nq_{n-1}(x)=n(p+q)_{n-1}(x)$$.
Associativity follows as well.  The identity would be $\{0\}=(0,0,0,...)$ and this surely satisfies the Appell condition
and the inverse under addition would be $\{-p_n(x)\}$ since
$$-p'_n(x)=-np_{n-1}(x)$$
Is this a valid proof that the set of Appell Sequences is a group under Addition?  Is the addition well defined?

A: Yes. In fact, when the coefficients are in a commutative ring $R$, such things form an $R$-module.


text:
Q: Plotting pandas dataframe with one color for several columns I have a dataframe that looks like this:
                                 A  ...            B
datetime                            ...
2020-01-01 00:00:00         10.622  ...           30
2020-01-01 01:00:00         16.397  ...           30
2020-01-01 02:00:00         24.190  ...           30
2020-01-01 03:00:00         33.579  ...           30
2020-01-01 04:00:00         44.643  ...           30
                            ...     ...           ...
2020-01-07 20:00:00         18.090  ...           30
2020-01-07 21:00:00         18.027  ...           30

When I use df.plot, all columns are plotted with default colors and solid lines. I would like to plot columns A to x in the same color but with different markers and columns x+1 to B in another color with the same markers.
Is this somehow possible without manually declaring it for every column seperately?
Thanks!

A: You can create a custom cycler for this task:
from cycler import cycler
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

markernr = 3
colornr = 2
#test data generation
np.random.seed(123)
df = pd.DataFrame(np.random.random((10, 6)), columns=["A1", "A2", "A3", "B1", "B2", "B3"])

colors = ["tab:red", "tab:blue", "tab:orange", "brown", "lightblue", "yellow"]
markers = ["x", "o", "D", "+", "H"]

my_cycler = (cycler(color=colors[:colornr]) *
             cycler(marker=markers[:markernr]))

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 6))

df.plot(ax=ax1, title="Standard cycler")

ax2.set_prop_cycle(my_cycler)
df.plot(ax=ax2, title="Customized cycler")

plt.show()

Sample output:


text:
Q: Retrieving single parts of a javasript/jquery object Hi suppose I have a jQuery selector such as this:
var a = $(this);
var b = a.nextUntil("button").text();

This will retrieve all the DOM elements till the next button. I want to access all these DOM elements individually as separate objects. Is there  way to do that?

A: If you want to execute a function for each of the elements, you can use .each
If you want all the objects to be in an array, you can do something like this:
var arr = a.nextUntil("button")

and then index it as an array.
console.log($(a[0]).text())


text:
Q: ASP.NET Page Cannot be Null when Repeater Data is null I am facing an issue with Repeater in ASP.NET now.
I am binding data to the repeater which is inside a div for which visibility is false and display is none. When I bind data to the repeater I get two cases:
CASE 1:
When query returns some data. In this case I do not get any error and every thing runs fine.
CASE 2:
When query returns blank. This time I get Page Cannot be null error.
(Page cannot be null. Please ensure that this operation is being performed in the context of an ASP.NET request.)
Please find the code which runs on that button click.
int RowCount = 0;
string cmd = "SELECT PrjB.Prj_ID, POB.ExpType as ExpType, TExp.Expenditure_ID AS ExpID, ISNULL(PrjB.Amount_Allocated, 0) AS
  BudgetAllocated, ISNULL(POB.AmtAllocated, 0) "
  + "AS BudgetAvailedPO, ISNULL(NonPOB.AmtPaid, 0) AS BudgetAvailedNonPO FROM v_ProjectBudgetAllocated AS PrjB LEFT OUTER JOIN "
  + "v_POBudgetAllocated AS POB ON PrjB.Prj_ID = POB.Proj_ID AND PrjB.Expenditure_Type = POB.ExpType LEFT OUTER JOIN "
  + "v_NonPOBudgetAvailed AS NonPOB ON NonPOB.PrjID = PrjB.Prj_ID INNER JOIN T_Expenditure AS TExp ON POB.ExpType = TExp.Expenditure_Type "
  + "WHERE (PrjB.Prj_ID = '" + PrjID + "') ORDER BY ExpID";

DataSet ds = new DataSet();
SqlCommand selectCmd = new SqlCommand(cmd, myConnection);

SqlDataAdapter da = new SqlDataAdapter(selectCmd);
da.Fill(ds);
RowCount = ds.Tables[0].Rows.Count;

poStep3.Visible = true;
poStep3.Style["display"] = "block";

if (RowCount == 0)
{
  poStep3.InnerHtml = "Cannot Create Purchase Order. There is no budget allocated to this Project ";
}
else
{
  PrjBudgetDetails.DataSource = ds;
  PrjBudgetDetails.DataBind();
}

The ASPX Code for the div is:

  <fieldset>

      Enter PO Details

    <legend id="poDataEntryInstructions" class="frmInstructions" runat="server">
      Please fill
      all the texts in the fields. All fields are mandatory
    </legend>

      <asp:Label ID="LbPOID" runat="server" Text="PO ID:" CssClass="formFieldLabel" AssociatedControlID="POIDText">
      </asp:Label>
      <asp:TextBox ID="POIDText" name="PrjIDText" runat="server" CssClass="formInputField">
      </asp:TextBox>
      <asp:Label ID="POIDTextDsp" Font-Bold="true" runat="server" Text="" Visible="false"
      CssClass="formFieldLabel" Style="display: none;">
      </asp:Label>

      <asp:Label ID="LbPOTitle" runat="server" Text="PO Title:" CssClass="formFieldLabel"
      AssociatedControlID="POTitleText">
      </asp:Label>
      <asp:TextBox ID="POTitleText" name="POTitleText" runat="server" CssClass="formInputField">
      </asp:TextBox>
      <asp:Label ID="POTitleTextDsp" Font-Bold="true" runat="server" Text="" CssClass="formFieldLabel"
      Visible="false" Style="display: none;">
      </asp:Label>

      <asp:Label ID="LbPODesc" runat="server" Text="PO Description:" CssClass="formFieldLabel" AssociatedControlID="PODescText">
      </asp:Label>
      <textarea id="PODescText" name="PODescText" cols="50" rows="6" runat="server" class="formInputField" />
      <asp:Label ID="PODescTextDsp" Font-Bold="true" runat="server" Text="" CssClass="formFieldLabel"
      Visible="false" Style="display: none;">
      </asp:Label>

      <asp:Label ID="LbPOIssueDateText" runat="server" Font-Bold="true" Text="PO Issue Date:" CssClass="formFieldLabel">
      </asp:Label>
      <asp:TextBox ID="POIssueDateText" name="POIssueDateText" runat="server" CssClass="formInputField">
      </asp:TextBox>
      <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
      </asp:ToolkitScriptManager>
      <asp:CalendarExtender ID="POIssueDateText_CalendarExtender" runat="server" TargetControlID="POIssueDateText"
      Format="MM-dd-yyyy">
      </asp:CalendarExtender>
      <asp:Label ID="POIssueDateTextDsp" runat="server" Font-Bold="true" Text="" Visible="false" CssClass="formFieldLabel" Style="display: none;">
      </asp:Label>

      <asp:Label ID="LbprjBudgetInfoHead" runat="server" Font-Bold="true" Text="Project Budget data:" CssClass="formFieldLabel">
      </asp:Label>

        Project Budget Details

        The
        current program budget status.

        <asp:Repeater ID="PrjBudgetDetails" runat="server" ClientIDMode="Static">
          <HeaderTemplate>

                <asp:Label ID="LbExpType" runat="server" Text="Expenditure Type" CssClass="LbTblDataDisp"
                Font-Bold="true">
                </asp:Label>

                <asp:Label ID="LbAllocatedBudget" runat="server" Text="Allocated Budget" CssClass="LbTblDataDisp"
                Font-Bold="true">
                </asp:Label>

                <asp:Label ID="LbAvailedBudget" runat="server" Text="Available Budget" CssClass="LbTblDataDisp"
                Font-Bold="true">
                </asp:Label>

                <asp:Label ID="LbRequestedBudget" runat="server" Text="Budget Requested" CssClass="LbTblDataDisp"
                Font-Bold="true">
                </asp:Label>

          </HeaderTemplate>
          <ItemTemplate>

                <asp:Label ID="ExpTypeText" runat="server" Text='<%#Eval("ExpType") %>' CssClass="LbTblDataDisp"AssociatedControlID="BudgetRequestedText">
                </asp:Label>

                <asp:Label ID="BudgetAllocatedText" runat="server" Text=' <%#Eval("BudgetAllocated") %>' CssClass="LbTblDataDisp" AssociatedControlID="BudgetRequestedText">
                </asp:Label>

                <asp:Label ID="BudgetAvailableText" runat="server" Text='<%#Convert.ToDouble(Eval("BudgetAllocated")) - Convert.ToDouble(Eval("BudgetAvailedPO")) - Convert.ToDouble(Eval("BudgetAvailedNonPO")) %>' CssClass="LbTblDataDisp" ClientIDMode="Static" AssociatedControlID="BudgetRequestedText">
                </asp:Label>

                <asp:TextBox ID="BudgetRequestedText" runat="server" dataKey='<%#Eval("ExpID") %>' dataValue='<%#Eval("ExpType") %>' CssClass="tblDataInput" dataAmount='<%#Convert.ToDouble(Eval("BudgetAllocated"))  Convert.ToDouble(Eval("BudgetAvailedPO")) - Convert.ToDouble(Eval("BudgetAvailedNonPO")) %>'></asp:TextBox>

          </ItemTemplate>
        </asp:Repeater>

              Please enter zero(0) if not
              requesting budget for any particular expenditure. The currency is INR.

            <asp:Button ID="POSubmitBtn" runat="server" Text="Submit Budget" CssClass="formNext" ClientIDMode="Static" OnClick="POSubmitBtn_Click" />
            <asp:Button ID="POGoToHomeBtn" runat="server" OnClick="POGoToHomeBtn_Click" Text="Home" CssClass="formNext" Visible="false" />

  </fieldset>

Its been few hours since I am banging my head at Google. Looks like I am stuck here and need some expert help to move ahead.
Thanks in Advance.
-Himanshu

A: I dont know if the person who gave answer here removed them or some thing else. But one guy posted the answer two days back and it worked.
The solution was to have another hidden div and make it enable instead of updating innerHTML of the current div.


text:
Q: Key error even though the item is in the set I tried to re-create the pseudocode for A* pathfinding (https://en.wikipedia.org/wiki/A*_search_algorithm)
I keep getting stuck on openSet.remove(current) as for me it just raises a key error.
openSet = {start_tile}
cameFrom = dict()
gScore = dict()
fScore = dict()
for tile in tile_background:
    gScore[tile] = float('inf')
    fScore[tile] = float('inf')

gScore[start_tile] = 0
fScore[start_tile] = h(start_tile, end_tile)

while len(openSet) > 0:

        current_tile = min(openSet, key=lambda x: fScore[x])
        if current_tile == end_tile:

            path = [current_tile]
            while current_tile in cameFrom:
                current_tile = cameFrom[current_tile]
                path.insert(0, current_tile)
            route = path

        openSet.remove(current_tile)
        for neighbour in current_tile.neighbours:
            est_gScore = gScore[current_tile] + 100

            if est_gScore < gScore[neighbour]:
                cameFrom[neighbour] = current_tile
                gScore[neighbour] = est_gScore
                fScore[neighbour] = est_gScore + h(neighbour, end_tile)
                if neighbour not in openSet:
                    openSet.add(neighbour)


text:
Q: TFS Custom Field Reporting on Historical Value Using Agile template on with some customized fields.
Custom-Field-X is a Drop Down List with allowed value set 0, 1, 2, 3 - this value could change daily.
Need a way to check if Custom-Field-X was ever set to 0 during its life time.
Using TFS2010.
Thanks!

A: I assume you are talking about a custom field you added for TFS workitems. You can use following code to find out whether the value was set to 0 or not. Alternately you can also use  workItemStore.GetWorkItem(id) to get specific workitem by Id. You can find details about retrieving work items @ http://pwee167.wordpress.com/2012/09/18/retrieving-work-items-using-the-team-foundation-server-api/.
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client; // You need to add reference to both these assemblies in your project

var collectionUri = new Uri("<TfsUrl>/<CollectionName>"); // For e.g. "http://tfs:8080/DefaultCollection"

var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUri);

WorkItemStore workItemStore = projectCollection.GetService<WorkItemStore>();

var results = workItemStore.Query("SELECT * FROM WORKITEMS");

WorkItem workItem = results[0];

foreach (Revision revision in workItem.Revisions)
{
    var originalValue = revision.Fields["Custom-Field-X"].OriginalValue;

    var curretValue = revision.Fields["Custom-Field-X"].Value;
}


text:
Q: makePersistent for owned one-to-many rs. not working reliably in JDO the makePersistent method of the PersistenceManager is not working reliably. one and the same junit-test is working and after a while its failing again?!
i have an object that includes a collection of other objects. that means an 1-n relationship.
my problem is that the junit-test of my classes is failing sometimes because the objects in the collection are not persisted properly.
i am using usually transactions but the persistanceManager is transaction-optional
i tried checking the objectState after each createObject and commit...
i figured out that the objects in the collection after a successful commit have no systemId (should be auto-generated) but are in state hollow/persistent-nontransactional.
that means sometimes they are (if they are persisted):
Comment [systemId=Project(1)/Comment(6), JDO-ObjectState=hollow/persistent-nontransactional]
and sometimes they are (if they are not persisted and a refach of the parent-object contains an empty collection)
Comment [systemId=null, JDO-ObjectState=hollow/persistent-nontransactional]
off course i could check manually if all the stored objects have an systemId but this approach is not nice at all. the commit should just fail!!
i do not understand that it is sometimes working and sometimes not! that means my code should not be wrong and this is a bug...
pls help me out
PS: i can post some code if necessary!
@PersistenceCapable
public class Ble implements Serializable, JDOObject<Ble> {

/**
 *
 */
private static final long serialVersionUID = 1L;

// NotNull
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key systemId;

// NotNull
@Persistent
private Key parentId;

// NotNull
@Persistent
@Extension(vendorName = "datanucleus", key = "gae.parent-pk", value = "true")
private Key projectId;

// NotNull
@Persistent
private String title;

@Persistent
private int position;

@Persistent
private boolean hasChildren;

@Persistent
private BleData requirementData;

@Persistent
private List<Comment> comments;

//getter/setter
}

childObject
    @PersistenceCapable
public class Comment implements Serializable, JDOObject<Comment> {

/**
 *
 */
private static final long serialVersionUID = 1L;

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key systemId;

@Persistent
private String text;

@Persistent
private long createdTimestamp;

//getter//Setter
}

A: the solution is always to use a new persistanceManager for each transaction. never reuse a pm!!

A: the Log if i try to add a comment and it's NOT working
05.09.2012 15:02:06 org.datanucleus.jdo.metadata.JDOMetaDataManager$MetaDataRegisterClassListener registerClass
INFO: Listener found initialisation for persistable class com.Comment
05.09.2012 15:02:06 org.datanucleus.store.appengine.MetaDataValidator validate
INFO: Performing appengine-specific metadata validation for com.Comment
05.09.2012 15:02:06 org.datanucleus.store.appengine.MetaDataValidator validate
INFO: Finished performing appengine-specific metadata validation for com.Comment
Comment [systemId=null, text=testAddCommentToBle - comment , createdTimestamp=1346850126819, JDO-Status=hollow/persistent-nontransactional]

the Log if i try to add a comment and it IS working
05.09.2012 15:00:25 org.datanucleus.jdo.metadata.JDOMetaDataManager$MetaDataRegisterClassListener registerClass
INFO: Listener found initialisation for persistable class com.Comment
05.09.2012 15:00:26 org.datanucleus.store.appengine.MetaDataValidator validate
INFO: Performing appengine-specific metadata validation for com.Comment
05.09.2012 15:00:26 org.datanucleus.store.appengine.MetaDataValidator validate
INFO: Finished performing appengine-specific metadata validation for com.Comment
Comment [systemId=Project(1)/Comment(6), text=testAddCommentToBle - comment , createdTimestamp=1346850025996, JDO-Status=hollow/persistent-nontransactional]

the add method looks like this.
public Boolean addCommentToBle(Key systemKey, Comment comment)
        throws Exception {
    PersistenceManagerFactory PMF = PersistenceUtil.getPersistenceManagerFactory();
    PersistenceManager pm = PMF.getPersistenceManager();
    pm.currentTransaction().begin();
    Ble ble= pm.getObjectById(Ble.class, systemKey);
    System.out.println(ble);
    ble.getComments().add(comment);
    pm.makePersistent(ble);
    pm.currentTransaction().commit();
    return true;
}


text:
Q: Writing a function that returns => T I'm trying to write a simple converter that turns a java.util.Function into a scala.Function1:
def toScalaProducer[T](f: JavaFunction0[T]) : => T  = => f()

Here is another variant that works well:
def toScalaFunction[T](f: JavaFunction0[T]) : () => T =
  () => f.apply()

The problem is that I want to pass the converted function into an existing Scala API, but that API only accepts arguments of type => T, not of type () => T.
Is there a way to write the toScalaProducer function?

A: () => T is the type for a function that takes no arguments and returns something of type T
=> T is the type for a value T that is lazily evaluated.  For instance:
def myFunc(t: => Int): Unit = {
   // Do something with t
}

myFunc(reallyExpensiveFunctionProducingAnInt())

Here, reallyExpensiveFunctionProducingAnInt could take a long time to run, but will only be executed if the value t is used in myFunc.  If you just use type Int instead of => Int it will have been called before myFunc is entered.
Have a look here for more information: Scala's lazy arguments: How do they work?
So if your toScalaProducer function simply executed the Java function and had a return value of T, it should work fine with the API.  It will only be executed when needed, so in many ways will behave like passing a function.


text:
Q: artillery.io xhr poll error I am unable to connect using artillery.io with setting engine = socketio, please find my configuration json below
socket error {"type":"Transport error", "description":400}

 "scenarios": [
    {
      "name": "my test",
      "engine": "socketio",
      "flow": [
        {
          "emit": {
            "channel": "command",
            "namespace": "command"
          }
        },
        {
          "think": 1
        }
      ]
    }
  ]

A: "scenarios": [
    {
      "name": "my test",
      "engine": "socketio",
      "flow": [
        {
          "emit": {
            "channel": "command"
            "data": "hello"
            "namespace": "/command"
          }
        },
        {
          "think": 1
        }
      ]
    }
  ]

Please try using above command


text:
Q: ElseIf Statement in VBA not applying all the conditions? I'm new to coding and attempting to learn some VBA. I've started trying to build simple applications to help me learn, including this BMI calculator.
I would like a simple string text message to be displayed in the specified text box in accordance with the calculated BMI score and the subsequent If and Elseif statements.
If the BMI score returns less than 18, the text box displays "You Are Underweight" as desired. Similarly, if the BMI score returns a value of equal or greater than 18, "You Are The Ideal Weight" is displayed.
However, this is where the problem is encountered. If the BMI score is greater than 25, "You Are The Ideal Weight" continues to be displayed, with the additional ElseIf and Else statements seemingly just ignored?
Can anyone spot what I am missing? My code is shown here:
Option Explicit

Sub BMI()

Dim Height As Variant
Dim Weight As Variant
Dim BMI As Double

Height = Height_Input.Value
Weight = Weight_Input.Value

If IsNumeric(Height_Input.Value) And IsNumeric(Weight_Input.Value) Then

    BMI = CDbl(Weight_Input.Value) / (CDbl(Height_Input.Value) * CDbl(Height_Input.Value))

    BMI_Output.Value = BMI

Else: MsgBox ("Please Enter Numeric Values")

End If

If BMI < 18 Then
    The_Verdict.Value = "You Are Underweight"

    ElseIf 18 <= BMI < 25 Then
        The_Verdict.Value = "You Are The Ideal Weight"

        ElseIf 25 <= BMI < 30 Then
            The_Verdict.Value = "You Are OverWeight"

Else: The_Verdict.Value = "You Are Obese"

End If

If Height_Input.Value = ("") Or Weight_Input.Value = ("") Then

    The_Verdict.Value = ""

End If

End Sub

A: 18 <= BMI < 25 is not correct VBA:
18 <= BMI And BMI < 25

Would be the correct method.
VBA resolves right to left so first it is asking BMI < 25 and returning TRUE or FALSE.  Then the next part is asking 18 <= TRUE which it will never be as TRUE is -1
Ultimately the Less than or equal to part are not needed as the IF will resolve in order:
If BMI < 18 Then
    The_Verdict.Value = "You Are Underweight"
ElseIf BMI < 25 Then
    The_Verdict.Value = "You Are The Ideal Weight"
ElseIf BMI < 30 Then
    The_Verdict.Value = "You Are OverWeight"
Else
    The_Verdict.Value = "You Are Obese"
End If


text:
Q: OWLOntologyManager trying to load multiple OWLDocumentSources I am trying to load multiple ttl files with the OWLOntologyManager by documentSource, and then reasoning over the imports closure with the main Ontology. This was done to try and mirror Protege's method of having a base Ontology that imports ontologies on its own.
How I attempt this, works in the following manner. I connect to the web repo and download the ttl file at its location, these files are then read and the documentIRI is found whithin. The documentIRI as well as the inputstream are both added to the OWLDOcumentSource and given to the manager to load.
The idea is to load over all the ontologies whithout following imports and then to reason over the base ontology and reasoning over the import closure.
The first problem is that even with:

manager.getOntologyLoaderConfiguration().setMissingImportHandlingStrategy(MissingImportHandlingStrategy.SILENT);

the imports are still being loaded and the following error message is received:
An error occurred creating the Configuration(s): org.semanticweb.owlapi.model.OWLOntologyFactoryNotFoundException: Could not find an appropriate factory to load ontology from ontology document: <sm:sentx.sol/config/site.ttl>"

How do I solve this problem? Is it a missing Factory that I need to implement?

A: @UninformedUser has pointed out that the configuration object needs to be assigned back to the manager, e.g.,
OWLOntologyLoaderConfiguration config = manager.getOntologyLoaderConfiguration();
config = config.setMissingImportHandlingStrategy(MissingImportHandlingStrategy.SILENT);
manager.setOntologyLoaderConfiguration(config);

However, for your use case, the missing import strategy is not relevant. If your ontology imports can be resolved as URLs, setting the missing import strategy will not have any effects - the imports are not missing. And if they cannot be resolved as URLs, all that will happen is that no exceptions will be thrown, but the imports will not be loaded, and therefore you won't be able to replicate Protege's behaviour.
What I would suggest is to put all ontology files you wish to load in the same folder and use an AutoIRIMapper instance pointed at the folder; what this does is to provide a mapping strategy that prefers local files over remote URLs.
This might not be sufficient for your needs - for a more granular strategy (for example, if you want just one of the imports to be resolved locally) you can use SimpleIRIMapper instead.
See this file for examples of how to use these classes: https://github.com/owlcs/owlapi/blob/version5/contract/src/test/java/uk/ac/manchester/owl/owlapi/tutorialowled2011/TutorialSnippetsTestCase.java
@Test
void testIRIMapper() throws OWLOntologyCreationException, OWLOntologyStorageException {
    OWLOntologyManager m = OWLManager.createOWLOntologyManager();
    // map the ontology IRI to a physical IRI (files for example)
    // Create the document IRI for our ontology
    File output = new File(temporaryFolder, "saved_pizza.owl");
    // Output will be deleted on exit; to keep temporary file replace
    // previous line with the following
    // File output = File.createTempFile("saved_pizza", ".owl");
    IRI documentIRI = IRI.create(output);
    // Set up a mapping, which maps the ontology to the document IRI
    SimpleIRIMapper mapper = new SimpleIRIMapper(EXAMPLE_SAVE_IRI, documentIRI);
    m.getIRIMappers().add(mapper);
    // set up a mapper to read local copies of ontologies
    File localFolder = new File("materializedOntologies");
    // the manager will look up an ontology IRI by checking
    // localFolder first for a local copy, checking its subfolders as well
    m.getIRIMappers().add(new AutoIRIMapper(localFolder, true));
    // Create the ontology - we use the ontology IRI (not the physical URI)
    OWLOntology o = m.createOntology(EXAMPLE_SAVE_IRI);
    // save the ontology to its physical location - documentIRI
    o.saveOntology();
}


text:
Q: How to keep the value of the source when using InjectFrom By injecting values into my domain object, I would keep the values of some properties.
Example:
Domain model
public class Person
{
    public string Name { get; set; }
    public Guid ID { get; set; }
    public DateTime CreateAt { get; set; }
    public string Notes { get; set; }
    public IList<string> Tags { get; set; }
}

View Model
public class PersonViewMode
{
    public string Name { get; set; }
    public Guid ID { get; set; }
    public DateTime CreateAt { get; set; }
    public string Notes { get; set; }
    public IList<string> Tags { get; set; }

    public PersonViewMode() { ID = Guid.NewGuid(); } //You should use this value when it is the Target
}

Sample
var p = new Person
            {
                ID = Guid.NewGuid() //Should be ignored!
                ,
                Name = "Riderman"
                ,
                CreateAt = DateTime.Now
                ,
                Notes = "teste de nota"
                ,
                Tags = new[] {"Tag1", "Tag2", "Tag3"}
            };

var pvm = new PersonViewMode();

pvm.InjectFrom(p); //Should use the ID value generated in the class constructor PersonViewMode

A: if you delete the set; from  from the ViewModel's ID then it won't be set;
otherwise you could save the value of ID in a separate variable and put it back after injecting,
or you can create a custom valueinjection that would ignore "ID" or would receive a list of properties to ignore as a parameter

here's the example for a custom injection that receives a list of property names to ignore:
public class MyInj : ConventionInjection
{
    private readonly string[] ignores = new string[] { };

    public MyInj(params string[] ignores)
    {
        this.ignores = ignores;
    }

    protected override bool Match(ConventionInfo c)
    {
        if (ignores.Contains(c.SourceProp.Name)) return false;
        return c.SourceProp.Name == c.TargetProp.Name && c.SourceProp.Type == c.TargetProp.Type;
    }
}

and use it like this:
pvm.InjectFrom(new MyInj("ID"), p);

if you need to ignore more, you can do like this:
pvm.InjectFrom(new MyInj("ID","Prop2","Prop3"), p);


text:
Q: Why does the fragmentation field, in IP header, indicate the offset by bytes, and not sequentially? Exactly what the title says. Since the offset number indicates the position of the single fragment in the overall datagram, and since they went to such lengths as dividing the offset by 8, to save space, why isn't the offset a sequential number? It would certainly save more space than dividing the offset by 8, and plus, i doubt that the offset could give much informations about error detection and similar stuff.
So, why isn't it sequential, to save even more space? It would not be offset anymore, it would be like position number, but the meaning would be the same.

A: If the packets arrive out of order (which is pretty common), having offsets makes it much easier to reassemble the big packet in the memory by putting the fragments right into their place, without additional memory shuffling. If you only had sequence numbers, you wouldn't know where to put the fragment of the data.
For high-speed networking, this might make a noticeable performance difference.


text:
Q: How do I know when a variable is accessed within my code? I'm using VS2008 to write a program. There's one specific line in my code that causes a numerical error. It is:
    Qp[j] = (Cp - Cm)/(Bp + Bm);

Qp is a std::vector. When I comment this line out, the numerical error disappears. I am going through my code line by line to find all the places that access Qp[j]. I was wondering if there was a feature in VS2008 or a linux program that wraps around the executable that can identify every line of code that reads from that section of memory (the specific element in the vector)?
I tried searching online but the keywords I used brought up results relating to global variables.
--- EDIT
Hi all. To those have responded, thank you. Just to clarify my question:
Imagine I have a vector with 5 elements. I'd like to know all the places in my code that use the value stored in element 3 at any point in time during execution. Is there an easy way to do this?

A: I am not sure if I understand you correctly, but if you comment out that line and the code works then maybe the problem is that line, and you don't need to check others lines.
Maybe in your case you get in the situation where Bp+Bm = 0 (division by zero error).

A: Qp may not have as many elements as the index j, check the size of Qp.


text:
Q: Android in-app billing for non-digital goods? I want to make a small app in which I sell some non-digital products. I was wondering if there is some sort of payment system with which the users can pay directly within the app?
I only found the in-app billing for Android but this is only working for digital content. PayPal also has an app but this is more or less something on its own as far as I saw.
Thanks for hints.


text:
Q: aws sam LambdaLayer deploying for every new build I have a Resource in my template.yml:
  MyLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: layers/my-layer
      CompatibleRuntimes:
        - python3.8
    Metadata:
      BuildMethod: makefile

This is my Makefile:
  build-MyLayer:
      mkdir -p "$(ARTIFACTS_DIR)/python"
      cp *.py "$(ARTIFACTS_DIR)/python"
      python -m pip install -r requirements.txt -t "$(ARTIFACTS_DIR)/python"

Every time while I doing sam build and then sam deploy the layer MyLayer deploys to the AWS and new version creating. Even if I do not change the code of the MyLayer module.
How can I disable a layer new version creating in every deploy?

A: I found a solution which responds to my requirements.
I am create a separated folder with template.yaml which describes a one resource (AWS::Serverless::LayerVersion) only. When I need release a new version I make a build that resource


text:
Q: Ruby is getting wrong class name from my code Weird error, I'm calling ::Facility::ProcedureDecorator, but for some reason on my staging server ruby wants to call ProceduresDecorator instead. Any ideas what is going on?
Here are some samples:
NameError: uninitialized constant #<Class:0x00555f1ea188d0>::ProceduresDecorator
Did you mean? Facility::ProcedureDecorator
File "/app/app/admin/facility.rb" line 32 in edit

def edit
  @facility = Facility.includes([:documents, :procedures]).find(params[:id])
  @facility_documents = @facility.documents
  @possible_document_kinds = FacilityDocument.kinds.map { |k, _| [k.humanize, k] }
  @facility_procedures = ::Facility::ProcedureDecorator
                         .decorate_collection(@facility.procedures) # line 32
  @facility_info = ::Facility::InfoDecorator.decorate(@facility.info)
  @possible_procedures = @facility_procedures.map { |procedure| [procedure.name, procedure.id] }
  @templates = @facility.emergency_event_templates
  @white_label = @facility.white_label
end

Edit:
Thanks guys for help, at the end problem was within config/environments/staging.rb, those two lines caused a problem.
config.cache_classes = true
config.eager_load = true


text:
Q: Multiple Output with OutputResponse in Mathematica I have a question here regarding how to derive multiple output from OutputResponse or in general. Here is a screenshot of the codes
As seen, I have only one quantity plotted. Tried google but didn't manage to find a solution.
Thanks in advance!
The codes are here:
ω = 2. Pi*50; Mag = 1; θ = 0.;

Tαβ2dqInv22 = {{Cos[ω t], -Sin[ω t]},
{Sin[ω t], Cos[ω t]}};
Tαβ2dq22 = {{Cos[ω t],
    Sin[ω t]}, {-Sin[ω t], Cos[ω t]}};

Inputαβ22 = {Mag Cos[ω t + θ],
   Mag Cos[ω t + θ]};
(*Inputαβ22={Mag ,Mag};*)

Outαβ2dq22 =
  FullSimplify[Tαβ2dq22.Inputαβ22] //
   TrigReduce;

g[t_] = OutputResponse[
   TransferFunctionModel[(0.67/(0.0025 s + 1) + 1)/(0.0025 s), s],
   Outαβ2dq22[[1]], t];
f[t_] = OutputResponse[
   TransferFunctionModel[(0.67/(0.0025 s + 1) + 1)/(0.0025 s), s],
   Outαβ2dq22[[2]], t];

Plot[{g[t], f[t]}, {t, 0, 0.2}, PlotRange -> Automatic]

A: Is this what you are looking for? The response to the two inputs:
res = Chop@Expand@
OutputResponse[
 TransferFunctionModel[(0.67/(0.0025*s + 1) + 1)/(0.0025*s),
  s], #1, t] & /@ Outαβ2dq22;
Plot[res, {t, 0, 0.05}, PlotRange -> All]

A: Suba has already done it.
tf = TransferFunctionModel[(0.67/(0.0025 s + 1) + 1)/(0.0025 s), s];
Outαβ2dq22 = FullSimplify[Tαβ2dq22.Inputαβ22] // TrigReduce // Chop;
Plot[Outαβ2dq22, {t, 0, 0.1}]

This is your input:

out1 = OutputResponse[tf, Outαβ2dq22[[1]], {t, 0, 0.2}];
out2 = OutputResponse[tf, Outαβ2dq22[[2]], {t, 0, 0.2}];

out3 = OutputResponse[tf, #, {t, 0, 0.2}] & /@ Outαβ2dq22;

You get the same output with out1 + out2 or out3:
Plot[{out1, out2}, {t, 0, 0.2}]

Plot[out3, {t, 0, 0.2}]

You have a network that only one source works. If both sources act, they must be linked to each other. Now a network on which two sources work and thus the answer to your question at the beginning " I have a question here regarding how to derive multiple output from OutputResponse or in general."

g1 = (uR - u1) s C1 + uR/R + (uR - u2)/(s L1);
sol = Solve[g1 == 0, uR];
iR = uR/R /. sol;
h1 = iR/u1 /. u2 -> 0;
h2 = iR/u2 /. u1 -> 0;
tf = TransferFunctionModel[{Join[h1, h2]}, s]

T = 10^-3;
params= {L1 -> 1, C1 -> 0.1*10^-6, R -> 1000};
q1 = SquareWave[{0, 1}, (t + T/4)/T];
q2 = SawtoothWave[{0, 1}, t/T];
out = OutputResponse[tf /. params, {q1, q2}, {t, 0, 5 T}];

Show[
 Plot[{q1, 1000 out}, {t, 0, 5 T}, ExclusionsStyle -> Automatic, PlotStyle -> {Blue, Thick}],
 Plot[q2, {t, 0, 5 T}, ExclusionsStyle -> Automatic, PlotStyle -> Darker[Red]]
 ]


text:
Q: MacBook Pro won't load photos My MacBook Pro is not loading my photos anymore. I insert the SD card, as I have always done, iPhoto pops up and says loading photos, but then the error message pops up saying that the disc was not ejected properly when I haven't even touched it! Can someone please help me?
Thanks!

A: Leslie,
Without further information, my first guess is a corrupted SD card. Try the following steps.
1) With the SD Card inserted, locate and launch Disk Utility.app
2) On the left column lists of hard disks, DVD/CD and other storage devices detected on your MacBook Pro.
3) Click once to select the SD card. This will cause the right half of the window to be populated with series of possible actions. The default action displayed is titled 'First Aid'. Locate the 'Verify Disk' button on the bottom right corner. Click once on it and allow some time for it to diagnose your SD card.
4) If the Disk Utility.app reports an error, click to grant it permission to fix it. Once it's done, quit Disk Utility.app
5) Relaunch iPhoto and see if it works.
If this helps, please mark your question as answered. Thanks.

A: To rule out the card can you try it in a different device (ideally not the camera you've taken it out of).
To rule out a fault with the SD Card reader on the MBP can you test it with a USB card reader?