text:
Q: Live stream microphone using python and play it on a web browser or through android media player i am not very familiar with python.
my goal is to stream microphone audio using python and receive and play it on an android app.
after hours of searching I've found some python codes that do this using socket and it's working but I was not able to find any tutorial about how to catch that stream on android app side and play it.
here is one of the socket stream code:
import pyaudio
import socket
import select

FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096

audio = pyaudio.PyAudio()

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('', 4444))
serversocket.listen(5)

def callback(in_data, frame_count, time_info, status):
    for s in read_list[1:]:
        s.send(in_data)
    return (None, pyaudio.paContinue)

# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK, stream_callback=callback)
# stream.start_stream()

read_list = [serversocket]
print ("recording...")

try:
    while True:
        readable, writable, errored = select.select(read_list, [], [])
        for s in readable:
            if s is serversocket:
                (clientsocket, address) = serversocket.accept()
                read_list.append(clientsocket)
                print ("Connection from"), address
            else:
                data = s.recv(1024)
                if not data:
                    read_list.remove(s)
except KeyboardInterrupt:
    pass

print ("finished recording")

serversocket.close()
# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()

my problem is that i want to get a stream url with an output file at the end of it like:
http://192.168.1.3:4444/out.mp3
using vlc cli i can do it easily:
cvlc -vvv alsa://plughw:1 --sout '#transcode{acodec=mp3,ab=16,channels=1,scodec=none}:standard{access=http,dst=0.0.0.0:8888/out.mp3}'

but i do want to use vlc for some reason and not know how to achieve this on python.

A: You can use os.system('insert command here') from os module. It will execute the argument in system terminal.
You can just run the cvlc using your python script


text:
Q: Ad Hoc doesn't get downloaded I want to distribute my iOS app by Ad Hoc.  Since the current version of XCode doesn't create .plist file, so I got one from StackOverflow and filled it as blow.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>items</key>
        <array>
                <dict>
                        <key>assets</key>
                        <array>
                                <dict>
                                        <key>kind</key>
                                        <string>software-package</string>
                                        <key>url</key>
                                        <string>http://hungry.portfolio1000.com/HungryHandongi.ipa</string>
                                </dict>
                        </array>
                        <key>metadata</key>
                            <dict>
                                <key>bundle-identifier</key>
                                <string>com.Akadev.HungryHandongi</string>
                                <key>bundle-version</key>
                                <string>1.06</string>
                                <key>kind</key>
                                <string>software</string>
                                <key>title</key>
                                <string>배고픈 한동이</string>
                        </dict>
                </dict>
        </array>
</dict>
</plist>

The url of the .plist file is: https://dl.dropboxusercontent.com/s/tulw9h412me6ayh/HungryHandongi.plist?dl=0
Now I want to let people download the app through the url http://hungry.portfolio1000.com/hungryhandongi.html which is coded like below:

Download

When I open the url with Safari and click 'Download' link, nothing happens.  I want know what I've done wrong.
Thank you.

A: I think you are getting this issue for iOS 8.
Yes for Over the air distribution you need to create plist file manually. and you have to change your identifier like
com.Akadev.HungryHandongi to com.Akadev.HungryHandongi.iOS8fix
Please check below plist , it will help you
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                     <string>http://www.path.com/build/iphone/some/2015/022015/name/appname.ipa</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>full-size-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                     <string>http://www.name.com/build/iphone/EnterpriseTB/2015/022015/some/iTunesArtwork.png</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>display-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                     <string>http://www.some.com/build/iphone/some/2015/022015/some/Icon.png</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>mobi.somecmp.appname.ios8fix</string>
                <key>bundle-version</key>
                <string>1.0</string>
                <key>kind</key>
                <string>software</string>
                <key>title</key>
                <string>appname 2015</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>

Note: For ADHoc Distribution device id should be added into your provisioning profile.

redpajama_set_name: RedPajamaStackExchange


text:
Q: my app is not running still in my phone but is not showing any error It Shows no error on Android Studio but app even not starting on phone.Is there any problem with the code.I feel like there may be any mistakes in syntax but i am not able to find one.Please help me.
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
  private Button bDriver,bCustomer;
   @Override
  protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button bDriver=(Button)findViewById(R.id.driver);
    Button bCustomer=(Button)findViewById(R.id.customer);
    bDriver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent=new
                       Intent(MainActivity.this,DriverLoginActivity.class);
            startActivity(intent);
            finish();
        }

    });
    bCustomer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent ryt=new
                  Intent(MainActivity.this,CustomerLoginActivity.class);
            startActivity(ryt);
            finish();

        }
    });
   }
  }

And activity_main.xml is this and please explain if there is any problem related to SDK version also upload the detail.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.trillcore.uber.MainActivity">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/driver"
    android:layout_below="@+id/customer"
    android:text="I am a Driver"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="I am a Customer"
    android:layout_above="@+id/driver"
    android:id="@+id/customer"/>
 </RelativeLayout>


text:
Q: Prove that $ \mathbb{E}[XY] - \mathbb{E}[X] \mathbb{E}[Y] = \int_{- \infty}^\infty \int_{- \infty}^\infty (F(x,y)-F_X(x) F_Y(y)) \,dx\,dy,$ I'm studying associated variables now and in one proof the following Lemma is used:
Let $X$ and $Y$ be random variables with distribution $F_X$ and $F_Y$ and joint distribution $F$. Then
\begin{align}
& \mathbb{E}[XY] - \mathbb{E}[X] \mathbb{E}[Y] \\[8pt]
= {} & \int_{- \infty}^\infty \int_{- \infty}^\infty (F(x,y)-F_X(x) F_Y(y)) \,dx\,dy,
\end{align}
if $\mathbb{E}[XY]$, $\mathbb{E}[X]$ and $\mathbb{E}[Y]$ exist.
The proof begins with introducing to vectors of independent variables:
Let $(X_1,Y_1)$ and $(X_2,Y_2)$ be independent, each distributed to $F$.
Define $I(u,x)=\begin{cases}1& \text{if } u \leq x \\ 0 & \text{otherwise} \end{cases}$.
Then it is said, that
$$
2 (\mathbb{E}[X_1Y_1] - \mathbb{E}[X_1] \mathbb{E}[Y_1]) = \mathbb{E}[(X_1 - X_2)(Y_1-Y_2)] $$
$$ = \mathbb{E} \left[\int_{- \infty}^\infty \int_{- \infty}^\infty [I(u,X_1)-I(u,X_2)][I(v,Y_1)-I(v,Y_2)] \, du \, dv \right].$$
The first equation is clear for me, but I don't get the second one. Some help would be nice here.
Furthermore the proof ends with the argument, that we can take the expectation under the integral sign since the expectation is finite, thats clear. Then we are ready, but I don't get the right result by calculating.To make the proof fit, we would have to end up at 2 times the right handside of the statement.
What I also observed is that this inequality gives a simple proof for $\mathbb{E}[XY] \geq \mathbb{E}[X] \mathbb{E}[Y]$.

A: For the second equality, think about the integral $$\int_{- \infty}^{\infty} \int_{- \infty}^{\infty} [I(u,X_1)-I(u,X_2)][I(v,Y_1)-I(v,Y_2)]du dv $$ which is a random variable. The structure of the integrand allows the integral to be rewritten as $$ \int_{- \infty}^{\infty} [I(u,X_1)-I(u,X_2)]du \int_{- \infty}^{\infty}[I(v,Y_1)-I(v,Y_2)]dv $$
Consider the integrand involving $u$. Its value is either $1$, $0$ or $-1$ depending on how $u$ relates to $X_1$ and $X_2$. By considering when these three possibilities occur, you should be able to convince yourself that the $u$ integral is just $X_1-X_2$. Similarly for the $v$ integral.
The later section of the proof hinges on evaluating $$\mathbb{E}[[I(u,X_1)-I(u,X_2)][I(v,Y_1)-I(v,Y_2)]]$$ This expectation can be written as a sum of four terms. One such term is $\mathbb{E}[I(u,X_1)I(v,Y_1)]$. Using standard indicator function notation, this is simply $$\mathbb{E}[1_{u\leq X_1}1_{v\leq Y_1}]=P(u\leq X_1,v\leq Y_1)=1-F_Y (v)-F_X(u)+F(u,v)$$ (best seen by drawing a diagram of $u$,$v$ space). Similar calculations with the other terms should give you the desired result.
Note: the final equation assumes that all the distribution functions involved are continuous. The equation may not be true at discontinuity points of $F_Y$, $F_X$. However, the set of such points is countable so the value of the double integral will not be affected.


text:
Q: Why does replace not replace? code:
a = 'g'
b = a.title()
b.replace(b, a)
print(b)

output: G
I think the output should be 'g' lowercase as the replace statement replaces the uppercase 'G' to lowercase one.
I am trying to solve a challenge in which I have to capitalize a string but not the one that starts with numerals?

A: You have to assign the value of b.replace(b, a) to the variable b before you print it.
a = 'g'
b = a.title()
b = b.replace(b, a)
print(b)

Output:
g

A: Strings in python are immutable.
Functions that would change the string, return a new one instead.
You can read the reasons behind this choice in many articles, like
https://www.educative.io/edpresso/why-are-strings-in-python-immutable

A: The output of replace need ot be reassign - because replace gives you a copy with the replaced changes - so it isnt in place!
a = 'g'
b = a.title()
b = b.replace(b, a)
print(b)


text:
Q: Cross-browser flexbox compatibility issues I'm building a webapp that has to be compatible with at least IE10+, Chrome, Firefox and iOS wrapped in Cordova.
It works very well on Chrome. But it turns out every time I fix a collateral bug on IE or Firefox it creates some bug on iOS and vice versa.
Most recent issue is due to Firefox and iOS. Before the fix, iOS was working (overflow-x was scrolling well) well but Firefox was not respecting its parent width and right flex box was out of the screen. Once I fixed the issue on Firefox, overflow scroll would not work on iOS anymore.
Regarding IE10, some nested flexboxes also won't respect their parent's width and the last box is half way out of the screen (?).
Do you have a reliable source for cross-browser development with flexbox ? I've already tried a bunch of guides but they help fix a bug on some browser and creates a new one on some other browser...
EDIT : A comparative table that explain how each browser deal with properties would be great.
Thanks.

A: It's possible that what you are trying to achieve simply isn't doable using flexbox, which is not fully supported by all the browsers you list.
Flexbox is known to be buggy on IE10, and may need prefixes on many of the browsers you are building for. The following is a good resource to find out which browsers fully support any given feature: http://caniuse.com/#search=flexbox.
You may find the "known issues" section relevant to figuring out if the issues you are having are documented.
Some specific information about the bugs you are encountering might help provide a more specific answer.

A: It sounds like you want this:
https://github.com/philipwalton/flexbugs
Self-described as "a community-curated list of flexbox issues and cross-browser workarounds for them."


text:
Q: The json data i am putting into a pug template is putting '<' at the beginning of a string and '>' at the end. why? how do i get rid of it? So i have a json file with a json array
    {
    "LunchItems": [
    {
        "name":" The Strange Brew",
        "price":"~6~",
        "description":" A Classic Irish Style Beer Cheese Soup Garnished with Red Pepper and Toasted Baguette"
    },
    {
        "name":" The Killer Tomato",
        "price":"~6~",
        "description":" A Roma Tomato and Roasted Red Pepper Bisque Garnished with Spiced Creme Fraiche"
    },
    {
        "name":" House Salad",
        "price":" ~7~",
        "description":" Spring Mix, Carrot, Red Onion, Roma Tomato, Mushroom and Red Peppers"
    },
    {
        "name":" Mediterranean Salad",
        "price":"~8~",
        "description":" Spring Mix, Red Onion, Kalamata Olives, Roma Tomato, Capers and Feta Cheese"
    },
    {
        "name":" Side Salad & Cup Of Soup",
        "price":"~6~",
        "description":" "
    },
    {
        "name":" The Ollie",
        "price":"~8~",
        "description":" A Quarter Pound Version of Our Signature Stout Burger Served on a Pretzel Roll with Spring Mix, Roma Tomato, Red Onion & Colby Jack Cheese - With Choice Of Side"
    },
    {
        "name":" The Neuben",
        "price":"~8~",
        "description":" Grilled Corned Beef Topped with Sauerkraut, Grilled Onions, Swiss Cheese and Stout Mustard Served on a Toasted Pretzel Roll - With Your Choice Of One Side"
    },
    {
        "name":" The Three Little Birds",
        "price":"~8~",
        "description":" House Made Chicken Salad Served On 3 Pretzel Rolls with Swiss Cheese and Roma Tomato - With Choice Of Side"
    },
    {
        "name":" The Fresh Prince",
        "price":" ~8~",
        "description":" Chopped Filet, Onion, Red Pepper & Swiss Served On a Toasted Sausage Roll with Au Jus & Garlic Aioli - With Choice Of Side"
    },
    {
        "name":" The Nine Iron",
        "price":"~8~",
        "description":" Corned Beef, Smoked Turkey, Benton's© Bacon, Swiss, Spring Mix, Red Onion, Tomato, & Garlic Aioli - With Choice Of Side"
    },
    {
        "name":" The Fish 'n' Chips",
        "price":"~8~",
        "description":" Two Beer Battered Cod Filets Served with House Made Tartare Sauce and Malt Vinegar Aioli - With Choice Of Side"
    },
    {
        "name":" The Big Cheese",
        "price":"~6~",
        "description":" A Classic Colby Jack & Sourdough Grilled Cheese Sandwich - With Choice Of Side"
    },
    {
        "name":" The Chicken Gyro",
        "price":"~9~",
        "description":" Grilled chicken breast with spring mix, roma tomato, red onion and feta cheese wrapped in toasted pita bread and served with house made tzatziki sauce - with choice of one side."
    },
    {
        "name":" Deluxe Quesadilla",
        "price":"~8~",
        "description":" Colby Jack, Roasted Corn, Red Peppers, Black Beans & Red Onion Served with House Salsa & Spiced Creme Fraiche"
    },
    {
        "name":" Cheese Quesadilla",
        "price":"~5~",
        "description":" Cheese quesadilla served with house salsa & spiced creme fraiche"
    }
]
}

I am using express to render pug files
    const express = require('express');
const app = express();
const lunches = require('./public/json/lunch.json');
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));

const server = app.listen(7000, () => {
    console.log(`Express running → PORT ${server.address().port}`);
  });

  app.get('/', (req, res) => {
    res.render('index',{
      lunches: lunches.LunchItems
    });
  });

    doctype html
html
  head
    title #{title}
    link(rel='stylesheet', href='/css/Index.css')
    meta(name="viewport" content="width=device-width, initial-scale=1")
    style.
        body {
            background-image: url("/images/wood.jpg");
            background-size: auto;
        }
  body
    div.menuContainer
        each item in lunches
            div.menuItem
                #{item.name}

                #{item.price}

                #{item.description}

the output is:
 < The Strange Brew>
<~6~>

< The Killer Tomato>
<~6~>
...
So why are the '<>' there and how do i get rid of them?

A: When you start a new line with #{variable}, Pug thinks you're wanting to use block-level tag interpolation:

Tag Interpolation
Pug:
- let myTag = 'h1';
#{myTag} Heading

HTML:

Heading

If you want to just render text on multiple new lines, you can use the piped (|) text syntax, the block text syntax (with a . after the tag), or inline tag interpolation for the line breaks:
Piped Text Example
div.menuItem
  | #{item.name}
  br
  | #{item.price}
  br
  | #{item.description}

Block Text Example
div.menuItem. // note the trailing dot
  #{item.name}

  #{item.price}

  #{item.description}

Inline Tag Interpolation Example
div.menuItem #{item.name} #[br] #{item.price} #[br] #{item.description}

These should all yield the same desired result.
Alternatively, a more semantic solution could be to use a description list (dl) element to mark up this information.
Alternative Example
article.menuItem
  h1 #{item.name}
  dl
    dt Price
    dd #{item.price}
    dt Description
    dd #{item.description}


text:
Q: error: error parsing db.yaml: error converting YAML to JSON: yaml: line 19: did not find expected '-' indicator kubectl apply -f db.yaml
error: error parsing db.yaml: error converting YAML to JSON: yaml: line 19: did not find expected '-' indicator
could you please give me a hint about what's wrong in the YAML file?
apiVersion: apps/v1
kind: Deployment
metadata:
    name: my-db
spec:
  selector:
    matchLabels:
      app: my-db
  replicas: 1
  template:
    metadata:
      labels:
        app: my-db
    spec:
      containers:
        - name: app
          image: postgres:my-postgres
          ports:
            - containerPort: 5432
         deployment.spec.template.spec.containers.env:
        - name: POSTGRES_HOST_AUTH_METHOD
          value: trust

A: the deployment.spec.template.spec.containers.env is the the path in the manifest (try following the names deployment -> spec -> ... ; you can see that in the manifest). so instead of using that, you should just simply use env . The correct manifest is below

apiVersion: apps/v1
kind: Deployment
metadata:
    name: my-db
spec:
  selector:
    matchLabels:
      app: my-db
  replicas: 1
  template:
    metadata:
      labels:
        app: my-db
    spec:
      containers:
        - name: app
          image: postgres:my-postgres
          ports:
            - containerPort: 5432
          env:
          - name: POSTGRES_HOST_AUTH_METHOD
            value: trust


text:
Q: How to create an EMF file from a MS Chart graph using a Stream I am trying to create an EMF image from a MS Chart graph. I have got no problem using a FileStream to temporary store the image like this:
FileStream fileStream = new FileStream("test.emf", FileMode.Create);
chart1.SaveImage(fileStream, ChartImageFormat.EmfPlus);
fileStream.Close();
Image emf = Metafile.FromFile("test.emf");

But if I try to get rid of the file using a MemoryStream I get a System.ArgumentException
HResult=0x80070057 (invalid parameter).
MemoryStream memoryStream = new MemoryStream();
chart1.SaveImage(memoryStream, ChartImageFormat.EmfPlus);
Image emf = Metafile.FromStream(memoryStream);

I can't figure out why it is not working. I've read that the problem may be caused by the need to dispose the Graphics object. How can do it?


text:
Q: PHP function doesn't return null but doesn't return anything either Here is my code, which uses an extended phpMailer.  This works if I check for firstResult and lastResult, but not if I check for emailResult:
$validator = new FormValidator();
            $firstResult = $validator->checkFirst($_POST['firstname']);
            $lastResult = $validator->checkLast($_POST['lastname']);
            $emailResult = $validator->checkEmail($_POST['emailaddress1']);
            var_dump($emailResult);
            if (is_null($firstResult) && is_null($lastResult) && is_null($emailResult)) {

                $mail = new ULSMail();

                $mail->IsSMTP();  // telling the class to use SMTP
                $mail->AddAddress("shummel@ulsinc.com");

                $mail->Subject  = "test";
                $mail->MsgHTML($messageHTML);

                redirectULS('english/forms/thankyou.php');

                if(!$mail->Send()) {
                    echo 'Message was not sent.';
                    echo 'Mailer error: ' . $mail->ErrorInfo;
                } else {

                    //$bridge->pushLead($lead);
                }
            } else {
                //...
            }

and in my FormValidator class:
function checkEmail($email){

        if(strlen(trim($email)) < 8){
        return 'Please enter a valid email address of more than 8 characters</span>';
    } else {
        return NULL;
    }

}

redirectULS is a simple redirect function for internal redirects on my site.  It works as long as I don't check for $emailResult.

A: Actually, it does!
if (checkEmail("123456789") === NULL)
  print "Actually, it does!\n";

What you're doing is printing the result directly, which will cast NULL to an empty string. Hence it only appears to return nothing.
Notice that I made use of the triple equals operator, which tests for equality in value AND type. As @Tomcat suggests, you can also use is_null()

A: Actually, it returns NULL when your string is lower than 8.
Try var_dump instead of echo/print, it should display the "real" value (=NULL) of your string.

A: How are you testing the return?
echo is_null(checkEmail('foo@bar.com')) ? 'Pass' : 'Fail';

Also just a note; your validation parameters of 8 characters will fail on an email such as j@cc.tv. While surely rare, it would be suggested you validate based on form using Regular Expressions. Plenty of examples on the web.

class Validator{

    public function checkEmail($email){
        return preg_match('/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email);
    }

    public function checkName($name){
        return preg_match('/[a-z]{2,}/i', $name); //valid if $name is 2+ A-Z characters
    }

}

$v = new Validator;
if($v->checkEmail($_POST['email'])
&& $v->checkName($_POST['fname'])
&& $v->checkName($_POST['lname'])){
    //the info is valid
}else{
    //the info is not valid
}


text:
Q: SSIS Package Validation Error I've set up a package level variable called FileFound for parametrising a flat file to DB object For Each Loop in SSIS for SQL Server. I've set the expression for this as the full file path including extension of the first file in the folder I want to loop through.
However, this produces the following error, which I am not sure how to resolve:
TITLE: Package Validation Error
------------------------------

Package Validation Error

------------------------------
ADDITIONAL INFORMATION:

Error at Data Flow Task [OLE DB Destination [10]]: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80040E37.

Error at Data Flow Task [OLE DB Destination [10]]: Opening a rowset for "C:\Python27\Whoscored\WhoScoredData\MatchPlayers\410988-08-14-2010-Aston Villa-v-West Ham-Away-Team.txt" failed. Check that the object exists in the database.

Error at Data Flow Task [SSIS.Pipeline]: "OLE DB Destination" failed validation and returned validation status "VS_ISBROKEN".

Error at Data Flow Task [SSIS.Pipeline]: One or more component failed validation.

Error at Data Flow Task: There were errors during task validation.

 (Microsoft.DataTransformationServices.VsIntegration)

------------------------------
BUTTONS:

OK
------------------------------

Can anyone tell me what I need to address to fix this error?
Thanks

A: I think your "name of source file" variable has got mixed up in your development with your "name of destination table" variable.  An OLE DB Destination should never be having anything to do with a file name.


text:
Q: Image Classification - Movie posters by genre. Keras model overfitting Please note everyone, that this is a "Multi-Label" problem as opposed to Multi-Class. It's a multi-label, multi-class problem. I am trying to classify movie posters by genre by reading the images alone. I have over 22000 images overall. I have one hot encoded the genres for the Keas model to predict multiple genres for movies (Used sigmoid in final dense layer activation). I need recommendation for a proper batch size and number of epochs. I am using VGG16. I would also like to know how to choose which layers to freeze.
I have tried for 25 epochs using VGG16. The model tends to over-fit though. Batch size was 10.
Here's my training images count by genre (Note: A movie could be more than one genre which is more often than not, the case)
{'Action': 2226.0,
 'Thriller': 2788.0,
 'Drama': 9283.0,
 'Romance': 2184.0,
 'Horror': 2517.0,
 'Sci-Fi': 756.0,
 'Mystery': 918.0,
 'Adventure': 1105.0,
 'Animation': 583.0,
 'Crime': 1369.0,
 'Comedy': 5524.0,
 'Fantasy': 735.0,
 'Family': 991.0,
 'Music': 319.0,
 'History': 359.0,
 'War': 177.0,
 'Musical': 191.0,
 'Biography': 484.0,
 'Sport': 190.0}
conv_base = VGG16(weights = 'imagenet', include_top = False, input_shape = (224,224,3))

for layer in conv_base.layers[6:]:
    layer.trainable = False

early = EarlyStopping(monitor='acc', patience=7, mode='auto')

classifier = Sequential()
classifier.add(conv_base)

from keras.layers import Dropout
classifier.add(Dense(units = 128, activation = "relu"))
classifier.add(Dropout(0.2))
classifier.add(Dense(units = 128, activation = "relu"))
classifier.add(Dropout(0.1))
classifier.add(Dense(units = 19, activation = 'sigmoid'))

classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ["accuracy"])

classifier.fit(X_train, y_train, epochs=15, batch_size=10, callbacks = [early])


text:
Q: Elixir fetching key/value pair from json/struct Being new to Elixir and functional programming I'm having some problems to fetch the "taste" key from this struct.
json = response.body
icecream = Poison.decode!(json, as: %{"items" => [%Icecream{}]})

Returns:
[%{"items" => [%MyModule.Icecream{size: "Large",
 taste: "Pistachio"}]}]

I would like to only get the taste ("Pistachio") saved to a variable in the most optimized way.
I'm looking forward to be enlightened. :)
Solution:
I came up with this myself:
taste = List.first(icecream["items"]).taste

A: Using pipes, you can do
icecream |> hd |> Map.get("items") |> hd |> Map.get(:taste)

However, I suggest you use get_in/2 in conjunction with Access helpers, which IMO results in very readable code and seems nicer for more complex cases.
import Access
get_in icecream, [at(0), key!("items"), at(0), key!(:taste)]

A: You could also use a simple pattern matching:
[%{"items" => [%{taste: taste_val}]}] = your_result

It saves taste value into a variable taste_val. If your result doesn't have a taste, it will be set to nil (or your default value) as you use module with defstruct where you define a structure.

A: You can also use Map.get or Map.fetch
See: https://hexdocs.pm/elixir/Map.html#fetch/2)
Bear in mind, if you are using
Map.fetch!(map,key)
you can cause a side effect (error thrown) when the key is not present in map. If you are using Map.fetch(map,key) you will get back a tuple with either ok or error status, signifying the availability of key in map.


text:
Q: TypeError: Undefined is not a constuctor (evaluating 'selectList.append(options)') I am getting this error when I run the test Cases (Jasmine):
TypeError: Undefined is not a constuctor (evaluating 'selectList.append(options)')
I am not sure why a few of my test cases are failing because of this. The tests in my browser run absolutely fine but failing locally (Maven test). (Using Jasmine, Phantom JS).
Here I have an editUser button, which when clicked hides and (update and cancel) buttons pop up which are hidden until then.
function userEditUser(id) {
   var grandParent = $('#updateUser' + id).parent().parent().parent();
   var updateUser = $('#updateUser' + id);
   updateUser.siblings().removeClass('hideElement');
   updateUser.addClass('hideElement');
   var column_authority = document.getElementById('name1');
   var name_list = ["A", "B", "C"];
   var selectList = document.createElement('select');
   selectList.setAttribute('name', 'userName');
   for(var i = 0; i <name_list.length; i++){
       var options = document.createElement('option');
       options.text=name_list[i];
       selectList.append(options);
   }
  column_authority.appendChild(selectList);

One of the Test Cases that is failing:
 it('update button should not have a css class hideElement', function () {
$('button[name="updateUser"]').click();
expect($('button[name="updateBtn"]')).not.toHaveClass('hideElement');

});
But it is failing at this point of the function:
selectList.append(options)

A: I guess Phantom JS does not recognize append function. Things are working fine for me now,
all I did is changed
selectList.append(options); to
selectList.appendChild(options);

This change answered all my failing test cases.
Thank you guys very much for your interest in providing a solution for my issue.


text:
Q: Parse text without delimiters using regex line by line I would like to extract 5 fields from this sample log. I do not want to use delimiters, only regex.
How do I parse each line and extract the fields I want?
Regex
rx_dict = {
'date': re.compile(r'(?P<date>(\d+)[\/](\d+)[\/](\d+))'),
'time': re.compile(r'(?P<time>\d{2}:\d{2}:\d{2}.(?:AM|PM))'),
'client': re.compile(r'(?P<client>(?:[0-9]{1,3}\.){3}[0-9]{1,3})'),
'flags': re.compile(r'(?P<flags>(?<=\].)(.{1,4}))'),
'query': re.compile(r'(?P<query>\s+([\S]*)$)'),
 }

Sample Log
4/19/2020 11:59:09 PM 2604 PACKET  0000014DE1921330 UDP Rcv 192.168.1.28   f975   Q [0001   D   NOERROR] A      (7)pagead2(17)googlesyndication(3)com(0)
4/19/2020 11:59:09 PM 0574 PACKET  0000014DE18C4720 UDP Rcv 192.168.2.54    9c63   Q [0001   D   NOERROR] A      (2)pg(3)cdn(5)viber(3)com(0)

A: You could use 1 pattern with re.findall to get the groups, and omit unnecessary groupings from your patterns.
Instead of using a lookbehind (?<=\].) you could match the ] char.
^(?P<date>\d+/\d+/\d+) (?P<time>\d{2}:\d{2}:\d{2} [AP]M).*? (?P<client>(?:[0-9]{1,3}\.){3}[0-9]{1,3}).*?] (?P<flags>.{1,4}).*? (?P<query>\S*)$

The separate parts look like

*

*^ Start of string

*(?P<date>\d+/\d+/\d+) Group date, match digits separated by / and space

*(?P<time>\d{2}:\d{2}:\d{2} [AP]M) Group time, match digits separated by : and AM or PM

*.*? Match any char as least as possible, then a space

*(?P<client>(?:[0-9]{1,3}\.){3}[0-9]{1,3}) Group client, match ip like format

*.*?] Match any char as least as possible, then ] and a space

*(?P<flags>.{1,4}).*? Group flags match 4 times any char except a newline and match a space

*(?P<query>\S*) Group query Match 0+ times a non whitespace char

*$ End of string

Regex demo | Python demo
Example code
import re

regex = r"^(?P<date>\d+/\d+/\d+) (?P<time>\d{2}:\d{2}:\d{2} [AP]M).*? (?P<client>(?:[0-9]{1,3}\.){3}[0-9]{1,3}).*?] (?P<flags>.{1,4}).*? (?P<query>\S*)$"

test_str = ("4/19/2020 11:59:09 PM 2604 PACKET  0000014DE1921330 UDP Rcv 192.168.1.28   f975   Q [0001   D   NOERROR] A      (7)pagead2(17)googlesyndication(3)com(0)\n"
            "4/19/2020 11:59:09 PM 0574 PACKET  0000014DE18C4720 UDP Rcv 192.168.2.54    9c63   Q [0001   D   NOERROR] A      (2)pg(3)cdn(5)viber(3)com(0)")
print(re.findall(regex, test_str, re.M))

Output
[('4/19/2020', '11:59:09 PM', '192.168.1.28', 'A   ', '(7)pagead2(17)googlesyndication(3)com(0)'), ('4/19/2020', '11:59:09 PM', '192.168.2.54', 'A   ', '(2)pg(3)cdn(5)viber(3)com(0)')]

A: If I understand you correctly, and you are only interested in applying the regular expressions you have in your dictionary, then the following should get you started
import re

log = ["4/19/2020 11:59:09 PM 2604 PACKET  0000014DE1921330 UDP Rcv 192.168.1.28   f975   Q [0001   D   NOERROR] A      (7)pagead2(17)googlesyndication(3)com(0)",
       "4/19/2020 11:59:09 PM 0574 PACKET  0000014DE18C4720 UDP R cv 192.168.2.54    9c63   Q [0001   D   NOERROR] A      (2)pg(3)cdn(5)viber(3)com(0)"]

rx_dict = {
    'date': re.compile(r'(?P<date>(\d+)[\/](\d+)[\/](\d+))'),
    'time': re.compile(r'(?P<time>\d{2}:\d{2}:\d{2}.(?:AM|PM))'),
    'client': re.compile(r'(?P<client>(?:[0-9]{1,3}\.){3}[0-9]{1,3})'),
    'flags': re.compile(r'(?P<flags>(?<=\].)(.{1,4}))'),
    'query': re.compile(r'(?P<query>\s+([\S]*)$)'),

for item in log:
    for key, r_exp in rx_dict.items():
        print(f"{key}: {r_exp.search(item).group(1)}")
    print()

Out:
date: 4/19/2020
time: 11:59:09 PM
client: 192.168.1.28
flags: A
query:       (7)pagead2(17)googlesyndication(3)com(0)

date: 4/19/2020
time: 11:59:09 PM
client: 192.168.2.54
flags: A
query:       (2)pg(3)cdn(5)viber(3)com(0)


text:
Q: uncaught referenceerror: is not defined onclick AspNet MVC In my project I need to call a "Save Items" function, but when I click the button nothing happens .. and I get the following error: "Uncaught ReferenceError: SaveData is not defined
     At HTMLAnchorElement.onclick (Create: 82) "
Anyone have any idea what might be causing this error?
The function:
function SalvarPedido() {

var data = $("#Data").val();
var valor = $("#Valor").val();
var descricao = $("#Descricao").val();

var token = $('input[name="__RequestVerificationToken"]').val();
var tokenadr = $('form[action="/Pedido/Create"] input[name="__RequestVerificationToken"]').val();

var headers = {};
var headersadr = {};
headers["__RequestVerificationToken"] = token;
headersadr["__RequestVerificationToken"] = tokenadr;

var url = "/Pedido/Create";

$.ajax({
    url: url
    , type: "POST"
    , datatype: "json"
    , headers: headersadr
    , data: { Id: 0, Data: data, Valor: valor, Descricao: descricao, __RequestVerificationToken: token }
    , success: function (data) {
        if (data.Resultado > 0) {
            ListarItens(data.Resultado);
        }
    }

});

}
The HTML:
div class="form-group">

            Salvar Pedido


text:
Q: Get current store id in opencart i try to show different header image in  frontend based on store id mean every store has different header image .
the problem is how to echo current store_id in frontend (in header)
so i can proceed with my code something like below :
<?php
if($store_id == '1') {  // 1 is default store
    //echo image here
}
else {  //if not default show different image
    //echo image here
}
?>

Opencart version : 1.4.9.6

A: The current store_id of Your store is in $this->config->get('config_store_id').
That means if You need it in the template, edit header controller (catalog/controller/common/header.php) - some in the index() function add this code (id it is not present already):
$this->data['store_id'] = $this->config->get('config_store_id');

Then in Your header.tpl of Your template (catalog/view/theme/<YOUR_THEME>/template/common/header.tpl) use it this way:
<?php if ($tore_id == 0) { ?>

Main store

<?php } else { ?>

Subdomain store

<?php } ?>

or this way:
<div class="container-<?php echo $store_id; ?>"> ...

It is upon You.
EDIT: Also consider moving on with newer OpenCart (latest is 1.5.4.1 as of 15th December, 2012) - it is worth the redesign and the functions and gadgets it has.


text:
Q: How to create a loop to find the mean of values found by a nested loop? Below I have code that finds the relative standard deviation of a bootstrap population that were bootstrapped from sample sizes ranging between 2 and 30.
I would like to create a loop that runs this loop for 10 iterations, finding the mean standard deviation for each sample size (2->30), and puts it into a data frame, so instead of the output being n 2:30 with the subsequent standard deviation, the standard deviation is instead a mean standard deviation (from 10 loops). I hope that makes sense.
n_range <- 2:29
bResultsRan <- vector("double", 28)
set.seed(30)
for (b in n_range) {
  bRowsRan<-Random[sample(nrow(Random), b), ]
  base <- read.table("base.csv", header=T, sep="," )
  base$area<-5036821
  base$quadrea <- base$area * 16
  bootRan <- boot(data=bRowsRan$count, average, R=1000)
  base$data<- bootRan$t
  base$popsize<-(base$data*base$quadrea)
  bValue <- sd(base$popsize)/mean(base$popsize)
  bResultsRan[[b - 1]] <- bValue}

BRRan <- data.frame(n = n_range, bResultsRan)

plot(BRRan)


text:
Q: Syntax error from adding IF function to Visualforce error I've isolated a syntax error down to one simple addition of an inline IF function.
If I comment out Block B and uncomment A, it compiles fine and renders as expected. If all I do is comment out Block A and uncomment Block B, Mavensmate won't let me compile and throws this error:
Result: [COMPILE FAILED]: (RevenueSchedule) Syntax error.  Missing ')'  (Line: 1, Column: -1)

Block A:
<apex:inputText id="revAmt"
rendered="{!IF(isLocked == false,'true','false')}"
value="{!sched.revenue}"
styleClass="amountField"
onchange="updateTotals('{!revSched.lineItem.id}');" />

Block B:
<apex:inputText id="revAmt"
rendered="{!IF(isLocked == false,'true','false')}"
value="{!IF(revSched.scheduleType == 'L',revSched.totalRevenue,sched.revenue)}"
styleClass="amountField"
onchange="updateTotals('{!revSched.lineItem.id}');" />

As you can see, they are identical besides the addition of the IF function to block B. That's the only reason I haven't definitively concluded that the syntax error lies elsewhere on the page. Can anyone see anything definitely wrong syntactically with anything in Block B, or any reason Block A would compile but not B?

A: This works with an output field, but not an input field. The value parameter cannot conditionally bind to two different fields.
<apex:page showHeader="true" sidebar="true" standardController="Account">
    <apex:form>
        <apex:inputText value="{!IF(FIND(Account.Name, 'a') >= 0, Account.Name, Account.AccountNumber)}"/>
    </apex:form>
</apex:page>

This does not compile, but change inputText to outputText and it will work.
To make this work, you will need to move that logic into your controller.
Set up a conditional getter and a conditional setter to set/get the value of either sched.revenue or revSched.totalRevenue depending on the logic you want.


text:
Q: Why does lens include an Iso for fromEnum/toEnum, but not one for show/read? Suppose you declare two isomorphisms
showing :: (Read a, Show a) => Iso' String a
showing = iso read show

reading :: (Read a, Show a) => Iso' a String
reading = iso show read

They are unsafe, not every String will parse as an a.
That begs the question: Why those two aren't included in the library if enum = iso fromEnum toEnum is?
It is just as unsafe and can't be prevented by the type system. They all shift the burden onto the programmer who has to ensure that the transformation will not break the isomorphism.
Quick example: under enum (+1) True will throw an exception

A: Warning: speculative answer follows.
One difference between the two scenarios I can think of is that it is reasonably easy to clarify when toEnum breaks down (quoting the lens docs: "this is only an isomorphism from the numeric range actually used"), while things are a fair bit murkier when it comes to read. Another difference is that toEnum is a method of Enum (and one required in a minimal instance definition, at that), while read isn't actually a method of Read, and so is, in a sense, less essential (in fact, the base docs explicitly discourage its usage).
On a more general note, when it comes to choosing between exposing a bullet-proof interface and including useful but potentially unsafe or unlawful combinators, lens usually goes for the latter, making them available for those who wish to use them while acknowleding any potential issues in the documentation (or, in hairier cases, in function and module names). Given that lens is a very general purpose library, this approach can be seen as a non-opinionated choice -- in a context like this, it can be hard to compensate for the absence of combinators.
P.S.: It is also worth noting that lens encodes read and show through the _Show prism. _Show is equivalent to prism' show readMaybe, and is safe with respect to the partiality of Read-ing values.

A: Besides the excellent comments in the other answer, I would hesitate about the lawfulness of these definitions. For the standard instances, where defined, fromEnum . toEnum (and vice versa) is actually id. But show . read is not, even for fully-defined values and using only standard instances, because it canonicalizes formatting and parenthesization:
> show (read "(5)" :: Int)
"5"
Data.Tree> show (read "Node     {      rootLabel=3 ,subForest=[]}" :: Tree Int)
"Node {rootLabel = 3, subForest = []}"


text:
Q: Awk between two dates in a logfile - almost working I have a csh script which is trying to identify entries in a logfile between two dates
(in the script they are $start_date and $end_date entered as DD/MM/YYYY but I have simplified here)
more text_B_14_FEB_03.dt | grep TMYO

TMYO140043J:=TMYO140043J     P33BJm SOLO            03/02/2014
TMYO140044J:=TMYO140044J     P4m    FINL            03/02/2014
TMYO140044M:=TMYO140044M     P3BJ   FINL            03/02/2014
TMYO140045M:=TMYO140045M     P33BJq MARS            04/02/2014
TMYO140046M:=TMYO140046M     P33BJq RENN            04/02/2014
TMYO140047M:=TMYO140047M     P33BJl AKHT            05/02/2014
TMYO140048M:=TMYO140048M     P3l    MACL            05/02/2014
TMYO140049M:=TMYO140049M     P3q    HAYE            06/02/2014
TMYO140050M:=TMYO140050M     P3q    ROCH            06/02/2014
TMYO140051M:=TMYO140051M     P3q    FORR            06/02/2014
TMYO140052L:=TMYO140052L     P3v    ROSE            07/02/2014
TMYO140053L:=TMYO140053L     P3v    CAIR            07/02/2014
TMYO140054L:=TMYO140054L     P3v    MURR            07/02/2014

I have tried the following but it can't handle dates properly from previous year?
more text_B_14_FEB_03.dt | grep TMYO | awk '$5>="02/01/2013" && $5<="13/02/2014"'

TMYO140043J:=TMYO140043J     P33BJm SOLO            03/02/2014
TMYO140044J:=TMYO140044J     P4m    FINL            03/02/2014
TMYO140044M:=TMYO140044M     P3BJ   FINL            03/02/2014
TMYO140045M:=TMYO140045M     P33BJq MARS            04/02/2014
TMYO140046M:=TMYO140046M     P33BJq RENN            04/02/2014
TMYO140047M:=TMYO140047M     P33BJl AKHT            05/02/2014
TMYO140048M:=TMYO140048M     P3l    MACL            05/02/2014
TMYO140049M:=TMYO140049M     P3q    HAYE            06/02/2014
TMYO140050M:=TMYO140050M     P3q    ROCH            06/02/2014
TMYO140051M:=TMYO140051M     P3q    FORR            06/02/2014
TMYO140052L:=TMYO140052L     P3v    ROSE            07/02/2014
TMYO140053L:=TMYO140053L     P3v    CAIR            07/02/2014
TMYO140054L:=TMYO140054L     P3v    MURR            07/02/2014

here it wrongly misses date entries from 03/02/2014 when i change start date to 04/01/2013??
more text_B_14_FEB_03.dt | grep TMYO | awk '$5>="04/01/2013" && $5<="13/02/2014"'

TMYO140045M:=TMYO140045M     P33BJq MARS            04/02/2014
TMYO140046M:=TMYO140046M     P33BJq RENN            04/02/2014
TMYO140047M:=TMYO140047M     P33BJl AKHT            05/02/2014
TMYO140048M:=TMYO140048M     P3l    MACL            05/02/2014
TMYO140049M:=TMYO140049M     P3q    HAYE            06/02/2014
TMYO140050M:=TMYO140050M     P3q    ROCH            06/02/2014
TMYO140051M:=TMYO140051M     P3q    FORR            06/02/2014
TMYO140052L:=TMYO140052L     P3v    ROSE            07/02/2014
TMYO140053L:=TMYO140053L     P3v    CAIR            07/02/2014
TMYO140054L:=TMYO140054L     P3v    MURR            07/02/2014

Any idea where is the awk part is going wrong? I appreciate perl is probably the most flexible answer to this, but my perk scripting is not there yet, and I would like to solve this using awk first.

A: You need to parse dates to seconds and compare them. You have to use mktime() function, that accepts a string with each part of a date, so you will have to split() it first. This program is weird because it has much repeated code, but it seems to work, and I hope you get the idea:
awk '
    BEGIN {
        date1 = "04/02/2014"
        split(date1, arr, "/")
        seconds1 = mktime(arr[3] " " arr[2] " " arr[1] " 0 0 0")

        date2 = "06/02/2014"
        split(date2, arr, "/")
        seconds2 = mktime(arr[3] " " arr[2] " " arr[1] " 0 0 0")
    }

    {
        split($NF, arr, "/")
        s = mktime(arr[3] " " arr[2] " " arr[1] " 0 0 0")

        if (s >= seconds1 && s <= seconds2) {
            print $0
        }
    }
' infile

With your second example data, it yields:
TMYO140045M:=TMYO140045M     P33BJq MARS            04/02/2014
TMYO140046M:=TMYO140046M     P33BJq RENN            04/02/2014
TMYO140047M:=TMYO140047M     P33BJl AKHT            05/02/2014
TMYO140048M:=TMYO140048M     P3l    MACL            05/02/2014
TMYO140049M:=TMYO140049M     P3q    HAYE            06/02/2014
TMYO140050M:=TMYO140050M     P3q    ROCH            06/02/2014
TMYO140051M:=TMYO140051M     P3q    FORR            06/02/2014

A: You should transform date to a format YYYYMMDD so it can be lexicographilly ordered. You can do it with gawk and regex, or by doing substrings operations with awk. Here is the gawk way
more text_B_14_FEB_03.dt | grep TMYO | gawk 'match($5, "([0-9]+)/([0-9]+)/([0-9]+)", ary) {B
=ary[3] ary[2] ary[1]; if (B < 20140213 && B> 20130104) print }'


text:
Q: How to add jwt auth to swagger (node + express)? I create project like this:
https://scotch.io/tutorials/speed-up-your-restful-api-development-in-node-js-with-swagger
swagger project create mega-project

How can I add jwt auth to project?
because I don't have idea, how I can do this to swagger :(


text:
Q: Unable to archive in React Native - Archive Fails with duplicate symbols for architecture arm64 It's showing

285 duplicate symbols for architecture arm64
Linker command failed with exit code 1 (use -v to see invocation)

Strangely, I can't seem to get Archive to work in XCode but the build succeeds without the errors on duplicate symbols and it's running properly on simulator as well. I'm getting this error only when I'm trying to make archive.
The project is on React Native 0.56.0, podfile installed as well.
I have no idea what the problem might be.

A: If you're coming from an old React Native template and started using cocoapods, make sure to remove all libraries linked on .xcodeproj:

*

*First remove the libraries links:

*Then the delete projects references too:

Finally, try archiving again.


text:
Q: OData Associations In C# I was reading about OData sources at Odata.org when I ran across this segment about associations.

Associations define the relationship between two or more Entity Types
  (for example, Employee WorksFor Department). Instances of associations
  are grouped in Association Sets. Navigation Properties are special
  properties on Entity Types which are bound to a specific association
  and can be used to refer to associations of an entity.
Finally, all instance containers (Entity Sets and Association Sets)
  are grouped in an Entity Container.
Putting the above paragraphs into OData terms, the feeds exposed by an
  OData service are represented by Entity Sets or a Navigation Property
  on an Entity Type that identifies a collection of entities. For
  example, the Entity Set identified by the URI
  http://services.odata.org/OData/OData.svc/Products or the collection
  of entities identified by the "Products" navigation property in
  http://services.odata.org/OData/OData.svc/Categories(1)/Products
  identifies a feed of entries exposed by the OData service.

I am making a OData service in C# using Visual Studio 2012 and would like to use the URL functionality mentioned. However I do not know how to set it up. Does anybody know how to do this?
Here is my code:
    public class AssociationTest : DataService<ServiceContext>
{
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
        config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
        config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
    }
}
public class ServiceContext
{
    CategoryList _categories = new CategoryList();
    public IQueryable<Category> CategorySet
    {
        get{return _categories.AsQueryable();}
    }
    ProductList _products = new ProductList();
    public IQueryable<Product> ProductSet
    {
        get{return _products.AsQueryable();}
    }

}
[System.Data.Services.Common.DataServiceKeyAttribute("ID")]
public class Category
{
    public string Type
    {
        get;
        set;
    }
    public int ID
    {
        get;
        set;
    }
}
public class CategoryList : List<Category>
{
    public CategoryList()
        : base()
    {
        Add(new Category { Type = "Hardware", ID = 0 });
        Add(new Category { Type = "Software", ID = 1 });
    }
}
[System.Data.Services.Common.DataServiceKeyAttribute("ID")]
public class Product
{
    public string Name
    {
        get;
        set;
    }
    public int ID
    {
        get;
        set;
    }
    public int CategoryID
    {
        get;
        set;
    }
}
public class ProductList:List<Product>
{
    public ProductList()
        : base()
    {
        Add(new Product { Name = "Computer", ID = 0, CategoryID = 0 });
        Add(new Product { Name = "Phone", ID = 1, CategoryID = 0 });
        Add(new Product { Name = "Outlook", ID = 2, CategoryID = 1 });
        Add(new Product { Name = "Excel", ID = 3, CategoryID = 1 });
    }
}

A: Instead of modeling the relationship between Product->Category with a foreign key, you could have your service model point to the product's category directly. What I mean is that instead of this:
public class Product
{
    // ...
    public int CategoryID
    {
        get;
        set;
    }
}

You could model it like this:
public class Product
{
    // ...
    public Category ProductCategory
    {
        get;
        set;
    }
}

If you set up the model this way, the WCF Data Services reflection provider should automatically create a navigation property on Product as well as the necessary association in the model.


text:
Q: Unable to create external item Trying to create an external item using
await graphClient.Connections[connectionId].Items[item.Id].Request().PutAsync(item);

by sending the following:
    {
  "properties": {
    "ticketTitle": "title of the item",
    "priority": "high",
    "assignee": "someone@somewhere.com",
    "additionalData": null,
    "@odata.type": null
  },
  "acl": [
    {
      "accessType": 1,
      "identitySource": "External",
      "type": 1,
      "value": "SomeUser",
      "additionalData": null,
      "@odata.type": "microsoft.graph.acl"
    }
  ],
  "content": {
    "type": 1,
    "value": "Some value",
    "additionalData": null,
    "@odata.type": "microsoft.graph.externalItemContent"
  },
  "id": "ABCD12345",
  "@odata.type": "microsoft.graph.externalItem",
  "additionalData": null
}

But I get the following response back:
Code: UnknownError
Inner error:
        AdditionalData:
        date: 2021-03-24T22:31:31
        request-id: fc55be4e-c84d-4376-8305-d0e33f2729a0
        client-request-id: fc55be4e-c84d-4376-8305-d0e33f2729a0
ClientRequestId: fc55be4e-c84d-4376-8305-d0e33f2729a0

What am I doing wrong? I tried not sending AdditionalData or ODataType in Properties, but same error

A: This is a bug in the Graph SDK beta. Gory details at https://github.com/microsoftgraph/msgraph-beta-sdk-dotnet/issues/260 - but essentially I monitored the network traffic and noticed that no PUT calls to the Graph API. The request url that the Graph SDK beta is using is missing "external" in between 'beta' and 'connections' - so instead of using 'beta/external/connections' it was using 'beta/connections'
Aaaaaargh. (and that is why it is called beta, I suppose).


text:
Q: Can I write a Java loader class that will hook HTTP requests in the loaded class? I have a class that I want to hook and redirect HTTP requests in.
I also have a loader class already written, but all it does it replace the functions that contain the HTTP requests I want to change.
Is there a way to hook HTTP requests in Java so that I can redirect them all more easily?
Sort of like a proxy-wrapper.
Clarification:
The app sends out a GET or POST request to a URL.
I need the content to remain the same, just change the URL.
DNS redirects won't work, the Host HTTP header needs to be correct for the new server.
PS: This is a Desktop App, not a server script.

A: A cumbersome but reliable way of doing this would be to make your application use a proxy server, and then write a proxy server which makes the changes you need. The proxy server could be in-process in your application; it wouldn't need to be a separate program.
To use a proxy, set a couple of system properties - http.proxyHost and http.proxyPort. Requests made via HttpURLConnection will then use that proxy (unless they specifically override the default proxy settings). Requests made using some other method like Apache HttpClient will not, i think, be affected, but hopefully, all your requests are using HttpURLConnection.
To implement the proxy, if you're using a Sun JRE, then you should probably use the built-in HTTP server; set up a single handler mapped to the path "/", and this will pick up all requests being sent by your app, and can then determine the right URL to send them to, and make a connection to that URL (with all the right headers too). To make the connection, use URL.openConnection(Proxy.NO_PROXY) to avoid making a request to the proxy and so getting caught in an infinite loop. You'll then need to pump input and output between the two sockets.
The only other way i can think of to do this would be to override HttpURLConnection with a new handler which steers requests to your desired destination; you'd need to find a way to persuade the URL class to use your handler instead of the default one. I don't know how you'd do that in a clean way.

A: While an older post, this should give some ideas of some kinds of bytecode injects which can be peformed: Java Programming: Bytecode Injection. Another tool is Javassist and you may be able to find some links from the Aspected-oriented programming wiki article (look at the bytecode weavers section).
There are some products which extensively dynamically modify code.
Depending upon what is desired, there may be ... less painful ... methods. If you simply want to 'hook' HTTP requests, another option is just to use a proxy (which could be an external process) and funnel through that. Using a proxy would likely require control over the name resolution used.

A: you can use servlet filters which intercept the requests, the requests can further be wrapped, redirected, forwarded or completed from here.
http://www.oracle.com/technetwork/java/filters-137243.html

A: Do you control all of the code? If so, I suggest using Dependency Injection to inject the concrete implementation you want, which would allow you to instead inject a proxy class.

A: *

*If you can change the source code, just change it and add your extra code on each HTTP request.

*If you can't change the source code, but it uses dependency injection, perhaps you can inject something to catch requests.

*Otherwise: use aspect-oriented programming and catch to URL class, or whatever you use to do HTTP requests. @AspectJ (http://www.eclipse.org/aspectj/doc/next/adk15notebook/ataspectj.html ) is quite easy and powerful.


text:
Q: Round off a number to display without decimals I have two values to display. Both of these contain decimals. I would like to round these numbers off so that the decimal will be eliminated. I tried to hide the decimal but the rounding off is not implemented. How do I do this ?
public Text minimumValue;
public Text maximumValue;

 void Start() {
      minimumValue.text = (54.7f / 100).ToString ("F0");
      maximumValue.text = (24.97f / 100).ToString ("F0");

}

A: To round up you use Math.Ceiling
public Text minimumValue;
public Text maximumValue;

 void Start() {
      minimumValue.text = Math.Ceiling(54.7f / 100).ToString ("F0");
      maximumValue.text = Math.Ceiling(24.97f / 100).ToString ("F0");

}

This will make both your examples round to 1 as shown here: https://dotnetfiddle.net/sGrjqQ


text:
Q: Whenever ansible makes changes to sshd in CentOS7 a random future play cannot connect This has been an irritating enough problem now that I thought I would finally ask the community at large what a possible solution might be.  It's even more irritating that I seem to be the only one experiencing this issue.
Essentially, anytime in CentOS 7.x, sshd configs, or any part of sshd gets modified, and the daemon gets restarted/reloaded at some "random point" in the next 3 minutes, the ssh connections all reset, and then that server is unreachable for a few seconds time via ssh.
This is especially a problem for ansible in that it needs to do these changes itself to sshd sometimes, and also reloading it (for instance in new CentOS 7x server builds).  But then in future plays it just randomly can't connect to ssh, and the it blows up the rest of the playbook/plays for that host which failed to be contacted.  This is especially bad for a large host pattern, as a few will randomly complete, but the others will fail at various stages along the playbook after sshd is manipulated.  It is of note, that nothing of the sort occurs in CentOS 5x, 6x, or even on Solaris.
The best I can do to avoid this is to create a 90 second wait after any changes to sshd, and even this isn't totally foolproof.  It makes those playbooks take 20+ minutes to run though if it's invoked 7-8 times.
Here are some facts on this environment:
All new installs are from official ISO DVD's.
Every server is a hyper-v 2012 guest
Every server which has this problem is CentOS 7.x
Here is some actual output of the problems and some hackneyed solutions:
The failure:
fatal: [voltron]: UNREACHABLE! => {"changed": false, "msg": "All items         completed", "results": [{"_ansible_item_result": true, "item": ["rsync", "iotop", "bind-utils", "sysstat.x86_64", "lsof"], "msg": "Failed to connect to the host via ssh: Shared connection to voltron closed.\r\n", "unreachable": true}]}

Example of one of the changes to sshd:
- name: Configure sshd to disallow root logins for security purposes on CentOS and Redhat 7x servers.
    lineinfile:
      backup: yes
      dest: /etc/ssh/sshd_config
      regexp: '^(#PermitRootLogin)'
      line: "PermitRootLogin no"
      state: present
    when: (ansible_distribution == "CentOS" or "RedHat") and (ansible_distribution_major_version == "7")
    notify: sshd reload Linux 7x

The following handler:
- name: sshd reload Linux 7x
   systemd:
     state: restarted
     daemon_reload: yes
     name: sshd

Finally my ghetto fix to try and account for this problem:
- name: Wait a bit on CentOS/Redhat 7x servers to ensure changes don't mess up ssh and screw up further plays.
    pause:
      seconds: 90
    when: (ansible_distribution == "CentOS" or "RedHat") and (ansible_distribution_major_version == "7")

There has got to be a better solution than what I came up with, and it's hard to believe that everyone else encounters this and also puts up with it.  Is there something I need to configure in CentOS 7.x servers to prevent this?  Is there something in ansible that is needed to deal with this, such as multiple ssh attempts per play on first failure?
Thanks in advance!

A: Rather than using the systemd module, try the service module:
- name: Restart secure shell daemon post configuration
  service:
    name: sshd
    state: restarted

A: This seems to be a common Problem.
Patch for Ansible ssh retries from 2016
A better solution might be to wait for sshd to be ready to connect.
Original thread with this ansible code solution:
[VM creation tasks...]
  - name: Wait for the Kickstart install to complete and the VM to reboot
    local_action: wait_for host={{ vm_hostname }} port=22 delay=30 timeout=1200 state=started
  - name: Now configure the VM...


text:
Q: Creating C# Objects Dynamically Currently having an issue creating a reusable object that I will need to use in a JSON construct string function.
Currently I have the following to create the bulk of the JSON string:
var data = new
  {
    record = new
      {
        value1 = Row.value1,
        value2 = Row.value2,
        form_values = new Dictionary<string, string>()
       }
   };
data.record.form_values["833b"] = Row.value3.ToString();
data.record.form_values["98wq"] = BuildMultiSelectList(Row.value3.ToString());

public object BuildMultiSelectList(string datavalue)
{
    var choicelist = new {
                      choice_values: [datavalue],
                      other_values: [],
                      };
    return choicelist;
}

The top half all works fine, though the function BuildMultiSelectList is giving errors such as "choice_values" does not exist in the current context and datavalue does not exist in the current context.
Any insight on why this has gone a bit rouge will be appreciated.

A: May be you are just mixing colon : with =?
        var choicelist = new {
                      choice_values = new string[] {datavalue},
                      other_values = new[] {},
                      };


text:
Q: CakePHP 2.x How to determine view path in controller in beforeRender() or earlier? I have the need to determine what app path my controller method will use for serving up the view before it does so. I'm using a theme but I also have many non-themed view files. I'm switching my themes based on domain name (2 domains point to the same Cake install) but need to exclude the non-themed views from rendering inside my theme.
This may sound confusing. Here's what is currently happening if a URL is accessed that does not have a theme view associated with it:

domainA.com/examples/index will render the view app/View/Examples/index.ctp with the layout from app/View/Layouts
domainB.com/examples/index will render the view app/View/Examples/index.ctp BUT with the layout from app/View/Themed/MyTheme/Layouts

This is because the "MyTheme" theme does not contain a view file for this controller-method pair (this is intentional). So I would like to instead have the following established:

domainB.com/examples/index continues to render the view app/View/Examples/index.ctp BUT INSTEAD with the layout from app/View/Layouts

This should only happen, of course, if and only if there is no view file within the "MyTheme" directory structure.

A: I think this is what you are looking for $this->View->viewPath.
You can use this in any controller call back function or action.


text:
Q: How to insert autoincrementing id from one table into another in one command (using returning)? I've attempted the following:
INSERT INTO second_table(id, somethingelse)
VALUES(
       (INSERT INTO first_table(post_text) VALUES('a text') RETURNING id),
       'abcd123'
    );

I know how to do select with 2 query, but I'm trying to avoid any concurrency issue by doing these 2 insertions at once. Above gives me the following error:
ERROR:  syntax error at or near "INTO"
LINE 3:         (INSERT INTO first_table(post_text) VALUES('a text...

I'm trying to insert auto-incrementing id from first_table into second_table when a row is inserted into first_table.

A: Use a data modifying CTE:
with first_insert as (
  INSERT INTO first_table(post_text)
  VALUES('a text')
  RETURNING id
)
INSERT INTO second_table(id, somethingelse)
select id, 'abcd123'
from first_insert;

A: Try creating a trigger to be executed whenever a row is inserted in first table.
something like:
CREATE  TRIGGER trigger_name AFTER INSERT OF post_text
ON first_table
[
 INSERT INTO second_table(id, somethingelse)
VALUES(
       (select id from first_table where post_text='a text'),
       'abcd123'
    );
];

A: You need to run below command to off identity column
    Set Identity_Insert [TableName] Off


text:
Q: R kernel for jupyter dying --- can't find libzmq.so.4 I'm using the Anaconda R-essentials bundle.
Following the docs, I created a virtual env:
conda create -n my-r-env -c r r-essentials
I started a Jupyter notebook ipython notebook --no-browser.
I create a new R notebook (I see R in the dropdown below Python3).
But the kernel keeps dying and Jupyter is throwing the error:
libzmq.so.4: cannot open shared object file: No such file or directory
The directory it's looking in (my-r-env/lib/R/library/rzmq/libs) has rzmq.so.
But, not libzmq.so.4.
What's the right way to solve this?


text:
Q: (Beginner) Proving arguments with resolution with detailed steps I am very new to resolution and would like to use it to prove the following two  arguments. I also would like to indicate the laws of equivalence used to obtain Skolem Normal Form of the premises and the negated conclusion:

1)
$Premise ~ 1: ∃x ~ toad(x) \\
Premise ~ 2: ∀x ~ (toad(x) → slimy(x)) \\
Premise ~ 3: ∀x ~ (slimy(x) → muddy(x)) \\
Conclusion: ∃x ~ (muddy(x) ∧ toad(x))$
Attempt:
Aside for turning negated conclusion into clausal normal form:
1. ∃x.(muddy(x) ∧ toad(x))        (Initial Conclusion)
2. ¬∃x.(muddy(x) ∧ toad(x))       (Negated Conclusion)
3. ∀x.¬(muddy(x) ∧ toad(x))       (DeMorgan Quantifer)
4. ∀x.(¬muddy(x) ∨ ¬toad(x))      (DeMorgan)
5. (¬muddy(x1) ∨ ¬toad(x1))       (∀-elim)

Aside for converting Premise 1:
1. ∃x.toad(x)                     (Initial Premise 1)
2. toad(c)                        (Skolemization)

Aside for converting Premise 2:
1. ∀x.(toad(x) → slimy(x))        (Initial Premise 2)
2. ∀x.(¬toad(x) ∨ slimy(x))       (Def. →)
3. (¬toad(x2) ∨ slimy(x2))        (∀-elim)

Aside for converting Premise 3:
1. ∀x.(slimy(x) → muddy(x))       (Initial Premise 3)
2. ∀x.(¬slimy(x) ∨ muddy(x))      (Def. →)
3. (¬slimy(x3) ∨ muddy(x3))       (∀-elim)

Actual Resolution Proof:
[ 1] {¬muddy(x1), ¬toad(x1)}   Negated Conclusion
[ 2] {toad(c)}                 Premise 1
[ 3] {¬toad(x2), slimy(x2)}    Premise 2
[ 4] {¬slimy(x3), muddy(x3)}   Premise 3
[ 5] {¬muddy(c)}               Res: 1, 2; θ = [x1/c]
[ 6] {¬slimy(x3), ¬toad(x3)}   Res: 1, 4; θ = [x1/x3]
[ 7] {slimy(c)}                Res: 2, 3; θ = [x2/c]
[ 8] {¬slimy(c)}               Res: 2, 6; θ = [x3/c]
[ 9] {}                        Res: 7, 8

2)
$Premise 1: ∀x ~ (big(x) → (muddy(x) ∨ slimy(x))) \\
Premise 2: ∀x ~ ((slimy(x) ∧ ∃y ~ greater(x, y)) → gobbles(x, x)) \\
Premise 3: ∀x ~ ((big(x) ∧ muddy(x)) → ∃y ~ (toad(y) ∧ gobbles(x, y))) \\
Conclusion: ∀x ~ ((big(x) ∧ greater(x, shrek)) → ∃z ~ gobbles(x, z))$
Attempt:
Aside for turning negated conclusion into clausal normal form:
1. ∀x.((big(x) ∧ greater(x,shrek)) → ∃z.gobbles(x,z))    (Initial Conclusion)
2. ¬∀x.((big(x) ∧ greater(x,shrek)) → ∃z.gobbles(x,z))   (Negation)
3. ∃x.¬((big(x) ∧ greater(x,shrek)) → ∃z.gobbles(x,z))   (DeMorgan)
4. ∃x.¬(¬(big(x) ∧ greater(x,shrek)) ∨ ∃z.gobbles(x,z))  (Def. →)
5. ∃x.(¬¬(big(x) ∧ greater(x,shrek)) ∧ ¬∃z.gobbles(x,z)) (DeMorgan)
6. ∃x.(big(x) ∧ greater(x,shrek) ∧ ∀z.¬gobbles(x,z))     (Double Neg., DeMorgan)
7. big(c) ∧ greater(c,shrek) ∧ ∀z.¬gobbles(c,z)          (Skolemization)

Aside for converting Premise 1:
1. ∀x(big(x) → (muddy(x) ∨ slimy(x)))        (Initial Premise 1)
2. ∀x(¬big(x) ∨ (muddy(x) ∨ slimy(x)))       (Def. →)
3. ¬big(x2) ∨ (muddy(x2) ∨ slimy(x2))        (∀-elim)

Aside for converting Premise 2:
1. ∀x.((slimy(x) ∧ ∃y.greater(x,y)) → gobbles(x,x))         (Initial Premise 2)
2. ∀x.(¬(slimy(x) ∧ ∃y.greater(x,y)) ∨ gobbles(x,x))        (Def. →)
3. ∀x.((¬slimy(x) ∧ ¬∃y.greater(x,y)) ∨ gobbles(x,x))       (DeMorgan)
4. ∀x.((¬slimy(x) ∧ ∀y.¬greater(x,y)) ∨ gobbles(x,x))       (DeMorgan)
5. ((¬slimy(x3) ∧ ¬greater(x3,y1)) ∨ gobbles(x3,x3))        (∀-elim)

Aside for converting Premise 3:
1. ∀x.((big(x) ∧ muddy(x)) → ∃y.(toad(y) ∧ gobbles(x,y)))         (Initial Premise 3)
2. ∀x.(¬(big(x) ∧ muddy(x)) ∨ ∃y.(toad(y) ∧ gobbles(x,y)))        (Def. →)
3. ∀x.((¬big(x) ∨ ¬muddy(x)) ∨ ∃y.(toad(y) ∧ gobbles(x,y)))        (DeMorgan)
4. ∀x.((¬big(x) ∨ ¬muddy(x)) ∨ (toad(f(y)) ∧ gobbles(x,f(y))))     (Skolemization)
5. ((¬big(x4) ∨ ¬muddy(x4)) ∨ (toad(f(y)) ∧ gobbles(x4,f(y))))     (∀-elim)
6. ((¬big(x4) ∨ ¬muddy(x4)) ∨ toad(f(y))) ∧ ((¬big(x4) ∨ ¬muddy(x4)) ∨ gobbles(x4,f(y))) (Distribution)

Actual Resolution Proof:
[ 1] {big(c)}                                             ∧-elim-1 Negated Conclusion, then ∧-elim-1 again
[ 2] {greater(c,shrek)}                                   ∧-elim-1 Negated Conclusion, then ∧-elim-2
[ 3] {¬gobbles(c,x1)}                                     ∧-elim-2 Negated Conclusion, ∀-elim
[ 4] {¬big(x2), muddy(x2), slimy(x2)}                     Premise 1
[ 5] {¬slimy(x3), ¬greater(x3,y1), gobbles(x3,x3)}        Premise 2
[ 6] {¬big(x4), ¬muddy(x4), toad(f(y))}                   Premise 3a ∧-elim-1
[ 7] {¬big(x4), ¬muddy(x4), gobbles(x4,f(y))}             Premise 3b ∧-elim-2
How to proceed?

A: For 1), the clause you get for $\exists x toad(x)$ should be $\{ toad(c) \}$, i.e. you need to use a constant here, not a variable. When you remove an existential quantifier and substitute a constant for the variable that was quantified by that existential quantifier, it is called Skolemization.
This constant should then be used (substituted for variables in order to unify) during subsequent resolution as well, e.g. on line 5 you would get $\{ \neg muddy(c) \}$. In fact, on line 7 you would get $\{ slimy(c) \}$, and on line 8 $\{ \neg slimy(c) $, the two of which resolve to the empty clause $\{ \}$, and you are done.
For 2), you need to negate the whole conclusion, which gets you $\exists x (big(x) \land greater(x,shrek) \land \forall z \neg gobbles(x,z))$, and by Skolemization you thus get $big(c) \land greater(c,shrek) \land \forall z \neg gobbles(c,z)$, and thus clauses $\{ big(c) \}$, $\{ greater(c,shrek) \}$, and $\{ \neg gobbles(c,x1) \}$


text:
Q: What does "transitive" mean in group action? By definition, the action of G on A is transitive if there is only one orbit, i.e., given any two numbers a, b ∈ A there is some g ∈ G such that a = g · b.
I want to know why "given any two numbers a, b ∈ A there is some g ∈ G such that a = g · b" is equivalent to "there is only one orbit". Based on what I have learned, the number of the orbits of a is

|O(a)| = |G|/|Ga|

, where Ga is the stabilizer of a.
If there is only one orbit, does it mean that the orbits of all elements of A are the same?
If there is only one orbit, then |O(a)| = 1, so |Ga| = |G|?
I'm so confused with the definition of transitive.

A: The orbit $O(a)$ of an element $a\in A$ is the set $\{ga:g\in G\}$.
Having one orbit means $O(a)=O(b)$ for any $a,b\in A$, which can be easily proved to be the same as transitivity of the action.
Note that the action can be restricted to any orbit $O(a)$ giving a transitive action.
So actually $A$ is the disjoint union of the orbits.
The size of $O(a)$ is irrelevant in being transitive.
For a simple example consider $A=\{0,1,2,3,a,b\}$ and let $G=\Bbb Z/4\Bbb Z=\{0,1,2,3\}$ act on $A$ by addition modulo $4$ on the numbers and
$$0a=2a=1b=3b=a,\quad
0b=2b=1a=3a=b\,.$$
Here we have two orbits: $\{0,1,2,3\}$ and $\{a,b\}$ of different sizes. Restricting the action of any of them yields a transitive action.

A: That definition of transitive basically says "given $a,b\in A$, $a$ is in the orbit of $b$". Meaning that any two elements of $A$ are always in the same orbit. But since all elements have exactly one orbit, there can only be one orbit in total.
And the other way around: if there is only one orbit, then all elements have the same orbit. So any given element $a$ is in the orbit of any further given element $b$. Which is your definition of transitive.


text:
Q: Como criar um contador na detecção de face? Como vocês podem ver no codigo abaixo, ele apenas detecta as faces com haar cascade, gostaria de saber como q faço para exibir na webcam a quantidade de pessoas detectadas no momento.
from  __future__ import print_function #importa a funcao da biblioteca future
import cv2
cap = cv2.VideoCapture(0) #webcam

 face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

while (cap.isOpened()):
ret,frame = cap.read()
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) #faz a conversao pra cinza por ser mais leve pro pc
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, flags=cv2.CASCADE_SCALE_IMAGE,minSize=(50, 50), maxSize=None)

if len(faces) > 0:
    print("Pessoa detectada!")
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x - 10, y - 20), (x + w + 10, y + h + 10), (0, 255, 0), 2)
        roi_gray = frame[y-15:y + h+10, x-10:x + w+10]

    cv2.imshow("imagem", frame) #mostra a face detectada
if cv2.waitKey(1) & 0xFF == ord('q'): # q definido para sair do projeto
    break #para o programa

cap.release() #mostra as coordenadas da deteccao
cv2.destroyAllWindows()

A: acredito que seja isto que esteja procurando...
text = "{} face(s) found".format(len(faces))
cv2.putText(frame, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX,
    0.5, (0, 0, 255), 2)

A: print('Total de Pessoas: {}'.format(len(faces)))


text:
Q: PHP Curl, Collection + JSON Response for specific field I'm messing with the teamsnap API which uses Collection + JSON which seems to be making it a bit more difficult to extract specific data (at least for me).
What I need to do is get each member id so I can loop through those to then get a JSON response for each member's info.  So far I am working on the first step.
Here is my code so far:
<?php
$url = "https://api.teamsnap.com/v3/members/search?team_id=TEAMID";
$access_key = 'TOKEN';
$request = curl_init( $url );
curl_setopt( $request, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $access_key ) );
$response = (string)curl_exec( $request );
curl_close($request);

$result = json_decode($response, true);
foreach ($result as $r) {
echo $r['id'];
}
?>

UPDATE:  I used print_r without json_decode and went line by line through thousands of lines of resposne to see how exactly the information I actually want is coming back.  This is a bit the relevant portion.  Sorry to have led you on a wild goose chase, but the response is quite complicated when it comes back and half of it is examples of how data COULD be returned....
{
    "collection":{
    "items":[
{
"href":"https://api.teamsnap.com/v3/members/MEMBERID",
"data":[
"name":"id",
"value":MEMBERID
},
{
"name":"type",
"value":"member"
},
{
"name":"address_city",
"value":""
},
{
"name":"address_state",
"value":""
},
{
"name":"address_street1",
"value":""
},
{
"name":"address_street2",
"value":null
},
{
"name":"address_zip",
"value":""
},

A: Assuming the data you provided is from $response. The data structure does not provide an easy way to parse the data. In order to get to the 'name':'id' value pair. Do this:
$result = json_decode($response);
foreach ($result->collection->items as $items=>$val) {
    foreach ($val->data as $data=>$datasets) {
        foreach ($datasets as $dataset=>$val) {
            echo $dataset.': '.$val;
            echo "
";
        }
    }
};

It will return the results as:
name: id
value: 3745306
name: type
value: user

A: Based on your edited data structure, the answer that I provided on my previous post no longer work. Here is the one based on your revised data structure:
$result=json_decode($response);
foreach($result->collection->template->data as $dataset) {
    foreach($dataset as $key=>$val) {
        echo $key.": ".$val;
        echo "
";
    }
}


text:
Q: Automator Shortcut only working in Textedit but not other I've been trying to run a piece of code in Automator. It is supposed to reformat text for me when it is correctly run. It gets the input from the clipboard and then outputs in the form of clipboard as well. I could get it to work in textedit and chrome when I apply the keyboard shortcut to which I assigned it. However, it does not work when I try to apply it in an application called Anki. I am guessing it might have to do with the fact it's text input, but that does not make too much sense.
Is there a solution?
Code (which is working, and for your reference):
function run(input, parameters) {

var someText = input[0]
someText = someText.replace(/(\r\n|\n|\r)/gm," ");

someText = someText.replace(/\s+/g,' ');
someText = someText.replace(/(\s)([a-z])[.]/g, '\n$1 $2.');
someText = someText.replace(/(\s)([A-Z])([.])/g, '\n$1 $2.');
someText = someText.replace(/(\s)(\d|\d\d|\d\d\d)([.|:|)])(\s)/g, '\n\n$2'+'. ');

//Other features: lines for bracketed letters and numbers
someText = someText.replace(/([(])(\d|\d\d|\d\d\d)([)])/g, '\n$2'+'.');
someText = someText.replace(/([(])([A-Z]|[a-z])([)])/g, '\n $2'+'.');

//Replace the wor- d dash thingy in case onto another line
someText = someText.replace(/([a-z])([-])(\s)([a-z])/g, '$1$4');

let words = someText.split(' ');

input[0] = (words.join(' '));

// consider the modifications for F. etc or 1. 2. 3. as well as a) b) c). Maybe not a. b. because words do end with that
//  return (input[0].unwrap);

return input[0];
}

Screenshot of how the workflow is like, note 'any application' is selected.


text:
Q: Is there a way to sort a list of two element tuples by both elements, but one of the elements reverse sorted? I want to sort a list of tuples (the tuples have the format (integer, string)) so that they are ordered from greatest to least integer and then the strings are sorted alphabetically without losing the integer order.
### Inputs: data = [(86, 'william'), (74, 'olivia'), (86, 'willaim'), (62, 'lyli'), (74, 'olivai'), (62, 'lily')]
### Outputs: data = [(86, 'willaim'), (86, 'william'), (74, 'olivai'), (74, 'olivia'), (62, 'lily'), (62, 'lyli')]
### What I know how to do: I know how to sort the tuples by specific element from greatest to least
import operator
data.sort(key = operator.itemgetter(0), reverse = True)
### This returns:
### data = [(86, 'william'), (86, 'willaim'), (74, 'olivia'), (74, 'olivai'), (62, 'lily'), (62, 'lyli')]
### At this point I'm not sure how to keep the integers ordered while sorting the strings alphabetically

A: data.sort(key=lambda x: (-x[0], x[1]))

If your key is a tuple, the sorting algorithm will prioritize sorting according to the first element of the tuple, then the second and so on.

A: Python's sort is stable:

The sort() method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).

So you can sort by the strings first, and then by the integers. This leaves the integers in descending order, but any items with the same integer will stay in the same relative order from when they were sorted by the strings.
from operator import itemgetter

data.sort(key=itemgetter(1))
data.sort(key=itemgetter(0), reverse=True)

This is not as efficient as Mikhail Genkin's answer, but it's closer to what you were trying to do.


text:
Q: Ignore changes and continue not behaving the same in VS15 as VS13 What happens in VSC15 is a filename[stale].cpp is created and stepped through instead of the main edited file. This wouldn't be a problem except it not longer allows me to see any of the values of any variable when I mouse over or watch it making live debugging significantly less useful for me.
What used to happen is you'd be stepping through and the yellow cursor would just be some amount of lines off of where it actually was based on the compiled version of the file. I could still see all values so long as they were in memory.
Is there any way to get this functionality back? As it stands now I need to completely restart the app every time I make a change (frequently) if I want to still see any valuable debugging info.
Edit and Continue is also arguably not a solution.. Wish it were.

A: You should be able to get the behavior you're looking for (make changes to your source but not use Edit and Continue) by disabling the debugger option Debug > Options > Enable Native Edit and Continue.
Having this option disabled won't bring up the "Edits were made that could be applied..." dialog, but will instead silently ignore your edit and not go into any stale code.
I've answered your linked question, so I hope Edit and Continue is a solution :)
-Ramkumar,
Visual Studio Debugger


text:
Q: Pass separate value into template function I am trying to find a way to pass value into go template function.
What i mean. I have template functions list defined in struct method:
func (o *MyObj) run() error{
  funcMap := template.FuncMap{
    "func1": func1,
    "func2": func2,
    }
}

Function1 signature is func func1(myval string) string{...}, but for Function2 id need to have access to one of MyObj struct field.
Mean:
func func2(myval string) string{
//MyObj.field would need to be used here.. How can i do it?
}

A: Credit to @JiangYD
func (o *MyObj)func2(myval string) string{}`

func (o *MyObj) run() error{
  funcMap := template.FuncMap{
    "func1": func1,
    "func2": o.func2,
    }
}


text:
Q: How are Pokestops chosen? After playing the game for a little while, I've noticed that Pokestops are chosen seemingly at random locations on the map. A few of them are even in inaccessible places; an abandoned church building, inside of an airforce base, etc. How are these locations chosen as Pokestops?

A: Pokémon GO's database is based on Niantic's portal database for Ingress, which is currently not accepting new requests for more locations while they review the process.
If you want to see every current PokéStop, download and register for Ingress, then go to https://www.ingress.com/intel
There are some plugins you can download to facilitate the discovery of Stops and Gyms based on that information (and even help updating the ones that still aren't registered as either).
Keep in mind that, while every PokéStop and Gym are based on Ingress Portals, not every Portal will be a PokéStop or Gym.


text:
Q: How to solve oversegmented whole white blood cell by watershed in MATLAB or others As the picture, I would like to separate adjacent cells by watershed algorithm, but the result shows oversegmented. How could I use imimposemin() to solve this problem. Thank you!
WATESHED CODE in MATLAB:
D = -bwdist(~BW);
D(~BW)  =-Inf;
L = watershed(D,8);
BW(L==0)=0;

Result
Input BW

A: You have to:

*

*compute the distance map or the ultimate eroded (more stable)

*Dilate the result in order to merge the close patterns

*use the result as inner seeds.

You get this result.
[EDIT] Here is the result when I use the gradient computed on the original image. But be careful, in order to preserve the global shape, I had to merge the gradient and the contour of the binary mask, see here.


text:
Q: Find TODOs with file names and line numbers in git diff I'd like to have a simple shell command to find my TODOs that are in the diff between my current branch and the repository's main branch.
On our team, we have an agreement, that we do not add new todos to the codebase, but we still have a couple of older todo items in our repository. However, when I work, I like to leave a todo in the code so that I don't forget to look into things or clean up things.
What I could already implement is showing the TODO items in the diff using grep. For example, if the main branch is called develop (but honestly, it would work the same with main, master:
# command
git diff develop HEAD | grep TODO

# output
+      // TODO: How to handle when summary is missing?
+      // TODO: How to handle this error? Exception?
+          // TODO: add function to build basket, maybe?
+        // TODO: Find a better place to set up this mock

This is a good start, but it would be much better if the names of the files (that include these todos) were also printed. Another problem with my current approach is that if there is no message after the TODOs, I can't really search for that in my project (in case the code base has TODOs that were added before (and are part of the main branch)

A: Torek's suggestion would look somewhat like this:
# print TODOs from HEAD that are not in develop
comm -23 \
  <(git grep -nFw TODO develop | sed 's/[^:]*://' | sort) \
  <(git grep -nFw TODO HEAD | sed 's/[^:]*://' | sort)

This has a few problems. Since grep -n prefixes each line by its line number, an existing TODO from develop that was moved around by deleting/inserting lines would be listed too. Also, filenames with linebreaks are not handled correctly, but this probably does not matter.
I think the best option would be to parse the output of git diff:
# print TODOs from HEAD that are not in develop
git diff develop HEAD | awk '
  /^diff / {f="?"; next}
  f=="?" {if (/^\+\+\+ /) f=$0"\n"; next}
  /^@@/ {n=$3; sub(/,.*/,"",n); n=0+$3; next}
  /^\+.*TODO/ {print f n ":" substr($0,2); f=""}
  substr($0,1,1)~/[ +]/ {n++}'

The filtered output looks like this:
+++ b/someFile
5:    // TODO: implement this
+++ "b/another file with spaces and a new\nline"
123:TODO in block comment
126:// multiple TODOs in same file

The b/ comes from git diff where b stands for the 2nd tree (here HEAD). All linenumbers are from HEAD.
Using git diff -U0 -G TODO could drastically speed this up if you have a lot of changes but nearly no TODOs


text:
Q: capturing text from text editors i researched on the internet but i couldnt find . how sqlassistant like programs can capture text from another text editors (notepad++ , sql management studio etc.)
for example , if u press ctrl + mouse left click in notepad++ , sql assistant detect text and repaint it blue and open stored procedure clicked in its own window.
is it possible with Hook api's ? i downloaded many api's examples written in c# , but no example about capturing text , is it possible with managed code ?

A: Programs like that use regular Win32 API calls to inspect window contexts. They use global keyboard hooks to detect the keypresses, then use calls like GetActiveWindow to determine what kind of window/control is selected and how to interact with it.
Here's an example for setting a global hook in C#

A: You can use Win32 API function to get an object / object' content
some win32 api function like getwindow-getwindowex-findwindow-findwindowex and so on from user32.dll can be usefull
in www.daneshjooyar.com there is some video about using api function in c#


text:
Q: How to compare to string in PowerShell foreach loop to files How to compare the current month with file modified in current month using power shell script. My code is working file but it is reading all the csv file in the given directory. I just wanted to read current month file i.e. modified in October 2018.
Please help me out , I have total 6 files in my directory. 3 files having date modified in October 2018 and remaining 3 files are modified in September 2018.
I want my script to check the current month then read all csv of current month i.e. October 2018
Code:
$files = Get-ChildItem 'C:\Users\212515181\Desktop\Logsheet\*.csv'
$targetPath = 'C:\Users\212515181\Desktop\Logsheet'
$result = "$targetPath\Final.csv"
$curr_month = (Get-Date).Month
$curr_year = (Get-Date).Year

# Adding header to output file
[System.IO.File]::WriteAllLines($result,[System.IO.File]::ReadAllLines($files[1])[1])

foreach ($file in $files)
{
    $month = $file.LastWriteTime.ToString()
    $curr_month=(Get-Date).Month

    if ($month= $curr_month)
    {
        $firstLine = [System.IO.File]::ReadAllLines($file) | Select-Object -first 1
        [System.IO.File]::AppendAllText($result, ($firstLine | Out-String))
        $lines = [System.IO.File]::ReadAllLines($file)
        [System.IO.File]::AppendAllText($result, ($lines[2..$lines.Length] | Out-String))
    }
}

# Change output file name to reflect month and year in MMYYYY format

Rename-Item $result "Final_$curr_month$curr_year.csv"

A: Your comparison is wrong. And will return $true causing all files to be read
It should be
 if ($month -eq $curr_month)

Also I would remove the second
$curr_month = (get-date).month

it's adding overhead to your script as you set it before the loop


text:
Q: ArgumentMatchers.any must not be null I am trying to test ViewModel to make sure livedata gets updated correctly. However when using ArgumentMatchers.any() it fails with IllegalStateException saying:

ArgumentMatchers.any(mViewModel.CountSubscriber::class.java) must not
be null

@Test
fun emitValueIfCountIs7() {
    doAnswer { invocation: InvocationOnMock ->
        val subscriber: mViewModel.CountSubscriber = invocation.getArgument(0)
        subscriber.onNext(7)
        null
    }.`when`(countUseCase).execute(
        ArgumentMatchers.any(mViewModel.CountSubscriber::class.java),
        ArgumentMatchers.any(Parameters::class.java)
    )

    // When
    mViewModel.getCount()

    // Verify
    assert(mViewModel.countResponse.value != null)
}

I am using Kotlin and have the following dependencies:
testImplementation 'junit:junit:4.12'
testImplementation "org.mockito:mockito-inline:2.23.4"
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0"

Here are my imports:
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.nhaarman.mockitokotlin2.doAnswer
import io.reactivex.Observable
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.ArgumentMatchers.any
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
import org.mockito.invocation.InvocationOnMock

Strange thing is that it used to work before, and I don't know what has happened that could affect this.

A: mockito-kotlin has added support for nullable args with anyOrNull()
        `when`(myMock.doesThis(any(), anyOrNull())).thenReturn(someObject)

A: Getting matchers to work with Kotlin can be a problem.
If you have a method written in kotlin that does not take a nullable parameter, then we cannot match with it using Mockito.any().
This is because it can return void and this is not assignable to a non-nullable parameter.
If the method being matched is written in Java, then I think that it will work as all Java objects are implicitly nullable.
One possible solution would be to use a library like mockito-kotlin
But you can solve this issue easily with a few lines of code yourself.
If you need typed any(type: Class)
private fun <T> any(type: Class<T>): T = Mockito.any<T>(type)

OR
You can use this matcher  instead of Matchers.any() :
object MockitoHelper {
fun <T> anyObject(): T {
    Mockito.any<T>()
    return uninitialized()
}
@Suppress("UNCHECKED_CAST")
   fun <T> uninitialized(): T = null as T
}

and use MockitoHelper.anyObject() instead of any() in your kotlin tests.
You can find more information in this post: Using  Mockito with Kotlin
There is a discussion about possible solutions in this post :
Is it possible to use Mockito in Kotlin?

A: use Mockito-kotlin
testImplementation "org.mockito.kotlin:mockito-kotlin:$mockito_kotlin_version"

this will use any that works for kotlin as this is a wrapper lib for Mockito but for kotlin

A: The correct solution is mentioned in the comment section of the question by @Ana Koridze. Yes, if you are using Koltin + mockitoKotlin. Make sure you are using the following import:
1 - Using the Mockito-kotlin:
import org.mockito.kotlin.any from Mockito-kotlin
instead of
import org.mockito.Mockito.any
testImplementation "org.mockito.kotlin:mockito-kotlin:$mockito_kotlin_version"

2 - Or if you are using older mockito kotlin version original created by nhaarman before the intergation
import com.nhaarman.mockitokotlin2.any from nhaaram's Mockito-kotlin instead of import org.mockito.Mockito.any
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:$mockito_kotlin2_version"

BTW, if you are using Android Studio or IntelliJ IDEA. the any() from mockitokotlin library should be italic by default style/color scheme.

Notice the any() at the end of line. This is from mockitokotlin

And here is the any() from mockito

Thanks @Sattar for the recommended edit.

A: This is what worked for me,

*

*either replaced all generic any()s , with a specific anyTYPE(), i.e anyInt(), anyList() etc from core lib org.mockito:mockito-core and it fixes the (nullability)issue, it seems the specific definitions with type can handle null. this option does not require you to import any extra lib

or

*if you really need to use the generic type any() , add this official Mckito extension lib https://github.com/mockito/mockito-kotlin  and make sure you use the any() from this lib (by making sure your imports has this in it import org.mockito.kotlin.any)

I suggest to start using MockK lib  https://github.com/mockk/mockk instead of Mockito as it is a Mock library for Kotlin = MockK)
however, if you feel lazy to switch right now or maybe dealing with legacy tests (as in my case :), this should fix your issue too.

A: For me all solutions above were not enough - in addition to that I had to mark the called method as an 'open' method.
According to this:
https://github.com/mockito/mockito-kotlin/wiki/Parameter-specified-as-non-null-is-null
The method is final and Mockito couldn't mock it so I had to add 'open'.

A: I wrote a simple wrapper function around Mockito's any() and got rid of the warning.
private fun <T> any() : T {
    return org.mockito.ArgumentMatchers.any()
}

I am still pretty green at Kotlin though, so I am not sure whether there may be some unwanted side effects. I put this answer out there in case it helps anyone or someone gives me feedback.


text:
Q: In what espace lives $\delta(x-y)$?
A Dirac distribution or Dirac $\delta$-distribution $\delta(p)$ is the distribution that is given by evaluating a function at a point $p$.

That is, the Dirac $\delta(p)$ function is the distribution defined by $$\langle\delta(p),\phi \rangle=\phi(p)$$
Suppose we want to write
$$\int\phi(x)\phi(x)dx=\int\int_0^1\delta(
x-y)\phi(x)\phi(y)dxdy$$
How should we define $\delta(
x-y)$?
In this page Free quantum fields on example 14.4 they have
$\delta(
x-y) \in \Gamma'(E \boxtimes E)$ where  $\Gamma'(E \boxtimes E)$ is the dual of the space of section of the bundle  $\Gamma(E \boxtimes E)$  and
And $E$ is the real line bundle

A: Define $\delta(x-y)$ for $x,y\in\mathbb{R}^n$ as the distribution on $\mathbb{R}^n\times\mathbb{R}^n$ such that
$$
\langle \delta(x-y), \varphi(x, y) \rangle = \int \varphi(t, t) \, dt
$$
for every test function $\varphi.$


text:
Q: use jquery inside data returnd by ajax using " innerHtml" I want to use jquery inside data returned by ajax using " innerHtml" ..
look here ,
js_rebind .";return false;\">"
 $text .'';

this link makes moving between the pages by ajax "by reloading the div that contains the data" ,
without - of course -  reloading whole page .
like this :

rows from mysql database

now everything is Ok , but ,
I use " detailsRow Plugin "  like this :

this plugin makes every TR/Row in the table get more details by click (+-) .. go there :
http://webworkflow.co.uk/plugins/detailsRow/
now this plugin works fine in the first page ( before reload the div by jquery )
but after reloading the div and in the other pages or also when I go back to the first page
it doesn't work ..
I put the code inside content_rows div like this :

but also doesn't work ..

A: It sounds like you need to call the $.detailsRow() function to modify the newly added DOM elements you create in the callback from the Ajax request. Just add a line to the callback function for $.post() like so:
$.post('". $url ."', {'t' : 't'},
    function(data){
        $('content_rows').attr('innerHTML',data);
        $('#rows').detailsRow('admin/blog/detailsRow',
            {
                data:{"id":"id"} ,
                dataType: "script"
            }
         );
    }
);

Or you could separate the call to $.detailsRow() into a separate function and use it as the callback for $(document).ready() and call it from within the $.post() callback.


text:
Q: How to interpret mysql output in shell script? What I try:
player=tester111

id=$(mysql -h "127.0.0.1" -u "myuser" -ppassword "database" -e \
  "SELECT id FROM login WHERE name='$player';")

echo $id

The following output appears:
id 223

How to get ONLY 223 as output?
I am new to stackoverflow, feel free to comment so I can improve my asking skills.

A: Use the -N switch when executing your query. -N is for skipping column name and thus you will get only values returned (that is 223 returned) like
id=$(mysql -N -h "127.0.0.1" -u "myuser" -ppassword "database" -e \
  "SELECT id FROM login WHERE name='$player';")