text:
Q: How do I add a resource folder to app data? I have a folder that contains many png images in my resources of my WPF application. I would like to add this folder to appdata/roaming. Since there are many images that are sorted in folders, I would prefer to add the whole folder. Is there any way to do this?
By the way, the folder is in a directory called Resources and all the pngs are build as resources in Visual Studio.

A: Here is my code example for your question:
 public void MyCopy()
    {
        //1.You can use the following code to get the path appdata/roaming, and suppose you want to copy the files to NewImageFolder
        string strTarget = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\NewImageFolder\\";
        if (!Directory.Exists(strTarget))
        {
            Directory.CreateDirectory(strTarget);
        }

        //2. Then you need to get the path of your the File to be copied
        string strSource = AppDomain.CurrentDomain.BaseDirectory;
        strSource = strSource.Substring(0, strSource.LastIndexOf("bin")) + "Resources\\Image";

        //3.Copy the file
        DirectoryInfo dir = new DirectoryInfo(strSource);
        FileInfo[] files = dir.GetFiles();
        string strFileName = null;
        foreach (FileInfo file in files)
        {
            strFileName = strSource + "\\" + file.Name;
            File.Copy(strFileName, System.IO.Path.Combine(strTarget, System.IO.Path.GetFileName(strFileName)));
        }
    }


text:
Q: All of system ram not available on Debian OS partition I have a computer with a Windows 7 and a Debian OS disk partition.
The computer has 12GB ram as can be seen when logged in on the Windows 7 OS. However, the Debian partition is only recognizing just under 4GB ram. Why would this be, and how can I fix this?
When I run the "free" command I see the reduced RAM amount as well as when I try to create a virtual machine in Virtual Box with the maximum RAM being allowed for a VM topping off at that same low amount. As far as I understood, (which is not saying much..) OS partitions were only disk partitions not RAM partitions.
Edit:
Running Debian 6 "Squeeze" 32 bit
Output of 'free' command
          total      used    free       ....
Mem:    3619800     386568   3233232    ...
-/+ buffers/cache:   66944   3552856
Swap:    497972         0    497972

I don't have Gnome installed so I'm not really sure how to take a screenshot. But in VirtualBox you have a setting for RAM allocation for VMs and on this Linux partition the option maxes out at 3584MB.

A: 4GB of memory requires 32 bits to store addresses. Most 32-bit processor architectures can only address 4GB of memory, and older x86 CPUs are no exception.
More recent 32-bit x86 CPUs can access more than 4GB of physical memory through a processor feature called PAE.¹ 64-bit x86 CPUs always have PAE.
PAE requires a Linux kernel compilation option. Without this option, the kernel can only address 4GB of RAM, and some of that is lost because it's used by peripherals such as the graphics card. But with this option, the kernel won't work on processors that don't have the PAE feature.
Debian's default kernel is compatible with most x86 processors but can't make use of some features of recent(-ish) processors such as PAE. To use more than 4GB of RAM, install a PAE-enabled kernel and reboot into it. On Debian squeeze, you need the linux-image-2.6-686-bigmem package.
If you have a 64-bit CPU, you can instead install a 64-bit kernel: linux-image-2.6-amd64. With a 64-bit kernel, you can make use of more than 4GB of RAM, and you can run both 32-bit and 64-bit applications. Or you can install a whole 64-bit distribution (the amd64 architecture). To find out whether your processor is a 64-bit one, run grep -w lm /proc/cpuinfo — if a line with flags : … lm … appears, you have a 64-bit CPU.
Note that on a 32-bit system, the size of virtual memory is still limited to 4GB. On Linux, that's split with 1–3GB for the kernel and 1–3GB for the process. This is the limit of addressable memory in a process; a 32-bit system can make use of more than 4GB of RAM because each process can use up to 1–3GB of that RAM. So if you want to run a VirtualBox VM with more than 3GB of RAM, you'll need to install a 64-bit distribution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need help creating PHP regex I've created a template engine, and now I want to get all remaining encapsulated strings ([[name]] or [[[name]]]). I've tried several things, including: ([[(.{2,})]]).
If there is any good tutorial/source on Regex I would greatly appreciate it!

A: To get the ([[...]]) :
preg_match_all('/\(\[\[.*?\]\]\)/',
    "XXX ([[abc]]) YYY ([[def]])",
    $out, PREG_PATTERN_ORDER);
var_dump($out);

For the [[[...]]]
preg_match_all('/\[\[\[.*?\]\]\]/',
    "XXX ([[abc]]) YYY ([[def]])",
    $out, PREG_PATTERN_ORDER);
var_dump($out);


text:
Q: Symfony 6.2 app not working as soon as a Command name is defined docker-compose.yml
version: "3"
services:
  nginx:
    image: nginx:1.23.3
    ports:
      - "8084:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
  php:
    build: .
    volumes:
      - ./api:/var/www/html/

nginx.conf
events {}
http {
    server {
        root /var/www/html/public;
        location / {
            try_files $uri /index.php$is_args$args;
        }
        location ~ \.php$ {
            fastcgi_pass php:9000;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }
    }
}

I installed Symfony Console "symfony/console": "^6.2".
composer.json
{
  "require": {
    "symfony/runtime": "^6.2",
    "symfony/http-kernel": "^6.2",
    "symfony/framework-bundle": "^6.2",
    "symfony/dotenv": "^6.2",
    "doctrine/doctrine-bundle": "^2.8"
  },
  "require-dev": {
    "phpunit/phpunit": "^9.5",
    "symfony/console": "^6.2"
  },
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  },
  "autoload-dev": {
    "psr-4": {
      "Tests\\": "tests/"
    }
  },
  "config": {
    "allow-plugins": {
      "symfony/runtime": true
    }
  }
}

I added a src/cli.php
<?php
require __DIR__.'/../vendor/autoload.php';

use Symfony\Component\Console\Application;

$application = new Application();

$application->add(new \App\Commands\ExtractAuthorPortraitsCommand());
$application->run();

I added a command
<?php declare(strict_types=1);

namespace App\Commands;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ExtractAuthorPortraitsCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        return Command::SUCCESS;
    }
}

As soon as I add a name to the command
#[AsCommand(name: 'app:extract-author-portraits')]
class ExtractAuthorPortraitsCommand extends Command

a request to the Symfony app (http://localhost:8084) then gives me an empty response.
And the PHP log shows Console Tool stuff which does not come in the log when Command has no name.
Console Tool
Usage:
  command [options] [arguments]
Options:
  -h, --help            Display help for the given command. When no command is given display help for the list command
  -q, --quiet           Do not output any message
  -V, --version         Display this application version
      --ansi|--no-ansi  Force (or disable --no-ansi) ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands:
  completion                    Dump the shell completion script
  help                          Display help for a command
  list                          List commands
 app
  app:extract-author-portraits
172.21.0.3 -  18/Jan/2023:07:28:25 +0000 "GET /index.php" 200

Any ideas?


text:
Q: I have a issue with creating a form in reactjs I'm having an error when using handleChange("firstName")
I tried to call the function in others ways
    const handleChange = input => e => {
      this.setState({ [input]: e.target.value });
    };

export class FormUserDetails extends Component {
  continue = e => {
    e.preventDefault();
    debugger;
    this.props.nextStep();
  };
  render() {
    const { values, handleChange } = this.props;
    return (

Who are you ?

        <form onSubmit={this.continue}>

            <input
              class="form-input"
              type="text"
              placeholder="Surname"
              name="firstname"
              defaultValue={values.firstName}
              onChange={handleChange("firstName")}
              required
            />

          <input type="submit" value="Next" class="submit-button" />
        </form>

    );
  }
}

export default FormUserDetails;

TypeError: handleChange is not a function
FormUserDetails.render
src/components/form/FormUserDetails.js:27

  24 |   placeholder="Surname"
  25 |   name="firstname"
  26 |   defaultValue={values.firstName}
> 27 |   onChange={handleChange("firstName")}
     | ^  28 |   required
  29 | />
  30 | <input

Thanks you for your help

A: You don't need to return a function, just do:
handleChange = e => {
  this.setState({
    [e.target.name]: e.target.value
  });
};

And then you can call it from onChange without params, provided you change the input name to firstName instead of firstname:
onChange={this.props.handleChange}

A: Another solution like the official docs
  handleChange(event) {
this.setState({value: event.target.value});

}
And you call it
render() {
return (
  <form onSubmit={this.handleSubmit}>

      Name:
      <input type="text" value={this.state.value} onChange={this.handleChange} />

    <input type="submit" value="Submit" />
  </form>
);

}


text:
Q: EventAggregator with MultiThreads I am having a little problem with the IEventAggregator, let me explain
public class doSomething
{
    public doSomething()
    {
        Action<AddEvent> GetAddSolution = s => this.Add(s.a, s.b);
        IEventAggregator.GetEvent<AddEvent>().Subscribe(GetAddSolution);
    }

    public void Add(int a, int b)
    {
        IEventAggregator.GetEvent<AddSolutionEvent>().Publish(new AddSolutionEventArgs(a + b));
    }
}

Let above be a Demo service, in my case it is a long running one, now if i have multiple threads calling Add(a,b) using the EventAggrigator, the last thread which published request gets all the responses
how do i return response to the thread which published the request event.
Please Provide Guidance.
Thank you in Advance.

A: Got the answer my self, its simple, using event Filters in eventaggregator. the filter delegate filters the events.


text:
Q: Asp MVC PayPal Transaction I am trying to make a paypal handler. You type a money amount into an input, than you press donate button, you will be forwarded to the paypal page, you can login and than press continue button... The problem after I press the continue button its forward me back to the https://www.example.org/Account/PayPalHandler/ page, and thats it all. What is missing from my code to complete the paypal transaction?
[HttpPost]
        public ActionResult DoPaymentPaypall(UserModel User_)
        {
            ResultModel<ManageAccountListModel> res_ = new ResultModel<ManageAccountListModel>();
            res_.DataSelect = new ManageAccountListModel();

            if (SessionManagement.LoginnedUser != null)
            {
                var config = ConfigManager.Instance.GetProperties();
                var accessToken = new OAuthTokenCredential(config).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                string moneyCount_ = User_.moneycount.ToString();
                var payment = Payment.Create(apiContext, new Payment
                {
                    intent = "sale",
                    payer = new Payer
                    {
                        payment_method = "paypal"
                    },
                    transactions = new List<Transaction>
                                    {
                                        new Transaction
                                        {
                                            description = "Donation",
                                            invoice_number = "001",
                                            amount = new Amount
                                            {
                                                currency = "USD",
                                                total = moneyCount_,
                                                details = new Details
                                                {
                                                    tax = "0",
                                                    shipping = "0",
                                                    subtotal = moneyCount_
                                                }
                                            },
                                            item_list = new ItemList
                                            {
                                                items = new List<Item>
                                                {
                                                    new Item
                                                    {
                                                        name = "Donation",
                                                        currency = "USD",
                                                        price = moneyCount_,
                                                        quantity = "1",
                                                        sku = "Custom Package"
                                                    }
                                                }
                                            }
                                        }
                                    },
                    redirect_urls = new RedirectUrls
                    {
                        return_url = "https://www.example.org/Account/PayPalHandler/",
                        cancel_url = "https://www.example.org/"
                    }
                });

                res_.SuccessMessage = payment.links.ToList()[1].href;

            }
            res_.Success = true;
            return new JsonResult { Data = res_, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

A: Your code above seems to only show the initial/start of the process...so assuming you mean after the user has approved your request to use Paypal for payment (don't confuse this as "the payment" - this step only indicates that the user as agreed to use Paypal for payment) you'll need to Execute the payment.
The link shows the full flow

*

*Create payment (this is what your code above maps to) - you'll get a payment id in this step

*redirect user to Paypal approval_url for approval (of the details in the Create above) using the id you recieved

*Paypal sends user back to your site with info on how to Execute payment (if user approves)

*Execute payment (this is done at  your site/app)

Hth


text:
Q: Processing: transparent image over curves Im new to Processing. I would like to put a .jpg or .png over curves and ellipses, so that they can see only where the image is transparent.
My code is below. The problem with it is that the transparent area is not fully transparent, but transparent white and the not-transparent parts have also decreased opacity.
    PImage img;

    void setup() {
      size(300,500);
      frameRate(30);
      strokeWeight(4);
      img = loadImage("sziluettmeret.jpg");
    }

   void draw() {
        background(0, 50, 70);
        stroke(0,70,90);
        noFill();
        beginShape();
        curveVertex(-100,  -100);
        curveVertex(10, 10);
        curveVertex(250,  250);
        curveVertex(300,  300);
        endShape();

       fill(255);
       ellipse(20 ,20,15,15);

       noFill();
       tint(255, 100);
       image(img, 0, 0);
    }

UPDATE:
I have this in my code:
    loadPixels();
    for(int i=0; i < img.pixels.length; i++) {
    tmpColor = img.pixels[i];
    tmpRed = red(tmpColor);
    tmpGreen = blue(tmpColor);
    tmpBlue = green(tmpColor);
    tmpAlpha = 255 - ((tmpRed + tmpGreen + tmpBlue)/3);
    img.pixels[i] = color(2*tmpRed,tmpGreen/2,tmpBlue,0);
    if(0xFFFFFF == tmpColor)

      }
     updatePixels();

The picture does not become transparent. (But it becomes purple, so the loop runs on every pixel for sure)

A: tint() doesn't do greenscreening. It'll recolor your image (if you use a non-neutral colour), and set the mix transparancy, so with tint(255,100), you effective gave the image an opacity of (approximately) 0.39
If you want to do greenscreening (or in your case, whitescreening), you want to run through the image's pixels when you load the image, then set opacity to 0 whenever r/g/b are 255, effectively "removing" all your white pixels.


text:
Q: Running my application in debug ends without any exceptions being thrown I'm using visual studio 2010 sp1, I have an application, and when I run it in debug, the application just stops running. It never pops up highlighting where the unhandled exception occurred, I even have the AppDomain.CurrentDomain.UnhandledException being listened to, and writing any exceptions to a text file, but it never seems to fire.
Any ideas what is going on? If I create a brand new project, and add all my source code to it, it seems to fix it, but eventually whatever setting is being changed is being triggered.


text:
Q: Animating WordPress (Twenty Thirteen) sub-menu I'm trying to add an animation to the dropdown menu of wordpress. I'm using this code:
jQuery(function() {
    jQuery("ul#menu-menu-1").hover(function() {
        jQuery(this).find('ul.sub-menu')
            .stop(true, true).delay(50).animate({ "height": "show", "opacity": "show" }, 200 );
    }, function(){
        jQuery(this).find('ul.sub-menu')
            .stop(true, true).delay(50).animate({ "height": "hide", "opacity": "hide" }, 200 );
    });

});

But 1) it goes ON an already "in position" sub-menu and 2) the sub-menu of the first parent is instead the sub-menu of the second one...

A: Your selector is of the entire navigation menu, causing all of the sub-menus to appear when the mouse hovers over any part of the menu.
Try using jQuery("ul#menu-menu-1 li").hover(function() { which will select the individual li elements within the menu instead.
Then use .children instead of .find, as to target li elements that are direct children of the menu item being hovered upon.
jQuery(function() {
    jQuery("ul#menu-menu-1 li").hover(function() {
        jQuery(this).children('ul.sub-menu')
            .stop(true, true).delay(50).animate({ "height": "show", "opacity": "show" }, 200 );
    }, function(){
        jQuery(this).children('ul.sub-menu')
            .stop(true, true).delay(50).animate({ "height": "hide", "opacity": "hide" }, 200 );
    });
});

For the animation to appear, remove the following from your styles.css near line 906
ul.nav-menu li:hover > ul, .nav-menu ul li:hover > ul {
    display: block;
}


text:
Q: How to create a looping animation by continuous translating an image? By using a repeating image like this,

is it possible to create animation like this?

A: I figured it out

MainActivity.java:
public class MainActivity extends Activity {

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

        final int screenWidth = getScreenDimensions(this).x;
        final int waveImgWidth = getResources().getDrawable(R.drawable.wave).getIntrinsicWidth();
        int animatedViewWidth = 0;
        while (animatedViewWidth < screenWidth) {
            animatedViewWidth += waveImgWidth;
        }
        animatedViewWidth += waveImgWidth;

        View animatedView = findViewById(R.id.animated_view);
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) animatedView.getLayoutParams();
        layoutParams.width = animatedViewWidth;
        animatedView.setLayoutParams(layoutParams);

        Animation waveAnimation = new TranslateAnimation(0, -waveImgWidth, 0, 0);
        waveAnimation.setInterpolator(new LinearInterpolator());
        waveAnimation.setRepeatCount(Animation.INFINITE);
        waveAnimation.setDuration(2500);

        animatedView.startAnimation(waveAnimation);
    }

    public static Point getScreenDimensions(Context context) {
        int width = context.getResources().getDisplayMetrics().widthPixels;
        int height = context.getResources().getDisplayMetrics().heightPixels;
        return new Point(width, height);
    }

}

activity_main.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <View
        android:id="@+id/animated_view"
        android:layout_width="match_parent"
        android:layout_height="74dp"
        android:background="@drawable/wave_repeating_bg" />

</FrameLayout>

wave_repeating_bg.xml:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/wave"
    android:tileMode="repeat" />

drawable-xxhdpi/wave.jpg:

A: bottom to top infinite animation i implement this way. it's too easy just use two image and animated one after another.

Inside MainActivity.java

        imageView_background1 = (ImageView) findViewById(R.id.imageView_background1);
        imageView_background1.setVisibility(View.GONE);
        imageView_background1.setVisibility(View.VISIBLE);
        Animation mAnimation = new TranslateAnimation(
                TranslateAnimation.ABSOLUTE, 0f,
                TranslateAnimation.ABSOLUTE, 0f,
                TranslateAnimation.RELATIVE_TO_PARENT, 0f,
                TranslateAnimation.RELATIVE_TO_PARENT, -1f);
        mAnimation.setDuration(10000);
        mAnimation.setRepeatCount(-1);
        mAnimation.setRepeatMode(Animation.INFINITE);
        mAnimation.setInterpolator(new LinearInterpolator());
        imageView_background1.setAnimation(mAnimation);

        imageView_background2 = (ImageView) findViewById(R.id.imageView_background2);
        imageView_background2.setVisibility(View.VISIBLE);
        Animation mAnimation1 = new TranslateAnimation(
                TranslateAnimation.ABSOLUTE, 0f,
                TranslateAnimation.ABSOLUTE, 0f,
                TranslateAnimation.RELATIVE_TO_SELF, 1f,
                TranslateAnimation.RELATIVE_TO_SELF, 0f);
        mAnimation1.setDuration(10000);
        mAnimation1.setRepeatCount(-1);
        mAnimation1.setRepeatMode(Animation.INFINITE);
        mAnimation1.setInterpolator(new LinearInterpolator());
        imageView_background2.setAnimation(mAnimation1);

Inside activity_main.xml (use same image both imageview)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/ic_splash_background">
    <ImageView
        android:id="@+id/imageView_background1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/ic_splash_categories" />
    <ImageView
        android:id="@+id/imageView_background2"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/ic_splash_categories" />
</FrameLayout>


text:
Q: Database File In Drop Box Shared Folder Can a software database file be saved and kept in a shared folder like drop box and be accessed and used (whether simultaneously or not) from more than one computers? A quickbooks database file is an example. Can it be centrally located on a dropbox folder and be accessed by a computer from another location getting the benefits of synced and up to date info?

A: Generally-speaking, no this will not work. Dropbox uses asynchronous replication. Unless the application is specifically designed with this use case in mind, your data will be hopelessly corrupted.
In the case of standard RDBMS engines, cooperation with the DB engine itself is required to implement reliable replication.
In short, very very rarely is replication as simple as copying files around (which is all Dropbox is doing).


text:
Q: Building a list of enum flags I have this method that accepts multiple JobSetting flags
private void ProcessTheData(string[] dataFiles, PictureBox sender, JobSetting? jobSetting)

The Flags enum is this
[Flags]
enum JobSetting
{
    ForcePrint = 1,
    ForceProof = 2,
    UseDefault = 4,
    SkipImposition = 8,
    HighPriority = 16,
    SetDP = 32
}

I have a event handler that looks at a CheckboxList and I build a list of flags based on the options that are checked.
JobSetting js;
if (((Control)sender).Name.ToLower().Contains("proof"))
{
    if (chkbxList_Proof.CheckedItems.Contains("Skip Imposition") && chkbxList_Proof.CheckedItems.Contains("High Priority") && chkbxList_Proof.CheckedItems.Contains("_SetDP"))
    {
        js = (JobSetting.ForceProof | JobSetting.SkipImposition | JobSetting.HighPriority | JobSetting.SetDP);
    }
    else if (chkbxList_Proof.CheckedItems.Contains("Skip Imposition") && chkbxList_Proof.CheckedItems.Contains("High Priority"))
    {
        js = (JobSetting.ForceProof | JobSetting.SkipImposition | JobSetting.HighPriority);
    }
    else if (chkbxList_Proof.CheckedItems.Contains("Skip Imposition"))
    {
        js = (JobSetting.ForceProof | JobSetting.SkipImposition);
    }
    else if (chkbxList_Proof.CheckedItems.Contains("High Priority"))
    {
        js = (JobSetting.ForceProof | JobSetting.HighPriority);
    }
    else if (chkbxList_Proof.CheckedItems.Contains("_SetDP"))
    {
        js = (JobSetting.ForceProof | JobSetting.SetDP);
    }
    else
    {
        js = JobSetting.ForceProof;
    }
}

It all works... but I feel like that has to be least effective way to build my list of flags.
I would like to build it in this fashion, or whatever correct way already exists to do it.
JobSeetings js = JobSetting.ForceProof;
if(chkbxList_Proof.CheckedItems.Contains("Skip Imposition"))
{
    js.add(JobSetting.SkipImposition)
}
if(chkbxList_Proof.CheckedItems.Contains("High Priority"))
{
    js.add(JobSetting.HighPriority)
}

A: You could just combine the flags with bitwise OR based on the items that are checked.
JobSetting js = JobSetting.ForceProof;
if (chkbxList_Proof.CheckedItems.Contains("Skip Imposition"))
{
   js |= JobSetting.SkipImposition;
}
if (chkbxList_Proof.CheckedItems.Contains("High Priority"))
{
   js |= JobSetting.HighPriority;
}
//etc, etc...

If "Skip Imposition" and "High Priority" are checked, then js will be equal to JobSetting.ForceProof | JobSetting.SkipImposition | JobSetting.HighPriority.


text:
Q: How to resolve access denied error for user "root@localhost" I want to resolve access denied error for user "root@localhost" password "No" while inserting value in information_schema database.
I have granted All privileges to the root user. But I'm still getting the same error.

A: that does not sound like a good idea, in the first place. You're giving root privileges to anyone who stumbles across your web ui.
I'd suggest creating a new user (or users) with privileges to do only what they need to.
If you -must- do something as root through the ui, then for your own safety set a strong password!

A: I don't think you're trying to do what you actually want to do. As in, the actual steps you're trying to take won't accomplish the action you desire.
You're not supposed to be able to directly INSERT to INFORMATION_SCHEMA. From the manual:

The INFORMATION_SCHEMA database contains several read-only tables. They are actually views, not base tables, so there are no files associated with them, and you cannot set triggers on them. Also, there is no database directory with that name.
Although you can select INFORMATION_SCHEMA as the default database with a USE statement, you can only read the contents of tables, not perform INSERT, UPDATE, or DELETE operations on them.

Now about your phpMyAdmin problem. Are you able to log in at the command line client? When you say you've granted all privileges to user root, from where have you done that? Also, didn't your MySQL come with a root user already created that has all privileges? I'm not sure why you would have to do the grants yourself. Show us your config.inc.php file, please.


text:
Q: Instantiate within Abstract class I have an abstract class which gives specific 'base' behavior to multiple sub classes.  I want to instantiate a Singleton inside this abstract class.  Is it good practice to:
a) instantiate a class within an abstract class
b) do this with a Singleton (I know these may be frowned upon)
For clarity I will give an example, the method instantiating the Singleton is:
public function createErrorRepository(repositoryType:String):void {
    this._errorFactory = ErrorFactory.getInstance();
    this._errorRep = this._errorFactory.createErrorRepository(repositoryType);
}

I have abstract methods:
public function getTitle():String {
    throw new IllegalOperationError("Error - getTitle functionality not supported");
}

Maybe i'm over thinking, but would be good to get some confirmation this is good practice?
Thanks
Chris
N.B I am using as3 but have tagged Java as well due to similarity.

A:
is it good practice to:
  a) instantiate a class within an abstract class

It probably depends on the design, but there is nothing wrong with creating an instance of a class within an abstract class if the instance is something that all of the subclasses should have. In Java this is done with protected fields if the subclasses need to access the fields.

b) do this with a Singleton

If the singleton is a heavy object (e.g. lots of fields, methods, and so on) which all the subclasses of the abstract class will need, then it's probably preferable to have only one instance shared among them. It looks like the ErrorRepository might well fit that description, as there doesn't seem to be a reason for multiple instances to exist.
One last thought: if you didn't write ErrorFactory, make sure that the errorFactory.createErrorRepository(repositoryType) method is returning the same instance in all cases. (Even if you did write it, it wouldn't be a bad idea to check. I speak from experience.)


text:
Q: Python-Turn turtle to the right Is there any way to turn turtle to the right (to the East) in Python regardless of which direction the turtle is facing?
Really appreciate any help

A: From the help page help(turtle)
 |  setheading(self, to_angle)
 |      Set the orientation of the turtle to to_angle.
 |
 |      Aliases:  setheading | seth
 |
 |      Argument:
 |      to_angle -- a number (integer or float)
 |
 |      Set the orientation of the turtle to to_angle.
 |      Here are some common directions in degrees:
 |
 |       standard - mode:          logo-mode:
 |      -------------------|--------------------
 |         0 - east                0 - north
 |        90 - north              90 - east
 |       180 - west              180 - south
 |       270 - south             270 - west
 |
 |      Example (for a Turtle instance named turtle):
 |      >>> turtle.setheading(90)
 |      >>> turtle.heading()
 |      90


text:
Q: Swift AddressBook - copy all people in source with sort ordering issue here is the issue I'm getting. Any help is much appreciated.

Here's the code:
var addressBook: ABAddressBookRef = {
    var error: Unmanaged<CFError>?
    return ABAddressBookCreateWithOptions(nil,
    &error).takeRetainedValue() as ABAddressBookRef
}()

var source = ABAddressBookCopyDefaultSource(addressBook)!

var allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, source: source, sortOrdering: kABPersonSortByFirstName)

Error message: Cannot convert the expression's type '(ABAddressBookRef, source: @lvalue Unmanaged, sortOrdering: Int)' to type '$T4'

A: Two errors: ABAddressBookCopyDefaultSource() returns
Unmanaged<ABRecord>!, so you have to call takeRetainedValue()
on the returned value.
And the last argument to ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering() must
be converted to the expected type ABPersonSortOrdering:
var source: ABRecord = ABAddressBookCopyDefaultSource(addressBook).takeRetainedValue()

var allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook,
    source, ABPersonSortOrdering(kABPersonSortByFirstName))


text:
Q: What is the best way for pooling httpclient? My main goal is for pooling a httpclient in silent or somehow, and i'd like to call a method to give me a httpclient...because i think its too resource usage for every rest call add a new httpclient instance and set the things and so on...is there best practice for it?

A: If you refer to Apache HTTP client then you may follow the steps below:

*

*Initiate Apache HTTP client only once, since it is thread safe you can safely reuse it. If you use Spring then it should be safe to store it in the Spring Context as a Bean. See following link for the thread-safety.

*Despite the fact that HTTP client instance itself is not pooled (since you gonna use single instance of it) what you can do to increase the performance is configuring pooled connection manager on the HTTP client. See following link for the details.
(search for the 'Pooling connection manager' on that page) . The actual code should be something similar to the snippet bellow :
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// Increase max total connection to 200
cm.setMaxTotal(200);
// Increase default max connection per route to 20
cm.setDefaultMaxPerRoute(20);
// Increase max connections for localhost:80 to 50
HttpHost localhost = new HttpHost("localhost", 80);
cm.setMaxPerRoute(new HttpRoute(localhost), 50);

CloseableHttpClient httpClient = HttpClients.custom()
        .setConnectionManager(cm)
        .build();

Hope this helps .


text:
Q: Android Beginner - Wrapping and PlainText - Eclipse/AndroidStudio Hello guys I am currently learning how to make apps and I encountered few problems I am trying to do the same thing in both Eclipse and AndroidStudio and I am having 2 different problems with PlainText fields..
in Android Studio: The field height is too big even thought I've set it to "wrap_content" I'm including an image - http://prikachi.com/images/110/7455110m.png how can I make it to really wrap the content inside I don't want the field to be bigger than the number
in Eclipse: whenever I try to add Plain Text field I get an error - http://prikachi.com/images/113/7455113A.png
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".crazy_tip_calc">

<TextView
    android:text="@string/bill_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/billTextView"
    android:layout_alignBottom="@+id/billEditText"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/billEditText"
    android:ems="5"
    android:text="@string/bill_edit_text"
    android:inputType="numberDecimal"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/billTextView" />

</RelativeLayout>

A: This is happening because the textview is using the defailt height of the normal text and is aligned to the top left corner which is default.
To achieve what you want, put those TextView and EditText in a LinearLayout and set the android:gravity to center_vertical. To change the height of the TextView, use android:textSize attribute
or set android:textAppearance to "?android:attr/textAppearanceMedium" or "?android:attr/textAppearanceLarge"


text:
Q: Two problems in code (open file with console string, and delete[]) I have a couple of questions. If I manually enter a file path, the function fopen_s always fails, but if I set the same path by code, the file opens without problems. My second issue is "delete[] bytes" and "delete[] locatie" doesn't compile, I get

error C2065: 'delete' undeclared identifier

and

C2059: syntax error ']'

and I have no clue why. The ASM part is an optimized loop btw.
char* getline()
{
    char line[50];
    char *eof;
    line[0] = '\0';
    line[sizeof(line)-1] = ~'\0';
    eof = fgets(line, sizeof(line), stdin);
}

int _tmain(int argc, _TCHAR* argv[])
{
    char* locatie, *bytes, c;
    FILE* bestand;
    int i, size;
    struct stat st;

    printf_s("Voer het pad van het bestand in en druk op enter.\n");
    locatie = getline();
    locatie[strlen(locatie)-1] ='\0';
    locatie = "C:\\Users\\xxx\\Documents\\haha.txt"; // <-- this line

    if ((i = fopen_s(&bestand, locatie, "r" )) != 0)
    {
        printf_s("Het bestand bestaat niet, of kon niet worden geopend!");
        getchar();
        return -1;
    }

    stat(locatie, &st);
    size = st.st_size;
    bytes = (char*)malloc(i+1);
    i = 0;

    loop:
    c = fgetc(bestand);
    __asm
    {
        movsx eax, byte ptr [c]
        cmp eax, 0x0FFFFFFFF
        je Break
        mov eax, dword ptr [bytes]
        add eax, dword ptr [i]
        mov cl, byte ptr [c]
        xor cl, 32
        mov byte ptr [eax], cl
        mov eax, dword ptr [i]
        add eax, 1
        mov dword ptr [i], eax
        jmp loop
    }

    Break:
    fclose(bestand);
    bytes[i] = '\0';
    printf(bytes);

    locatie = "C:\\Users\\xxx\\Documents\\haha.cpt";
    fopen_s(&bestand, locatie, "w");
    fprintf_s(bestand, "%c", bytes);
    fclose(bestand);
    delete[] bytes;
    delete[] locatie;
    return 0;
}

A: delete[] is C++, use free() in C.
The program has undefined behaviour as the function getline() does not return anything. Do not attempt to fix this by returning line (or eof which is either NULL or points to line) but you need to malloc() a new buffer and return it or pass a buffer to getline() to be populated.
This is a mistake:
fprintf_s(bestand, "%c", bytes);

the format specifier "%c" expects an argument of type char but bytes is a char*. Use "%s" instead:
fprintf_s(bestand, "%s", bytes);

A: But getline() isn't returning anything! And if it did, it looks as if you are returning a pointer to a local buffer - line - which goes out of scope as soon as the function returns.


text:
Q: Trouble with event.stopPropagation() and onClick I wrote this piece of code several years ago, and at the time, it works in Firefox and Chrome, but now, it results in an infinite loop in Chrome:

    Header

You can run the code here: http://jsfiddle.net/Py7Mu/205/
Basically, what its supposed to do, is if the user clicks inside the div (i.e. Header), it finds the link within it, and invokes a click on it. On Chrome, that invoked click also propagates back to the parent, which in turn starts the whole process again.
I know I should be using less obtrusive JavaScript, but this stems from an old rails app (upgrade will hopefully come soon enough).
Any idea why the event doesn't actually stop propagating? Technically, the code should work without the stopPropagation call, as the if statement inside the function should stop subsequent calls from firing. Apparently, Chrome does not update the currentTarget when programmatically invoking a click.

A: if there is only one child anchor could you not just do something like...
$(el).click(function(){
    if (this.tagName !== 'A')
        this.getElementsByTagName('A')[0].click();
});

or i guess if it's nested further down...
$(el).click(function(){
    if (this.tagName !== 'A')
        $('a', this)[0].click();
});

A: Looks like it is caused by the event handlers being attached inline. If you attach them using jQuery, onDomReady, it should work, and better yet, cross-browser (your current script won't work in IE <9). Also, you don't need the anchor check inside your event handler if you can properly stop the propagation.
Try this:
$(function(){

    $(div).click(function(){
        $(this).children('a').click();
    });

    $(a).click(function(e){
        e.stopPropagation();
    });

});


text:
Q: Launching Windows Form on IIS - any workaround? I faced problem with IIS web application. There is some RTF processing needed on server side and this can be done with windows control. This control requires to be created and shown in order to perform operations (RTF stuff).
I would like to expose web-service from IIS that could launch windows form on Windows Server (the one that is hosting IIS), perform some work and return data to web-service. Problem is that IIS does not allow to launch windows forms.
Requirement is to host whole app on IIS. Windows Service installed separately is not an option here. I tried deploying WCF service on IIS that that didn't worked too.


text:
Q: Wrong proof of the functional equation for $ \zeta (s) $ but why is the result correct? If I introduce the function $ f(x)= |x|^{s-1} $ inside Poisson summatory formula and use the fact that
$$ \sum_{n=-\infty}^{\infty}|n|^{s-1}=2\zeta (1-s) $$
If I combine this expression in the Poisson sum formula and the Mellin transform
$$ \int_{0}^{\infty}t^{s-1}\cos(at)dt = \Gamma (s)\cos(\pi s /2)/a^{s} $$
I manage to prove Riemann's functional equation
$$ \zeta (1-s)= 2(2\pi )^{-s}\Gamma(s)\cos(\pi s/2)\zeta (s) $$
But I have proved this using BAD mathematics then why is the result correct? How is that possible ?

A: For a good proof, and in particular for an easy one, see the article of Knopp and Robins here. They present a new, simple proof, based upon Poisson summation.


text:
Q: TOSSIM for windows I am new to "Wireless Sensor Network". I need to be familiar with the simulators and emulators so I decided to use TOSSIM. So, can anyone provide with the documentation or tutorials for windows?

A: There are two key points that you should figure out in TOSSIM:

*

*What is noise model and how to build a noise model?

*How to run the TOSSIM simulation and how to output the log info we want?

Here are some selected docs and tutorials I have gone through before:

*

*Official instruction (from TinyOS wiki) of TOSSIM is essential;

*A tutorial video from ANT Lab;

*Building a Network Topology for TOSSIM (Please download and open with browser)
Although TinyOS is compatible with Windows, the installation of TinyOS on Windows would be harder than that on Linux. Hope you have a pleasant WSN journey.


text:
Q: Can't access variable inside if statement I'm trying to use this code to be able to stop double bookings in my booking system. At the moment when you enter the same time twice then it comes up with this error:
Email is validthis time is already booked
Notice: Undefined variable: sql in C:\xampp\htdocs\book.php on line 44

Warning: mysqli_query(): Empty query in C:\xampp\htdocs\book.php on line 44
Error:

this is my code
<?php

//$error = ""; // Initialize error as blank
$con=mysqli_connect("localhost","","","");

if (mysqli_connect_errno($con))
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    $email = $_POST['email'];
    $time = $_POST["time"];
    $name = $_POST["name"];
    $surname = $_POST["surname"];
    $date = $_POST["date"];
    $adl1 = $_POST["adl1"];
    $adl2 = $_POST["adl2"];
    $postcode = $_POST["postcode"];

    if(!filter_var(($email), FILTER_VALIDATE_EMAIL))
    {
        echo "E-mail is not valid";
    }
    else
    {
        echo "Email is valid";

        $result = mysqli_query($con, "SELECT time FROM tbl_booking WHERE time = '$time'") or trigger_error("Query Failed! SQL: $result - Error: ".mysqli_error($con), E_USER_ERROR);
        if(mysqli_num_rows($result) == 0)
        {
            $sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";

        }
        else
        {
            echo("this time is already booked");
        }

        if (!mysqli_query($con, $sql))
        {
            die('Error: ' . mysqli_error($con));
        }

        mysqli_close($con);
    }
}

Basically I think it's trying to access the $sql inside the if statement but I have no idea why it can't. Unless i'm being stupid.

A: Set $sql as "global" -> you just need to create it before the if-statement.

A: You can rewrite your code as, since in else condition there is no query to the mysqli_query(), that why you got the error,
if(mysqli_num_rows($result) == 0){
     $sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";
     mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
 } else {
     echo("this time is already booked");
  }

A: Try to declare $sql value on top of your php code your code not execute
 if(mysqli_num_rows($result) == 0)
        {
            $sql="INSERT INTO tbl_booking (name, surname, email, date, time, adl1, adl2, postcode) VALUES ('$name','$surname','$email','$date','$time','$adl1','$adl2','$postcode')";

        }

this condition its actually executing your else body that why it generate exception that $sql variable not defined


text:
Q: CSS Remove padding and apply full width to table columns from a class I added the following CSS media query to a page, but can't figure out how to set the width of the upper column to full width,remove the padding of the lower column to center it, and center the button.
@media only screen and (max-width: 760px),
(min-device-width: 768px) and (max-device-width: 1024px)  {

/* Force table to not be like tables anymore */
table, thead, tbody, th, td, tr, cuerpo_con {
   display: inline-block;
   width:100%;
   position:relative;
   border-collapse:collapse;
   margin: 0 auto;
   overflow: hidden;
   padding-left: 0px;
}

Off centered columns with different widths and padding

Here's the HTML
I see that the upper column has 400px width as well as the padding for the lower column set to 30px. Just can't figure out how to remove them with css so it all looks center on mobile devices.

                    Cuenta:
                    3826

                    Ruta:
                    1-11

                    Dirección:
                    BO LEMPIRA OAK RIDGE

                    Medidor:
                    20203948

                    Saldo:
                    LPS 0.00

                    <button class="Pagos ui-button ui-corner-all ui-widget ui-button-disabled ui-state-disabled" onclick="payNow( ['3826;0.00'] )" disabled="">

                       Pagar Ahora
                    </button>

                      <button class="Info ui-button ui-corner-all ui-widget" onclick="abrirVentanaInfo('3826'); return False;">

                         Ver Información
                      </button>

A:

@media only screen and (max-width: 760px), (min-device-width: 768px) and (max-device-width: 1024px)  {
  td {
    padding: 0 !important;
    width: 100% !important;
    display: block !important;
    text-align: center;
  }
  table {
    width: 100%;
  }
}

                        Cuenta:
                        3826

                        Ruta:
                        1-11

                        Dirección:
                        BO LEMPIRA OAK RIDGE

                        Medidor:
                        20203948

                        Saldo:
                        LPS 0.00

                        <button class="Pagos ui-button ui-corner-all ui-widget ui-button-disabled ui-state-disabled" onclick="payNow( ['3826;0.00'] )" disabled="">

                           Pagar Ahora
                        </button>

                          <button class="Info ui-button ui-corner-all ui-widget" onclick="abrirVentanaInfo('3826'); return False;">

                             Ver Información
                          </button>

A: I guess this code will help to solve the problems.

@media only screen and (max-width: 760px), (min-device-width: 768px) and (max-device-width: 1024px)  {

table {
    width: 100%;
  }
td {
    padding: 0 !important;
    margin: auto;
    display: table;
    text-align: center;
}
tr {
    margin-bottom: 8px;
}

}

                    Cuenta:
                    3826

                    Ruta:
                    1-11

                    Dirección:
                    BO LEMPIRA OAK RIDGE

                    Medidor:
                    20203948

                    Saldo:
                    LPS 0.00

                    <button class="Pagos ui-button ui-corner-all ui-widget ui-button-disabled ui-state-disabled" onclick="payNow( ['3826;0.00'] )" disabled="">

                       Pagar Ahora
                    </button>

                      <button class="Info ui-button ui-corner-all ui-widget" onclick="abrirVentanaInfo('3826'); return False;">

                         Ver Información
                      </button>


text:
Q: An elegant proof of the identity $\int_0^{2\pi} \log \left| 1-ae^{i\theta} \right|d\theta=0$ when $|a|\leq 1, a \in \mathbb{C}$. Is there any fantastic way to proving this identity?
$$\int_0^{2\pi} \log \left| 1-ae^{i\theta}\right|d\theta =0$$
I used power series approach(we have $2\log |1-z|=\log (1-z)(1-\bar{z})$), which was unsuccessful to show the result when $|a|=1$ because the series $\log(1-z)=-\sum_{n=1}^{\infty} z^n/n$ does not converge uniformly for $|z|=1$.
Any solution is appreciated. Thanks.


text:
Q: Extending SignalR Server Hub class to create a base Hub class I am trying to extend the SignalR Hub class to create a base class that is a SignalR Hub at it's core but with some extra pzazz.
My base class:
public class MyBaseHub : Hub
{
    protected ISession NhSession { get; set; }

    public MyBaseHub(ISession nhSession)
    {
        NhSession = nhSession;
    }
}

My derived class:
public class MyDerivedHub : MyBaseHub
{
    public MyDerivedHub(ISession nhSession) : base(nhSession) { }
}

The above builds fine, but the SignalR generated javascript throws an error and I cannot create a connection on the client. There was more code in my base class, but I took it all out to try and narrow down the issue and found the problem is on the client side.
The generated Javascript throws an exception, "Uncaught SyntaxError: Unexpected Number", when defining the MyBaseHub hub client:
myBaseHub`1: { generated properties go in here }

So I'm guessing that SignalR hubs can only be inherited once? Does anyone know if what I'm trying to do is possible?

A: Your question says the base hub is generic but the code sample doesn't show it. If you make the class abstract, the proxy generator won't pick it up. Also, you can rename hubs by using the [HubName] attribute.
[HubName("MyHub")]
public class MyHub2 : Hub
{
}


text:
Q: How to avoid micro lags while music is playing? I'm writing Audio Player in Qt. I use QMediaPlayer. I tried to connect music position with QSlider, but when 2 connecting are working, it makes micro lags. That's my code:
connect(player, &QMediaPlayer::positionChanged, this, [&](qint64 value){
    int pos = static_cast<int>(value);
    ui->positionSlider->setValue(pos);
});
connect(ui->positionSlider, &QSlider::valueChanged, this, [&](int value){
    player->setPosition(value);
});

How can I fix this bug?

A: You need to check if the slider is pressed when the slider value changes.
If it's not pressed, it means it is just a progress event.
If it is pressed, then it means the user is interacting with it, therefore set the mediaplayer position
connect(ui->positionSlider, &QSlider::valueChanged, this, [&](int value)
{
    if (ui->positionSlider->isSliderDown())
        player->setPosition(value);
});

By the way, that's exactly what they do in the reference example.


text:
Q: How can I use Microsoft Surface SDK with Visual Studio 2012? I visited Surface SDK and it tells that it requires Visual Studio 2010/Express. I tried to install it with VS 2012 RC but it does not allow. Does surface sdk not support VS 2012 RC ? How can I use it with VS 2012 RC ?

A: Install the SDK 2.0 Feb. 2012 Update on a box with Win 7 and Visual Studio 2010. Then create a  Surface Project from the Template.  Change the Main Surface Window ( I forget the class name. ) to inherit from Window instead of Surface Window if you want it to work on Windows 8.  Of course doing this you will loose the input stack for Tags and stuff. Copy the Surface SDK redistributable Assemblies for the controls to a folder for future reference in new projects.  You could Upgrade the project that you create with Visual Studio to VS2012.  Create a template from there.  Hope this points you in the right direction.  I have not done it in a while and am writing from the top of my head. -Mark

A: you have to reference the following ddls:
Microsoft.Surface.Core.dll,
Microsoft.Surface.dll,
Microsoft.Surface.Presentation.Design.dll,
Microsoft.Surface.Presentation.dll,
Microsoft.Surface.Presentation.Generic.dll


text:
Q: How to pagebreak within listings? I have a quite big txt file, and the problem is, if I include it with listings, latex tries to put it on one page, but it is too big for one page. So a part is missing. I am wondering, if Latex could do a pagebreak automatically?
My txt file is:
*---------------------------------*
*          GARCH Model Fit        *
*---------------------------------*

Conditional Variance Dynamics
-----------------------------------
GARCH Model : sGARCH(1,1)
Mean Model  : ARFIMA(9,0,9)
Distribution    : norm

Optimal Parameters
------------------------------------
        Estimate  Std. Error  t value Pr(>|t|)
ar1     0.000000          NA       NA       NA
ar2     0.000000          NA       NA       NA
ar3     0.000000          NA       NA       NA
ar4     0.000000          NA       NA       NA
ar5     0.000000          NA       NA       NA
ar6     0.000000          NA       NA       NA
ar7     0.000000          NA       NA       NA
ar8     0.382810    0.207125   1.8482 0.064573
ar9    -0.554678    0.215585  -2.5729 0.010085
ma1     0.000000          NA       NA       NA
ma2     0.000000          NA       NA       NA
ma3     0.000000          NA       NA       NA
ma4     0.000000          NA       NA       NA
ma5     0.000000          NA       NA       NA
ma6     0.000000          NA       NA       NA
ma7     0.000000          NA       NA       NA
ma8    -0.390819    0.204799  -1.9083 0.056352
ma9     0.551610    0.208866   2.6410 0.008267
omega   0.000004    0.000001   4.0863 0.000044
alpha1  0.078665    0.009643   8.1578 0.000000
beta1   0.907778    0.010924  83.1024 0.000000

LogLikelihood : 7007.315

Information Criteria
------------------------------------

Akaike       -5.4203
Bayes        -5.4044
Shibata      -5.4203
Hannan-Quinn -5.4145

Q-Statistics on Standardized Residuals
------------------------------------
               statistic   p-value
Lag[1]             3.623 5.698e-02
Lag[p+q+1][19]    23.913 1.008e-06
Lag[p+q+5][23]    28.490 2.919e-05
d.o.f=18
H0 : No serial correlation

Q-Statistics on Standardized Squared Residuals
------------------------------------
              statistic   p-value
Lag[1]            3.598 5.786e-02
Lag[p+q+1][3]    29.381 5.947e-08
Lag[p+q+5][7]    39.060 2.309e-07
d.o.f=2

ARCH LM Tests
------------------------------------
             Statistic DoF   P-Value
ARCH Lag[2]      4.638   2 9.836e-02
ARCH Lag[5]     35.851   5 1.017e-06
ARCH Lag[10]    38.599  10 2.984e-05

Nyblom stability test
------------------------------------
Joint Statistic:  1.9746
Individual Statistics:
ar8    0.1611
ar9    0.1230
ma8    0.1581
ma9    0.1156
omega  0.8409
alpha1 0.3889
beta1  0.4009

Asymptotic Critical Values (10% 5% 1%)
Joint Statistic:         1.69 1.9 2.35
Individual Statistic:    0.35 0.47 0.75

Sign Bias Test
------------------------------------
                   t-value   prob sig
Sign Bias           0.6522 0.5143
Negative Sign Bias  0.3228 0.7468
Positive Sign Bias  0.1376 0.8905
Joint Effect        1.4975 0.6828

Adjusted Pearson Goodness-of-Fit Test:
------------------------------------
  group statistic p-value(g-1)
1    20     64.58    7.143e-07
2    30    108.88    3.537e-11
3    40    124.32    7.785e-11
4    50    131.00    2.105e-09

Elapsed time : 1.170002

My LaTex code is:
\documentclass[a4paper,
        12pt,
        bibliography=totoc,
        index=totoc,
        abstracton,
        headsepline,
        ]{scrreprt}
\usepackage{listings} % for ROutput

\lstset{
 basicstyle=\tiny,
  backgroundcolor=\color{gray!10},
  keywordstyle=\color{black!40!black}
}

\begin{document}

\subsection[R Output]{R Output}
\lstinputlisting[float=h,frame=tb,caption=Here is my caption,label=thelabel]{mytxt.txt}

\end{document}

This looks like the following:

You can see, that there is not enough space, so what should I do? I would like to increase the size from \tiny to something bigger, but then the problem gets even more worse?


text:
Q: Getting Django to work with a remote Oracle database on Ubuntu I can't figure out how to install the Oracle/Python adapters to make this work. Whenever I try to install cx_Oracle I get the following error:
python setup.py install                                                                                ~VIRTUAL_ENV/build/cx-oracle
running install
running bdist_egg
running egg_info
creating cx_Oracle.egg-info
writing cx_Oracle.egg-info/PKG-INFO
writing top-level names to cx_Oracle.egg-info/top_level.txt
writing dependency_links to cx_Oracle.egg-info/dependency_links.txt
writing cx_Oracle.egg-info/PKG-INFO
writing top-level names to cx_Oracle.egg-info/top_level.txt
writing dependency_links to cx_Oracle.egg-info/dependency_links.txt
writing manifest file 'cx_Oracle.egg-info/SOURCES.txt'
reading manifest file 'cx_Oracle.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'cx_Oracle.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_ext
building 'cx_Oracle' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/demo -I/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public -I/usr/include/python2.6 -c cx_Oracle.c -o build/temp.linux-x86_64-2.6-10g/cx_Oracle.o -DBUILD_VERSION=5.0.4
In file included from /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/oci.h:2655,
                 from cx_Oracle.c:10:
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/oci1.h:148: warning: function declaration isn't a prototype
In file included from /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/ociap.h:222,
                 from /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/oci.h:2679,
                 from cx_Oracle.c:10:
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:676: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:2667: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:2676: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:2686: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:2695: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:2704: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:2713: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:2721: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:2731: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:2738: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/nzt.h:2746: warning: function declaration isn't a prototype
In file included from /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/oci.h:2679,
                 from cx_Oracle.c:10:
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/ociap.h:10069: warning: function declaration isn't a prototype
/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/rdbms/public/ociap.h:10075: warning: function declaration isn't a prototype
gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions build/temp.linux-x86_64-2.6-10g/cx_Oracle.o -L/usr/lib/oracle/xe/app/oracle/product/10.2.0/server/lib -L/usr/lib/oracle/xe/app/oracle/product/10.2.0/server -lclntsh -o build/lib.linux-x86_64-2.6-10g/cx_Oracle.so
/usr/bin/ld: skipping incompatible /usr/lib/oracle/xe/app/oracle/product/10.2.0/server/lib/libclntsh.so when searching for -lclntsh
/usr/bin/ld: cannot find -lclntsh
collect2: ld returned 1 exit status
error: command 'gcc' failed with exit status 1

Here are the vars in my .bashrc file:
# Export Oracle Values
ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
PATH=$PATH:$ORACLE_HOME/bin
LD_LIBRARY_PATH=$ORACLE_HOME/lib
export ORACLE_HOME
export ORACLE_SID=XE
export PATH
export LD_LIBRARY_PATH

I want to connect to a remote Oracle database anyway. There's no need for one to be installed on my local machine. Is this possible? And if so, how do I do it?

A: You need to add $ORACLE_HOME/lib to your LD_LIBRARY_PATH


text:
Q: How do I properly use this kotlin library? I'm working to implement a library that calls RPC calls and I can't understand how exactly I can implement library functionality into my MainActivity.
I've succesfully imported library as a module, but just don't know how to use.
Lirabry link - https://www.google.com/search?client=safari&rls=en&q=solana+kotlin&ie=UTF-8&oe=UTF-8

Please help me understand how can I call any function from library on my MainActivity


text:
Q: Lollipop Device-Owner App breaks phone Thanks to such so answers I was able to setup a device-owner App on my smartphone. This is a very basic test app just made to enable / disable screen pinning mode...
Anyway, at the end it works but with a very, very bad drawback : I've lost all access to the phone capabilities

*

*No more phone icon, except in the Settings > Applications > All

*If I call it, it's ringing on the caller side, but the phone does not react at all...

*However the status cellular icon indicates that it has 3G network.

All of those symptoms are pretty weird and leads me to wonder if my tiny device-owner app is locking something somewhere : Would anyone have any thoughts or experience about this ?

A: I found my own answer.
The key thing is to re-enable the default system applications with the DevicePolicyManager.enableSystemApp method, because for some reason when provisioning device with your NFC-triggered-device-owner-app at install time, it prevents further installation of all the default apps (at least on my Nexus 6).
So, once provisioned etc. I listed all the uninstalled apps and re-enabled them with the code below:
        DevicePolicyManager mDPM = (DevicePolicyManager) this.getSystemService(Context.DEVICE_POLICY_SERVICE);
        ComponentName mDeviceAdminRcvr = new ComponentName(this, DeviceAdminRcvr.class);

        List<PackageInfo> packs = getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
        for (int i=0; i<packs.size(); i++)
        {
            PackageInfo p = packs.get(i);
            try {
                mDPM.enableSystemApp(mDeviceAdminRcvr, p.packageName);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }


text:
Q: Gem can be required in IRB but not by Rails When I add
require 'soundcloud'

in Rails and start the server using
rails server

I get
...rb:9:in `require': cannot load such file -- soundcloud (LoadError)

the same yields
=> true

in IRB.
I installed Ruby, Rails, etc following http://installrails.com/.
Any ideas what could be causing this?

A: Why don't you use Bundler?
Add to Gemfile:
gem 'soundcloud'

then run
bundle install

in the root of your project and it all should work automatically.


text:
Q: Removing some tags with jquery in contenteditable div i have a contenteditable div. when a user paste text in it. It comes with html tags and i would like to remove all tags except b,i,u,blockquote,h3 tags.
How can i achieve that?
Thank you for your helps.

A:

var ignoreTags = "b, i, u, blockquote, h3";

$("[contenteditable]").on({
  paste : function() {
    setTimeout(function(){
      $(this).find("*").not(ignoreTags).contents().unwrap();
    }.bind(this), 0);
  }
});
p{color: blue;}
[contenteditable]{background:#eee;padding:16px;}

H2. Unwrap me.

H3. Keep me.

blockquote

Unwrap Paragraph but keep bold and italic

pasteHere


text:
Q: Web pack build in laravel : Bootstrap's JavaScript requires jQuery error Here is my script for webpack build with laravel mix
const { mix } = require('laravel-mix');
mix.js([
        'public/admin/js/jquery.js',
        'public/admin/js/bootstrap.min.js',
    ],'production/js/final.js');

But when i include final.js i got the following error
Uncaught Error: Bootstrap's JavaScript requires jQuery

I've installed the jquery with npm install jquery --save but still i got above error

A: i've had this issue quite a while ago. In my case after some googling i came to the conclusion that i forgot to install the bootstrap-sass-loader so incase that you are using the bootstrap-sass package do make sure you've installed the loader aswell. You can do this by running the following command:
$ npm install bootstrap-sass-loader --save

If this isn't the case try to take a look at this it isn't a tutorial for your problem exactly but it does show some simulair tutorials and answers.
Hope it helps!


text:
Q: How to add a profile like Test/ITG to JHipster Basically I am working on Jhipster project which has come by two default profile (dev and prod), so now I would like to add another profile like Test/ITG.
I am a beginner with JHipster so I really don't know where to find the documentation if there is any. And so far I haven't seen any post about creating a new profile. I don't know what files to add, what things to change in order to use that profile rather than the 'dev' or 'prod'.
Thank you so much in advance.

A: Here is a post which explains adding a new profile if you are using Maven:
https://medium.com/tekraze/add-a-new-profile-to-jhipster-application-spring-boot-application-25fa9851756c
If you are using Gradle, you have to modify build.gradle to something like the following:
if (project.hasProperty('prod')) {
    apply from: 'gradle/profile_prod.gradle'
} else if (project.hasProperty('test')) {
    apply from: 'gradle/profile_test.gradle'
} else {
    apply from: 'gradle/profile_dev.gradle'
}

Create the new file gradle/profile_test.gradle like profile_dev.gradle or profile_prod.gradle and modify them to your liking.


text:
Q: Add Drop Shadow to both top and bottom of an UIImageView I'm trying to add a drop shadow to an UIImageView so that the drop shadow appears at both the top and bottom of the UIImageView.
imageView.layer.shadowOffset only does one or the other.
Any ideas?
Thanks

A: Solved it, by using the imageView.layer.shadowOffset = CGSizeMake(0,0) adds a drop shadow to top and bottom.


text:
Q: POST request, not sending anything, isset($_POST) always false I am new to C#. I tried all solutions to other questions and still i can't find what is wrong. My code is common in other answers but it seems to never send anything. I have tried in my own server and the company i'm working for server. I know this kind of answer has been answered many times before, but maybe i am missing something like others so this might be useful to someone besides me.
C# code:
       var buttonSaveClicked = new MouseEventHandler((o, a) =>
        {
            var user_token = this.textApiKey.Text;

            if (user_token.Length == 0) MessageBox.Show("API Key cannot be empty!", "API Key Error", MessageBoxButtons.OK, MessageBoxIcon.None);

            var httpWebRequest = (HttpWebRequest) WebRequest.Create("http://localhost/networksWindows.php");
            httpWebRequest.ContentType = "application/json; charset=utf-8";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string json = "{\"user_token\": \"batatas\", \"bata\": \"cook\"}";

                System.Diagnostics.Debug.WriteLine(json);

                streamWriter.Write(json);
                streamWriter.Flush();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                System.Diagnostics.Debug.WriteLine(result);
                User user = JsonConvert.DeserializeObject<User>(result);

                if (user.status == "error") MessageBox.Show("Invalid API Key. Please make sure you have generated a API key and insert it correctly.", "API Key Error", MessageBoxButtons.OK, MessageBoxIcon.None);
                else if (user.status == "success")
                {
                    System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));

                    t.Start();

                    this.Close();
                }
            }

        });

PHP script in my server:
<?php

$json = null;

if (isset($_POST['user_token']))
{
$json = $_POST['user_token'];

echo "user";
}

?>

A: You have to decode your json post in PHP.
Try using this:
$json = json_decode($_POST);
if (isset($json['user_token']) {
  $userToken = $json['user_token'];
}

A: If you want $_POST to understand your data, it has to be sent as form-encoded key=value&key2=value2, not as JSON.
If you want to post JSON, you need to decode it on server side:
$post = (array)json_decode(file_get_contents("php://input"));
if (isset($post['user_token'])) {
    // ...
}

You can replace file_get_contents("php://input") with $HTTP_RAW_POST_DATA, but its availability depends on configuration.
P.S. streamWriter.Flush() call is redundant.

A: Decode your json as an array:
$json = json_decode($_POST, true);


text:
Q: Captialized names and remove underscore from API drop down list appscript? I am able to get API fields on the front end HTML field box dropdown successfully.
I want achieve Account Currency instead of account_currency on the front end. How can I acheive that.
Code.gs
var ACCOUNTDATA = {
    adAccountUIFields: ['account_currency', 'account_id', ...... ]

}

html
<select id="fieldsData">

<? var data = ACCOUNTDATA.adAccountUIFields ?>
 <? if (data.length > 0) { ?>
<? for (i=0; i<data.length; i++) { ?>
 <option value="<?= data[i] ?>"><?= data[i] ?></option>
   <? } ?>
 <? } ?>

   </select>

A: *

*Use split to separate the strings between _.

*Use map, replace and toUpperCase to capitalize the first letter in each word.

*Use join to join the words back to a single string, with blank spaces in between.

const updatedData = data[i].split("_")
                           .map(word => word.replace(/./, i => i.toUpperCase()))
                           .join(" ");


text:
Q: Tkinter Button Command switches when new Button is used I face an issue which is that my first button is using the second button's command. I have faced this logic error multiple times when trying to create buttons programmatically with different functions, is there a way to resolve this or is this a limitation to Tkinter? The gif below illustrates my issue.
import tkinter as tk
root = tk.Tk()
root.geometry("400x400")

def print_when_clicked(message):
    print(message)

array = ["hi", "bye"]

for i in array:
    tk.Button(root, text=i, command=lambda:print_when_clicked(i)).pack()

A: You have fallen in to one of the classic Python traps.  The issue is that the lambda captures the i variable, NOT the value of i.  So, after the loop finishes, i is bound to "bye", and both functions use it.
The trick to work around this is to use a fake default argument:
for i in array:
    tk.Button(root, text=i, command=lambda i=i:print_when_clicked(i)).pack()


text:
Q: Uninstalling pillow requires another 161 packages to be removed I'm using Anaconda Navigator 1.9.7 with Python 3.7.4 and accoding to conda list I have pillow 6.2.0 installed, which should be fine. However I cannot import it in a project, neither using import pillow, nor import PIL. I tried to update it to no avail, I did a conda update pillow, but this didn't help. Now I'm trying to conda uninstall pillow, however it tells me then that another 161 (!) packages will be removed, among which anaconda-navigator-1.9.7-py37_0, anaconda-client-1.7.2-py37_0, matplotlib-3.1.3-py37_0,jupyter-1.0.0-py37_7 etc...
This does not sound right! What shall I do? Completely uninstall Anaconda or trying to force removing only the specific pillow package?
EDIT: When trying to remove the pillow package via the Anaconda GUI, it throws the error: "Downgrading/removing these packages will modify Anaconda Navigator dependencies."
EDIT: help('modules') returns that package pil is installed, indeed import pil works. matplotlib though seems to not recognize it??

A: I created a workaround: Since apparently the module is installed as pil and matplotlib is looking for PIL, I modified the image.py file in the matplotlib folder of the package. Instead of import PIL I changed it to import pil. Now the code runs without errors!


text:
Q: Improving absolute precision of ADC to balance battery voltage I plan to use a relatively high-end microcontroller (Piccolo TMS320F28035, 12-bit resolution, +/- 4LSB offset, +/- 60 LSB gain) to measure voltage across stacked battery cells and control associated analog electronics to equalize their charge. The microcontroller will also store data in an eeprom memory (blackbox).
The current plan is to read up to 10 cell voltages. The problem is the large common mode voltage (each cell can go up to 3.5 V) - I cannot use isolated amplifiers such as INA124 or non-isolated high-precision INA117 due to high cost.
The current plan is to use voltage dividers (0.1%) at each tap and calculate cell voltages relatively to each other:

*

*V1 is measured directly

*V2 is calculated as measured V2 value less calculated V1

*and so forth

The problem with this setup is that the tenth measured voltage will suffer from high voltage-divider ratio and thus could be off by too much.
Another approach is to use a battery monitoring chip and use is as an analog front end (BQ77PL900) but the cost is quite high as well.
Are there better ways to precisely read battery cell voltages?
Thanks,
SBNY

A: I was thinking about a circuit like this one to 'extract' the single cell's voltage:
(My first shot at circuitlab, please be lenient :))

simulate this circuit – Schematic created using CircuitLab
This scheme can be applied identically to every cell to be measured.
I'm not sure if this works when "self-powered" from the battery pack as sketched.
You should definitely go for a rail-to-rail op-amp, which kind of excludes bi-polar devices.
Are you actually charging batteries or rather "supercapacitors"? - Maybe you can find some ideas for either case by searching for "supercap balancing", resulting for example in this paper on the topic.
Edit:
Maybe it's worth mentioning that with this op-amp-based circuit you can of course scale the output value to your exact needs by varying the resistor values. For example, one might want to scale some "3V max." of the cells (= range from 0V to 3V) to an output of "5V max." (range 0V to 5V) to feed into a 5V-ADC. Or one may scale the voltage down, for example to measure "4.2V max." LiPos with a 3.3V µC/ADC.
Edit #2:
With one more op-amp per cell it's also possible to remove some constant offset voltage and increase the resolution of the measurement. If, for example, a single cell needs only be measured between 2.5V and 3V, the 2.5V constant voltage can be subtracted by the 2nd op-amp, and the resulting, limited voltage range of only 0V - 0.5V can then be scaled up to, e.g., 0V - 3.3V. With a 10-bit ADC this would yield a (theoretical) resolution of 0.5V/1024 ~ 0.5mV/LSB.

A: Use an analogue multiplexer followed by a single high-precision resistor divider. The multiplexer will need to be powered from the highest point in the battery stack for it to work correctly. Control the multiplexer from IO pins on your MCU - 4x IO pins will address up to 16 multiplexed inputs - in this way you also save 9x analogue input pins. Net gain is 5 pins.
EDIT - I would recommend using an external ADC and one that is 16-bit. It can sit on the output of the precision attenuator. You can find decent ones that are much more linear than internal MCU ADCs.
I would also suggest powering the MCU at midrail on the battery stack so that a cheaper lower voltage range multiplexer can be used. This will mean that the ADC has to measure negative voltages but there are some that can do this.

A: A radical approach would be to put a separate microcontroller at each battery. A uC with a 10-bit A/D costs almost nothing these days. No need for a resistor divider, simple use a reference (TL431 or similar) and have the uC measure the reference's voltage with respect to its supply voltage. The uC's can send their measurements to the central uC via optocouplers or and IR LED (one per slacve uC) + a TSOP receiver (one).


text:
Q: How do we target elements that start with a false *ngIf condition? I need to effect the attributes and or styles of dom elements that aren't present until an *ngIf condition returns true which I'm attempting to access with a @viewChild() decorator.  So far no matter what I attempt to do I'm getting an error saying

Cannot read property nativeElement of undefined

I came across a few resources saying we should apply ChangeDetectorRef so we can update the component manually after setting the variable that toggles the dom element however I haven't had any luck with this method either.The examples I've come across don't even use {static: true} in their @viewChild() decorators so I figured maybe there were other changes made under the hood that requires modifying how we need to go about applying this solution, or maybe there's a different encouraged standard now all together.
My code currently looks like this:
inside component
//Where my data enter the component.
@Input() ElementData : OvaadGraphicObject;

TemplateType: string; //this variable toggles the *ngIf conditions
@ViewChild('graphicContainer', {static: true}) GraphicContainer: ElementRef;

//setting the TemplateType variable when the component initializes
ngOnInit(): void{ this.TemplateType = this.determineElementType(); }

//attempts to effect dom element after *ngIf condition is true and element exists
ngAfterViewInit(): void{ this.initGraphic(); }

/*I was initially setting the TemplateType var here and decided to split it apart to
  set things in different lifecycles to force it to work in the proper order.*/
private initGraphic():void{
    if(this.ElementData.selfClosing){
      this.ForgedElement = this.buildElement();
      this.TemplateType = 'single element';
    }
    else{
      //this.TemplateType = this.determineElementType();
      this.changeDetector.detectChanges();//

      /*this checks to make sure the var isn't undefined before attempting to access the dom element
        which from the console.log provides the correct result*/
      if(this.TemplateType !== undefined){
          console.log(this.TemplateType);
          this.applyElementProperties();//this is what attempts to modify the dom element
      }
      else{ console.log('GRRRRRRRR!!!!!!!'); }

    }
  }

private applyElementProperties():void{
    const attributes: OvaadGraphicAttribute[] = this.ElementData.attributes;
    const styles: OvaadSvgStyleProperty[] = this.ElementData.styles;

    if(attributes.length > 0){
        attributes.forEach(a=>{

            //GraphicContainer is somehow still undefined at this point causing an error
            this.GraphicContainer.nativeElement.setAttribute(a.attribute, a.setting);
        });
    }
    if(styles.length > 0){
        styles.forEach(a=>{
            this.GraphicContainer.nativeElement.style[a.property] = a.setting;
        });
    }
  }

inside my template
<svg:g *ngIf="TemplateType === 'single element'" [innerHtml]='insertElement()'></svg:g>

<svg:g #graphicContainer *ngIf="TemplateType == 'group element'">

    <svg:g svg-component *ngFor="let item of ElementData.subElements" [ElementData]="item"></svg:g>

</svg:g>

<svg:linearGradient #graphicContainer *ngIf="TemplateType === 'linear gradient'">

    <svg:g svg-component *ngFor="let item of ElementData.subElements" [ElementData]="item"></svg:g>

</svg:linearGradient>

<svg:radialGradient #graphicContainer *ngIf="TemplateType === 'radial gradient'">

    <svg:g svg-component *ngFor="let item of ElementData.subElements" [ElementData]="item"></svg:g>

</svg:radialGradient>

<svg:symbol #graphicContainer *ngIf="TemplateType === 'linear gradient'">

    <svg:g svg-component *ngFor="let item of ElementData.subElements" [ElementData]="item"></svg:g>

</svg:symbol>

As you see in my template I'm using #graphicContainer on every item except minus the first item.  I figured that due to how *ngIf works there wouldn't be any confusion in the dom because there will always only be one of them rendered.  I deleted the #graphicContainer from all but one just to see if they were causing some type of confusion but the behavior stayed the same.  How can I get this to work?
Update
To help understand more of what's happening this is what the determineElementType() function looks like.
private determineElementType():string{
    const item: string = this.ElementData.element;
    let elementType: string;

    if(item === 'g'){ elementType = 'group element'; }
    else if(item === 'linearGradient'){ elementType = 'linear gradient'; }
    else if(item === 'radialGradient'){ elementType = 'radial gradient'; }
    else if(item === 'symbol'){ elementType = 'symbol'; }
    else{ elementType = 'unknown element'; }

    return elementType as string;
  }

I could set the *ngIf condition to work directly off the main data abject which comes through an @Input() but this functionality won't be needed in every instance of use.  In the instances that it does, other things need to be done before toggling the element otherwise other errors can occur from other things not existing to in turn render into the element, so that's why I'm doing it this way instead of just using *ngIf="ElementData.element === 'g'" for example.

A: TemplateType must be initialized in ngOnInit then you can get reference of the dom elements , don't try to change the states of any element at ngAfterViewInit method and you dont need to call this.changeDetector.detectChanges();

ngOnInit(): void{
 this.TemplateType = this.determineElementType();
 if(this.ElementData.selfClosing){
      this.ForgedElement = this.buildElement();
      this.TemplateType = 'single element';
  }
}

ngAfterViewInit(): void{ this.initGraphic(); }

private initGraphic():void{
    if(!this.ElementData.selfClosing && this.TemplateType !== undefined){
          console.log(this.TemplateType);
          this.applyElementProperties();
     }else{ console.log('GRRRRRRRR!!!!!!!'); }
 }


text:
Q: Working on one summary file and multiple workbooks; I ran the code below and nothing happened Just started learning vba this week so forgive me if my question is dumb...I have a summary file called Test and multiple workbooks. cell A1 in each workbook match the names in column A of the summary file Test. I am trying to get the value of A1, find that in column A of Test, go the column B same row, copy the value, come back to the workbook and paste as value.
I tried the code below. It ran through but nothing happened... I know the code looks horrible but I think it makes sense to me. Any help is much appreciated!
Sub Macro1()
Set fso = CreateObject("scripting.filesystemobject")
Set ff = fso.getfolder("C:\Users\34664\summary\test")
For Each file In ff.Files
Workbooks.Open file
Set wbk2 = ActiveWorkbook
Sheets("Summary").Select
Range("A1").Select

rngY = Range("A1").Value

  Workbooks("Test.xlsx").Activate
  Sheets("test").Select
    Columns("A:A").Select
    Selection.Find(What:=rngY, After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate

ActiveCell.Offset(0, 1).Select
Selection.Copy

wbk2.Activate
Range("A50").PasteSpecial Paste:=xlPasteValues

ActiveWorkbook.Save
ActiveWorkbook.Close

Next

End Sub


text:
Q: Folders created by Program causes read-only to appear So, I stumbled across a little problem, I can't seem to figure out.
I have a NAS where I dump data on and a script to download files I need back to my PC.
While doing so, it creates a folder for the file. After that, I run a different script that encodes the video files to save some space.
However, for some reason, the files and folders keep getting a 'read-only' lock that prevents the source file to be deleted after compression.
So I have to get into each individual folder and remove the read-only permission.
Is there some way to disable the read-only lock?
The Owner if the Root folder is my personal account, with full access.
Changing it to SYSTEM or Admin with full access doesn't change anything.


text:
Q: jQuery updating global variable which is a function after click event in other function I have a script which changes the images of several list elements when clicking on thumbnails below the images, think of a color swatch. The script is swapping the src and a custom data-hover-src attribute (main image and hover image), the jquery function's variables inside the HTML onclick attribute are populated with PHP.
The swap of the main images is working fine, but the hover image (data-hover-src attribute) of the main image does not get updated after clicking a thumbnail.
Here's a fiddle which illustrates the problem: http://jsfiddle.net/YN3LV/14/
Image swap when hovering over main image:
 window.HoverImage = function () {
     var $this = $(this);
     var HoverUrl = $this.data('hover-src');
     $this.data('hover-src', $this.attr('src'));
     $this.attr('src', HoverUrl);
 };

 $(function () {
     $('img.image_update').hover(HoverImage, HoverImage);
 });

Update main image when clicking thumbnail
 function UpdateImage(color, defaultimage, hoverimage) {
     var SelectedColor = color;
     var DefaultUrl = defaultimage;
     var HoverUrl = hoverimage;
     $(".swatch_" + SelectedColor).click(function () {
         $(".swatch_" + SelectedColor).closest("ul").prev().attr({
             src: DefaultUrl,
                 "data-hover-src": HoverUrl
         });
     });
 }

I have tried setting the HoverUrl variable as global by omitting the var, "resetting" it with undefined at the end of the update image function but nothing worked. How can I resolve this and is there a smarter way of doing this, e.g. by combining everything in one function?

A: Wow this is pretty cool, took me a bit but this seems to work consistently. Fiddle
Basically, the data selector did not seem to work for our situation. So I used attr instead. Perhaps mixing them is the real problem.
 HoverUrl = $this.attr('data-hover-src');
 DefaultUrl = $this.attr('src');
 $this.attr('data-hover-src',DefaultUrl );
 $this.attr('src', HoverUrl);


text:
Q: Integration of the product of a function and the Heaviside function while solving a problem in quantum electrodynamics I have to solve the following integral: $$\int_0^t\hat{\pi}(t')\int_{0}^{+\infty} k^2    \Big\{ e^{ik(r-R)} -e^{-ik(r-R)}\Big\}e^{-ick (t-t')}dk \, dt'.$$
As the integral over $k$  is similar to Fourier Transform integrals, it makes sense to write it as
$$\int_{-\infty}^{+\infty} k^2  \mathcal{H}(k)    e^{ick(t'-t+\frac{r-R}{c})}dk -\int_{-\infty}^{+\infty} k^2 \mathcal{H}(k)  e^{ick(t'-t-\frac{r-R}{c})}dk$$
with $\mathcal{H}(k)$ the Heaviside function. I know that the Fourier Transform of the Heaviside function will have a contribution of the Dirac Delta and another of the Cauchy Principal Value. The first one makes sense to me as it will easily solve the integral over $t'$ evaluating the operator $\hat{\pi}$ in a retarded time. Furthermore, due to the $k^2$ factor I can't find a way to solve this integral.
Notice that it one defines $\xi=c(t'-t-\frac{r-R}{c})$, my problem is reduced to solve the integral $$ \int_{-\infty}^{+\infty} k^2  \mathcal{H}(k)    e^{i\xi  k}dk $$
I hope you can help me to solve it


text:
Q: Discord.js "undefined" before first array object in embed I am making a Discord bot command where you can build a city. There is a list command I am trying to make which lists all of the roads and places made in the city. Both of them keep having "undefined" before the first line in the value place. Here is what I get in my embed: the places, the roads
Here is my code for both of the commands:
const citydb = require("city.json")
client.on("message", message => {
    let { localroad, routeroad, privateplace, publicplace } = ``;

    for (var i = 0; i < citydb["roads-local"].length; i++) {localroad += citydb["roads-local"][i]}
    for (var i = 0; i < citydb["roads-route"].length; i++) {routeroad += citydb["roads-route"][i]}
    for (var i = 0; i < citydb["places-private"].length; i++) {privateplace += citydb["places-private"][i]}
    for (var i = 0; i < citydb["places-public"].length; i++) {publicplace += citydb["places-public"][i]}

    if (message.content === config.pfx+"city-listroads") {
        let roadlist = new MessageEmbed()
            .setTitle("Moth City Roads Registry")
            .setDescription("A list of roads created in Moth City.")
            .setColor("#2C3E50")
            .addFields(
                { name: "Local Roads", value: localroad, inline: true },
                { name: "Routes", value: routeroad, inline: true }
            )
        message.channel.send(roadlist)
    } else if (message.content === config.pfx+"city-listplaces") {
        let placelist = new MessageEmbed()
            .setTitle("Moth City Places Registry")
            .setDescription("A list of places created in Moth City.")
            .setColor("#2C3E50")
            .addFields(
                { name: "Homes", value: privateplace, inline: false },
                { name: "Places", value: publicplace, inline: false }
            )
        message.channel.send(placelist)
    }
});

And here is my data in the JSON file:
{"roads-route": ["MR 1 \n","MR 40 \n","MR 66 \n","MR 166 \n","MR 29 \n"],"roads-local":["Mist Parkway \n","Swagith Highway \n","Lepid Avenue \n","Wings Street \n","N Indigo Highway\n","S Indigo Highway\n"],"places-private":["7253 Lepid Avenue - Zak's House \n","9446 Mist Parkway - Sqmapi's House \n"],"places-public":["6030 Wings Street - Mountain Top Cake Shop \n"]}

I don't know what I am doing wrong. Any help is appreciated. Thank you.

A: The following line is trying to use destructuring to set all these variables, but none of their names is a key of ``:
let { localroad, routeroad, privateplace, publicplace } = ``;

If you want to set several variables to the same initial value, the syntax is different:
let localroad, routeroad, privateplace, publicplace
localroad = routeroad = privateplace = publicplace = ""

There is a simpler way of joining the data together, though:
let localroad = citydb["roads-local"].join("")
let routeroad = citydb["roads-route"].join("")
let privateplace = citydb["places-private"].join("")
let publicplace = citydb["places-public"].join("")

Going beyond that, if you change join("") to join("\n") in each of those cases, you can leave out the \n at the end of each entry in your JSON files.


text:
Q: How do I edit a (Default) or (Standard) RegKey using VBA I'm creating an Excel that need to be opened always in a new instance. To do so I decided to edit some RegKey via VBA when it opens.
My problem is to edit a RegKey that doesn't have a name, a (Default) or a (Standard).
To add a normal RegKey I have no problem:
RegKeyPath = "HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Excel\Options\DisableMergeInstance"

The default RegKey doesn't work at all:
RegKeyPath = "HKEY_CLASSES_ROOT\Excel.Sheet.12\shell\Open\command\(Default)"

My code:
Private Sub RegKeyUpdate()

    Dim RegKeyPath As String
    Dim RegKeyValue As String
    Dim RegKeyType As String

    RegKeyPath = "HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Excel\Options\DisableMergeInstance"
    RegKeyValue = "1"
    RegKeyType = "REG_DWORD"

    RegKeySave RegKeyPath, RegKeyValue, RegKeyType

    RegKeyPath = "HKEY_CLASSES_ROOT\Excel.Sheet.12\shell\Open\command\(Default)"
    RegKeyValue = RegKeyRead(RegKeyPath) & " /x"
    RegKeyType = "REG_SZ"

    RegKeySave RegKeyPath, RegKeyValue, RegKeyType

End Sub

Function RegKeyRead(RegKeyPath As String) As String

    Dim objRegistryKey As Object

    On Error GoTo ErrorHandler

    Set objRegistryKey = CreateObject("WScript.Shell")

    RegKeyRead = objRegistryKey.RegRead(RegKeyPath)

    If 1 <> 1 Then
ErrorHandler:
        On Error GoTo 0
        On Error GoTo ErrorHandler
    End If

End Function

Public Sub RegKeySave(RegKeyPath As String, RegKeyValue As String, Optional RegKeyType As String)

    Dim objRegistryKey As Object

    On Error GoTo ErrorHandler

    Set objRegistryKey = CreateObject("WScript.Shell")

    objRegistryKey.RegWrite RegKeyPath, RegKeyValue, RegKeyType

    If 1 <> 1 Then
ErrorHandler:
        On Error GoTo 0
        On Error GoTo ErrorHandler
    End If

End Sub

I expect to discover a way to add not only a new RegKey, but to add a new "folder" of RegKeys and edit its default value.


text:
Q: Probability theory - n random variables independent, two vectors formed of those variables independent Use measure theory to prove:  If random variables $X_1,..,X_n$ are independent, then two vectors $(X_1,..,X_k)$ and $(X_{k+1},..,X_n)$ are independent.

A: Let $\left(\Omega,\mathcal{A},P\right)$ be the underlying probability space for the $X_i$.
Further let $\mathcal{V},\mathcal{W}\subseteq\mathcal{A}$ such that $P\left(V\cap W\right)=P\left(V\right)P\left(W\right)$
whenever $V\in\mathcal{V}$ and $W\in\mathcal{W}$.
It is our aim to show that more broadly: $$P\left(V\cap W\right)=P\left(V\right)P\left(W\right)\text{ whenever }V\in\sigma\left(\mathcal{V}\right)\text{ and }W\in\sigma\left(\mathcal{W}\right)\tag0$$
If that has been reached then we are ready because we can apply it on $\mathcal{V}=\bigcup_{i=1}^{k}\sigma\left(X_{i}\right)$ and $\mathcal{W}=\bigcup_{i=k+1}^{n}\sigma\left(X_{i}\right)$.
Be aware that here $\sigma\left(\mathcal{V}\right)=\sigma\left(X_{1},\dots,X_{k}\right)$
and $\sigma\left(\mathcal{W}\right)=\sigma\left(X_{k+1},\dots,X_{n}\right)$

Proof:
Fix some $V_{0}\in\mathcal{V}$ and let: $$\mathcal{W}\left(V_{0}\right):=\left\{ W\in\sigma\left(\mathcal{W}\right)\mid P\left(V_{0}\cap W\right)=P\left(V_{0}\right)P\left(W\right)\right\} $$
Then it is not difficult to prove that $\mathcal{W}\left(V_{0}\right)$
is a $\sigma$-algebra and this with $\mathcal{W}\subseteq\mathcal{W}\left(V_{0}\right)$.
This justifies the conclusion that $\mathcal{W}\left(V_{0}\right)=\sigma\left(\mathcal{W}\right)$.
This can be done for every $V_{0}\in\mathcal{V}$ so actually we have
proved that: $$\forall V\in\mathcal{V}\;\forall W\in\sigma\left(\mathcal{W}\right)\;P\left(V\cap W\right)=P\left(V\right)P\left(W\right)\tag1$$
Now secondly fix some $W_{0}\in\sigma\left(\mathcal{W}\right)$ and
let: $$\mathcal{V}\left(W_{0}\right):=\left\{ V\in\sigma\left(\mathcal{V}\right)\mid P\left(V\cap W_{0}\right)=P\left(V\right)P\left(W_{0}\right)\right\} $$
Similarly it can be prove that $\mathcal{V}\left(W_{0}\right)$ is
a $\sigma$-algebra and this with $\mathcal{V}\subseteq\mathcal{V}\left(W_{0}\right)$
as is proved above and is stated in $(1)$. This justifies the conclusion that $\mathcal{V}\left(W_{0}\right)=\sigma\left(\mathcal{V}\right)$.
This can be done for every $W_{0}\in\sigma\left(\mathcal{W}\right)$
so actually we have proved that: $$\forall V\in\sigma\left(\mathcal{V}\right)\;\forall W\in\sigma\left(\mathcal{W}\right)\;P\left(V\cap W\right)=P\left(V\right)P\left(W\right)$$
which is of course the same as $(0)$. So we reached our aim.