text:
Q: Using a Function in a Callback/Using a SegmentedControl within a Cell I have an app that has UISegmentedControls in each UITableViewCell, it looks like this:
https://i.stack.imgur.com/ezMUJ.png
For every row in which the user selects the "Yes" option, I would like to print the index of the row.
The first step, in this case, would be to use an addTarget on the UISegmentedControl in order to specify a function to handle the Segmented Control's action. However, since I am using a custom segmented control, the addTarget is not available (callback and delegation are the only ways of passing information into the segmented control).
My first question is, is there a way to call a method within a callback?
My second question is, is there an easier way to do this overall? Some people have suggested protocols and delegation for transferring data between the cell and the view controller, but I am not really sure how to do this or that it would be appropriate.
Here is the code I have so far:
import UIKit
class MyTableViewController: UITableViewController {
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 150
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return 10
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
    cell.backgroundColor = .green
    return cell

}

func printCellIndexPath(cell: UITableViewCell){

}

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.register(MyCell.self, forCellReuseIdentifier: "cellId")

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
class MyCell: UITableViewCell{
var myTableViewController: MyTableViewController?

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    setupViews()

}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

let nameLabel: UILabel = {
    let label = UILabel()
    label.text = "Sample Item"
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
    }()

let actionButton = YSSegmentedControl(
    frame: CGRect.zero,
    titles: [
        "Yes",
        "No"
    ],
    action: {
        control, index in
        if index == 1 {
            print ("tapped")
        }
        else{

        }

})

func setupViews(){

    addSubview(nameLabel)
    addSubview(actionButton)
    actionButton.translatesAutoresizingMaskIntoConstraints = false

    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-160-[v1]-16-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel, "v1": actionButton]));
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": nameLabel]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-60-[v0]-60-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": actionButton]))

}

}
Where MyCell is my custom cell class and actionButton is the UISegmentedControl that exists within each cell.

A: To Remove delegation and callbacks why not u make YSSegmentedControl in cellForrowatIndexpath method and there u will pass tag to YSSegmentedControl's object as like that

actionButton.tag = indexpath.row

and when u click on any segment u will get callback in YSSegmentedControl delegates which are

func segmentedControl(_ segmentedControl: YSSegmentedControl,
  willPressItemAt index: Int){
           print("(segmentedControl.tag)" + "(index)")
      }
func segmentedControl(_ segmentedControl: YSSegmentedControl, didPressItemAt index: Int){

}

From these delegates method u will get YSSegmentedControl row via
segmentedControl.tag and particular button index via index


text:
Q: When i click on edit give me inputfield and 2 buttons

{{project.name}}

This is the code I want, when I click on this icon, the project.name needs to turn into an input field and give me 2 buttons in the same page
I am working with html and typescript.

A: You can use ngIf and a property binding
In your component's class:
public isInputVisible : boolean = false;
public editProject(): void {
   this.isInputVisible = true;
}

In your template:

<ng-container *ngIf="!isInputVisible">{{project.name}}</ng-container>
<input [(ngModel)]=project.name"" *ngIf="isInputVisible" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display loading or IsBusy icon while login or between other activity is performed I would like to display the loading icon (IsBusy) to display efficiently while while login into the app and should disappear after successful login. Here in my case, its not happening at all.
In the finally step, if set to IsBusy = true, then I can see that gets displaying (screen shot added for that), but that is not I want. I would like to it display for a small fraction of time while login into the app and it should go away once after successful login.
note: For all the else condition I have set to IsBusy=false
<ActivityIndicator x:Name="activityIndicator" IsRunning="{Binding IsBusy}" VerticalOptions="Center" HorizontalOptions="Center"></ActivityIndicator>

public MainPage()
    {
       InitializeComponent();
       this.BindingContext = this;
       this.IsBusy = false;
    }

public async void Button_Clicked(object sender, System.EventArgs e)
        {
            this.IsBusy = true;
            string emailText = emailEntry.Text;
            string passwordText= passwordEntry.Text;
            if(!string.IsNullOrWhiteSpace(emailEntry.Text) && !string.IsNullOrWhiteSpace(passwordEntry.Text))
            {
                if(ValidateEmail(emailText) == true)
                {
                    int count = (from x in conn.Table<PlayerDetails>().Where(x => x.Email == emailText) select x).Count();
                    if (count!= 0)
                    {
                        try
                        {
                           List<PlayerDetails> myList = (from x in conn.Table<PlayerDetails>().Where(x => x.Email == emailText && x.Password == passwordText) select x).ToList();
                            if(myList.Count() > 0)
                            {
                              // do the login stuff here.....
                            }
                            else
                            {
                                this.IsBusy = false;
                                await DisplayAlert("Notification", "No such email or password", "Cancel");

                            }

                        }
                        catch (NullReferenceException ex)
                        {
                          if(ex!=null)
                            Debug.WriteLine("Something is thrown ! " + e.ToString());
                        }
                        finally
                        {
                            IsBusy = false;
                        }
                    }
                    else
                    {
                        this.IsBusy = false;
                        await DisplayAlert("Notification", "Unable to find the user details", "Cancel");
                    }
                }
                else
                {
                    this.IsBusy = false;
                    await DisplayAlert("Notification", "Email is not a valid one", "Cancel");
                }
            }
            else
            {
                this.IsBusy = false;
                await DisplayAlert("Notification","Input details cannot be blank", "Cancel");
            }
        }

A: I just tested your code and I found it works.
The reason why you can't see the ActivityIndicator is the code executed very fast and you can't even see the process of ActivityIndicator changing from running to not running.
If you add a little delay after setting IsBusy = true, you will find it really works:
 this.IsBusy = true;
 Task.Delay(TimeSpan.FromMilliseconds(2000));
 string emailText = emailEntry.Text;
 string passwordText= passwordEntry.Text;

A: I am almost certain that your MainPage is not implementing INotifyPropertyChanged interface. Try changing you MainPage implementation so it'll look like this:
public class MainPage : ContentPage, INotifyPropertyChanged
{
    private bool isBusy;

    public event PropertyChangedEventHandler PropertyChanged;

    public bool IsBusy
    {
        get => isBusy;
        set
        {
            isBusy = value;
            OnPropertyChanged(nameof(IsBusy));
        }
    }

    //public bool IsBusy
    //{
    //  get => isBusy;
    //  set { SetProperty(ref isBusy, value); }
    //}

    public MainPage()
    {
    }

    protected bool SetProperty<T>(ref T backingStore, T value, [CallerMemberName]string propertyName = "",
        Action onChanged = null)
    {
        if (EqualityComparer<T>.Default.Equals(backingStore, value))
        {
            return false;
        }

        backingStore = value;

        onChanged?.Invoke();

        OnPropertyChanged(propertyName);
        return true;
    }

    public void OnPropertyChanged([CallerMemberName] string propertyName = "")
    {
        var changed = PropertyChanged;
        if (changed == null)
        {
            return;
        }

        changed(this, new PropertyChangedEventArgs(propertyName));
    }
}

Comment regarding code:

*

*I strongly recommend you should put INotifyPropertyChanged in a base class or ViewModel

*You can use choose which IsBusy implementation is better. They are doing the same but with different syntax.

One more thing to add:
Take a look at MVVM pattern. With MVVM approach you can split View from logic (will should be in ViewMode). In your case the BindingContext will be ViewModel.
What's more, take a look at PropertyChanged.Fody nuget for INotifyPropertyChanged classes.

A: The best loader for xamarin forms is this : https://github.com/aritchie/userdialogs
void UserLogin()
{
    Device.BeginInvokeOnMainThread (() => UserDialogs.Instance.ShowLoading ("Loading ...", MaskType.Black));
    Task.Run (() => {
        //add Login method here
    }).ContinueWith (result => Device.BeginInvokeOnMainThread (() => {
        UserDialogs.Instance.HideLoading ();
    }
}));


text:
Q: How can I draw an image part by part? class DrawIma extends JPanel{
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);
        for (int i=0;i<20;i++){
            for (int j=0;j<20;j++) {
                g.drawImage(BuArr[i*20+j], 20*i, 20*j, 20, 20, null);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

In this part, BuArr are the 400 blocks divided from a BufferedImage, now i want them to be draw one by one, but the method can not draw the blocks separately, how can i do this?

A: Swing is single thread and not thread safe.
This means that you should not perform any long running or blocking (Thread.sleep) operations within the IU thread (the Event Dispatching Thread).  It also means that you can not update, modify or create UI elements outside of the EDT context.
Instead, use a Swing Timer to generate a repeated callback at a specified interval and render the portions of the image to something like a BufferedImage, which you can the paint to the component via its paintComponent method...
See Concurrency in Swing and How to use Swing Timers for more details
Because it was a good time waster
This generates a List of Rectangles which represent the individual blocks I want to paint, I then randomise the List and run the Timer, picking the top most Rectangle off the List and using BufferedImage#getSubImage to draw it from the master to the buffer, which gets painted to the screen...

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestImage {

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

    public TestImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage master;
        private BufferedImage copy;

        private List<Rectangle> blocks;

        public TestPane() {
            setBackground(Color.BLACK);
            try {
                master = ImageIO.read(new File("..."));
                copy = new BufferedImage(master.getWidth(), master.getHeight(), BufferedImage.TYPE_INT_ARGB);
                Graphics2D g2d = copy.createGraphics();
                AlphaComposite composite = AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f);
                g2d.setComposite(composite);
                g2d.setColor(new Color(0, 0, 0, 0));
                g2d.fillRect(0, 0, master.getWidth(), master.getHeight());
                g2d.dispose();

                int blockSize = 40;

                int width = master.getWidth();
                int height = master.getHeight();

                float aspect = Math.min(width, height) / (float) Math.max(width, height);

                int blockHeight = blockSize;
                blocks = new ArrayList<>(blockSize * 2);
                for (int y = 0; y < master.getHeight(); y += blockHeight) {
                    if (y + blockHeight > master.getHeight()) {
                        blockHeight = master.getHeight() - y;
                    }
                    int blockWidth = blockSize;
                    for (int x = 0; x < master.getWidth(); x += blockWidth) {
                        if (x + blockWidth > master.getWidth()) {
                            blockWidth = master.getWidth() - x;
                        }
                        Rectangle block = new Rectangle(x, y, blockWidth, blockHeight);
                        blocks.add(block);
                    }
                }
                Collections.shuffle(blocks);
                Timer timer = new Timer(40, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (blocks.isEmpty()) {
                            ((Timer) e.getSource()).stop();
                        } else {
                            Graphics2D g2d = copy.createGraphics();
                            Rectangle block = blocks.remove(0);
                            g2d.drawImage(master.getSubimage(block.x, block.y, block.width, block.height), block.x, block.y, TestPane.this);
                            g2d.dispose();
                            repaint();
                        }
                    }
                });

                timer.start();

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return master == null ? new Dimension(200, 200) : new Dimension(master.getWidth(), master.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (copy != null) {
                int x = (getWidth() - copy.getWidth()) / 2;
                int y = (getHeight() - copy.getHeight()) / 2;
                g2d.drawImage(copy, x, y, this);
            }
            g2d.dispose();
        }

    }

}


text:
Q: intermittent EXC_BAD_ACCESS in static audio-analysis function I am writing an iOS app that uses live audio analysis. It has an intermittent crash (after ~5 min, only on the Simulator. While this means it's not of concern for a shipping app, it sure is a pain for development, and besides, I'll sleep better at night if I track it down. The crash always happens in the same place, in a static function in my audio-analysis code: The crash has happened here:
struct Tone {
// (other stuff)

// THIS is the problem function:
static bool dbCompare(Tone const& l, Tone const& r) { return l.db < r.db; }
  }
};

And also here:
Tone const* findTone(double minfreq = 70.0, double maxfreq = 700.0) const {
    if (m_tones.empty()) { m_oldfreq = 0.0; return NULL; }
    double db = std::max_element(m_tones.begin(), m_tones.end(), Tone::dbCompare)->db;
    Tone const* best = NULL;
    double bestscore = 0;
    for (tones_t::const_iterator it = m_tones.begin(); it != m_tones.end(); ++it) {

    // ON THIS LINE. Is my iterator somehow becoming invalid?:
        if (it->db < db - 20.0 || it->freq < minfreq || it->age < Tone::MINAGE) continue;
        if (it->freq > maxfreq) break;
        double score = it->db - std::max(180.0, std::abs(it->freq - 300.0)) / 10.0;
        if (m_oldfreq != 0.0 && std::fabs(it->freq/m_oldfreq - 1.0) < 0.05) score += 10.0;
        if (best && bestscore > score) break;
        best = &*it;
        bestscore = score;
    }
    m_oldfreq = (best ? best->freq : 0.0);
    return best;
}

(Ok, this fix, below, is wrong per @Justin. I'm leaving it here for completeness, for now at least).
In an attempt to survive any null pointers that might get passed in, I added some checks and attempts at error-handling:
struct Tone {
    static bool dbCompare(Tone const& l, Tone const& r) {
    try {
      if (&l == NULL || &r == NULL) throw 1;
      return l.db < r.db;
      throw 1;
    }
    catch(int e) {
      NSLog(@"AUDIO ERROR: Pointer invalid. %d", e);
    }
    return 0;
  }
};

No dice, it still fails on the same line. Am I misunderstanding try-catch-throw? Is the error just happening further back up the pipeline?
This bit of code is from the open-source Rock-Band-style game Performous, and their game doesn't have this problem. (It's also not for the iPhone.) So this gives me hope that I can eliminate the Simulator crash...
EDIT 2 Per @Justin I am running with GuardMalloc. Simulator 5.0 gives immediate crash— there seem to be some SO questions about this but for now I'm running the 4.3 simulator, which gives the crash in the normal fashion, but with nothing else I know how to use:
#0  0x94f38c97 in malloc_error_break ()
#1  0x94efa4ce in szone_error ()
#2  0x94efc35f in allocate_pages ()
#3  0x94f013cc in allocate_pages_securely ()
#4  0x94f019b8 in szone_malloc_should_clear ()
#5  0x94f0266b in szone_malloc ()
#6  0x00331cc3 in GMmalloc_zone_malloc ()
#7  0x94f38edb in malloc_set_zone_name ()
#8  0x94f394a8 in _malloc_initialize ()
#9  0x94f3986b in malloc ()
#10 0x00002ef0 in start ()
#11 0x00013f1d in std::_List_const_iterator<Tone> std::max_element<std::_List_const_iterator<Tone>, bool (*)(Tone const&, Tone const&)>(std::_List_const_iterator<Tone>, std::_List_const_iterator<Tone>, bool (*)(Tone const&, Tone const&)) at /Developer/of_007_iphone/apps/cwi007/SingXO/SingXO/Pitch/pitch.hh:25
#12 0x000139b2 in Analyzer::findTone(double, double) const ()
#13 0x00011950 in -[AppDelegate timerCallback:] ()
#14 0x00115308 in -[CCTimer update:] ()
#15 0x0011e124 in -[CCScheduler tick:] ()
#16 0x0014993a in -[CCDirectorIOS drawScene] ()
#17 0x0014bda4 in -[CCDirectorDisplayLink mainLoop:] ()
#18 0x007baa88 in CA::Display::DisplayLink::dispatch(unsigned long long, unsigned long long) ()
#19 0x007babcd in CA::Display::EmulatorDisplayLink::callback(__CFRunLoopTimer*, void*) ()
#20 0x019c88c3 in __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ ()
#21 0x019c9e74 in __CFRunLoopDoTimer ()
#22 0x019262c9 in __CFRunLoopRun ()
#23 0x01925840 in CFRunLoopRunSpecific ()
#24 0x01925761 in CFRunLoopRunInMode ()
#25 0x020bb1c4 in GSEventRunModal ()
#26 0x020bb289 in GSEventRun ()
#27 0x00beac93 in UIApplicationMain ()
#28 0x00002fb6 in main ()

I also get this in the console:
GuardMalloc[MyApp-723]: *** mmap(size=2097152) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug

Oh, and of course, here's the function that NOW seems to be the likely culprit:
- (void)timerCallback:(NSTimer *)timer {
  Tone const * tone = audio->analyzer->findTone();
  if (tone && tone->db > kToneMinDB) {
    self.currentPitch = tone->freq;
    self.currentVolume = tone->stabledb;
    self.currentNoteName = [NSString stringWithCString:scale->getNoteStr(tone->freq).c_str() encoding:NSUTF8StringEncoding];
//    NSLog(@"Current Note Name in timerCallback: %@", currentNoteName);
    self.currentNoteFunction = [pitchFilter getPitchFunctionFromPitchName:currentNoteName];
  } else {
    self.currentNoteName = @"--";
    self.currentNoteFunction = -1;
  }

}
I don't understand how the program is entering the if (tone) block without a valid tone, or conversely how it can crash if the tone is valid. Help?
(This is getting long. Should I delete some of it in the service of a more-focused question?)
Things I'm thinking:
1. It's a threading issue ::shudder:: where one thread is changing the audio data while another one is reading it.
2. Something in the timerCallback function is corrupting, I dunno, the stack because it's alloc'ing too often. This function gets called a lot, but not an extreme amount; it's scheduled for every 150 ms.
Not sure why either of these would be an issue in the simulator but not on the device, though.

A: A C++ reference can never be 0/NULL. If it were, you're already well into Undefined Territory. You will have to move your tests up in the execution chain if the parameters may be 0.
That is to say, the only well formed version of dbCompare looks like this:
struct Tone {
    static bool dbCompare(Tone const& l, Tone const& r) {
        return l.db < r.db;
    }
};

Update
Your iterator would be invalid if it were resized while you iterate -- I don't see that happening in this implementation. Are you resizing the container from another thread?
Also, try running it with GuardMalloc - it aims to make these issues obvious to you. By failing sooner, it will be more local to the implementation (in many cases).

A: The ' best = &*it' line looks odd to me. Is the container storing by reference or value?   It seems like you might be returning the address of temporary storage.  That could cause problems down the line.


text:
Q: Solving an integral with from compound distribution of two Normal Distributions with a Uniform Distribution I'm looking to solve an integral that arises when trying to find the probability density of a random variable that is distributed uniformly as $\mathcal{U}(a,b)$, but whose endpoints, $(a,b)$, are themselves distributed by the same normal distribution $\mathcal{N}(0,\sigma)$, where $\sigma$ is the standard deviation.
The integral to be done is
\begin{align}
\frac{1}{2\pi \sigma^2}\iint_{-\infty}^\infty \frac{1}{|b-a|} \text{rect} \left[ \frac{x - (a+b)/2}{b-a} \right] \exp \left[ - \frac{(a^2 + b^2)}{2 \sigma^2} \right]\, \text{d} a \text{d} b,
\end{align}
where the rect$(x)$ function is defined as 1 when $|x|<1/2$ and 0 otherwise. Note here that it does not matter if $a<b$ or $b<a$.
This integral looks solvable, but organizing the limits and such may prove to be tedious. Numerically, it looks like the solution should itself look similar to another Gaussian.
Any ideas on how to solve or set up the limits of this integral?


text:
Q: How to use std::conditional to set type depending on template parameter type I have a templated class:
template<typename T>
class Foo
{
    X x;
}

For Foo< P > I wish X to be int.
For Foo< Q > I wish X to be float.
I am attempting the following on ideone:
#include <iostream>
#include <typeinfo>
using namespace std;

class P{};
class Q{};

template<typename T>
class Base
{
    using Xint = conditional<typeid(T)==typeid(P), int, float>;
    Xint x;
public:
    void Foo() { cout << typeof(x); }
};

int main() {
    Base<P> p;      cout << p.Foo() << endl;
    Base<Q> q;      cout << q.Foo() << endl;

    return 0;
}

http://ideone.com/KzIILu
However, this does not compile.
What's the correct way to do this?

A: You should use compile-time checks, not runtime.
using Xint = typename conditional<is_same<T, P>::value, int, float>::type;


text:
Q: In Laravel 5.7 React app, getting the error: 'classProperties' isn't currently enabled I'm very new to React.js. I installed Laravel 5.7 and swapped Vue.js scaffolding with React by running this command:
php artisan preset react

Now the problem is, I cannot assign anything to the state inside a component.
For example if I do the following inside the component:
state = { foo: false };

I got the error:
ERROR in ./resources/js/components/Root.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: D:\xampp\htdocs\smart-school-v0.1\resources\js\components\Root.js: Support for the experimental syntax 'classProperties' isn't currently enabled (8:11):

I installed:
@babel/plugin-proposal-class-properties

and updated .babelrc (Babel configuration file) like this:
{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [
      "@babel/plugin-proposal-class-properties"
  ]
}

I followed this but no luck.
Package.json
{
    "private": true,

    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "@babel/plugin-proposal-class-properties": "^7.2.3",
        "@babel/preset-env": "^7.2.3",
        "@babel/preset-react": "^7.0.0",
        "axios": "^0.18",
        "babel-preset-react": "^6.23.0",
        "bootstrap": "^4.0.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^4.0.13",
        "lodash": "^4.17.5",
        "popper.js": "^1.12",
        "react": "^16.2.0",
        "react-dom": "^16.2.0",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.15.3",
        "sass-loader": "^7.1.0"
    },
    "dependencies": {
        "react-router-dom": "^4.3.1"
    }
}

.babelrc
 {
    "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
    ],
    "plugins": [
        "@babel/plugin-proposal-class-properties"
    ]
 }

Root.js Component
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

export default class Root extends Component {

    state = { foo: false };

    render() {

        return (

Loaded

        );
    }
}

if (document.getElementById('app')) {
    ReactDOM.render(<Root />, document.getElementById('app'));
}

It is not working as expected and I'm keep getting this error:
Syntax Error: SyntaxError: D:\xampp\htdocs\smart-school-v0.1\resources\js\components\Root.js: Support for the experimental syntax 'classProperties' isn't currently enabled (19:11):

17 |
18 |
> 19 |     state = { foo: false };
    |           ^
20 |
21 |     render() {
22 |

Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation.

@ ./resources/js/app.js 14:0-28
@ multi ./resources/js/app.js ./resources/sass/app.scss
                                                                                Asset     Size   Chunks
    Chunk Names
/css/app.css  0 bytes  /js/app  [emitted]  /js/app
/js/app.js  593 KiB  /js/app  [emitted]  /js/app

ERROR in ./resources/js/components/Root.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: D:\xampp\htdocs\smart-school-v0.1\resources\js\components\Root.js: Support for the experimental syntax 'classProperties' isn't currently enabled (19:11):

Please help me out.
Thanks in advance.

A: Simple Add this to your
package.json
"babel": {
        "presets": [
          "@babel/preset-env",
          "@babel/preset-react"
        ],
        "plugins": [
            "@babel/plugin-proposal-class-properties"
        ]
    }

A: *

*Cretae .babelrc file in root folder.

*Write in .babelrc:

{ "plugins": ["@babel/plugin-proposal-class-properties"] }

*Run npm install --save-dev @babel/plugin-proposal-class-properties

*Run npm run dev

Hope it will help you.

A: I just tested on Laravel Framework 5.7.19 and the following steps work:

*

*Make sure your .babelrc file is in the root folder of your application, and add the following code:

{
  "plugins": ["@babel/plugin-proposal-class-properties"]
}

*Run npm install --save-dev @babel/plugin-proposal-class-properties.

*Run npm run watch.

A: You can simply

*

*create .babelrc file and paste this code in your .babelrc file
{  "plugins": ["@babel/plugin-proposal-class-properties"]  }

*and now run npm install --save-dev @babel/plugin-proposal-class-proper

*and finally run npm run watch
done

A: Just add these lines to your Package.json file:
"babel": {
        "presets": [
            "@babel/preset-env",
            "@babel/preset-react"
        ],
        "plugins": [
            "@babel/plugin-proposal-class-properties"
        ]
    }


text:
Q: Any way to get null(empty) columns using IN condition in oracle? without using is null? I have a table(employee) like below:
  EMPNO    ENAME      JOB          MGR HIREDATE        SAL       COMM     DEPTNO
  -------- ---------- --------- ------ ---------- -------- ---------- ----------
      7369 SMITH                  7902 17/12/1980      800                    20
      7499 ALLEN      SALESMAN    7698 20/02/1981     1600        300         30
      7521 WARD                   7698 22/02/1981     1250        500         30
      7566 JONES      MANAGER     7839 02/04/1981     2975                    20
      7654 MARTIN     SALESMAN    7698 28/09/1981     1250       1400         30
      7698 BLAKE                  7839 01/05/1981     2850                    30
      7782 CLARK      TESTER      7839 09/06/1981     2450                    10

Here what i need to get is: employee number, name and job where job IN ('SALESMAN', 'MANAGER' and NULL(empty)).
I prepared a query by using is NULL
select empno, ename, job
from employee
where job in('SALESMAN', 'MANAGER') or job is null;

Is there any way, other than above Query?
can i pass null in side IN condition?

A: use nvl function:
select empno, ename, job
from employee
where nvl(job, 'NULL') in('SALESMAN', 'MANAGER', 'NULL')


text:
Q: Descobrir quantos dias passaram de uma data até outra Em um programa em java, onde a pessoa insere primeiro o dia, depois o mes, depois o ano, como faço para saber quantos dias passaram dessa data inserida até outra data posterior que também será informada pela pessoa?
Por exemplo:
Primeira data informada: 20/10/1990
Segunda data informada: 23//05/2005
Como faço para saber a quantidade total de dias que passaram?

A: A Date-Time API do Java 8 facilitou muito esse tipo de operação.
Para o seu problema em específico podemos nos valer das unidades ChronoUnit. O método between faz exatamente o que você está querendo.
LocalDate begin = LocalDate.of(1990, Month.OCTOBER, 20);
LocalDate end = LocalDate.of(2005, Month.MAY, 23);
long days = ChronoUnit.DAYS.between(begin, end); // 5329

Exemplo funcional no Ideone

A: Solução a partir do Java 1.4 focado no seu problema:
String dataUm = "20/10/1990";
String dataDois = "23/05/2005";

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); // dd/MM/yyyy é o formato brasileiro que você está usando, para mais formatos, veja o link de referência

Date dateUm = simpleDateFormat.parse(dataUm);
Date dateDois = simpleDateFormat.parse(dataDois);

long diferencaEmMilisegundos = dateDois.getTime() - dateUm.getTime();

/**
 * divide por 1000 para converter em segundos
 * divide por 60 para converter em minutos
 * divide por 60 novamente para converter em horas
 * divide por 24 para converter em dias
 */
System.out.println(diferencaEmMilisegundos / 1000 / 60 / 60 / 24);

*

*Link para visualizar os formatos de SimpleDateFormat


text:
Q: List and modal in framework7 I am trying to fix this problem 2 days and I am a rookie in Javascript
Currently I am Using visual studio + Cordova + Framework 7
var pet1 = select_all('pet');

    $$('#pet1').empty();

    $$.each(pet1, function (index, value) {

        $$('#pet1').append('
'
            + '
'
            + '
'
            + '          '
            + '
'
            + '
'
            + '
'
            + '
' + value.title + '
'
            + '
Element label
'
            + '
'
            + '
' + value.description + '
'
            + '
Additional description text
'
            + '
'
            + '
'
            + '
');

    });

and this work well
after that i found a documentation in Framework 7 that call Modal With Slider
and the code is in here http://framework7.io/docs/modal.html
which call open-slider-modal
I don't know why cant copy the code

But the problem for me is I don't know how to add this code into it
Please help me , between sorry for my bad English.
thanks everyone

A: Okay I finished it myself already , will post the answer here for help the others who facing same problem like me
var pet1 = select_all('pet');

$$('#pet1').empty();

$$.each(pet1, function (index, value) {

    $$('#pet1').append('
'
        + '
'
        + '
'
        + '          '
        + '
'
        + '
'
        + '
'
        + '
' + value.title + '
'
        + '
Element label
'
        + '
'
        + '
' + value.description + '
'
        + '
Additional description text
'
        + '
'
        + '
'
        + '
');

});

just
continue the code below
$$('.open-slider-modal').on('click', function () {
  var modal = myApp.modal({
    title: 'Awesome Photos?',
    text: 'What do you think about my photos?',
    afterText:  '
'+
                  '

'+
                  '
'+
                    '

' +
                    '

'+
                  '
'+
                '
',
    buttons: [
      {
        text: 'Bad :('
      },
      {
        text: 'Awesome!',
        bold: true,
        onClick: function () {
          myApp.alert('Thanks! I know you like it!')
        }
      },
    ]
  })
  myApp.swiper($$(modal).find('.swiper-container'), {pagination: '.swiper-pagination'});
});

and then
first change the
$$('.open-slider-modal').on('click', function () {

to
$$(document).on('click', '.open-slider-modal', function () {

change the class inside your list

'

you will be done


text:
Q: WPF MVVM Validation on passthrough property on VM I am trying to use IDataErrorInfo for validation in WPF+MVVM. I followed MSDN article of how to implement it. The question is that what do I do with the pass through property on the VM?
For example,
public class A : INotifyPropertyChanged, IDataErrorInfo
{
    protected string _Name;
    public string Name
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
            OnPropertyChanged("Name");
        }
    }

    public string this[string propertyName]
    {
        get
        {
            string result = null;

            if (propertyName == "Name")
            {
                if (Name == "ABC")
                {
                    result = "Name cannot be ABC";
                }
            }

            return result;
        }
    }
}

public class ViewModel : INotifyPropertyChanged
{
    A a = new A();

    public string ModelName
    {
        get
        {
            return a.Name;
        }
        set
        {
            a.Name = value;
            OnNameChanged();
            OnPropertyChanged("ModelName");
        }
    }
}

<TextBox Name="txtName" Text="{Binding Path=ModelName, ValidatesOnDataErrors=True}" />

What do I have to do on the view model so that I don't have to re-validate the Name property again on the view model?
Thanks

A: What you need is to expose your whole Class A through your ViewModel.
This blog post (is not perfect but) show an easy way to do it: http://www.eidias.com/Blog/2012/7/2/simple-validation-in-wpf-mvvm-using-idataerrorinfo
Also you have an interesting discussion on How to display the error on this topic: MVVM pattern, IDataErrorInfo and Binding to display error?

A: Validation occurs on the class that has the binding set. In your case it is the ViewModel. If you have to have pass through properties then just implement the IDataErrorInfo on the ViewModel and have that pass through also
//ViewModel
public string this[string propertyName]
{
    get
    {
        if (propertyName == "ModelName")
        {
            return a["Name"];
        }

        return null;
    }
}

I do not know of a way around not having the IDataErrorInfo on the ViewModel in your case


text:
Q: Orderer Key-Value structure in objective c In my application I need to send a JSON to the server. The order of the JSON is important.
I tried to use NSMutableDictionary and then use NSJSONSerialization to convert the dictionary to JSON. But the orderer is messed up.
What other options do I have to have a key-value structure but maintain the insertion order?


text:
Q: Soundpool play several times android I have Problem playing soundpool .
I am new to education in Android and I hope you will help me.
I created class to load soundpool
 public class Suond {

    protected  static int suond1 ,suond2,suond3,suond4,suond5,suond6,suond7;
    protected  static  SoundPool sou;
    protected  static  AudioAttributes aa;

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")

    protected static void oi(Context Con ){

         if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP){

             aa = new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_GAME)
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .build();

 sou = new SoundPool.Builder().setMaxStreams(10)
.setAudioAttributes(aa).build();

                  suond1 = sou.load(Con,R.raw.Music1,1);
                  suond2 = sou.load(Con,R.raw.Music2,1);
                  suond3 = sou.load(Con,R.raw.Music3,1);
                  suond4 = sou.load(Con,R.raw.Music4,1);
                  suond5 = sou.load(Con,R.raw.Music5,1);
                  suond6 = sou.load(Con,R.raw.Music6,1);
                  suond7 = sou.load(Con,R.raw.Music7,1);
                           }

             else{ sou = new SoundPool(10,AudioManager.STREAM_MUSIC,1);

                  suond1 = sou.load(Con,R.raw.Music1,1);
                  suond2 = sou.load(Con,R.raw.Music2,1);
                  suond3 = sou.load(Con,R.raw.Music3,1);
                  suond4 = sou.load(Con,R.raw.Music4,1);
                  suond5 = sou.load(Con,R.raw.Music5,1);
                  suond6 = sou.load(Con,R.raw.Music6,1);
                  suond7 = sou.load(Con,R.raw.Music7,1);

                 }

                }

    }

I also have 10 buttons representing levels in the game In each button textview Contains a value used with an animated listener for each text view At the end of the listener, use soundpool.
valueAnimator.addListener(new Animator.AnimatorListener() {
      @Override
      public void onAnimationStart(Animator animation) {

        suond.sou.play(Suond.suond1, 1, 1, 1, 0, 1);

      }

      @Override
      public void onAnimationEnd(Animator animation) {

          Suond.sou.play(Suond.suond2, 1, 1, 1, 0, 1);

      }

      @Override
      public void onAnimationCancel(Animator animation) {

      }

      @Override
      public void onAnimationRepeat(Animator animation) {

      }
    });

 valueAnimator.setDuration(2000);
 valueAnimator.start();
 }

Each button has a listener connected to each other, where when the listener plays the first button, the animation starts with the second and third button to the tenth button respectively. Everything goes well but when the animation reaches the eighth button and sometimes the ninth or tenth the sound disappears until the activity leaves and returns two or three times to the sound activity back to play.
In my guess I think the sound stopped because of playing several times in a row but when I read about Soundpool it's dedicated to playing short sounds and can play more than  sound at the same time can play up to 16 sounds at the same time in my application sounds are not playing At the same time but respectively and that the sounds he used did not exceed 30 KB.
I don't know what is wrong.
Why the sound stops playing when you play it several times in a row.
I use Android 4.0
Thank you very much and hope to help me with any solutions.

A: (1) You have typo's in your code so how did you get it to compile ?
Suond.sou.play(Suond.suond2, 1, 1, 1, 0, 1);
suond.sou.play(Suond.suond1, 1, 1, 1, 0, 1);

anyway it should be:
Suond.sou.play(Suond.suond2, 1, 1, 1, 0, 1);

(2) MaxStreams is set to 10 so you can only have 10 concurrent streams (not 16):
sou = new SoundPool.Builder().setMaxStreams(10).setAudioAttributes(aa).build();
else{ sou = new SoundPool(10,AudioManager.STREAM_MUSIC,1);

(3) keep track of your active sounds (Suond.sou.play returns an integer):
int streamID = Suond.sou.play(Suond.suond2, 1, 1, 1, 0, 1);//streamID better as an integer array

(4) Remember to tidy-up after you leave the activity (If you're not going to use it after the activity finishes, then release in onDestroy().):
//loop round your active sounds
sou .stop(streamID) ;stop ONE active sound
sou .release();


text:
Q: How to create multiple processes by using fork() to keep splitting the array and get the index of the given number // arr[0] = 1, arr[1] = 2, arr[2] = 3, arr[3] = 4, arr[4] = 5, arr[5] = 6, arr[6] =7, arr[7] = 8.
// count = 8  which is the length of the array in this case
// value = 6 which is the value that is being searched

int get_first(int arr[], int count)
{
   int half = count / 2;
   int *firstHalf = malloc(half * sizeof(int));
   memcpy(firstHalf, arr, half * sizeof(int));
   return firstHalf;
}

int get_second(int arr[], int count)
{
    int half = count / 2;
    int *secondHalf = malloc(half * sizeof(int));
    memcpy(secondHalf, arr + half, half * sizeof(int));
    return secondHalf;
}

pid_t  pid;
pid = fork();
if (pid == 0)
  {
      int half = count / 2;
      int *result = get_first(arr, count);

      while (sizeof(result) != 1)
      {
          half = half / 2 ;
          int *result = get_first(result, half);
      }
      if (result[0] == value[0])
      {
          return the index of value
      }
  }

else
  {
      int half = count / 2;
      int *result1 = get_second(arr, count);

      while (sizeof(result1) != 1)
      {
          half = half / 2 ;
          int *result1 = get_second(result1, half);
      }
      if (result1[0] == value[0])
      {
          return the index of value
      }
  }

I am new to c and I am really not good at fork(). I need to write a program that uses multiple processes to keep splitting an array into two equal parts. When the array only has a single element, the process will compare the single element to the integer being searched for.
For example, to split an array 5, 6, 7, 8. P1 creates two children, P2 which is assigned to search 5, 6, and P3 which is assigned to search 7, 8. P2 creates two children, P4 which is assigned to search 5, and P5 which is assigned to search 6. P3 creates two children P6 which is assigned to search 7, and P7 which is assigned to search 8.
I wrote two functions to split the array and they are both working fine. The first function gets the first part of the array and the second function gets the second part of the array (I did not write the indexing part because I have not got to there yet). But I am struggling with the fork(). I think the way I am using fork() does not help me to get the right answer, because it does not get to every element in the array.
My question is how to change the fork() in order to allow it to compare every element in the array with the value that I am searching for. Can someone help me to fix it? Thanks in advance.

A: When fork() returns it returns (on success) in two processes (the calling process and its new child process). Both starts with same code (the first command after fork()). The child process gets an exact copy of the memory in its current state. Thus, although all variables have now its own "incarnation" in their process they have the identical values like just before the fork() in the parent process.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

/* the type of array elements: */
typedef int Value;

/** fills the sample array with values.
 *
 * For this sample, it's simply filled with conscutive values.
 *
 * @param n the size of array
 * @param arr the array
 */
void fillArray(size_t n, Value *arr)
{
  Value value; /* aux. to provide value to set */
  size_t i; /* loop index */
  value = 0;
  for (i = 0; i < n; ++i) arr[i] = value++;
}

/** searches for value in two processes concurrently.
 *
 * @param n the size of array
 * @param arr the array
 * @param pivot the value to search for
 */
void search(size_t n, Value *arr, Value pivot)
{
  size_t n_2 = n / 2;
  if (!n) return; /* nothing to do */
  printf("search %d...\n", (int)pivot); /* assumes (int)pivot makes sense */
  if (n_2 >= 1) {
    pid_t pid;
    pid = fork();
    if (pid < 0) {
      fprintf(stderr, "ERROR: fork failed!\n");
      return;
    }
    if (pid == 0) { /* in child process */
      size_t i;
      for (i = n_2; i < n; ++i) {
        if (arr[i] == pivot) break;
      }
      if (i < n) { /* element at i is a hit */
        printf("Hit %d (found in child)\n", (int)i);
      }
    } else { /* in parent process */
      size_t i;
      for (i = 0; i < n_2; ++i) {
        if (arr[i] == pivot) break;
      }
      if (i < n_2) { /* element at i is a hit */
        printf("Hit %d (found in parent)\n", (int)i);
      }
      /* terminate child process */
      exit(0); /* funny things happen if this were not here */
    }
  } else { /* special case: only 1 element in array */
    if (arr[0] == pivot) {
      printf("Hit 0 (found)\n");
    }
  }
}

int main(int argc, char **argv)
{
  /* should become input: */
  size_t n; /* the size of array */
  Value *arr; /* the array */
  /* get number of values */
  n = 10;
  /* allocate space for array */
  arr = (Value*)malloc(n * sizeof (Value));
  /* fill array */
  fillArray(n, arr);
  /* make some sample searches */
  search(n, arr, (Value)3);
  search(n, arr, (Value)7);
  /* clean-up */
  free(arr);
  /* done */
  return 0;
}

I tried this with gcc on cygwin. (Cygwin seems to support fork() on Windows - for my surprise.)
Output:
$ gcc --version
gcc (GCC) 5.4.0
Copyright (C) 2015 Free Software Foundation, Inc.

$ gcc -o forkSearch forkSearch.c

$ ./forkSearch
search 3...
Hit 3 (found in parent)
search 7...
Hit 7 (found in child)

Live Demo on coliru
What I didn't solve in this sample is (IMHO) the actual challenge: how to pass the found value from child to parent process (in case).


text:
Q: Why is this giving me NullPointerException? I am creating a word-by-word palindrome ("yes I can, can I yes?") as follows:
'''
public class Palindrome {
LinkedQueue<String> queue;
LinkStack<String> stack;

public Palindrome() {
    LinkedQueue<String> queue = new LinkedQueue<>();
    LinkStack<String> stack = new LinkStack<>();
}

public boolean isPalindrome(String sentence) {

    String[] sentenceSplit = sentence.split(" ");

    for(String word : sentenceSplit) {
        queue.enqueue(word.toLowerCase());
        stack.push(word.toLowerCase());
    }

    while (stack.top() == queue.front()){
            stack.pop();
            queue.dequeue();
    }

    if(stack.size() == 0) {
        return true;
    }
    return false;
}

public static void main(String[] args) {
    Palindrome test = new Palindrome();
    test.isPalindrome("can you you can");
}

}
'''
In here, it says I receive a nullpointerexception during my for each loop where I enqueue and push each string in the string array, I have tested the strings in the string array and they do exist, so why am I receiving this error? Thanks.

A: Change
LinkedQueue<String> queue = new LinkedQueue<>();
LinkStack<String> stack = new LinkStack<>();

to
queue = new LinkedQueue<String>();
stack = new LinkStack<String>();

A: You constructor is declaring variables but you use your class attributes that are not initialized.
Move the content of your constructor into your class' attributes.
Also, you might want to use .equals instead of == when comparing Strings in
"while (stack.top() == queue.front())".


text:
Q: SQLAlchemy - Different name for inherited column I have the following sql alchemy models:
class Employee(Base):
    __tablename__ = "employee"
    name = Column(String)

class Manager(Employee):
    __tablename__ = "manager"
    manager_name = Column(String)

I want manager_name to represent the column name in the base class. Is there a way to do it?

A: seems like this solves the issue:
class Employee(Base):
    __tablename__ = "employee"
    name = Column(String)

class Manager(Employee):
    __tablename__ = "manager"
    manager_name = Employee.name


text:
Q: Enterprise integration testing fixture setup I am trying to test a component in a new online shopping system written using "enterprise integration patterns (EIP)". The component observes customers' shopping behaviour and makes suggestions along the way.
The way EIP works allows such component to be written easily, but I am having extreme difficulties setting up test fixtures for this component. In this system, much of the data have some logical connection which each other, which requires them to be varied together. This translates to tests with hundreds lines of setup, which is not maintainable.
I am now evaluating three solutions:
1. Create our own builders for all messages and response objects:
Purpose:
* Insulates the tests from some changes.
* Allows better fixture code reuse. (Can set some defaults in the builders.)
Pros/cons:
Each test will still require a significant amount of code to setup, but is largely future-proof. Data consistency is entirely up to the programmer.
2. Connected builders:
Basically add some methods to the builders from solution 1 to fill fields of each other. For example, there may be methods on the order builder to generate the search and page view histories.
Purpose:
* Further reduces the amount of fixture setup in each test
* Improves the consistency of fixtures
Pros/cons:
The builders are highly complex and may become maintenance issues of their own.
3. Emulate interactions with real services
Purpose: similar to solution 2
Pros:
* The data will be more real and consistent
* Easier to setup elaborate tests data (e.g. page view history)
Cons:
* Very complex and highly externally dependent
* The code used to describe/carry out the emulated actions may be just as long
* Slow to run
4. Locally (re-)implemented services
Purpose:

*

*Solves the external dependency in solution 3 by re-implementing simple versions of the services locally

*Reduce the number of test code required (compared to solution 3) by extrapolating actions from the end results (see solution 2)

Pros/cons:
* Much more reliable than solution 3, but requires a lot of implementation
My question:
Any better solutions? If not, which one would you have chosen? Also, would you have chosen differently if the method chosen here will be applied to all other services in the future?

A: From my experience testing services that rely heavily on data, here are some suggestions:

*

*Absolutely use real data, not test data. I think you've already mentioned it can be very painful to hand mock data since it changes often and can be complex/large.

*Be able to re-generate the real data quickly. It's not too hard to write a tool to take a one time dump of data and use that, but ideally when the data models change, you can easily take another snapshot of data and use that.

*Avoid complex code. You've covered this already. No one will keep up the quality of the tests if the complexity is too large.
The approach I've settled on for the time being that I like is the following:

*

*Make sure all database calls/external dependencies sit behind interfaces. This allows you to mock data. Seems like you have this down.

*Create a special implementation of an interface that does two things: a) Makes a live database call, b) Saves the result of the database call to a JSON file.

*When you need to create a snapshot of real data, you swap out your production implementation of a given interface for the one from (2). Then you go through a few use cases and JSON files get written to disk.

*Your test start up code simply needs to read JSON from disk and hydrate objects.
This has worked really well for me as it allows for quick copies of real data and it is very easy to update when the data changes.
There's obviously some work involved, but the code required is not terribly complex.


text: Q: Отлавливать изменение изображений в галерее Есть автоматическая галерея(слайд шоу)на главной странице сайта, необходимо изменять текст в блоке параллельно с изображением. Подскажите как отследить изменение в блоке с изображением?


text:
Q: Generalized partial fraction decomposistion Consider two functions  $ v(x)$ and $u(x)$.
And, you want to break
$$ \frac{1}{u(x) v(x)}.$$
Then, why can't you do $$ \frac{1}{ u(x) v(x)} = \frac{A}{u(x)} + \frac{B}{v(x)},$$ implying
$$ 1 = Av(x) + Bu(x)?$$
And, then put zeros of $u(x)$ and $v(x)$ to solve for constants.
Consider, $(x-b)^3 =v(x)$ and, $ (x-a)^2 = u(x)$. I decomposed this as
$$\frac{1}{(b-a)^2(x-b)^3} +  \frac{1}{(a-b)^3 (x-a)^2}.$$
However this is wrong. Why? I heard it has something to do with poles and all but I haven't done complex analysis yet.

A: The equation $\frac 1 {u(x)v(x)} =\frac  A {u(x)}+\frac  B {v(x)}$ is same as $1=Av(x)+Bu(x)$. If $u$ and $v$ are polynomials then this equation can only hold when $u$ and $v$ are constants. Hence you cannot, in general, find constants $A$ an $B$ so as to satisfy this equation.

A: Please note that one can have the following decomposition$$\frac{1}{u(x)v(x)}=\frac{A}{u(x)}+\frac{B}{v(x)},$$where $A$ and $B$ are constants, implying$$1=Av(x)+Bu(x),$$only if there exist constants $A$ and $B$ such that the above relations hold.
So, one cannot conclude that such decomposition always exists for any functions $u(x)$ and $v(x)$. Even if $u(x)$ and $v(x)$ are polynomials, the latter relation usually does not hold because of degree mismatch of both sides. For example, in your example, $u(x)=(x-a)^2$ and $v(x)=(x-b)^3$, the relation$$1=A(x-b)^3+B(x-a)^2$$ is not correct because the degree of both sides are not equal.


text:
Q: Tool for searching & analyzing results from multiple search engines Are there any tools/programs which can simultaneously search multiple search engines and analyze the results?

A: Copernic is very popular ... and free for personal use.

Copernic Agent makes every Web search
  a super-search with this intelligent
  tool, trusted by millions of users
  worldwide.

If you want a web-based solution, try WolframAlpha


text:
Q: AC Signal Conditioning for ADC (Design Choices) I have a low frequency (50Hz) signal which can be positive or negative (centered around system ground) depending on the mode selected.  The signal has a maximum amplitude of +/- 12V.  So, just to be clear, when one mode is selected, the signal is positive from 0 to 12V and when the other mode is selected, the signal is negative from 0 to -12V.
Now, I would like to digitize this signal using a 12bit ADC (MCP3208 - datasheet) and it's fine (preferable perhaps) if the signal is rectified so that it is always positive.
So, I have two main choices: I can rectify and scale my signal, which will give me more digital precision or I can DC bias and scale the signal with the obvious loss of digital precision (converting 0-12V, as opposed to converting 0-24V).  Option #1 would seem the obvious choice, but my concern is with the precision rectifier circuit.
The question then is: which option will distort the signal the least and (in essence) how precise are precision rectifier circuits when compared to a simple buffered voltage divider?
I should add that in this application maintaining the shape of the signal is important, more important than resolution, I think.

A: Looking at your choice of ADC you have 8 input channels. Why not have 1 input just scaled and a second input inverted and scaled.
Otherwise you need to AC couple but at this (low) frequency you probably need a fairly large quality capacitor, buffer and scaling to your ADC.
I don't think a precision rectifier is what you want; you'll loose all negative signal.
EDIT
Just found this article describing an absolute value circuit. At 50Hz I would expect precision to be good. You are always going to get some additional distortion from any diode based op-amp circuit.

A: One choice is to use a 14 bit A/D and have it convert the full ± input range.
If you truly don't care about the sign of the input, only its absolute value, then a active precision rectifier circuit sounds like a reasonable choice.
You say the signal is 50 Hz, but that its wave shape is important.  Therefore the bandwidth is higher than 50 Hz.  You need to specify how high it needs to be.  For example, if up to the 100th harmonic is good enough, then the active rectifier needs to work up to 5 kHz.  That should still be doable to 12 bits with good parts.

A: With a rectifier, your measurement setup will be blind below the forward voltages of the diodes, which is a nonlinearity and will cause harmonics to show up.
Level shifting the signal is the better choice here, IMO. You should leave a bit of extra headroom (e.g. -14 .. 14 V) so you don't hit the extremes because of manufacturing tolerances.
If you can oversample, you can get some extra precision bits there as well.


text:
Q: Group representations and short exact sequences Let $0 \rightarrow A \rightarrow B \rightarrow C \rightarrow 0$ be a short exact sequence of groups. What can be said about group representations of $B$ if we assume a complete classification of the representations of $A$ and $C$? Precisely, assume we have determined the categories $Rep_R(A)$ and $Rep_R(C)$ of $R$-linear representations for a commutative ring $R$, up to equivalence.
If the sequence splits, then by identifying a representation of $B$ with its "classifying map" $B\rightarrow Aut(M)$ for an $R$-module $M$, we classify a representation of $B$ with its component representations of $A$ and $C$, so it seems like we have an equivalence between $Rep_R(B)$ and the pullback of the diagram $$ Rep_R(A) \rightarrow Mod_R \leftarrow Rep_R(C) $$ where both maps are the canonical forgetful functors taking a map $A \rightarrow Aut(M)$, say, to $M$.

What can be said if the sequence does not split?

I am most interested in the case when $B$ is a semidirect product of $A$ and $C$. I was inspired to ask this by this question, which asks about the specific case of the sequence $$0\rightarrow SO(n) \rightarrow O(n) \rightarrow \mathbb{Z}_2 \rightarrow 0$$

A: Even in the simplest case of a direct product, so that $B=A\times C$, this is complicated. The pullback of
$$Rep_R(A) \rightarrow Mod_R \leftarrow Rep_R(C)$$
will give $R$-modules with actions of $A$ and $C$ that don't necessarily commute, so representations of the free product $A*C$ rather than the direct product $A\times C$.
If $R$ is a field of characteristic $p>2$ and $A$ and $C$ are cyclic groups of order $p$ then there's a fairly simple classification of modules for $RA$ and $RC$, but classifying $R[A\times C]$-modules is a "wild" problem that there's no hope of solving.


text:
Q: OpenVPN server with internal DNS nameservers I have a OpenVPN 2.4.6 x86_64-redhat-linux-gnu running on Centos 7 AWS ec2 instance.
I also have 2 internal company DNS nameservers that I can query internal hostnames from (working fine)
Whenever employees connect to our subnets via OpenVPN, I want their laptops to use our internal DNS nameservers for name resolution, but no matter how many combinations of configs I tried, I cant get the connecting client to use the internal DNS for name lookup (the client, Ubuntu, is using its local /etc/resolv.conf for lookups of internal hostnames, not our own DNS)
heres my openvpn server.conf,
port 1194
proto udp
dev tun
user nobody
group nobody
persist-key
persist-tun
keepalive 10 120
topology subnet
management 127.0.0.1 5555
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt

push "redirect-gateway def1"
**push "dhcp-option DOMAIN company.ec2us"
push "dhcp-option DNS xxx.xxx.91.251"
push "dhcp-option DNS xxx.xxx.126.93"**

push "route 192.xxxx.xxx.0 255.255.255.0"  # ABC1 subnet
push "route 192.xxxxx.0 255.255.255.0"  # NYC office LAN
push "route 208.xxxx.0 255.255.255.0"  # XYZ internal

crl-verify crl.pem
ca ca.crt
cert server_v8OxxxxxxxFCOK.crt
key server_v8ORxxxxxx7FCOK.key
tls-auth tls-auth.key 0
dh dh.pem
auth SHA256
cipher AES-128-CBC
tls-server
tls-version-min 1.2
tls-cipher TLS-DHE-RSA-WITH-AES-128-GCM-SHA256
status /var/log/openvpn/status.log
verb 3

the client OVPN file looks like this,
client
proto udp
remote xxx.xxx.155.45 1194
dev tun
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
verify-x509-name server_v8ORQmlxxxxFCOK name
auth SHA256
auth-nocache
cipher AES-128-CBC
tls-client
tls-version-min 1.2
tls-cipher TLS-DHE-RSA-WITH-AES-128-GCM-SHA256
dhcp-option DOMAIN company.ec2us
dhcp-option DNS xxx.xxx.91.251
dhcp-option DNS xxx.xxx.126.93

verb 3
<ca>
-----BEGIN CERTIFICATE-----

xxxxxx
    -----END CERTIFICATE-----

    Certificate:
     xxxxxx

I can see that the server is giving out the DNS options,
Wed Feb 27 17:06:48 2019 PUSH: Received control message: 'PUSH_REPLY,redirect-gateway def1,dhcp-option DOMAIN company.ec2us,dhcp-option DNS xxx.xxx.91.251,dhcp-option DNS xxx.xxx.126.93,route xxx.xxx.40.0 255.255.255.0,route xxx.xxx.30.0 255.255.255.0,route xxx.xxx.251.0 255.255.255.0,route-gateway 10.8.0.1,topology sub

But once connected on the client, if I do nslookup $name-of-internal -host, its using my default 8.8.8.8 thats in my /etc/resolv.conf
Is there a way to force clients to use internal DNS hosts?


text:
Q: How to know which X509 Certificate Signed another Certificate (Java) There are three certificates in my example, assume they form a chain but i don't know yet which of them signed which:
X509Certificate c1 = ....
X509Certificate c2 = ....
X509Certificate c2 = ....

I would like to know which certificate is responsible for signing the other certificate.
The plan was to get the "AuthorityKeyIdentifier" and match it with the "SubjectKeyIdentifier".
import org.bouncycastle.asn1. DEROctetString;

private static String decodeKey(byte[] e) {
    DEROctetString octet = new DEROctetString(e);
    return octet.toString();
}

String subjectKeyId = decodeKey(c.getExtensionValue("2.5.29.14"));
String authorityKeyId = decodeKey(c.getExtensionValue("2.5.29.35"));

Im getting the following for the certificates (in order of the chain): subject/authority key ID pair
Values of the SubjectKeyIdentifier and AuthorityKeyIdentifier  after Decoding:
Certificate 1: (end of the chain)
#0416041482b7384a93aa9b10ef80bbd954e2f10ffb809cde
#04183016801482b7384a93aa9b10ef80bbd954e2f10ffb809cde

Certificate 2: Signed by Certificate 1
#04160414ab8059c365836d1d7d13bd19c3ec1a8f0d476aa3
#04183016801482b7384a93aa9b10ef80bbd954e2f10ffb809cde

Certificate 3: Signed by Certificate 2
(no SubjectKeyIdentifier - null bytes)
#041830168014ab8059c365836d1d7d13bd19c3ec1a8f0d476aa3

Formatted and Aligned for Easy Reading (Same thing as the one on top)
------------------------------------------------------------------------------
       01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
------------------------------------------------------------------------------
Certificate 1
#04 16 04 14       82 b7 38 4a 93 aa 9b 10 ef 80 bb d9 54 e2 f1 0f fb 80 9c de
#04 18 30 16 80 14 82 b7 38 4a 93 aa 9b 10 ef 80 bb d9 54 e2 f1 0f fb 80 9c de

Certificate 2
#04 16 04 14       ab 80 59 c3 65 83 6d 1d 7d 13 bd 19 c3 ec 1a 8f 0d 47 6a a3
#04 18 30 16 80 14 82 b7 38 4a 93 aa 9b 10 ef 80 bb d9 54 e2 f1 0f fb 80 9c de

Certificate 3
=== == == == == == == == == == == NO DATA  == == == == == == == == == == == ==
#04 18 30 16 80 14 ab 80 59 c3 65 83 6d 1d 7d 13 bd 19 c3 ec 1a 8f 0d 47 6a a3

I was expecting c3's AuthorityKeyIdentifier to be equivalent to c2's SubjectKeyIdentifier. that does not seem to be the case here.
EDIT: some parts of the result seem to match, I have some idea on the "SubjectKeyIdentifier" - it always starts with '#04' followed by the length of the contents (in hex). I now have a certain idea on how to decode the "SubjectKeyIdentifier", but the "AuthorityKeyIdentifier" is still a big mystery to me.
relevant SO post
Did i do anything wrong with the decoding?
Why are the AuthorityKeyIdentifier not matching correctly against the SubjectKeyIdentifier of the certificate that signed it?

A: If you take a look at the ASN.1 definition of SKI and AKI in RFC5280 (following the links in your question) the difference becomes obvious:
SubjectKeyIdentifier ::= KeyIdentifier

AuthorityKeyIdentifier ::= SEQUENCE {
  keyIdentifier             [0] KeyIdentifier           OPTIONAL,
  authorityCertIssuer       [1] GeneralNames            OPTIONAL,
  authorityCertSerialNumber [2] CertificateSerialNumber OPTIONAL  }

KeyIdentifier ::= OCTET STRING

So, the AKI is not an OCTET STRING, but a SEQUENCE of three optional elements. One of these elements is the octet string that can be compared to an SKI.
The Distinguished Encoding Rules (DER) determine the byte representation of these ASN.1 structures. The individual bytes of an AKI extension have the following meaning (see A Layman's Guide to a Subset of ASN.1, BER, and DER):
04 18 30 16 80 14 82 b7 38 4a 93 aa 9b 10 ef 80 bb d9 54 e2 f1 0f fb 80 9c de

04 OCTET STRING
18 LENGTH
30 SEQUENCE
16 LENGTH
80 CONTEXT-SPECIFIC PRIMITIVE TAG 0
14 LENGTH
.. DATA

The first two bytes (04 18) are part of the Extension structure (as explained in the related question Why doesn't my key identifier match?), the actual AKI extension content starts at "30 16".
Your Java code for decoding the AKI should look like this (using Bouncy Castle):
byte[] extensionValue = cert.getExtensionValue("2.5.29.35");
byte[] octets = DEROctetString.getInstance(extensionValue).getOctets();
AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(octets);
byte[] keyIdentifier = authorityKeyIdentifier.getKeyIdentifier();
String keyIdentifierHex = new String(Hex.encode(keyIdentifier));

And for decoding SKI:
extensionValue = cert.getExtensionValue("2.5.29.14");
octets = DEROctetString.getInstance(extensionValue).getOctets();
SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier.getInstance(octets);
keyIdentifier = subjectKeyIdentifier.getKeyIdentifier();
keyIdentifierHex = new String(Hex.encode(keyIdentifier));

Also, both extensions are optional. If your code should work with arbitrary certificates, then a fallback mechanism is necessary (like verifying the signatures).

A: If you're looking for a really quick check, just open the certificate in windows and look for a tab called "Certification Path". It also lets you easily traverse up through the certificate chain if applicable. (I'd post a picture, but apparently don't yet have enough reputation.)


text:
Q: About the uniqueness of the displacement current In the Maxwell-Ampère equation, i.e.:
\begin{equation}
\nabla\times\vec{B} = \mu_0 \vec{J} + \mu_0\epsilon_0 \frac{\partial \vec{E}}{\partial t}
\end{equation}
the $\vec{J}_d$ term:
$$ \vec{J}_d := \epsilon_0 \frac{\partial \vec{E}}{\partial t} $$
was derived by taking the divergence of the left hand side of the equation.
Explicitly, before Maxwell's addition of the $\vec{J}_d$ term Ampère's law  was:
$\nabla\times\vec{B} = \mu_0 \vec{J}$, but when acting with $\nabla \cdot$ we had:
$$ 0 \equiv \nabla \cdot \left(\nabla\times\vec{B}\right) = \mu_0 \nabla\cdot\vec{J} = -\mu_0 \frac{\partial \rho}{\partial t} $$ from the $\text{div}(\text{curl}\ \bullet)$ identity and the continuity equation. But $\frac{\partial \rho}{\partial t} $ is not necessarily zero so we need to add a new term let's call it $\vec{J}_d$. And now comes my question. We need $\vec{J}_d : \nabla\cdot\left( \vec{J} + \vec{J}_d \right) = 0 \Rightarrow \nabla \cdot \vec{J}_d = \frac{\partial \rho}{\partial t} $. And indeed $\vec{J}_d = \epsilon_0 \frac{\partial \vec{E}}{\partial t}$ is a solution, but for this "test of the divergence"
$$\vec{J'}_d = \epsilon_0 \frac{\partial \vec{E}}{\partial t} + \vec{k}$$
where $\vec{k}$ is a constant vector, or even
$$\vec{J''}_d = \epsilon_0 \frac{\partial \vec{E}}{\partial t} + \nabla \times \vec{T}$$ where $\vec{T}$ is any vector, satisfy $\nabla\cdot\left(\nabla\times\vec{J}_d\right) = 0$. Why, then does $\vec{J}_d$ has the form it has and not any of the other possible solutions presented above?
Thanks in advance.

A: But surely that is not the only constraint.
If
$$\vec{J'}_d = \epsilon_0 \frac{\partial \vec{E}}{\partial t} + \vec{k}$$
then
$$
\nabla\times\vec{B} = \mu_0 \vec{J} + \mu_0\epsilon_0 \frac{\partial \vec{E}}{\partial t} + \mu_0 \vec{k}
$$
This implies that even without any current or time-dependent electric field there is a non-conservative magnetic field. But without currents or time-dependent electric fields we know that the B-field is curl-free.

A: First off, you can't define
$$\vec{J'}_d = \epsilon_0 \frac{\partial \vec{E}}{\partial t} + k$$
because you'd be adding a vector to a scalar, so we're left with your second idea:
$$\vec{J}_d = \epsilon_0 \frac{\partial \vec{E}}{\partial t} + \nabla \times \vec{T}$$
If we take this to be the value of $\vec{J}_d$, then Ampere's law becomes
$$\nabla\times\vec{B} = \mu_0 \vec{J} + \mu_0\epsilon_0 \frac{\partial \vec{E}}{\partial t} + \nabla \times \vec{T}$$
Consider a circumstance where the electric field is constant ($\frac{\partial \vec{E}}{\partial t} = 0$) and there are no currents ($\vec{J} = 0$). Your modified Ampere's law predicts that
$$\nabla\times\vec{B} = \nabla \times \vec{T}$$
But experimentally, we find that in such circumstances,  $\nabla \times \vec{B} = 0$, so we conclude that $\nabla \times \vec{T} = 0$

A: The other answers say some interesting things about the consequences of this term, but the biggest reason it's not there is that all experiments have confirmed Maxwell's equations as we know them, and there is no evidence that a modification would be necessary.
After all, the equations are not unique: for example, they could easily be modified to include magnetic monopoles and they would be made more symmetrical. But nobody has ever seen a magnetic monopole, and so they don't appear in Maxwell's equations.

A:
Explicitly, before Maxwell's addition of the $\vec{J}_d$ term Ampere's law  was:
  $\nabla\times\vec{B} = \mu_0 \vec{J}$

The important thing to understand with all this is that Ampere's law is about conduction current, and conduction current is not the only current. Have a look at Taming Light at the Nanoscale:
"Look around, and you will probably see numerous electronic and optical gadgets, such as mobile phones, personal digital assistants, laptops, TVs and digital cameras. These may all do different things but they have one thing in common: in the electronic circuits that drive these devices, charged particles flow through components and impart power via what is known as the conduction current. But is the motion of charged particles the only current we have available?"
The answer is no, because we also have displacement current. It's "a time-varying electric field", and that's exactly what we see when an electromagnetic wave passes us by. There is no charged particle present, but the displacement current is present, and it's alternating: the field-variation increases to a maximum, then decreases back to zero. Note that we could put this wave through pair production, so we can convert displacement current into charged particles. Then when we move them, we call the phenomenon conduction current. Also note that because of this, displacement current is more fundamental than conduction current. And that knowing all this makes it clear that the original version of Ampere's law doesn't go far enough:
"Ampère's law determines the magnetic field associated with a given current, or the current associated with a given magnetic field, provided that the electric field does not change over time".

Why, then does $\vec{J}_d$ has the form it has and not any of the other possible solutions presented above?

Because of what displacement current is. Maxwell effectively worked backwards from Ampere and conduction current, and ended up saying "light consists of transverse undulations in the same medium that is the cause of electric and magnetic phenomena". When people read this they tend to think of sinusoidal E and B waves:
Image courtesy of mathematica
However that doesn't go far enough either. See the Wikipedia electromagnetic radiation article:
"Also, E and B far-fields in free space, which as wave solutions depend primarily on these two Maxwell equations, are in-phase with each other. This is guaranteed since the generic wave solution is first order in both space and time, and the curl operator on one side of these equations results in first-order spatial derivatives of the wave solution, while the time-derivative on the other side of the equations, which gives the other field, is first order in time, resulting in the same phase shift for both fields in each mathematical operation."
E is the spatial derivative of the wave, and B is the time derivative. So the real wave is the integral of the E and B sine waves. I'll illustrate this with a canoe analogy: imagine you're in a canoe as a ten-metre ocean wave* approaches. Your canoe starts to slope upwards, slowly at first, then faster, then the slope starts to flatten out, and your canoe is momentarily horizontal on the top of the wave. At this point displacement current is at a maximum, at the mid-point of the E and B sine waves. Then the process is reversed, something like this:

The slope of your canoe denotes E, and the rate of change of slope denotes B. One is the spatial derivative, the other is the time derivative. The displacement current is represented by the current of water that lifted you bodily up ↑ by ten metres, then let you down ↓ again. It has a vector nature, and the |direction| is the polarization direction. We write it as:
$$\vec{J}_d = \epsilon_0 \frac{\partial \vec{E}}{\partial t}$$
Adding a constant k would be like repeating the canoe scenario in deeper water. The wave is 10m high, so the deeper water won't alter the tilt of your canoe or how high you go. You can't add something to one side of the expression because each side is telling you about one aspect of the wave, and you can't change one side without changing the other.
* without a trough


text:
Q: Facebook app with Kohana 3 Using FB in a site is simple
require_once 'facebook-php-sdk/src/facebook.php';
// Create our Application instance.

$facebook = new Facebook(array(
  'appId' => 'zzzz',
  'secret' => 'zzz',
  'cookie' => true,
));

I have tried the following in the bootstrap.php
include Kohana::find_file('vendors/Facebook', 'facebook');
//gives correct path, facebook.php is 755

The Facebook class is written as:
class Controller_Facebook extends Controller{}

$this->facebook = new Facebook(array('appId' => 'zzz', 'secret' => 'zzz',  'cookie' => true,));

//the line above causes the error below
ErrorException [ Fatal Error ]: Class 'Facebook' not found

Has anyone solved this problem before?
If so, then how do I access $this->facebook in the controllers

A: I think you have a typo in the path, you want:
include Kohana::find_file('vendor/Facebook', 'facebook');

'vendor/' instead of 'vendors/' in the path.

A: Take a look on a zombor's Facebook module. You can extend it for your needs (seems like it has only authorization features).


text:
Q: Section and subsection in header I have a rather simple problem that I can not solve, I am only trying to get both the section and subsections in the header (using fancyhdr). However, I don't seem to be able to get that done. I would like to get on the left the section or subsection and on the right the page numbering. Currently I am using the following code:
\pagestyle{fancy}

\fancyhead[L]{\rightmark}
\fancyhead[R]{\thepage}
\fancyfoot[L]{}
\fancyfoot[C]{}
\fancyfoot[R]{}

But in the beginning, I am having 3 chapters with no subsection and hence the header only displays the page numbering. I tried different combinations of rightmark and leftmark but I didn't get it the way I want. So, I am trying to get the section in the header unless there is a subsection, then I want the subsection in the header. Any ideas how to get that done?
Thank you
Jonas

A: You want to redefine \subsectionmark (that by default does nothing) to issue a mark:
\documentclass[a4paper,oneside]{report}

\usepackage{fancyhdr}

\usepackage{kantlipsum} % for mock text

\pagestyle{fancy}
\fancyhf{} % clear all fields
\fancyhead[L]{\rightmark}
\fancyhead[R]{\thepage}

\renewcommand{\subsectionmark}[1]{%
  \markright{\MakeUppercase{\thesubsection.\ #1}}}%
}

\begin{document}

\chapter{Chapter title}

\kant[1]

\section{Section title}

\kant[2-7]

\subsection{Subsection title A}

\kant[8-10]

\subsection{Subsection title B}

\kant[11-14]

\subsection{Subsection title C}

\kant[15-18]

\end{document}

A: are you familiar with the package scrlayer-scrpage? This one allows you to modify your page layout a bit more in detail. It takes a while to read through the documentation and it is not too easy to find exactly what you are looking for. However, a good Google search in combination with scrlayer-scrpage will help you further.
I created a small example, which always put the "active" element in the Header, which is the {section, subsection, etc} mentioned last. I uncommented some lines (%lehead to %cofoot). You can use those if you want to write a specific term at a certain Position, like your Name for example. This is for documents like books where you have two pages next to each other. First letter can be l (left) c (Center) or r (right) than e (for even numbered page) or o (for odd numbered pages) and then head for the Header and foot for the foot part of the page.
Please check if you can compile it and if it is what you were looking for.
Best regards, Bastien
\documentclass[a4paper,11pt]{scrartcl}

\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage[automark, headsepline, footsepline]{scrlayer-scrpage}

\clearpairofpagestyles
\automark*{section}
\automark*{subsection}
\automark*{subsubsection}
\ihead{\headmark}
\ohead*{\pagemark}

%\lehead{}
%\rehead{}
%\lohead{}
%\rohead{}
%\cefoot{}
%\cofoot{}

\pagestyle{scrheadings}

\begin{document}
    \section{Section A}
    \blindtext
    \subsection{Subsection a}
    \blindtext
    \blindtext
    \subsection{Subsection b}
    \blindtext
    \blindtext
    \newpage
    \subsection{Subsection c}
    \blindtext
    \section{Section B}
    \blindtext
    \subsection{Subsection c}
    \blindtext
    \blindtext
    \subsection{Subsection d}
    \blindtext
    \newpage
    \section{Section C}
    \blindtext
    \subsection{Subsection e}
    \blindtext
\end{document}


text:
Q: SQL Running total previous 3 months by date and id This is a simplification of the table q3 I'm working with:
      Partno EndOfMonth AA AS EA ES
        a    31.5.2017   5  1  0  1
        b    31.5.2017   3  1  0  1
        c    31.5.2017   2  2  0  1
        a    31.6.2017   1  2  2  2
        b    31.6.2017   1  0  1  2
        c    31.6.2017   2  3  1  4
        a    31.7.2017   4  3  2  0
        b    31.7.2017   3  0  6  0
        c    31.7.2017   4  1  0  0

I need to sum the numbers in the last four columns for each part in Partno so that the sum represents the running total of the last three months at each date in the EndOfMonth column.
The result i'm looking for is:
      Partno EndOfMonth AA AS EA ES
        a    31.5.2017   5  1  0  1
        b    31.5.2017   3  1  0  1
        c    31.5.2017   2  2  0  1
        a    31.6.2017   6  3  2  3
        b    31.6.2017   6  1  1  3
        c    31.6.2017   4  5  1  5
        a    31.7.2017   10 6  4  3
        b    31.7.2017   7  1  7  3
        c    31.7.2017   8  6  1  5

So e.g. for partno A at 31.7.2017 the last thee months' sum for the 'AA' column is 4+1+5=10.
I'm quite new to SQL and am well and truly stuck with this. I've tried something like the following to just get a simple rolling total (without even specifying the sum range to be the last 3 months). Also, I'm not sure if the database even supports all the functions in the below code, since it's giving me the error "Incorrect Syntax near the keyword 'OVER'"
  SELECT
    Partno,
    EndofMonth,
    SUM(q3.AA) OVER (PARTITION BY q3.Partno ORDER BY EndofMonth ROWS UNBOUNDED PRECEDING) as 'AA'
FROM q3

Anyway, any help would be greatly appreciated!
Thanks
EDIT:
Thanks to Benjamin and with a little help from this post: https://dba.stackexchange.com/questions/114403/date-range-rolling-sum-using-window-functions
I was able to find the solution:
SELECT a.Partno, a.EndofMonth, SUM(b.AA) as 'AA', SUM(b.AS) as 'AS',...
FROM q3 a, q3 b
WHERE a.Partno = b.Partno AND a.endOfMonth >= b.endOfMonth
    AND b.endOfMonth >= DATEADD(month,-2,a.endOfMonth)
GROUP BY a.Partno, a.endOfMonth

A: Something like this might work:
SELECT a.Partno, a.EndofMonth, SUM(b.AA) as AA
FROM q3 a, q3 b
WHERE a.Partno = b.Partno
    AND DATEDIFF(month, b.endOfMonth, a.endOfMonth) < 4
GROUP BY a.Partno, b.Partno

This assumes that endOfMonth is in datetime format, if it is not you will have to use convert(). Note that you might have to replace DATEDIFF() depending on what implementation you are using.
I haven't tested this, so I might be way off. It has been a while since I worked with SQL. Hopefully you can get it working by messing around with it a bit, and if not then maybe it will inspire you to write something better. Let me know how it goes!


text:
Q: How Sign a PDF File using a Ceritificate PKCS11, SmartCard-eToken and itextsharp in .NET? Sorry, but I don't speak english, and I will do my best.
I tried to sign a PDF document with a digital certificate from PKCS # 11 type in C #. NET 4.0. As you know such a certificate requires a private key, in my case is stored on an Aladdin eToken, and then make a signature using itextsharp.
I tried with CAPICOM, System.Security.Cryptography, BouncyCastle, Chilkat, Net.Pkcs11, etc. But no works.
PdfSignatureAppearance has the method SetCrypto(key, cert, ..., ...) , where the first parameter is the key of the certificate and the second parameter is the same certificate, but I can't get the private key of the eToken. Hey read and think this is impossible.
I'm using C # native, using cryptography. NET in a few lines of code:
X509Certificate2 x509 = (Certificate from X509Certificate2Collection);
CspParameters cspParams = new CspParameters(1",eToken Base Cryptographic Provider", "Default")
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspParams))
{
byte[] signature = rsa.SignData(x509.RawData, "SHA1");
//I don't know how join it with itextsharp
rsa.PersistKeyInCsp = false;
rsa.Clear();
}

I think I can use the method SignData(), but I'm a little confused. How I can relate itextsharp.
I found much documentation but nothing specific, such as java applets do not work because I have Windows 7 64 bits, and codes. NET does not work. I would, if possible, use the same core. NET or free libraries with support for Windows 7 64 bits. Someone did a real solution?
Also I would like to know how to delete the eToken PIN cache since it only asks me for the password once and then stays in memory.
Please I need your help.
Thank you.

A: I've found this great framework to work with tokens: pkcs11.net
found in here: http://sourceforge.net/projects/pkcs11net/
The thing is:
with the rsa private key and certificate you got from the token, you it with use IText to sign. With the key, is the plain signing you are shown in IText's web site.
You see, pdf signing is different from pkcs7 signing, and that is different from xml signing.
Post a comment if you need more info


text:
Q: How to run one batch in pytorch? I'm new to AI and python and I'm trying to run only one batch to aim to overfit.I found the code:
iter(train_loader).next()
but I'm not sure where to implement it in my code. even if I did, how can I check after each iteration to make sure that I'm training the same batch?
train_loader = torch.utils.data.DataLoader(
    dataset_train,
    batch_size=48,
    shuffle=True,
    num_workers=2
)

net = nn.Sequential(
    nn.Flatten(),
    nn.Linear(128*128*3,10)
)

nepochs = 3
statsrec = np.zeros((3,nepochs))

loss_fn = nn.CrossEntropyLoss()
optimizer = optim.Adam(net.parameters(), lr=0.001)

for epoch in range(nepochs):  # loop over the dataset multiple times

    running_loss = 0.0
    n = 0
    for i, data in enumerate(train_loader, 0):
        inputs, labels = data

         # Zero the parameter gradients
        optimizer.zero_grad()

        # Forward, backward, and update parameters
        outputs = net(inputs)
        loss = loss_fn(outputs, labels)
        loss.backward()
        optimizer.step()

        # accumulate loss
        running_loss += loss.item()
        n += 1

    ltrn = running_loss/n
    ltst, atst = stats(train_loader, net)
    statsrec[:,epoch] = (ltrn, ltst, atst)
    print(f"epoch: {epoch} training loss: {ltrn: .3f}  test loss: {ltst: .3f} test accuracy: {atst: .1%}")

please give me a hint

A: If you are looking to train on a single batch, then remove your loop over your dataloader:
for i, data in enumerate(train_loader, 0):
    inputs, labels = data

And simply get the first element of the train_loader iterator before looping over the epochs, otherwise next will be called at every iteration and you will run on a different batch every epoch:
inputs, labels = next(iter(train_loader))
i = 0
for epoch in range(nepochs):
    optimizer.zero_grad()
    outputs = net(inputs)
    loss = loss_fn(outputs, labels)
    loss.backward()
    optimizer.step()
    # ...


text:
Q: What is an easy way to update PHP from 5.2.0 to 5.2.14 on Debian? I want to update my version of PHP from 5.2.0 to 5.2.14 (or later, but I don't want to upgrade to 5.3 for compatibilty reasons).
Every guide I find to upgrade PHP is for updating to the last available version, but I dont't find a way to update to a specific version.
The easiest and quickest the solution, the best

A: I would suggest:

*

*identify php-related packages you installed on the system; packages like php5-cli, php5-cgi, libapache2-php5

*Pock around packages.debian.org to see what is the latest available version of php 5.2.

*Download these packages manually.

*sudo dpkg -i *.deb at the directory you keep the debs

*lock the installed version, prevent accidentally upgrade by apt-get upgrade.

There are might be ways to probe versions available using just apt-get, if anyone knows please share.


text:
Q: Javascript and HTML5 File API - problems getting file correctly routed to function I am wondering how to define a file reference for an HTML5 'file' object, to be used as input to a JavaScript function that will convert the file into Base64 encoding, WITHOUT using an interactive file input element.  I have seen the HTML5Rocks examples, and numerous others, but they all use an <input type=file> element to read and gather inputs about the file to operate on. I am intending to take image files (i.e. binary) as input, and output Base64 strings. (Perhaps it is obvious, but I am new to the HTML5 and JavaScript worlds)
Some of my reading seems to indicate that this isn't possible for security reasons: JS would then be able to run arbitrary files. I wanted to double check.
What is the output of the 'file' input type? Can I manually mimic it in some way?  (I found one reference here about just directly including the file itself inside the JS, but can you do that with a binary file?  Frankly, not sure how I would do that on the FileMaker side, though, either. My plan, up to this point, was the export the file from FileMaker to a known location, then use that location as the input to the JavaScript)
  The whole picture: I am trying to create a self contained web-viewer element in FileMaker 12. In FileMaker, I can dynamically define my HTML and JavaScript BEFORE running it.  I want to dynamically hardcode the JavaScript to ALREADY contain the file reference based on the information from the database (i.e. path and filename). This is all running on a local machine, no server involved.
I am trying to minimize the interaction the end user has to make to get the file encoded:  I don't want them to have to put the image into the database, and then also have to drop (or file-chooser) the image again in the web viewer.  I want to keep all of this code inside the FileMaker database to make it much more portable and robust, i.e. not have to rely on an internet connection.  So, the user puts their file into the database, which automatically detects that event, it calculates the JavaScript (including the path to the file), and the JavaScript runs the Base64 function on it, returning the encoded string to the database.

 Perhaps I should do it the other way around:  have the user drop the file into a JavaScript area that then copies it into the database.  Not sure that the JavaScript would have any handles for interacting with the database, though.
------------------------   EDIT  (in addition to some tagging and flagging of original question)
Let's ignore the whole FileMaker side of things for now.  I decided to go the route of just using HTML5 and JavaScript as the file input portion (instead of trying to read it in FM and then output to JS).  Just to see if I can get the JavaScript part to work.
Here is some code that I am playing with right now.  It is mostly from the HTML5 Rocks demo, as well as the base64 encoding routine I found.  However, I am running into problems with exactly how to define and call my reader, the onload event, and the encoding function.  Any suggestions would be appreciated:

A: No, in web browsers you can't access arbitrary files on user's computer. Never ever.
You can get files from the network (but read contents only if they are from the same origin or allowed via CORS, and file:// protocol doesn't allow it), IndexedDB database and Chrome's sandboxed filesystem (which is not user's filesystem — it only contains files you've put there yourself).
And you can create "files" yourself:
var file = new Blob(["file content"], {type:"text/plain"})

Blob is the base class of File and it's generally usable everywhere where input.files[] is.
You may have privileges to access local files from other JS-based environments like Widgets or browser extensions.


text:
Q: Android SearchView open direction I have successfully moved my menu items to the left side of the Toolbar.
But unfortunately when SearchView opens it opens toward left so it get disappeared while only the close button of SearchView is visible.
How should i force SearchView to open to the right?

A: Whether SearchView expands to left or right is not easily switchable, it is a consequence of what SearchView layout is.
You can, however, try overriding the layout of SearchView in your theme. I haven't done this myself, you may need to wiggle the layout a bit to get it right.
Derive your theme from Theme.Material and override the searchViewStyle attribute with your custom style for search view:
<style name="MyTheme" parent="android:Theme.Material">
    <item name="android:searchViewStyle">@style/MySearchView</item>
</style>

Then, derive the custom search view style and override the layout attribute:
<style name="MySearchView" parent="android:Widget.Material.SearchView">
    <item name="android:layout">@layout/search_view</item>
</style>

And finally, create your custom layout/search_view.xml to adjust the layout the way you want it. Copy over the original search_view.xml and make any changes you need -- probably change order of search_src_text (line 79) and search_close_btn (line 98)
Don't forget to prefix all ids in the copied layout with android: (or not, if you're using the support lib variant, but that's another story, I'm sure you know what to do)

(Marcos Vasconcelos) This solution doesn't works prior of Android 4.0.
(Ivan Bartsov) Thanks for the edit, but it's not really true. Actually, prior to Android 5.0 (since it relies on Material theme, obviously) -- but it can be adjusted to be used with appcompat-v7 support library, which makes it suitable all the way down to 2.1. The OP obviously uses either Android 5.0+ or the support lib -- you may have noticed they're using Toolbar which is only available since API 21


text:
Q: SUMIF and COUNTIF for SQL I have some data that looks like this:
col1, col2, col3
A,    1.2,  A|X|Y|Z
B,    0.3,  B|X|Y|Z
X,    1.0,  X|Y|Z
Y,    0.2,  Y|Z
Z,    1.0,  Z

I want to select the rows where the item in col1 appears in the col3 pipe-delimited list other than its own list. And for each of those items, I want to count the number of rows where that item appears in col3, and also sum col2 where that condition is met. So the results should be something like this:
col1, foo,  bar
X,    2,    1.5
Y,    3,    2.5
Z,    4,    2.7

I've been trying to use CASE WHEN and LIKE to do this (see below), but it's not working. For foo I get all zeroes, and for bar I get null. Maybe I need some kind of subquery that I don't understand how to use?
SELECT
  col1,
  COUNT(CASE WHEN col3 LIKE col1 THEN 1 END) as foo,
  SUM(CASE WHEN col3 LIKE col1 THEN col2 END) as bar

FROM table

GROUP BY
  col1

A: You can do this with a self-join.  In standard SQL, it would look like:
select t.col1, count(*) as foo, sum(col2) as bar
from t join
     t t2
     on '|' || t2.col3 || '|' like '%|' || t.col1 || '|%'
group by t.col1;

The syntax might vary in the database you are actually using, but the idea should work with whatever string concatenation mechanism your database uses.

A: With a self join and aggregation:
SELECT t1.col1, COUNT(*) foo, SUM(t2.col2) bar
FROM tablename t1 INNER JOIN tablename t2
ON t2.col1 <> t1.col1 AND CONCAT('|', t2.col3, '|') LIKE CONCAT('%|', t1.col1, '|%')
GROUP BY t1.col1

The above code will work in MySql.
For other databases you can use their concatenation operators like || or +.
See the demo.
Results:
> col1 | foo | bar
> :--- | --: | --:
> X    |   2 | 1.5
> Y    |   3 | 2.5
> Z    |   4 | 2.7


text:
Q: Delete all login.keychain files Does anyone know a way to script the deletion all login.keychain files from all user directories on Mac OS X?  This is a lab environment bound to AD, and when a user changes their password, without correcting their keychain upon first login, it gets messy.  Mass deletion once a week (or logoff hook) seems easier than training students.

A: cron job with maybe rm -rf /Users/*/Library/Keychains but logoff hook might work better.


text:
Q: Is there a plugin that counts posts by author? I want to have a page listing all the authors and the number of posts each of them has published. Is there a plugin that does this already? Being able to count number of comments as well would be a plus.
Thanks for the help.

A: I don't know about a plugin but you can use this:
In author.php you can use this to count posts:
<?php
global $wp_query;
$curauth = $wp_query->get_queried_object();
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '" . $curauth->ID . "' AND post_type = 'post' AND post_status = 'publish'");
?>

Post Count: <?php echo $post_count; ?>

Inside a Loop you can use this to count posts and comments:
<?php
global $wpdb;
$user_id = $post->post_author;  //change this if not in a std post loop
$where = 'WHERE comment_approved = 1 AND user_id = ' . $user_id ;
$comment_count = $wpdb->get_var(
    "SELECT COUNT( * ) AS total
        FROM {$wpdb->comments}
        {$where}
    ");
$user = get_userdata($user_id);
$post_count = get_usernumposts($user->ID);
echo '
User ' . $user->display_name . ' post count is ' . $post_count .', comment count is ' . $comment_count . '
';
?>

For All Authors:
<?php
global $wpdb;
$where = 'WHERE comment_approved = 1 AND user_id <> 0';
$comment_counts = (array) $wpdb->get_results("
        SELECT user_id, COUNT( * ) AS total
        FROM {$wpdb->comments}
        {$where}
        GROUP BY user_id
    ", object);
foreach ( $comment_counts as $count ) {
  $user = get_userdata($count->user_id);
  $post_count = get_usernumposts($user->ID);
  echo '
User ' . $user->display_name . ' post count is ' . $post_count .', comment count is ' . $count->total . '
';
}
?>


text:
Q: Make a get/post request within controller in rails I have following code as action in controller:
class BuildPagesController < ApplicationController
 def add
  email= "abc@yahoo.com"
  name= "abc"
  # I want to make a get request/call
  # such as localhost:3000/save?email=abc@yahoo.com&name=abc

 #I tried the following but my console simply freezes
    post_url = "http://localhost:3000/save?email=abc@yahoo.com&name=abc"
    address = URI(URI.encode("#{post_url}"))
    http = Net::HTTP.new address.host, address.port
    request = Net::HTTP::Get.new address.request_uri
    http.start

 end
end

Another controller is as follows:
class SavePagesController < ApplicationController
 def save
  Page.create(email: params[:email], name: params[:name])
 end
end

routes.rb  is as follows:
  match 'add', to: 'build_pages#add', via: [:get,:post]
  match "save" => "save_pages#save", via: [:get,:post]