text:
Q: How to hide a jpg file in a disk image starting at a particular offset? Disk image name: Alienimage.dd
Picture to be hidden in the disk image: picture1.jpg
The picture needs to be hidden starting at offset 1MB of the disk image. The rest of the disk image remains unmodified. What LINUX commands can i use?
Here is the fdisk of the image file:
root@kali:/media/sf_Kali_Shared/AlienImage# fdisk -l alienimage.dd

Disk alienimage.dd: 216.9 MiB, 227409920 bytes, 444160 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x6f20736b

Device         Boot      Start        End    Sectors   Size Id Type
alienimage.dd1       778135908 1919645538 1141509631 544.3G 72 unknown
alienimage.dd2       168689522 2104717761 1936028240 923.2G 65 Novell Netware 386
alienimage.dd3      1869881465 3805909656 1936028192 923.2G 79 unknown
alienimage.dd4               0 3637226495 3637226496   1.7T  d unknown

Partition table entries are not in disk order.

A: Given this picture and this disk image
$ cat catpic

 ^ ^
>'.'<
(U U)

$ wc -c catpic # need this later to extract image
18 catpic

$ cat diskimage
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea

We insert the image into the diskimage at offset 100 bytes
$ dd if=catpic of=diskimage bs=1 seek=100 conv=notrunc
18+0 records in
18+0 records out
18 bytes (18 B) copied, 8.5e-05 seconds, 212 kB/s

We prove the image is stored inside the diskimage, then we extract it
$ cat diskimage
Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore
 ^ ^
>'.'<
(U U)
iqua. Ut enim ad minim veniam, quis nostrud
exercitation ullamco laboris nisi ut aliquip ex ea

$ dd if=diskimage bs=1 skip=100 count=18 2>/dev/null

 ^ ^
>'.'<
(U U)

Notes
For bigger files you will want to increase bs substantially.


text:
Q: nginx only accessible from localhost I setup a simple nginx server and it works if I just type localhost into the browser. If I try to access it from my phone in the same network, by typing the IP address of my computer, I get a "webpage not available" message. This is my nginx.conf:
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.fedora.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    server {
        listen 80;
        location / {
            root /usr/share/nginx/html;
        }
    }
}

According to this post, I configured my firewall to allow http in the Home zone, and set the wireless network to be in that zone.
The first two entries in the INPUT chain of iptables are
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere             ctstate     RELATED,ESTABLISHED
ACCEPT     all  --  anywhere             anywhere

so I don't think that's the problem.
And yet, looking at the tcpdump capture of the request from my phone I see a reply host unreachable - admin prohibited:
21:13:38.514782 IP 192.168.1.3.54982 > sidney.http: Flags [S], seq 2569820651, win 14600, options [mss 1460,sackOK,TS val 3018406 ecr 0,nop,wscale 6], length 0
21:13:38.514934 IP sidney > 192.168.1.3: ICMP host sidney unreachable - admin prohibited, length 68

Output of firewall-cmd --list-all --zone=home:
home (active)
  target: default
  icmp-block-inversion: no
  interfaces: wlo1
  sources:
  services: dhcpv6-client http mdns samba-client ssh
  ports: 80/tcp
  protocols:
  masquerade: no
  forward-ports:
  sourceports:
  icmp-blocks:
  rich rules:

What could be the problem? I'm on Fedora 24.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make this form in a multistep form in vue.js Here I have written a code for forms with three different components. and that is displaying in a single page and I want to make this template to be appear step by step like multistep form. For example while we are at first template if we click to next button then it should got to second template like multistep form.
<!DOCTYPE html>

    <link rel="stylesheet" href="styles.css" />

        <friend-contact></friend-contact>
        <friend-contact-again></friend-contact-again>
        <friend-contact-once-again></friend-contact-once-again>

vue.js
const app = Vue.createApp({
  data() {
    return {

    };
  },
});

app.component('friend-contact', {
  template: `

    First name:

  <input type="text" id="fname" name="fname" value="first_form">

  Last name:

  <input type="text" id="lname" name="lname" value="first_form">

  <input type="submit" value="Submit">

  `,
  data() {
    return {
      fname:'',
      lname:''
    };
  },
});

app.component('friend-contact-again', {
  template: `

    First name:

  <input type="text" id="fname" name="fname" value="second_form">

  Last name:

  <input type="text" id="lname" name="lname" value="second_form">

  <input type="submit" value="Submit">

  `,
  data() {
    return {
        fname:'',
        fname:''

    };
  },
});

app.component('friend-contact-once-again', {
  template: `

    First name:

  <input type="text" id="fname" name="fname" value="third_form">

  Last name:

  <input type="text" id="lname" name="lname" value="third_form">

  <input type="submit" value="Submit">

  `,
  data() {
    return {
      fname:'',
      lname:''

    };
  },
});
app.mount('#app');

A: Since all three of you friend contact forms are basically the same, I created a Vue 2 CLI application that reuses the same form component three times.
I included the HTML table in the template just to view the list of contacts once three have been created.
Obviously up to you what you do with the contacts once they are created (post to a database, etc).
Home.vue
<template>

Home

        <button class="btn btn-primary" v-if="!displayForm && !displayTable" @click="showForm">Add Friends</button>

    <friend-contact-form v-if="displayForm" @save-contacts="saveContacts" />

          FIRST NAME
          LAST NAME

          {{ contact.firstName }}
          {{ contact.lastName }}

    <button class="btn btn-primary" v-if="displayReset" @click="reset">Reset</button>

</template>

FriendContactForm.vue
<template>

Friend {{ currentContactNumber[numContacts] }}

        <form @submit.prevent="saveContact">

            First Name
            <input type="text" class="form-control" v-model="contact.firstName">

            Last Name
            <input type="text" class="form-control" v-model="contact.lastName">

          <button class="btn btn-primary">{{ formBtnLabel }}</button>
        </form>

</template>


text:
Q: Executing tags as per desired order and enabling BeforeAll and AfterAll in scala I am using Bdd Cucumber with Scala. My Runner class code  is as follows;
@RunWith(classOf[Cucumber])
@CucumberOptions(
  monochrome = false,
  plugin = Array("pretty", "html:target/html/tests", "json:target/json/tests.json"),
  features = Array("path to features"),
  glue = Array("step definition pacckage"),
  tags= {"not (@wip or @repetitive)"})
class AutomationTestRunner {
}

I have three fearture files and I have assigned them tags. But when I do sbt test, cucumber executes test cases in alphabetic order of tags. But in my case I want to decide on the basis of tag which feature will first which will run third and so on. How can I do that?

*In one of my step definition, Before starting of test cases I want to query database and drop all tables. As I am using scala, in my build.sbt I have specified cucumber dependencies as follows

"io.cucumber" % "cucumber-scala_2.12" % "6.2.1",
"io.cucumber" % "cucumber-junit" % "6.2.1",
  // This dependency required for Cucumber Junit implementation to be recognized.
  "com.novocode" % "junit-interface" % "0.11" % "test",

For cleaning up database, before execution of any test, I may need to use BeforeAll or BeforeClass, as far as I understan from official docs. But I am only getting option of Before and After. I am not getting any option of BeforeAll and AfterAll. How I can enable these in my code.

A: I'll answer your second question. In order to override the BeforeAll/AfterAll methods, you need to mixin the trait BeforeAndAfterAll. It is located at scalatest, so make sure you have this dependency defined in your build.sbt file.


text:
Q: Getting joined entity and count not working I 'm trying to execute this query but I get an error:
select c, count(i) as total
from \Invoice i
join i.client c
GROUP BY i.client

Error: Cannot select entity through identification variables without choosing at least one root entity alias.
What is wrong? I want to get all the client entity fields

A: You may try this:
select c.*, count(c.id) as total
from \Invoice i
join i.client c
GROUP BY c.id

I do not really know if this works but in Doctrine1's DQL implementation this would be the right way to go.


text:
Q: Remove double quotes from athena query results I have a athena table with an int column format as
CREATE EXTERNAL TABLE `events`(
  `build` string,
  `event_ts` bigint
ROW FORMAT SERDE
  'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
STORED AS INPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat'
LOCATION
  'xyz'
TBLPROPERTIES (
  'CrawlerSchemaDeserializerVersion'='1.0',
  'CrawlerSchemaSerializerVersion'='1.0',
  'UPDATED_BY_CRAWLER'='events',
  'averageRecordSize'='166',
  'classification'='parquet',
  'compressionType'='none',
  'objectCount'='9569916',
  'recordCount'='892536278576',
  'sizeKey'='141488304366761',
  'typeOfData'='file')

When i query that table it always returns results wrapped in double quotes for each column build or event_ts. There are no quotes in the original data.
Output from select * in java and when downloaded from athena is
"build1", "1234314"
"build2", "1231231"

Can someone advise how to remove these double quotes in query results  without changing these table formats or replacing the quotes in the application ?


text:
Q: Value doesn't change when I call a flutter class I have this home_page class where I have a scafold and the body will change if the  selectedSubject !=null
by calling the other class which is the SubjectPage(selectedSubject) selectedSubject as a parameter,
at first when the condition is true the UI and the selectedSubject variable inside of the SubjectPage class change, but when I change the selectedSubject at home_page using the setState the SubjectPage will be called again, but the value inside SubjectPage will remain.
this is the code
//Where selectedSubject change
    onTap: (){
        setState(() {
           selectedSubject = new SubjectModel(document['uid'],document['name'],document['description'],document['instructorName'],document['subjectColor']);
           });
           Navigator.of(context).pop();
       },

This is where I change the body of the scaffold
body: selectedSubject == null ?
                Container(
                    height: 200,
                    margin: EdgeInsets.all(5),
                    alignment: Alignment.topLeft,
                    child: Column(
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text("Subject for Today",style:TextStyle(fontWeight: FontWeight.bold,fontSize: 30) ,),
                            Text(DateTime.now().toString(),style:TextStyle(fontWeight: FontWeight.w200,fontSize: 15) ,),
                            FlatButton(onPressed: (){}, child: Text("Go to subject"),
                              color: Color(0xfff9683a),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.only(topRight: Radius.circular(20)),
                              ),),
                            // ListView(
                            //   children: [
                            //     //list task
                            //   ],
                            // )
                          ],
                        ),
                      ],
                    ))
                    : SubjectPage(selectedSubject)

This is the SubjectPage Class
class SubjectPage extends StatefulWidget {
  final SubjectModel selectedSubject;
  SubjectPage(this.selectedSubject);
  @override
  SubjectPageState createState() => SubjectPageState(selectedSubject);

}

class SubjectPageState extends State<SubjectPage>{
  final SubjectModel selectedSubject;
  SubjectPageState(this.selectedSubject);
  TimeOfDay currentTime = TimeOfDay.now();
  Color color;

  @override
  Widget build(BuildContext context) {
    print(selectedSubject.name);
    color = Color(int.parse("0x"+selectedSubject.subjectColor.toString().replaceAll('#', "")));
    return Container(
      margin: EdgeInsets.all(5),
      alignment: Alignment.topLeft,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(selectedSubject.name.toString().titleCase,
            style: TextStyle(fontWeight: FontWeight.bold,
                fontSize: 50),),
          Text(selectedSubject.instructorName,
            style: TextStyle(fontSize: 15,
                fontWeight: FontWeight.w200),),
          Text(selectedSubject.description),

          Container(
            margin: EdgeInsets.only(top: 10),
            width: double.infinity,
            height: 30,
            child: ListView(
              scrollDirection: Axis.horizontal,
              children: [
                Container(
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      border: Border.all(
                        color: color,
                      ),
                      borderRadius: BorderRadius.all(Radius.circular(50))
                  ),
                  height: 5,
                  width: 200,
                  child: Text("Tues 3:10pm - 4:10pm"),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

please help :( newbie

A: You can use key property of SubjectPage to rebuild it every time the key will change. Try this code:
body: selectedSubject == null
            ? Container(...)
            : SubjectPage(
                // Here I assumed that uid is a String. If not, use string literals
                key: Key(selectedSubject.uid),
                selectedSubject: selectedSubject,
              )
...

class SubjectPage extends StatefulWidget {
  final SubjectModel selectedSubject;

  SubjectPage({Key key, @required this.selectedSubject}): super(key: key);

  @override
  SubjectPageState createState() => SubjectPageState(selectedSubject);
}


text:
Q: error in creating alertbox in android hi i am a new developer in android, i am being a trainer and i am trying to create an alert box.
In my project i have placed 2 edit text boxes and if any of them is being empty i want to pop up an alert box if both the boxes are filled up it will moves over to a new page.
the following is my coding
{ b = (Button)findViewById(R.id.widget30);

    et1 = (EditText)findViewById(R.id.et1);
    et2 = (EditText)findViewById(R.id.et2);

    b.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            if(et1.getText().toString().length() == 0 )
            {
                et.setVisibility(View.VISIBLE);
                alertbox();
            }
            else if (et2.getText().toString().length() == 0)
            {
                et.setVisibility(View.VISIBLE);
                alertbox();
            }
            else
            {
            main.this.finish();
            Intent myIntent = new Intent(v.getContext(), T.class);
             startActivityForResult(myIntent, 0);
            }
        }
    });
}

public void alertbox()
{
    et = new TextView(this);
    Builder alert =new AlertDialog.Builder(main.this);
    alert.setTitle("Alert");
    alert.setMessage("Required all fields");
    alert.setView(et);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
    {
         public void onClick(DialogInterface dialog, int whichButton)
         {
            dialog.cancel();
         }
    });
    AlertDialog alert1 = alert.create();
    alert1.show();
}
}

It is moving over to a new page but the alert box is not opening, following is the error in logcat
java.lang.NullPointerException in the following lines of my coding
{

if(et1.getText().toString().length() == 0 )
                {
                    et.setVisibility(View.VISIBLE);
                    alertbox();
                }
                else if (et2.getText().toString().length() == 0)
                {
                    et.setVisibility(View.VISIBLE);
                    alertbox();
                }
}
}

pls help me to identify what mistake i have did

A: probably on this line
 et.setVisibility(View.VISIBLE);

et is a null object as it not exists. It seams you create only after you call alertbox()

A: You should consider looking at the documentation: http://developer.android.com/guide/topics/ui/dialogs.html
The Android SDK takes care of dialogs for you via the showDialog() and dismissDialog() methods. You would add need to add an onCreateDialog method and add your creation code here.
Android also reuses a dialog once it's been created, whereas in your code you would create a new one each time.
This is the very basics of what you can do and there are many more options.

A: b.setOnClickListener(new OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        if(et1.getText().toString().length() == 0 )
        {

            alertbox();
        }
        else if (et2.getText().toString().length() == 0)
        {

            alertbox();
        }
        else
        {
         Intent myIntent = new Intent(main.this, T.class);
         startActivity(myIntent);
        }
    }
});`


text:
Q: Node js pdf-make lib dose support large data? i am using this lib the small data process but large data not process it goes to server crash
try catch method also be user but it not catch error
node make report.json file
it lib issue any else

A: Memory limit? Try launch nodejs with --max-old-space-size=4096 key. It set memory limit to 4GB from default ~1.4GB.


text:
Q: вызов команд PowerShell для ExchangeServer 2010 из приложения C# Приложение должно выполнить команды по созданию mailbox например. Запускаться в локальной сетке, но не с машины где стоит сам Exchange.
Есть у кого примерчик?


text:
Q: Appium - Command line Team,
Can you please guide me or point me some tutorials to run Appium through command line? I see lot of issues with Appium.app on MAC. It would be great, if you can share your knowledge or materials for me to move forward to run a sample application with appium through command line. Please refer my settings in appium.app for your reference.
Appium - Not able to launch the inspector
Logs:
info: [debug] Responding to client with success: {"status":0,"value":{"build":{"version":"1.2.2","revision":"cf6ff5939ddc6b4d45fcbabfbfe13c950e0058c4"}}}
info: <-- GET /wd/hub/status 200 1.335 ms - 104 {"status":0,"value":{"build":{"version":"1.2.2","revision":"cf6ff5939ddc6b4d45fcbabfbfe13c950e0058c4"}}}
info: --> GET /wd/hub/sessions {}
info: [debug] Responding to client with success: {"status":0,"value":[]}
info: <-- GET /wd/hub/sessions 200 2.145 ms - 23 {"status":0,"value":[]}
info: --> POST /wd/hub/session {"desiredCapabilities":{"platformName":"iOS","platformVersion":"7.1","newCommandTimeout":"999999","automationName":"Appium","deviceName":"iPhone Simulator"}}
info: [debug] Using local app from command line: /Users/rsangili/Desktop/temp/Payload/TestApp2.app
info: [debug] Creating new appium session dd2c8121-6a13-48be-8a0b-9fc6233437a5
info: [debug] Removing any remaining instruments sockets
info: [debug] Cleaned up instruments socket /tmp/instruments_sock
info: [debug] Setting Xcode folder
info: [debug] Setting Xcode version
info: [debug] Setting iOS SDK Version
info: [debug] iOS SDK Version set to 7.1
info: [debug] Detecting automation tracetemplate
info: [debug] Not auto-detecting udid, running on sim
error: Could not parse plist file (as binary) at /Users/rsangili/Desktop/temp/Payload/TestApp2.app/en.lproj/Localizable.strings
info: Will try to parse the plist file as XML
error: Could not parse plist file (as XML) at /Users/rsangili/Desktop/temp/Payload/TestApp2.app/en.lproj/Localizable.strings
warn: Could not parse app Localizable.strings
info: [debug] Not setting locale
info: [debug] Creating instruments
info: [debug] Preparing uiauto bootstrap
info: [debug] Dynamic bootstrap dir:
info: [debug] Dynamic env:
info: [debug] Dynamic bootstrap code:
info: [debug] Dynamic bootstrap path:
info: [debug] Reusing dynamic bootstrap:
info: [debug] Fixing device was changed from:"
info: [debug] No iOS / app preferences to set
info: [debug] Starting iOS 7.* simulator log capture
info: [debug] Killing the simulator process
info: [debug] Killing any other simulator daemons
info: [debug] Checking whether instruments supports our device string
info: [debug] Getting list of devices instruments supports
info: [debug] Instruments is at: /Applications/Xcode.app/Contents/Developer/usr/bin/instruments
info: [debug] Fixing device was changed from:"
info: [debug] Cleaning up appium session
error: Failed to start an Appium session, err was: Error: Command failed:
info: [debug] Error: Command failed:
    at ChildProcess.exithandler (child_process.js:648:15)
    at ChildProcess.emit (events.js:98:17)
    at maybeClose (child_process.js:756:16)
    at Process.ChildProcess._handle.onexit (child_process.js:823:5)
info: [debug] Responding to client with error: {"status":33,"value":{"message":"A new session could not be created. (Original error: Command failed: )","killed":true,"code":null,"signal":"SIGTERM","origValue":"Command failed: "},"sessionId":null}
info: <-- POST /wd/hub/session 500 6381.780 ms - 199

Thanks,
Ramesh

A: Using Appium from Command Line
Installation

*

*Open a terminal session

*Install homebrew (instructions)

*Run the below commands

 $ brew install node # install node and npm
 $ npm install -g appium # globally install appium
 $ npm install wd
 $ appium # Launch your appium server!

Usage
Whenever you want to begin an appium server session, type appium to run the server.
Arguments can be added to that command.
appium --app path/to/app --device-name "iPhone Simulator"
Using Appium.app inspector with server
In my development env setup, I don't use the Appium.app server, but I DO use the inspector.

*

*Start your Appium server with the --app and --device-name arguments

*Click on the Appium.app inspector icon

*The iPhone Simulator will launch, and may give you an authorization prompt for Instruments to control it

A: Setting up Appium
Mac:

Download and install Latest Java from http://www.oracle.com/technetwork/java/javase/downloads/index.html
Download and install latest Android SDK from http://developer.android.com/sdk/index.html
Configure path to ANDROID_HOME and JAVA_HOME in .bash profile
Configure path to Platform-tools and tools folder in .bash profile
Install ruby
Install brew
    ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)"

Set path for brew from .bash profile
  export PATH="$HOME/.linuxbrew/bin:$PATH"
  export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
  export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

Install node:Paste the below commands one by one  at terminal and hit enter
  brew update
  brew install node
  brew link node

Install appium
  npm install -g appium

  npm install wd

To start appium: Paste the below command at terminal and hit enter
  appium

Install Appium python client:
Download source from
https://github.com/appium/python-client
Extract it, Navigate to the folder containing the Python client from terminal and install by:
cd python-client
python setup.py install

IDE used: Pycharm
Linux:

Download and install Latest Java from http://www.oracle.com/technetwork/java/javase/downloads/index.html
Download and install latest Android SDK from http://developer.android.com/sdk/index.html
    Configure path to ANDROID_HOME and JAVA_HOME in .bashrc profile
Configure path to Platform-tools and tools folder in .bashrc profile
command gedit.bashrc to open bash profile and specify path
Install ruby
Install linux brew
      ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)"
Steps to get appium working on ubuntu pc :
Install ruby: Paste the below command at terminal and hit enter
  sudo apt-get install build-essential curl git m4 ruby texinfo libbz2-dev libcurl4-openssl-dev libexpat-dev libncurses-dev zlib1g-dev

Install linux brew:Paste the below command at terminal and hit enter
      ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)"
set path for brew
Type: gedit.bashrc at terminal and copy paste following into the .bashrc file
  export PATH="$HOME/.linuxbrew/bin:$PATH"
  export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
  export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

Install node:Paste the below commands one by one  at terminal and hit enter
  brew update
  brew install node
  brew link node

Install appium
  npm install -g appium

  npm install wd

To start appium: Paste the below command at terminal and hit enter
  appium

Install Appium python client:
Download source from
https://github.com/appium/python-client
Extract it, Navigate to the folder containing the Python client from terminal and install by:
      cd python-client
 python setup.py install

IDE used: Spyder/Pycharm
You can get spyder by running command
        Sudo apt-get install Spyder
    Windows:
Download and install python 2.7.9 from https://www.python.org/downloads/
Download and install Latest Java from http://www.oracle.com/technetwork/java/javase/downloads/index.html
Download Android SDK from http://developer.android.com/sdk/index.html
Set Environment variables to JAVA_HOME for Java , Python.exe  for python and ANDROID_HOME to Android sdk, and Android Tools and platform tools.
IDE used: Pycharm
Download and install pycharm IDE from https://www.jetbrains.com/pycharm/
Install Appium python client:
Download source from
https://github.com/appium/python-client
Extract it, Navigate to the folder containing the Python client from terminal and install by:
cd python-client
python setup.py install
Start node server by using Appium gui from windows PC


text:
Q: Отступы между блоками в bootstrap Всем привет. Как сделать между блоками отступ?
Вот что у меня есть

Нужно чтобы было так

мой код:

            <?= Html::img(Url::to('/uploads/politics/9859aeecafa753b42b613e63d4872b54_presydent_ua.jpg'), ['alt' => '9859aeecafa753b42b613e63d4872b54_presydent_ua.jpg']) ?>

Петро Порошенко

Президент

            <?= Html::img(Url::to('/uploads/politics/a521671ed3207abf6735d35b1b9a9b0a_800px-Yulia_Tymoshenko_2018_Vadim_Chuprina.jpg'), ['alt' => '9859aeecafa753b42b613e63d4872b54_presydent_ua.jpg']) ?>

Петро Порошенко

Президент

            <?= Html::img(Url::to('/uploads/politics/9859aeecafa753b42b613e63d4872b54_presydent_ua.jpg'), ['alt' => '9859aeecafa753b42b613e63d4872b54_presydent_ua.jpg']) ?>

Петро Порошенко

Президент

            <?= Html::img(Url::to('/uploads/politics/a521671ed3207abf6735d35b1b9a9b0a_800px-Yulia_Tymoshenko_2018_Vadim_Chuprina.jpg'), ['alt' => '9859aeecafa753b42b613e63d4872b54_presydent_ua.jpg']) ?>

Петро Порошенко

Президент

A: Задать внешние отступы блокам .col-lg-3 не получится (вернее, получится, но тогда это сломает сетку), поэтому внутри них лучше сформировать отдельные блоки .blocks-politic и уже работать с ними:

.blocks-politic {
  box-shadow: 1px 2px 5px gray;
  margin: 15px;
  padding: 15px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

Володимир Зеленський

Президент

Володимир Зеленський

Президент

Володимир Зеленський

Президент

Володимир Зеленський

Президент


text:
Q: Working with STM32 flash memories.. on renode I am a newbie on embedded flash memories and in particular my university assigned me a job with them on a stm32f407 MCU.
I have to work with renode (don't ask me why, they want so) and it has 0 support for flash memories. I am ready to write a peripheral for the renode simulator and to do a pull request if it goes well but first of all I need to understand well how embedded flash memories work.
In particular I need to write a sort of log in the flash memory, a kind of <timestamp, event> of fixed bytes length everytime an interrupt occurs.
If I understood the problem well, I first need to erase a sector (and I want to use only the sector #11 that has enough size for me).

After the erasing, the sector is all 1s so I can program the flash memory on successive addresses without problems right? I know that I can only write a 0 and it can't be converted again to a 1 without erasing the sector, but I need to write only one time at each memory address so a single erase operation at beginning would be fine right?
Thank you!


text:
Q: using ANT_OPTS to affect target java app I have a 2gig linux 64bit OS.  I am using ant 1.7.1 and jdk 1.6_31.  I have a simple app that prints that asks for the size of the Maximum java heap and prints it.  I am using export ANT_OPTS="-Xmx64M" but when I run my little application with ant target in build.xml, it reports 446Meg.
<target name="askmem">
    <java
        fork="true"
        classname="com.stagirite.test.AskMemory"
        classpathref="project.classpath">

        <classpath path="${build.dir}"/>
    </java>
</target>

I must be doing something wrong?  (I discovered from stackoverflow that with this JVM, the default heap is 1/4 total memory, which is what is happening, rather than the value I specified in ANT_OPTS.
Andy

A: You're forking the Java anyway, so even if ANT_OPTS did affect the java task, I don't think they'd transfer to it. ANT_OPTS is for ant itself.
If you want to control the JVM used by the forked java task, use nested <jvmargs> elements.


text:
Q: Capybara: How to check that an element has content among many similar elements? I need to check that some content exists on the page within a specific type of selector. For example, let's say I have the following HTML:

HEADLINE ONE

HEADLINE TWO

I know how to select only the first one on the page:
find('h2').should have_content('Headline Two')  # have_content is also case insensitive

How would I check that the content exists among all of the h2s on the page?

A: Apparently you can select elements with a given text:
page.should have_selector('h2', text: /#{headline}/i)

Note: I used a regular expression to make the text search case insensitive.


text:
Q: Is it a bad practice to explicitly declare a default field value? Duplicate question to :

Should I always/ever/never initialize object fields to default values?

Environment: Visual Studio 2008 w/ Resharper 4.1 w/ 32bit .NET Framework 3.5
Resharper reports that

Initializing field by default value is redundant

Is it a bad practice to declare a default field value, explicitly?
I find explicitly declaring default value to be more readable.
By the way this is not a duplication of this question
Are default parameters bad practice in OOP?
[UPDATE] For those wondering on where to change Resharper 4.1 setting to change the warning to hint/suggestion; Changing following setting

will change  Visual Studio 2008

A: If you find it more readable that way, that's fine. I don't think it'll affect the JITted code - and even if it does, the performance hit will be absolutely tiny.
If ReSharper is annoying you when it comes to this warning, just configure it not to treat it as a problem. I don't have ReSharper on this machine, but I think it's fairly easy to find the relevant options - let me know if you can't and I'll look for it when I'm on the right machine.

A: Initializing the fields might imply a performance penalty:

*

*http://www.codeproject.com/KB/dotnet/DontInitializeVariables.aspx

*http://blog.codinghorror.com/for-best-results-dont-initialize-variables/

A: It is redundant, but I would stay consistent. If you are always initializing fields, keep it that way regardless of the type.  Also, as you pointed out in a comment, being required to think about default values for certain types is distracting, so another reason to initialize first.

A: The general answer is like others have stated, if it makes more sense to you and your team then reset the Reshaper setting to a hint. The C# will initialize all values to their default value (0 for numbers, null for reference types) which is equivalent to the .NET 2.0 default operator:
int i = default(int);

EDIT: You wouldn't use the above in your code. It is equivalent to 'i = 0', however it is much less readable. I only used it to illustrate the point about the unnassigned variables are initialized with their default value.

A: I would say it's bad practice not to explicitly define the field. An uninitialized field should not be assumed to be the default value, it should be assumed as "null". In this case, you want it to explicitly be 0, and you should therefore declare it to be 0.
Resharper is a very strict coding style, and you shouldn't blindly listen to it, especially if it damages the readability of your code.
Furthermore, if someone were to need to port this to a different language (where perhaps the default value is undefined, rather than "0") then it would cause uninitialized variable compiler errors or, even worse, run-time errors.

A: If it like Java at all (on a cell phone... Hard to look up) then explicitly initializing it means you cannot mark the field as final (might be const in C#) which makes it harder to properly make an immutible class.

A: I guess it's a matter of taste, but as I've said elsewhere, I don't like redundancy.
Leaving off initializer for a field could either mean that the coder knew it would be initialized to default values, or that he knew it would not be initialized and didn't care, or else he didn't think about it and his code just happens to work. The latter two would be, shall we say, "educational opportunitites".
On the other hand, initializing a field to its default value says to me that the coder doesn't understand the platform, or doesn't trust it.
What about cases where the default value is never used? Cases where the field is initialized from all constructors, or where the field is always set before being read? In those cases, setting to the default value is not an indication of intent - only an indication of following a rule that makes no sense.


text:
Q: what happens when string is implicitly converted to int in HIVE? When I use hive query data encountered the following such a situation:
select '6455983054544699410' = 6455983054544699395 ===> true

So I want to know what happens when string is implicitly converted to int in hive?
thanks.

A: Both sides are being cast to double
hive> select '6455983054544699410' =  6455983054544699395;
WARNING: Comparing a bigint and a string may result in a loss of precision.
OK
_c0
true

hive> select cast('6455983054544699410' as double) , cast (6455983054544699395 as double);
OK
_c0 _c1
6.4559830545446994E18   6.4559830545446994E18

https://github.com/apache/hive/blob/master/ql/src/java/org/apache/hadoop/hive/ql/plan/ExprNodeGenericFuncDesc.java
// For now, if a bigint is going to be cast to a double throw an error or warning
      if ((oiTypeInfo0.equals(TypeInfoFactory.stringTypeInfo) && oiTypeInfo1.equals(TypeInfoFactory.longTypeInfo)) ||
          (oiTypeInfo0.equals(TypeInfoFactory.longTypeInfo) && oiTypeInfo1.equals(TypeInfoFactory.stringTypeInfo))) {
        String error = StrictChecks.checkTypeSafety(conf);
        if (error != null) throw new UDFArgumentException(error);
        console.printError("WARNING: Comparing a bigint and a string may result in a loss of precision.");
      } else if ((oiTypeInfo0.equals(TypeInfoFactory.doubleTypeInfo) && oiTypeInfo1.equals(TypeInfoFactory.longTypeInfo)) ||
          (oiTypeInfo0.equals(TypeInfoFactory.longTypeInfo) && oiTypeInfo1.equals(TypeInfoFactory.doubleTypeInfo))) {
        String error = StrictChecks.checkTypeSafety(conf);
        if (error != null) throw new UDFArgumentException(error);
        console.printError("WARNING: Comparing a bigint and a double may result in a loss of precision.");
      }


text:
Q: How to Manually create a windows service for Apache 2.2 I accidentally removed my Apache windows service trying to install another Apache web server. Does anyone know how I can create another Apache windows service from cmd? I tried "sc create ..." but I am missing a script on the end like -k start? Not sure what I need for the end of it...
I am running Apache 2.2
Thank you

A: You can put the arguments for the service on the "binPath" argument on your "sc" command, escaping any quotes with slashes. For example, if you wanted to run: "C:\Program Files\foo\bar.exe" -service
sc create service_name binpath= "\"C:\Program Files\foo\bar.exe\" -service"

Look at the resulting service entry in HKLM\System\CurrentControlSet\Services\service_name and see if the ImagePath value looks like you want it to.

A: The Apache2.2 service can be re-created with the bin\httpd.exe -k install command. Then started with the bin\httpd.exe -k start command.


text:
Q: VBA Unix to DOS text conversion code error I am currently working on a code that creates a text file to dump data from a Unix data file into a temp text file which I can access in vba for post processing of data. My macro works only when this file is in a DOS format so I am trying to convert the Line feeds from Unix to DOS. Right now I am getting an error when I try to write out the revised text to the temp file. My code is listed below
    Filepath = Application.GetOpenFilename(".f06 files (*.f06),*.f06")
    Dim tempFilepath As String
    tempFilepath = Replace(Filepath, ".f06", "_temp.txt")

    Dim realfile As Integer
    realfile = FreeFile
    Dim tempfile As Integer
    tempfile = FreeFile
    Dim FileContent As String

    Open tempFilepath For Output As tempfile
    Close #1
    Open Filepath For Input As realfile

    Do While Not EOF(realfile)
         Line Input #realfile, FileContent
         FileContent = Replace(FileContent, Chr(10), vbCrLf)
         Print #tempfile, FileContent
    Loop

I am getting the error on the line:
Print
    #tempfile, FileContent

with a Run-time Error 54, Bad file mode.
Just wondering if anybody can see a glaring error to help me fix my code! I've been scouring the internet for the last two days trying to get this task done in different ways but haven't been able to manage it yet.
Thanks!

A: Freefile returns the same handle number until you actually open a file using that handle. Tested the code above and Realfile and Tempfile both turn out to be 1. This confuses the hell out of file handling APIs.
Ideal way to do this is to open the file immediately after calling FreeFile and then call it again when you need to open another file. Final code:
Filepath = Application.GetOpenFilename(".f06 files (*.f06),*.f06")
Dim tempFilepath As String
tempFilepath = Replace(Filepath, ".f06", "_temp.txt")

Dim realfile As Integer
realfile = FreeFile()
Open Filepath For Input As realfile

Dim tempfile As Integer
tempfile = FreeFile()
Open tempFilepath For Output As tempfile

Dim FileContent As String

Do While Not EOF(realfile)
     Line Input #realfile, FileContent
     FileContent = Replace(FileContent, Chr(10), vbCrLf)
     Print #tempfile, FileContent
Loop

Close tempfile
Close realfile


text:
Q: Python netCDF4 install error I'm trying to install netCDF4 package for python 2.7 on Ubuntu 14.04 with
sudo pip install --user netCDF4

The installation crashes with the following error:
error: unknown file type '.pyx' (from 'netCDF4/_netCDF4.pyx')

The only hint I found from other threads was that this has something to do with pyrex/Cython. Any idea what I can do to fix this?
Here's the entire output from the installation:
haaviston@tuomi13kl:~/.local/lib/python2.7/site-packages/pkg_resources$ pip install --user netCDF4
Downloading/unpacking netCDF4
  Downloading netCDF4-1.3.0.tar.gz (542kB): 542kB downloaded
  Running setup.py (path:/tmp/pip_build_haaviston/netCDF4/setup.py) egg_info for package netCDF4
    Package hdf5 was not found in the pkg-config search path.
    Perhaps you should add the directory containing `hdf5.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'hdf5' found
    using nc-config ...

        HDF5_DIR environment variable not set, checking some standard locations ..
    checking /home/haaviston ...
    checking /usr/local ...
    checking /sw ...
    checking /opt ...
    checking /opt/local ...
    checking /usr ...
    HDF5 library version: 1.8.11 found in /usr
    using netcdf library version 4.1.3
    using Cython to compile netCDF4.pyx...
    netcdf lib does not have group rename capability
    netcdf lib has nc_inq_path function
    netcdf lib does not have nc_inq_format_extended function
    netcdf lib does not have nc_open_mem function
    netcdf lib does not have cdf-5 format capability

Requirement already satisfied (use --upgrade to upgrade): numpy>=1.7 in /usr/lib/python2.7/dist-packages (from netCDF4)
Installing collected packages: netCDF4
  Running setup.py install for netCDF4
    Package hdf5 was not found in the pkg-config search path.
    Perhaps you should add the directory containing `hdf5.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'hdf5' found
    using nc-config ...

        HDF5_DIR environment variable not set, checking some standard locations ..
    checking /home/haaviston ...
    checking /usr/local ...
    checking /sw ...
    checking /opt ...
    checking /opt/local ...
    checking /usr ...
    HDF5 library version: 1.8.11 found in /usr
    using netcdf library version 4.1.3
    using Cython to compile netCDF4.pyx...
    netcdf lib does not have group rename capability
    netcdf lib has nc_inq_path function
    netcdf lib does not have nc_inq_format_extended function
    netcdf lib does not have nc_open_mem function
    netcdf lib does not have cdf-5 format capability
    building 'netCDF4._netCDF4' extension
    error: unknown file type '.pyx' (from 'netCDF4/_netCDF4.pyx')
    Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_haaviston/netCDF4/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-5Mjz_n-record/install-record.txt --single-version-externally-managed --compile --user:
    Package hdf5 was not found in the pkg-config search path.

Perhaps you should add the directory containing `hdf5.pc'

to the PKG_CONFIG_PATH environment variable

No package 'hdf5' found

reading from setup.cfg...

using nc-config ...

    HDF5_DIR environment variable not set, checking some standard locations ..

checking /home/haaviston ...

checking /usr/local ...

checking /sw ...

checking /opt ...

checking /opt/local ...

checking /usr ...

HDF5 library version: 1.8.11 found in /usr

using netcdf library version 4.1.3

using Cython to compile netCDF4.pyx...

netcdf lib does not have group rename capability

netcdf lib has nc_inq_path function

netcdf lib does not have nc_inq_format_extended function

netcdf lib does not have nc_open_mem function

netcdf lib does not have cdf-5 format capability

running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-2.7

creating build/lib.linux-x86_64-2.7/netcdftime

copying netcdftime/__init__.py -> build/lib.linux-x86_64-2.7/netcdftime

creating build/lib.linux-x86_64-2.7/netCDF4

copying netCDF4/__init__.py -> build/lib.linux-x86_64-2.7/netCDF4

copying netCDF4/utils.py -> build/lib.linux-x86_64-2.7/netCDF4

running build_ext

building 'netCDF4._netCDF4' extension

error: unknown file type '.pyx' (from 'netCDF4/_netCDF4.pyx')

----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_haaviston/netCDF4/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-5Mjz_n-record/install-record.txt --single-version-externally-managed --compile --user failed with error code 1 in /tmp/pip_build_haaviston/netCDF4
Storing debug log for failure in /home/haaviston/.pip/pip.log


text:
Q: How to properly search in a list in ReactJS I am trying to set a simple search operation in a user interface as shown below:

I have a total of 70 react-strap cards and each card contain a vessel with name, type and an image. I would like to search the name of the vessel and have the card related to that vessel to pop-up. All my images are currently contained inside the external database Contentful. Below the fields of interests:
The problem is that I don't know how to write a search function that locate a specific value of a list.

Below the code:
SideBar.js
import React from 'react';
import Client from '../Contentful';
import SearchVessel from '../components/SearchVessel';

class Sidebar extends React.Component {
    state = {
        ships: [],
    };

    async componentDidMount() {
        let response = await Client.getEntries({
            content_type: 'cards'
        });
        const ships = response.items.map((item) => {
            const {
                name,
                slug,
                type
            } = item.fields;
            return {
                name,
                slug,
                type
            };
        });

        this.setState({
            ships
        });
    }

    getFilteredShips = () => {
        if (!this.props.activeShip) {
            return this.state.ships;
        }
        let targetShip = this.state.ships.filter(
            (ship) => this.props.activeShip.name === ship.name
        );
        let otherShipsArray = this.state.ships.filter((ship) => this.props.activeShip.name !== ship.name);
        return targetShip.concat(otherShipsArray);
    };

    render() {
        return (

                {this.props.activeShipTypes}

                <SearchVessel />

                    {this.getFilteredShips().map((ship) => {
                        console.log(ship);
                        return (
                            <Card className="mb-2">
                                <CardImg />
                                <CardBody>

                                    <CardTitle>

{ship.name}

                                    </CardTitle>
                                    <CardSubtitle>{ship.type}</CardSubtitle>
                                    <CardText>

Project Details

For a description of the project view the specification included

                                    </CardText>
                                    <Row style={{ marginTop: '20px' }}>

                                                    Project Notes

                                                    Abstract

                                    </Row>
                                </CardBody>
                            </Card>
                        );
                    })}

        );
    }
}

export default Sidebar;

VesselSearch.js
import React, { Component } from 'react';

export default class SearchVessel extends Component {
    render() {
        const { value, handleSubmit, handleChange } = this.props;

        return (
            <React.Fragment>

Search for Vessel

                            <form className="mt-4" onSubmit={handleSubmit}>

                                    type vessel separated by comma

                                    <input
                                        type="text"
                                        name="search"
                                        placeholder="Type name of vessel here"
                                        className="form-control"
                                        value={value}
                                        onChange={handleChange}
                                    />

                                        <button type="submit" className="input-group-text bg-primary text-white">

                                        </button>

                            </form>

            </React.Fragment>
        );
    }
}

What I have done so far:
1) I tried different combination with the filter function and I think I am close. The problem is that when I operate the search nothing happens and in order to find the card of the vessel I want, I have to scroll down until I find it.
I am running out of ideas and if you see something I didn't catch point me in the right direction for solving this issue.

A: You're close! I would add a field to your state called 'searchText' and then create a method to filter based on that searchText state item.
getFilteredShips = () => this.state.ships.filter(s => s.name.includes(this.state.searchText)

Then just map over those values to render the cards that match the search text. The cards will update each time the searchText value updates.
this.getFilteredShips().map(ship => ..........

A: React is famous for re-usable component. You will have all the data of these vessels in an array. You will loop through the array and render the items with card component.And when you search for the specific card you want that vessel to pop out on top.
There are two ways to do it:
You have to run through the array, find the index of that vessel and do whatever it takes to manipulate your array and to make that item at top and re-render your list.
Alternatively render one more component on top of your vessel list as user clicks the search button. You just have to find the item index and render it. This way you don't have to deal with array manipulation. It doesn't matter if you have 80 or 1000 cards.
Please checkout official documentation for array methods, for array slicing and splice.
Hope this is what you are looking for. If you need further help, comment please.


text:
Q: snow leopard issue when installing rails 3.0.3 with RVM I have installed ruby via RVM. Installed rails into ruby-1.9.2-head@rails_3_0_3 and set it to default to use:
monster:gems gtheys$ rvm use ruby-1.9.2-head@rails_3_0_3 --default

Some additional information:
monster:gems gtheys$ ruby -v
ruby 1.9.2p174 (2011-01-28 revision 30696) [x86_64-darwin10.6.0]
monster:gems gtheys$ which gem
/Users/gtheys/.rvm/rubies/ruby-1.9.2-head/bin/gem
monster:gems gtheys$ rails -v
/opt/local/lib/ruby/vendor_ruby/1.8/rubygems.rb:779:in `report_activate_error': Could not find RubyGem rails (>= 0) (Gem::LoadError)
    from /opt/local/lib/ruby/vendor_ruby/1.8/rubygems.rb:214:in `activate'
    from /opt/local/lib/ruby/vendor_ruby/1.8/rubygems.rb:1082:in `gem'
    from /opt/local/bin/rails:18

What do I need to do. I see when I want to use rails it goes to to the wrong location...
UPDATE
I installed the gem Bundle and afterwards reinstalled rails 3.0.3 and now it seems to work :)
monster:~ gtheys$ rails -v
Rails 3.0.3
monster:~ gtheys$ which rails
/Users/gtheys/.rvm/gems/ruby-1.9.2-head@rails_3_0_3/bin/rails
monster:~ gtheys$

Fun solving your own problems :)

A: I installed the gem Bundle and afterwards reinstalled rails 3.0.3 and now it seems to work :)
monster:~ gtheys$ rails -v
Rails 3.0.3
monster:~ gtheys$ which rails
/Users/gtheys/.rvm/gems/ruby-1.9.2-head@rails_3_0_3/bin/rails
monster:~ gtheys$
Fun solving your own problems :)
Thanks @tomeduarte for the tip


text:
Q: What JavaScript library can you recommend? I want to use JavaScript on my web page. In particular I would like to have a auto-completer (like stackoverflow use for tags). I also would like to have drop down menus and so on.
I think, for these purposes it make sense to use a JavaScript library (I never did it before).  I browsed Internet the first option that I found was jQuery, I also found a list of other libraries.
So, I have a hard time choosing between these libraries and would like to ask your advise. My requirements to the library as as follow:

*

*Of course cross-browser functionality (works on as many browsers as possible).

*Easy to use (good documentation with examples + active community).

*Possibility to change the code (corresponding copy right + good documentation of the code).

Thank you in advance for any help.

A: Go for jquery and jquery UI which contains a nice autocomplete plugin. It's a javascript framework which gathered lots of pace, there's an enormous community and it is very likely you will find a plugin for every needs. It is guaranteed to work cross browser and you get a great documentation.


text:
Q: Reporting Services - Report Paramaters Losing State I am embedding a report into my ASP.NET app using the report viewer control.
When I change a paramater value and click View Report, I'm losing my paramater selection.
Any ideas?

A: Check if ViewState is enabled (for the page and for the control)

A: The problem was that I was setting the report location in the code behind but not che3cking if there had been a postback so the report was being reset each time.


text:
Q: Uncaught TypeError: Cannot read property 'wrapper' of undefined am using Inspinia admin theme. i just implement one of the modal effect from below link enter link description here modal effect name "slip"
the effect would comes into life when click one of the menu from hover popup which belong from side nav bar.
Issue: Uncaught TypeError: Cannot read property 'wrapper' of undefined
am using Angular for front-end and latest bootstrap framework.
by default: angular bootstrap has already .wrapper class.
is that naming conflict or what?
already came across some good solution from stack overflow but i couldn't able to use it effectively.
kindly suggest solution with jsfiddle. it would very greatfull
thanks for the heads up

A: The problem you have encountered is that you try to use the wrapper member of an object which is undefined. Reproduction example:
var foo;
var bar = foo.wrapper;

It is advisable to search for

.wrapper

in your javascript code and find where it is being used and what object is assumed to have such a member, then fix the issue.


text:
Q: Can Junit Ignore annotation be set to specific platforms or environments? Is there a standard way to ignore tests just for one platform or environment?
I have a cross platform build which has some junit tests which I only want to ignore on specific platforms.  I figure I can conditionalize the tests a few different ways:

*

*use categories to disable tests for specific platforms (e.g. NOT_SOLARIS)

*modify Ignore annotation and TestMethod to add Platform option to ignore
@Ignore("IssueTracker-ID", Ignore.PlatformSOLARIS)
If I choose the second option I will need to alter my local fork of junit (which isn't an issue since I'm already using a modified version).  I can change the Ignore annotation to support a platform key and then change TestMethod.isIgnored to act on the key.
Is there a standard Junit way to handle this kind of situation?
Thanks
Peter

A: You can always use Assume. For example:
public void testWindows() {
  assumeTrue(platform != SOLARIS)
}


text:
Q: Dockerized Telnet over SSH Reverse Tunnel I know that the title might be confusing so let me explain.
The is my current situation:
Server A - 127.0.0.1
Server B - 1.2.3.4.5
Server B opens a reverse tunnel to Server A. This gives me a random port on Server A to communicate with the Server B. Let's assume the port is 1337.
As I mentioned to access Server B I am sending packets to 127.0.0.1:1337.
Our client needs a Telnet connection. Since Telnet is insecure but a requirement, we decided to use telnet OVER the ssh reverse tunnel.
Moreover, we created an alpine container with busybox inside of it to eliminate any access to the host. And here is our problem.
The tunnel is created on the host, yet the telnet client is inside a docker container. Those are two separate systems.
I can share my host network with the docker with -network=host but it eliminates the encapsulation idea of the docker container.
Also binding the docker to host like that -p 127.0.0.1:1337:1337 screams that the port is already in use and it can't bind to that (duh ssh is using it)
Mapping ports from host to the container are also not working since the telnet client isn't forwarding the traffic to a specific port so we can't just "sniff" it out.
Does anyone have an idea how to overcome this?
I thought about sharing my host network and trying to configure iptables rules to limit the docker functionality over the network but my iptables skills aren't really great.

A: The port forward does not work, because that is basically the wrong direction. -p 127.0.0.1:1337:1337 means "take everything thats coming in on that host-port, and forward it into the container". But you want to connect from the container to that port on the host.
Thats basically three steps:

*The following steps require atleast Docker v20.04

*On the host: Bind your tunnel to the docker0 interface on the host (might require that you figure out the ip of that interface first). In other words, referring to your example, ensure that the local side of the tunnel does not end at 127.0.0.1:1337 but <ip of host interface docker0>:1337

*On the host: Add --add-host host.docker.internal:host-gateway to your docker run command

*Inside your container: telnet to host.docker.internal (magic DNS name) on the port you bound in step 2 (i.e. 1337)


text:
Q: 2013th powered prime factors Let $N$ be a positive integer. Prove that there exists a positive integer $n$ such that $n^{2013}-n^{20}+n^{13}-2013$ has at least $N$ distinct prime factors.
factorize the polynomial for some special n does no seem to be working

A: Hint/start: If $P(x)$ is an integer polynomial, and $m,n$ are relatively prime, and $m\mid P(a)$ and $n\mid P(b)$ then there exists $c$ so that $mn\mid P(c)$. (Why?)
So, all you need to show is that there are infinitely many primes $p$ so that the polynomial $x^{2013}-x^{20}+x^{13}-2013$ has a root modulo $p$.
You can use a similar approach to Euclid's proof of the infinitude of primes to prove this, but it is a little tricky.


text:
Q: CakePHP 3 - relationship between models I related two models following the official documentation of CakePHP 3 and can not return the values of one of them in view (Template).
The Code:
Work - Entity
namespace App\Model\Entity;

use Cake\ORM\Entity;

class Work extends Entity

    {
        protected $_accessible = [
            'project' => true,
            'client' => true,
            'filter' => true,
            'tech_1' => true,
            'tech_2' => true,
            'tech_3' => true,
            'tech_4' => true,
            'job' => true,
            'status' => true,
            'link' => true,
        ];
    }

WorksImage - Entity
namespace App\Model\Entity;

use Cake\ORM\Entity;

class WorksImage extends Entity
{
    protected $_accessible = [
        'photo' => true,
        'photo_dir' => true,
        'work_id' => true,
        'work' => true,
    ];
}

PagesController - Controller:
 namespace App\Controller;

    use Cake\Core\Configure;
    use Cake\Network\Exception\NotFoundException;
    use Cake\View\Exception\MissingTemplateException;

    class PagesController extends AppController
    {

        public function portfolio()
        {
            $this->loadModel('Works');
            $this->loadModel('WorksImages');
            $works = $this->Works->find('all',['contain' => ['WorksImages'],'limit' => 10, 'order' => ['Works.created' => 'DESC']]);
            $this->set(compact('works'));
        }

}

WorksTable - Table:
namespace App\Model\Table;

use App\Model\Entity\Work;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

class WorksTable extends Table
{
    public function initialize(array $config)
    {
        $this->table('works');
        $this->displayField('project');
        $this->primaryKey('id');
        $this->addBehavior('Timestamp');
        $this->hasOne('WorksImages', [
            'foreignKey' => 'work_id'
        ]);
    }

WorksImagesTable - Table
namespace App\Model\Table;

use App\Model\Entity\WorksImage;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

class WorksImagesTable extends Table
    {

    public function initialize(array $config)
    {
        $this->table('works_images');
        $this->displayField('id');
        $this->primaryKey('id');
        $this->addBehavior('Timestamp');
        $this->belongsTo('Works', [
            'foreignKey' => 'work_id',
            'joinType' => 'INNER'
        ]);
    }

Portfolio - View (Template)

Portfólio

            <?php foreach ($works as $work): ?>

<?= 'Conteúdo da tabela Works = ' . $work->project ?>

<?= 'Conteúdo da tabela WorksImages = ' . $work->work_id ?>

            <?php endforeach ?>

I can not return any value from the WorksImagesTable model. During Debugging, I realize that the tables are related, in addition, cake returns no error in the view.
I can not understand what is wrong.
I thank in advance any help.
Thanks.

A: In the foreach loop (debug($work->works_image)) returned something like this:
object(App\Model\Entity\WorksImage) {

    'new' => false,
    'accessible' => [
        'photo' => true,
        'photo_dir' => true,
        'work_id' => true,
        'work' => true
    ],
    'properties' => [
        'id' => (int) 1,
        'photo' => 'arteviva.jpg',
        'photo_dir' => 'a4cd522c-b7b9-437a-99fc-0eb15827944f',
        'work_id' => (int) 1,
        'created' => object(Cake\I18n\Time) {

            'time' => '2015-05-08T20:25:07+0000',
            'timezone' => 'UTC',
            'fixedNowTime' => false

        },
        'modified' => null
    ],
    'dirty' => [],
    'original' => [],
    'virtual' => [],
    'errors' => [],
    'repository' => 'WorksImages'

}


text:
Q: progress bar doesn't fill the space it's supposed to I'm trying to achieve something like that:

and I tried using card view and ended with that:

and I have got a problem becaues I want the "water left" progress bar to go to the end of the card (as shown in the picture 1) but it doesn't change it's length (and I don't want to hard code that lenth), any ideas what can I do ?
(code:
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:backgroundTint="@color/white"
    android:orientation="horizontal"
    card_view:cardCornerRadius="40dp"
    card_view:cardElevation="5sp"
    card_view:contentPadding="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="@color/white"
        android:gravity="center_vertical"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imageView2"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                tools:srcCompat="@tools:sample/avatars" />
        </LinearLayout>

        <TableLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1">

            <TableRow>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="3dp"
                    android:text="name:"
                    android:textSize="14dp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/plc_ModelId"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="3dp"
                    android:textSize="14dp"
                    tools:text="12345678" />
            </TableRow>

            <TableRow>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="3dp"
                    android:text="water left:"
                    android:textSize="14dp"
                    android:textStyle="bold" />

                <ProgressBar
                    android:id="@+id/progressBar2"
                    style="?android:attr/progressBarStyleHorizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_margin="3dp" />

            </TableRow>

            <TableRow>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="3dp"
                    android:text="time left:"
                    android:textSize="14dp"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/plc_Version"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="3dp"
                    android:textSize="14sp"
                    tools:text="00h 20 m" />
            </TableRow>

        </TableLayout>

    </LinearLayout>
</androidx.cardview.widget.CardView>

A: To achieve a full width use android:layout_weight="1" in your ProgressBar
        <TableRow>

            <TextView
                android:text="water left:"
             ../>

            <ProgressBar
                android:id="@+id/progressBar2"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="match_parent"
               />

        </TableRow>

Also using a LinearProgressIndicator provided by the Material Components Library and the trackThickness attribute you can achieve a different height:
Something like:
  <com.google.android.material.progressindicator.LinearProgressIndicator
            android:id="@+id/progressBar2"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            card_view:trackThickness="12dp"
            card_view:trackColor="@color/white"
            card_view:indicatorColor="@color/red600Light"
            android:progress="75"
            android:layout_margin="3dp"
            />


text:
Q: Using custom icons for Leaflet Layer groups? I have searched posts and tutorials and could not find the answer to my specific application of this feature
Almost all the examples use L.marker to simply place a marker on the map using various custom icons. This would be fine except I am not just placing markers but rather adding all the geoJson data to layers, then adding those layergroups to the control and then to the map. - I.E. I want all the layer routeca1 to use a red icon. I think I have narrowed this to needing to use the point to layer function:
pointToLayer: function (feature, latlng) {
            return L.marker(latlng, {icon: redIcon});
    }

I am not using the onEachFeature function, as I have seen an example on how to do this using that function but cant make that work for what I am doing here.
The map works great without trying to do a different color icon. I have all my points and polygons appearing and controlable by the layercontrol, but when I try to add the point to layer I just get a white map or the same map with no changes depending on where I try to add it in.
I added the icon sections below based off of the Leaflet Tutorial -
 var routeca1 = L.layerGroup();

 var geojsonFeature1 = [{***random geojson data points here****}  ];

    L.geoJSON(geojsonFeature1)
.bindPopup(function (layer) {
    return ''+'Location ID: '+ layer.feature.properties.locationid +'' + '
' + '
'+ layer.feature.properties.Description + '
' + layer.feature.properties.model + '
' + '
'+ layer.feature.properties.addresscomponents;
}).addTo(routeca1);

    var streets  = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '© OpenStreetMap', maxZoom: 17, minZoom: 6});

    var map = L.map('map', {
        center: [34.068, -118.248],
        zoom: 10,
        layers: [streets, routeca1]
    });

var baseLayers = {
        "Streets": streets
    };

    var overlays = {
        "CA1": routeca1
    };

var MarkerIcon = L.Icon.extend({
    options: {
        shadowUrl: './leaflet/images/marker-shadow.png',
        iconSize:     [38, 95],
        shadowSize:   [50, 64],
        iconAnchor:   [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor:  [-3, -76]
    }
});

var greenIcon = new MarkerIcon({iconUrl: './leaflet/images/marker-icon-green.png'}),
    redIcon = new MarkerIcon({iconUrl: './leaflet/images/marker-icon-red.png'}),
    blueIcon = new MarkerIcon({iconUrl: './leaflet/images/marker-blue.png'});

    L.icon = function (options) {
    return new L.Icon(options);
};

    L.control.layers(baseLayers, overlays).addTo(map);

A: I edited your code just using the red leaf from this example. The key changes I made to your code are:

*

*declaring the icon variable(s) before you turn your geoJSON data into a leaflet layer. That way, you can refer to the icon variable during the layer's construction.

*adding the "point to layer" code to the L.geoJSON layer's construction

*giving the leaflet layer a variable name (myLayer) so that I can set the icon and bind the popup separately.

//I start by setting up my icon here
var MarkerIcon = L.Icon.extend({
    options: {
        shadowUrl: 'leaf-shadow.png',
        iconSize:     [38, 95],
        shadowSize:   [50, 64],
        iconAnchor:   [22, 94],
        shadowAnchor: [4, 62],
        popupAnchor:  [-3, -76]
    }
});

//be sure the png files exist in your file directory and are pathed correctly
var greenIcon = new MarkerIcon({iconUrl: 'leaf-green.png'}),
    redIcon = new MarkerIcon({iconUrl: 'leaf-red.png'}),
    orangeIcon = new MarkerIcon({iconUrl: 'leaf-orange.png'});

L.icon = function (options) {
    return new L.Icon(options);
};

// I create an empty layer group
var routeca1 = L.layerGroup();

//var geojsonFeature1 = [{***random geojson data points here****}  ];
//I made up some points which work in your set-up. Though most of the attributes for the pop-up are missing
var geojsonFeature1 = {
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "Description": "A"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.24207305908203,
          34.084369762367984
        ]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "Description": "B"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.23057174682616,
          34.07356398381666
        ]
      }
    }
  ]
};

// L.geoJSON(geojsonFeature1); //removed this line
//and added the following instead, which sets the icon based on the variable created above and adds each marker to the layer group. Note "redIcon" must be created above this, or it is not going to work:
 myLayer = L.geoJSON(geojsonFeature1, {
    pointToLayer: function (feature, latlng){
        return L.marker(latlng, {icon: redIcon});
    }
 }).addTo(routeca1);

 //I then bind the popup to the layer here:
 myLayer.bindPopup(function (layer) {
    return ''+'Location ID: '+ layer.feature.properties.locationid +'' + '
' + '
'+ layer.feature.properties.Description + '
' + layer.feature.properties.model + '
' + '
'+ layer.feature.properties.addresscomponents;
});

// now I create my map and other layers
var streets  = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '© OpenStreetMap', maxZoom: 17, minZoom: 6});

var map = L.map('map', {
        center: [34.068, -118.248],
        zoom: 10,
        layers: [streets]
    });

var baseLayers = {
        "Streets": streets
    };

var overlays = {
        "CA1": routeca1,

    };

//lastly add the layers to the map!
L.control.layers(baseLayers, overlays).addTo(map);

I hope this helps!


text:
Q: Angular 5 - communication between Components and Services I use Angular 5.
The aim is to load data when Login is ok and to use these data in the other components.
The data are loaded by using Services Class with getActiveTasks Method and getStats Method.
Login Component :
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {

  constructor(private auth: AuthenticationService,
              private klinckServices: KlinckServices,
              private router: Router) { }

  loadData($event) {
    console.log('Authentification OK');
    let success;
    this.klinckServices.getActiveTasks(this.auth.getEcmUsername())
      .then((webScriptdata) => {
          console.log('KlinckSercices - loadData');
          success = webScriptdata;
          this.klinckServices.listTasks = success.data as ActiveTask[];
          this.router.navigate([this.klinckServices.getStats()]);
          console.log(this.klinckServices.listServices);
        },
        msg => {
          alert(msg);
          return '';
        });
   // this.router.navigate([this.klinckServices.loadData()]);
  }
}

Services Class :
@Injectable()
export class KlinckServices {

  listTasks: ActiveTask[];
  listServices: Stats [] = [];

  constructor(private apiService: AlfrescoApiService,
              private auth: AuthenticationService) {
    console.log('KlinckServices - constructor');
  }
  getStats(): string {
    this.listTasks.forEach((item, index) => {
      if (this.getServicesInListTasks(item.properties.wfvd_nomService) !== null) {
        if (! this.getServicesInListServices(item.properties.wfvd_nomService)) {
          const listLength = this.listTasks.filter(item2 => item2.properties.wfvd_nomService === item.properties.wfvd_nomService).length;
          console.log(listLength);
          const at: ActiveTask[] = [];
          for (let i = 0; i < listLength; i++) {
            at.push(this.listTasks.filter(item2 => item2.properties.wfvd_nomService === item.properties.wfvd_nomService)[i]);
          }
          this.listServices.push({
            data: at,
            count: listLength,
            service: item.properties.wfvd_nomService
          });
        }
      }
    });
    return '/dashboard';
  }
  getServicesInListServices( serviceSearch: string) {
    return(this.listServices.find( x => x.service === serviceSearch));
  }
  getServicesInListTasks( serviceSearch: string) {
    return(this.listTasks.find( x => x.properties.wfvd_nomService === serviceSearch));
  }

When the dashboard component is loaded , i need to retrieve these data :
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit, AfterViewInit
{
  @ViewChild(DataTableDirective) datatableElement: DataTableDirective;
  @Input() public klinckServices: KlinckServices;

  listTasks: ActiveTask[];
  listPatients: Patient[];
  listMedecins: Medecin[];
  listDocType: Typologie[];
  listServices: Stats [] = [];
  dtOptions: any = {};
  docNodeId: string;
  detailTaskId: any;

  constructor(private auth: AuthenticationService,
              public dialog: MatDialog,
              private http: HttpClient)
  {
    console.log('DashboardComponent - constructor');
    this.listServices = this.klinckServices.listServices;
    console.log(this.listServices);
    this.getPatients();
    this.getMedecins();
    this.getDocumentType();
  }

But I get this error message in console : "ERROR TypeError: Cannot read property 'listServices' of undefined"
So what is the best way to communicate between components and services ?

A: You should inject the service as you do in the LoginComponent
constructor(private klinckServices: KlinckServices

And you should also provide it to the module
providers: [KlinckServices]

A: You can for instance:

*

*Use Singleton Service in Angular and load data once during login

*Load data not on login but on Dashboard init (OnInit method which interface U use in class definition - and ofcors you must inject you KlinkService in constructor to use it as @CornelC mention in his answer).

Additional Question for you: why you don't use Rxjs in your services (it is standard in angualar) on KlinkService.getActiveTasks (because you call it as promise) ?


text:
Q: I want to subtract one column from another in pandas, but I keep getting a copy error. Is there a better way to do this operation? I have a data frame TB_greater_2018 that 3 columns: country, e_inc_100k_2000 and e_inc_100k_2018. I would like to subtract e_inc_100k_2000 from e_inc_100k_2018 and then use those values returned to create a new column of the differences and then sort by the countries with the largest difference.  My current code is:
case_increase_per_100k = TB_greater_2018["e_inc_100k_2018"] - TB_greater_2018["e_inc_100k_2000"]
TB_greater_2018["case_increase_per_100k"] = case_increase_per_100k
TB_greater_2018.sort_values("case_increase_per_100k", ascending=[False]).head()

When I run this, I get a SettingwithCopyWarning.  Is there a way to do this without getting this warning?  Or just overall a better way of accomplishing the task?

A: You can do
TB_greater_2018["case_increase_per_100k"]  = TB_greater_2018["e_inc_100k_2018"] - TB_greater_2018["e_inc_100k_2000"]
TB_greater_2018.sort_values("case_increase_per_100k", ascending=[False]).head()

It looks like the error is from finding the difference and using that as a column in separate operations, although tbh I'm not clear why that would be.


text:
Q: Defining implicit imports causes an error with other imports I have an application built in VB.NET. Everything is working great, here are the imports I'm using....
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Data.Odbc
Imports System.Windows.Forms.Control
Imports System.Windows.Forms.DataGridView
Imports System.Runtime.InteropServices.Marshal
Imports System.IO

I'm trying to do something with excel and added the following import which causes me some issues.....
Imports Microsoft.Office.Interop.Excel

In Public Class I have this...
Private DtTable as DataTable

The errors are:

DataTable is ambiguous, imported from the namespaces or types
  'Microsoft.Office.Interop.Excel, System.Data'.

also, I have a function where I use this as a paramter...
ByRef c As Windows.Forms.ComboBox

I get the following error...

Type Windows.Forms.Combobox is not defined.

A: You'll need to declare explicity your DataTable like this:
Private DtTable as Data.DataTable

The same for the second error. Declare it like this:
ByRef c As System.Windows.Forms.ComboBox

A: That is because the name DataTable is in multiple namespaces. Do it this way instead.
Imports Microsoft.Office.Interop
Private xlTable as Excel.DataTable

or, if you want the standard DataTable
Private dtTable as DataTable

And you missed the "System" part in the combox scope. But again, you are better doing it this way.
Imports System.Windows.Forms
ByRef c As ComboBox


text:
Q: What are some good resources for learning how to program animations? I have a sound foundation on GLSL, OpenGL, and a lot about 3D graphics techniques in total. However, one concept still confounds me and that is the process of animation.
Does anyone have resources on where I can learn animating meshes in C++? Some examples would be awesome as well. :)

A: Animation is a lot of work, whether you are going to do it "by hand", or whether you intend to simulate the animation. If simulation is your cup of tea, see this answer I posted a few months ago.


text:
Q: Show that Cov(T,T')=Var(T) Let $X_1,...,X_n$ be a sample, all with mean $\mu$ and $Var(X_i)<\infty$.  Let $T(X_1,...,X_n)=\sum_{i=1}^na_iX_i$. If T is the UMVUE of $\mu$ and T' is another linear unbiased estimate of $\mu$, then show that
$$Cov(T,T')=Var(T)$$
So I know that $E(T)=E(T')=\mu$ since T and T' are unbiased.
Then I also know that $Cov(T,T')=E(TT')-E(T)E(T')=E(TT')-\mu^2$
Then $Var(T)=E(T^2)-E(T)^2=E(T^2)-\mu^2$
The goal then becomes to show that $E(TT')=E(T^2)$, or to show that $T=T'$.
This is where I get stuck.  I want to use uniqueness of the UMVUE, so I want to show that T' is as UMVUE of $\mu$ giving the desired result.  I assume that since T' is another linear unbiased estimator, it is of the form $\sum_{j=1}^nb_jX_j$.
I suppose one viable approach is to show that $Var(T')\le Var(T)$, where then using that T is the UMVUE we could conclude that T=T' and the problem is done.
Any help is appreciated, thanks in advance

A: I don't think your proposed approach will work - if it did, you would also be proving that when a UMVUE exists, there are no other linear unbiased estimators.
What you can do instead is to say given the UMVUE $T$ and another linear unbiased estimator $T^\prime$, consider the estimator $\lambda T + (1 - \lambda)T^\prime$. You can prove that this is still unbiased, and therfore we have
$\mathrm{Var}(\lambda T + (1 - \lambda) T^\prime) \geq \mathrm{Var}(T)$
for $\lambda \in \mathbb{R}$. This gives a quadratic in $\lambda$ which is non-negative everywhere, and takes the value $0$ when $\lambda = 1$. This means the discriminant of the quadratic must be 0, and following the consequences of this conclusion algebraically will give the result.


text:
Q: Same Query MySQL User Defined Variables I'm attempting to use MySQL's user defined variables, but due to restrictions I can't use them in the same way as it demonstrates, where one query sets the variable and a second uses it. My requirement is to be able to use it multiple times in a query.
Consider the following:
SELECT (Some Really Taxing Calculation) AS Total FROM Purchases
WHERE Total < 55 AND itemName = "Bananas"
OR Total > 90 AND itemName = "Apples"
OR Total = 30 AND itemName = "Peaches"
ORDER BY Total

It'd be really nice to only run the Total calculation once, and then use the result multiple times throughout the query. Right now, the only way I've gotten it to work in one query is to rerun it for every place it's used as Total returns an error saying an unknown column has been used.

A: Imbed the total calculation in a sub-query...
SELECT
  Total
FROM
  (SELECT (Some Really Taxing Calculation) AS Total, * FROM Purchases) AS Purchases
WHERE Total < 55 AND itemName = "Bananas"
   OR Total > 90 AND itemName = "Apples"
   OR Total = 30 AND itemName = "Peaches"
ORDER BY
  Total

Note: The sub-query (inline-view) is expanded by MySQL when generating it's PLAN.  Putting brackets around the query doesn't necessarily mean you're forcing it to be stupidly inefficient :)

A: SELECT *, total.Value
FROM Purchases, (SELECT COUNT(*) as Value .... Some Really Taxing Calculation) total
WHERE Total < 55 AND itemName = "Bananas"
OR Total > 90 AND itemName = "Apples"
OR Total = 30 AND itemName = "Peaches"
ORDER BY Total

So basically, do your calculation in a nested SELECT type query in the FROM clause and give it a name of total than you can then use else where in your query.


text:
Q: Docker network interfaces card bandwidth limitation? How docker's network interface bandwidth limitation is determine? is it based on the physical network card bandwidth? and if not, from where is taken the bandwidth?
I have a certain application deployment where docker creates multiple nics. Now, when we send data to this node, we send it to the physical NIC, which is 1Gbps, we are able to see incoming data in the physical nic and, as we are expecting we also see data on the nics created by docker, now when I want to determine the bandwidth usage per second for that node, can I assume that the bandwidth used by all the docker nics is it taken from the physical bandwidth?
For example: in a run test, if the physical nic bandwidth usage was 100Mbps and the total of 4 docker nics was 200Mbps, then could we say the physical nic total bandwidth usage was 400Mbps?

A: Docker don't handle such feature. See: https://github.com/moby/moby/issues/9607
Have a look at cgroup net_cls https://www.kernel.org/doc/Documentation/cgroup-v1/net_cls.txt


text:
Q: Open a port CentOS I'm new in CentOS and I'm trying to create a little script in Python, something like:
$ python -m SimpleHTTPServer

If I try to access port 8000 in my web browser, I don't get access, however if I turn off the firewall with:
$ system-config-firewall-tui

I'm able to access the service.
I just need to access port 3343 and 8880 but I don't want to disable the firewall.

A: Try something like this:
$ iptables -A INPUT -p tcp --dport 3343 -j ACCEPT
$ iptables -A INPUT -p tcp --dport 8880 -j ACCEPT

A: Just for anybody who needs, after make the change in iptables i reload the services with:
/etc/init.d/iptables restart

And
/etc/init.d/networking restart


text:
Q: New to JSON.net, sample code Im starting a new WP7 app that gets information from a DNLA server. The server supports JSON languages for the REST protocol. I did some research and found json.net was very well recommended.
I can get data by using http://192.168.1.1:234/rest/status?media=json
Giving me:
{"serverStatus":"STARTED","renderers":[{"uuid":"00a0965fa15c","ipAddress":"192.168.1.10","name":"KDL-52NX803","profileId":"9","status":"ACTIVE"},{"uuid":"1829220b083f","ipAddress":"192.168.1.13","name":"Windows Media Player","profileId":"1","status":"INACTIVE"},{"uuid":"5d70ac53cf8e","ipAddress":"192.168.1.14","name":"Unrecognized device","profileId":"1","status":"UNKNOWN"},{"uuid":"60465a95eec4","ipAddress":"192.168.1.22","name":"Playstation 3","profileId":"4","status":"UNKNOWN"},{"uuid":"001dd860bce4","ipAddress":"192.168.1.9","name":"Xbox 360","profileId":"3","status":"INACTIVE"}]}
Im very much new to c#, ive read the official Json.NET documenation, but would prefer to see sample code to get me moving.
I have created listbox to collect "renderers" data, and TextBlock for the current "serverStatus" of the server.
If anyone can help and would very much appreciate your efforts

A: For starters, http://json2csharp.com/ is handy for putting in your json and creating a poco.
public class Renderer
{
    public string uuid { get; set; }
    public string ipAddress { get; set; }
    public string name { get; set; }
    public string profileId { get; set; }
    public string status { get; set; }
}

public class RootObject
{
    public string serverStatus { get; set; }
    public Renderer[] renderers { get; set; }
}

This page has simple examples on serialize/dserialize.
RestSharp is a wonderful HTTP API Client that supports WP7.  It will deserialzie for you and also allows you to implement your own serializer/deserializer.


text:
Q: Can't get the parameter of the action in my bean using primefaces diagram With the following code with primefaces 6.0
<p:diagram  value="#{myBean.model}" var="m" >
    <f:facet name="element">
        <h:commandButton value="#{m.id}" action="#{myBean.test(m.id)}"/>
    </f:facet>
</p:diagram>

and
@Named
@SessionScoped
public class MyBean implements Serializable {
    .....
    private  DefaultDiagramModel model;
    //getter and setter

    public String test(int id) {
        System.out.println("ID IS : " + id);
        return null;
    }
    ....
}

I get the value of the id on the button label (rendered on the xhtml page).
But I get always the number

ID IS : 0

on the IDE console
If I change my code with action="#{myBean.test(4)}" I get in the IDE console

4

If I change my code with action="#{myBean.test(6)}" I get in the IDE console

6

But when I come back to action="#{myBean.test(m.id)}" I get always in the IDE console the number 0
But the value if the id is well rendered on button label on the xhtml page
Non Exception is thrown!
Any help please?

A: Take a look into how-to-pass-a-parameter-along-with-hcommandbutton. I've checked example with <f:param> and it works like a charm in your case.
So in your case
<p:diagram  value="#{myBean.model}" var="m" >
   <f:facet name="element">
       <h:commandButton value="#{m.id}" action="#{myBean.test}">
           <f:param name="elementId" value="#{m.id}" />
       </h:commandButton>
   </f:facet>
</p:diagram>

And in bean
public String test() {
    String elementId= FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("elementId");
    System.out.println("ID IS : " + elementId);
    return null;
}


text:
Q: How do get maximum count grouped by element in pandas data frame I have data grouped by tow columns [CustomerID,cluster] like this:
CustomerIDClustered.groupby(['CustomerID','cluster']).count()

                    Count
CustomerID cluster
1893       0            1
           1            2
           2            5
           3            1
2304       2            3
           3            1
2655       0            1
           2            1
2850       1            1
           2            1
           3            1
3648       0            1

I need assign most frequent cluster to the customer id
For Example:

*

*1893->2 (2 appear in cluster more than other clusters)

*2304->2

*2655->1

A: Use sort_values, reset_index and last drop_duplicates:
df = df.sort_values('Count', ascending=False).reset_index().drop_duplicates('CustomerID')

Similar solution, only filter by first level of MultiIndex:
df = df.sort_values('Count', ascending=False)
df = df[~df.index.get_level_values(0).duplicated()].reset_index()
print (df)
   CustomerID  cluster  Count
0        1893        2      5
1        2304        2      3
2        2655        0      1
3        2850        1      1
4        3648        0      1


text:
Q: php mail() sending two different messages on submit to different parties I modified the following script. Everything seems to work except the person who submits the form('to2') gets an email with ('message2' - with single space lines) followed by ('message' - with double space lines).
The recipients of ('message') works as it should in that they only get ('message' - with single space lines).
MY OBJECTIVE is for ('to2') only to receive ('message2') without being followed by ('message'). I tried positioning mail('message2') string in different locations of the scripts' logic, but, I keep getting the same results or broken. Any help with logic is appreciated.
Here is the script...
<?php
session_start();
?>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=500">
<title>EXAMPLE</title>

<?php

if(isset($_POST['Submit'])) {
$ip_address = $_SERVER['REMOTE_ADDR'];
    $Subject = 'TEST';
    $Subject2 = 'SUCCESS';
    $A1 = $_POST['A1'];
    $Name = $_POST['Name'];
    $Phone = $_POST['Phone'];
    $Email = $_POST['Email'];
    $message = $_POST['message'];
    $message2 = $_POST['message2'];

// Type in your Email address to receive the mail
$to =  'me@example.com';
$to2 =  $Name.' <'.$Email.'>';

    if($Name == "" or $Phone == "" or $Email == "" ) {
        echo 'One or more fields has not been filled out.

        Click on your browser back button once and try again.';
    }
    elseif(!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
        echo 'The Email address could not be validated.

        Click on your browser back button once and verify your Email address.';
    }
    else { // All checks passed

        $headers = "From: ".$Name." <".$Email.">\r\n";
        $headers .= "Bcc: [VENDOREMAILS]\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=utf-8\r\n";
        $headers2 = "From: Support <me@example.com>\r\n";
        $headers2 .= "MIME-Version: 1.0\r\n";
        $headers2 .= "Content-Type: text/html; charset=utf-8\r\n";
        $message = "
Subject: $Subject

Question: $A1

Name: $Name

Phone: $Phone

Email: $Email
";
        $message2 = "
Subject: $Subject2

Question: $A1

Name: $Name

Phone: $Phone

Email: $Email
"
.nl2br($message);
        $sendMail = mail($to, $Subject, $message, $headers);
        if($sendMail) {
            echo "THANK YOU FOR YOUR SUBMISSION";
            mail($to2, $Subject2, $message2, $headers2);
        }
        else {
            echo "An error occured and the mail could not be sent.

Please try again";
        }
    }
}
else {
    header("location:example.html");
}
?>

A: Remove the code
.nl2br($message);

from the end of the definition of $message2. I think that should do it.


text:
Q: Behaviour of $\sum_{n=1} \frac{1}{n!} e^{an}\log(n)$ as $a \to \infty$ I am interested in the behavior of the following sum
\begin{align}
\sum_{n=1} \frac{1}{n!} e^{an}\log(n),
\end{align}
as $a$ approaches infinity.
Using $\log(n) \le n$ we can the following upper bound
\begin{align}
\sum_{n=1} \frac{1}{n!} e^{an}\log(n) \le   e^{a+e^a}.
\end{align}
However, I think the true behavior is more like  $e^{\log(a)+e^a}$. However, I am not sure how to show whether this is true or not.

A: We expect the largest summand approximately where $n\approx e^a$.
Comparing the log to its tangent at that point,
$$\ln n\le  a-1+\frac{n}{e^a}$$
So
$$\begin{align}\sum_{n=1}^\infty\frac1{n!}e^{an}\ln n&\le (a-1)\sum_{n=1}^\infty\frac1{n!}e^{an}+ \sum_{n=1}^\infty\frac1{(n-1)!}e^{a(n-1)}\\&=(a-1)(e^{e^a}-1)+e^{e^a}\\&=e^{\ln a+e^a}-a+1\end{align}$$

A: A full asymptotic series for $S$, with $x=\exp(a) \to \infty,$
$$ S:=\sum_{n=1}^\infty \frac{x^n}{n!} \log{n} \sim e^x\big(\, \log(x) - \frac{1}{2x}-\frac{5}{12x^2} + ... \big)$$
can be derived in the following manner.
It is a well-known Laplace transform that can be rearranged as such:
$$ \frac{\log{n}}{n} =-\frac{\gamma}{n} - \int_0^\infty e^{-nt} \,\log{t}\, dt. $$
The $\gamma$ is Euler's constant. Insert this into definition for S, interchange order of sum and integration, and sum the series to get
$$ S=-\gamma\big(e^x-1)-x\int_0^\infty e^{-t}\exp{(x\, e^{-t})} \log{t} \, dt. $$
This exact representation takes a simpler form on the substitution $e^{-t} \to u,$
$$ S=-\gamma\big(e^x-1)-x\int_0^1 \exp{(x\,u)} \log{(\log{(1/u)})} \, du. $$
Clearly for $x$ large what matters the most is what happens near $u=1.$ Expand the log-log as
$$ \log{(\log{(1/u)})} = \log{(1-u)} - \frac{1}{2}(u-1) + \frac{5}{24}(u-1)^2+... $$
Now
$$\int_0^1\log{(1-u)}\exp(x\,u)du=-\frac{e^x}{x}\big(\gamma+\Gamma(0,x)+\log(x)\big) \sim  -\frac{e^x}{x}\big(\gamma+\log(x)\big)$$
where the incomplete gamma function is neglected because its asymptotic expansion is exponentially small in comparison. Likewise, neglecting terms that are exponentially small, we find that
$$ \int_0^1(u-1)\exp(x\,u) du \sim -\frac{e^x}{x^2} \text{ and }
 \int_0^1(u-1)^2\exp(x\,u) du \sim \frac{2e^x}{x^3} .$$
Algebra completes the solution.

A: Let $N(t)$ be the Poisson process of the unit rate. Then
$$ \sum_{n=0}^{\infty} \frac{e^{an}}{n!}f(n) = e^{e^a}\mathbb{E}[f(N(e^a))]. $$
In our case, one can set $f(n) = \log(n \vee 1)$. In view of the law of large numbers, one may expect that this is approximately
$$e^{e^a}f(\mathbb{E}[N(e^a)]) = e^{e^a}f(e^a) = a e^{e^a}.$$

Indeed, by the Bennett-type concentration inequality, with $\psi(x) = (1+x)\log(1+x)-x $, for any $\epsilon > 0$ we have
$$ \mathbb{P}( \left| N(\lambda) - \lambda \right| \geq \epsilon\lambda) \leq 2e^{-\psi(\epsilon)\lambda}. $$
Then by using the inequality $\log(\lambda \pm a) \leq \log(\lambda+|a|)=\log\lambda + \int_{0}^{|a|/\lambda} \frac{ds}{1+s} $, we have
\begin{align*}
\mathbb{E} \left[ \log(N(\lambda)\vee 1) \mathbf{1}_{\{|N(\lambda)-\lambda|\geq\epsilon\lambda\}} \right]
&\leq \mathbb{E} \left[ \log \left( \lambda + \left|N(\lambda) - \lambda\right| \right) \mathbf{1}_{\{|N(\lambda)-\lambda|\geq\epsilon\lambda\}} \right] \\
&\leq (\log\lambda)\mathbb{P}( \epsilon\lambda \leq \left|N(\lambda) - \lambda\right|) \\
&\quad + \int_{0}^{\infty} \frac{ds}{1+s} \mathbb{P}( (s\vee\epsilon)\lambda \leq \left|N(\lambda) - \lambda\right|) \\
&\leq 2(\log \lambda)e^{-\psi(\epsilon)\lambda} + \int_{0}^{\infty} \frac{2e^{-\psi(s\vee \epsilon)\lambda}}{1+s}\,ds
\end{align*}
This bound vanishes as $\lambda \to \infty$, so with $f(n) = \log(n\vee 1)$, it follows that
$$ \lim_{\lambda\to\infty} \frac{\mathbb{E} \left[ f(N(\lambda)) \right] }{\log\lambda} = 1 $$
This proves the desired asymptotics:
$$ \lim_{a\to\infty} \frac{\sum_{n=1}^{\infty} \frac{1}{n!}e^{an}\log n}{a e^{e^a}} =\lim_{a\to\infty} \frac{\mathbb{E}[f(N(e^a))]}{a} = 1. $$


text:
Q: Problemas con refresco de imagenes en chrome Tengo una aplicacion, la cual a traves de un formulario subo 3 imagenes, las cuales la ruta de estas se almacena en una base de datos y las imagenes en el disco en una carpeta especifica. La aplicacion tiene 3 "ventanas" que muestran una vista previa de las imagenes...
El asunto es, que al editar un registro, al cambiar alguna de las imagenes, si abro el registro nuevamente, sigue mostrando las mismas imagenes anteriores cargadas y no la modificacion que se hizo...
Revisando en internet, enconrtre que agregando un par de lineas al head de la pagina se evita el uso del cache, pero no me dio resultados:
<head>
  <meta http-equiv="Expires" content="0">
  <meta http-equiv="Last-Modified" content="0">
  <meta http-equiv="Cache-Control" content="no-cache, mustrevalidate">
  <meta http-equiv="Pragma" content="no-cache">
</head>

Y tambien probe el agregar al principio de la pagina (antes del <!DOCTYPE html>), las siguientes lineas de php, pero tampoco funciono:
header("Expires: Tue, 01 Jul 2001 06:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

Este punto importante, esto solo me ocurre con los navegadores de celulares, no en navegadores de computadores.