text:
Q: ionic issues with @ionic-native/push For a few days now I have been trying to get push notifications working in ionic, I have gone over 7 tutorials so far, but each and every one of them fails once I get to a point where its time to start testing!. Is it just me or are all these tutorials way out of date?
So far I have tried tutorials from:

*

*c-sharpcorner.com

*saowen.com

*medium.com

*sitepoint.com

*masteringionic.com

*thielcole.github.io

*luisjordan.net

For each of these tutorials, I run into a wall regarding the Push module, one way or another I keep getting these same errors, there are some very small variations between different tutorials, but in general these are the same errors, the ones below come from the latest tutorial I followed (the luisjordan one):
From the app.component.ts file, i get an error for the constructor:
----------------------
typescript: C:/Users/***/Documents/ionic/push-luisjordan/src/app/app.component.ts, line: 15
Cannot find name 'Push'.

L15:  constructor (platform : Platform, statusBar : StatusBar, splashScreen : SplashScreen, private push : Push) {
L16:              platform.ready().then(() => {
----------------------

And from app.module.ts file, i get an error for the providers:
----------------------
typescript: C:/Users/***/Documents/ionic/push-luisjordan/src/app/app.module.ts, line: 12
Argument of type '{ declarations: (typeof HomePage | typeof MyApp)[]; imports: (ModuleWithProviders | typeof
Browse...' is not assignable to parameter of type 'NgModule'. Types of property 'providers' are
incompatible. Type '(typeof SplashScreen | PushOriginal | { provide: typeof ErrorHandler; useClass: typeof
IonicError...' is not assignable to type 'Provider[]'. Type 'typeof SplashScreen | PushOriginal | { provide:
typeof ErrorHandler; useClass: typeof IonicErrorH...' is not assignable to type 'Provider'. Type
'PushOriginal' is not assignable to type 'Provider'. Type 'PushOriginal' is not assignable to type
'ClassProvider'. Property 'provide' is missing in type 'PushOriginal'.

L12:  @NgModule({
L13:    declarations: [

To prevent turning this thing into an even bigger wall of text, i have made the below pastebin page, it contains the same errors posted above, but more importantly it also contains the code of app.component.ts & app.module.ts
https://pastebin.com/RUH9egA9
To help speed things up, heres a overview of version numbers and some replies to common question's i see on other ionic questions:
$ ionic info

Ionic:

   ionic (Ionic CLI)  : 4.8.0 (C:\Users\Olivier\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.2.1

Cordova:

   cordova (Cordova CLI) : 8.1.2 (cordova-lib@8.1.1)
   Cordova Platforms     : android 7.1.4
   Cordova Plugins       : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 2.3.2, (and 7 other plugins)

System:

   NodeJS : v10.2.1 (C:\Program Files\nodejs\node.exe)
   npm    : 6.5.0
   OS     : Windows 10

$ ionic cordova plugins
> cordova plugin ls

You have been opted out of telemetry. To change this, run: cordova telemetry on.
cordova-plugin-device 2.0.2 "Device"
cordova-plugin-ionic-keyboard 2.1.3 "cordova-plugin-ionic-keyboard"
cordova-plugin-ionic-webview 2.3.2 "cordova-plugin-ionic-webview"
cordova-plugin-splashscreen 5.0.2 "Splashscreen"
cordova-plugin-statusbar 2.4.2 "StatusBar"
cordova-plugin-whitelist 1.3.3 "Whitelist"
cordova-support-google-services 1.1.0 "cordova-support-google-services"
phonegap-plugin-multidex 1.0.0 "Multidex"
phonegap-plugin-push 2.2.3 "PushPlugin"

$ ionic cordova platform list
> cordova platform ls

You have been opted out of telemetry. To change this, run: cordova telemetry on.
Installed platforms:
  android 7.1.4
Available platforms:
  browser ~5.0.1
  ios ~4.5.4
  osx ~4.0.1
  windows ~6.0.0

*

*In the working directory i have installed the module with 'npm install --save @ionic-native/push'

*I have made sure to add the android platform, and i test with 'ionic cordova emulate android'

*I have edited my config.xml to have a widget id that matches my firebase app (tho i guess this is getting ahead of things?)

Does anybody have any clue what could be wrong? I've been reading about this for days and I still don't know what I could be missing? Every time I run into the same issue where ionic wont accept the push module... :(
Thanks in advance, if anybody has any additional questions after this wall-o-text then please don't hesitate to ask either.

A: It looks like Ionic team recently have made changes to their native plugins.
You seem to have installed a plugin (Version >= 5.0.0) which is supported for ionic 4.
Since you are using ionic 3 uninstall the plugin and install 4.20.0 version.
npm uninstall @ionic-native/push

and then
npm i -s @ionic-native/push@4.20.0

For more detailed explanation,you can check out this answer https://stackoverflow.com/a/54398403/6617276


text:
Q: Links don't work in PISA Here is a part of my HTML:

Header is a header

... other stuff ...

go there!

I process this using PISA:
%PISA_BIN% -s --encoding utf-8 %TITLE%.html %TITLE%.pdf

In the resulting PDF, link is not working: it's shown in underlined blue as a usual link, but when I click on it nothing happens. Tested this with Adobe Reader, Foxit Reader and Chrome embedded browser.
Also, in the resulting HTML link works as expected.
What's wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to calculate this Cross product I was trying to calculate this Cross product
Cross[{a, b}, {c, d + e}]

Mathematica gives the following result
{a, b} x {c, d + e}

and below error information:

Cross: The arguments are expected to be vectors of equal length, and the number of arguments is expected to be 1 less than their length.

However, I would like to get the following result:
a d + a e - b c

How to do it?

A: As far as I know, cross product is unique for 3D vectors. Pad 0s to the vectors as their 3rd components before crossing them
Cross[{a, b, 0}, {c, d + e, 0}]

{0, 0, -b c + a d + a e}

and one can take the 3rd component of the result.

Update
One can also use TensorWedge without padding
TensorWedge[{a, b}, {c, d + e}][[1, 2]]


text:
Q: Ruby Open-URI library aborted in 404 HTTP error code I use OpenURI library.
object = open("http://example.com")

If http://example.com server code response is equals to 200 my program acts as I expected.
But if http://example.com server response code is equals to 400 (or other) then script aborts with OpenURI::HTTPError: 404 Not Found.
I can avoid this if I use 'begin-rescue' construction and handle 'HTTPError exception'.
Is this a correct way?
Should I use Net/Http library instead of OpenURI to handle all cases?

A: Rescuing the OpenURI::HTTPError is perfectly reasonable. See this related answer: https://stackoverflow.com/a/7495389/289274
But if you would rather not deal with exception handling, here's how you can do it with Net::HTTP:
https://stackoverflow.com/a/2797443/289274


text:
Q: How do I get values of same key from all documents in MongoDB using Java? I am new in working on mongodb. Here is my Mongodb documents I only want the name values.
{
    "_id" : ObjectId("5da527f784a58d78fcd0b177"),
    "name" : "Jabed",
    "email" : "jabed@gmail.com",
    "Sex" : "male",
    "age" : "19",
    "address" : "Kochukhet, Dhaka",
    "Contct" : "01797259329"
}

{
    "_id" : ObjectId("5da6f415f2bdee4b90cf41d0"),
    "name" : "Bulbul Gulzer Deb",
    "email" : "gulzer.deb@gmail.com",
    "Sex" : "male",
    "age" : "19",
    "address" : "Narinda, Dhaka",
    "Contct" : "01756223666"
}

{
    "_id" : ObjectId("5dd771907607c3e12d9183d7"),
    "name" : "Aniruddha Dey",
    "email" : "aniruddha.dey@gmail.com",
    "Sex" : "male",
    "age" : "14",
    "address" : "Narinda, Dhaka",
    "Contct" : "01745706020"
}

Expected output will be
Jabed
Bulbul Gulzer Deb
Aniruddha Dey

A: Use the projection:
db.yourdocument.find( {}, { name: 1, _id: 0 } )

More control over projected fields can be found here


text:
Q: Reuse Workflow in github action - Azure deployment I need to reuse a workflow in another workflow instead of repeating things.
The build workflow already performs pip install and I just need the installed package to be reused during the deploy workflow instead of re-running pip install
     build:
       runs-on: ubuntu-latest
       needs: create-envfile
       steps:
          - uses: actions/checkout@v2
          - name: Set up Python version
            uses: actions/setup-python@v1
            with:
              python-version: '3.8'
          - name: Create and start virtual environment
            run: |
               python -m venv venv
               source venv/bin/activate

          - name: Install dependencies
             run: |
               eval `ssh-agent -s`
               cat ./.github/workflows/id_rsa | ssh-add -
               pip install -r requirements.txt

          - name: Upload artifact for deployment jobs
            uses: actions/upload-artifact@v2
            with:
             name: python-app
             path: |
                .
                !venv/

    deploy:
       runs-on: ubuntu-latest
       needs: build
       environment:
           name: 'Production'
           url: ${{ steps.somesecret }}

       steps:
          - name: Download artifact from build job
            uses: actions/download-artifact@v2
            with:
               name: python-app
               path: .

         - name: 'Deploy to Azure Web App'
             uses: azure/webapps-deploy@v2
             id: deploy-to-webapp
             with:
               app-name: 'project-prod'
               slot-name: 'Production'
               publish-profile: ${{ secrets.somesecrethere }}

What happens here, is as long as the deploy workflow  finishes downloading artifacts from build, it will restart running pip install the packages from requirements.txt, which of course a redundant. How to prevent this and reuse the already installed package instead


text:
Q: Extracting average of raster using overlapping shapefile I am attempting to extract the average value per class in a shapefile (containing Land Use and Land Cover (LULC) classes) of an underlying/overlapping numpy array raster file representing precipitation values.
What packages and/or statements can be used to effectively derive the average precipitation per LULC per raster file?


text:
Q: Resource use in file read/write with python, options and considerations I'm developing in python, still new to the game, and I want to make sure I tackle this problem correctly.  I'll gladly accept all advice.
Imagine trying to use data stored across multiple flat files, in many cases with a combined size exceeding 20-35 gb.  In the most general case, these files may be delimited (csv, tab) or may simply be fixed width. The goal is to take these files, or some subset of each file, parse the input (each column represents a variable in data), and send it to some destination (which could be local or remote sql, some other local file in a variety of output formats including text or some proprietary data format such as stata's .dta)
The goal is to use available system resources to conduct this operation in the quickest way possible ( i guess in terms of kb per second? )
Questions:

*

*Is there an efficiency gain from using compiled C to do the read operations? If so, which library should I learn how to use? And, should c also do the parsing and output?

*If the file comes in a .zip or .gz, should the entire file be decompressed prior to reading and writing, or do you leave it compressed and use a library capable of reading from the compressed file?

*Should the program use multi-threading?  I imagine reading some subset of a file (say, n lines at a time), parsing and outputting in, say, j threads.  It's not obvious that reading the file one line at a time is optimal... and it seems like the optimal number of threads and processes will depend upon the resources available and the size of the job.
So, maybe the code should be 'smart' enough to optimally determine how many threads to use and how much work each thread should be expected to do.

*How does one measure and compare efficiency between different methods?

*Should the program be able to do this dynamically and choose input output methods based on their performance? (Will method A always strictly dominate method B, or do idiosyncratic changes in the deployment environment matter)
Just to be clear, I'm willing to accept almost any level of code inefficiency in exchange for non-negligible improvements in resource efficiency
I hope these questions provide a clear idea of what I'm trying to figure out.  My programming experience is mostly confined to scientific/statistical packages, so if any of my questions boil down to 'rtm', please be gentle and suggest the appropriate manual.

A:
Is there an efficiency gain from using compiled C to do the read operations?

Not really.  The limitation will be I/O bandwidth and Python uses the underlying C libraries.

If the file comes in a .zip or .gz, should the entire file be decompressed prior to reading and writing, or do you leave it compressed and use a library capable of reading from the compressed file?

First, get everything else to work well.  Don't try to finesse this up front.  Python's ZipFile implementation can process CSV format files by opening ZIP archive members without expanding them.
Is this faster?  You can't know in advance.  You can only know by building it and measuring what you built.  Don't wring your hands.  It's only a few lines of code.  Build both.

Should the program use multithreading?

No.
Use OS-level multi-processing.
python something.py source.zip | python part2.py | python part3.py | python part4.py >result

This will be amazingly fast and -- without much work -- will use all the available OS resources.

How does one measure and compare efficiency between different methods?

Ummm... That's a silly question.  You build it and measure it.  Elapsed time is as good a measure as anything else.  If you're confused, use a stop watch.  Seriously.  There's no magic.

Should the program be able to do this dynamically and choose input output methods based on their performance?

No.

(Will method A always strictly dominate method B, or do idiosyncratic changes in the deployment environment matter)

Yes.  And Yes.  Some methods are always more efficient.  However, an OS is hellishly complex, so nothing substitutes for simple, flexible, componentized design.
Build simple pieces that can be flexibly recombined.
Don't hand-wring in advance.  Design the right data structure and algorithm when you can.  When you can't, just pick something sensible and move on.  Building something and tuning is much easier than fretting over details only to find out that they never mattered.

*

*Build Something.

*Measure.

*Find the bottleneck.

*Optimize only the proven bottlenecks.


text:
Q: Create an Info/Help message at top of a custom post type I'm wondering how you go about creating an info/help message at the top of a custom post type in WP's dashboard? I often see these at the top of plugins and Id like to do the same thing for my custom post types if possible (see image below for example --- Note: Screenshot has been taken from NSP-Code's "Post-Types Order" plugin on the settings page")

EDIT #1
Thanks for the help everyone! It appears that I have two distinctly different ways available to me in how I can approach this as outlined by @Stephen & @Bainternet...Both look like viable options so Im going to try them all out and report back with what seems to work best in my situation.
Thanks again for the assistance. WPSE is by far my fav place to learn new things about Wordpress, this place is great.

A: If you want something like this:

Then here's something that does the job:
add_action('admin_footer','print_mynote');
function print_mynote(){
    global $typenow,$pagenow;
    if  (in_array( $pagenow, array( 'post.php', 'post-new.php' ))  && "Post_Type_Name" == $typenow ) {
        ?>

    <?php
    }
}

Just make sure you change Post_Type_Name to the name of your post type, and change PUT your info help message here.... to your actual message.

A: The hook you are after is admin_notices. This is fired at the top of every admin page.
If you wish to restrict the notice to certain pages you can use: get_current_screen() to get the current screen.
 $screen = get_current_screen();

You can wrap the notices in div elements with class 'error' or 'updated' to get the red, or yellow styled notices.
For instance:
function wpse51463_admin_notice(){
      $screen = get_current_screen();

    //If not on the screen with ID 'edit-post' abort.
    if( $screen->id !='edit-post' )
        return;

      ?>

        A notice on the post list screen

        An error message

     <?php

 }
 add_action('admin_notices','wpse51463_admin_notice');

For a plug-ins settings page (nested under the Settings tab) the screen id should be settings_page_{page-name}. You can of course determine the id of a page by using the above to print the current screen id of every page.


text:
Q: Android Sherlock Actionbar onOptionsItemSelected is not called
I m using Sherlock Actionbar to show share option in Action Bar of my application.
  The Share option works fine.
I want to get the option which user selects from Share option, so that I can share
  different text for facebook, messages, mail etc.
For this I am using onOptionsItemSelected function but this function
  is never called.
Please help me to fix this or is there any workaround
  to achieve this. Thanks..

public class MainActivity extends SherlockActivity {

    private ShareActionProvider mShareActionProvider;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        /** Inflating the current activity's menu with res/menu/items.xml */
        getSupportMenuInflater().inflate(R.menu.items, menu);

        mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();

        Intent intent = getDefaultShareIntent();

        if(intent!=null)
            mShareActionProvider.setShareIntent(intent);
        return super.onCreateOptionsMenu(menu);

    }

    /** Returns a share intent */
    private Intent getDefaultShareIntent(){

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");
        intent.putExtra(Intent.EXTRA_TEXT,"Sample Content !!!");
        return intent;
    }

    @Override
    public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
        System.out.println("Testing...................");
        return false;
    }

}

Items.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/share"
        android:title="@string/share"
        android:showAsAction="always"
        android:actionProviderClass="com.actionbarsherlock.widget.ShareActionProvider"
    />
</menu>

A:
For this I am using onOptionsItemSelected function but this function is never called.

It is not supposed to be called. It is not called for any action provider.

I want to get the option which user selects from Share option, so that I can share different text for facebook, messages, mail etc.

That is not directly supported by ShareActionProvider.


text:
Q: AWS Cognito - Reset User Password by sending the code and link to the reset form I'm trying to implement the next logic in AWS Cognito:
AWS lambda catch CustomMessage_ForgotPassword event,
Lambda function returns HTML template, which contains Reset code and what I'm trying to do is to adding a button with the link, which should redirect user to the Cognito form, where he enter Code + new password.
I've create link https://${ENVIRONMENT}/confirmForgotPassword?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_APP}&scope=openid%20profile%20email&response_type=token&user_name=${userName}&confirmation_code={####}.
When I click on the link inside email I navigate to the page, which shows me an error:

I would like to navigate:

The question: Is it possible to send a code with the constructed link to the form by email?

A:
Lambda function returns HTML template, which contains Reset code and what I'm trying to do is to adding a button with the link, which should redirect user to the Cognito form, where he enter Code + new password.

I don't think this is possible. The person should already be on that page, having just clicked the "reset password" link, which triggered your Lambda function to run, so they shouldn't need another link to the same page. Or they just logged in and landed on the reset page, because you flagged their account as needing to reset the password. In either case, they are already on the page that is waiting for them to read the code your Lambda function generated, and type it into the input field. That page is not designed to be refreshed, or loaded directly, as it could pose a security risk if bots could spam that page with different codes.


text:
Q: how do i have constant value without a global variable in C using functions So, i have this code:
#include <stdio.h>

void menu_loop(int run) {
    if (run == 0) {
        printf("bad\n");
        menu();
    }
    else
        printf("good");
}
int check_menu(int menu1) {
    if (menu1 > 3 || menu1 < 0)
        return 0;
    else
      return 1;
}
int menu() {
    int choice;
    printf("----MENU----\n0 -> Exit\n1 -> Prime time\n2 -> Calander calculating\n3 -> Matrix printing\n");
    scanf_s("%d", &choice);
    int check2 = check_menu(choice);
    menu_loop(check2);
}

void main() {
    menu();
}

what i need to do is whenever check_menu returns a 0 then i need to have a certein variable that starts at 0 go up by 1.
everytime i try this i find that the value gets reinitialized to 0 since im initializing it inside the function.
thanks in advance!

A: Returning an error code from a function in case something bad has happened is a common practice in C as it doesn't has a concept of throwing an exception as in more high level languages. I recommend you defining a macro to be more explicit and use a loop instead of recursion.
#include <stdio.h>

#define INVALID_CHOICE_ERR 1

int check_menu(int menu1)
{
    if (menu1 > 3 || menu1 < 0)
        return INVALID_CHOICE_ERR;
    else
        return 0;
}

int menu()
{
    int choice;
    do {
        printf("----MENU----\n0 -> Exit\n1 -> Prime time\n2 -> Calander calculating\n3 -> Matrix printing\n");
        scanf_s("%d", &choice);
    } while (check_menu(choice) == INVALID_CHOICE_ERR);
    // Now that a valid choice has been selected, you can use it
}

void main()
{
    menu();
}

Or you can get rid of the macro and function by simplifying the while loop
while (choice > 3 || choice < 0);

Also I recommend you reading about the disadvantages of scanf() Disadvantages of scanf


text:
Q: Link problem between projects in same solution (Exe depends on Lib) I have one solution with several projects. Say ProjectA is the one that will produce the exe file, and ProjectB simply produces a .lib file. I have checked that ProjectA depends on ProjectB, so that ProjectB will always compile before ProjectA.
When I compile ProjectB everything goes fine. But if I compile ProjectA I get linking errors saying that some method of B does not exist. I have checked, and it does exist.
¿What is going on?
Thanks for your help!

A: Project Properties, Linker, General: Set "Link Library Dependencies" to Yes.

A: I found there were several things I needed to check to fix the vexing link error:

"link.exe" exited with code 1104.

*

*As per @Eric's answer, on the top level (Project A) : Project -> Linker -> General -> Link Library Dependencies : Yes

*Select the parent / top level project, and in the Project Properties prop list, click Project Depdendencies and ensure Project A references Project B

*Somewhat counter intuitively, on ProjectA ensure that you don't have an additional linker library dependency on ProjectB.lib. This seems to encourage to look VS to look for another library called ProjectB.lib, elsewhere.

*

*You do not need to add the output directory of ProjectB to ProjectA's additional Link directories (default is $(SolutionDir)$(Platform)\$(Configuration)\).


text:
Q: Unable to insert data into table with foreign key in oracle11g CREATE TABLE  Client_master (
    Client_no varchar(6) PRIMARY KEY,
    Name varchar(15) NOT NULL,
    City varchar(15),
    Pincode number(8),
    State varchar(15),
    Bal_due Number(10,2),
    CHECK(Client_no LIKE 'C%'));

INSERT INTO
Client_master(Client_no,Name,City,Pincode,State,Bal_due)
VALUES('C00001','Ivan Bayross','Bombay','400054','Maharashtra',15000);

1 row created.

CREATE TABLE  Sales_order(
    Order_no varchar(6) PRIMARY KEY REFERENCES Client_master (Client_no),
    Order_date date,
    Client_no varchar(6),
    Dely_type char(1) DEFAULT 'f',
    Billed_yn char(1),
    Salesman_no varchar(6),
    Dely_date date,
    Order_status varchar(10),
    CHECK(Order_no LIKE 'O%'),
    CHECK(Order_status IN ('inprocess','backorder','cancelled')),
    CHECK(Dely_date>Order_date));

INSERT INTO Sales_order(Order_no, Order_date, Client_no, Dely_type, Billed_yn, Salesman_no, Dely_date, Order_status)
VALUES('C19001','12-jan-96','C00001','f','n','S0001','20-jan-96','inprocess');

INSERT INTO
*
ERROR at line 1:
ORA-02291: integrity constraint (SYSTEM.SYS_C007155) violated - parent key not
found

Please help me insert data into Child table.
What's this  SYSTEM.SYS_C007155 error? Why this error message "parent key is not found"?

A: The parent key not found is because you have a foreign key in your sales_order table which is pointing to the client_master, and there is no matching key value - exactly what it says. But it's because you've done something odd:
Sales_order(Order_no varchar(6) PRIMARY KEY REFERENCES Client_master (Client_no)

You've made the order_no the primary key for this table, but also made it a foreign key to the client_no on the other table. Your insert uses order_no of 'C19001', which doesn't match the client_no you previously inserted into the parent table.
You almost certainly wanted sales_order.client_no to be a foreign key to client_master.client_no, so you would have the references... against that column:
CREATE TABLE  Sales_order(Order_no varchar(6) PRIMARY KEY,
  Order_date date,
  Client_no varchar(6) REFERENCES Client_master (Client_no),
  ...

You have a further problem as the check constraint you have against the order_no is CHECK(Order_no LIKE 'O%') but as mentioned the value you're putting in is 'C19001', which doesn't match the pattern. Presumably you meant the insert to be for 'O19001'; if not then the constraint is defined incorrectly. I actually hit that check constraint before the primary key constrain in 11gR2, so you may just have changed that while posting the question.
You can look in the user_constraints and user_cons_columns views to see what a constraint is doing, but you'll find it easier if you name your constraints instead of letting Oracle give them default names like SYS_C007155:

Specify a name for the constraint. If you omit this identifier, then Oracle Database generates a name with the form SYS_Cn. Oracle stores the name and the definition of the integrity constraint in the USER_, ALL_, and DBA_CONSTRAINTS data dictionary views (in the CONSTRAINT_NAME and SEARCH_CONDITION columns, respectively).

For example:
CREATE TABLE  Client_master (
  Client_no varchar(6),
  Name varchar(15) NOT NULL,
  City varchar(15),
  Pincode number(8),
  State varchar(15),
  Bal_due Number(10,2),
  CONSTRAINT Client_master_pk PRIMARY KEY (Client_no),
  CONSTRAINT Client_master_chk_no CHECK(Client_no LIKE 'C%'));

INSERT INTO Client_master(Client_no,Name,City,Pincode,State,Bal_due)
VALUES('C00001','Ivan Bayross','Bombay','400054','Maharashtra',15000);

1 row inserted.

CREATE TABLE Sales_order (
  Order_no varchar(6),
  Order_date date,
  Client_no varchar(6),
  Dely_type char(1) DEFAULT 'f',
  Billed_yn char(1),
  Salesman_no varchar(6),
  Dely_date date,
  Order_status varchar(10),
  CONSTRAINT Sales_order_pk PRIMARY KEY (Order_no),
  CONSTRAINT Sales_order_fk_client FOREIGN KEY (Client_no)
    REFERENCES Client_master (Client_no),
  CONSTRAINT Sales_order_chk_no CHECK (Order_no LIKE 'O%'),
  CONSTRAINT Sales_order_shk_status CHECK
    (Order_status IN ('inprocess','backorder','cancelled')),
  CONSTRAINT Sales_order_chk_dates CHECK(Dely_date>Order_date));

INSERT INTO Sales_order(Order_no, Order_date, Client_no, Dely_type, Billed_yn, Salesman_no, Dely_date, Order_status)
VALUES('O19001','12-jan-96','C00001','f','n','S0001','20-jan-96','inprocess');

1 row inserted.

If you do have a violation, e.g. with your original order_no value, you'd see a more useful message:
INSERT INTO Sales_order(Order_no, Order_date, Client_no, Dely_type, Billed_yn, Salesman_no, Dely_date, Order_status)
VALUES('C19001','12-jan-96','C00001','f','n','S0001','20-jan-96','inprocess');

ORA-02290: check constraint (YOUR_SCHEMA.SALES_ORDER_CHK_NO) violated

so you can have a better idea which constraint is violated, and what that means, without having to loo in the data dictionary. SALES_ORDER_CHK_NO is easier to interpret than SYS_C007155 Use names that make sense for you of course.
You can name inline constraints too:
CREATE TABLE  Client_master (
  Client_no varchar(6) CONSTRAINT Client_master_pk PRIMARY KEY,
...

CREATE TABLE Sales_order (
  Order_no varchar(6) CONSTRAINT Sales_order_pk PRIMARY KEY,
  Order_date date,
  Client_no varchar(6) CONSTRAINT Sales_order_fk_client REFERENCES Client_master (Client_no),
...

but it might be clearer and easier to maintain with them all grouped together at the end.


text:
Q: speedbar, defn-, clojure-mode I'm using Emacs 24 on OSX.
I'm using speedbar (from Emacs) + clojure-mode (from list-packages -> install).
Let Foo.clj contain the following content:
(defn foo ... )
(defn- bar ...)

In clojure land, this means that foo is meant to be a public function and bar is meant to be a private function.
Right now, both "foo" and "bar" show up in the speedbar. I would like "foo" to show up, and "bar" to not show up.
Thus, my question: how is "speedbar" getting a list of tags from clojure-mode ? And how can I edit this list so that "foo" (from defn) shows up while "bar" (from defn-) does not show up?
Thanks!


text:
Q: Inline code causes ruby interpreter to crash My ruby based data analysis project needs high performance. I plan to create an inline C function that reads a piece of data and updates some global variables, which I can do more processing in ruby.
The following toy code:
require 'inline'
class Foo
  inline :C  do |builder|
    builder.c_raw_singleton <<SRC
     static char *cstr = "hi you'all, welcome";
      void write_global(VALUE self, VALUE *name){
        rb_gv_set(rb_string_value_cstr(name), rb_str_new_cstr(cstr));
        cstr[1] ++;
      }
SRC
  end
end

$bar = ""
Foo.write_global('bar') #=> 1
puts $bar;
Foo.write_global('bar') #=> 1
puts $bar;

will cause exception on ruby interpreter.
I wonder what the problem is.
UPDATE 1
Thanks to @mu-is-too-short who pointed out the constant string can't be modified, I changed it to be a buffer (see the following), but got compile errors like
WARNING: '&cstr[0]' not understood
WARNING: '"%s"' not understood
WARNING: '"hi you'all' not understood
WARNING: 'welcome"' not understood
WARNING: Can't find signature in "\t static char cstr[20];static int f(&cstr[0], \"%s\", \"hi you'all, welcome\");\n      void write_global(VALUE self, VALUE *name){\n        rb_gv_set(rb_string_value_cstr(name), rb_str_new_cstr(cstr));\n\t\tcstr[1] ++;\n      }\n"
inline1a.rb:5:37: error: expected declaration specifiers or '...' before '&' token
     builder.c_raw_singleton <<SRC

Here is the new code that doesn't try to modify constant string.
require 'inline'
class Foo
  inline :C  do |builder|
    builder.c_raw_singleton <<SRC
     static char cstr[20];
     sprintf(&cstr[0], "%s", "hi you'all, welcome");
      void write_global(VALUE self, VALUE *name){
        rb_gv_set(rb_string_value_cstr(name), rb_str_new_cstr(cstr));
        cstr[1] ++;
      }
SRC
  end
end

$bar = ""
Foo.write_global('bar') #=> 1
puts $bar;
Foo.write_global('bar') #=> 1
puts $bar;

A: Your problem is that you're trying to modify read-only memory. If you get all the clutter out of the way, you can show this with a small C program:
int
main(int argc, char **argv) {
  char *cstr = "hi you'all, welcome";
  cstr[1]++;
  return 0;
}

If you compile that and run it you should get a bus error (or similar) because cstr is in read-only memory and cstr[1]++ is trying to modify that read-only memory. There is some discussion on this over in Is it possible to modify a string of char in C? and probably hundreds of other questions in the c tag.
The solution is to not modify cstr. I don't have enough details to offer more concrete advice.

A: Watch out for how RubyInline defines your Ruby methods. If you use c_raw or c_raw_singleton then it uses -1 as the arity in the call to rb_define_method or rb_define_singleton_method, so the method is called as:
VALUE func(int argc, VALUE *argv, VALUE obj)

So in your case your signature should be something like:
VALUE write_global(int argc, VALUE *argv, VALUE self)

Here's a version of your class with that change. I've also moved the cstr declaration into the prefix to avoid a warning and used StringValueCStr instead of rb_string_value_cstr as it is better documented, but I've omitted any error checking (which you should add as otherwise you could get further segfaults):
class Foo
  inline :C  do |builder|

    builder.prefix("static char cstr[] = \"hi you'all, welcome\";")

    builder.c_raw_singleton <<SRC
      VALUE write_global(int argc, VALUE* argv, VALUE self){
        rb_gv_set(StringValueCStr(argv[0]), rb_str_new_cstr(cstr));
        cstr[1] ++;
        return Qnil;
      }
SRC
  end
end

With this class, the output of your code is:
hi you'all, welcome
hj you'all, welcome


text:
Q: Is there a contract for namespace map argument of target's start method in lxml.etree.XMLParser? In lxml, if you use the following script:
#!/usr/bin/env python3

DFXP_BASE_MARKUP = '''<tt xmlns="http://www.w3.org/ns/ttml" xmlns:tts="http://www.w3.org/ns/ttml#styling" />'''

from lxml import etree

class X(object):
    def start(self, name, attrs, nsmap={}):
        if nsmap:
            print("{}: {}".format(etree.LXML_VERSION, dict(nsmap)))

p = etree.XMLParser(target=X())
p.feed(DFXP_BASE_MARKUP)

you might get different results, depending on the version of lxml, for example some of my results were:
(4, 4, 1, 0): {'': 'http://www.w3.org/ns/ttml', 'tts': 'http://www.w3.org/ns/ttml#styling'
(4, 4, 0, 0): {'': 'http://www.w3.org/ns/ttml', 'tts': 'http://www.w3.org/ns/ttml#styling'}
(4, 3, 5, 0): {None: 'http://www.w3.org/ns/ttml', 'tts': 'http://www.w3.org/ns/ttml#styling'}
(4, 3, 4, 0): {None: 'http://www.w3.org/ns/ttml', 'tts': 'http://www.w3.org/ns/ttml#styling'}

The problem is that the default namespace is sometimes associated with the key '' and sometimes None. It looks like the behaviour changed in lxml-4.4.0. It seems like a rather relevant change and I can see no mention of it in the release notes.
I have actually come across this problem debugging through pycaption -> beautifulsoup4 -> lxml. It appears that beautifulsoup produces invalid XML because of this, when used together with >=lxml-4.4.0. For me the solution is to use an old enough version of lxml, but it looks like it might be a major issue for beautifulsoup4 for example.
Have you come across this problem? Is there any place in the documentation which specifies which key we should expect in this situation or indicates that both are allowed by the contract?


text:
Q: Scrape Dynamic information from html I have dynamic information displayed in html
0.5936

gives

4,000

Using python I would like to track changes in the number
I have been using beautiful soup to find the span and then the class to find the number
how can I do this every time it changes?

A: If the changes are driven by javascript you will need to use something that interprets the javascript (or connects to something else that does) like selenium.
EDIT: clarification


text:
Q: iFrame modal scrolling on ipad/iphone I'm working on a project on which I'm creating a modal. Basically, I have an overlay with position: fixed; The overlay contains an iFrame with the content of the modal. The iFrame can vary in height and when it does not fit the viewport the content gets cut off. Furthermore, when I scroll in the modal the only thing that scrolls is the background layer behind the overlay.
You are supposed to be able to scroll down in the iframe without the background layer moves. How can I achieve this?
Everything works fine in Firefox, Safari, Chrome and even in IE8. However, the issue only appears on iPad/iPhone.
You can see a working demo of the issue here: http://mcash.dk/dev/overlay/

A: Basically you need to enclose the iframe in a container div and then style the container with
-webkit-overflow-scrolling:touch

Read more here:
IFRAMEs and the Safari on the iPad, how can the user scroll the content?


text:
Q: Using variables instead of state Is it still possible to render variables in react? Trying to use a more lightweight method of storing data on a component, but variables don't seem to render anymore in react. Is useRef the new method for variables or is it still possible in basic let variables.
Here is an example of variables not rendering in react:
https://codesandbox.io/s/serene-galileo-ml3f0?fontsize=14

A: You have a misconception about how React handles state. The reason why normal variables don't seem to work in React is actually an optimization. React only rerenders the elements on your page when absolutely necessary. The way you tell React "hey, my state changed, can you update the page to reflect that" is by using state variables. In your example, React only rerenders the elements that reference the b variable when you update it using setB. However, it does not rerender the elements that represent a when you update it using a++, because it has no way to detect that a was updated.
useState is actually more efficient than local variables, because it rerenders only what is necessary.

A: see virchau13's answer.
Although saving to a state is more intensive than a simple variable assignment, you have to take into account that what you see on the screen will only change via renders. So if you wanted to see the display increment on the screen, it will only do so via renders, which is most easily achieved through state changes.


text:
Q: Floating-point arithmetic issue (300.2 - 300 = 0.1999...) Description
So I wrote the following calculation:
var valueWithoutIntegers = value - Math.floor(value);

This statement seems to do the job just fine, except when I had the value value = 300.2. So basically I had :
0.19999999999998863 = 300.2 - Math.floor(300.2)

So I fiddle around quickly in my JavaScript console:
300.2 - Math.floor(300.0) // gives 0.19999999999998863
300.2 - Math.floor(300.1) // gives 0.19999999999998863
300.2 - Math.floor(300.0) // gives 0.19999999999998863
300.2 - 300               // gives 0.19999999999998863
300.2 - 300.1             // gives 0.0999999999999659

So I was all like... WTF right? But I thought, maybe I need to help the laws of physics, I mean floating points in computer science. So I googled a bit and tried out:
Number((300.2).toFixed(2)) - Number((300.2).toFixed(0)) // gives 0.19999999999998863
Number((300.2).toFixed(2)) - Number((300.2).toFixed(2)) // gives 0, makes sense!
300.2 - Number((300.2).toFixed(0))                      // gives 0.19999999999998863
Number(300.2) - Number(300)                             // gives 0.19999999999998863

Yikes ! Feel free to run any of these statements in your JavaScript console. I ran it in my Google Chrome and in my local Node.JS application.
So my questions

*

*Where does this magic come from? I don't see why this would be a corner case, I only used 1 number after the decimal! Not like, 200.

*How can I refactor my statement, so I won't have to deal with this or other edge cases?


text:
Q: Combine Images for overlay I try to do something similar to this post: related question
Now I try to combine several stencils. The combined stencil looks as expected, however the inverted group is either black or white, depending on the order of the group created.  The result I get:

It seems that the grouping still takes some Blend-information of the childs, or maybe I just don't get the idea of the blends. Any Idea how I can achieve an overlay as in the old question but with several stencils?
Here are the images:

package application;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.effect.BlendMode;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Main extends Application {
@Override
public void start(Stage stage) {
    Image original = new Image(getClass().getResourceAsStream("image.jpg"));

    Image stencil1 = new Image(getClass().getResourceAsStream("stencil.jpg"));

    Image stencil2 = new Image(getClass().getResourceAsStream("stencil2.jpg"));

    Image stencil3 = new Image(getClass().getResourceAsStream("stencil3.jpg"));

    ImageView iv = new ImageView(stencil1);
    ImageView iv2 = new ImageView(stencil2);
    ImageView iv3 = new ImageView(stencil3);

    iv2.setBlendMode(BlendMode.ADD);
    iv3.setBlendMode(BlendMode.ADD);
    Group stencil = new Group();

    stencil.getChildren().add(iv);
    stencil.getChildren().add(iv2);
    stencil.getChildren().add(iv3);

    Rectangle whiteRect = new Rectangle(original.getWidth(), original.getHeight());
    whiteRect.setFill(Color.WHITE);
    whiteRect.setBlendMode(BlendMode.DIFFERENCE);

    Group inverted = new Group(stencil, whiteRect);

    // display the original, composite image and stencil.
    HBox layout = new HBox(10);
    layout.getChildren().addAll(new ImageView(original), inverted, stencil);
    layout.setPadding(new Insets(10));
    stage.setScene(new Scene(layout));
    stage.show();

}

public static void main(String[] args) {
    launch();
}
}

A: I finally figured it out myself. The trick is to create always new instances of the ImageView objects, as the blending modes are applied down the scene-graph 'till the imageview-objects.
here is the code snipped that worked for me:
        package application;
    import javafx.application.Application;
    import javafx.geometry.Insets;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.effect.BlendMode;
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import javafx.scene.layout.HBox;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Rectangle;
    import javafx.stage.Stage;

    public class Main extends Application {

        private ImageView originalImageView;
        private ImageView stencilImageView;
        private Image original;
        private Image stencil;
        private Image stencil2;

        private Rectangle whiteRect;
        private Group inverted;

        private Group overlaidBlack;

        private Rectangle redRect;

        private Group redStencil;
        private Group overlaidRed;

        private ImageView stencilImageView2;
        private Group to;
        private Group to2;

        @Override
        public void start(Stage stage) {

            original = new Image(getClass().getResourceAsStream("image.jpg"));

            stencil = new Image(getClass().getResourceAsStream("stencil.jpg"));
            stencil2 = new Image(getClass().getResourceAsStream("stencil2.jpg"));

            stencilImageView = new ImageView(stencil);

            // first invert the stencil so that it is black on white rather than white on black.
            whiteRect = new Rectangle(stencil.getWidth(), stencil.getHeight());
            whiteRect.setFill(Color.WHITE);
            whiteRect.setBlendMode(BlendMode.DIFFERENCE);

            stencilImageView2 = new ImageView(stencil2);

            stencilImageView2.setBlendMode(BlendMode.ADD);

            to = new Group(stencilImageView, stencilImageView2);

            ImageView tmpIv = new ImageView(stencil2);
            tmpIv.setBlendMode(BlendMode.ADD);
            to2 = new Group(new ImageView(stencil), tmpIv);

            inverted = new Group(to, whiteRect);

            originalImageView = new ImageView(original);

            overlaidBlack = new Group(originalImageView, inverted);

            inverted.setBlendMode(BlendMode.MULTIPLY);

            overlaidBlack = new Group(originalImageView, inverted);

            // create a new mask with a red tint (red on black).
            redRect = new Rectangle(stencil.getWidth(), stencil.getHeight());
            redRect.setFill(Color.RED);
            redRect.setBlendMode(BlendMode.MULTIPLY);

            redStencil = new Group(to2, redRect);

            redStencil.setBlendMode(BlendMode.ADD);

            overlaidRed = new Group(overlaidBlack, redStencil);

            // display the original, composite image and stencil.
            HBox layout = new HBox(10);
            layout.getChildren().addAll(new ImageView(original), overlaidRed);

            layout.setPadding(new Insets(10));
            stage.setScene(new Scene(layout));
            stage.show();
        }

        public static void main(String[] args) {
            launch();
        }
    }


text:
Q: Preserving the Timestamp details in java I've an input string as
2020-01-21T02:16:51.8320Z
I need to parse this string into a java Date object.
I tried using following code.
LocalDate localDate = LocalDate.parse(date, flexUtcDtf);
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

Output:
Wed Jan 22 00:00:00 EST 2020
Is it possible to get the output as following Date object instead?(i.e. preserving the time details as well)
Wed Jan 21 02:46:51.8320 EST 2020
Thanks.

A: java.util.Date
.from(
    Instant.parse(
        "2020-01-21T02:16:51.8320Z"
    )
)
.toString()

Beware of data loss. Your input has a fourth digit of decimal fraction of a second. That means microseconds. The Instant class can handle that. But the legacy Date class you asked for cannot, and is limited to milliseconds. So any microseconds will be lopped off, truncated to milliseconds.
The terrible legacy classes such as java.util.Date have been given new methods to facilitate converting back and forth between the modern java.time classes. Here we are using Date.from( Instant ) to produce a legacy date from the modern Instant parsed from your input.
Beware that Date has many flaws and problems. Among those is the behavior of its toString method. That method takes the value of the Date which is a moment in UTC, and then applies the JVM's current default time zone while generating the text. This creates the illusion of  that time zone being part of the Date.
I suggest you avoid Date entirely, and use only the java.time classes. But my code here answers the Question as asked.
Also, your desired output format is a terrible one. Instead, use ISO 8601 standard formats for data exchange. For presentation to the user, use DateTimeFormatter.ofLocalizedDateTime. Both of these topics have been addressed many times on Stack Overflow, so search to learn more.

A: First - congratulations on using the Java 8 time functions - wise choice!
Per your question:

*

*This is the way to convert "LocalDate" to "java.util.Date":
Date myDate =  Date.from(localDate.atZone(ZoneId.systemDefault()).toInstant());

... or ...

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

Per the documentation:

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
LocalDate is an immutable date-time object that represents a date,
  often viewed as year-month-day. Other date fields, such as
  day-of-year, day-of-week and week-of-year, can also be accessed. For
  example, the value "2nd October 2007" can be stored in a LocalDate.
This class does not store or represent a time or time-zone. Instead,
  it is a description of the date, as used for birthdays. It cannot
  represent an instant on the time-line without additional information
  such as an offset or time-zone.

*So a better choice might be LocalDateTime

*In either case, "java.util.Date" automatically has "everything you need".  It is a "date/time" object. It stores date and time, irrespective of any time zone.


text:
Q: Attribute get erased after initialization - kotlin I'm working in a Android project using Kotlin. I have this piece of code:
val foo = FooClass(this)
var colorRunning = FooClass.getProperty("myproperty")

and the class FooClass is:
class FooClass(val context: Context) : SomeHeritance{
    private val styles: HashMap<String, String> = hashMapOf()

override fun onCreate(context: Context?) {
    Log.e("Hash is empty here", this.styles.size.toString())

    this.styles.put("a","a")
    this.styles.put("b","a")
    this.styles.put("c","a")

    Log.e("Hash is size is 3", this.styles.size.toString())

}

override fun getProperty(someProp: String) {
    Log.e("Hash is size is 0", this.styles.size.toString()) //I don't understand why
    return styles[someProp]!!
}

The problem is that the HashMap styles get initialized in the onCreate method, but when I want to access to some of the values there from the method getPropery the HashMap is empty.
Making some tests, I could check that if I initialize the HashMap on the method getProperty the hash remains initialized.

A: Seems like your onCreate is not called on start. Put the init of your Map inside an init block:
init {
   with(styles){
       put("a","a")
       put("b","a")
       put("c","a")
   }
}

That way you can be sure to have the values put into the map before accessing it.
Also make sure to hande null values in your getProperty correctly. Instead of !! you could throw an Exception:
fun getProperty(someProp: String): String
        = styles[someProp] ?: throw IllegalArgumentException()


text:
Q: Extract month from datetime column in pandas DataFrame I have a DataFrame read from Excel with one of the columns of type DateTime.
sales_data=pandas.read_excel(r'Sample Sales Data.xlsx')

I was able to extract substrings from other columns using str.extract/lambda functions. But I was unable to process the column "Order Date"
The command sales_data['Order Date'] gives the below output

As recommended in other StackOverflow questions, I tried with
sales_data['Order Date'].apply(lambda x:x.str.slice())

I got an error that : AttributeError: 'datetime.datetime' object has no attribute 'str'
To check the type of the Order date column, I tried
sales_data['Order Date'].apply(lambda x:type(x))

I got the type datetime.datetime
But when I tried the datetime operation
sales_data['Order Date'].apply(lambda x:x.strftime("m"))

I got the error: AttributeError: 'int' object has no attribute 'strftime'
I got a similar error for the command
sales_data['Order Date'].apply(lambda x:x.dt.month)

Please suggest a method to extract month from the datetime object into another column without iterating through the DataFrame. I am not able to use datetime or int functions with this column since it is behaving as both a datetime and int column.

A: Use dt accessor:
sales_data=pandas.read_excel(r'Sample Sales Data.xlsx', parse_dates=['Order Date'])
sales_data['Order Date'].dt.month

Suppose this dataframe:
>>> sales_data
            Order Date
0  2016-01-01 00:00:00
1  2016-03-28 22:00:00

>>> sales_data['month'] = sales_data['Order Date'].dt.month
>>> sales_data
           Order Date  month
0 2016-01-01 00:00:00      1
1 2016-03-28 22:00:00      3

A: Try using pd.to_datetime to ensure your columns dtype is datetime. Then use dt.month to extract the month. You can also extract day and year by using dt.day, dt.year respectively.
import pandas as pd

sales_data = pd.read_excel(r'Sample Sales Data.xlsx')
sales_data['Order_Month'] = pd.to_datetime(sales_data['Order Date']).dt.month

A: I found the issue.
The sales_data['Order Date'] column had a mix of both date and int values due to some input data inaccuracy.
I found this since
sales_data['DateType']=sales_data['Order Date'].apply(lambda x:type(x))
sales_data['DateType'].unique()

returned array([<class 'datetime.datetime'>, <class 'int'>], dtype=object)
I cleaned this DataFrame by filtering out the values without the datetype as datetime.
type1=type(sales_data['DateType'][0])
new_df=sales_data[sales_data['DataType']==type1]

Now the new dataframe supports the date and string operations.
pd.to_datetime(new_df['Order Date']).dt.month

This can be assigned to other columns.


text:
Q: How to correctly use network stream to get data? I have an app communicates with industry machines through TCP/IP protocol.
It should come out something after I send an command to the machine's end point.
However, though I have implemented it with the way that Microsoft document shows,
my app never reads the data from the network stream.
Here is the code:
//The tcp client has been connected here.
if (client.Connected)
{
    var stream = client.GetStream();

    if (stream.CanWrite)
    {
        var bytes = Encoding.ASCII.GetBytes("010000000004");

        stream.Write(bytes, 0, bytes.Length);

        stream.Flush();
    }

    while(stream.DataAvailable is false) //keep sleeping when the data is not available
    {
        Thread.Sleep(10);
    }//The loop will be endless

    if (stream.CanRead) //I can't get to this step
    {
        var reader = new StreamReader(stream, Encoding.ASCII);

        var result = reader.ReadLine();
    }
}

I want to get the message from the machine so that I can interact with it.


text:
Q: Inference problem, having issues translating problem from words into probabilistic terms This is the question:
There are particular readers for swipe cards, Under normal operating conditions, there is a small probability of 0.02 that swiping a card fails to open
the entrance - some of these readers have a particular
fault. If this fault occurs, then the probability of swipe failure rises to 0.1.
an estimate says that 22% of all the readers it has sold
so far have this fault. It decides to send technicians around to test all the readers it has sold,
and replace the faulty ones. You are tasked with designing a rule to help the technicians decide
whether or not a card reader is faulty. They are to test each reader by swiping a card through it
repeatedly in successive independent trials, until a failure occurs on the N-th trial. Based on N,
the technician must decide whether or not the tested reader is faulty.
My question and answer:
Translating problems like this from words to math has always been a problem for me; I'm trying to work out the two main random variables as per a question, my answer so far has been that it is two Bernoulli random variables where one describes the probablility of a faulty card reader and the other one describes the probability of swipe failure, where you can use the law of total probability to determine the values.
P(Fail|Fault) = 0.1, P(Fail|Fault') = 0.02, P(Pass|Fault) = 0.9, P(Pass|Fault') = 0.98.
The bit that confuses me is when they ask for the two main random variables, as far as I know N is a random variable too correct? So am I interpreting the conditional variables incorrectly in the above paragraph?

A: Welcome to CV. Nice question. Here's my attempt:
Let $X$ be random variable such that $X=k$ denotes, first swipe failure occurs in $k^{th}$ swipe. Let the probability of swipe failure in any random swipe be $p_x$. So we have:
$$X \sim Geometric(p_x)$$
Now define another random variable $Y$ that takes value $1$ if machine is faulty and $0$ otherwise. So  we have:
$$Y \sim Bern(p_y)$$
Also,
$$Pr(X=x)=\sum_y Pr(X=x|Y=y)Pr(Y=y)$$
Now, $$Pr(X=N|Y=1)Pr(Y=1) = (1-p_{x|y=1})^{N-1}p_{x|y=1}p_y = (1-0.1)^{N-1}*0.1*0.22$$
Similarly, $$Pr(X=N|Y=0)Pr(Y=0) = (1-p_{x|y=0})^{N-1}p_{x|y=0}(1-p_y) = (1-0.02)^{N-1}*0.02*0.78$$
Therefore, $$Pr(X=N)=0.1*0.22*0.9^{N-1}+0.02*0.78*0.98^{N-1}$$
Now the technician only observes $N$ and must decide whether machine is faulty. So we are interested in:
$$Pr(Y=1|X=N)$$
Using Bayes:
$$Pr(Y=1|X=N)=\frac{Pr(X=N|Y=1)Pr(Y=1)}{Pr(X=N)}$$
Let us assume that technician decides that the machine is faulty if $Pr(Y=1|X=N)\geq0.95$
So, we finally have:
$$\frac{0.1*0.22*0.9^{N-1}}{0.1*0.22*0.9^{N-1}+0.02*0.78*0.98^{N-1}}\geq0.95$$
From here you can calculate an upper bound on $N$. Hope there aren't any mistakes.


text:
Q: How to transform a CompactBuffer to List How can I transform a CompactBuffer to List? an example is as below:
data.csv
1,Lokesh
2,Bhupesh
2,Amit
2,Ratan
2,Dinesh
1,Pavan
1,Tejas
2,Sheela
1,Kumar
1,Venkat
val r = sc.textFile("data96/data.csv")
val rm = r.map(x=>(x.split(",")(0), x.split(",")(1)))

val r_grp = rm.groupByKey

Array[(String, Iterable[String])] = Array((2,CompactBuffer(Bhupesh,
  Amit, Ratan, Dinesh, Sheela)), (1,CompactBuffer(Lokesh, Pavan, Tejas,
  Kumar, Venkat)))

r_grp.foreach(println(_))
(1,CompactBuffer(Lokesh, Pavan, Tejas, Kumar, Venkat))
(2,CompactBuffer(Bhupesh, Amit, Ratan, Dinesh, Sheela))

So, it is easy to get the CompactBuffer format. The following will generate the result in List format, which is what I want to present.
val swapped = rm.map(item=>item.swap)

val com= rm.combineByKey(List(_), (x:List[String], y:String) =>y::x,(x:List[String], y:List[String])=>x:::y) //this is terrible to me, I don't want to do this way

Array[(String, List[String])] = Array((2,List(Dinesh, Ratan, Amit,
  Bhupesh, Sheela)), (1,List(Lokesh, Venkat, Kumar, Tejas, Pavan)))

com.repartition(1).saveAsTextFile("data96/s43")

Generated result:
hdfs dfs -cat data96/s43/*
(2,List(Dinesh, Ratan, Amit, Bhupesh, Sheela))
(1,List(Lokesh, Venkat, Kumar, Tejas, Pavan))

It's much easier to get the result in CompactBuffer format, but I need to get List format and don't want to go through the highlighted terrible confusing command.
By the way, how do I further sort each group in asc or desc?

A: You can simply change CopmpactBuffer to list with toList method
val r_grp = rm.groupByKey
// After groupBykey
(2,CompactBuffer(Bhupesh, Amit, Ratan, Dinesh, Sheela))
(1,CompactBuffer(Lokesh, Pavan, Tejas, Kumar, Venkat))

Simply use toList to convert to List and sortBy to sort it
val com = r_grp.map(x => (x._1, x._2.toList.sortBy(x => x)))
com.foreach(println)

Output :
(1,List(Kumar, Lokesh, Pavan, Tejas, Venkat))
(2,List(Amit, Bhupesh, Dinesh, Ratan, Sheela))


text:
Q: Indeterminate form of limit: is it obligatory to write it? I'm preparing for a Limits/Derivatives exam.
I have two very basic questions that I couldn't find an answer to.
Question 1: when calculating limit of a sequence or of a function, do I always have to write down the indeterminate form? If I solve the limit without writing down the indeterminate form, would it be incorrect (not full answer)?
Question 2: I am familiar with all seven indeterminate forms, however would it be correct to write it down like that? Example:
$$ \lim \frac{n}{n-1} = \bigg[ \frac{\infty}{\infty -1} \bigg] = \bigg[ \frac{\infty}{\infty} \bigg] = \text{. . . rest of solution . . .}$$
Of course I could write down the $\bigg[ \frac{\infty}{\infty} \bigg]$ right away. I came up with this simple example on purpose. $ \bigg[ \frac{\infty}{\infty -1} \bigg] $ - just need to know if such symbol is correct to use.
So essentially I need to know whether it's okay to "do calculations on the indeterminate form, inside the square brackets".
Thanks!

A: None of us can answer on behalf of your teacher/lecturer, but here comes my personal take on your questions:
Q1: I would say it is always good practice to state that the given limit is of one of the indeterminate forms (if this is the case!). I would say that probably 99% of the questions about limits ever given out at exams are about indeterminate forms - this is just because teachers want to 'test' students' knowledge on 'difficult' cases. However, it is not impossible that the teacher would put one or more non-indeterminate forms in their exam, just to test that students are able to spot them and act accordingly! It is not unheard of to have students who apply L'Hopital rule without thinking twice to limits $\lim_{x\to x_0} f(x)$ that are simply equal to $f(x_0)$ by continuity (no indeterminate form whatsoever!). Therefore, I would say it is always good to check at the very beginning of the calculation that you are truly facing an indeterminate form, and state so explicitly.
Q2: I do not have experience of the symbol $\lbrack \frac{\infty}{\infty -1} \rbrack$ been ever used. You can just state in words that 'this limit is in the indeterminate form $[\frac{\infty}{\infty}]$'. What you should probably not do (in general) is to continue writing your solution by putting an equal sign after $[\frac{\infty}{\infty}]$, that is to say: it is not OK in general to keep working inside square brackets. Once you know it is an indeterminate form, that's when you need to start working on the function and perform algebraic manipulations on it - I don't see how you can do that on the symbolic expression $[\frac{\infty}{\infty}]$!


text:
Q: Fish shell functions show $argv in job control, not file I'm trying to switch to fish shell but I've run into one sticking point. If I alias vi to vim and edit a file, I can't see which file I'm editing in job control.
polis@josh1 ~> function testvi
                   vim $argv
               end
polis@josh1 ~> functions testvi
function testvi
    vim $argv
end
polis@josh1 ~> testvi foobar
polis@josh1 ~> jobs
Job Group   CPU State   Command
2   26087   0%  stopped vim $argv

How do I make it so the output is:
2   26087   0%  stopped vim foobar

A: This is a situation where a command abbreviation is preferable to an alias (i.e., a function):
abbr -a vi vim

Now when you type "vi" and press space it will be magically replaced by "vim". You can do more complicated expansions. For example I use these abbreviations quite a bit:
abbr -a gca git commit --amend
abbr -a gcm git checkout master

The advantages of the abbreviation is they are much simpler than a function and the expansion shows up in your shell history which I find more useful than an aliased function name.

A: The idea is we want to expand $argv first into a new command, and then execute that. We can do that with eval.
However, this has the wrinkle that any special characters in the new command will be interpreted, so we need to escape them first.
The overall function is:
function testvi
    eval "vim "(string escape $argv)
end

This uses the new string builtin, which is in the just-released fish 2.3.0.
Illustration of the result, here editing a file 'foobar $baz' to show that escaping works:
> testvi 'foobar $baz'
> jobs
Job Group   State   Command
 5  60249   stopped vim 'foobar $baz'


text:
Q: Edit a specific part of a txt file and save the changes I'm trying to display information from a txt file and then save whatever changes were made and write it back to the txt file.
            with open("tasks.txt", 'r') as t_file:
                for line in t_file:
                    if line.startswith(username):
                        users_tasks_list.append(line)
                        for count, ele in enumerate(users_tasks_list, 1):
                            if task_select == int(count):
                                task_info = ele.split(",")
                                # I want to display the information in this format
                                print("\n" + " Task:\t\t" + task_info[1]
                                      + "\n" + "Assigned to:\t\t " + task_info[0]
                                      + "\n" + "Date assigned:\t" + task_info[3]
                                      + "\n" + "Due date:\t\t" + task_info[4]
                                      + "\n" + "Task complete?\t" + task_info[5]
                                      + "\n" + "Description:"
                                      + "\n" + task_info[2])

                                while True:
                                    # If the task is not completed entering 1 must change No to Yes
                                    # Entering 2 should allow you to edit the user of the task or the due date
                                    task_edit = int(input("\nEnter 1 to mark the task as complete \nEnter 2 to edit the task \nEnter 0 to return \n"))
                                    if task_edit == 1:
                                        task_info[5] = "Yes"
                                        t_file = open("tasks.txt", "w")
                                        user_tasks = " ".join(users_tasks_list)
                                        t_file.write(user_tasks)
                                        t_file.close()
                                        print("Task completed")

                                    elif task_edit == 2:
                                        print("success")
                                        if task_info[5] == "No":
                                            task_change = int(input("\nEnter 1 to edit the User \nEnter 2 to edit the due date of the task \n"))

This is what I have, I'm struggling to save the information back to the txt file.
The information on the txt file is in the format below:
assigned to (e.g. user), task title, task description, date assigned (in the format: dd mmm yyyy), due date (in the format: dd mmm yyyy), task complete (e.g. No)
Each task should be on a new line.
Any help will be greatly appreciated.


text:
Q: Strange Behaviour: SQL And operator with multiple IN operators I am using multiple IN operators with AND in my sql query where clause as given below...
---
where ID in (1, 3, 234, 2332, 2123, 989) AND tag in ('wow', 'wonderful')

But surprisingly behaviour of result seems to be of OR type rather then AND type. What I mean is it is ignoring AND operator...
Can you please explain me why?

A: I couldn't reproduce the result using SQL Server 2008.

SELECT * FROM
(
  SELECT 0 AS ID, 'wow' as Tag
) X
WHERE ID in (1, 3, 234, 2332, 2123, 989) AND tag in ('wow', 'wonderful')

Result:
No records

SELECT * FROM
(
  SELECT 1 AS ID, 'wow' as Tag
) X
WHERE ID in (1, 3, 234, 2332, 2123, 989) AND tag in ('wow', 'wonderful')

Result:

ID    Tag
1  wow

Check your code again.


text:
Q: Transaction tx = graphDatabaseService.beginTx(); is null in neo4j embedded version 2.3.8 Below is my code. When i call graphDatabaseService.beginTx() it is giving nullPointerException. Is there any other ways to create Transaction in Neo4j
 protected Record getNext() throws Exception {
Transaction tx = graphDatabaseService.beginTx();
    try {
    if (hits == null) {
        hits = index.query(query);
       tx.success();
    }
    T next = hits.next();
    if (next == null) {
        return finished();
    } else {
        return nodeToRecord.call(next);
    }
    }
    finally{
        closeIndexResults(hits);
         tx.close();
    }
}

A: Your graphDatabaseService variable has a null value. Make sure you have properly initialized it before getNext() is called. For example:
GraphDatabaseService graphDatabaseService = new GraphDatabaseFactory().newEmbeddedDatabase(dbPath);


text:
Q: MySql - only update some rows if the table exists - do not want an error thrown I want to run an update query.
The query will be run against multiple databases - not every database will have the table.
I don't want the update to be attempted if the table does not exist.  I don't want any error to be thrown - I just want the update to be ignored.
Any ideas?
EDIT: just to be clear - the query is executed in an automated deployment - no human interaction possible.
EDIT2: the logic to say whether the update should run or not will need to be in the MySql query itself.  This is not being run through a command prompt or batch or managed code.

A: To do this in native MySQL (like in a mysql script), you could use a stored procedure.
This would be appropriate for a one-off administrative type function, you wouldn't want to do this as part of an application. (Then again, if this were part of an application, you would have the conditional logic to control whether an UPDATE is performed, or to catch and handle the exception if the table doesn't exist.)
Here's an example of a stored procedure that uses a CONTINUE HANDLER to catch error 1146 (table does not exist) and swallow it, so that no error is returned to the caller.

DELIMITER //
DROP PROCEDURE IF EXISTS `table_doesnt_exist_handler`//
CREATE DEFINER=`root`@`%` PROCEDURE `table_doesnt_exist_handler`()
BEGIN
  DECLARE table_doesnt_exist BOOLEAN;
  DECLARE CONTINUE HANDLER FOR 1146 SET table_doesnt_exist = TRUE;

  UPDATE table_doesnt_exist SET foo = 1 WHERE foo = 1;

END//
CALL `table_doesnt_exist_handler`()//
DROP PROCEDURE IF EXISTS `table_doesnt_exist_handler`//
DELIMITER ;

Another option is to test for the existence of the table, and conditionally running the statement. In native MySQL, again, this would need to be done inside a stored procedure.
DELIMITER //
DROP PROCEDURE IF EXISTS `table_doesnt_exist_approach_2`//
CREATE DEFINER=`root`@`%` PROCEDURE `table_doesnt_exist_approach_2`()
BEGIN
  SELECT @table_exists := COUNT(1) AS table_exists
    FROM information_schema.tables
   WHERE table_schema = DATABASE()
     AND table_name = 'table_doesnt_exist';
  IF  @table_exists > 0 THEN
    UPDATE table_doesnt_exist SET foo = 2 WHERE foo = 1;
  END IF;
END//

CALL `table_doesnt_exist_approach_2`()//
DROP PROCEDURE IF EXISTS `table_doesnt_exist_approach_2`//
DELIMITER ;

My preference would be to go with the CONTINUE HANDLER.

A: You could do something like do a describe on the table name and if the result is empty then dont run the update. You can do this in a short script, although I'm not sure what language your using. You could also probably manage it in a stored procedure if your looking strictly DB here.

A: You can first run a query to see if that table exists and then run the actual query.
Ex:
table_exists_query = Select count(*) from INFORMATION_SCHEMA.tables where table_name='xxxx';

if(run_query(table_exists_query)==1)
    run the actual query


text:
Q: Tamanho dos elementos numa pagina responsiva Estou numa situação bastante complicada, já pesquisei em diversos lugares e não sei se estou pesquisando certo, entretanto, minha dúvida é a seguinte:
Em muitos sites temos a seguinte configuração de composição em uma página: um cabeçalho com a nome do site, uma barra de navegação abaixo do cabeçalho, um corpo com conteúdo abaixo da barra de navegação e por fim um rodapé abaixo do corpo.
Entretanto existem várias duvidas que me cercam com relação a isso.
Já que eu teria colunas uma abaixo da outra, o celular jogaria o tamanho da coluna na tela toda, mas no desktop se eu atribuir um tamanho em porcentagem para as colunas, então, isto também teria efeito no celular e ficaria horrível.
Por outro lado, se eu não definir tamanho algum para as
 e deixá-las se comportarem de acordo com a quantidade de conteúdo, isso ficaria estranho, pois dependendo do texto do corpo a
 de conteúdo iria variar de tamanho e meu  ficaria pulando pra cima e pra baixo.

A: Nas tags você indica que sua dúvida tem relação ao Bootstrap 3. Então, você precisa entender o conceito de grid Exemplos pra resolver sua questão. Outros conceitos são margin e padding, mas o grid é o mais importante aqui.
Também presumi, que você tenha algum conhecimento de criação de sites não responsivos.
E este é que é o problema.
Depois de 15 anos fazendo sites com
 e depois com o CSS anterior ao CSS3, também tive dificuldades pra entender coisas como esta.
Notei que você fala em colunas uma abaixo da outra... Colunas ficam uma ao lado da outra. Linhas ficam uma abaixo da outra.
No bootstrap você aninha colunas dentro de linhas.

coluna 4/12 = 1/3

coluna 4/12 = 1/3

coluna 4/12 = 1/3

.coluna 3/12 = 1/4

coluna 4/12 = 1/3

coluna 5/12

Este código cria duas linhas, cada uma com três colunas.
A primeira linha tem 3 colunas da mesma largura, cada uma com um terço do tamanho.
A segunda linha também com 3 colunas. cada uma com um tamanho diferente.
Você notou que dividi por 12? É porque o grid do bootstrap faz isso. Ele divide a largura da tela em 12 partes.
Tambem deve ter notado o md. Este é um modificador de classe que indica que esta regra se aplica a monitores médios (pense tablet) para cima.
Ou seja col-md-3, pode ser lido como ocupe um quarto (3/12=1/4) se a tela do dispositivo for média.
Agora, pense mobile first, porque as regras do bootstrap são aplicadas de baixo para cima (em termos de tamanho).
Se você usar col-sm-7 estará dizendo ocupe 7 espaços de 12, quando a tela for pequena.
Então, não defina tamanhos absolutos ou percentuais para as div. Entenda o grid e adapte o layout do site para usa-lo.
No design responsivo, você pode criar uma versão de layout para cada tamanho de tela (jeito antigo, sem frameworks como boostrap) e ter a maior dor de cabeça pra manter as coisas funcionando. Ou pode entender melhor o conceito e fazer um único código para qualquer dispositivo.
Conceitos a estudar: grid, margin e padding.
Site do Boostrap em português


text:
Q: With pytest and factory-boy, how do I create a factory for a non-traditional type of object? I'm using Django 2, Python 3.7 and factory-boy.  Trying to create a factory for the django-address' AddressField -- https://pypi.org/project/django-address/ , which I guess is a non-traditional model, in that it doesn't inherit from models.Model.  I created this factory, using objects = models.Manager() ...
class AddressFactory(factory.DjangoModelFactory):
    """
        Define Address Factory
    """
    objects = models.Manager()

    class Meta:
        model = AddressField

    street_number = "123"
    route = "Rd"
    raw = "123 Fake Rd"
    formatted = "123 Fake Rd."
    latitude = 87.1234
    longitude = -100.12342
    locality = factory.SubFactory(LocalityFactory)

class CoopFactory(factory.DjangoModelFactory):
    """
        Define Coop Factory
    """
    class Meta:
        model = Coop

    name = "test model"
    address = factory.SubFactory(AddressFactory)
    enabled = True
    phone = "312-999-1234"
    email = "test@hello.com"
    web_site = "http://www.hello.com"

    @factory.post_generation
    def types(self, create, extracted, **kwargs):
        if not create:
            # Simple build, do nothing.
            return

        if extracted:
            # A list of types were passed in, use them
            for type in extracted:
                self.types.add(type)
        else:
            type = factory.SubFactory(CoopTypeFactory)
            self.types.all().set( (type) )

Then I have this test ...
@pytest.mark.django_db
def test_address_create(self):
    """ Test address model """    # create customer model instance
    address = AddressFactory()
    assert address is not None

but running the test results in the below error ...
davea$ python manage.py test --settings=maps.test_settings
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
setUpTestData: Run once to set up non-modified data for all class methods.
setUp: Run once for every test method to setup clean data.
EsetUp: Run once for every test method to setup clean data.
.
======================================================================
ERROR: test_address_create (tests.test_models.ModelTests)
Test address model
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 126, in _get_manager
    manager = model_class.objects
AttributeError: type object 'AddressField' has no attribute 'objects'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_models.py", line 27, in test_address_create
    address = AddressFactory()
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 46, in __call__
    return cls.create(**kwargs)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 564, in create
    return cls._generate(enums.CREATE_STRATEGY, kwargs)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 141, in _generate
    return super(DjangoModelFactory, cls)._generate(strategy, params)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 501, in _generate
    return step.build()
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/builder.py", line 279, in build
    kwargs=kwargs,
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/base.py", line 315, in instantiate
    return self.factory._create(model, *args, **kwargs)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 184, in _create
    manager = cls._get_manager(model_class)
  File "/Users/davea/Documents/workspace/chicommons/maps/web/venv/lib/python3.7/site-packages/factory/django.py", line 130, in _get_manager
    manager = model_class._default_manager
AttributeError: type object 'AddressField' has no attribute '_default_manager'

What do I need to do to build a factory for this type of object?
Edit: This is my Coop model in all its glory ...
class Coop(models.Model):
    objects = CoopManager()
    name = models.CharField(max_length=250, null=False)
    types = models.ManyToManyField(CoopType)
    address = AddressField(on_delete=models.CASCADE)
    enabled = models.BooleanField(default=True, null=False)
    phone = PhoneNumberField(null=True)
    email = models.EmailField(null=True)
    web_site = models.TextField()

A: The base Coop model should be similar to:
from address.models import AddressField
from django.db import models

class Coop(models.Model):
    name = models.CharField(max_length=255)
    address = AddressField()

To configure the factories in your tests, you have to create a factory for each model from django-address
class CountryFactory(factory.DjangoModelFactory):
    class Meta:
        model = 'address.Country'

    name = 'Test Country'
    code = '123'

class StateFactory(factory.DjangoModelFactory):
    class Meta:
        model = 'address.State'

    name = 'Test State'
    code = '456'
    country = factory.SubFactory(CountryFactory)

class LocalityFactory(factory.DjangoModelFactory):
    class Meta:
        model = 'address.Locality'

    name = 'Test Locality'
    postal_code = '123'
    state = factory.SubFactory(StateFactory)

class AddressFactory(factory.DjangoModelFactory):
    class Meta:
        model = 'address.Address'

    street_number = "123"
    route = "Rd"
    raw = "123 Fake Rd"
    formatted = "123 Fake Rd."
    latitude = 87.1234
    longitude = -100.12342
    locality = factory.SubFactory(LocalityFactory)

class CoopFactory(factory.DjangoModelFactory):
    class Meta:
        model = Coop

    name = 'new Coop'
    address = factory.SubFactory(AddressFactory)

And the test will be:
class FactoryTest(TestCase):
    def test_example(self):
        coop_from_factory = CoopFactory()
        self.assertIsNotNone(coop_from_factory)

        coop = Coop.objects.create(name='test', address=coop_from_factory.address)
        self.assertIsNotNone(coop)


text:
Q: My user (tom) has user_u , user_r and user_t via semanage but it still can perform sudo My user (tom) is mapped to user_u user , user_r role and user_t domain via semanage
[tom@localhost ~]$ id -Z
user_u:user_r:user_t:s0
[tom@localhost ~]$

because I have made the "default" as "user_u"
[tom@localhos ~]$ sudo semanage login -l

Login Name           SELinux User         MLS/MCS Range        Service

__default__          user_u               s0                   *
root                 unconfined_u         s0-s0:c0.c1023       *
system_u             system_u             s0-s0:c0.c1023       *
[tom@localhos ~]$

but it still can perform sudo
[tom@localhost ~]$ sudo -l
Matching Defaults entries for tom on localhost:

User tom may run the following commands on localhost:
    (ALL) NOPASSWD: ALL
[tom@localhost ~]$

It seems, this is because of "%<user tom's group> ALL = (ALL) NOPASSWD:ALL" in the sudoers
[tom@localhost ~]$ sudo cat /etc/sudoers
root ALL = (ALL) NOPASSWD:ALL
%<user tom's group> ALL = (ALL) NOPASSWD:ALL
admin ALL = (ALL) NOPASSWD:ALL
[tom@localhost ~]$

Please help me fix my issue


text:
Q: installing MySQLdb for Python 2.7 on OSX gives an IndexError I am trying to install MySQLdb in python 2.7 and it gives me following error on running setup.py file
Traceback (most recent call last):
  File "setup.py", line 16, in <module>
    metadata, options = get_config()
  File "/Users/hhamza/Desktop/MySQL-python-1.2.2/setup_posix.py", line 53, in get_config
    libraries = [ dequote(i[2:]) for i in libs if i.startswith(compiler_flag("l")) ]
  File "/Users/hhamza/Desktop/MySQL-python-1.2.2/setup_posix.py", line 7, in dequote
    if s[0] in "\"'" and s[0] == s[-1]:
IndexError: string index out of range

Does anyone know what am i missing here?


text:
Q: Regex for specific list I need to extract from each line with comma separated numbers (C#)
test    35,1    35,2    35,3    35,4    35,5

test2   35,1    35,2    35,3    35,4    35,5

test3   35,1    35,2    35,3    35,4    35,5

test    35,1    35,2    35,3    35,4    35,5

test2   35,1    35,2    35,3    35,4    35,5

test3   35,1    35,2    35,3    35,4    35,5

I would like to have a group name test that would have two matches
test    35,1    35,2    35,3    35,4    35,5
test    35,1    35,2    35,3    35,4    35,5

What I've achieved so far
(?>test(?>(?<test>[\w\s,]+)\n))

but all the text is selected till the last line

A: You can name your capture groups like this: (?<name>expression). Writing the rest is fairly simple. Start with the literal string test, followed by any whitespace characeter, to ensure you don't capture test2 or test3. Then capture all remaining characters to get the rest of your line.
(?<test>test\s.*)

You can then access your named groups like this:
var matches = Regex.Matches(input, @"(?<test>test\s.*)");
foreach(Match match in matches)
{
    string result = match.Groups["test"].Value;
}

A: Here is the regex you can leverage:
(?<key>test\d*)\b(?>\s*(?<test>\d+(?:,\d+)*))+

See the regex demo here, the key named group will hold the test+digit(s) value and the test group will hold all the numbers after the key inside a CaptureCollection (match.Groups["test"].Captures):

Here is an IDEONE demo showing how you can retrieve these values in C#:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        var strs = new List<string> { "test    35,1    35,2    35,3    35,4    35,5",
        "test2   35,1    35,2    35,3    35,4    35,5",
        "test3   35,1    35,2    35,3    35,4    35,5",
        "test    35,1    35,2    35,3    35,4    35,5",
        "test2   35,1    35,2    35,3    35,4    35,5",
        "test3   35,1    35,2    35,3    35,4    35,5"};

        var pattern = @"(?<key>test\d*)\b(?>\s*(?<test>\d+(?:,\d+)*))+";
        foreach (var s in strs)
        {
            var match = Regex.Match(s, pattern, RegexOptions.ExplicitCapture);
            if (match.Success)
            {                     // DEMO
                var key = match.Groups["key"].Value;
                var tests = match.Groups["test"].Captures.Cast<Capture>().Select(m => m.Value).ToList();
                Console.WriteLine(key);
                Console.WriteLine(string.Join(", and ", tests));
            }
        }
    }
}

Output:
test
35,1, and 35,2, and 35,3, and 35,4, and 35,5
test2
35,1, and 35,2, and 35,3, and 35,4, and 35,5
test3
35,1, and 35,2, and 35,3, and 35,4, and 35,5
test
35,1, and 35,2, and 35,3, and 35,4, and 35,5
test2
35,1, and 35,2, and 35,3, and 35,4, and 35,5
test3
35,1, and 35,2, and 35,3, and 35,4, and 35,5


text:
Q: Why do the styles of HTML emails keep changing in Outlook? The problem I am currently seeing is pretty bizarre. Here are the steps that take place that cause the issue:

*

*Create HTML email with multiple styles

*Send HTML email to an email linked to Microsoft Outlook

*Open the email in Outlook, look at it notice all of the styles

*Wait a few days, open the email again, look at it notice some of the styles have changed

Basically without editing the email, without resending it, simply storing it in Outlook Inbox the styles are constantly changing. Examples of this include changing padding, changing bullet sizes, changing font sizes, etc.
It is very bizarre, frustrating, and confusing. Has anyone seen this issue or has anyone seen it and fixed it? Any input will be very helpful!
Thank you.

A: After forwarding the HTML email, or replying on top of it, we were seeing issues with the output of HTML. This was due to the format of the email after forwarding. Thank you for the help to TylerH.

A: Outlook is notorious for converting email into it's own Microsoft Word powered renderer. It basically adds a lot of junk and strips some other stuff. There are ways to code around some of this, you just have to know the quirks and make sure you are coding in best practices to avoid them.
Normally the changes are most obvious when you forward an email, are you referring to an email that is just sitting there, or has it been forwarded back and forth in a conversation? Sometimes just switching to forward/reply without actually sending it is enough to break it in the email view.
I'm not sure if you are doing anything to cause it or if it is simply breaking when it becomes automatically archived, either way, this seems to be the likely cause.


text:
Q: How to get the size of data present in coredata store? How to get the total memory size in bytes of data present in core data store.And How to get the memory size for particular rows of data.

A: Using Swift 5, I came up with this answer. It not only gets the size of the store and files, but also formats the data size using Apples ByteCountFormatter.
public func getSqliteStoreSize(forPersistentContainerUrl storeUrl: URL) -> String {
    do {
        let size = try Data(contentsOf: storeUrl)
        if size.count < 1 {
            print("Size could not be determined.")
            return ""
        }
        let bcf = ByteCountFormatter()
        bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
        bcf.countStyle = .file
        let string = bcf.string(fromByteCount: Int64(size.count))
        print(string)
        return string
    } catch {
        print("Failed to get size of store: \(error)")
        return ""
    }
}

To use is as simple as:
// Get Core Data storage size:
guard let storeUrl = self.managedObjectContext!.persistentStoreCoordinator!.persistentStores.first?.url else {
    print("There is no store url")
    return
}
print("The size of the store is: \(self.getSqliteStoreSize(forPersistentContainerUrl: storeUrl))")

One minor detail here is to ensure you check that your moc and persistentStoreCoordinator actually have value - in my case I know that they do because of how I have initialised them.
Regarding the answer above that takes into account the wal and shm files, you can check these by appending a string to the URL:
let newFileName = storeUrl.absoluteString.appending("\("-wal")")
let newFileName2 = storeUrl.absoluteString.appending("\("-shm")")
print("The size of the wal is: \(self.getSqliteStoreSize(forPersistentContainerUrl: URL(string: newFileName)!))")
print("The size of the shm is: \(self.getSqliteStoreSize(forPersistentContainerUrl: URL(string: newFileName2)!))")

A: On iOS 7 and above, older answers don't work anymore for SQLite-backed persistent stores, because of SQLite journal files. For each persistent store file you need to get the size of the SQLite file itself (e.g. Foo.sqlite) and the sizes of the journal files (e.g. Foo.sqlite-wal and Foo.sqlite-shm) and add the sizes to get the total. This is really important because it's very likely that most of the data is actually in the journal files. You can use NSFileManager to get this information for each file.
If you're using binary attributes in your model and you have "Allows External Storage" enabled for any of those attributes, it gets more complicated. In that case you need to find all of the external storage files and add up their sizes too. Their location is not documented but should be in a subdirectory of the directory where the SQLite file is found. For a SQLite file named Foo.sqlite look for a directory named .Foo_SUPPORT/_EXTERNAL_DATA, and the external binary files will be there. Since this is not documented, it may be subject to change without warning.
A better approach-- if it's not too late-- is to put the persistent store in its own subdirectory. Instead of putting it in the documents directory, create a new directory inside documents and put your SQLite file there. That is, create a directory called something like data and put Foo.sqlite in it. To add up the size, just recursively scan every file in data and add up the sizes. Then you'll catch everything, even if journaling or external binaries or whatever change in future versions of iOS. A good way to do the scan would be with NSFileManager's enumeratorAtPath: or enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: methods.
Finding the memory size for a particular row of data is a very different question, and there's no general solution. There's the overhead of any object instance, plus your attributes, plus any internal undocumented objects NSManagedObject might create (including instance vars and dynamically allocated memory). It's not even a fixed value since data can be allocated and released on the fly. Adding up the sizes of just your attributes is easy-- just run through them and add up the size of each (string length, data length, etc), but it's not the full picture.

A: - (void)reportFileSizeOfPersistentStores
{
    NSArray *allStores = self.persistentStoreCoordinator.persistentStores;
    NSFileManager *fileManager = [NSFileManager defaultManager];

    for (NSPersistentStore *store in allStores)
    {
        NSString *filePath = store.URL.path;
        NSDictionary *attributes = [fileManager attributesOfItemAtPath:filePath
                                                                 error:nil];

        NSString *fileSize = attributes[NSFileSize];

        NSLog(@"FileSize:%@", fileSize);
    }
}


text:
Q: Multiple thread access to Excel I have two methods, method1, method2, both have lock(App) where App is a static instance in the same class.
App is a static instance in a shared project Helper
void method1()
{
    lock(Helper.App)
    {
       ExcelApp.FormulaCell.AddComments(errMsg);
    }
}

    void method2()
    {
        lock(Helper.App)
        {
           //plot data (an 2-D array) to cells
           var dataRng = ExcelApp.CurrentSheet.Cells(Formulacell.Row + 1, Formulacell.Column + 1);
           dataRng = dataRng.get_Resize(n, m);
           dataRng.Value2 = data;
        }
    }

method1, method2 are called by many threads.
I want at one time only method1 or method2 run
The issue is they seem not.
in method1 & method2, I plot some data to Excel, I get Exception

Name:COMException
  Message:Exception from HRESULT: 0x800AC472

I googled and find the exception is caused by Excel Application is not ready.
There is no UI gesture, so I conclude the exception is caused by the two methods try to write to Excel at the same time.

A: Please check if youre calling an async methods to excell.
If so, this is the problem, even though you used locks, the actual calls are running in the same time.
Try to wait till the excell methods ends.
Ofir


text:
Q: Help creating simple diagram I want to create a little diagram that looks like:

with $\implies$ (double-lined arrow) for the arrows.  And I'd like to be able to write things on the arrows if possible.
How can I do this?  I've never used latex to create a diagram before!

A: What you are looking for is the TikZ package (https://www.ctan.org/pkg/pgf). It has become the de-facto standard drawing tool within LaTeX. The picture you gave could be written as
\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\node at (0, 0) (a) {(a)};
\node at (2, 0) (b) {(b)};
\node at (4, 0) (c) {(c)};

\draw [double, ->, bend right, auto, swap] (a) to node {label 1} (b);
\draw [double, ->, bend right, auto, swap] (b) to node {label 2} (a);
\draw [double, ->, auto] (c) to node {label 3} (b);

\end{tikzpicture}
\end{document}

and would render as
Now, what is happening here? You might consider the tikzpicture the canvas on which to draw. The three \node commands create points on the canvas at the given coordinates (0, 0), (2, 0), and (4, 0), respectively (the first number being the horizontal coordinate from left to right and the second one the vertical, from bottom to top). For later reference, these are called a, b, and c, respectively and drawn as such, with parentheses.
The \draw commands are responsible for the arrows. We'll ignore the options for a moment and pretend the command was \draw (c) to node {label 3} (b). This draws a line from the point we call c to the point b. In order to label the line, we create another node ad hoc using node {label 3}, where the thing in braces is the text to appear next to the line.
The options to the \draw command do the following:

*

*double draws two lines instead of one to make them appear like the "implies" arrow, as you requested.

*-> specifies the arrow's tips. That is, no tip at the beginning (straight line -, and an arrow tip at the end, >.

*bend right is for the curvature. bend left is also possible. Note that both arrows are bent right.

*auto positions the line's label cleverly. Try compiling the example without the option: The label will be written on the line instead of next to it.

*swap controls whether the label should appear to the left or to the right of the line. If neither line had the swap option, the labels would be set between the lines, with little spacing between them. Try it out!

TikZ is a intimidatingly powerful package. When learning to use it, you should definitely follow the package author's invitation to follow the tutorials at the beginning.

A: A short code with tikz-cd:
\documentclass[border=3pt]{standalone}
\usepackage{tikz-cd, amsmath}

\begin{document}\begin{tikzcd}
(a) \rar[Rightarrow, bend right, "f"] & \lar[Rightarrow, bend right, swap, " g"] (b) & \lar[Rightarrow, swap, " h "](c)
\end{tikzcd}

\end{document}


text:
Q: datatables lock thead like freeze rows in excel Is it possible to "lock" the top row of the results from dataTables? so that when i scroll through 100s of row results, the top heading doesnt move. I have tried setting a size to tbody and making it overflow in css but that obviously doesn't work.
tbody{
    overflow-y:scroll;
    height:600px;

}

A: Yes, it is possible.  Sounds like you want to use the DataTables "FixedHeader" extension:
$(document).ready( function () {
    var table = $('#example').DataTable();
    new $.fn.dataTable.FixedHeader( table );
} );

Source: https://www.datatables.net/extensions/fixedheader/


text:
Q: How to unlock all SF4 characters, on PC? I'm trying to unlock Akuma and Gouken on SF4 for PC (Steam Version, not Super Street Figher).
So far I got Sakura, Dan, Gen, Rose and Fei Long. I explained how to unlock them in the answer.
What am I missing ? There are still 4 unfilled boxes on the menu. 2 characters I know who are: Gouken and Akuma. I suspect one other is Seth. Who is missing ?

A: *

*Unlocking Sakura: Play with Ryu, any level, and finish the game.

*Unlocking Dan: Play with Sakura, any level, and finish the game.

*Unlocking Rose: Play with M.Bison, any level, and finish the game.

*Unlocking Fei Long: Play with Abel, any level, and finish the game.

*Unlocking Gen: Play with Chun Li, any level, and finish the game.

*Unlocking Cammy: Play with C. Viper, any level, and finish the game.

*Unlocking Akuma: After unlocking Sakura, Dan, Rose, Fei Long, Gen and Cammy, finish the game in any level with any character you have already beaten the game, no continues, and a required amount of perfects(shown below). After beating Seth, you will fight Akuma. He must be beaten without using continues.

*Unlocking Gouken: After unlocking Akuma as shown above, beat the game using Akuma, then finish the game in any level with any character you have already beaten the game, no continues, no round loss, and a required number of perfects, super/ultra finishes and first attacks. After beating Seth, you will fight Gouken. He must be beaten without using continues.

*Unlocking Seth: Finish the game with all characters, including Akuma and Gouken.

Notes:

*

*Some of these conditions aren't necessary to face Akuma or Gouken after Seth, but if you don't match them, you will not unlock them for use.

*The required number of perfects, super/ultra finishes and first attacks change according to how many rounds are needed to win a match.

For 1 round matches:
1 perfect
  3 super/ultra finishes
  5 first attacks
For 2 round matches:
2 perfect
  5 super/ultra finishes
  10 first attacks
For 3 round matches:
3 perfect
  7 super/ultra finishes
  15 first attacks
For 4 round matches:
4 perfect
  9 super/ultra finishes
  20 first attacks


text:
Q: Padding errors using OpenSSL for encrypt/decrypt with Keys extracted from Digital Cert I am using some command line Open SSL commands to encrypt and decrypt data using Public and Private keys extracted from a Digital Cert.   When I try to decrypt I get PKCS padding errors.  Can someone tell me where I'm going wrong?
These are the command I've been using:
a) Extract Public key:  openssl x509 -pubkey -noout -in xxxxx.cer  > xxxxxpublickey.pem
b) Extract Private Key:openssl pkcs12 -in xxxxxx.pfx -nocerts -out xxxxxprivatekey.pem -nodes
c) Encypt a key (.bin file): openssl enc -aes-256-cbc -in kenkey.bin -out kenkey_Key -pass file:xxxxxpublickey.pem
d) Decrypt key produced in c) openssl rsautl -decrypt -hexdump -in kenkey_key -inkey xxxxxprivatekey.key -out aeskey.txt
This produces errors like this:

RSA operation error 3248:error:0407109F:rsa
  routines:RSA_padding_check_PKCS1_type_2:pkcs decoding
  error:.\crypto\rsa\rsa_pk1.c:273: 3248:error:04065072:rsa
  routines:RSA_EAY_PRIVATE_DECRYPT:padding check
  failed:.\crypto\rsa\rsa_eay.c:602: