text:
Q: How to interchange sum and integral? We fix  the point $\xi_{0}\in \mathbb R.$
Choose sequence $\{f_{n}\}_{n\in \mathbb N}\subset L^{1}(\mathbb R)$ with the following property :
(1) $\|f_{n}\|_{L^{1}(\mathbb R)} \leq 1, $ for $n\in \mathbb N;$ and
(2) $\hat{f_{n}}(\xi_{0})= 0,$ for every $n\in \mathbb N.$
Define $f:\mathbb R \to \mathbb C$ as follows:
$$f(x)=\sum_{n=1}^{\infty}\frac{2^{n-1}}{3^{n}} f_{n}(x), (x\in \mathbb R).$$
Since $\|f_{n}\|_{L^{1}}\leq 1$, and $\sum_{n=1}^{\infty} \frac{2^{n-1}}{3^{n}}<\infty,$ the series, $ \sum_{n=1}^{\infty}\frac{2^{n-1}}{3^{n}} f_{n}(x) $ is absolutely summable in $L^{1}(\mathbb R);$ and hence, $f\in L^{1}(\mathbb R).$

My Question is: Can we expect $\hat{f}(\xi_{0})= 0$ ?

Ruff attempt: By definition of Fourier transform, we have,
$\hat{f}(\xi_{0})= \int_{\mathbb R} f(x) e^{-2\pi i \xi_{0} \cdot x} dx = \int_{\mathbb R}(\sum_{n=1}^{\infty}\frac{2^{n-1}}{3^{n}} f_{n}(x))  e^{2\pi i \xi_{0}\cdot x} dx; $
now from here, if I guess, we can interchange sum and integral; (but I don't know how to justify it); then by the hypothesis (2), $\hat{f_{n}}(\xi_{0})=0;$  it will follows that, $\hat{f}(\xi_{0})=0.$

A: Answered in comments:

The series converges in $L^1$. The map $g \mapsto \int g(x)e^{2\pi i \xi\cdot x}\,dx$ is continuous for every $\xi$. That allows the interchange.  ...we have $$\int \left(\lim_{N\to\infty} \sum_{n=1}^N f_n(x)\right)e^{2\pi i\xi\cdot x}\,dx = \lim_{N\to\infty} \sum_{n=1}^N \int f_n(x)e^{2\pi i\xi \cdot x}\,dx$$ by continuity of the integral as a function of $g\in L^1$.  -Daniel Fischer


text:
Q: how to upload image in codeigniter 3 i have trouble with uploading an image using codeigniter. i am new in this and didin't have a clue in how to upload image using codeigniter. so i hope any of you guys can help me out
this is my form named form_add.php
<form method="POST" action="<?php echo base_url()."index.php/crud/insert"; ?       >">

            Nama
            <input type="text" name="nama_produk"/>

            Info
            <input type="text" name="info_produk"/>

            Harga
            <input type="text" name="harga_produk"/>

            Stock
            <input type="text" name="stock"/>

    <?php echo form_open_multipart('upload/do_upload');?>

            Gambar
            <input type="file" name="gambar_produk">

            Di Buat Oleh
            <input type="text" name="penulis_produk"/>

            Kategori
            <input type="text" name="kategori"/>

            Kode Kategori
            <input type="text" name="kode_kategori"/>

            <input type="submit" name="btnsubmit" value="Simpan" />

    </form>

and this is my controller named crud.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Crud extends CI_Controller {
public function __construct()
    {
            parent::__construct();
            $this->load->helper(array('form', 'url'));
    }

public function index(){
    $data = $this->mymodel->GetAll();

    $this->load->view('view_all_produk',array('data' => $data));

}

public function add_data(){
    $this->load->view('form_add');

}

public function insert(){
    $nama_produk = $_POST['nama_produk'];
    $info_produk = $_POST['info_produk'];
    $harga_produk = $_POST['harga_produk'];
    $stock = $_POST['stock'];
    $penulis_produk = $_POST['penulis_produk'];
    $gambar_produk = $_FILES['gambar_produk']['name'];
    $gambar_tmp = $_FILES['gambar_produk']['tmp_name'];
    $kategori = $_POST['kategori'];
    $kode_kategori = $_POST['kode_kategori'];
    $data_insert = array(
        'nama_produk' => $nama_produk,
        'info_produk' => $info_produk,
        'harga_produk' => $harga_produk,
        'stock' => $stock,
        'penulis_produk' => $penulis_produk,
        'gambar_produk' => $gambar_produk,
        'kategori' => $kategori,
        'kode_kategori' => $kode_kategori
    );
    $res = $this->mymodel->insertData('produk',$data_insert);
    if($res >= 1){
        $this->session->set_flashdata('pesan','Tambah Data Sukses');
        redirect('crud/index');
    }else{
        echo "
Insert Data Gagal!!!
";

    }

    }

    public function do_upload()
    {
            $config['upload_path']          = './assets/images';
            $config['allowed_types']        = 'gif|jpg|png';
            $config['max_size']             = 300;
            $config['max_width']            = 1024;
            $config['max_height']           = 768;

            $this->load->library('upload', $config);

            if ( ! $this->upload->do_upload('gambar_produk'))
            {
                    $error = array('error' => $this->upload-  >display_errors());

                    $this->load->view('form_add', $error);
            }
            else
            {
                    $data = array('upload_data' => $this->upload->data());

            }
    }

and this is the model named mymodel.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Mymodel extends CI_Model {
public function GetAll($where="") {

    $data = $this->db->query('select * from produk '.$where);
    return $data -> result_array();

}

public function insertData($tableName,$data){
        $res = $this->db->insert($tableName,$data);
        return $res;

}

    public function updateData($tableName,$data,$where){
        $res = $this->db->update($tableName,$data,$where);
        return $res;

}
public function GetKategori($where=""){
    $data = $this->db->query('select * from kategori '.$where);
    return $data;
}
}

also this is what it shows after i run it
A PHP Error was encountered
Severity: Notice
Message: Undefined index: gambar_produk
Filename: controllers/crud.php
Line Number: 30
Backtrace:
File: C:\xampp\htdocs\genstore\admin\application\controllers\crud.php
Line: 30
Function: _error_handler
File: C:\xampp\htdocs\genstore\admin\index.php
Line: 315
Function: require_once

A PHP Error was encountered
Severity: Notice
Message: Undefined index: gambar_produk
Filename: controllers/crud.php
Line Number: 31
Backtrace:
File: C:\xampp\htdocs\genstore\admin\application\controllers\crud.php
Line: 31
Function: _error_handler
File: C:\xampp\htdocs\genstore\admin\index.php
Line: 315
Function: require_once

A Database Error Occurred
Error Number: 1048
Column 'gambar_produk' cannot be null
INSERT INTO produk (nama_produk, info_produk, harga_produk, stock, penulis_produk, gambar_produk, kategori, kode_kategori) VALUES ('sada', 'asdas', 'asdasd', 'sdasd', 'sdasd', NULL, 'sadasd', '14')
Filename: C:/xampp/htdocs/genstore/admin/system/database/DB_driver.php
Line Number: 691
so can anyone tell me what's my mistake? thanks

A: Are you using multipart on the form?
<?php echo form_open_multipart('upload/do_upload');?>

https://www.codeigniter.com/userguide3/libraries/file_uploading.html
Edit: i see you are, there's a form within a form in your code!!

A: try this ! Send form-data encoded as "multipart/form-data":
<form method="POST" action="<?php echo base_url()."index.php/crud/insert"; ?>"  enctype="multipart/form-data">

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update JavaFx chart from Swing I have a JavaFx Application which plot a chart.
public class Test2 extends Application {
  @Override public void start(Stage stage) {
    final SwingNode chartSwingNode = new SwingNode();
    chartSwingNode.setContent(
      new ChartPanel(generatePieChart())
    );

    stage.setScene(
      new Scene(new StackPane(chartSwingNode))
    );
    stage.show();
  }

  private JFreeChart generatePieChart() {
    DefaultPieDataset dataSet = new DefaultPieDataset();
    dataSet.setValue("China",        1344.0);
    dataSet.setValue("India",        1241.0);
    dataSet.setValue("United States", 310.5);

    return ChartFactory.createPieChart(
      "Population 2011", dataSet, true, true, false
    );
  }

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

Then I call it from Swing using a button.
_btnStart.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
      new Thread() {
        @Override
        public void run() {
            Application.launch(Test2.class);

        }
      }.start();
  }
});

When I click button, the chart will be shown. Now I want to update the chart. How can I pass value to Test2 class and update the chart? Should I use JFXPanel instead?

A: If you really need to make it in such a way, why not using a Singleton?
Create a class ChartSingleton.java:
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

public class ChartSingleton {
  private static ChartSingleton instance = null;
  private static ChartPanel chartPanel = null;

  private ChartSingleton() {
    chartPanel = new ChartPanel(generatePieChart());
  }

  public static ChartSingleton getInstance() {
    if (instance == null) {
      instance = new ChartSingleton();
    }
    return instance;
  }

  private JFreeChart generatePieChart() {
    DefaultPieDataset dataSet = new DefaultPieDataset();
    dataSet.setValue("China",        1344.0);
    dataSet.setValue("India",        1241.0);
    dataSet.setValue("United States", 310.5);

    return ChartFactory.createPieChart(
            "Population 2011", dataSet, true, true, false
    );
  }

  public ChartPanel getChartPanel() {
    return chartPanel;
  }
}

Then replace the line:
chartSwingNode.setContent(new ChartPanel(generatePieChart()));

With this:
ChartSingleton chartSingleton = ChartSingleton.getInstance();
chartSwingNode.setContent(chartSingleton.getChartPanel());

Now you can update/modify your chart through the ChartSingleton class using:
chartSingleton.youNewMethodToModifyOrUpdateTheChart();


text:
Q: custom post meta not saving in custom post type i have written a code for my custom meta post. the meta post is check box showing just below the custom post. but when i try to save it. it don not save and leave check box blank.i dont know why its not saving?
Checkbox it using from another custom post.

    add_action( 'add_meta_boxes', 'cd_meta_box_add_alert' );
    function cd_meta_box_add_alert()
    {
    add_meta_box( 'my-meta-box-id-2', 'Select People for blog',
    'cd_meta_box_cb_alert', 'alert' , 'normal', 'high' );
    }

    function cd_meta_box_cb_alert()
    {
    // $post is already set, and contains an object: the WordPress post
    global $alert;
    $valuesalert = get_post_custom( $post->ID );
    // We'll use this nonce field later on when saving.
    wp_nonce_field( 'alert_my_meta_box_nonce', 'alert_meta_box_nonce' );
    $checkalert = isset( $valuesalert['people_to_alert'] ) ? esc_attr($valuesalert['people_to_alert'][0] ) : '';

    $people_array_alert = unserialize($valuesalert['people_to_alert'][0]);
    $args = array(
    'post_type' => 'lowenbaumpeople',
    'posts_per_page' => -1,
    'orderby' => 'title',
    'order'   => 'ASC',
    );
    $queryalert = new WP_Query( $args );
    while ( $queryalert->have_posts() ) : $queryalert->the_post();
    if ( !empty($people_array_alert) && is_array($people_array_alert) ) {
    $checkalert = (in_array($post->ID, $people_array_alert)) ? 'on' : '';
    }

    <input type="checkbox" value="<?php echo $post->ID; ?>" name="people_to_blog[]" <?php checked( $checkalert, 'on' ); ?> />
    <label for="people_to_blog"><?php the_title();?></label>

    add_action( 'save_post', 'cd_meta_box_save_alert' );
    function cd_meta_box_save_alert( $post_id )
    {   global $post;
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if( !isset( $_POST['alert_meta_box_nonce'] ) || !wp_verify_nonce($_POST['alert_meta_box_nonce'], 'alert_my_meta_box_nonce' ) ) return;
      if( !current_user_can( 'edit_post' ) ) return;

    update_post_meta( $post_id, 'people_to_alert', $_POST['people_to_alert'] );

}

i have turn on the debug mode and found these error
[13-Sep-2015 11:09:59 UTC] PHP Notice:  Undefined offset: 0 in /home/cdrossen6800/public_html/lowenbaumlaw/wp-includes/capabilities.php on line 1190
[13-Sep-2015 11:09:59 UTC] PHP Notice:  Undefined index: people_to_alert in /home/cdrossen6800/public_html/lowenbaumlaw/wp-content/themes/lowenbaum/functions.php on line 819
[13-Sep-2015 11:10:00 UTC] PHP Notice:  Array to string conversion in /home/cdrossen6800/public_html/lowenbaumlaw/wp-includes/formatting.php on line 957


text:
Q: Find number of Each Day Type Left in Month (Excel) Trying to find the number of weekdays LEFT in the month: e.g. 2 Mondays, 2 Tuesdays, etc in excel.  Anyone know how I can go about doing this?
Thanks!

A: Which version of Excel are you using? If you have Excel 2010 you can customise NETWORKDAYS.INTL function to count any single day, e.g. to count Mondays from today until the end of the month (including today) you can use this formula
=NETWORKDAYS.INTL(TODAY(),EOMONTH(TODAY(),0),"0111111")
For Tuesdays use "1011111" for Wednesdays "1101111", etc.
There are specific codes for common "weekends", e.g. 11 for Sunday weekends, but, in fact, you can use any combination of days by using a string as shown - zeroes denote days to be counted, 1s are days to be ignored - the string starts with Monday and ends with Sunday


text:
Q: Outlook VSTO - How to check if MailItem exist (new email dialog is open and is active inspector) I have code like this
var mi = MyAddIn.Application.ActiveInspector().CurrentItem as MailItem;

if (mi != null)
{
    mi.Attachments.Add(myFilePath);
}

The problem with this code is that it assumes that new mail dialog will be opened (the ActiveInspector CurrentItem is a MailItem).  However, that is not always so in my case.
If that is not the case, then above code getting mi will throw NullReferenceException.
How do I check if I have new mail dialog opened and if so then use above line to get it; otherwise create new MailItem (new mail dialog)?
I am trying to do something like this:
var mi;

if (MyAddIn.Application.ActiveInspector().CurrentItem != null)
{
    // get existing
    mi = MyAddIn.Application.ActiveInspector().CurrentItem as MailItem;
}
else
{
    // otherwise, create new one
    mi = MyAddIn.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
}

// now use it to attach file
if (mi != null)
{
    mi.Attachments.Add(myFilePath);
}

A: You need to check out what is returned from the ActiveInspector method call first.
var mi;
var inspector = MyAddIn.Application.ActiveInspector();
if (inspector != null)
{
   // get existing
   mi = inspector.CurrentItem as MailItem;
}
else
{
   // otherwise, create new one
   mi = MyAddIn.Application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
 }

// now use it to attach file
if (mi != null)
{
   mi.Attachments.Add(myFilePath);
}

See How to: Programmatically Determine the Current Outlook Item for more information.


text:
Q: Protected view in Office 2010 hangs and can't be turned off I'm using Office 2010 SP2 on Windows 10. Whenever I open an Excel or Word file, it hangs at "Opening in protected view".
To resolve this issue, I went into Trust Center, disabled trusted view as so:

I also disabled blocking for all file types here:

However, when I try to open Excel files, Excel still tries to open it in Protected View, and hangs on the loading screen here:

How can I resolve this? I don't need protected view, so I'd like to just disable it entirely.

A: For unrelated reasons, I downgraded Windows 10 to Windows 7 on this machine and reinstalled Office, where the problem no longer presented. I suspect the issue was related to Windows 10's relationship with Office 2010, but I can't be sure.


text:
Q: log in batch program i have been formulating and doing a batch program that enables the user to enter his password,just like that, and i seem to arrive at nothingness, can anybody show me how to create a batch program that enables the user to enter his password?and run a specific program when log in is successfull, by the way, i am using windows xp sp2

A: set /p "PASSWORD=Enter your password: "

I use the quotes so I can show the trailing space in the batch file.  Otherwise it's not necessary; any trailing spaces will be echoed into the output.
set /? shows a number of ways of manipulating variables in cmd.exe

A: Here's something that works for me...
@echo off

:loginPASS
set /p password=Password:
if %password% == qwerty goto loginsuccessful
if %password% == %password% goto loginfailed

:loginfailed
echo Login failed, password was incorrect!
pause
cls
goto login

:loginsuccessful
echo LOGIN SUCCESSFUL!
cd <location of file (dont include its name) example: C: /Users/YOURUSERNAME/desktop>
<type in file name here>

if you want to make a username input too, then delete the loginPASS section make a new one called loginUSER and type in this:
:loginUSER
set /p username=Username
cls
if %username% == Admin goto AdminLogin
if %username% == Bob goto BobLogin
if %username% == %username% goto NoUsername

make a new section called NoUsername
    :NoUsername
    echo User not found, check your username again.
    pause
    cls
    goto loginUSER
this will tell the user if they entered the wrong username.
after that make a new section for 1 of the users and name appropriately.
in this case you will name it AdminLogin.
After that repeat loginPASS and make the password for the user.
The whole code should look something like this:
@echo off
:AdminLogin
set /p password=Password:
if %password% == 158468 goto loginsuccessful
if %password% == %password% goto loginfailed

:loginfailedADMIN
echo Login failed, password was incorrect!
pause
cls
goto AdminLogin

:loginsuccessfulADMIN
echo LOGIN SUCCESSFUL!
cd <location of file (dont include its name) example: C: /Users/YOURUSERNAME/desktop>
<type in file name here>
pause
exit

You will want to make seperate login sections for each user.
Hope this helps!
P.S There might be other ways but this is what i use.


text:
Q: Is setting the custom class in IB not working in Xcode 4.5? I have a button class named BFToggleButton, derived from UIButton. In my xib file, I dragged a  UIButton, changed its custom class as BFToggleButton. In the Objects part of the IB, I'm seeing this button as Toggle Button - Button.
However, in the code, when I call a method that's not present in UIButton, but present in BFToggleButton class, I get an exception saying that an unrecognized selector is sent to an instance of UIButton.
So that gives me the impression that there may be a problem about setting the custom class in Xcode 4.5. Because if I'm not missing anything this should work according to my experiences with the previous XCodes.
Have you experienced the same thing?

A: Seems like the problem was about the Target Membership of the BFToggleButton class. I right clicked on this class and selected Show File Inspector and saw that the Target Membership checkbox was not checked and that was why the interface builder didn't recognize this class.


text:
Q: `send`ing into `zip`ped generators with `yield from` I am using Python 3.6 where you can nicely zip individual generators of one kind to get a multidimensional generator of the same kind. Take the following example, where get_random_sequence is a generator that yields an infinite random number sequence to simulate one individual asset at a stock market.
import random
from typing import Iterator

def get_random_sequence(start_value: float) -> Iterator[float]:
    value = start_value
    yield value

    while True:
        r = random.uniform(-.1, .1) * value
        value = value + r
        yield value

g = get_random_sequence(1.)
a = [next(g) for _ in range(5)]
print(a)
# [1.0, 1.015821868415922, 1.051470250712725, 0.9827564500218019, 0.9001851912863]

This generator can be easily extended with Python's zip function and yield from to generate successive asset values at a simulated market with an arbitrary number of assets.
def get_market(no_assets: int = 10) -> Iterator[Sequence[float]]:
    rg = tuple(get_random_sequence(random.uniform(10., 60.)) for _ in range(no_assets))
    yield from zip(*rg)

gm = get_market(2)
b = [next(gm) for _ in range(5)]
print(b)
# [(55.20719435959121, 54.15552382961163), (51.64409510285255, 53.6327489348457), (50.16517363363749, 52.92881727359184), (48.8692976247231, 52.7090801870517), (52.49414777987645, 49.733746261206036)]

What I like about this approach is the use of yield from to avoid a while True: loop in which a tuple of n assets would have to be constructed explicitly.
My question is: Is there a way to apply yield from in a similar manner when the zipped generators receive values over send()?
Consider the following generator that yields the ratio of successive values in an infinite sequence.
from typing import Optional, Generator

def ratio_generator() -> Generator[float, Optional[float], None]:
    value_last = yield
    value = yield
    while True:
        ratio = 0. if value_last == 0. else value / value_last
        value_last = value
        value = yield ratio

gr = ratio_generator()
next(gr)    # move to the first yield
g = get_random_sequence(1.)
a = []
for _v in g:
    _r = gr.send(_v)
    if _r is None:
        # two values are required for a ratio
        continue
    a.append(_r)
    if len(a) >= 5:
        break
print(a)
# [1.009041186223442, 0.9318419861800313, 1.0607677437816718, 0.9237896996817375, 0.9759635921282439]

The best way to "zip" this generator I could come up with, unfortunately, does not involve yield from at all... but instead the ugly while True: solution mentioned above.
def ratio_generator_multiple(no_values: int) -> Generator[Sequence[float], Optional[Sequence[float]], None]:
    gs = tuple(ratio_generator() for _ in range(no_values))
    for each_g in gs:
        next(each_g)

    values = yield
    ratios = tuple(g.send(v) for g, v in zip(gs, values))

    while True: # :(
        values = yield None if None in ratios else ratios
        ratios = tuple(g.send(v) for g, v in zip(gs, values))

rgm = ratio_generator_multiple(2)
next(rgm)    # move to the first yield
gm = get_market(2)
b = []
for _v in gm:
    _r = rgm.send(_v)
    if _r is None:
        # two values are required for a ratio
        continue
    b.append(_r)
    if len(b) >= 5:
        break
print(b)
# [(1.0684036496767984, 1.0531433541856687), (1.0279604693226763, 1.0649271401851732), (1.0469406709985847, 0.9350856571355237), (0.9818403001921499, 1.0344633443394962), (1.0380945284830183, 0.9081599684720663)]

Is there a way to do something like values = yield from zip(*(g.send(v) for g, v in zip(generators, values))) so I can still use yield from on the zipped generators without a while True:?
(The given example doesn't work, because it doesn't refresh the values on the right-hand side with the values on the left-hand side.)
I realize that this is more of an aesthetic problem. It would still be nice to know though...


text:
Q: Why does Rails 4 say Missing Helper file, though it is there? I wrote a project in Rails 3. There are three controllers, three views, three helper files (very small project).
One of the helper files, which probably is causing the problem:
> cat helpers/my_helper.rb

module MyHelper

    require 'some_gems'
    ...

    def my_function ()
       ... #some functionality
    end

end

Now I moved to Rails 4 (updated all the staff).
Still when just starting the app rails s -b localhost -p 3000 and going to localhost:3000 in browser I get an Exception:
AbstractController::Helpers::ClassMethods::MissingHelperError in WelcomeController#index
Missing helper file helpers/my_helper.rb

What is the problem? The file is there, why Rails still missing it?

A: It could be that the helper could not be loaded because of missing gems from which it is trying to require libraries. Please check that your Gemfile includes all gems that you need for this helper.


text:
Q: No viewDidLoad method in PSListController I have checked recent header files for PSListController , PSViewController and PSBaseView, but there is no method for acknowledgement of view creation, like iOS has viewDidLoad - Although there are many methods available for view Display. One I found is: -(id)initForContentSize:(CGSize)contentSize, but I don't want to use it as I don't think it would be appropriate to do so.
So which method should I choose in order to initialize my instance variables or do other stuff? Thanks.
Note: I am using rpetrich's Header Files.

A: Some of those headers are slightly older on the repository but looking at an iOS 7 version of PSViewController you will see that it is a subclass of UIViewController. UIViewController does contain viewDidLoad so PSListViewController "should"  contain the same.
Source: http://www.developer.limneos.net/?framework=Preferences.framework&header=PSViewController.h


text:
Q: Does an RDBMS delete its triggers when needed? Suppose we have a trigger, named Foo.
Foo depends on the T table and depends on the a, b, c columns.
If the T table is dropped, the T trigger is also dropped?
If c is deleted, is the T trigger dropped?
If an alteration happens for the T table, but it doesn't affect the a, b, c columns, is the T trigger dropped?
Thank you in advance for your answers,
Best regards,
Lajos Arpad.

A: Having just tried, it, I can answer to your three questions:

*

*If you drop the table T the trigger is also dropped.

*If you drop a column that the trigger depends on (e.g. c in your example), the trigger is not dropped but instead it becomes invalid.  You then get an ORA-04098 'trigger XYZ is invalid and failed re-validation' error if the triggering event on the table happens (e.g. the trigger is a BEFORE INSERT trigger and you INSERT into the table).

*If you make an alteration to the table T that does not affect the trigger, the trigger is not dropped and remains valid.

A: The only scenario where a trigger is dropped without an explicit
DROP TRIGGER <trigger_name>;

Is when the table is also dropped.
DROP <TABLE_NAME>;

In cases where the source code of the trigger references schema that is no longer present, the trigger becomes invalid.  You can query your database for invalid objects with:
   select * from user_objects where status != 'VALID'
   -- invalid objects associated with the user you are logged in as
   select * from all_objects where status != 'VALID'
   -- all invalid objects  in the database

There is a case where a drop 'cascades' when you specify a cascade.  But this is focused on dropping child tables.
drop table <table_name> cascade constraints;

Oracle 10g documentation on DROP TABLE DDL command.
All that said triggers are often misused and introduce bugs. I would encourage you to avoid placing your application logic in them.

A: You should really try this or consult Oracle docs/support. I don't have access to a Oracle DB right now (it's weekend ;-)) to verify it, but as far as I remember the results of these actions would be the following:

*

*Yes (triggers are part of the respective table)

*No effect on triggers

*No effect on triggers


text:
Q: Error inflating the class for toolbar I am using the toolbar for my app it works fine in the lollipop version.But in the previous version the app gets crashed.I have tried changing the styles to
Theme.AppCompat.NoActionBar but it didn't works.
Styles:
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>
<style name="AppThemes" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

<style name="MyTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowBackground">@color/windowBackground</item>
</style>

XmlToolbar:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar         xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:elevation="4dp"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Logcat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{nidhinkumar.webviewss/nidhinkumar.webviewss.ParseMainAct}: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.v7.widget.Toolbar
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2338)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
        at android.os.Handler.dispatchMessage(Handler.java:110)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:5299)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.support.v7.widget.Toolbar
        at android.view.LayoutInflater.createView(LayoutInflater.java:620)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:696)
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:816)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:745)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
        at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:305)
        at android.app.Activity.setContentView(Activity.java:1966)
        at nidhinkumar.webviewss.ParseMainAct.onCreate(ParseMainAct.java:36)
        at android.app.Activity.performCreate(Activity.java:5286)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)

ParseMainAct:
public class ParseMainAct extends Activity{
private static String TAG = ParseMainAct.class.getSimpleName();

private Toolbar mToolbar;
private ListView listView;
private List<Message> listMessages = new ArrayList<>();
private MessageAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.parseact_main);
    listView = (ListView) findViewById(R.id.list_view);
    mToolbar = (Toolbar) findViewById(R.id.toolbar);

    adapter = new MessageAdapter(this);

    listView.setAdapter(adapter);

    Intent intent = getIntent();

}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String message = intent.getStringExtra("message");

    Message m = new Message(message, System.currentTimeMillis());
    listMessages.add(0, m);
    adapter.notifyDataSetChanged();
}

private class MessageAdapter extends BaseAdapter {

    LayoutInflater inflater;

    public MessageAdapter(Activity activity) {
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return listMessages.size();
    }

    @Override
    public Object getItem(int position) {
        return listMessages.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = inflater.inflate(R.layout.parselist_row, null);
        }

        TextView txtMessage = (TextView) view.findViewById(R.id.message);
        TextView txtTimestamp = (TextView) view.findViewById(R.id.timestamp);

        Message message = listMessages.get(position);
        txtMessage.setText(message.getMessage());

        CharSequence ago = DateUtils.getRelativeTimeSpanString(message.getTimestamp(), System.currentTimeMillis(),
                0L, DateUtils.FORMAT_ABBREV_ALL);

        txtTimestamp.setText(String.valueOf(ago));

        return view;
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    return super.onOptionsItemSelected(item);
}

}
parse_main.xml:
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <include
        android:id="@+id/toolbar"
        layout="@layout/my_tool_bar" />
</LinearLayout>

<ListView
    android:id="@+id/list_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"></ListView>

A: You should create your toolbar.xml inside you layout:
<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"
    tools:context="xxxxxx">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:orientation="vertical">

        <include
            android:id="@+id/main_menu_activity_toolbar"
            layout="@layout/XmlToolbar" />

And then inflate it your activity:
mToolbar = (Toolbar) findViewById(R.id.main_menu_activity_toolbar);

EDIT
Use NoActionBar in your base application theme
<!-- Base application theme. -->

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
    </style>

A: May be somewhere in your app AppTheme or 'AppThemes' has been used. you see you have give parent theme as Theme.AppCompat.Light.DarkActionBar. that means your Activity having this theme has ActionBar.
You cannot use ToolBar As long as ActionBaris there.
just Change Theme.AppCompat.Light.DarkActionBar
to Theme.AppCompat.Light.NoActionBar. and you are good to go.
Hope this will help you.
Update
Set your ToolBaras Your ActionBar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);

A: You have to made two styles.xml file one for device below lollipop and other is styles.xml (v-21) for device lollipop and above version.
Sample of style.xml
<style name="MyAppThemes" parent="MyTheme.Base">
<!-- Customize your theme here. -->
</style>

<style name="MyTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
 <item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowBackground">@color/windowBackground</item>
</style>

Sample of style.xml(v-21)
 <style name="MyAppThemes" parent="MyAppThemes.Base">
<item name="android:windowActionBar">false</item>
<item name="android:colorPrimary">@color/colorPrimary</item>
<item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="android:colorAccent">@color/colorAccent</item>
<item name="android:windowBackground">@color/windowBackground</item>
</style>

Now inside your AndroidMainfest.xml  change application theme
 android:theme="@style/MyAppThemes">

I hope it will solve your problem.


text:
Q: firebase-functions@0.7.5 requires a peer of firebase-admin@~5.5.0 but none is installed? Here is the error pic and please also tell me how to commit that file

A: This warning means that the same versions are required in your warning message like in my case it was
firebase-functions@0.7.5 requires a peer of firebase-admin@~5.5.0 but none is installed?
so this signify that i was using a greater version of firebase admin but the firebase-functions required 5.5.0 ver of firebase-admin
so to resolve it type in the following code: npm install firebase-admin@5.5.0
where in you have to replace that ver "5.5.0" based on your required ver.
Like in your warning if it shows
firebase-admin@~4.5.0 but none is installed?
then you have to replace the ver as
npm install firebase-admin@4.5.0

A: I solved it by typing:
npm install firebase-admin@5.5.0

A: here it was just another version ...

firebase-functions@0.8.1 requires a peer of firebase-admin@~5.8.1 but none was installed.

while instead of manually installing packages, one can add dependencies to the package.json:
{
    ...
    "dependencies": {
        "firebase-admin": "~5.8.1",
        "firebase-functions": "^0.8.1"
    }
}

and then download them altogether by running npm install . in the project directory. there are more libraries available at @firebase-ops on npmjs.com (this is where I have the numbers from).
sudo npm install -g firebase-tools installs the firebase command, to test & deploy.

A: I solved mine my using the following command:
npm install firebase-admin --save


text:
Q: Multiple dex files error when downloading my library from Sonatype I have developed a library that has been around for some months, and I'm having a problem when downloading it from Sonatype repositories (uploading it works fine).
My library is MaterialList, and it can be imported by

*

*Adding this line to your build.gradle file
compile 'com.github.dexafree.materiallist:2.1.0'

*Cloning the project and adding the library as a module by hand
For testing, you can just clone the repo and try both options, changing the app/build.gradle line, from compile project() to the one in the first option
When you compile and run by setting the compile project option, it works perfectly.
But when it's downloaded from Sonatype, it complains about multiple dex files defining a class on a library I need inside my library.
The full trace is the following:
Error:Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    /[sdk-path]/android/sdk/build-tools/21.1.2/dx --dex --no-optimize --output /[project-path]/MaterialList/app/build/intermediates/dex/debug --input-list=/[project-path]/MaterialList/app/build/intermediates/tmp/dex/debug/inputList.txt
  Error Code:
    2
  Output:
    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Lcom/nhaarman/listviewanimations/util/Swappable;
      at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
      at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
      at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
      at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
      at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
      at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:454)
      at com.android.dx.command.dexer.Main.runMonoDex(Main.java:303)
      at com.android.dx.command.dexer.Main.run(Main.java:246)
      at com.android.dx.command.dexer.Main.main(Main.java:215)
      at com.android.dx.command.Main.main(Main.java:106)

Any suggestion about how to make it not happen?
Thanks in advance

A: lib-manipulation and lib-core-slh both depend on lib-core themselves. As I see no reference to any StickyListHeaders stuff in your library, I don't think you need the lib-core-slh dependency. You should also be able to remove the lib-core dependency, since lib-manipulation includes this for you.
You could also try to include the dependencies directly, without the @aar suffix. Perhaps this messes things up.
compile 'com.nhaarman.listviewanimations:lib-core:3.1.0'
compile 'com.nhaarman.listviewanimations:lib-manipulation:3.1.0'
compile 'com.nhaarman.listviewanimations:lib-core-slh:3.1.0'

This could be an error on my part though. Let me know if any of these solutions work for you.


text:
Q: Is there a good way to do WebParts with Multi-Browser Support? I'm investigating using WebParts for a client website, and I'm running into an IE\FireFox\Chrome compatibility issue (there's always something, right?). It's been fairly well discussed in forums and posts such as this one:
ASP.NET Web Parts: Drag and Drop Support in Non-IE Browsers
Most discussions about this topic are from 2006 - 2008, the most recent discussions I can find are from roughly 2010. This is almost the end of 2011... Surely there has been SOME improvement... Right? Right?
Anyhow, the issues are things like not being able to drag and drop between Web Part Zones in Chrome, and not having a drop-down menu, but only having links for the verbs.
The drag&drop is the more significant issue.
Thanks!


text:
Q: getting "Segmentation fault: 11" from NodeJS after 4.0 update I just reinstalled NodeJS. Prior to the reinstall, when I ran node -v I got a version number that said something like "0.2.x"... It was a weird number. And since I read this morning Node was just updated to version 4.x.x I thought I should update it. Also, I was having other problems, so I thought that this might be the reason for that.
When I run the following server.js I get the following console print out.
server.js...
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var _ = require('lodash');

// Create the application.
var app = express();

// Add Middleware necessary for REST API's
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));

// CORS Support
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

// Connect to MongoDB
mongoose.connect('mongo connection string......');
mongoose.connection.once('open', function() {

  // Load the models.
  app.models = require('./models/index');

  // Load the routes.
  var routes = require('./routes');
  _.each(routes, function(controller, route) {
    app.use(route, controller(app, route));
  });

  console.log('Listening on port 3000...');
  app.listen(3000);
});

The console prints the following after I run node --debug server.js
Debugger listening on port 5858
Segmentation fault: 11

Edit: I have another project that is based off of MEANJS. When I run the Gruntfile.js I get a Segmentation fault: 11 from the console.
Edit #2: I just downgraded to node v0.12.7 and things seem to be working normal...

A: Before deleting node_modules and then running npm install again, try npm rebuild. It will re-compile native modules for the new version of Node/V8 you have installed without having to download all the files again.
npm rebuild should work. But if it doesn't, then try deleting node_modules and running npm install as a nuclear option.

A: I believe you need to reinstall some native lib in node_modules, so basically might need to remove node_modules, and npm install again.
Also npm cache clean might need to run, before install.


text:
Q: What does $\int_{-\infty}^{\infty}\sum_{i=0}^{\infty}\frac{x^i}{i!}dx$mean? I was reading a research paper and I came across this sentence which I didn't really understand.

We first cast Eq.1 into its standard form: $$\int_{-\infty}^{\infty}\sum_{i=0}^{\infty}\frac{x^i}{i!}dx$$
$$T^2-944T+155184-h=0$$
Eq. 1 is stated at the beginning of the paper and is the following:
$$h(T)=520(212-T)+{(212+T)}^2$$
What are the integral and sums supposed to mean and/or refer to?

A: I don't know the context, but $$\sum_{i=0}^{\infty} \frac{x^i}{i!} = e^x$$
because the sum is the Taylor series of $e^x$.
If this is the case, the integral has a more clear meaning.


text:
Q: Rails: Active admin load user on every page Every time I reload a page (a totally blank page as well) I get this:
User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]

So Active Admin load the admin user 1 every time I reload the page. Is it normal? There is one way to load AFTER other sql query?

A: I think that this query runs every time to check if the current admin user is a valid and existing one. I'd never used Active Admin, but with rails admin is the same thing


text:
Q: ThreeJS Size Canvas to fill space I set up a basic example here http://jsfiddle.net/8nbpehj3/37/

Button

.wrapper {
  width: 100vw;
  height: 100%;
}
.nav {
  height: 40px;
  background-color: red;
}
.chart {
  width: 100%;
  height: 100%;
}

There is a red nav bar at the top and I want the canvas to fill the remaining space.  Currently it goes over the available space and causes scrolling.
How can I get it to fill to size correctly?

A: If I understand correctly, the chart element is a container for the canvas. If so, you could achieve what you want with flexbox (I've added background color to highlight the areas):

html, body {
  padding: 0;
  margin: 0;
}

.wrapper {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.nav {
  height: 40px;
  background-color: red;
}
#chart {
  background-color: yellow;
  flex: 1;
}
#chart > canvas {
  display: inline-block;
}

Button

Canvas here

I added the display: inline-block to the canvas element because I've found in the past that without that, this technique can cause a vertical scroll bar to appear.


text:
Q: I want to print a "receipt" in C but can't figure it out I have been trying to figure out how to print this "receipt", but I don't know if it is possible without just printing everything on their own.
This is what I want to print: https://pastebin.com/qxk18ARh (check the raw paste data):
****************************************************************************************************
*                                         PERSONAL DETAILS                                         *
*                                                                                *
*           Name:                                                   Tesla                          *
*           Surname:                                                Nikola                         *
*           Address:                                                Androutsou 150, Piraeus, 15232 *
*           Total days of consumption:                              179                            *
*           Sq. Meters:                                             110                            *
*                                                                                *
****************************************************************************************************                                    *                                               PRICING                                            *
*                                                                                *
*           Initial cost:                                           EUR 19.32                      *
*           Details:                                                                               *
*                   Municipal Taxes:                                EUR 7.05                       *
*                   Total Charges:                                  EUR 12.27                      *
*           Final cost (after credit card payment deduction):       EUR 17.39                      *
*                                                                                *
****************************************************************************************************                                    *                                          PAYMENT DETAILS                                         *
*                                                                                *
*           Credit Card Number:                                     1234 5678 9012 3456            *
*                                                                                *
****************************************************************************************************

Odd line breaks, trailing white space and overlong lines as found in the pastebin link, but probably not what is really wanted. The raw data contains many tabs, too.
I searched and found only how to print a hollow square with these for loops:
for (int i = 1; i <= 23; i++) {
    for (int j = 1; j <= 23; j++) {
        if (i == 1 || i == 23 || j == 1 || j == 23){
            printf("* ");
        }else{
            printf("  ");
        }
    }

    printf("\n");

But I am looking for a rectangle firstly, and I don't know how to put the 2 lines inside in this way. So I am mostly asking if it's possible in a more compact way like with loops and if yes how should I go about doing it.
Any kind of help will be great. Thanks in advance.

A: A nice way to print a form involves using variable widths.
A singular advantage is that it allows updates in a uniform manner.
To print:
*        Initial cost:            EUR 19.32  *
*        Details:                            *
*            Municipal Taxes:     EUR 7.05   *

Use:
int width1a = 8;
int width1b = width1a + 4;
int width2a = 25;
int width2b = 25 - 4;
int width3 = 9;

// Notice the common format
printf("*%*s%-*s%-*s  *\n", width1a, "", width2a, "Initial cost:",    width3, "EUR 19.32");
printf("*%*s%-*s%-*s  *\n", width1a, "", width2a, "Details:",         width3, "");
printf("*%*s%-*s%-*s  *\n", width1b, "", width2b, "Municipal Taxes:", width3, "EUR 7.05");

More advance things like centering a title can the be done with computed widths.


text:
Q: TreeMap - Synchronization Documentation Explanation TreeMap javadoc has the below part and i could not understand the last line of the below part. Does it means to create a lock and move the map modification logic into a synchronized block or something else all together. Will only the structural modification requires synchronization and accessing is thread safe.
Note that this implementation is not synchronized.
If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedSortedMap method.

A: Basically, the Javadoc is rather confusing because if you modify the map at all (including when you are merely changing the value associated with an existing key), you want to synchronize all operations in almost all cases. The (almost) only time you do not need to synchronize is if the map is completely read-only after being published.
Now, why does the Javadoc say If ... at least one of the threads modifies the map structurally - it's because if you are merely changing the value associated with an existing key, then the worst thing that can happen is that you read stale value for some unspecified time. In contrast, if a structural change is made without synchronization, then much worse things can happen (like NullPointerExceptions, infinite loops).
It's however almost always better to synchronize or use a concurrent collection rather than allowing stale values.

A:
Does it means to create a lock and move the map modification logic
  into a synchronized block or something else all together.
  Will only the structural modification requires synchronization and
  accessing is thread safe.

No it is not enough. Synchronizing only the processing that makes a structure modification is not enough because if a method that reads the map is not synchronized, the method can be invoked concurrently with the synchronized method.So, the access to the Map could be concurrent with a reading operation and a structure modification operation. Which is undesirable.
Finally, it means that all access to the map should be synchronized if multiple threads access the map concurrently, and at least one of the threads modifies the map structure.


text:
Q: Solve for $x$ in $\frac{\sin(30)\cdot\sin(60)\cdot\sin(x+10)}{\sin(80)\cdot\sin(40)\cdot\sin(x)}=1$ I have reduced a variant of the $80-80-20$ triangle problem to this equation-
$$\frac{\sin\left(30\right)\cdot\sin\left(60\right)}{\sin\left(80\right)\cdot\sin\left(40\right)}\cdot\frac{\sin\left(x+10\right)}{\sin\left(x\right)}=1$$ I'm looking for a nice transformation of the equation to get $x$. I already solved the problem by reflection but want an alternative solution with sine rule. Please give hints or another better equation if you can find one. I found the original problem solved on AoPS using law of sines but could not apply the similar methods here.

A: Let us use the identity $$\sin\theta\cdot\sin(60^\circ-\theta)\cdot\sin(60^\circ+\theta)=\frac{\sin3\theta}4$$
to get $$\frac{\sin40^\circ\sin80^\circ}{\sin60^\circ}=\frac1{4\sin20^\circ}.$$
In your equation, leave the terms containing $x$ in LHS and move the others to RHS, then use the derived relation.
$$\frac{\sin(x+10^\circ)}{\sin x}=\frac{\sin40^\circ\sin80^\circ}{\sin30^\circ\sin60^\circ}=\frac1{2\sin20^\circ}=\frac{\sin30^\circ}{\sin20^\circ}$$
From here, considering the nature of the original problem, $x=20^\circ$ is an obvious solution. To confirm further, expand $\sin$ to get,
$$\frac{\sin(x+10^\circ)}{\sin x}=\frac{\sin(20^\circ+10^\circ)}{\sin20^\circ}$$
$$\cos10^\circ+\cot x\sin10^\circ=\cos10^\circ+\cot20^\circ\sin10^\circ$$
$$\cot x=\cot 20^\circ.$$


text:
Q: icepdf english font dislocation overlap
icepdf PDF to image, appear   english font  dislocation  overlap, look the image
I Used jar version :
<artifactId>icepdf.core</artifactId>
version>4.3.4.1</version>

<artifactId>icepdf.viewer</artifactId>
<version>4.3.4</version>

I want get result

help appreciated


text:
Q: How to manually compute response variable using regression with poly I believe I can manually compute response values from coefficients obtained using 'raw' polynomial predictor variables.
Example R code is
x <- seq(-2,2,length=100)

# true function
y <- 1.2*x^2 + 2.3*x + 3.4

# add noise
eps <- rnorm(100, 0, 1)
y <- y + eps

df <- data.frame(x=x, y=y)

# fit quadratic to noisy data points
qfit <- lm(y ~ x + I(x^2), data=df)

# manual predictions
xmat <- cbind(1, x, x^2)
yhat <- xmat %*% qfit$coeff

This yields the coefficients:
Coefficients:
(Intercept)            x       I(x^2)
      3.385        2.362        1.277

I could port that manual calculation to another programming language.
However, it appears using the function 'poly' is preferred on account of the correlation between x and x^2 in the above model, leading to the new fit
newfit <- lm( y ~ poly(x, degree=2), data=df)

and this yields different coefficients:
     (Intercept) poly(x, degree = 2)1 poly(x, degree = 2)2
        5.122729            27.549886            15.536953

Questions:
The first question is whether it is really better or even necessary that poly with its orthogonal polynomials is used instead of raw predictors?
The second question is how to manually compute responses using the coefficients from the regression using the poly function? I need to do this because the model will be implemented in another program in another language.


text:
Q: How can I execute a command on scroll before a user reaches the bottom of the screen? I would like to execute a command on scroll before a user reaches the bottom of the screen. My code below loads new dynamic content when
a user scrolls midway down the screen but I would like the dynamic content to load outside of the viewport. Is there a way to do this? Will I need to adjust the .outerheight or .offset to load the dynamic
content earlier? I've attached a graphic that shows what I am trying to accomplish.

 var busy = false;

jQuery( document ).ajaxStart(function() {
    busy = true;
});
jQuery( document ).ajaxStop(function() {
    busy = false;
});

jQuery(window).bind('scroll', function() {

    if(jQuery(window).scrollTop() >= jQuery('#dynamicContent').offset().top + jQuery('#dynamicContent').outerHeight() - window.innerHeight) {

        if (!busy) {
            jQuery('.load-more').click();

        }
    }
});

Here's a snippet of my ajax:
        $.ajax({

            url: '/content',
            type: 'post',
            data: { categoryData: categoryData},
            dataType: 'json',
            success: function(res) {
                response = res.data;

            },
            error: function(err) {
                error = err;

            },
            complete: function() {

                self.hideLoader();

                if (!error) {
                    $('#dynamicContent').html(response.html);
                    self.filterSet(response.enabled);
                    self.setHistory(href, order, filters);

                }

            }
        });

A: sample code to detect, when you reach at the bottom of the page
$(window).on("scroll", function() {
        var scrollHeight = $(document).height();
        var scrollPosition = $(window).height() + $(window).scrollTop();
        if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
            // when scroll to bottom of the page
            alert("you are at bottom of page");
        }
    });


text:
Q: Difference between $\mathbb Z^+$ and $\mathbb N$ $\mathbb Z^+$ stands for the Positive Integers: $\{1,2,3,4,5\dots\}$
$\mathbb N$ stands for the Natural Numbers: $\{1,2,3,4,5\dots\}$
So what is the difference between $\mathbb Z^+$ and $\mathbb N$?

A: According to Wikipedia, the natural numbers $\mathbb{N}$ are sometimes thought of as the positive integers $\mathbb{Z}^+=\{1,2,3,\dots\}$ or as the non-negative integers $\{0,1,2,\dots\}$.  That is why mathematicians should always clearly define what they mean by natural numbers at the start.


text:
Q: How to check network resource loaded correctly from javascript? I have a page with many resources loaded.
I would like to know if there is any way to know when a resource loaded correctly from javascript.
I have:
index.html

and
<script src="myResource.js"></script>

How can I know from javascript that myResource is correctly loaded without searching for some variable inside of myResource file.
I would like to do something like:
window.network.isLoaded("myResource.js") ? 'it is loaded!' : 'it is not loaded';

is this possible?

A: You should be able to achieve this with load event listener:
var $script = document.querySelector("[src='myResource.js']");

$script.addEventListener("load", function () {
    // your callback's code
});

As it has been pointed out by @pwolaq, this code won't work when the script has already been loaded.
To overcome this problem, you can use event delegation & event capturing (and make sure this code is placed before your script definition):
var $document = document.querySelector("body");

document.addEventListener('load', function(evt) {
    var $script = document.querySelector("script[src='myResource.js']");

    if (!evt.target.isEqualNode($script) {
        return;
    }

    // Callback code
}, true);

A: Normally scripts are loaded synchronously. So any script beneath:
 <script src="myResource.js"></script>

Will have access to its predecessor variables and functions.
Better way is to check if resources that the script has loaded are present then the script itself.

A: You can do it using Javascript.
For example, using jQuery:
$.getScript("myResource.js", function(data, textStatus, jqxhr) {
  if (jqxhr.status !== 200) {
    console.error('resource could not be loaded:', textStatus);
  }
});

Or, just with javascript:
var script = document.createElement("script");
script.setAttribute("type", "text/javascript")
script.setAttribute("src", "myResource.js");
if (typeof script === "undefined") {
  console.error("resource could not be loaded");
} else {
  document.getElementsByTagName("head")[0].appendChild(script);
}

A: You can do something like this:
if ($('script[src="myResource.js"]').length > 0){
    // script is loaded
}else{
    // not loaded
}

Hope it helps


text:
Q: Error while installing Plone I was installing Plone on my laptop, and got this error.
Plone-5.0.6-UnifiedInstaller-r1.tgz: Permission denied
Cannot write to 'Plone-5.0.6-UnifiedInstaller-r1.tgz' (Success).

I don't know what this means. I work with a proxy and I did add proxy and password with wget as shown below.
wget --proxy-user "user" --proxy-password "password" --no-check-certificate https://launchpad.net/plone/5.0/5.0.6/+download/Plone-5.0.6-UnifiedInstaller-r1.tgz

What does this error mean? How can I fix it?


text:
Q: Where to download publish profile for my Azure SQL project? When publishing services and sites to my Azure account, I just fetch the publish profile and use it. It works like a charm. However, I can't find any profile to publish my database project. I can create a local file with extension publish.xml but it doesn't work when uploading.
I've tested a bunch of different settings but I get all kinds of errors (0, 25, 40 etc.) and to be honest, I can't see me getting through any time soon.   :)
I also tried to download the simple project and copy the XML-file from there. However, when I attempt to publish that way, I get an error about VS not being able to connect to the server after 21 seconds.
Where can I download the file generated by my Azure account? (Please note that it's not the pubxml files I'm talking about here.)
I've found this article but on my account, it looks like this, instead.

A: first of all : did you open firewall access toyour database server? you need to enable this thorugh themanagement portal on SQL level or through the powershell / cli tools. for SQL there's no such thing as a publishingsettingsfile
and connecting happens through a SQL based user and password credential. (this user and password was set during sql database setupe, and can be reset and found in the portal)
I hope this helps.


text:
Q: Is there an active equivalent to Yahoo GeoPlanet available for commercial use? It looks like GeoPlanet is dead (Is GeoPlanet dead?).
Is there a suitable alternative that covers Parents (preferably Ancestors) and Neighbours? If there's a name for this type of data, that'd be helpful.
Spatial data would be a plus, but I can get by without it for now.
This project may come to nothing, but in case I am ever able to charge for the service I need to make sure I don't shoot myself in the foot with a restrictive licence.

A: Maybe you want to take a look on Mapzen Who's On First gazeteer project. Not sure if that's what you want but looks like the closest thing to GeoPlanet out there.


text:
Q: Protect my htdocs folder with a password I did not find an answer to that question in the already asked one:
I have an ht docs folder on a machine and i would like to protect that folder with a password. the folder is not on my machine, its on another machine that i access remotely,
I tried 7 Zip but i want to avoid compressing the folder, because it contains source code that i need to access without compressing/decompressing
How can i protect that folder with a password without problems with running Apache
Thanks in Advance


text:
Q: sharer or feed dialog url count I need to share the URLs and get the share count for each of them. I've been googling a lot and trying this 2 ways:
1.- First I've been using the deprecated "facebook.com/sharer.php" to share an URL, then I run FQL query like this: https://api.facebook.com/method/fql.query?query=select+total_count+from+link_stat+where+url="...here the URL..."
In this case, it never counts the first share. E.g. I share the URL for the first time and FQL query gives me zero. Then I share URL for the second time - then the FQL query gives me 1. etc.
2.- I've found a message here that sharer is deprecated from March 2011, and it's better to use "facebook.com/dialog/feed" for the purposes of URL sharing. But if I share URLs with the feed dialog, FQL query always gives me zero.
The question is: How do I share URLs and get the valid count for them?
Thanks.

A: You can use the new Send Button which replaces the old sharer.php that is not going to be supported.
Send Button is easy integrated:
http://developers.facebook.com/docs/reference/plugins/like/
(see the example in right)
To count the shares you can use Insights table
http://developers.facebook.com/docs/reference/fql/insights/#plugins

*

*domain_widget_send_views

*domain_widget_send_clicks

*domain_widget_send_inbox_views

*domain_widget_send_inbox_clicks

I also belive that this reflect the like count also.
Hope this helps!


text:
Q: C++, why am I getting access violations after modifying newly allocated objects? Alright, so I'm currently working on a game and ran into a memory issue after refactoring some of the code today.
It uses a component based design and I was modifying how the components were allocated and passed off to entities. Originally some components were allocated as member variables within the entities but now I want to have them allocated elsewhere and passed off to the entity via pointer.
You can see how I implemented this below with sample code from my project. I essentially iterate through all the entities and allocate the components for them. The problem is I'm hitting a access violation at the first line of "starting up" the "instanceObject" on the 6th iteration and have no idea why. Using the debugger, it doesn't look like any of the variables point to a invalid address.
Here is what I'm doing to create the entities and components.
for (unsigned int i = 0; i < 512; ++i) {
    InstanceObject* _pInstanceObject = new InstanceObject;

    // Initialize temporary variables
    XMFLOAT3 _position, _rotation;
    float _angle = (i / 512.0f) * (2.0f * XM_PI),
          _scale = (float)pResourceManager->numberGenerator.GetInt(50, 5);

    _position.x = 100000.0f * cos(_angle) + pResourceManager->numberGenerator.GetInt(50000, -25000);
    _position.y =(float) pResourceManager->numberGenerator.GetInt(50000, -25000);
    _position.z = 100000.0f * sin(_angle) + pResourceManager->numberGenerator.GetInt(50000, -25000);

    _rotation.x = (XM_PI * 2) * (pResourceManager->numberGenerator.GetInt(100, 0) / 100.0f);
    _rotation.y = (XM_PI * 2) * (pResourceManager->numberGenerator.GetInt(100, 0) / 100.0f);
    _rotation.z = (XM_PI * 2) * (pResourceManager->numberGenerator.GetInt(100, 0) / 100.0f);

    // Set component's state using the temporary variables.
    _pInstanceObject->StartUp(&_position,
        &_rotation,
        &XMFLOAT3(_scale, _scale, _scale),
        &XMFLOAT3(0.0f, 0.0f, 1.0f),
        &XMFLOAT3(1.0f, 0.0f, 0.0f),
        &XMFLOAT3(0.0f, 1.0f, 0.0f)
        );

    // Hand pointer of the component to entity.
    // Entity will handle deallocating component
}

And here is the relevant code from the component.
class InstanceObject {
private:
    XMVECTOR anteriorAxis,
         lateralAxis,
         normalAxis,
         position,
         rotationQuaternion,
         scale;

    XMMATRIX translationMatrix,
         rotationMatrix,
         scaleMatrix;
    void SetAnteriorAxis(const XMFLOAT3 *_anteriorAxis) { anteriorAxis = XMLoadFloat3(_anteriorAxis); }
    void SetLateralAxis(const XMFLOAT3 *_lateralAxis)   { lateralAxis = XMLoadFloat3(_lateralAxis); }
    void SetNormalAxis(const XMFLOAT3 *_normalAxis)     { normalAxis = XMLoadFloat3(_normalAxis); }
public:
    InstanceObject(void)  { }
    InstanceObject(const InstanceObject& _object) : anteriorAxis(_object.anteriorAxis), lateralAxis(_object.lateralAxis),
        normalAxis(_object.normalAxis), position(_object.position), rotationQuaternion(_object.rotationQuaternion), scale(_object.scale),
        translationMatrix(_object.translationMatrix), rotationMatrix(_object.rotationMatrix), scaleMatrix(_object.scaleMatrix) {}
    ~InstanceObject(void) { }

    bool StartUp(const XMFLOAT3 *_position, const XMFLOAT3 *_rotation, const XMFLOAT3 *_scale,
        const XMFLOAT3 *_lookAxis, const XMFLOAT3 *_strafeAxis, const XMFLOAT3 *_upAxis);

    void SetPosition(const XMFLOAT3* _position) { position = XMLoadFloat3(_position); }
    void SetRotationQuaternion(const XMFLOAT3 *_rotation) { rotationQuaternion = XMQuaternionRotationRollPitchYaw(_rotation->x, _rotation->y, _rotation->z); }
    void SetScale(const XMFLOAT3 *_scale) { scale = XMLoadFloat3(_scale); }
}

bool InstanceObject::StartUp(const XMFLOAT3 *_position, const  XMFLOAT3 *_rotation, const XMFLOAT3 *_scale,
        const XMFLOAT3 *_lookAxis, const XMFLOAT3 *_strafeAxis, const XMFLOAT3 *_upAxis) {
    SetPosition(_position);
    SetRotationQuaternion(_rotation);
    SetScale(_scale);
    SetAnteriorAxis(_lookAxis);
    SetLateralAxis(_strafeAxis);
    SetNormalAxis(_upAxis);

    return true;
}

Any idea of what could be causing this behavior and how should I fix it?

A: I believe the issue is that the XMVECTOR in your InstanceObject class need to be 16 byte aligned, and the new operator won't guarantee this for you. You can add a quick check into your code to confirm - check whether the InstanceObject pointer & 0xF is non zero in the iteration in which it crashes.
If that is the case you can write a custom allocator that guarantees the right alignment and use placement new.
It seems to be a fairly common problem with XMVECTOR when used as a member (here's an existing Connect bug report on this issue, there are a few web pages if you search).
If you just want to fix it quickly to let you get on with other things, you can add a static operator new and delete to your class declaration implemented something like the following snippet:
void* InstanceObject::operator new( size_t size )
{
    // _aligned_malloc is a Microsoft specific method (include malloc.h) but its
    // straightforward to implement if you want to be portable by over-allocating
    // and adjusting the address
    void *result = _aligned_malloc( size, 16 );
    if( result )
        return result;

    throw std::bad_alloc();
}

void InstanceObject::operator delete( void* p )
{
    if( p ) _aligned_free(p);
}

If the InstanceObject share a common lifetime you could replace the use of _aligned_malloc with your own aligned arena allocator and make the delete a no-op to improve efficiency.

A: You're taking the addresses of temporaries! That's not even allowed!
// Set component's state using the temporary variables.
_pInstanceObject->StartUp(&_position,
    &_rotation,
    &XMFLOAT3(_scale, _scale, _scale), // not valid
    &XMFLOAT3(0.0f, 0.0f, 1.0f), // not valid
    &XMFLOAT3(1.0f, 0.0f, 0.0f), // not valid
    &XMFLOAT3(0.0f, 1.0f, 0.0f) // not valid
    );

I suggest that you turn up the warning levels on your compiler settings, and enable as much standard conformance as possible. Things get much easier when your compiler tells you what you're doing wrong.
As a solution, you could try simply passing the objects by value:
_pInstanceObject->StartUp(_position,
    _rotation,
    XMFLOAT3(_scale, _scale, _scale),
    XMFLOAT3(0.0f, 0.0f, 1.0f),
    XMFLOAT3(1.0f, 0.0f, 0.0f),
    XMFLOAT3(0.0f, 1.0f, 0.0f)
    );

bool StartUp(XMFLOAT3 _position, XMFLOAT3 _rotation, XMFLOAT3 _scale,
    XMFLOAT3 _lookAxis, XMFLOAT3 _strafeAxis, XMFLOAT3 _upAxis);

A: It looks like your XMFLOAT3 structures are being allocated on the stack, not on the heap. They would get cleaned up when their variables go out of scope.
Try allocating your structures on the heap instead:
XMFLOAT3* _position = new XMFLOAT3;


text:
Q: How to minimize and resize PNG images with transparency in php I have 512 * 512 big size PNG images with transparency.
How to create 256 * 256 PNG images with smaller file size, which also support transparency and maintaining quality.
EDIT: I'm using this code but the output image is cropped and not supporting transparency.
   $image = imagecreatefrompng("C:\Users\HP\htdocs\icon_hd.png");  // 512 * 512
    $bg = imagecreatetruecolor(256, 256);
    imagefill($bg, 0, 0, 0);
    imagealphablending($bg, TRUE);
    imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
    imagedestroy($image);
    $quality = 100;
    imagepng($bg, "C:\Users\HP\out_icon.png", 9);
    imagedestroy($bg);

A: You can use ImageMagick :
Simple example:
$inFile = "big_img.png";
$outFile = "small_img.png";
$image = new Imagick($inFile);
$image->thumbnailImage(256, 256);
$image->writeImage($outFile);

More info

A: try this,
$im = new Imagick();
$im->readImage('myimage.gif');
$im->resizeImage(256,256,Imagick::FILTER_LANCZOS,1);
$im->setImageBackgroundColor('white');
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$im->writeImage('mythumb.gif');
$im->clear();
$im->destroy();


text:
Q: Filtering array to remove filtered object in react Objective is to have an array with captured pokemons if user clicks on the input and an array of not-captured pokemons if user un-clicks the input. I've managed to filter out the pokemon when it's no longer captured and have it in the not-captured array but I can't seem to delete that pokemon from the old captured array.
Eg. If I click on "bulbasaur", "charmender", "squirtle", I get them all in the captured array. If I then remove one of them, I correctly get the removed one in the not-captured array but I can't seem to delete it from the previous captured array.
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import PokemonIcon from "./PokemonIcon";

const PokemonCard = ({ pokemon, capturedPkm, setCapturedPkm, notCapturedPkm, setNotCapturedPkm }) => {
    const [label, setLabel] = useState('Not captured')

    const toggleCaptured = (checked, id) => {
        const pokemonName = { id: pokemon.id, name: pokemon.name }

        if (checked && id === pokemon.id) {
            setCapturedPkm([...capturedPkm, pokemonName])
            setLabel('Captured!')
        } else {
            setLabel('Not captured!')
            setNotCapturedPkm([...notCapturedPkm, pokemonName])
            if (checked === false) {
                let newArr = [...capturedPkm]
                let pkmRemoved = newArr.filter((el, i) => el.id === id)
                let newArrPkm = newArr.splice(pkmRemoved, 1)
                console.log('newArr',newArrPkm, 'pkmRemoved', pkmRemoved)
                setCapturedPkm(newArrPkm)
            }
        }

    }
    useEffect(() => {
        console.log('captured', capturedPkm, 'not captured', notCapturedPkm)
    }, [capturedPkm, notCapturedPkm])

    return (
        <>

                <Link
                    to={{ pathname: `/pokemon/${pokemon.id}` }}
                    style={{ textDecoration: "none", color: "#000000" }}
                    state={{ pokemon: pokemon, capturedPkm }}
                >

                        <PokemonIcon img={pokemon.sprites?.['front_default']} />

                </Link>

{pokemon.name}

                        <input type="checkbox"
                            defaultChecked={false}
                            value={pokemon.name}
                            onChange={(e) => toggleCaptured(e.target.checked, pokemon.id)} />

                            {label}

        </>
    );
};

export default PokemonCard;

A: I guess you forgot to update the notCapturedPkm array. You could try something like this :
if (checked && id === pokemon.id) {
    setCapturedPkm([...capturedPkm, pokemonName])
    // Update this array, by removing the selected pokemon
    setNotCapturedPkm([...notCapturedPkm.filter(pkm => pkm.id !== pokemon.id)])
    setLabel('Captured!')
}


text:
Q: PyGtk: pass most recent data to module when button clicked? I'm wondering how to update the variable being sent through the PyGtk expression button.connect("clicked", funct, data). I want my function to receive the most recent data when the button is clicked, not the data that existed at the time button.connect() was called.
A very similar question was answered at http://mailman.daa.com.au/pipermail/pygtk/2006-October/013018.html but did not involve the use of seperate python files, as my question does.
Specifically, my code has two python files, main.py and utils.py, and the function I want to call lies in utils.py. The code works as desired if I put the on_clicked function inside main.py, where the data variable is defined, but I don't want to do that, as it interferes with modularisation.
utils.py contains some function with an argument:
def on_click(button, data):
    print(data)

main.py calls this function through the button.connect() expression:
import utils

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gio

data = "1"

win = Gtk.Window()
button = Gtk.Button(label="call the on_click function")
button.connect("clicked", utils.on_click, data)
win.add(button)

data = "2"

win.show_all()
Gtk.main()

When data is updated, on_clicked is still operating with the old data; i.e. 1 is being printed. I tried simply calling button.connect("clicked", utils.on_click, data) again after the data update, but that seems to cause its own problems and isn't very elegant - connect() should only have to be called once.

A: You are passing one object and then assign data to another one. The callback only knows about the first object.
There are some approaches but i'll give a simple example, where you create a class with setter/getter and then you will be able to change the value of a property in the object instance the callback knows about:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gio

class UserData:
    def __init__(self, data_value):
        self.data = data_value;

    def setData(self, new_value):
        self.data = new_value

    def getData(self):
        return self.data

def on_click(button, data):
    print(data.getData())

data = UserData("1")

win = Gtk.Window()
button = Gtk.Button(label="call the on_click function")
button.connect("clicked", on_click, data)
win.connect("destroy", Gtk.main_quit)
win.add(button)

data.setData("2")

win.show_all()
Gtk.main()


text:
Q: how to authenticate azure ad oauth2.0 web api in b2c clients I have created a azure function app as httprequest (web api https://ph-bde-uat-ptsocfunapp.azurewebsites.net/api/Quote ) and deployed in azure.
Now I added oauth2.0 azure ad authentication and I am able to authenticate the api using postman with microsoft MFA. but how a third party clients will be authenticated this api in their Apps. (here the client app is developed using ruby).
I tried using azured ad oauth2.0 authentication with client id, client secret, authorize token, validate token and callback url and scope. but now I want this api to be authenticated using any 3rd party application. how we can authenticate the api in client apps or server to server authentication without user name and password.

A: For server-to-server, use the client credentials flow.
"The OAuth 2.0 client credentials grant flow permits an app (confidential client) to use its own credentials, instead of impersonating a user, to authenticate when calling web resource, such as REST API. This type of grant is commonly used for server-to-server interactions that must run in the background, without immediate interaction with a user. These types of applications are often referred to as daemons or service accounts."


text:
Q: Shell script: if statement does not work as I want it to I wrote a shell script (for practice) that should compile a C++ (.cpp) file, automatically generate an executable with clang++ and execute it. My code:
#!/bin/bash

function runcpp() {
  CPPFILE=$1
  if [ -z $CPPFILE ]; then
    echo "You need to specify a path to your .cpp file!"
  else
    echo -n "Checking if '$CPPFILE' is a valid file..."
    if [[ $CPPFILE == "*.cpp" ]]; then
      echo -e "\rChecking if '$CPPFILE' is a valid file... successful"
      echo -n "Generating executable for '$CPPFILE'..."
      clang++ $CPPFILE
      echo -e "\rGenerating executable for '$CPPFILE'... done"
    fi
  fi

}

It's not done yet, however, at line 9 (if [[ $CPPFILE == "*.cpp" ]]; then) something goes wrong: the script exits, even though the file I specified is a .cpp file. My Terminal window:
kali@kali:~$ ls -lha *.cpp
-rw-r--r-- 1 kali kali 98 Feb  9 19:35 test.cpp
kali@kali:~$ runcpp test.cpp
Checking if 'test.cpp' is a valid file...kali@kali:~$


text:
Q: Sending email with attachment using URL hacking /email/author/EmailAuthor I am trying to send an email using URL hacking and using standard salesforce Email functionality.
I will be coming to this page using Opportunity PDF. Problem is how to show an attachment down below in the attached files of this page.
I did R&D and found that only document can be visible and not attachment.Is there a way i can show the attachment and send that attachment in the email..
If this is not possible.We cannot make the attachment visible.Can i send the attachment using code but only from that standard email author page..?
https://cs16.salesforce.com/_ui/core/email/author/EmailAuthor?doc_id=00Pf0000000x1HuEAI&p3_lkid=006f0000004fKcj

A: See @Phil Hawthorne's answer to getContent() returns Blob PDF-body in console, but HTML page (rendered like PDF) in Email service code where he recommends putting the PDF into a VF template, create a new record when you do & then having workflow send the actual email which doesn't count against your Apex daily limits. Perhaps that solution might serve your purposes.
I believe if you do a search of posts here on SF.SE, you'll find at least one or two that ask about rendering to PDF and sending an email at the same time. I'm fairly certain you can do that with button code and a template.

A: the solution is very simple - you should clone the email template and associate the attachments to it.
then use the clone emailtemplate in the URL redirect.
and don't forget to add to the URL - +'&new_template=1'
otherwise, it will not be displayed.


text:
Q: Why can $\frac{a}{(a,b)}|(\frac{b}{(a,b)})*(x-y)$ be simplified as $\frac{a}{(a,b)}|(x-y)$? I am reading the proof for a proposition in a number theory book, and it states that by another proposition which states $(\frac{a}{(a,b)}, \frac{b}{(a,b)})=1$, where $(a,b)$ is the greatest common divisor of $a$ and $b$, $\frac{a}{(a,b)}|(\frac{b}{(a,b)})*(x-y)$ be simplified as $\frac{a}{(a,b)}|(x-y)$. How does that simplification occur?

A: Because
$\frac{a}{(a,b)}$
and
$\frac{b}{(a,b)}$
are relatively prime.


text:
Q: MS Ajax breaks when Response.Redirect is used between two applications I'm currently working on an application that needs to use Windows and Forms authentication (Windows for internal users, Forms for external).  To achieve this I created a small application that grabs Windows users' Domain and Username then redirect to the main application which uses forms authentication.
The applications are hosted as follows:

*

*http://webserver/passthrough (stores the windows auth data in cookie and redirects)

*http://webserver/app (the main application)

Everything works except for Microsoft Ajax on the main application completely breaks for windows users after the redirect from the passthrough.
If the windows user then closes the browser window and then navigates directly to http://webserver/app in a new session, everything works fine.
Any input would be greatly appreciated.
Jason

A: OK, so I solved this, but it's really not pretty...
I deployed the passthrough application to a separate website running on a different port with the same host header so the deployment now looks like this.

*

*http://webserver:81/Passthrough

*http://webserver/app
Really not what I wanted to do, but it works.
I vow never to use Microsoft Ajax ever again!


text:
Q: ASP.NET MVC Stripe Error No such token I cant seem to solve this error
Credit.cshtml
 <form action="@Url.Action("Charge", "Home")" method="POST">

        Amount: $5.00

</form>

HomeController
[HttpPost]
   //Parameters can contain stripeToken, stripeEmail, stripeName, stripeAddress submitted from Credit.cshtml form
       public ActionResult Charge(string stripeToken, string stripeEmail)
       {
           Debug.WriteLine("stripe token is " + stripeToken);
           Debug.WriteLine("stripe email is " + stripeEmail);

           StripeConfiguration.SetApiKey("");

           //Take the token submitted by the form
           var token = stripeToken;

        //Charge to the user card
           var charges = new StripeChargeService();

            var charge = charges.Create(new StripeChargeCreateOptions
            {
                Amount = 1000,
                Currency = "sgd",
                Description = "Example charge",
                SourceTokenOrExistingSourceId = token
            });

           return View();
       }

An exception of type 'Stripe.StripeException' occurred in Stripe.net.dll but was not handled in user code
No such token: tok_1BYf3F2eZvKYlo2C0MJgUKKD
What is happening? Some help pleasee thankss

A: A "no such token" error generally happens when the token you are trying to charge does not match the account you are making the API call on.
I'd recommend double checking the API keys that you're using, make sure the publishable key on your front-end and secret key in your back-end belong to the same account.
If switching up API Keys doesn't resolve it, you'd want to get in touch with Stripe, their support can look up the token id and tell you why it's not working!


text:
Q: Custom loss function including output of layer I have a dataset that contains 1 value of y_true per case. I want to build a DNN that outputs 3 coefficients that will later be used as follows to create y_pred
y_pred = 4*coeff_1 + 5*coeff_2 + 6 *coeff_3

I am using keras and when i tried to define a custom function like this
from keras.callbacks import ModelCheckpoint
from keras.layers import advanced_activations
from keras.models import Sequential
from keras.layers import Dense, Activation, Flatten
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error

import keras.backend as K

def custom_objective(layer):
    return K.sum(layer.output)

NN_model = Sequential()

# The Input Layer :
NN_model.add(Dense(X_train.shape[1], kernel_initializer='normal',input_dim = X_train.shape[1], activation='relu'))

# The Hidden Layers :
NN_model.add(Dense(20, kernel_initializer='normal',activation='elu'))
NN_model.add(Dense(20, kernel_initializer='normal',activation='elu'))

output_layer = Dense(1, kernel_initializer='normal',activation='linear')

# The Output Layer :
NN_model.add(output_layer)

# Compile the network :
NN_model.compile(loss=custom_objective(output_layer), optimizer='Adamax', metrics=['mean_absolute_error'])
NN_model.summary()

NN_model.fit(X_train, y_train, epochs=10,verbose = 1)

print('NN train = ', mean_absolute_error(y_train , NN_model.predict(X_train)))

predictions = NN_model.predict(X_test)

MAE = mean_absolute_error(y_test , predictions)

print('NN MAE = ', MAE)

I get all

TypeError: Using a tf.Tensor as a Python bool is not allowed. Use
  if t is not None: instead of if t: to test if a tensor is defined,
  and use TensorFlow ops such as tf.cond to execute subgraphs
  conditioned on the value of a tensor.

So my question is
How can I define a DNN that will take 1 y_true per data, output 3 values which it will combine linearly to assemble a y_pred which will be used to get the loss function and train the network
Thank you for your time

A: How about something along these lines?
from keras.models import Model
from keras.layers import Dense, Input, Add, Lambda

def model(inp_size):
    inp = Input(shape=(inp_size, 1))

    x1 = Dense(20, activation='elu')(inp)
    x1 = Dense(20, activation='elu')(x1)
    x1 = Dense(1, activation = 'linear')(x1)

    x2 = Dense(20, activation='elu')(inp)
    x2 = Dense(20, activation='elu')(x2)
    x2 = Dense(1, activation = 'linear')(x2)

    x3 = Dense(20, activation='elu')(inp)
    x3 = Dense(20, activation='elu')(x3)
    x3 = Dense(1, activation = 'linear')(x3)

    x1 = Lambda(lambda x: x * 4.0)(x1)
    x2 = Lambda(lambda x: x * 5.0)(x2)
    x3 = Lambda(lambda x: x * 6.0)(x3)
    out = Add()([x1, x2, x3])

    return Model(inputs = inp, outputs = out)


text:
Q: Method `push_str` returns () instead of String I'm trying to learn rust via rustlings and I'm encountering this weird error. I understand that it modifies self in place but why does it return a unit () instead of the modified String
impl AppendBar for String {
    // TODO: Implement `AppendBar` for type `String`.
    fn append_bar(self) -> Self {
        self.push_str(" bar")
    }
}

I tried to contain it in a variable first but I still get the same error. I was expecting that this would avoid a unit () return type.
impl AppendBar for String {
    // TODO: Implement `AppendBar` for type `String`.
    fn append_bar(self) -> Self {
       let mut contain = self;
       contain.push_str(" bar")
    }
}

A: Something like this?
impl AppendBar for String {
    fn append_bar(mut self) -> Self {
        self.push_str(" bar");
        self
    }
}

The String::push_str function don't return anything, it mutates the String in place.
So you will you need to mutate the self and return it, in two separated statements.