text:
Q: Chrome extension, Javascript: getting URL from address bar I have an extension that I am working on that has a "pop-up" putton on the bar,
I visit a site (for example google.com) the button is pressed, I run this code in popup.html:
window.addEventListener("load", windowLoaded, false);

function windowLoaded() {
  chrome.tabs.getSelected(null, function(tab) {
    localStorage['url_in_address_bar']=tab.url;
  });
}

but instead of saving the google address, it saves it's own address like this: "chrome://extensions/".
How do I get it to save the last address instead of itself?

A: Your code shows the problem. getSelected returns the tab as a callback, which means the callback is executed when Chrome has found the selected tab. This is asynchronous, and is executed later:
window.addEventListener("load", windowLoaded, false);

function windowLoaded() {
  // 1) request selected tab
  chrome.tabs.getSelected(null, function(tab) {
    localStorage['url_in_address_bar']=tab.url; // 3) selected tab is stored
  });
}

// 2) a tab is created
var saved_email = localStorage['blocker_user_email'];
if (saved_email === undefined ||  saved_email == "a@a.com")
{
    //self.close();
    chrome.tabs.create({url: '0_register.html'});
} else{
      // self.close();
      chrome.tabs.create({url: '1_options.html'});
}

You could solve it by putting the second part of your code into the callback function:
window.addEventListener("load", windowLoaded, false);

function windowLoaded() {
  chrome.tabs.getSelected(null, function(tab) {
    localStorage['url_in_address_bar']=tab.url;

    var saved_email = localStorage['blocker_user_email'];
    if (saved_email === undefined ||  saved_email == "a@a.com")
    {
        //self.close();
            chrome.tabs.create({url: '0_register.html'});
    } else{
          // self.close();
          chrome.tabs.create({url: '1_options.html'});
    }
  });
}

A callback function is a function you provide as an argument to another function (e.g. getSelected). When that other function has completed its task (e.g. find selected tab), it will execute the provided function. In the meantime, however, the code coming after the request will be executed regularly.


text:
Q: Error:Error converting bytecode to dex: Cause: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/zzee; hi i have error on my android studio

Error:Error converting bytecode to dex: Cause:
  com.android.dex.DexException: Multiple dex files define
  Lcom/google/android/gms/internal/zzee;
Error:Execution failed for task
  ':app:transformClassesWithDexForDebug'.

com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException:
    java.util.concurrent.ExecutionException:
    com.android.ide.common.process.ProcessException: Error while executing
    java process with main class com.android.dx.command.Main with
    arguments {--dex --num-threads=4 --output

My  build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        applicationId "com.brommko.android.promophotography"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 14
        versionName "3.4"
        manifestPlaceholders = [manifestApplicationId          : "${applicationId}",
                                onesignal_app_id               : "c0fbadc6-4013-4613-b00b-566eab144d3c",
                                onesignal_google_project_number: "4122760152"]
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.onesignal:OneSignal:3.+@aar'
    compile 'com.google.android.gms:play-services-gcm:11.0.4'
    compile "com.google.android.gms:play-services-location:11.0.4"
    compile 'com.github.quentin7b:android-location-tracker:3.2'
    compile 'com.google.firebase:firebase-messaging:10.0.1'
    compile 'com.google.firebase:firebase-ads:10.0.1'
    compile 'com.google.firebase:firebase-crash:10.0.1'
    compile 'org.jetbrains:annotations-java5:15.0'
    compile 'com.github.hotchemi:android-rate:1.0.1'
}

apply plugin: 'com.google.gms.google-services'

A: This is because you've mixed version of dependencies. The problem is because OneSignal automatically adds the following dependencies:
com.google.android.gms - Version 11.2.+
com.android.support - Version 26.1.+

So, you need to change your support, Firebase, and google play service dependencies version. It will be like this:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:design:26.1.0'

    // Don't use +, use exact dependency version.
    //compile 'com.onesignal:OneSignal:3.+@aar'
    compile 'com.onesignal:OneSignal:[3.6.5, 3.99.99]'

    compile 'com.google.android.gms:play-services-gcm:11.2.1'
    compile "com.google.android.gms:play-services-location:11.2.1"
    compile 'com.google.firebase:firebase-messaging:11.2.1'
    compile 'com.google.firebase:firebase-ads:11.2.1'
    compile 'com.google.firebase:firebase-crash:11.2.1'

    compile 'com.github.quentin7b:android-location-tracker:3.2'
    compile 'org.jetbrains:annotations-java5:15.0'
    compile 'com.github.hotchemi:android-rate:1.0.1'
}

Read more at Troubleshooting Android

redpajama_set_name: RedPajamaStackExchange


text:
Q: Почему не генерируется изображение php ? И не работает капча почему? НАШЕЛ РЕШЕНИЕ! НАДО БЫЛО УКАЗАТЬ ПОЛНЫЙ ПУТЬ К ШРИФТУ "
$capfont = 'C:\OSPanel\domains\Betcms\captcha\Highspeed_2.ttf';"
Не могу найти причину по которой не генерируется изображение, из-за этого не работает капча
//captcha.php
<?php

$capletters = 'ABCDEFGKIJKLMNOPQRSTUVWXYZ123456789';

$captlen = 5;

$capwidth = 210; $capheight = 64;

$capfont = 'Highspeed_2.ttf';

$capfontsize = 23;

header('Content-type: image/png');

$capim = imagecreatetruecolor($capwidth, $capheight);

imagesavealpha($capim, true);

$capbg = imagecolorallocatealpha($capim, 0, 0, 0, 127);

imagefill($capim, 0, 0, $capbg);

$capcha = '';

for ($i = 0; $i < $captlen; $i++){

$capcha .= $capletters[rand(0, strlen($capletters)-1) ];

$x = ($capwidth - 20) / $captlen * $i + 10;

$x = rand($x, $x+5);

$y = $capheight - ( ($capheight - $capfontsize) / 2 );

$capcolor = imagecolorallocate($capim, rand(0, 100), rand(0, 100), rand(0, 100) );

$capangle = rand(-35, 35);

imagettftext($capim, $capfontsize, $capangle, $x, $y, $capcolor, $capfont, $capcha[$i]);

}
session_start();

$_SESSION['captcha'] = strtolower($capcha);

imagepng($capim);

imagedestroy($capim);

?>

//index.php
<? if (!isset($_POST['captcha'])) { ?>

Регистрация

<form action="" method="post">

Логин:

<input type="text" name="login" value="<? echo $log = (isset($_SESSION['login'])) ? $_SESSION['login'] : ''; ?>" required>

E-mail:

<input type="email" name="email" value="<? echo $em = (isset($_SESSION['email'])) ? $_SESSION['email'] : ''; ?>"  required>

Пароль:

<input type="password" name="pas1"  required>

Пароль еще раз:

<input type="password" name="pas2"  required>

Символы с картинки:

<input type="text" name="captcha"  required>

<input type="submit" name="regOn" value="Регистрация">

</form>
<? } ?>

//control.php
<?php
if (isset($_POST['captcha'])) {
    $errorCaptcha = false;

    #принимаем и обрабатываем каптчу
    $captcha = trim(strtolower($_POST['captcha']));

    #если каптча введена неверно, добавляем ошибку
        if ($captcha != $_SESSION['captcha']) $errorCaptcha = true;

    #если каптча введена верно
    if  (!$errorCaptcha) {

        #очищаем данные
        foreach($_POST as $key=>$value){
            $_POST[$key] = XSS($value);
        }

        #проверяем и записываем данные
        $login = (is_string($_POST['login'])) ? $_POST['login'] : false;
        $pas1 = (!empty($_POST['pas1'])) ? $_POST['pas1'] : false;
        $pas2 = (!empty($_POST['pas2'])) ? $_POST['pas2'] : false;
        $email = (preg_match("|^[-0-9a-z_\.]+@[-0-9a-z_^\.]+\.[a-z]{2,6}$|i", $_POST['email'])) ? $_POST['email'] : false;

        #проверяем все ли данные введены корректно
        if ($login && $pas1 && $pas2 && $email) {

            #если пароли совпадают
            if ($pas1 == $pas2) {

            #обнуляем ошибки
            $error = false;

            #проверяем не зарегистрирован ли пользователь с таким логином
            $query = $db -> query("SELECT * FROM users WHERE login = ?s ", $login);
            $loginInBase = $db -> numRows($query);

            #если пользователь с таким логином есть, выводим ошибку
            if ($loginInBase)  {
                                   errors('Пользователь с таким логином уже зарегистрирован!');
                                   $error = true;
                                }

            #проверяем не зарегистрирован ли пользователь с таким email
            if (!CheckEmail($email)) {
                                        errors('Пользователь с таким Email уже зарегистрирован!');
                                        $error = true;
                                     }

            #если не возникло никаких ошибок
            if (!$error) {

            #запоминаем пароль
            $password = md5(sha1(md5($pas1)));

            #проверяем наличие бонуса при регистрации
            $bonus_reg = ($settingsSystem['bonus_reg']) ? $settingsSystem['bonus_reg'] : 0;

            #добавляем пользователя в БД
            $query = $db -> query("INSERT INTO users (login, password, email, balance) VALUES (?s, ?s, ?s, ?i)", $login, $password, $email, $bonus_reg);

            #если пользователь добавлен в базу
            if ($query) {
                        show('Успешная регистрация! Теперь вы можете авторизоваться в системе.');
                        $_SESSION['login'] = '';
                        $_SESSION['email'] = '';
                        }
                else
                        {
                        #если не удалось записать пользователя в БД, выдаем ошибку
                        errors('Ошибка записи пользователя в БД.');
                        }

            #если возникали ошибка, выводи соответствующее сообщение
            } else errors('Ошибка регистрации. Повторите снова.');

            #если пароли не совпали, выдаем ошибку
            } else errors('Пароли не совпадают!');

        #если какие-либо данные не заполнены, или введены не корректно, выдаем ошибку
        } else errors('Заполните корректно все поля!');

    } else  {
            #выводим сообщение о том, что каптча введена неверно
            echo errors('Каптча введена неверно!');

            #запомним данные, которые вводил пользователь
            $_SESSION['login'] = XSS($_POST['login']);
            $_SESSION['email'] = XSS($_POST['email']);

            }
}

A: Для того чтобы увидеть ошибки, отключи заголовок
header('Content-type: image/png');

Следует указывать полный путь к шрифту
D:\server\localhost\test\www\georgia.ttf

Получить его можно так:
//windows
$font = dirname(__FILE__) . '\arial.ttf';
//unix
$font = dirname(__FILE__) . '/arial.ttf';


text:
Q: CGrigCtrl horizontal scrolling How to enable horizontal scrollbar smooth scrolling for CGridCtrl. Now it jumps by fields when I scroll it from left to right.

A: I assume you're talking about CGridCtrl published in this CodeProject article.
If so, then you're going to have to completely override the drawing methods to offset the columns by the current scroll position (instead of calculating the first column to display from the scroll position).
To get you started, you should begin by looking at GetScrollPos(SB_HORZ) to use as an offset to begin drawing.


text:
Q: IIS 8.5 error on targetFramework 4.5.2 I've a problem on windows server 2012 R2 and IIS 8.5. My asp.net application, go error on webconfig line

like Unrecognized attribute 'targetFramework'.
.NET Framwework 4.5.2 installed and application pool from iis are using NET CLR v.40xxx
Any idea why ?

A: If you install the .NET Framework 4 before you enable IIS, you need to run the ASP.NET IIS Registration tool in order to register the .NET Framework with IIS using following syntax:
aspnet_regiis -iru

Note, you should use correct version of aspnet_regiis utility. The location where the tool is installed depends on the .NET Framework version. See link above.


text:
Q: How to write a simple class in C++? I have been reading a lot of tutorials on C++ class but they miss something that other tutorials include.
Can someone please show me how to write and use a very simple C++ class that uses visibility, methods and a simple constructor and destructor?

A: #include <iostream>
#include <string>

class Simple {
public:
  Simple(const std::string& name);
  void greet();
  ~Simple();
private:
  std::string name;
};

Simple::Simple(const std::string& name): name(name) {
  std::cout << "hello " << name << "!" << std::endl;
}

void Simple::greet() {
  std::cout << "hi there " << name << "!" << std::endl;
}

Simple::~Simple() {
  std::cout << "goodbye " << name << "!" << std::endl;
}

int main()
{
  Simple ton("Joe");
  ton.greet();
  return 0;
}

Silly, but, there you are.  Note that "visibility" is a misnomer: public and private control accessibility, but even "private" stuff is still "visible" from the outside, just not accessible (it's an error to try and access it).

A: Well documented example taken and explained better from Constructors and Destructors in C++:
#include <iostream>            // for cout and cin

class Cat                      // begin declaration of the class
{
  public:                      // begin public section
    Cat(int initialAge);       // constructor
    Cat(const Cat& copy_from); //copy constructor
    Cat& operator=(const Cat& copy_from); //copy assignment
    ~Cat();                    // destructor

    int GetAge() const;        // accessor function
    void SetAge(int age);      // accessor function
    void Meow();
 private:                      // begin private section
    int itsAge;                // member variable
    char * string;
};

// constructor of Cat,
Cat::Cat(int initialAge)
{
  itsAge = initialAge;
  string = new char[10]();
}

//copy constructor for making a new copy of a Cat
Cat::Cat(const Cat& copy_from) {
   itsAge = copy_from.itsAge;
   string = new char[10]();
   std::copy(copy_from.string+0, copy_from.string+10, string);
}

//copy assignment for assigning a value from one Cat to another
Cat& Cat::operator=(const Cat& copy_from) {
   itsAge = copy_from.itsAge;
   std::copy(copy_from.string+0, copy_from.string+10, string);
}

// destructor, just an example
Cat::~Cat()
{
    delete[] string;
}

// GetAge, Public accessor function
// returns value of itsAge member
int Cat::GetAge() const
{
   return itsAge;
}

// Definition of SetAge, public
// accessor function
 void Cat::SetAge(int age)
{
   // set member variable its age to
   // value passed in by parameter age
   itsAge = age;
}

// definition of Meow method
// returns: void
// parameters: None
// action: Prints "meow" to screen
void Cat::Meow()
{
   cout << "Meow.\n";
}

// create a cat, set its age, have it
// meow, tell us its age, then meow again.
int main()
{
  int Age;
  cout<<"How old is Frisky? ";
  cin>>Age;
  Cat Frisky(Age);
  Frisky.Meow();
  cout << "Frisky is a cat who is " ;
  cout << Frisky.GetAge() << " years old.\n";
  Frisky.Meow();
  Age++;
  Frisky.SetAge(Age);
  cout << "Now Frisky is " ;
  cout << Frisky.GetAge() << " years old.\n";
  return 0;
}

A: Even if he is a student, worth trying to answer because it is a complex one not that easy at least for a new Visitor of C++ :)
Classes in C++ serve an intersection of two design paradigms,
1) ADT :: which means basically a new type, something like integers 'int' or real numbers 'double' or even a new concept like 'date'.
in this case the simple class should look like this,
class NewDataType
{
public:
// public area. visible to the 'user' of the new data type.
.
.
.
private:
// no one can see anything in this area except you.
.
.
.
};

this is the most basic skeleton of an ADT...
of course it can be simpler by ignoring the public area!
and erasing the access modifiers (public, private) and the whole thing will be private.
but that is just nonsense. Because the NewDataType becomes useless!
imagine an 'int' that you can just declare but you CAN NOT do anything with it.
Then, you need some useful tools that are basically not required to the existence of the NewDataType, but you use them to let your type look like any 'primitive' type in the language.
the first one is the Constructor. The constructor is needed in many places in the language.
look at int and lets try to imitate its behavior.
int x; // default constructor.

int y = 5; // copy constructor from a 'literal' or a 'constant value' in simple wrods.
int z = y; // copy constructor. from anther variable, with or without the sametype.
int n(z); // ALMOST EXACTLY THE SAME AS THE ABOVE ONE, it isredundant for 'primitive' types, but really needed for the NewDataType.

every line of the above lines is a declaration, the variable gets constructed there.
and in the end imagine the above int variables in a function, that function is called 'fun',
int fun()
{
    int y = 5;
    int z = y;
    int m(z);

    return (m + z + y)
    // the magical line.
}

you see the magical line, here you can tell the compiler any thing you want!
after you do every thing and your NewDataType is no more useful for the local scope like in the function, you KILL IT.
a classical example would be releasing the memory reserved by 'new'!
so our very simple NewDataType becomes,
class NewDataType
{
public:
// public area. visible to the 'user' of the new data type.
    NewDataType()
    {
        myValue = new int;
        *myValue = 0;
    }

    NewDataType(int newValue)
    {
        myValue = new int;
        *myValue = newValue;
    }

    NewDataType(const NewDataType& newValue){

        myValue = new int;
        *myValue = newValue.(*myValue);
    }
private:
// no one can see anything in this area except you.
    int* myValue;
};

Now this is the very basic skeleton, to start building a useful class you have to provide public functions.
there are A LOT of tiny tools to consider in building a class in C++,
.
.
.
.
2) Object :: which means basically a new type, but the difference is that it belongs to brothers, sisters, ancestors and descendants. look at 'double' and 'int' in C++, the 'int' is a sun of 'double' because every 'int' is a 'double' at least in concept :)

A: class A
{
  public:
    // a simple constructor, anyone can see this
    A() {}
  protected:
    // a simple destructor. This class can only be deleted by objects that are derived from this class
    // probably also you will be unable to allocate an instance of this on the stack
    // the destructor is virtual, so this class is OK to be used as a base class
    virtual ~A() {}
  private:
    // a function that cannot be seen by anything outside this class
    void foo() {}
};


text:
Q: Jquery and javascript in html, calling function multiple times Let me start out with, my java skills are almost nonexistant.
I have a site that I want to put multiple forms on and have them open a popup window. We are using javascript/jquery to make the popup when selecting an item from dropdown. We have been able to get it to work on one form, but not multiple so I was trying to set it as a function.

I am having trouble trying to figure out how to make it a function and then having it call out to my select form:
> <form>
                        <select id="<?php the_field('last_name', 100); ?>selectBox" name="fieldname" size="1" class="select" style="background-color:#ffffff;font-size: 12px;margin-top: 0px !important;width: 95%;">
                            <option value>Issues</option>
                            <option id="agriculture" class="issue-select" value="agriculture">Agriculture</option>
                            <option id="budget" class="issue-select" value="budget">Budget</option>
                            <option id="corporate_welfare" class="issue-select" value="corporate_welfare">Corporate Welfare</option>
                            <option id="education" class="issue-select" value="education">Education</option>
                            <option id="entitlements_welfare" class="issue-select" value="entitlements_welfare">Entitlements & Welfare</option>
                            <option id="environment_energy" class="issue-select" value="environment_energy">Environment & Energy</option>
                            <option id="federalism" class="issue-select" value="federalism">Federalism</option>
                            <option id="finance_banking" class="issue-select" value="finance_banking">Finance & Banking</option>
                            <option id="free_speech_religious_liberty" class="issue-select" value="free_speech_religious_liberty">Free Speech & Religious Liberty</option>
                            <option id="health_care" class="issue-select" value="health_care">Health Care</option>
                            <option id="immigration" class="issue-select" value="immigration">Immigration</option>
                            <option id="international_relations" class="issue-select" value="international_relations">International Relations</option>
                            <option id="judiciary" class="issue-select" value="judiciary">Judiciary</option>
                            <option id="labor" class="issue-select" value="labor">Labor</option>
                            <option id="military_preparedness_budget" class="issue-select" value="military_preparedness_budget">Military Preparedness & Budget</option>
                            <option id="regulations" class="issue-select" value="regulations">Regulations</option>
                            <option id="privatization" class="issue-select" value="privatization">Privatization</option>
                            <option id="taxes" class="issue-select" value="taxes">Taxes</option>
                            <option id="trade" class="issue-select" value="trade">Trade</option>
                            <option id="war_on_terror" class="issue-select" value="war_on_terror">War On Terror</option>
                        </select>
                        </form>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Agriculture
'; ?><?php the_field( "agriculture", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Budget
'; ?><?php the_field( "budget", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Corporate Welfare
'; ?><?php the_field( "corporate_welfare", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php echo the_title(); echo ' on Education
'; ?><?php the_field( "education", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Environment & Energy
'; ?><?php the_field( "environment_&_energy", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Entitlements & Welfare
'; ?><?php the_field( "entitlements_&_welfare", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Federalism
'; ?><?php the_field( "federalism", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Finance & Banking
'; ?><?php the_field( "finance_&_banking", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Free Speech & Religious Liberty
'; ?><?php the_field( "free_speech_&_religious_liberty", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Health Care
'; ?><?php the_field( "health_care", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Immigation
'; ?><?php the_field( "immigration", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on International Relations
'; ?><?php the_field( "international_relations", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Judiciary
'; ?><?php the_field( "judiciary", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Regulations
'; ?><?php the_field( "regulations", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Privatization
'; ?><?php the_field( "privatization", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Taxes
'; ?><?php the_field( "taxes", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Labor
'; ?><?php the_field( "labor", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Trade
'; ?><?php the_field( "trade", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php the_title(); echo ' on Military Preparedness
'; ?><?php the_field( "military_preparedness_&_budget", 100 ); ?>

<img src="<?php echo esc_url( home_url( '/wp-content/themes/c3/img/close-x.png' ) ); ?>" alt="close button"/>
<?php echo the_title(); echo ' on War on Terror
'; ?><?php the_field( "war_on_terror", 100 ); ?>

Any help would be appreciated. As stated I need to make multiple of these select boxes.


text:
Q: Spring - No default constructor found I have a class which looks like this:
@Service("myService")
public class MyServiceImpl {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

and I also have a test class which looks like this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
    MyServiceImpl.class})
...

I get this exception:
 Injection of autowired dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire
field: private org.springframework.messaging.simp.SimpMessagingTemplate
myPackage.MyServiceImpl.simpMessagingTemplate; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.messaging.simp.SimpMessagingTemplate] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}

Does anyone know what I can do in order to get it work, SimpMessagingTemplate does not have a default constructor.

A: SimpMessagingTemplate seems to have either no default constructor or is not annotated with @Component (or @Service or another sub-class of @Component); or both.
Please check that a default constructor is available and the class is configured to be a Spring bean.

A: Its not related to missing constructor, but Spring fails to find proper bean to inject into your test class,
Two options to solve it as I see

*

*@ContextConfiguration(classes = {
MyServiceImpl.class, SimpMessagingTemplate.class})

*Add @mock SimpMessagingTemplate simpMessagingTemplate; to your test class


text:
Q: simple calculation not working for some reason Alright, I'm trying to calculate the percentage of two values. This should be really simple but for some weird reason it's not working. I'm too tired/dumb to figure it out.
Here's my code, it keeps returning 0, i checked the values while debugging and with FilesCompleted being 295 and TotalFilesCount being 25002 the returnvalue var is just 0, it should be 1 already.
private int CalculatePercentComplete(int FilesCompleted, int TotalFilesCount)
        {
            int returnvalue = (FilesCompleted / TotalFilesCount) * 100;

            if (returnvalue > 100 || returnvalue < 1) return 1;
            else return returnvalue;
        }

A: How about
int returnvalue = (int)(((double)FilesCompleted / TotalFilesCount) * 100);

What this is doing

*

*Converting int FilesCompleted to double. For eg if its 295, then this will convert it into 295.0 so that division happens in double.
There is no need to convert TotalFilesCount to double also as divison of double by integer (or integer by double) returns a double.

*So the returned double result is 0.011799056075513958 which is multipled by 100

*So the retunred result is 1.1799056075513958 which is finally converted to int which returns 1

A:
i checked the values while debugging and with FilesCompleted being 295 and TotalFilesCount being 25002 the returnvalue var is just 0, it should be 1 already.

No, because all the arithmetic is being done with integers. So first this expression is evaluated:
(FilesCompleted / TotalFilesCount)

That's 295 / 25002. The result of that integer arithmetic is 0... and when you then multiply it by 100, you've still got 0. The simplest fix is just to do the multiplication first:
int returnvalue = (FilesCompleted * 100) / TotalFilesCount;

Note that that will overflow if FilesCompleted is greater than int.MaxValue / 100. You could fix that by either doing everything in floating point arithmetic:
int returnvalue = (int)((FilesCompleted * 100.0) / TotalFilesCount);

... or by using long integer arithmetic:
int returnvalue = (int)((FilesCompleted * 100L) / TotalFilesCount);

Neither of these are necessary if you don't expect to have an insane number of files, of course. (You're fine up to 42 million files...)
As a side note, your parameter names violate .NET naming conventions. They should be camelCased - totalFilesCount and filesCompleted.

A: Indeed, simple error, when doing diversions with int, the answer will be an int. Your answer would be between 0 and 1 so rounded down it is 0 (int).
Use:
int returnvalue = (int)((FilesCompleted / (double)TotalFilesCount) * 100);

To make your calculation use a double for the fractional number and then multiply that by 100 and cast that to an int.

A: The FilesCompleted/TotalFilesCount returns 0.01 which in int format is 0, try FilesCompleted*100/TotalFilesCount!


text:
Q: api get request fails, but post, put, delete work Environment and Settings:

*

*react-native 0.57

*expressjs for server

*using axios for api request

*set timeout 10000ms

*the request is a json data with username and small other infos

*http request (not https)

I'm developing a small react native project and now having a trouble with "api GET request".
It's all perfect for POST, PUT, DELETE actions but only the GET request returns timeout error with "BadRequestError: request denied" server log.
The same code on android works just fine, but it only happens on ios.
I've set NSAllowsArbitraryLoads to true and also NSExceptionDomains just in case but neither of them solved the problem.

A: Latest iOS sdk enforces connection to be in https protocol instead of http.
you can add an exception to your domain inside info.plist file of the Xcode project.
if you want to allow everything write this inside info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
    <key>yourdomain.com</key>
    <dict>
        <!--Include to allow subdomains-->
        <key>NSIncludesSubdomains</key>
        <true/>
        <!--Include to allow HTTP requests-->
        <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
        <true/>
        <!--Include to specify minimum TLS version-->
        <key>NSTemporaryExceptionMinimumTLSVersion</key>
        <string>TLSv1.1</string>
    </dict>
 </dict>
</dict>

A: Steps:

*

*Open your project in xcode.

*Right click on info.plist.

*Choose Open As Source code.

*Add below code before end of </dict> tag.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

A: Ok, got a solution.
It was because of an empty object on body when sending 'GET' request.
checking if it is empty and making it undefined solved the problem.


text:
Q: How to create a 2 dimensional array in C? I want to create a 2 dimensional array in C that will be filled with values from a text file. These values are integers and contain 5 rows by 10 columns. Each integer is separated by a space and each column by an end of line.
I am using int[ , ] xxx = new int[5,10];
I am getting 9 errors, ranging from C2143, C3409, C2059. What am I doing wrong?

A: If you can do it with a compile time allocation and you don't need the pointer then:
int x[5][10];


text:
Q: Spring HATEOAS: Practicable for a microservice architecture? I know this question was already asked but I could not find a satisfying answer.
I started to dive deeper in building a real restful api and I like it's contraint of using links for decoupling. So I built my first service ( with java / spring ) and it works well ( although I struggled a bit with finding the right format but that's another question ). After this first step I thought about my real world use case. Micorservices. Highly decoupled individual services. So I made a my previous scenario and I came to some problems or doubts.
SCENARIO:
My setup consists of a reverse proxy ( Traefik which works as service discovery and api gateway) and 2 Microservices. In addition, there is an openid connect security layer. My services are a Player service and a Team service.
So after auth I have an access token with the userId and I am able to call player/userId to get the player information and teams?playerId=userId to get all the teams of the player.
In my opinion, I would in both responses link the opposite service. The player/userId would link to the teams?playerId=userId and vice versa.
QUESTION:
I haven't found a solution besides linking via a hardcoded url. But this comes with so many downfalls as I can't imagine that this a solution used in real world applications. I mean just imagine your api is a bit more advanced and you have to link to 10 resources. If something changes, you have refactor and redeploy them all.
Besides the synchonization problem, how do you handle state in such a case. I mean, REST is all about state transfer. So I won't offer the link of the player to teams service if the player is in no team. Of course I can add the team ids as attribute to the player to decide whether to include the link or not. But this again increases coupling between the services.
The more I dive in the more obstacles I find and I'm about to just stay with my spring rest docs and neglect the core of Rest which I is a pity to me.

A:
Practicable for a microservice architecture?

Fielding, 2000

The REST interface is designed to be efficient for large-grain hypermedia data transfer, optimizing for the common case of the Web, but resulting in an interface that is not optimal for other forms of architectural interaction.

Fielding 2008

REST is intended for long-lived network-based applications that span multiple organizations.

It is not immediately clear to me that "microservices" are going to fall into the sweet spot of "the web".  We're not, as a rule, tring to communicate with a microservice that is controlled by another company, we often don't get a lot of benefit out of caching, or code on demand, or the other rest architectural constraints.  How important is it to us that we can use general purpose components to exchange information between different microservices within our solution? and so on.

If something changes, you have refactor and redeploy them all.

Yes; and if that's going to be a problem for us, then we need to invest more work up front to define a stable interface between the two.  (The fact that we are using "links" isn't special in that regard - if these two things are going to talk to each other, then they are going to need to speak a common language; if that common language needs to evolve over time (likely) then you need to build those capabilities into it).
If you want change over time, then you have to plan for it.
If you want backwards/forwards compatibility, then you have to plan for it.
Your identifiers don't need to be static - there are lots of possible ways of deferring the definition of an identifier; the most obvious being that you can use another identifier to look up the identifier you want, or the formula for calculating it, or whetever.
Think about how Google works - the links they use change all the time, but it doesn't matter because the protocol (refresh your bookmarked search form, enter your text in "the" one field, click the button) hasn't changed in 20 years.  The interface is stable (even though the underlying spellings of the identifiers is not) and that's enough.


text:
Q: div inside ul prevents selecting first child li selector I am working in a CMS. first-child selector not working as there is a div inside the ul. When i remove the div in console, first-child selector applies. I cant change the DOM nor use JS. So what would be the solution. Thanks in advance.

ul.tab-list li:first-child img{
     max-width: 145px;
     height: 59px;
}

      Link Text

A: To select the  inside the
 that is the subsequent sibling of the
 that is the first child of a
:
ul > div:first-child + li img {
  // ...
}


text:
Q: DefaultImagePath no longer working In my Xamarin.Android project I have a loading image in drawable-nodpi folder.
I show this image while I'm loading other images from a url. Here's how I retrieve it;

local:MvxBind="ImageUrl Picture; DefaultImagePath 'res:loading'

However, ever since the update to 3.5.1, the image no longer appears. I couldn't see anything that could change this in version notes.
Did the binding change somehow, or is this a bug, or am I doing something wrong?
Thanks in advance.


text:
Q: Dragging a Div in jQuery - fine when mouse is slow, but fails on fast mouse movement I want to drag a div around using my own jQuery code.
This example on jsfiddle works fine when the mouse movements are slow
http://jsfiddle.net/craic/kr7Un/
But any fast movement pulls the mouse out of the box and the tracking is lost.
jQuery UI draggable doesn't have this problem and tracks just fine regardless of how fast you move: http://jqueryui.com/demos/draggable/
But I want to roll my own simple version so that I can integrate it with Raphael, key presses, etc. I've looked at the jQuery UI draggable source but it is, for me, pretty impenetrable (800 lines).
I don't think it is an issue with event bubbling... any ideas?

A: There are 2 issues.  One is that you are canceling the drag when the mouse leaves the element, you don't want to do that.  The 2nd is that the mousemove is only on box, once the cursor is out of the box it is no longer going to execute the mousemove.  You can store the element which you are dragging and then add the mousemove to the entire page instead.
EDIT: Actually, I guess the mouseup should really also be on the document just in case you release the mouse click during a fast movement and your cursor is outside the box.  Updated the jsfiddle.
See here:
http://jsfiddle.net/Jjgmz/1/
var box = $('#box');

box.offset({
    left: 100,
    top: 75
});

var drag = {
    elem: null,
    x: 0,
    y: 0,
    state: false
};
var delta = {
    x: 0,
    y: 0
};

box.mousedown(function(e) {
    if (!drag.state) {
        drag.elem = this;
        this.style.backgroundColor = '#f00';
        drag.x = e.pageX;
        drag.y = e.pageY;
        drag.state = true;
    }
    return false;
});

$(document).mousemove(function(e) {
    if (drag.state) {
        drag.elem.style.backgroundColor = '#f0f';

        delta.x = e.pageX - drag.x;
        delta.y = e.pageY - drag.y;

        $('#log').text(e.pageX + ' ' + e.pageY + ' ' + delta.x + ' ' + delta.y);

        var cur_offset = $(drag.elem).offset();

        $(drag.elem).offset({
            left: (cur_offset.left + delta.x),
            top: (cur_offset.top + delta.y)
        });

        drag.x = e.pageX;
        drag.y = e.pageY;
    }
});

$(document).mouseup(function() {
    if (drag.state) {
        drag.elem.style.backgroundColor = '#808';
        drag.state = false;
    }
});


text:
Q: Ragged CSV read with Dask produces DtypeWarning - option to ignore "nan" on load? I'm trying to use Dask to read a large ~500MB CSV file which contains pairs of float and str columns that are read together, resulting in two lists being read into memory at a time. This works without errors, but I get a DtypeWarning since it's a ragged CSV (the column lengths differ significantly between pairs) and it mixes nan (float) with strings before I can filter then out with .dropna().
Data structure (much larger in practice):
Col1: [1, 2, 3, 4, nan, nan, nan] -> (ok, no warning)
Col2: ['A', 'B', 'C', 'D', nan, nan, nan] -> (mixed str and float; DtypeWarning)

I want to avoid using low_memory=False since this significantly impacts execution time  (~6x slower), but it feels like good practice to not just ignore the error.
Is there a way to improve on the below example code to prevent the above warning?
import pandas as pd
import dask.dataframe as dd

length = 10000000
ratio = 0.9
A = {'A': [0.07]*length, 'B': ['a']*int(length*ratio) + [float('nan')]*(length-int(length*ratio))}
pd.DataFrame(A).to_csv('testing.csv')
df = dd.read_csv('testing.csv')['B'].compute().dropna().tolist()

A: Some suggestions:

*

*If the file fits into memory, it's often more convenient to use plain pandas. The gain from parallel processing of dask kicks in for large tasks/files.

*It might be worth specifying dtype explicitly, e.g. dtype='str' or as appropriate.

A: Answering my own question:
While I was originally concerned about execution time, I found that splitting the file into 10 smaller csv files led to faster extraction of the headers (~1 second total instead of ~5 seconds for one large file) when using pandas. This puts it on-par with the execution time of dask to prepare its csv "representations". The time to then load the columns that I'm after is actually faster than dask using this method, even when low_memory=False is used (<1 second for pandas vs ~3 seconds for dask).
This seems to address the issue efficiently, especially when compared to loading one large csv in pandas (~60 seconds becomes ~2 seconds).
Summary:

*

*Split large csv into 10 smaller csv files

*Collect column headers

*Read columns as-needed, using low_memory=False


text:
Q: MySql Troubles with date/time values My table has a "TIME" type column. It has 2 rows with the following values for company a:
04:30:00
04:30:00
I wanted a total of those 2 rows to be written in a csv file using the code
enter code here

$sql2 = "SELECT company, SUM(intervalTime)
   INTO OUTFILE 'd:/myfile/xxx.csv'
   FIELDS TERMINATED BY ','
   FROM june2013 GROUP BY company";

     if (mysqli_query($con,$sql2))
    {
    echo "Summary added to text file successfully";
    }
    else
   {
     echo "Error transferring summary " . mysqli_error($con);
    }

The results were transferred to a csv file with the following values:
company a   86000
company b   420000
company c   292000
Total of 04:30:00 + 04:30:00 should be 9 hours. I got a total of 4300 + 4300.
Any idea how I solve this problem?
Thanks a lot !

A: You can't just SUM a time column like that, you need to convert it into a numeric value first (maths works with numbers).
Try this:
$sql2 = "SELECT company, SEC_TO_TIME( SUM( TIME_TO_SEC( intervalTime ) ) )
   INTO OUTFILE 'd:/myfile/xxx.csv'
   FIELDS TERMINATED BY ','
   FROM june2013 GROUP BY company";

A: I assume that for each company there are two rows. Then, this query might help:
select
    t1.company AS com,
    addtime(
        (select intervalTime from june2013 AS t2 where t2.company = t1.company LIMIT 1),
    (select intervalTime from june2013 AS t2 where t2.company = t1.company LIMIT 1, 1)
) AS dif
into outfile 'd:/myfile/xxx.csv'
FIELDS TERMINATED BY ','
from june2013 as t1
group by t1.company;

The dates are summed correctly using function addtime(time1, time2). See mysql documentation.


text:
Q: Can not execute Sonar: Fail to decorate I installed a sonar server on my own pc (Windows XP), and I deployed sonar on Tomcat with a MySQL database.
I successfully analysed an old project. But with my current project, I get this exception when trying to execute mvn sonar:sonar:
EDIT:
[INFO] [14:39:37.254] Sensor CoberturaSensor done: 218 ms
[INFO] [14:39:37.254] Sensor Maven dependencies...
[INFO] [14:39:41.426] Sensor Maven dependencies done: 4172 ms
[INFO] [14:39:41.848] Execute decorators...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:53.354s
[INFO] Finished at: Tue May 15 14:39:43 CEST 2012
[INFO] Final Memory: 21M/138M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:sonar-maven-plugin:2.0:sonar (d
efault-cli) on project XXX: Can not execute Sonar: Fail to decorate 'com.myPackage
.myClass': 793 -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal o
rg.codehaus.mojo:sonar-maven-plugin:2.0:sonar (default-cli) on project XXX: Can
not execute Sonar
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor
.java:217)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor
.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor
.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProje
ct(LifecycleModuleBuilder.java:84)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProje
ct(LifecycleModuleBuilder.java:59)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBu
ild(LifecycleStarter.java:183)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(Lifecycl
eStarter.java:161)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Laun
cher.java:290)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.jav
a:230)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(La
uncher.java:409)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:
352)
Caused by: org.apache.maven.plugin.MojoExecutionException: Can not execute Sonar

        at org.codehaus.mojo.sonar.Bootstraper.executeMojo(Bootstraper.java:118)

        at org.codehaus.mojo.sonar.Bootstraper.start(Bootstraper.java:65)
        at org.codehaus.mojo.sonar.SonarMojo.execute(SonarMojo.java:90)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(Default
BuildPluginManager.java:101)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor
.java:209)
        ... 19 more
Caused by: org.sonar.api.utils.SonarException: Fail to decorate 'com.myPackage.myClass
'
        at org.sonar.batch.phases.DecoratorsExecutor.executeDecorator(Decorators
Executor.java:84)
        at org.sonar.batch.phases.DecoratorsExecutor.decorateResource(Decorators
Executor.java:70)
        at org.sonar.batch.phases.DecoratorsExecutor.decorateResource(Decorators
Executor.java:63)
        at org.sonar.batch.phases.DecoratorsExecutor.decorateResource(Decorators
Executor.java:63)
        at org.sonar.batch.phases.DecoratorsExecutor.execute(DecoratorsExecutor.
java:55)
        at org.sonar.batch.phases.Phases.execute(Phases.java:94)
        at org.sonar.batch.bootstrap.ProjectModule.doStart(ProjectModule.java:14
3)
        at org.sonar.batch.bootstrap.Module.start(Module.java:83)
        at org.sonar.batch.bootstrap.BatchModule.analyze(BatchModule.java:115)
        at org.sonar.batch.bootstrap.BatchModule.doStart(BatchModule.java:105)
        at org.sonar.batch.bootstrap.Module.start(Module.java:83)
        at org.sonar.batch.bootstrap.BootstrapModule.doStart(BootstrapModule.jav
a:109)
        at org.sonar.batch.bootstrap.Module.start(Module.java:83)
        at org.sonar.batch.bootstrapper.Batch.startBatch(Batch.java:72)
        at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:59)
        at org.sonar.maven3.SonarMojo.execute(SonarMojo.java:143)
        at org.codehaus.mojo.sonar.Bootstraper.executeMojo(Bootstraper.java:113)

        ... 23 more
Caused by: java.lang.ArrayIndexOutOfBoundsException: 793
        at org.sonar.plugins.core.timemachine.tracking.HashedSequenceComparator.
equals(HashedSequenceComparator.java:34)
        at org.sonar.plugins.core.timemachine.ViolationTrackingBlocksRecognizer.
computeLengthOfMaximalBlock(ViolationTrackingBlocksRecognizer.java:48)
        at org.sonar.plugins.core.timemachine.ViolationTrackingDecorator.mapViol
ations(ViolationTrackingDecorator.java:130)
        at org.sonar.plugins.core.timemachine.ViolationTrackingDecorator.decorat
e(ViolationTrackingDecorator.java:70)
        at org.sonar.batch.phases.DecoratorsExecutor.executeDecorator(Decorators
Executor.java:79)
        ... 39 more

I don't understand where the problem comes from. Please anyone have an answer? Can it come from my POM configuration?
PS: the command lines mvn clean install and mvn site work correctly...

A: You're facing a bug of Sonar 3.0 (=> http://jira.codehaus.org/browse/SONAR-3442). We have release Sonar 3.0.1 (see http://www.sonarsource.org/downloads/) that fixes this issue.


text:
Q: OCS 2007 R2 A/V NAT - outside client trying internal IPs I have an existing OCS 2007 R2 install (single server internal, single Edge Server). It's been running for a while, and now I am trying to change its configuration. We have been using a NIC directly connected to the public network for A/V Edge, as R1 required, and I am changing it so that the A/V Edge is connected to the public Internet via NAT, behind our ISA server.
As required, we have our internal DNS server configured so that the A/V Edge machine pulls up the public IP address when it queries the A/V Edge FQDN. In addition, I went into the A/V Edge configuration, and told it to enable NAT.
Internal clients can use the A/V fine. However, external clients are doing something very strange. A packet capture on the external client machine show that it sets up the conversation with the usual chatter to the access and conferencing edge servers. Suddenly, instead of trying to access the A/V Edge's public IP, it tries accessing our base domain name's IP address via HTTPS. In other words, instead of looking up av.domain.com, it looks up domain.com. Then, after that, it does actually try the correct public IP address of the A/V Edge Server via port 3478 (TURN).
But here's where it gets weird. After a little more back-and-forth with the access and conferencing edge servers, it then tries the STUN conversation (over ports in the 50,000+ range) with the internal private IP address of our OCS server. Needless to say, these queries go nowhere, and the client is unable to get the audio/video.
Any suggestions?
Thanks!
J.Ja

A: The edge server does the DNS lookup, and passes the IP address. ie it must resolve your av.domain.com to an external IP address.
see this article: Configuring R2 A/V Edge Service for NAT


text:
Q: Truncated MVN CDF I saw a twitter discussion which ended with: the cdf of a truncated multivariate Gaussian / normal does not exist.
Why? Could someone walk me through it? I thought that the CDFs always exist.


text:
Q: Load Android image in React Native I'm trying to load image from Android's drawble resources library using React Native.
I tried to require it like this:
<Image source={require("image!some-image")} />

And:
<Image source={{uri: "some-image", isStatic: true}} />

But no luck.. I know that I can require image from the js path but in this case I need it from the 'res' folder.

A: There are three things that could possibly be wrong.

*

*Android does not support '-' in image names. use '_' instead.

*Ensure that you are rebuilding the app when you add the asset (react-native run-android). This should be done every time you add/modify an asset to the res folder

3.There ought to be a ',' before isStatic.
<Image source={{uri: "some-image" isStatic: true}} />. I'm guessing this was a typo


text:
Q: Refresh partialview in _Layouts.cshtml I have the following partial view:
Login Status
@{
    if (ViewBag.UserId > 0)
    {
        @Html.ActionLink("Log Out", "LogOut", "Home", null);
    }
    else {
        @Html.ActionLink("Log In", "Login", "Home", null);
    }
}

It's just a pretend login status area. Now, the idea is to have this appear in master page for my MVC site, so that it appears on all pages. Here's how I'm rendering it in the _Layout.cshtml file:

   @{ Html.RenderPartial("LoginStatus"); }

What I'd like to have is, when the user clicks either the "Log In" or "Log Out" links, an action is performed (to log the user in/out) and then the partial view is refreshed - but the the rest of the page is left alone.
At the moment, when I click any of the links, the site navigates to "Home/Login" or "Home/Logout". I don't want it to render a view, I'd like to refresh just the partial view, regardless of which page I'm on.
What is the suggested way to do this?
Cheers.
Jas.

A: You could use AJAX. So you could use jquery to unobtrusively AJAXify those links by subscribing for their click event and sending an AJAX request to the corresponding controller action which would return the partial view and update the DOM.

A: Try the @Ajax.ActionLink() method.


text:
Q: Why SSRS formula throws error when not all parameters are selected? My report has 2 multi-valued parameters : TerritoryGroup and Year.
On each page, I'm displaying a Year.
On the first page, I have a page header, and a chart.
On the second page, I still have that page header, and then the report for the parametrized values.
I want the page header of the first page to show the first and the last selected Year.
And on the subsequent pages, I want the page header to show that page Year.
The available 4 Year in my dataset are 2001,2002,2003,2004.
My problem is that the formula I made is working when the 4 Year are selected, but it throws an error when I select less than 4 Year.
Here's my formula :
= IIF(Globals!PageNumber = 1
                ,(IIF(Parameters!Year.Count > 1
                               ,Parameters!Year.Value(0) & " - " & Parameters!Year.Value(Parameters!Year.Count-1)
                                               ,Parameters!Year.Value(0)))
                     ,IIF(Globals!PageNumber = 2
                               ,Parameters!Year.Value(0)
                                               ,IIF(Globals!PageNumber = 3
                                                               ,Parameters!Year.Value(1)
                                                                               ,IIF(Globals!PageNumber = 4
                                                                                ,Parameters!Year.Value(2)
                                                                                ,IIF(Globals!PageNumber = 5
                                                                                ,Parameters!Year.Value(3),"")))))

Could someone help me with this?
Don't hesitate if you need more details.

A: = switch(
Globals!PageNumber = 1 and Parameters!Year.Count = 1 , Parameters!Year.Value(0),
Globals!PageNumber = 1 and Parameters!Year.Count = 2 , Parameters!Year.Value(0) & " -
" & (Parameters!Year.Value(0)+1),
Globals!PageNumber = 1 and Parameters!Year.Count = 3 , Parameters!Year.Value(0) & " -
" & (Parameters!Year.Value(0)+2),
Globals!PageNumber = 1 and Parameters!Year.Count = 4 , Parameters!Year.Value(0) & " -
" & (Parameters!Year.Value(0)+3),
Globals!PageNumber = 2 ,Parameters!Year.Value(0),
Globals!PageNumber = 3 ,Parameters!Year.Value(1),
Globals!PageNumber = 4 ,Parameters!Year.Value(2),
Globals!PageNumber = 5 ,Parameters!Year.Value(3)
)


text:
Q: document.getElementById() returns blank value I use IE11.
I was trying to figure out why my document.getElementById("Courier0") returns blank value.
However when I debug page and open that object,
I noticed ie9_value holds the correct string passed on from page.

Does anyone know how to get the value for this awkward case?
I tried:
if(document.forms[0].Courier0.value)

 if(document.getElementById("Courier0").value)

 var e = document.getElementById("Courier0");
 if(e.options[e.selectedIndex].value)

None of these seem to work.

A: Found the answer here
var e = document.getElementById("Courier0");
 if(e.options[e.selectedIndex].text)


text:
Q: DataTable in Bokeh dashboard; reactive filtering with a slider widget I am trying to use a slider widget in Bokeh to reactively filter a DataTable and I think I am missing something in my code. The table is not updating as I move the slider. Here is my code:-
from operator import index
from bokeh.models.widgets.markups import Div
import numpy as np
from numpy.lib import source
import pandas as pd
from bokeh.io import curdoc,show
from bokeh.layouts import column, row, gridplot,widgetbox
from bokeh.models import ColumnDataSource, CustomJS,Select, Slider, BoxSelectTool, LassoSelectTool, Tabs, Panel, LinearColorMapper, ColorBar, BasicTicker, PrintfTickFormatter, MultiSelect, DataTable, TableColumn
from bokeh.plotting import figure, curdoc
from bokeh.palettes import viridis, gray, cividis, Category20, Category20c
from bokeh.transform import factor_cmap,cumsum
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import classification_report, confusion_matrix, mean_squared_error, r2_score, recall_score, f1_score
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.cluster import KMeans
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from math import pi
from bokeh.transform import cumsum

np.random.seed(42)

print("step 1")
#define the categorical variable
category_a = ['A','B','C']
category_b = ['X','Y','Z']
print("step 2")
df_random = pd.DataFrame({
   'id': np.arange(0, 100),
   'date': pd.date_range(start='1/1/2021', periods=100, freq='D'),
   'month':np.random.randint(1, 12, 100),
   'sensor_1': np.random.uniform(0, 1,100),
   'sensor_2': np.random.uniform(10, 150, 100),
   'sensor_3': np.random.randint(0, 90, 100),
   'sensor_4': np.random.randint(0, 450, 100),
   'sensor_5': np.random.randint(0, 352, 100),
   'categorya': np.random.choice(category_a, 100, p=[0.2, 0.4, 0.4]),
   'categoryb': np.random.choice(category_b, 100, p=[0.6, 0.2, 0.2]),
})

source = ColumnDataSource(data=df_random)

columns = [
    TableColumn(field='id', title='ID'),
    TableColumn(field='date', title='Date'),
    TableColumn(field='month', title='Month'),
    TableColumn(field='sensor_1', title='Sensor 1'),
    TableColumn(field='sensor_2', title='Sensor 2'),
    TableColumn(field='sensor_3', title='Sensor 3'),
    TableColumn(field='sensor_4', title='Sensor 4'),
    TableColumn(field='sensor_5', title='Sensor 5'),
    TableColumn(field='categorya', title='Category A'),
    TableColumn(field='categoryb', title='Category B'),
]

data_table = DataTable(source=source, columns=columns, width=1100, height=280)

slider = Slider(start = 1, end = 100, value = 10, step = 1, title = "i", width = 300)

callback_code = """ i = slider.value;
                    new_data = groupeddf[sensor_2>=slider.value]
                    data_table.source.data = new_data """

callback = CustomJS(args = dict(slider = slider, table = data_table), code = callback_code)
slider.js_on_change('value', callback)

layouttable=widgetbox(slider, data_table)

curdoc().title = "table"
curdoc().add_root(layouttable)

Ideally, I would like to be able to add in more slider widgets to help me filter the data table to a granular level. But for now I would like to be able to get it working at a simple level.
Can anyone point out what I am doing wrong?

A: first widgetbox not supported anymore. you should use row, column etc.
first : slider.on_change('value', update)
create a function that update
def update(attr, old, new):
    upd_slider = df_random[df_random['sensor_2'] > slider.value]
    updated_data ={
        'id': upd_slider['id'],
        'date': upd_slider['date'],
        'month': upd_slider['month'],
        'sensor_1': upd_slider['sensor_1'],
        'sensor_2': upd_slider['sensor_2'],
        'sensor_3': upd_slider['sensor_3'],
        'sensor_4': upd_slider['sensor_4'],
        'sensor_5': upd_slider['sensor_5'],
        'categorya': upd_slider['categorya'],
        'categoryb': upd_slider['categoryb'],
    }
    source.data = updated_data

we cannot change only sensor_2 like source.data['sensor_2] because it change only one value and lens of source would be different.
full code
from operator import index
from bokeh.models.widgets.markups import Div
import numpy as np
from numpy.lib import source
import pandas as pd
from bokeh.io import curdoc,show
from bokeh.layouts import column, row, gridplot,Column
from bokeh.models import ColumnDataSource, CustomJS,Select, Slider, BoxSelectTool, LassoSelectTool, Tabs, Panel, LinearColorMapper, ColorBar, BasicTicker, PrintfTickFormatter, MultiSelect, DataTable, TableColumn
from bokeh.plotting import figure, curdoc
from bokeh.palettes import viridis, gray, cividis, Category20, Category20c
from bokeh.transform import factor_cmap,cumsum
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import classification_report, confusion_matrix, mean_squared_error, r2_score, recall_score, f1_score
from sklearn.preprocessing import StandardScaler, PolynomialFeatures
from sklearn.cluster import KMeans
from sklearn.svm import SVC
from sklearn.decomposition import PCA
from math import pi
from bokeh.transform import cumsum

np.random.seed(42)

print("step 1")
#define the categorical variable
category_a = ['A','B','C']
category_b = ['X','Y','Z']
print("step 2")
df_random = pd.DataFrame({
   'id': np.arange(0, 100),
   'date': pd.date_range(start='1/1/2021', periods=100, freq='D'),
   'month':np.random.randint(1, 12, 100),
   'sensor_1': np.random.uniform(0, 1,100),
   'sensor_2': np.random.uniform(10, 150, 100),
   'sensor_3': np.random.randint(0, 90, 100),
   'sensor_4': np.random.randint(0, 450, 100),
   'sensor_5': np.random.randint(0, 352, 100),
   'categorya': np.random.choice(category_a, 100, p=[0.2, 0.4, 0.4]),
   'categoryb': np.random.choice(category_b, 100, p=[0.6, 0.2, 0.2]),
})

source = ColumnDataSource(data=df_random)

columns = [
    TableColumn(field='id', title='ID'),
    TableColumn(field='date', title='Date'),
    TableColumn(field='month', title='Month'),
    TableColumn(field='sensor_1', title='Sensor 1'),
    TableColumn(field='sensor_2', title='Sensor 2'),
    TableColumn(field='sensor_3', title='Sensor 3'),
    TableColumn(field='sensor_4', title='Sensor 4'),
    TableColumn(field='sensor_5', title='Sensor 5'),
    TableColumn(field='categorya', title='Category A'),
    TableColumn(field='categoryb', title='Category B'),
]
def update(attr, old, new):
    upd_slider = df_random[df_random['sensor_2'] > slider.value]
    updated_data ={
        'id': upd_slider['id'],
        'date': upd_slider['date'],
        'month': upd_slider['month'],
        'sensor_1': upd_slider['sensor_1'],
        'sensor_2': upd_slider['sensor_2'],
        'sensor_3': upd_slider['sensor_3'],
        'sensor_4': upd_slider['sensor_4'],
        'sensor_5': upd_slider['sensor_5'],
        'categorya': upd_slider['categorya'],
        'categoryb': upd_slider['categoryb'],
    }
    source.data = updated_data

data_table = DataTable(source=source, columns=columns, width=1100, height=280)

slider = Slider(start = 1, end = 100, value = 10, step = 1, title = "i", width = 300)
slider.on_change('value', update)

layouttable=Column(slider, data_table)

curdoc().title = "table"
curdoc().add_root(layouttable)


text:
Q: What Oauth2 flow to choose for this particular situation? I have a single page app (call it Collector) on my server and would like my users to have a customizable list of links like :
facebook.com/get_my_latest_posts_about_cats
github.com/get_my_comments_for_repo_LinuxKernel
anynews.com/get_my_soccer_news
They can add new/remove links into their link dialog box every time.
So what I am trying to do is to relieve the user of the pain to login every time in order to get data from the facebook,github,news ... server.
Of course, the first time the user clicks on any of his links he will receive the respective login page of the link (e.g. facebook.com/get_my_latest_posts_about_cats -> facebook.com/login) but afterwards I'll use their access token along with refresh token stored in my Collector database so that they won't have to write their pass and username every next time.
My question :
(Please tell me if at least it makes any sense, so that I don't get any false ideas about how this works)

*

*I don't know what flow should I implement my Collector web app because I'm doing this for the first time, and the whole authentication process is also new for me, so which one actually would fit my needs ?

*I thought about user agent flow, becaue I don't think I want to store the client_secret in my Collector database.

A: For single page apps, it's usually the best to use implicit flow. This way, the access token gets just to the frontend part - stays in the browser, it doesn't get to your Collector backend, because the access token is located in the hash part (behind "#") of  the redirect URL from an OAuth2 server. Then you can store the access token in browser's SessionStorage to survive reloads. But if you use this flow, you must use HTTPS, otherwise it's not secure (the access token is transferred through an insecure channel).
Maybe you will want to get new tokens before current ones expire. It's usually done be using iframes, but it depends on a concrete OAuth2 server implementation. You can check http://openid.net/specs/openid-connect-session-1_0.html for OpenId Connect (which is an OAuth2 extension).


text:
Q: Why itween animations seem to take more time than declared and prevent delayed Destroy() I have this code:
void OnCollisionEnter (Collision collision)
{
    if (canCollide == true) {
        canCollide = false;
        ContactPoint contactPoint = collision.contacts [0];

        GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube);
        cube.transform.localScale = new Vector3 (5, 5, 5);
        cube.transform.position = contactPoint.point;

        iTween.MoveTo (cube, iTween.Hash (
            "y", 40,
            "time", 0.5));
        iTween.MoveTo (cube, iTween.Hash (
            "position", new Vector3 (55, 79, 10),
            "time", 0.5f,
            "delay", 0.5f,
            "oncompletetarget", GameObject.Find ("PlayerCar"),
            "oncomplete", "IncrementGauge"));
        Destroy (cube, 1.1f);

    }

}

This works ok, both animations are in sequence. But the sum of the times shoud be 1 second. But Destroy() cannot be delayed by 1 second, it has to be at least 1.1 second. Why? Can I somehow destroy the cube a bit faster and still have IncrementGauge() fired (1 second on Destroy, prevents firing IncrementGauge()).
Thanks.

A: This happens because the iTween library checks in every Update call if 1.0 second has passed, which can't be exactly 1.0 second because it depends on your framerate and floating point arithmetic is imprecise.
Your problem can be solved by destroying the cube and incrementing the gauge in the same callback method DestroyCubeAndIncrementGauge() passed into the parameteroncomplete as string.
public class CollisionObject : MonoBehaviour
{
    [SerializeField]
    private bool canCollide = true;

    void OnCollisionEnter(Collision collision)
    {
        if (canCollide == true) {
            canCollide = false;
            ContactPoint contactPoint = collision.contacts [0];

            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
            cube.transform.localScale = new Vector3(5, 5, 5);
            cube.transform.position = contactPoint.point;

            iTween.MoveTo(cube, iTween.Hash(
                "y", 40,
                "time", 0.5));
            iTween.MoveTo(cube, iTween.Hash(
                "position", new Vector3 (55, 79, 10),
                "time", 0.5f,
                "delay", 0.5f,
                "oncompletetarget", this.gameObject,
                "oncompleteparams", cube,
                "oncomplete", "DestroyCubeAndIncrementGauge"
            ));
        }
    }

    public void DestroyCubeAndIncrementGauge(GameObject cube)
    {
        // destroy the cube
        Destroy(cube);
        // inform the PlayerCar to IncrementGauge
        GameObject.Find("PlayerCar").SendMessage("IncrementGauge");
    }
}


text:
Q: jquery not working when my laptop connected to internet at work My question is about jquery. Recently I have built a website as a project for a job. And one day the jquery stopped loading. It happened the day before I was fiddling with some jquery code, plus were trying to connect Dreamweaver CS6 with XAMPP thru local host. I am not sure whether it has something to do with it.
The issue with loading jquery is when I am at work and connected to the network by cable. In addition the www.jquery.com seems to be not loading css for my machine, it shows just a plain text and links. The people who are in the same office does have those issues. Moreover I cannot access src="http://code.jquery.com/jquery-latest.js" from my browser.
The interesting thing is that when I connect my laptop to wireless at home, then everything works fine. And the website itself works fine on the remote server. So its only my office computer and laptop when connected to the local network. There was one article which was saying that it might something to do with 'host' file itself, but I checked, nothing different from default.
After researching the web, I have found a quick solution, rather then using src="http://code.jquery.com/jquery-latest.js
I have tried src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js  and it solved an issue of loading the website pages, but not the website www.jquery.com itself.
Anyway I am still looking for a solution, because I would have to make changes to present website. Moreover it is just interesting what it might be. But I cannot figure out what is the issue. Please help me, appreciate it.
Can it be explained why my browser does not show any jquery activity on this website: http://gvweb.es/add-ons/varios/zoomer/zoomer.html  where as I know that there is.
Any idea would be of great value, Thanks a lot.

A: If you cannot access src="http://code.jquery.com/jquery-latest.js" from your browser. Then copy all code from "http://code.jquery.com/jquery-latest.js" & save the codes on a external .js file & call it on head section.

A: in case it is a case with every machine on your work network that no one is able to access www.jquery.com then your network administrator might have some policy which is restricting access to www.jquery.com
You can consult your network administrator on the same for a speedy resolution..

A: It looks like you cannot access that hosted copy of jQuery. This leaves you with a few options:

*

*Download your own copy of jQuery and host it with your application.

*Use an alternative hosted copy of jQuery. Google and Microsoft also host copies of jQuery. You can learn more about them on the jQuery download page.

These solutions only work around the core issue, though. Since you indicate that only your laptop is impacted, this is likely a sign of a much more serious issue. When domains like that no longer resolve correctly, sometimes it's a sign of a virus, malware or other security issue.

A: Suddenly I found a solution.
Apparently I had to override the configurations in the router or access point (dns serve configurations) in order to access and view action (jQuery, javascript) content of certain websites.
So I have followed an internet article: http://kyokasuigetsu25.wordpress.com/2011/01/07/how-to-bypass-open-dns/#comment-799
Brief instruction: Network and Sharing Center-Connections(Local area connection status)-Properties-Internet Protocol Versio 4(TCP/IPv4)-Propeties - General - Use the following DNS server address - Preferred DNS Server 8888 - Alternate DNS server - 8844
And it worked for me.
Thanks to all of you.


text:
Q: How to create custom ReactiveMongo Reader & Writer for object? Let's say I have the following model:
case class Game(var _id: Option[BSONObjectID] = None,
                   name: String,
                   genre: Genre.Kind,
                   var created: Option[DateTime] = None,
                   var updated: Option[DateTime] = None
                  )

I want to store an instance of Game as follows:
{"_id": "ObjectId(12345)", "name": "My Shooter Game", "genre": "Shooter", …}
For Genre I want to store the value as a String, but programmatically I want to deal with types and not values.
So here is what I thought would work:
object Genre {

  sealed trait Kind

  implicit val genreJsonFormat = Json.format[Genre.Kind]

  case object Shooter extends Kind {
    val name = "Shooter"

    override def toString = name
  }

  def getGenre(genre: String) = genre match {
    case Shooter.name => Shooter
    // ...
  }

  implicit object GenreWriter extends BSONDocumentWriter[Genre.Kind] {
    def write(genre: Genre.Kind): BSONDocument =
      BSONDocument("genre" -> genre.toString)
  }

  implicit object GenreReader extends BSONDocumentReader[Genre.Kind] {
    def read(doc: BSONDocument): Genre.Kind = Genre.getGenre(doc.getAs[String]("genre").get)
  }

}

Unfortunately, I get this compile error:

No unapply or unapplySeq function found

For:
implicit val genreJsonFormat = Json.format[Genre.Kind]

Any idea how I can achieve that?

A: The macros from Play JSON do not yet support sealed family, so you have to do it the same way it's done for the BSON handlers.


text:
Q: Why is it necessary to introduce different sets of creation and annihilation operators to quantize the complex K-G field? I am reading Peskin & Schroeder and in chapter 2 (p.21) he quantizes the real K-G field such as:
$$\phi=\int\dfrac{d^3p}{(2\pi)^3}\dfrac{1}{\sqrt{2E_p}}\left(a_pe^{ip·x}+ a^{\dagger}_pe^{-ip·x}\right)$$
in analogy with the harmonic oscillator.
I understand that this allows $\phi=\phi^{\dagger}$ as it should.
The problem arises in exercise 2.2.b) when you are asked to follow the same procedure but for a Complex K-G field and "show that the theory contains two sets of particles of mass m". In this case I don't think the first expression holds true since $\phi=\phi^{\dagger}$ is not always the case. I've seen that the solution is to express the field in terms of two different creation and annihilation operators $a$ and $b^{\dagger}$ in the following way:
$$\phi=\int\dfrac{d^3p}{(2\pi)^3}\dfrac{1}{\sqrt{2E_p}}\left(a_pe^{-ip·x}+ b^{\dagger}_pe^{ip·x}\right)$$
But I don't undersand why. What is the condition on the complex field that forces you to introduce $b^{\dagger}$ ? Is it just to ensure that $\phi$ is different than $\phi^{\dagger}$ ? Later on this b's turn out to be the ladder operators for antifermions, that come as a negative-frequency solution of the Dirac equation, but I don't see the relation between this and my K-G complex field. Can anyone shed some light in this issue?

A: Maybe it would make more sense to turn the question around.
Remember that the operators are essentially the coefficients in the Fourier expansion of the field.  You could just as easily have written
$$\phi = \int \frac{d^3p}{(2\pi)^3} \frac{1}{\sqrt{2E_p}} \left(c_1(p)\ e^{ip\cdot x} + c_2(p)\ e^{-ip\cdot x}\right)$$
The question now becomes what, if anything, do these coefficients have to do with one another?  In the absence of additional information, the answer is "nothing," so you need to use different symbols ($a$ and $b$) for them to reflect this.
On the other hand, if you make the demand that $\phi = \phi^\dagger$, it becomes immediately clear that $c_1 = c_2^\dagger$ so we can just stick with $a$.
From this perspective, the question isn't why you need to add a $b$ for the second coefficient in the complex case; it's why you don't need to add a $b$ for the second coefficient in the real case.


text:
Q: Did Windows update corrupt a Linux partition? I have a dual boot system with Linux Mint 18.1 and Windows 10, which I only use occasionally. I booted into Windows 10, and it started applying updates. Upon restarts I was presented with the:
error: no such partition.
Entering rescue mode...
grub restore>

Most of the threads I found suggested going through all the disks found by ls to find the one with boot, and calling ls (hd0,1) or ls (hd0,msdos1) but all of those resulted in unknown filesystem .
I tried using set prefix=(hd0,1)/boot/grub and set root to similar, but when I ran insmod normal I also got unknown filesystem
So I tried using Rescatux, but it wouldn't recognize a number of the drives (no-flags).
So I tried boot-repair from a pendrive, selected the "Recommended repair" and it said it had succeeded, however when I rebooted, it booted straight into Windows.
So I tried following the instructions for running boot-repair from the live Linux installation disk which recommends running gparted, and this is where I'm getting worried. The screenshot seems to indicate that /dev/sda3 which is my Linux partition, has mostly unallocated space. The swap is there, but my partition, which going by the numbers, seems like it should be dev/sda4 is nowhere to be seen.

Can anyone shed any light on this, and tell me how I might be able to bring that partition back?
I've heard that Windows 10 can be "greedy" when running updates, and steal space from other partitions if the updates don't fit on the Windows partition. Could this be what has happened here? Or could Windows have otherwise corrupted those drives?
So my question is whether anything can be done given what you can see in the above.
There are a few related "grub recovery" questions on SO and other forums, but all of them seem to assume the partition is still there.
I want to ascertain whether this is an issue relating to grub/mbr, in which case I can address it in those terms, or if it's beyond that and I should look at partition recovery.
I ran testdisk, and it's telling me the hard disk seems too small. I don't know what to make of that, or understand how that happened.

A: OK, I think I've come to one resolution, though if anyone has anything to add, feel free!
The part where testdisk lists partitions that can't be recovered is a bit misleading, because you can select through them like menu options, however there is nothing to choose here, you just select continue which provides you with further options, and has no bearing on what entry had focus at the point of hitting enter, so just a quirk in the design of the program.
(This screen answers one part of the question, which is "Can Windows updates corrupt a Linux partition" and the answer to that is sadly YES)
Hit enter continue, you might get another warning about disk size and the geometry being wrong, but I just continued, at which point you get a list of partitions and options:

I decided to use P which prints out the files and dirs, and from those listings you can copy to another location, such as a mounted hard drive.
It shows files that can't be recovered in red, however many of these are actually files that were deleted long ago:

That's not always the case however, and I also found that files marked in red sometimes still copied perfectly, so try before you despair.
Some directories had lots of odd files in them that I didn't recognize, but given the above I can't be sure if these are deleted files showing up, or if those are a result of the file system damage that seems to have happened as a result of the windows update (I suspect the former).
However, some of my files did fail to copy, so there is some data corruption, so it seems I will need to reinstall Linux from scratch. Although this time, without Windows on the same machine, as it just can't be trusted.


text:
Q: pythonic way to combine a lot of startswith statements What is the "pythonic" way to combine a lot of startswith statements?
Here are the details:
I receive various types of messages from a server, which sends them with different first letters in order for receiver to quickly identify and sort them. I wrote a code with a lot of
if message.startswith('A'):
   do_A()
elif message.startswith('B'):
   do_B()

- like statements. However, I feel there is more pythonic way to write the code without many statements, like maybe to make a list of all possible first letters and have one startswith statement.
Other variants with if message[0]=='A' are even better, since it appears to be faster per this, and speed matters to me.

A: Use a dictionary mapping first letter to a function:
message_map = {'A': do_A, 'B': do_B}
dispatch = message_map.get(message[:1])
if dispatch is not None:
    dispatch()

Functions in Python are first-class objects, so you can store them in a dictionary like this.
Note that I used a slice to get the first character; it'll result in an empty string if message happens to be empty, rather than throw an IndexError exception.


text:
Q: How to set up Subversion to support HTTPS? This may be a FAQ but my attempts at getting a straightforward answer from the tigris website failed. All I know is that the admins at our site failed to set up or enable Subversion HTTPS access, and that they claim that WebDAV would be needed for that, but they haven't set that up either.
What's the real low down?
Thanks.

A: I've created an HTTPS: oriented production Subversion server at a previous company with no problems and I don't recall doing anything with WebDAV.
You can start with the Tigris Subversion packages using HTTP: and then fairly easily convert it to HTTPS: using steps just like any normally configured HTTPS: website.  Nothing special that I remember.


text:
Q: Php random order for imported .php pages [solved] Version with 1 result
<?php
srand();
$files = array("folder/content1.php", "folder/content2.php", "folder/content3.php", "folder/content4.php", "folder/content5.php", "folder/content6.php");
$rand = array_rand($files);
include ($files[$rand]);
?>

Version with 5 results (provided by Code Spirit)
<?php
$files = array("folder/content1.php", "folder/content2.php", "folder/content3.php", "folder/content4.php", "folder/content5.php", "folder/content6.php");
foreach (array_rand($files, 5) as $file) {
  include($files[$file]);
}

?>

A: You need a loop.
foreach (array_rand($files, 3) as $file) {
  include($files[$file]);
}


text:
Q: How to copy gradle dependencies between two PCs? How to copy gradle dependencies properly? Local repo is down.
I copied ~/.gradle/caches/modules-2/files-2.1/com.whatever/* from one PC to another PC but it does not pick that com.whatever dependency.
Is there any trick that needs to be done?
Need to have dependencies while repo is down.
Cheers,

A: The gradle cache cannot be transferred to other machine, for resolution follow this process as suggested by James here

A: The Gradle dependency cache is currently not portable, so copying ~/.gradle/caches/modules02 will only work if ~ has the same path on both machines.
If the stability of your repository is not great, you will have to setup another one, potentially file based for ease of setup, and copy into the data found in the Gradle cache respecting the structure of the repository, so something like <group_with_dots_as_file_separator>/<module>/<version>/<module>-<version>.<ext> for a Maven style repo.


text:
Q: How to send generic T to another thread? How to send generic T?
I try to send a generic T to another thread but I'm getting:
error[E0308]: mismatched types
  --> src/main.rs:23:22
   |
23 |             t1.merge(Element(vec![3]));
   |                      ^^^^^^^^^^^^^^^^ expected associated type, found struct `Element`
   |
   = note: expected associated type `<T as Join>::Item`
                       found struct `Element`
   = help: consider constraining the associated type `<T as Join>::Item` to `Element`

Full code:
trait Join {
    type Item;
    fn merge(&mut self, other: Self::Item);
}

#[derive(Debug, Default)]
struct Element(Vec<u8>);

impl Join for Element {
    type Item = Element;
    fn merge(&mut self, mut other: Self::Item) {
        self.0.append(&mut other.0);
    }
}

fn work<T>()
where
    T: Default + Join + Send + Sync + 'static,
{
    let (sender, receiver) = std::sync::mpsc::channel::<(T)>();
    std::thread::spawn(move || {
        while let (mut t1) = receiver.recv().unwrap() {
            t1.merge(Element(vec![3]));
        }
    });

    loop {
        let mut t1 = T::default();
        sender.send(t1);
        std::thread::sleep(std::time::Duration::from_secs(5));
    }
}

fn main() {
    // works!
    let mut e = Element(vec![1]);
    e.merge(Element(vec![2]));

    // bad!
    work::<Element>();
}

Playground link

A: When you use generics you let the caller decide which types must be used by your generic function.
This line in your example t1.merge(Element(vec![3])); is invalid because it assumes T = Element but the caller can chose from infinitely many possible types of T where T != Element which is why the compiler is complaining.
To make your function fully generic you have to do something like add a Default bound to <T as Join>::Item in the function signature and then change the offending line to t1.merge(<T as Join>::Item::default());.
Updated working commented example:
use std::fmt::Debug;

trait Join {
    type Item;
    fn merge(&mut self, other: Self::Item);
}

#[derive(Debug)]
struct Element(Vec<u8>);

// updated Default impl so we can observe merges
impl Default for Element {
    fn default() -> Self {
        Element(vec![1])
    }
}

impl Join for Element {
    type Item = Element;
    fn merge(&mut self, mut other: Self::Item) {
        self.0.append(&mut other.0);
    }
}

fn work<T>() -> Result<(), Box<dyn std::error::Error>>
where
    T: Default + Join + Send + Sync + Debug + 'static,
    <T as Join>::Item: Default, // added Default bound here
{
    let (sender, receiver) = std::sync::mpsc::channel::<T>();
    std::thread::spawn(move || {
        while let Ok(mut t1) = receiver.recv() {
            // changed this to use Default impl
            t1.merge(<T as Join>::Item::default());

            // prints "Element([1, 1])" three times
            println!("{:?}", t1);
        }
    });

    let mut iterations = 3;
    loop {
        let t1 = T::default();
        sender.send(t1)?;
        std::thread::sleep(std::time::Duration::from_millis(100));
        iterations -= 1;
        if iterations == 0 {
            break;
        }
    }

    Ok(())
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // works!
    let mut e = Element(vec![1]);
    e.merge(Element(vec![2]));

    // now also works!
    work::<Element>()?;

    Ok(())
}

playground


text:
Q: AFTER ALTER ON DATABASE gives the old password value in Oracle I am writing a trigger to fetch the 'password' value when 'sys.users$' table gets updated.
CREATE OR REPLACE
TRIGGER Sys_User_Nm_Trg AFTER ALTER ON DATABASE
WHEN (ora_dict_obj_type = 'USER')
DECLARE

CURSOR get_pw IS
SELECT password
FROM sys.user$
WHERE name = ora_dict_obj_name;

user_pw_ VARCHAR2(100);

BEGIN

IF (ora_dict_obj_name != 'SYS' AND ora_dict_obj_name != 'SYSTEM') THEN
  IF (ora_des_encrypted_password IS NOT NULL) THEN

 OPEN get_pw;
 FETCH get_pw INTO user_pw_;
 CLOSE get_pw;

 END IF;
END IF;

END;
/

But this cursor gives the old 'password' not the changed 'password' value. But if I run
SELECT password
FROM sys.user$
WHERE name = ora_dict_obj_name;

in a separate transaction it gives the correct changed value. Is there something that I should change in the trigger to fetch the updated value for the password?


text:
Q: Fastest way to process a python list of tuples In a Django project, I have a python list of tuples like so:
users_and_values = [(user_id,value),(user_id,value),......]

where value can either be 0.0 or 1.0 (float). Given this list, I need to create a new one, which is like so:
[(user_object,value),(user_object,value),......]

where user_object is the object associated with each user_id (containing user attributes and such).
What is the most efficient way to achieve this (performance and correctness both matter)? Currently, I'm trying to achieve that as follows in a Django view:
    user_ids = [user_id for user_id, value in users_and_values]
    user_objs = User.objects.filter(id__in=user_ids)
    context["votes"] = [(user_objs(user_id),value) for user_id, value in users_and_votes]

This gives me the error:

'QuerySet' object is not callable

I could also have tried [(User.object.get(id=user_id),value) for user_id, value in users_and_values], but that would be too many DB calls. So can anyone chime in with what I'm doing wrong, and the correct solution? Thanks in advance.

A: user_objs is an unordered collection of users. You have to manually map the user ids to the corresponding values by iterating over it:
user_ids = [user_id for user_id, value in users_and_values]
user_objs = User.objects.filter(id__in=user_ids)

ids_to_values = dict(users_and_values)  # {id1: value1, ...}
context["votes"] = [(user, ids_to_values[user.id]) for user in user_objs]


text:
Q: How to send a multiple post request in a single batch? I am trying to send multiple POST requests in a single batch.
With these 3 requests we are setting the status on the Notification and Order --> Work Is Done, Complete and Close Report.
Like FIORI.
But in the SAP Gateway Client, only requests 1 and 3 are ok. The status for the Order is still the same.
Maybe one request is blocking the other?
Do I have to create different changesets? And how do I do that?
Request-URI:
/sap/opu/odata/sap/EAM_MALFUNCTION_MANAGE/$batch

Request:
--batch
Content-Type: multipart/mixed; boundary=changeset

--changeset
Content-Type: application/http
Content-Transfer-Encoding: binary

POST C_MaintNotificationTPPerform_user_action?sap-client=320&MaintenanceNotification='100000001882'&DraftUUID=guid'00000000-0000-0000-0000-000000000000'&IsActiveEntity=true&Statusobject='OV100000675500000001'&Targetstatus='O030'&Eventconfiguration='1'&Reasoncodegroup=''&Reasoncode=''&Isadditionalreason=false HTTP/1.1
Content-Type: application/json
sap-contextid-accept: header
Accept: application/json
Accept-Language: en
DataServiceVersion: 2.0
MaxDataServiceVersion: 2.0
Content-Length: 626

--changeset
Content-Type: application/http
Content-Transfer-Encoding: binary

POST C_MaintNotificationTPPerform_user_action?sap-client=320&MaintenanceNotification='100000001882'&DraftUUID=guid'00000000-0000-0000-0000-000000000000'&IsActiveEntity=true&Statusobject='OR000004001747'&Targetstatus='0050'&Eventconfiguration='1'&Reasoncodegroup=''&Reasoncode=''&Isadditionalreason=false HTTP/1.1
Content-Type: application/json
sap-contextid-accept: header
Accept: application/json
Accept-Language: en
DataServiceVersion: 2.0
MaxDataServiceVersion: 2.0
Content-Length: 800

--changeset
Content-Type: application/http
Content-Transfer-Encoding: binary

POST C_MaintNotificationTPPerform_user_action?sap-client=320&MaintenanceNotification='100000001882'&DraftUUID=guid'00000000-0000-0000-0000-000000000000'&IsActiveEntity=true&Statusobject='QM100000001882'&Targetstatus='0051'&Eventconfiguration='1'&Reasoncodegroup=''&Reasoncode=''&Isadditionalreason=false HTTP/1.1
Content-Type: application/json
sap-contextid-accept: header
Accept: application/json
Accept-Language: en
DataServiceVersion: 2.0
MaxDataServiceVersion: 2.0
Content-Length: 755

--changeset--

--batch--


text:
Q: Can I block a syslog message with iptables I've got a few firewalls that I don't personally manage sending junk syslog messages through my ubuntu machine (which acts as a software router).  Is there an easy way for me to block forwarding a particular syslog message (by some text) like I would with with rsyslog or syslog-ng rules using iptables.

A: You could write something horrible with -m u32 --u32 to do this, but iptables really isn't meant to operate at this level, so it'd be really ugly, and probably inefficient and/or unreliable too.


text:
Q: "babel" is read-only with react jsx I am importing babel to my jsx file like below. But i get error for Module build failed: SyntaxError: "babel" is read-only
var babel = require("babel-core");
import { transform } from 'babel-core';
import * as babel from 'babel-core';

A: I guess the error is because you are using same variable name babel.
var babel = require("babel-core");
import * as babel from 'babel-core';

Use different names and try again.


text:
Q: asynchronous code to nested synchronous manner in Meteor/React I have been trying to run data fetching code in a container component and pass it to the display one to reduce using hooks and load time. I tried both await/sync and Meteor's wrapAsync Here is its Docs but I admit I dont really understand this function.
N.B:  The code is pseudo code that explains the basic structure and functionality I need to apply, everything has been imported properly. The code structure and order is the same as the actual code. Thats what matters
Current Result
display component errors out as undefined because the data or t1Doc are empty
Container async/await
const Container = withTracker(({ id, ...rest }) => {
  const t1Handle = Meteor.subscribe("table1");
  const t2Handle = Meteor.subscribe("table2");
  const isLoading = !t1Handle.ready() && !t2Handle.ready();
  const fetchT1Documents = async () => {
  const t1Doc = await t1Collection.findOne(query);
  let t2Doc;
  const fetchT2Documents = async () => {
    t2Doc = await t2Collection.findOne(t1Doc.FK);
  }
  fetchT2Documents();
  parseXmltoJs(t1Doc, (err, result) => {
    fetchAjaxData(result,t2Doc)
    .then((data) => {
    return {
      isLoading,
      t1Doc,
      t2Doc,
      data
    }
  })
});
  }
  fetchT1Documents();

  return {
    isLoading,
    t1,
    ...rest,
  };
})(WithLoading(displayComponent));

Loader
const WithLoading = (Comp) => ({ isLoading, children, ...props }) => {
  if (isLoading) {
    return <Loader />;
  } else {
    return (
      <Fade in={true} timeout={500}>
        <div>
          <Comp {...props}>{children}</Comp>
        </div>
      </Fade>
    );
  }
};

export { WithLoading };

sorry for the bad editing

A: A few tips on this one...
You can make a publication that publishes more than one collection/query, eg table1 and table2. It returns a single handle, that is ready when both collections have data.
No need to do an await on the collection.findOne() calls - these are calls to minimongo (client side cache), and will return either null when the subscription is loading, and will return the data otherwise.
The pattern you are using is excellent, and allows separation of display logic from the grubby data layer :)