text:
Q: image picker/UIImagePickerController show blank screen/NavigationController swift 5 I am trying to get answer from this question answer link but failed :(
iOS UIImagePickerController showed blank page
Then I try below code but still show blank screen without image list :(
I think don't fire the delegation function
You can also check from GitHub
https://github.com/MdAshfaqurRahmanIOS/image-picker-3
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    var imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        imagePicker.delegate = self
    }
    @IBAction func buttonAction(_ sender: UIButton) {
        imagePicker.sourceType = .photoLibrary
        imagePicker.allowsEditing = true
        present(imagePicker, animated: true)
    }
}
extension ViewController: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerEditedImage")] as? UIImage {
            imageView.image = image
        }
        picker.dismiss(animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
}

Add this info.plist
key =>>>> Privacy - Photo Library Usage
value =>> please access photogallery

Console log

*

*2020-12-17 22:49:11.928762+0600 image-picker-3[1309:51223]
[lifecycle] [u B37332A2-92E0-4D65-981B-0DBBDB4534D9:m (null)]
[com.apple.mobileslideshow.photo-picker(1.0)] Connection to plugin
interrupted while in use. 2020-12-17 22:49:11.944027+0600
image-picker-3[1309:51223] [lifecycle] [u
B37332A2-92E0-4D65-981B-0DBBDB4534D9:m (null)]
[com.apple.mobileslideshow.photo-picker(1.0)] Connection to plugin
invalidated while in use. 2020-12-17 22:49:12.003410+0600
image-picker-3[1309:51015] UIImagePickerController UIViewController
create error: Error Domain=NSCocoaErrorDomain Code=4099 "The
connection to service on pid 0 named
com.apple.mobileslideshow.photo-picker.viewservice was interrupted,
but the message was sent over an additional proxy and therefore this
proxy has become invalid." UserInfo={NSDebugDescription=The
connection to service on pid 0 named
com.apple.mobileslideshow.photo-picker.viewservice was interrupted,
but the message was sent over an additional proxy and therefore this
proxy has become invalid.}

A: Try to follow my programmatically example below, first add your button and delegates to your controller and import Photo framework:
import UIKit
import Photos

class YourViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

lazy var takePicButton: UIButton = {
    let button = UIButton()
    button.backgroundColor = .red
    button.setTitle("Present img picker", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
    button.layer.cornerRadius = 14
    button.clipsToBounds = true
    button.addTarget(self, action: #selector(handlepickPicture), for: .touchUpInside)
    button.translatesAutoresizingMaskIntoConstraints = false

    return button
}()

now in viewDidLoad add button and set constraints:
override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(takePicButton)
    takePicButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20).isActive = true
    takePicButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20).isActive = true
    takePicButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20).isActive = true
    takePicButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
}

After that set your func to present image picker controller:
var imagePicker = UIImagePickerController()

@objc fileprivate func handlepickPicture() {

    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary
    imagePicker.view.tintColor = .white
    imagePicker.mediaTypes = ["public.image"]
    imagePicker.allowsEditing = true
    imagePicker.navigationBar.barTintColor = .black

    checkPermission()
}

check the permission, don't forget to set your info.plist privacy usage description (like you):
fileprivate func checkPermission() {
    let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
    switch photoAuthorizationStatus {
    case .authorized:
        print("Add Photo")
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
            print("Access is granted by user")
            self.present(imagePicker, animated: true, completion: nil)
        }
        print("Access is granted by user")
    case .notDetermined:
        PHPhotoLibrary.requestAuthorization({
            (newStatus) in
            print("status is \(newStatus)")
            if newStatus ==  PHAuthorizationStatus.authorized {
                /* do stuff here */
                DispatchQueue.main.async {
                    self.present(self.imagePicker, animated: true, completion: nil)
                }
                print("success")
            }
        })
        print("It is not determined until now")
    case .restricted:
        // same same
        print("User do not have access to photo album.")
        goToSetting()
    case .denied:
        // same same
        print("Text tapped...")
        goToSetting()
        print("User has denied the permission.")
    case .limited:
        goToSetting() // the function show an alert to enable Authorization manually
        print("User has denied the permission.")
    @unknown default:
        fatalError()
    }
}

write the function to set authorization manually:
fileprivate func goToSetting() {
    let title = "Oooooops!"
    let message = "Hi man, for use this App press Go To settings and enabled access to Pohto Gallery... Check read and write option and relaunch the App!"

    let alertController = UIAlertController(title: "", message: "", preferredStyle: .alert)

    let subview = (alertController.view.subviews.first?.subviews.first?.subviews.first!)! as UIView
    subview.backgroundColor = UIColor(white: 0, alpha: 0.2)

    alertController.setValue(NSAttributedString(string: title, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 18, weight: .heavy),NSAttributedString.Key.foregroundColor : UIColor.red]), forKey: "attributedTitle")
    alertController.setValue(NSAttributedString(string: message, attributes: [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 14, weight: .regular),NSAttributedString.Key.foregroundColor : UIColor.white]), forKey: "attributedMessage")

    let cancelAction = UIAlertAction(title: "Cancel", style: .destructive) { (_) in
        print("Action cancelled")
    }

    let goToSettingPermission = UIAlertAction(title: "Go To setting", style: .default) { (action) in
        UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:], completionHandler: nil)
    }

    alertController.addAction(goToSettingPermission)
    alertController.addAction(cancelAction)

    self.present(alertController, animated: true, completion: {
    })
}

this is the result, on dx the alert for manual authorization, on left the picker controller

If you don't see the preview photos, try to run app with another simulator device.

A: You can use it by taking these photos into a collectionView like this "I've made it using RxSwift:
import UIKit
import RxSwift
import Foundation
import Photos

private let reuseIdentifier = "ImageCell"

class ImagesCollectionViewController: UICollectionViewController {

//MARK: - vars
private var images = [PHAsset]()
private var selectedPhotoSubject = PublishSubject<UIImage>()
var selectedPhoto: Observable<UIImage> {
    return selectedPhotoSubject.asObservable()
}

//MARK: - LifeCycle
override func viewDidLoad() {
    super.viewDidLoad()
    linkPhotosLibrary()
    self.title = "Pick an Image"

}
//MARK: - PhotoLibrary
private func linkPhotosLibrary() {
    PHPhotoLibrary.requestAuthorization { [weak self] status in
        if status == .authorized {

            let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image,options: nil)
            assets.enumerateObjects { (object, count, stop) in
                self?.images.append(object)
            }
            self?.images.reverse()
            DispatchQueue.main.async {
            self?.collectionView.reloadData()
            }
        }

    }
}

// MARK: - UICollectionViewDataSource

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images.count
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCell

    let asset = images[indexPath.row]
    let manager = PHImageManager.default()

    manager.requestImage(for: asset, targetSize: CGSize(width: 200,height: 200), contentMode: .aspectFit, options: nil) { image, _ in

        DispatchQueue.main.async {
            cell.imageViewOutlet.image = image
        }
    }

    return cell
}

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let selectedAsset = images[indexPath.row]
    PHImageManager.default().requestImage(for: selectedAsset, targetSize: CGSize(width: 500, height: 500), contentMode: .aspectFit, options: nil) { [weak self] image , info in
        guard let info = info else {return}
        let isDegradedImage = info["PHImageResultIsDegradedKey"] as! Bool
        // as we will call this function 2 times one for the small image in the collection and one here that's why we use it as this will tell us if the image is thumbnail or original image
        if !isDegradedImage {

            if let image = image {
                self?.selectedPhotoSubject.onNext(image)
                self?.dismiss(animated: true, completion: nil)
            }
        }

    }
}

}
or you can use it normally:
    var myGallery: GalleryController!

    func showGalleryImages () {

        self.myGallery = GalleryController()
        self.myGallery.delegate = self
        Config.tabsToShow = [.imageTab, .cameraTab]
        Config.Camera.imageLimit = 100

        self.present(self.myGallery, animated: true, completion: nil)

    }

}


text:
Q: How to convert category data to Sankey plot in python? I have a data:
for eg:
    Roll no.  1          2         3          4
0   30        Good       Fair      Excellent  Good
1   31        Poor       Fair      Good       NaN
2   34        Excellent  Good      Poor       Fair
3   35        Good       Good      Fair       Good
4   36        NaN        Fair      Poor       Fair
5   37        Excellent  Good      Excellent  Excellent
6   39        Good       Good      Fair       Excellent
7   42        Good       Good      Fair       Fair
8   44        Fair       Good      Fair       Poor
9   45        Good       Good      Good       Good
10  46        Poor       Good      Fair       Fair
11  50        Excellent  Good      Good       Good

Student data with their performance across Test 1, Test 2, Test 3, Test 4 and I need to compare how they are performing over time.
So for that I need to prepare the Sankey chart to check how many are getting converted from one Category to another.
I am very much familiar with data visualization and I really clueless about this chart. I don't know how to source and destination, nodes, etc.
Please help.
I have tried for test 1 and test 2:
But I didn't work:
data_cross = pd.crosstab(data_pivot[1], data_pivot[2])
data_tidy = data_cross.rename_axis(None, axis=1).reset_index().copy()

formatted_data = pd.melt(data_tidy,
                         [1],
                         var_name='2',
                         value_name='Value')

formatted_data

import plotly.graph_objects as go

fig = go.Figure(data=[go.Sankey(
    node = dict(
      pad = 15,
      thickness = 20,
      line = dict(color = "black", width = 0.5),
      label = ['Poor','Fair','Good','Excellent'],
      color = ['blue', 'yellow', 'green', 'orange']
    ),
    link = dict(
        source = [0, 0], # indices correspond to labels...
        target = [1, 2],
        value = formatted_data['Value'],
        color = ['lightblue', 'lightyellow', 'lightgreen','lightorange']
  ))])

fig.update_layout(title_text="Basic Sankey Diagram", font_size=10)
fig.show()

I want something like this:
Instead of Wales, Scotland, England I want my categories i.e. poor, fair, good, excellent and also I have so many sources and destinations i.e Test 1, Test 2, 3 and 4.

A: A Sankey chart can be created using the D3Blocks library.
Install first:
pip install d3blocks

# Load d3blocks
from d3blocks import D3Blocks

# Initialize
d3 = D3Blocks()

# Load example data
# df = d3.import_example('energy')

# In your case you need to transform the data in the right shape which you can do with:
df = d3.adjmat2vec(df)

# Plot
d3.sankey(df, filepath='sankey.html')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python не работает while True: в связке с pool.map Добрый вечер, пытаюсь сделать чтобы программа в определенный промежуток времени проверяла ответы сервера и все это делаю в 3 потоках, проблема в том что программа сама завершается даже при включенном while True: подскажите что я делаю не так.
if __name__ == '__main__':

settings.current_error = ""

try:

    load_sites_list("scan.txt")                                 # | LOAD SITES FROM FILE

    while True:

        seeds.seeds = []                                        # | CLEAR OLD SEEDS
        get_seeds = seeds()                                     # | GET CURRENT SEEDS

        time.sleep(settings.time_seleep)                        # | SLEEP - settings.time_seleep

        if len(get_seeds.seeds) != settings.max_scanners:       # | CHECKING HOW MUCH SCANNERS WORK

            if len(settings.sites) != settings.site_count:

                start_scan("http://" + settings.sites[settings.site_count])
                settings.site_count += 1

            else:

                print "Done ..."
                break

        else:

            settings.pool.map(scan_vendor, get_seeds.seeds)

            settings.pool.close()
            settings.pool.join()

        if settings.current_error != "":
            print "[ERROR] " + settings.current_error

A:
если я сейчас удалю settings.pool.close(), settings.pool.join() то она будет работать но почему ?

Это ошибка пытаться вызывать pool.map() (новую работу добавить дочерним процессам), после вызова pool.close() (как документация и говорит).
Вот полный пример кода, который к AssertionError ведёт:
#!/usr/bin/env python2
import time
from multiprocessing import Pool

def get_result(arg):
    time.sleep(arg)  # do some work
    return arg

def main():
    L = [2] * 10

    pool = Pool()
    pool.map(get_result, L)
    pool.close()  # no more work
    pool.join()   # wait until child processes die

    #XXX it is an error to pass more work to the pool after pool.close()
    pool.map(get_result, L) # assertion fails

if __name__ == '__main__':
    main()

Убедитесь, что вы видите ошибку:
Traceback (most recent call last):
  File "/usr/lib/python2.7/runpy.py", line 174, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  ...
    pool.map(get_result, L) # assertion fails
  File "/usr/lib/python2.7/multiprocessing/pool.py", line 250, in map
    assert self._state == RUN
AssertionError


text:
Q: How do I provide databinding to an array using Aurelia and a mutiselect checkboxlist UI? So when the page loads, if the checkboxes were already selected previously, and the data is in the database, then the checkboxes should display as being checked in the form. Currently they are not checked (not bound to the database).
Here is the html

<select>
<option style="font-weight:normal">Cause(s) to support</option>
</select>

<iron-dropdown id="causes" horizontal-align="right" vertical-align="top" style="margin-top:25px;">

<input type="checkbox" value.bind="cause" checked.bind="selectedCause" change.delegate="causePicked()"> ${cause}

</iron-dropdown>

here is the JavaScript
  causes = ['Christian', 'Environmental', 'Hunger', 'Animal Rights', 'Homeless', 'Veterans', 'Elderly', 'other'];
  talents = ['music', 'athletics', 'childcare', 'mechanics', 'construction', 'computers', 'communication', 'chess playing', 'listening', 'other'];
  works = ['hashbrown slinging', 'nail hammering', 'leaf removal', 'floor mopping', 'counseling', 'other'];
  selectedCause = [];
  selectedTalent = [];
  selectedWork = [];

  async activate() {
    this.uid = this.app.auth.getTokenPayload().sub;
    this.user = await this.app.appState.getUser(this.uid);
    //this.app.appState.user;
    this.role = this.user.userType;
    this.causes.sort();
    this.talents.sort();
    this.works.sort();
    if (this.user.userType === 'Charity'){
      this.role = 'Charity Manager';
    }
  }

here is the link to repo and src code
https://github.com/WebJamApps/combined-front/blob/dev/src/dashboard-child-routes/user-account.html
https://github.com/WebJamApps/combined-front/blob/dev/src/dashboard-child-routes/user-account.js
Any suggestions are very appreciated, thanks

A: I was able to do it and the code examples are here for anyone else trying to figure this out
https://github.com/WebJamApps/combined-front/blob/dev/src/dashboard-child-routes/user-account.html
https://github.com/WebJamApps/combined-front/blob/dev/src/dashboard-child-routes/user-account.js


text:
Q: Django Urlconf Named Groups String Matching I'm trying to match two strings in an url, but it's not working out likely due to my poor knowledge of regex. I want urls like the following:

*

*testserver/username/

*testserver/username/1234/

*testserver/username/rewards/

Username would be passed in to the url as a kwarg. Here's what I have:
url(r'^(?P<username>[-\w]+)/$', Posts_Index, name="userposts"),
url(r'^(?P<username>[-\w]+)/photos/$', Photo_Index, name="userphotos"),
url(r'^(?P<username>[-\w]+)/rewards/$', Rewards_Index, name="userrewards"),
url(r'^(?P<username>[-\w]+)/following/$', Follower_Index, name="userfollowers"),
url(r'^(?P<username>[-\w]+)/followers/$', Following_Index, name="userfollowing"),
url(r'^(?P<username>[-\w]+)/(?P<pk>\d+)/$', SinglePost_Index, name="singlepost"),

However, only userposts will be found. If I try to query userphotos or anything below userposts, only the userposts url will be checked, which obviously leads to failure. How can I fix this issue?

A: From the django docs: Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
Thus if you reverse the order of the urls it should work better.


text:
Q: Selenium doesn't recognise xpath I am using Selenium WebDriver to get from a drop down list values. Unfortunately I can't get it, because my code can't recognise the xpath.
Here's my code:
  WebElement selector = driver.findElement(By.xpath("id('search')/x:fieldset/x:table[1]/x:tbody/x:tr[2]/x:td[1]/x:select"));
  Select s = new Select(selector);
  List<WebElement> options = s.getOptions();
  for (WebElement wb : options) {
     System.out.println(wb.getText());
  }

The problem is with the 1st line (WebElement selector). In output I get something like this:

Exception in thread "main"
  org.openqa.selenium.InvalidSelectorException: The xpath expression
  'id('search')/x:fieldset/x:table[1]/x:tbody/x:tr[2]/x:td[1]/x:select'
  cannot be evaluated

I've even tried to find by name or class, but selenium still doesn't find this list.
How to solve the problem? Thanks in advance :)

A: Ganjira, This is no way to write a xpath. If you find it tough to recognize item . Use Selenium IDE 'Select' button.

A: If you can provide sample of html page on which you try to find your element, it would be very helpful. Anyway, try to search using css selectors e.g.
WebElement selector = driver.findElement(By.css("#search > select"));


text:
Q: The sum of consecutive digits a) Find the natural numbers ${\overline{ab}}$ such that
${\overline{ab}}= a+(a+1)+...+b$.
b) Exist natural numbers ${\overline{abc}}$ such that
${\overline{abc}} = a+(a+1)+...+{\overline{bc}}?$;
Generalization.
In case a), using arithmetic progression sum, obtain the equation ${\overline{ab}}= \frac{(a+b)(-a+b+1)}{2}$ solutions having:
15, 27.

A: $2.10^na+2x=2\overline{ax}=x(x+1)-a(a-1)$ where $x$ could be $\overline{b},\overline{bc}...$
$ x^2-x-a^2-(2.10^n-1)a=0$ has solutions $\displaystyle x=\frac{1\pm\sqrt{1+4a^2+4(2.10^n-1)a}}{2}$. There are no integer solutions for $n=2,3,4,6,7$. For $n=5$, $a=19048, x=47620$ is the only solution.


text:
Q: On Lyapunov's method I been reading the standard proof of Lyapunov's method (https://en.wikipedia.org/wiki/Lyapunov_stability)
for example page $7$ here,
https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-241j-dynamic-systems-and-control-spring-2011/readings/MIT6_241JS11_chap13.pdf
I can't see why and where we really need that the function $V(x)\ \ge0$. Could someone explain this to me?

A: Some geometric ideas about Lyapunov's method.
Given a dynamical system
$$
\dot x = f(x,t)
$$
Suppose that $V(0) = 0$ and $V(x) > 0 $ for $x \ne 0$ then there exist a closed level curve/surface around $x=0$ indexed by a suitable $\epsilon > 0$ or $V(x) = \epsilon$
Now $\dot V(x) = \nabla V(x)\dot x = \nabla V(x)f(x,t) \le 0$
tell us that the directional derivative for $V(x)$ in the dynamic system's direction is negative. This show us that the dynamic system's path is entering the level curve/surface associated to $V(x) = \epsilon$
So it is essential that around $x=0$ assumed as the equilibrium point, the existence of a closed curve/surface. This is guaranteed by $V(x) = \epsilon > 0$
I hope this helps.


text:
Q: Plotting two dictionaries in one bar chart with Matplotlib I have these two dictionaries that I want to plot in the same bar chart using Matplotlib:
accuracy_pre = {"Random Forest": rf_accuracy_score, "Logistic Regression": log_accuracy_score, "KNN": knn_accuracy_score}

accuracy_post = {"Random Forest": gs_rf_accuracy_score, "Logistic Regression": gs_logmodel_accuracy_score, "KNN": knn_accuracy_score_iter}

The dictionary values are integer variables. Both dictionaries have the same keys, so there will be 6 bars in total, but those belonging to the same key will be right next to each other.
I'm able to create two separate bar charts, but I have trouble putting them together in one. Could someone help me?
This is the code for the bar chart I already have:
X = np.arange(len(accuracy_pre))
plt.bar(X, accuracy_pre.values(), align='center', width=0.5)
plt.xticks(X, accuracy_pre.keys())
plt.title("Accuracy score - before grid search", fontsize=17)
plt.ylim(0, 1)

A: I tweaked your code a bit to get the desired plot. Hope this helps!
import numpy as np
import matplotlib.pyplot as plt

#sample data
accuracy_pre = {"Random Forest": 1, "Logistic Regression": 2, "KNN": 3}
accuracy_post = {"Random Forest": 4, "Logistic Regression": 5, "KNN": 6}

X = np.arange(len(accuracy_pre))
ax = plt.subplot(111)
ax.bar(X, accuracy_pre.values(), width=0.2, color='b', align='center')
ax.bar(X-0.2, accuracy_post.values(), width=0.2, color='g', align='center')
ax.legend(('Pre Accuracy','Post Accuracy'))
plt.xticks(X, accuracy_pre.keys())
plt.title("Accuracy score", fontsize=17)
plt.show()


text:
Q: C# WPF Array of nested classes with image I am struggling to teach myself C#, and long googling has not turned up this answer:
I have a classes Rom, Game and Art. Rom.Game.Art is for images and is defined thus:
public class art
{
    public Image Screen { get; set; }
    public Image Marquis { get; set; }
    public Image Logo { get; set; }

    public art ()
    {
        BitmapImage Default_image = new BitmapImage();
        Default_image.BeginInit();
        Default_image.UriSource = new Uri(@"C:\Users\Major Major\Documents\Visual Studio 2013\Projects\Robin\Robin\images\bee_ace.png", UriKind.Absolute);
        Default_image.EndInit();

        this.Screen = new Image();
        this.Screen.Source = Default_image;
        this.Marquis = new Image();
        this.Marquis.Source = Default_image;
        this.Logo = new Image();
        this.Logo.Source = Default_image;
    }
}

I want to create an array of Roms, and populate the many nested properties and subclasses from a DataTable in a loop. Before I get into the loop, though, I just want to get a block of test code to work. The following works just fine:
        InitializeComponent();
        BitmapImage Image_0 = new BitmapImage();

        Image_0.BeginInit();
        Image_0.UriSource = new Uri(@"E:\Arcade\Art\Box\Intellivision\Congo Bongo.jpg", UriKind.Absolute);
        Image_0.EndInit();

        ROMS.Insert(0, new Rom());

        ROMS[0].Name = "Congo Bongo";
        ROMS[0].Game.Art.Screen.Source = Image_0;
        ROMS[0].Game.Date = "1983";
        ROMS[0].Game.Platform = "Intellivision";

        ROM_list.ItemsSource = ROMS;

My complaint is that, if I put this in a loop, all of the images in the array will be the same--they will be the last image entered. It seems the expression "ROMS[0].Game.Art.Screen.Source = Image_0;" ties ROMS[0].Game.Art.Screen.Source to the variable Image_0, rather than just transferring the value (this seems like surprising behavior to me, but no worries). So that in order to keep populating ROMS[j].Game.Art.Screen.Source, I have to create an array of BitmapImages separate from the ROM array as a reference. What I'd prefer is to instantiate(?) the BitmapImages within the array, like this:
        ROMS[0].Game.Art.Screen.Source = new BitmapImage();
        InitializeComponent();
        ROMS[0].Game.Art.Screen.Source.BeginInit();
        ROMS[0].Game.Art.Screen.Source.UriSource = new Uri(@"E:\Arcade\Art\Box\Intellivision\Congo Bongo.jpg", UriKind.Absolute);
        ROMS[0].Game.Art.Screen.Source.EndInit();

This doesn't work. Rom.Game.Art.Screen.Source is not a BitMapImage, and I cannot find the methods to assign an image to it.
So my questions, specifically:
1. Is there a way to assign an image source to ROMS[0].Game.Art.Screen.Source without creating a separate BitmapImage that lives on separately, or is that stupid?

*Is there a smarter way to do what I'm trying to do?

*Is there a reference to help me understand the relationships between the myriad image classes in C#?
Sorry for the wordy question, and thanks.

A: I think you should do some review about DataBinding. You will save more time.
You just need create something like the models:
ROM.Game.Art.Screen.Path ="meuPath.Jpg";
myItemSource = ROMS;

and in the end, do something like:
            <ItemsControl x:Name="myItemSource">
                    <TextBlock Text="{Binding ROM.Game.Art.Screen.Name}"/>
                    <Image Source="{Binding ROM.Game.Art.Screen.Path,Converter=MyConverterImageToPath"/>
            </ItemsControl>

A: You need to create a new instance of the BitMapImage for each of your array member. C# uses references if you assign  an object to a variable.
ROMS[0].Game.Art.Screen.Source = Image_0;

here you are creating a reference to Image_0, if you do now something like ...
ROMS[1].Game.Art.Screen.Source = Image_0;

both roms[0] and roms[1] .screen.source referencing Image_0. If you do now something like:
ROMS[0].Game.Art.Screen.Source.UriSource = new Uri(@"E:\Arcade\Art\Box\Intellivision\Congo Bongo.jpg", UriKind.Absolute);

you update Image_0 and all your rom.screen.source are referencing to Image_0 and are updated
If you want to use Image_0 as base "image" for all, what you could do is call the .Clone() function of the bitmapImage, which creates a deep copy of the object (a new object, instead of a reference).
So somewhere in the begin you have:
InitializeComponent();
BitmapImage Image_0 = new BitmapImage();

Image_0.BeginInit();
Image_0.UriSource = new Uri(@"E:\Arcade\Art\Box\Intellivision\Congo Bongo.jpg", UriKind.Absolute);
Image_0.EndInit();

in your loop you have then
ROMS[i].Name = "Congo Bongo";
ROMS[i].Game.Art.Screen.Source = Image_0.Clone();
ROMS[i].Game.Date = "1983";
ROMS[i].Game.Platform = "Intellivision";

A: Thanks a lot for looking at this.
The deep copy concept is instructive, and gets me on the right track. But there is still no method that lets me modify ROMS[i].Game.Art.Screen.Source (the class of this Is Image.Source). It's interesting that I can assign a BitmapImage directly to an Image.Source, but then I cannot alter the BitmapImage by going through the class nest. In other words
ROMS[1].Game.Art.Screen.Source.UriSource
does not exist, even though ROMS[1].Game.Art.Screen.Source was set equal to a BitmapImage, which has a .UriSource.
So, using you comments as a starting point, I came up with the following, which will work in a loop, obviously with loop variables in place of each string:
        InitializeComponent();

        ROMS.Insert(0, new Rom());
        ROMS.Insert(1, new Rom());

        ROMS[0].Name = "Congo Bongo";
        ROMS[0].Game.Art.Screen.Source = new BitmapImage(new Uri(@"E:\Arcade\Art\Box\Intellivision\Congo Bongo.jpg", UriKind.Absolute));
        ROMS[0].Game.Date = "1983";
        ROMS[0].Game.Platform = "Intellivision";

        ROMS[1].Name = "Donkey Kong";
        ROMS[1].Game.Art.Screen.Source = new BitmapImage(new Uri(@"E:\Arcade\Art\Box\Intellivision\Donkey Kong.jpg", UriKind.Absolute));
        ROMS[1].Game.Date = "1982";
        ROMS[1].Game.Platform = "Intellivision";

        ROM_list.ItemsSource = ROMS;

Still, I have to create a new BitMapImage and Uri every time I modify Game.Image.Source. I wonder what happens to the old BitMapImage and Uri, which don't even have names and can't be modified. Do they just float around in memory for eternity, haunting the living variables? Am I still doing something silly?


text:
Q: Python 3 serial search through text file only finds one result - why is my search loop not correctly finding subsequent items? I am trying to get my program to ask the user to enter product codes for some items and then for the program to look up the codes in a text file and present the items code/name/price on the screen.
My code will find the first code entered, but any subsequent codes entered are never found - the program only ever displays the first item that the user is searching for.
Why does my code fail to find and display more than one item?
I have a txt file with three lines:
12312356 product1 1.50
76576543 product2 6.20
98765423 product3 2.20

and a python program with the code:
        item_list = []
        item_quantity = []
        item_order = True
        while item_order == True:
            item_code = input("What is the code of the product you require? ")
            item_list.append(item_code)
            quantity = int(input("What quantity: "))
            item_quantity.append(quantity)
            repeat = input("Would you like to enter another item? (Y/N): ")
            if repeat == "N":
                item_order = False

        with open("stockfile.txt", "r") as f:
            for x in range(len(item_list)):
                product_found = False
                for a_line in f:
                    if item_list[x] in a_line:
                        print(a_line, end="")
                        product_found = True
                if product_found == False:
                    print("Product with code", item_list[x], "not found!")

A: You open a file, then for every request you read all the file, but after the first request is processed you are at end of file, so when you iterate again on the file to process the following user request the body of the for a_line in f: is never processed.
You may

*

*put the with open... inside the for x in... loop

*process the file autonomously, using e.g. a dictionary
d = {code:[name,price] for code, name, price in [l.split() for l in f]}

before the for x ... loop, and in the body just test for
if something in d:

A: I would write it the other way around.
 with open("stockfile.txt", "r") as f:
            for a_line in f:
                # to get the product name
                product = a_line.split(" ")[1]
                if product in item_list:
                    item_list.remove(product)

            if len(item_list)>0:
                for product in item_list:
                     print("Product with code", product, "not found!")


text:
Q: Is it safe to use Trigger to make it UNIQUE in MySQL? i have data cabang of table, that is structure :

i want to create data cabang.Main ID use custom UNIQUE using trigger, i have syntax:
CREATE DEFINER=`root`@`localhost` TRIGGER `Pembuat ID` BEFORE INSERT ON `data cabang` FOR EACH ROW SET NEW.`Main ID` =
    CONCAT(
        NEW.`Main ID`,
        '-',
        RIGHT(
            CONCAT(
                '000000',
                (SELECT count(NEW.`Main ID`)
                 FROM `data cabang` as `dc`
                 WHERE
                    dc.`Main ID` = NEW.`Main ID`
                )+ 1
            )
        ,7)
     )

The point is i using Trigger:

*

*create Trigger BEFORE INSERT

*I update NEW.Main ID using calculate variables Main ID and add 1 value (Like Auto increment)

is this safe if i using that for many insert in one time?


text:
Q: Need help in understanding objective c code I need some help in understanding the following code:

*

*What is the meaning of '@' in @"Reload"
button = MakeTestButton(&button_rect, @"Reload", content);
[button setTarget:web_view];
[button setAction:@selector(reload:)];

*Where I can find the definition of "@selector(reload:)"?

A: *

*String constants are declared as @"some text" in objective-c. This creates an instance of NSString.

*I recommend you read Apple's documentation on selectors. Basically, @selector(reload:) will get a pointer to the method that will be called when an objects receives a reload: message.

A: @selector is a built in primitive in the language.  Think of @selector(reload:) as "the name of the method reload:".  It returns a SEL, which you can then pass to a function and later use it to call the method reload:.  In the context of your code, when you click the button, the button will call [web_view reload:self].
In @"Reload", the @ means that it's an NSString instance instead of a char const *.

A: *

*The @ sign indicates to the compiler that the string is an NSString instead of a standard "C" string. This is a shortcut for creating NSString objects.

*See Explanation of Cocoa @selector usage


text:
Q: How to get Broadcast intent of changing date format I want to do some thing on changing date format of android Device.
But I do't find any broadcast action or any method for achieving it.

A: Create a content observer and listen to changes to Settings.System.DATE_FORMAT


text:
Q: Python list to pandas dataframe I have a list that follows this format:
a=['date name','10150425010245 name1','10150425020245 name2']

I am trying to convert this to Pandas df:
newlist=[]
for item in a:
    newlist.append(item.split(' '))

Now, convert this to df:
pd.DataFrame(newlist)

which results in
                  0     1
0              date  name
1    10150425010245 name1
2    10150425020245 name2

I want to have 'date' and 'name' as header, but I can't manage to do that. Is there a more efficient way to automatically convert a list of strings into a dataframe than this?

A: Here's one approach.
Use list comprehensions instead of loops.
In [160]: data = [x.split('') for x in a]

In [161]: data
Out[161]: [['date', 'name'], ['10150425010245', 'name1'], ['10150425020245', 'name2']]

Then use data[1:] as values and data[0] as column names.
In [162]: pd.DataFrame(data[1:], columns=data[0])
Out[162]:
             date   name
0  10150425010245  name1
1  10150425020245  name2

A: you were on the right track. With slight modification, your code works fine.
    import pandas as pd
    a=['date name','10150425010245 name1','10150425020245 name2']
    newlist=[]
    for item in a:
        newlist.append(item.split(' '))

    newlist2=pd.DataFrame(newlist,columns=["date","name"])[1:]

    newlist2

    date            name
    10150425010245  name1
    10150425020245  name2

A: Tempted to summarise the answers already given in one line:
a=['date name','10150425010245 name1','10150425020245 name2']
pd.DataFrame(
     map(str.split, a)[1:],
     columns=a[0].split(),
)

Output:
Out[8]:
              date  name
0   10150425010245  name1
1   10150425020245  name2


text:
Q: Accessing a website through its IP address instead of hostname I would like to know the chances of not being able to access a website only through the domain name and denied of access through its direct IP address.
I wish draw attention to the following example, however the question is relevant to  any other scenario: www.kickass.to website has the following addresses,

*

*67.212.88.146

*67.212.88.10

*205.204.64.122

*68.71.58.34
When I used the above, I received a message called "forbidden" but I can easily place the full URL and access the site.
Any domain address eventually converts to be an IP address by the browser as per my understanding. I am a little clueless here.

A: Often, web servers are configured to use name-based virtual hosting, where the content that is served depends on the domain name that was requested in the Host header.
Name-based virtual hosting is necessary for almost all shared hosting, as well as for most web applications that use more than one domain name in their operation.  As it is so frequently used, it is not unusual for it to be enabled even on a web server that only serves requests for a single domain name, whether for fancy domain name redirects, like this, or just due to organizational standards and/or an oversight by the admins.
More info:
This approach was developed to allow for web sites for different domain names to be hosted on the same web server.  When you visit a site in a web browser, it sends a Host header with the domain name from the URL that it is attempting to load, and the server will send the content for the appropriate site.
e.g. browser sends:
GET / HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537.36
Host: www.kickass.to
Accept: */*

server replies:
HTTP/1.1 301 Moved Permanently
Server: nginx/1.7.8
Date: Tue, 10 Feb 2015 05:50:25 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://kickass.to/

<html>

[... snip ...]
(In this case the server has actually just sent me a redirect to http://kickass.to/ instead of a page at http://www.kickass.to/)
When you access the server using a URL with just the IP address of the server, the IP address will be sent in the Host header instead of a domain name.
GET / HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.91 Safari/537.36
Host: 67.212.88.10
Accept: */*

If the server is configured for name-based virtual hosting, depending on the details of the configuration, it may serve you a particular site that is set as the default site to host at the IP address, or it may give you an error response.
HTTP/1.1 403 Forbidden
Server: nginx/1.7.8

[... snip ...]

A: Short Answer? Name-based virtual hosting allows IP address accesses to web servers to be treated differently from hostname accesses to the same web servers. And many web systems administrators "dead end" IP address accesses for basic security reasons. Additionally, "Forbidden" messages are not typically sent by IP address access being blocked; my gut tells me some web server firewall is detecting IP address access and stopping it dead in it's tracks.
Longer Answer? While name-based virtual host setups like the one used in Apache allows multiple hostnames to use the same IP address, that—in and of—itself does not mean you will get a "Forbidden" if you are attempting to access a server via the raw IP address. That said, doing a curl -I to www.kickass.to shows that Nginx is being used:
HTTP/1.1 301 Moved Permanently
Server: nginx/1.7.8
Date: Tue, 10 Feb 2015 05:46:59 GMT
Content-Type: text/html
Content-Length: 184
Connection: keep-alive
Location: http://kickass.to/

While I refer to my experience with Apache—which is the most commonly used web server on the Internet—Nginx is gaining traction and allows for similar behaviors to Apache as I describe. Including being able to use ModSecurity. Read on for details; the same basic concepts apply to Apache and Nginx.
When I setup Apache servers with name-based virtual hosts, I do make a very conscious effort to create a "virtual moat" by having the default Apache config—often set as 000-default in the sites-enabled directory—to throw all non-hostname/IP-specific access to a literal blank HTML page. The logic being that many malicious pieces of software out there will attempt to "hack" a site by gaining access via the IP address. Why? Easy. Many Apache setups have a default "It works!" page setup at that address. Competent systems administrators will get rid of that page since robots/spiders out to hack a site will specifically look for that kind of "It works!" page as a basic clue that, "Hey! This administrator just tossed a server into production without really cleaning this basic stuff up. Let's see what exploits can try on this server." Believe it or not, but dead-ending the default Apache config is the simplest way to discourage unwanted accesses and DDoS attempts.
But like I said, a "Forbidden" doesn't smell like an intentional "dead end" to me. Who knows, maybe the systems administrator did "dead end" the default Apache config into a completely dead or non-existent directory. But whenever I see "Forbidden" in a case like this, it makes me believe that the administrator has ModSecurity installed.
ModSecurity is an Apache web service level module that acts as a firewall between a web server and unwanted traffic. It uses "rule sets" to scan traffic in real-time—as the actual HTTP request is made—and if a pattern of access/behavior checks as "bad" it will throw up a "Forbidden" for that access. And in the case of raw IP addresses, one of the core rules in the ModSecurity core rule set (CRS) is to "Forbidden" any/accesses to RAW IP addresses.
So in my humble opinion, you are seeing a web server using ModSecurity—or a similar firewall tool—react to a raw IP request by just blocking the request entirely as "Forbidden."
Additionally, you are stating that www.kickass.to has multiple IP addresses. That tells me some kind of load balancing is happening when requests are made to www.kickass.to. Anyone setting up a load balanced cluster will definitely make sure their child nodes are fairly bullet proof and inaccessible to unwanted requests. So exactly what I describe above, but even more so.


text:
Q: How can I get the Id of a recently entered collection Using Firestore and React I tell you I am putting together an electronic commerce system, which asks me to obtain the ID that I just entered in the system, but I am using this
import React, { useContext, useState } from "react";
import { db } from "../firebase/firebase";
import{ addDoc, doc, collection, serverTimestamp, getDoc, updateDoc, query, where } from "firebase/firestore"
import { contextoProducto } from "./ProductContext";
import swal from 'sweetalert';
import Order from "./Order";

const CartFinish = () => {

  let flag = 0;
  const{ cartProduct, totalPrecio, clearCart } = useContext(contextoProducto);

  const [form, setForm] = useState({});
  const [sendProducts, setSendProducts] = useState(false);

  const finalizarCompra = () => {
    const ventasCollection = collection(db, 'ventas');
    addDoc(ventasCollection, {
      form,
      items: cartProduct,
      date: serverTimestamp(),
      total: totalPrecio,
      IVA: totalPrecio * 0.19, //IVa en Chile es del 19%
      totalFinal: totalPrecio * 1.19,
    })
    let order = {
      form,
      items: cartProduct,
      date: serverTimestamp(),
      total: totalPrecio,
      IVA: totalPrecio * 0.19, //IVa en Chile es del 19%
      totalFinal: totalPrecio * 1.19,
    };
    actualizarStockDb(cartProduct);
    clearCart();
    obtenerIdVenta(order)
  }

  const obtenerIdVenta = (order) => {
    const ventasCollection = collection(db, 'ventas');
    const q = query(ventasCollection, where('totalFinal', '==', order.totalFinal), where('IVA', '==', order.IVA), where('Total', '==', order.Total),where("form.name", "==", order.form.name), where("form.lastName", "==", order.form.lastName), where("form.email", "==", order.form.email), where("form.address", "==", order.form.address), where("form.phone", "==", order.form.phone));
    getDoc(q)
      .then(result => {
        const lista  = result.docs.map(element => {
          return {
            id: element.id,
            ...element.data(),
          }
        })
        setSendProducts(lista);
      }).catch(error => console.err)
  }

  const actualizarStockDb = (cartProduct) => {
    cartProduct.forEach((element) => {
      actualizarStock(element.id, element.quantity);
    });
  }

  const actualizarStock = (id, quantity) => {
    let product;
    const productCollection = collection(db, 'Products');
    const referenceDoc = doc(productCollection, id);

    getDoc(referenceDoc)
    .then(result => {
        product = {
          id: result.id,
          stock: result.data().stock - quantity,
       }
        updateDoc(referenceDoc, product)
        product.stock < 0 ? swal("No hay stock suficiente", "Gracias", "Error") : swal("Compra realizada", "Gracias", "success");
    })
  }

  const handleChange = (e) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value
    });
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    finalizarCompra();
    flag = 1
  }

  return (
    <>

Formulario de Envio

      <form onSubmit={handleSubmit}>
        Name
        <input type="text" value={form.name} name= "nombre" onChange={handleChange} />
        Email
        <input type="text" value={form.email} name="email" onChange={handleChange} />
        Phone
        <input type="text" value={form.phone} name="phone" onChange={handleChange} />
        City
        <input type="text" value={form.city} name="city" onChange={handleChange} />
        Address
        <input type="text" value={form.address} name="address" onChange={handleChange} />
        Codigo de area
        <input type="text" value={form.zip} name="zip" onChange={handleChange} />
        Provincia
        <input type="text" value={form.state} name="state" onChange={handleChange} />
        Pais
        <input type="text" value={form.country} name="country" onChange={handleChange} />
        <button type="submit">Enviar</button>
      </form>

    {flag === 1 ? <Order send={sendProducts} />: null}
    </>
  );
}

export default CartFinish;

I have tried several ways such as using more than one where, occupying a doc (ventaCollection, from.id) and it does not work, can you help me, thanks
The query is how to obtain an ID of a collection that has just been entered??, Thanks


text:
Q: GitLab fatal: unable to access : The requested URL returned error: 503 While trying to fetch/push/pull the git repository, it throws 503 error.
Using TortoiseGit
git.exe fetch -v --progress "origin"
fatal: unable to access 'http://gitlab.foo.com/group/repository.git/': The requested URL returned error: 503
Using GitBash
fatal: unable to access 'http://gitlab.foo.com/group/repository.git/': The requested URL returned error: 503

A: Having the thought, HTTP 503 is "service unavailable", and under error category 5XX it could be server issue. But the service was accesible on browser (80). We eventually looked multiple possible (routing, firewall, dns) option on gitlab server, but no luck.
Noticeably I was behind the corporate proxy server. The solution was lying locally with machine, having proxy SYSTEM VARIABLE / ENVIRONMENT VARIABLE, which was overridding the gitconfig settings.
I removed proxy system variables, and it started working. Possible system variables to look for and delete it.
http_proxy
https_proxy
HTTP_PROXY
HTTPS_PROXY
You may also set no_proxy to gitlab URL.

A: It is also possible that you have an existing git config file with proxy settings in it.
Try to delete this file or move it to another location to make sure that is the problem.


text:
Q: Nginx subfolder as location My nginx.conf contains this:
server {
    listen          80;
    server_name     myserver.com X.X.X.X;
    root /var/www/html;

    location / {
        proxy_pass http://127.0.0.1:8082;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_buffering     off;
        proxy_connect_timeout 43200000;
        proxy_send_timeout    43200000;
        proxy_read_timeout    43200000;
        proxy_redirect off;
        proxy_set_header Proxy "";
    }

    location /api/socket {
        proxy_pass http://localhost:8082/api/socket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
    location /newapp {
        #Should this be empty?
    }

}

As you can see, both / and /api/socket point to a proxy. Both of them work.
Originally this line didn't exist:
root /var/www/html;

I added it. I also added the "location /newapp". What I want is to go to the index file under the folder /var/www/html when I type
myserver.com/newapp
However, I get a 404. Am I missing something in the config file?

A: If you would like the URI /newapp (or /newapp/index.html) to find the file /var/www/html/index.html, you will need to use the alias directive and not the root directive.
For example:
location /newapp {
    alias /var/www/html;
}

See this document for more.

A: Creating the folder /newapp inside /var/www/html solves the issue. But I am not sure if this is the way to go. However, it worked then.


text:
Q: Memoizing a recursive call So I have recursive function that needs to be memoized since it takes so long to run. I understand that you store it in a cache, but need help doing that. Also one thing I noticed was that when I printed the value after the function call, I would get the correct value, but when i removed it, the answer would be wrong. Any help is appreciated. The function is supposed to calculate the probability of getting a number after a rolling a s sided die that isn't within 1 of the previous roll after rolling t times
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <vector>
using namespace std;

double dond(int s, int t, int l);

int main(int argc, char *argv[]) {
    int s, t, l;

    s = atoi(argv[1]);
    t = atoi(argv[2]);
    l = atoi(argv[3]);
    //printf("%d %d %d\n", s, t, l);

    cout << dond(s, t, l) << endl;
}

double dond(int s, int t, int l) {
    int i, j;
    double a, d = 0, yuh = 1.0/s;
    vector <double> cache;

    if(t == 1 && l == -1) return 1;
    if(t == 1) {
        if(l == 0 || l == s-1) return (s-2)/(double)s;
        else return (s-3)/(double)s;
    }
   for(i = 0; i < s; i++) {
       if(l == -1 || (i != l && i != l-1 && i != l+1)) {
           cache.push_back(dond(s, t-1, i)); //store into cache
          // printf("A: %f\n", a);
          //printf("",a );
       }
    }
    for(i = 0; i < cache.size(); i++) a += cache[i];
    return yuh * a;
}


text:
Q: What should be in the columns of the roles table for acl9 Probably a stupid question but I am pretty close to getting acl9 implemented. Just a little unsure what the data should look like in the roles table:
id | name  | authorizable_type | authorizable_id | created_at | updated_at
---+-------+-------------------+-----------------+------------+------------

I assume name would be "admin" and such.
I'm not certain what authorizable_type and authorizable_id are referring to.

A: The main purpose of the authorizable_type and the authorizable_id map the `authorizable_object'. Hope this helps usually if you are creating a roles table in your application your migration should look like the following:
class CreateRoles < ActiveRecord::Migration
  def self.up
    create_table :roles, :force => true do |t|
      t.string   :name
      t.string   :authorizable_type
      t.integer  :authorizable_id
      t.timestamps
    end
    add_index :roles, :name
    add_index :roles, [:authorizable_id, authorizable_type]
    add_index :roles, [:name, :authorizable_id, :authorizable_type], :unique => true
  end

  def self.down
    remove_index :roles, [:name, :authorizable_id, :authorizable_type]
    remove_index :roles, [:authorizable_id, :authorizable_type]
    remove_index :roles, :name
    drop_table :roles
  end
end

A: First of all, version 1.2 of acl9 ships with a generator for the migration needed for the roles table (as well as a few other goodies), see bin/rails g acl9:setup -h for more details.
Secondly, to explain these fields, Rails has a feature called polymorphic associations (read more about it here), which allow you to associate one model with any other model.  acl9 uses this feature to enable to you apply a role on any other model you wish, in acl9 terminology we call those other models "objects" (read more about that here). All you need to do is include the acts_as_authorization_object call in your model and that allows you to do something like this:
user.has_role! :admin, school

And that user has the :admin role for that school (and only for that particular school). As per the polymorphic association feature the authorizable_id will contain the primary key of that school from your DB, and authorizable_type will contain the class name "School".


text:
Q: Find the smallest square matrix in which some objects fit following some rules I have to put some objects in a matrix. The data of these objects is given in another matrix in which each line contains an object, and the first column represents its width, and the second its height.
I want to know which is the smallest matrix that can contain all these objects, with the following rule: objects can't be adjacent to each other, except for diagonals. See the following example:
|1 3|
|1 2|

In this case, we need to populate the main matrix with two objects: one that is 1x3 units in the main matrix, and another that is 1x2.
One possible example to fill it would be (not the smallest possible):
|x x x o|
|o o o x|
|o o o x|
|o o o o|

This following example is incorrect:
|x x x o|
|o x o o|
|o x o o|
|o o o o|

Because two objects collide. In this example, the answer would be the size of the smallest possible matrix in which all objects can fit; that is:
|x o o|
|x o x|
|x o x|

The answer would be 3. So I want a function that receives the first matrix ([[1,3], [1,2]]) and returns 3.
I've tried for some time to do this, but it seems impossible to me. I don't know much of matrixes beyond determinants, and I see no way in which what I know relates to this. I think the main problem is that the ship may create an exclusive area, but only if it is not in the corners (and two or more ships may share the same area). I made a program that would try all possibilities and choose the smallest one, but it takes forever to do it for the amount of data I have. So, I was wondering, is there another way, purely mathematical (without testing everything)?

A: The short answer is that you cannot (theoretically) do much better than brute force searching.
While I do not have a proof, I would be extremely surprised if this problem is not NP-complete. Your problem is closely related to rectangle packing, a well studied problem.
Your best option would be to use a combinatorial search system, based on either SAT or Constraint Programming.These systems still do possibly exponential search, but have many tricks and heuristics to improve performance in practice.
I work on the minion constraint solver minion. How big are your biggest problems? I could give some guidance on how achievable they are.


text:
Q: Assigning an array as a react component state property? When trying to set a non empty array as a component state property (at initialisation, in the component constructor), like for example:
this.state = { results: ['apple','orange'] } //in the component constructor

this error is returned in the console:

In this environment the sources for assign MUST be an object.This
  error is a performance optimization and not spec compliant

If the array is empty though, that works (but as soon as you try to reasign a non empty array, it would bug)
So this works:
this.state = { results: [] }  //in the component constructor

until you do
this.setState({results: ['apple','orange'] }) //in a component function

at which point the previous error would be returned...
I don't understand. Aren't javascript arrays supposed to be of the type object too and thus usable as a state property value?
I tested it with the latest react-native version (0.45.1), on an android device.
The state.results object is only used in a listview like this:
   const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })

  render () {
    return (

    <ListView
              style={{position: 'absolute', width: 100, backgroundColor: 'white', zIndex: 3}}
              keyboardShouldPersistTaps='always'
              initialListSize={15}
              enableEmptySections={true}
              dataSource={ds.cloneWithRows(this.state.results)}
              renderRow={(rowData, sectionId, rowId, highlightRow) =>
                <RowWrapper styles={styles.rowWrapper} >
                  <TouchableOpacity
                    activeOpacity={0.5}
                    onPress={() => {this.onItemPress(this.state.results[rowId])}}
                  >
                    <Text style={styles.rowText}>{rowData}</Text>
                  </TouchableOpacity>
                </RowWrapper>
              }
            />
   )
  }

    class RowWrapper extends Component {
      constructor (props) {
        super(props)
        this.defaultTransitionDuration = 500
        this.state = {
          opacity: new Animated.Value(0)
        }
      }
      componentDidMount () {
        Animated.timing(this.state.opacity, {
          toValue: 1,
          duration: this.defaultTransitionDuration
        }).start()
      }
      render () {
        return (
          <TouchableWithoutFeedback>
            <Animated.View style={{...this.props.styles, opacity: this.state.opacity }}>
              {this.props.children}
            </Animated.View>
          </TouchableWithoutFeedback>
        )
      }
    }

A: You shouldn't mutate the state.
instead of doing
this.setState({results: ['apple','orange'] })

You should be doing
var resultsArr = this.state.results.slice();
var newResults = ['apple','orange'];
resultsArr.concat(newResults); or resultsArr.push(newResults);
this.setState({results: resultsArr })


text:
Q: Python Distribution and Packaging, Entrypoint setup I'm trying to play around with python packaging and distribution. I have a script that I want to execute globally so I added an entrypoint in setup.py, but I can't get it to work.
Anatomy
mypackage/
.
├── venv/
├── mypackage.py
└── setup.py

setup.py
from distutils.core import setup

setup(
      entry_points={
        'console_scripts': [
            'mypackage=mypackage:run'
        ]
        }
     )

mypackage.py
#!/usr/bin/env python

import sys, os

def run():
   os.system("pwd")

I installed with pip
$ pip install .

I then tried to run the module
$ mypackage

I get this error
ImportError: No module named mypackage

What am I doing wrong?

A: You should refactor your package in such a way
mypackage
├── mypackage
│   ├── __init__.py
│   └── main.py
└── setup.py

Unfortunately, you need to have full-package structure even for a single script to make it work due to the underlying script-generation code of setuptools. So mypackage.py becomes main.py in my example and then
setup(
    entry_points={
        'console_scripts': [
            'mypackage=mypackage.main:run'
        ]
    }
)

will do the thing.


text:
Q: How to disable driver certificate verification in Windows 10 I just built a new machine and need to load an older driver for one of my 44" Designjet printers, but Win 10 will not allow either the driver for Win 7 64-bit or for Win 8 64-bit because they lack a proper digitally signed certificate. Never had this issue in Win 7.
I tried using the shift/restart technique to access the Troubleshoot/Advanced Options/Startup Settings page where option #7 is to disable the certificate verification, but it doesn't seem to work. After selecting option 7 with the F7 key there is no verification of my selection, the computer just starts its reboot. This seems a little odd. Anyway even after trying this several times I still get the verification errors when trying to load one of the drivers.
Is there any known way around this? I see a bunch of certificate functionality on the god mode screen, but I have no idea how to use any of that.
Thanks for any help.
Jim

A: I found these instructions in a Microsoft forum:

*

*Click start, and type gpedit.msc

*ENABLE the option for code signed drivers at:

*User Config/Admin Templ./System/Driver installation

*then set the drop box to "Ignore"

A: Seems like the problem was that I hadn't disabled the Win 10 Auto Driver Install. The OS didn't like me trying to install the archaic Win 7 64-bit driver over the auto installed brand new generic Win 10 driver.
Once I did that and removed the printer from the installed printer list, rebooted and then added the printer again, the "Have Disk" option worked just fine and now I have a fully functional HP driver installed.
Thanks for the help I received.

A: Go to Start -> Run -> GPEdit.msc
Now go to User Configuration -> Administrative Templates -> System -> Driver Installation -> Code signing for drivers
Click on "Disabled", then on "OK".


text:
Q: Excel VBA .Find() misbehaving Cannot locate string I have a series of values on a sheet
E11: "Notional"
E12: "Strike"
E13: "Coupon"
Etc.
In my code, use the sheet name
Function AddInput(name As String, strInput As String, Optional suffix = "") As String
Dim inputVal As Variant
On Error GoTo ERROR_FUNCTION
    With Worksheets(name)
        If .Cells.Find(what:=strInput, LookAt:=xlWhole,searchorder:=xlByRows).Offset(0, 1).Value <> "" Then
            inputVal = Trim(Cells.Find(what:=strInput, LookAt:=xlWhole,     searchorder:=xlByRows).Offset(0, 1).Value)
            If TypeName(inputVal) = "Date" Then inputVal = Format(inputVal, "YYYYMMDD")
        AddInput = Replace(strInput, " ", "") & "=" & inputVal & "&"
            If suffix <> "" Then AddInput = AddInput & suffix
        Else
            AddInput = ""
        End If
    End With

Exit Function
ERROR_FUNCTION:
    Debug.Print strInput & ": input not found"
    MsgBox strInput & ": input not found"
End Function

I am able to find whats in Cell E12, but not E11.
I have done the following:
1) I copied the cell value into the search function directly (No chance to fat-finger it).
2) I copied the values from E11 down 1 (if for some reason it couldn't find that range etc... it just returned E12).
I still cannot find that one cell, it works for every other value I put through it.
Has anyone encountered this, and how did you resolve it?
Thanks!

A: Make sure you start each search correctly:
Sub dural()
    Dim r As Range
    strSheetname = ActiveSheet.Name
    MyInputString = Application.InputBox(Prompt:="Enter value", Type:=2)
    With Sheets(strSheetname)
        Set r = .Cells.Find(what:=MyInputString, After:=Range("A1"))
    End With
    MsgBox r.Address(0, 0)
End Sub


text:
Q: Why does argv have a 'v' I am studying Python as a novice programmer.  I have seen argv, as in sys.argv used and I believe it is used in other languages as well.  What is the significance of the 'v' in 'argv'? What does it stand for and where does the term originate?
I am hoping this will help me understand and remember the use of "argv".

A: The variables are named argc (argument count) and argv (argument vector) by convention, from C.
note that in Python there's no sys.argc. You just use len(sys.argv) as pointed fred-larson


text:
Q: recv() char array size I'm working on implementing a C++ client server chat program to learn more / practice socket programming. I'm using winsockV2.
Briefly,
the client program connects to a server, who stores the client socket in a vector
client program sends messages for the server to distribute to other clients in the vector.
The problem I think I'm running into is that the clients and server are receiving the message and storing it in a char message[256] and if the message is shorter than 256, strange chars are displayed when I std::cout << message; which I'm being told is uninitialized memory. Here's an example of the output:
k:message from client to other client╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠(■o

Is there some way of creating a character array of the size of the received message? i.e
char recvMessage[4096];
int s = recv(socket, recvMessage, sizeof(recvMessage),0);
char recvOutput[strlen(recvMessage)] = recvMessage;
std::cout << recvOutput << std::endl;

Otherwise what is your solution for recv'ing messages which you do not know the length of?
If I'm being a complete idiot, please be kind, I came from PHP. classes are below:
SVR.CPP
See receiveMessages() and distributeMessages() functions
#include "stdafx.h"
#include "svr.h"

svr::svr()
{
    //WSA Business I don't understand
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

    /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0)
    {
        /* Tell the user that we could not find a usable */
        /* Winsock DLL.                                  */
        printf("WSAStartup failed with error: %d\n", err);
    }
    //End of WSA Business

    //get addressSize
    addressSize = sizeof(address);
    //set address data members
    address.sin_family = AF_INET;
    address.sin_port = htons(444);
    address.sin_addr.s_addr = INADDR_ANY;

    //init sListen
    sListen = socket(AF_INET, SOCK_STREAM, 0);
    bind(sListen, (sockaddr*)&address, addressSize);
}

svr::~svr()
{
}

void svr::start()
{
    std::thread newConnThread(&svr::newConnection, this);
    newConnThread.join();
}

void svr::receiveMessages(int clientIndex)
{
    std::cout << "\tsvr::recv thread started for client index:" << clientIndex << std::endl;

    //create char arr
    char recvMessage[256];

    //forever
    while (true)
    {
        //receive message and input it to recvMessage char arr.
        recv(clients[clientIndex], recvMessage, sizeof(recvMessage), 0);

        //if message is not null, send out to other clients
        if (recvMessage != NULL)
        {
            std::cout << "\t\tINFO:Received message of length: " << std::strlen(recvMessage) << " size: " << sizeof(recvMessage) << " : " << recvMessage << std::endl;
            distributeMessages(recvMessage, clientIndex);
        }
    }
}

//distributes messages to all clients in vector. called by receiveMessages function, normally in rMessages thread.
void svr::distributeMessages(std::string message, int clientIndex)
{
    for (unsigned int i = 0; i < clients.size(); i++)
    {
        if (clientIndex != i)
        {
            send(clients[i], message.c_str(), message.length(), 0);
        }
        else
        {
            //would have sent to self, not useful.
        }
    }
}

//accepts new connections and adds sockets to vector.
void svr::newConnection()
{
    //mark for accept, unsure of somaxconn value;
    listen(sListen, SOMAXCONN);

    std::cout << "\tSERVER: awaiting new connections..." << std::endl;
    while (true)
    {
        //accept connection and push on to vector.
        clients.push_back(accept(sListen, (sockaddr*)&address, &addressSize));

        //responds to new clients.
        const char *message = "Hi, you've successfully connected!";

        int clientIndex = clients.size() - 1;
        int sent = send(clients[clientIndex], message, 33, 0);

        //start new receiveMessage thread
        std::thread newClient(&svr::receiveMessages, this, clientIndex);

        //detach here, let newConn thread operate without depending on receiveMessages
        newClient.detach();
    }
    std::cout << "\tSERVER: no longer listening for new connections" << std::endl;
 }

CLI.CPP
See cSend() and cRecv() functions
#include "stdafx.h"
#include "cli.h"

cli::cli(char *ip)
{
    //WSA
    {
        WORD wVersionRequested;
        WSADATA wsaData;
        int err;

        // Use the MAKEWORD(lowbyte,highbyte) macro declared in windef.h
        wVersionRequested = MAKEWORD(2, 2);

        err = WSAStartup(wVersionRequested, &wsaData);

        if (err != 0)
        {
            std::cout << "WSAStartup failed with the error: " << err;
        }
    }

    //get addressSize
    addressSize = sizeof(address);

    //set address struct data members
    address.sin_family = AF_INET;
    address.sin_port = htons(444);

    //if ip empty, prompt user;
    if (ip == NULL)
    {
        std::string ipInput;
        std::cout << "\n\tConnect to which IP: ";
        std::cin >> ipInput;
        address.sin_addr.s_addr = inet_addr(ipInput.c_str());
    }
    else
    {
        address.sin_addr.s_addr = inet_addr(ip);
    }

    sock = socket(AF_INET, SOCK_STREAM, 0);

    std::cout << "\n\tYour username: ";
    std::cin >> uname;
}

cli::~cli()
{
}

void cli::start()
{
    try
    {
        //hold string
        char message[33];

        std::cout << "\n\tcli::start() called";
        int conRet;

        //connects to server socket & receives a message, stores in it message variable
        conRet = connect(sock, (sockaddr*)&address, (int)addressSize);
        recv(sock, message, sizeof(message), 0);

        std::cout << "\n\tSERVER: " << message;

        //starts threads, pass this for object scope.
        std::thread sendThread(&cli::cSend, this);
        std::thread recvThread(&cli::cRecv, this);

        //this function (start) will return/end when send and recv threads end.
        sendThread.join();
        recvThread.join();
    }
    catch (std::exception e)
    {
        std::cerr << e.what() << std::endl;
    }
}

void cli::cSend()
{
    std::cout << "\n\tcli::send thread started";
    //char arr for sending str;
    std::string getLine;
    while (true)
    {
        std::cout << "\n\t" << uname << ":" << std::flush;
        //set to "" because i suspected the value remains in the string after a loop.
        std::string message = "";

        //get input, put it in message
        std::getline(std::cin, message);

        //get full message
        std::string fullMessage = uname + ":" + message;

        //get constant int, size of fullMessage
        const int charArrSize = fullMessage.length();

        std::cout << "\t\tINFO: Sending character array of length: " << charArrSize << " size: " << sizeof(fullMessage.c_str()) << " : " << fullMessage.c_str() << std::endl;

        //sends it
        send(sock, fullMessage.c_str(), charArrSize, 0);
    }
}

void cli::cRecv()
{
    std::cout << "\n\tcli::recv  thread started";

    //initialize arr to 0, will hopefully help avoid the weird chars in the cout
    char recvMessage[256]{ '\0' };

    while (true)
    {
        recv(sock, recvMessage, sizeof(recvMessage), 0);

        std::cout << "\t\tINFO:Received message of length: " << std::strlen(recvMessage) << " size: " << sizeof(recvMessage) << " : " << recvMessage << std::endl;

        std::cout << recvMessage << std::endl;
    }
}

A:
what is your solution for recv'ing messages which you do not know the
  length of?

recv() tells you the length of the message it received. You don't have to wonder what it is. That's recv()'s return value.
 int s = recv(socket, recvMessage, sizeof(recvMessage),0);

See -- there you go. It's right here in front of you. It's s. Of course if there was an error s would be negative and you need to check for that. But, ignoring that little detail, your worries are over: s is the length of your message you just received.
 char recvOutput[strlen(recvMessage)] = recvMessage;

That's not going to work. What is strlen() doing here? strlen() computes the size of the string, expecting the string to be an old-fashioned, C-style character string that's terminated by a \0 byte. recv() does not terminate anything it receives with a \0 byte. Instead, it returns the actual character count.
And, besides, this won't work anyway. You can't initialize an array this way.
Your obvious intent here, apparently, is to expect to receive a text string as message. Well, since your language of choice is C++, and you tagged your question as such, the logical conclusion is that you should be using what C++ gives you to deal with text strings: the std::string class:
std::string recvOutput{recvMessage, recvMessage+s};

There you go. Mission accomplished. Since you already known the length of the received message in s, as we've determined before (and after double-checking that s is not negative), you can simply use std::string's existing constructor that initializes the new string given an iterator, or a pointer, to the start and the end of string.
When dealing with low-level operating system interfaces, like sockets, you have no choice but to use primitive data types, like plain char arrays and buffers, because that's the only thing that the operating system understands. But, with the rich set of templates and classes offered by the C++ library, your code should switch to using C++ classes and templates at the first opportunity, in order to be able to use all those resources. As such, as soon as you've determined how big is the text string recv() just came up with, just stuff it into a std::string before figuring out what to do with it.


text:
Q: React js reform DateTime values in array back to momentjs objects I'm working on a week calendar and to store appointments in DB I store them as scalar DateTime. The calendar that I'm working with only works with moment objects. I found that I can parse the DateTime as moment objects like this --> moment('2020-06-12T09:00:00.014Z'). I'm just wondering how I could efficiently reformat the appointmentToRender array so that start and end are no longer just DateTime's but moment object before passing the appointmentToRender array to <WeekCalendar />
appointmentToRender array structure:
appointmentToRender
(2) [{…}, {…}]
0: {start: "2020-06-12T08:00:00.316Z", end: "2020-06-12T09:22:00.316Z", __typename: "Appointment"}
1: {start: "2020-06-14T09:00:00.390Z", end: "2020-06-14T10:22:00.390Z", __typename: "Appointment"}
length: 2
__proto__: Array(0)

A: You can simply set the properties as moment objects. Parse correctly as utc using: moment.utc() moment.utc('2020-06-12T09:22:00.316Z'); and simply set the properties.
You can then process using moment methods and properties.
Render calling the relevant format you need.
Simple demo:

// parse as UTC correctly
const start = moment.utc('2020-06-12T09:22:00.316Z');
const end = start.clone().add(1, 'd');

const appointmentToRender = [{
  start: start,
  end: end,
  __typename: 'Appointment'
}];

const item = appointmentToRender[0];

// calcute using the moment objects
const diff = end.diff(start, 'h');
console.info(`${diff} hours difference`);

// format etc
console.info(item.end.format('ddd, Mo MMM YYYY, HH:mm'));

React:
import React, {useState} from "react";
import moment from 'moment';

export default function App() {
  const [data,] = useState(() => {
    // parse as UTC correctly
    const start = moment.utc('2020-06-12T09:22:00.316Z');
    const end = start.clone().add(1, 'd');

    const appointmentToRender = [{
      start: start,
      end: end,
      __typename: 'Appointment'
    }];

    return appointmentToRender;
  });

  return (

      {data && data.map((item, index) => (

          {item.end.format('ddd, Mo MMM YYYY, HH:mm')} ({item.end.diff(item.start, 'h')} hours long)

      ))}

  );
}


text:
Q: Second insert not working, but first and third are I have three EXECUTE statements running using psycopg2.  The first INSERT is visible after the updates and the third INSERT is visible, but second INSERT is not happening.
OpenERP is giving my function an open cursor which I use for all three statements; OpenERP then commits after my function returns.  I've tried to catch any exceptions (there are none), I've tried using debugging prints to find clues (none) -- any ideas?  Below are the statements.
works:
    cr.execute("""\
        INSERT INTO ir_act_report_xml
            (
              id, header, report_type, type, model, name, report_name,
              create_uid, create_date, write_uid, write_date,
              auto, multi, attachment_use
               )
        VALUES
            (
              %s, 't', 'pdf', 'ir.actions.report.xml', '%s', '%s', '%s',
              1, now() AT TIME ZONE 'UTC', 1, now() AT TIME ZONE 'UTC',
              false, false, false
              )
            """
            % (action_id, model_name, title_name, report_xml_id)
              )

does not work, no errors given
    cr.execute("""\
        INSERT INTO ir_model_data
            (
            module, name, model, res_id, date_init, date_update,
            create_uid, create_date, write_uid, write_date,
            noupdate
            )
        VALUES
            (
              '%s', '%s', '%s', %s, now() AT TIME ZONE 'UTC', now() AT TIME ZONE 'UTC',
              1, now() AT TIME ZONE 'UTC', 1, now() AT TIME ZONE 'UTC',
              false
              )
            """
            % (module, imd_xml_id, model_name, action_id)
            )

works:
    cr.execute("""\
        INSERT INTO ir_values
            (
              id, key, key2, value, model, name, res_id,
              create_uid, create_date, write_uid, write_date
              )
        VALUES
            (
              %s, 'action', 'client_print_multi', 'ir.actions.report.xml,%s', '%s', '%s', 0,
              1, now() AT TIME ZONE 'UTC', 1, now() AT TIME ZONE 'UTC'
              )
            """
            % (iv_id, action_id, model_name, title_name),
            )

All three are processed serially with no intervening commits nor rollbacks.

A: To track down problems like that, check what actually happens on the database.
Set log_min_duration_statement to 0 before running your SQL statements and check the PostgreSQL log file afterwards. Then you know what statements were actually executed.
Possible explanations for behavior like that:

*

*The three INSERTs are executed on different database sessions.

*The failing statement doesn't even make it to the database, and the exception is caught in Python.

*Your transaction management is different from what you think, and one statement is rolled back.


text:
Q: How to set http header Cache? I need to store the javascript and page details to browser cache using http headers.
Can anyone help me to get this?
Many thanks

A: You could use HTML meta:
<meta http-equiv="Cache-control" content="public">
or
PHP headers:
header("Cache-Control: public"); // HTTP/1.1
header("Expires: Tue, 08 Oct 2013 00:00:00 GMT"); // Date in the future

Source: [PHP Manual]

A: How about simply setting the expire date in a header -
header("Cache-Control: public");
header("Expires: Tue, 08 Oct 2013 00:00:00 GMT"); // Date in the future

It should be noted that modern browsers do a good job caching resources. Usually these methods are used to force reloading a resource; To prevent browser cache.

A: I think there is some confusion about exactly what you are wanting to cache. Two items are being referred to here -

*

*The page itself with all HTML elements and references to external files.

*A JavaScript file being referenced to by the HTML document.

To cache the first item (the page), setting the headers with PHP should cache the HTML contents of the page.
header("Cache-Control: public");
header("Expires: Tue, 08 Oct 2013 00:00:00 GMT"); // Date in the future

This will cache the contents of the page but not necessarily the files referenced by it. For example, if you had in your HTML file this code -
<script src="http://domain/some/js/file.js" type="javascript" ></script>

Then that text will be caches but not file.js. To manually set the cache on those external files, you'll need to serve them using PHP and manually set the headers.
You'll want to do something similar to this -
<script src="another_file.php" type="javascript" ></script>

Now in another_file.php you are going to want to load the JavaScript file and "echo" it out with the appropriate headers -
$file = '/absolute/path/to/your_script.js';
if (file_exists($file)) {
    header('Content-Type: text/javascript');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit();
}


text:
Q: Android Compose detectTransformGestures action end I'm using detectTransformGestures to help simplify pan and zoom operations (working fine).
I need to know when the user has finished panning or zooming (similar to ACTION_UP). Unfortunately, cannot find a way to do it.
Is there a "callback" or any other way to achieve this while keep using detectTransformGestures?

A: There is currently no such feature. You can star this feature request to get it resolved faster and to be notified when it is done.
In the meantime, you can copy the source code of detectTransformGestures and add any events you want. For example, here's how you can add an event that will be called after the last finger releases the screen:
suspend fun PointerInputScope.detectTransformGestures(
    panZoomLock: Boolean = false,
    onGesture: (centroid: Offset, pan: Offset, zoom: Float, rotation: Float) -> Unit,
    onAllGesturesEnd: () -> Unit,
) {
    val processingEvents = mutableListOf<PointerId>() // store all currently started gestures
    forEachGesture {
        awaitPointerEventScope {
            var rotation = 0f
            var zoom = 1f
            var pan = Offset.Zero
            var pastTouchSlop = false
            val touchSlop = viewConfiguration.touchSlop
            var lockedToPanZoom = false

            val input = awaitFirstDown(requireUnconsumed = false)
            processingEvents.add(input.id) // remember a newly started gesture
            do {
                val event = awaitPointerEvent()
                val canceled = event.changes.fastAny { it.positionChangeConsumed() }
                if (!canceled) {
                    val zoomChange = event.calculateZoom()
                    val rotationChange = event.calculateRotation()
                    val panChange = event.calculatePan()

                    if (!pastTouchSlop) {
                        zoom *= zoomChange
                        rotation += rotationChange
                        pan += panChange

                        val centroidSize = event.calculateCentroidSize(useCurrent = false)
                        val zoomMotion = abs(1 - zoom) * centroidSize
                        val rotationMotion = abs(rotation * PI.toFloat() * centroidSize / 180f)
                        val panMotion = pan.getDistance()

                        if (zoomMotion > touchSlop ||
                            rotationMotion > touchSlop ||
                            panMotion > touchSlop
                        ) {
                            pastTouchSlop = true
                            lockedToPanZoom = panZoomLock && rotationMotion < touchSlop
                        }
                    }

                    if (pastTouchSlop) {
                        val centroid = event.calculateCentroid(useCurrent = false)
                        val effectiveRotation = if (lockedToPanZoom) 0f else rotationChange
                        if (effectiveRotation != 0f ||
                            zoomChange != 1f ||
                            panChange != Offset.Zero
                        ) {
                            onGesture(centroid, panChange, zoomChange, effectiveRotation)
                        }
                        event.changes.fastForEach {
                            if (it.positionChanged()) {
                                it.consumeAllChanges()
                            }
                        }
                    }
                }
            } while (!canceled && event.changes.fastAny { it.pressed })
            processingEvents.remove(input.id) // remove gesture from the list when it has ended
            if (processingEvents.isEmpty()) { // if that's the last gesture - call the callback
                onAllGesturesEnd()
            }
        }
    }
}

A: Answer from Pylyp Dukhov is correct but contains some unnecessary part.
I have a detailed answer about how ACTION_UP and onTouchEvent is implemented in Jetpack Compose here, you can check it to get familiar with touch system of Jetpack Compose which might look scary at the beginning.
In a nutshelll all touch events that has a loop like drag, detect gesturest, etc are like this.
val pointerModifier = Modifier
    .pointerInput(Unit) {
        forEachGesture {

            awaitPointerEventScope {

                awaitFirstDown()
               // ACTION_DOWN here

                do {

                    //This PointerEvent contains details including
                    // event, id, position and more
                    val event: PointerEvent = awaitPointerEvent()
                    // ACTION_MOVE loop

                    // Consuming event prevents other gestures or scroll to intercept
                    event.changes.forEach { pointerInputChange: PointerInputChange ->
                        pointerInputChange.consumePositionChange()
                    }
                } while (event.changes.any { it.pressed })

                // ACTION_UP is here
            }
        }
}

When you are at the bottom of the loop which means you are already have all of your pointers up.
If you check the source code of detectTransformGestures you will see that it checks
 val canceled = event.changes.any { it.positionChangeConsumed() }

to start which means any other event consumed move/drag before this pointerInput, it works like when you want another touch to consume event when touch is for instance top right of the screen.
And while (!canceled && event.changes.any { it.pressed })
runs a loop until any is consumed or till at least one pointer is down
so just adding a callback below this while suffice.
suspend fun PointerInputScope.detectTransformGesturesAndEnd(
    panZoomLock: Boolean = false,
    onGesture: (centroid: Offset, pan: Offset, zoom: Float, rotation: Float) -> Unit,
    onGestureEnd: ()->Unit
) {
    forEachGesture {
        awaitPointerEventScope {
            var rotation = 0f
            var zoom = 1f
            var pan = Offset.Zero
            var pastTouchSlop = false
            val touchSlop = viewConfiguration.touchSlop
            var lockedToPanZoom = false

            awaitFirstDown(requireUnconsumed = false)
            do {
                val event = awaitPointerEvent()
                val canceled = event.changes.any { it.positionChangeConsumed() }
                if (!canceled) {
                    val zoomChange = event.calculateZoom()
                    val rotationChange = event.calculateRotation()
                    val panChange = event.calculatePan()

                    if (!pastTouchSlop) {
                        zoom *= zoomChange
                        rotation += rotationChange
                        pan += panChange

                        val centroidSize = event.calculateCentroidSize(useCurrent = false)
                        val zoomMotion = abs(1 - zoom) * centroidSize
                        val rotationMotion = abs(rotation * kotlin.math.PI.toFloat() * centroidSize / 180f)
                        val panMotion = pan.getDistance()

                        if (zoomMotion > touchSlop ||
                            rotationMotion > touchSlop ||
                            panMotion > touchSlop
                        ) {
                            pastTouchSlop = true
                            lockedToPanZoom = panZoomLock && rotationMotion < touchSlop
                        }
                    }

                    if (pastTouchSlop) {
                        val centroid = event.calculateCentroid(useCurrent = false)
                        val effectiveRotation = if (lockedToPanZoom) 0f else rotationChange
                        if (effectiveRotation != 0f ||
                            zoomChange != 1f ||
                            panChange != Offset.Zero
                        ) {
                            onGesture(centroid, panChange, zoomChange, effectiveRotation)
                        }
                        event.changes.forEach {
                            if (it.positionChanged()) {
                                it.consumeAllChanges()
                            }
                        }
                    }
                }
            } while (!canceled && event.changes.any { it.pressed })

            onGestureEnd()
        }
    }
}

And you need pointerIds in a loop when you want to track the first pointer that is pressed or if it's up the next one after that. This works for drawing apps to not draw line to second pointer's position when first one is down, also drag uses it too but it needs to be checked in a loop. adding and removing it before and after a loop doesn't do any work.
/*
   Simplified source code of drag

    suspend fun AwaitPointerEventScope.drag(
    pointerId: PointerId,
    onDrag: (PointerInputChange) -> Unit
): Boolean {
    var pointer = pointerId
    while (true) {
        val change = awaitDragOrCancellation(pointer) ?: return false

        if (change.changedToUpIgnoreConsumed()) {
            return true
        }

        onDrag(change)
        pointer = change.id
    }
}
 */

usage is
@Composable
private fun TransformGesturesZoomExample() {

    val context = LocalContext.current

    var centroid by remember { mutableStateOf(Offset.Zero) }
    var zoom by remember { mutableStateOf(1f) }
    val decimalFormat = remember { DecimalFormat("0.0") }

    var transformDetailText by remember {
        mutableStateOf(
            "Use pinch gesture to zoom in or out.\n" +
                    "Centroid is position of center of touch pointers"
        )
    }

    val imageModifier = Modifier
        .fillMaxSize()
        .pointerInput(Unit) {
            detectTransformGesturesAndEnd(
                onGesture = { gestureCentroid, _, gestureZoom, _ ->
                    centroid = gestureCentroid
                    val newZoom = zoom * gestureZoom
                    zoom = newZoom.coerceIn(0.5f..5f)

                    transformDetailText = "Zoom: ${decimalFormat.format(zoom)}, centroid: $centroid"
                },
                onGestureEnd = {
                    Toast
                        .makeText(context, "Gesture End", Toast.LENGTH_SHORT)
                        .show()
                }
            )
        }
        .drawWithContent {
            drawContent()
            drawCircle(color = Color.Red, center = centroid, radius = 20f)
        }

        .graphicsLayer {
            scaleX = zoom
            scaleY = zoom
        }

    ImageBox(boxModifier, imageModifier, R.drawable.landscape1, transformDetailText, Blue400)
}

Result

A: fun Modifier.onPointerUp(block: () -> Unit): Modifier = pointerInput(Unit) {
    forEachGesture {
        awaitPointerEventScope {
            awaitFirstDown()
            waitForUpOrCancellation()
            block()
        }
    }
}


text:
Q: When initialzing a variable of an interface type, what happens to the non-interface methods belonging to the class in the initialization statement? When .getClass() is called on myMap and myTreemap, "class java.util.LinkedHashMap" and "class java.util.TreeMap" are returned. Despite the matching return types, myMap can only use the methods in the map interface. I've heard that this eases programming by allowing programmers to change the implementation type easily. But - what good is changing the implementation type if I (seemingly) can only access the methods in the interface?
Also - myMap are myTreeMap are sorted according to their class type but again, what about the methods of the class type?
import java.util.*;

public class Freq {
public static void main(String[] args) {

    Map<String, Integer> m = new HashMap<String, Integer>();

    for (String a : args) {
        Integer freq = m.get(a);
        m.put(a, (freq == null) ? 1 : freq + 1);
    }

    System.out.println(m.size() + " distinct words:");
    System.out.println(m);

    System.out.println();

    Map<String, Integer> myMap = new LinkedHashMap<String, Integer>(m);
    System.out.println("map: " + myMap.getClass());
    //output is "map: class java.util.LinkedHashMap"
    //but, only the methods in the myMap interface can be accessed.

    System.out.println(myMap.toString());
    //output in order of appearance like a LinkedHashMap should.

    TreeMap<String, Integer> myTreemap = new TreeMap<String, Integer>(m);
    System.out.println("treemap: " + myTreemap.getClass());
    //output is "treemap: class java.util.TreeMap"
    //methods in the Map interface and myTreemap can be accessed.

    System.out.println(myTreemap.toString());
    //output in in alphabetical order like a treemap should.

    }
}

A: Interfaces are a great feature. Think about it -- lets say you want to implement an algorithm that uses a hashMap. Previously in the code, the user chose a hash map implementation that was optimized in algorithms ran earlier. If you didn't have an interface,(rather, if the concept of interfaces didn't exist at all...or a set of function pointers didn't exist at all ), you would have to create the new algorithm that you want to implement for each implementation of the hash map. That's a lot of redundant code, and it's not very readable.
You don't really lose access to the underlying methods. However, if you want to access the underlying TreeMap and its methods...you will have to cast it to a tree map from a map.
@suppressedwarnings
TreeMap treeMap = null;
if(myMap instanceof TreeMap){
    treeMap = (TreeMap)myMap;
}
if(treeMap == null){
     return;
     //If it wasn't the correct type, then it could not safely be cast.
}
//Now, do treeMap stuff
treeMap.treeMapOnlyMethod();

Using instanceof is usually an indicator of poor design -- instead, polymorphism should be used.

A:
I've heard that this eases programming by allowing programmers to change the implementation type easily.

Correct.

But - what good is changing the implementation type if I (seemingly) can only access the methods in the interface?

You can get e.g. Tree or Hash variants using the same API, the one published by the interface, while only changing the code at one place. If you were allowed to use the class's non-interface methods you wouldn't get that benefit: you would have to change all those calls too.

Also - myMap are myTreeMap are sorted according to their class type but again, what about the methods of the class type?

I don't understand the question. What about them?

A: You will understand the point of interface much better if you look at an example with method parameters:
boolean validateMap(Map<String, Object> map) {
  return map.get("x") != null && map.get("y") != null;
}

Observe that this method doesn't care which exactly map you passed in: it will work equally well with any type. That's the beauty of polymorphism.


text:
Q: Integration of one vector over another I have two vectors of the same size and I want to make a third vector of the same size but values of that third vector are integrated.
I did this in origin and it is quite simple, but I need that in matlab. I will post the example:
A       B           C(integrated B over A)
0       0           0
0,041   1812,282    37,15178
0,129   2186,023    213,0772
0,25    2318,906    485,62541
0,407   2141,382    835,75801
0,553   1969,284    1135,83663
0,618   1926,069    1262,4356
0,857   2149,071    1749,41483
1,034   2302,972    2143,42064
1,071   2115,559    2225,16346
1,136   2173,948    2364,57244
1,198   2301,871    2503,32283
1,262   975,241     2608,19041
1,343   0           2647,68767

Matlab work so far:
I tried
C=trapz(B,A)

and get the result
C =

-2.6481e+03

It is ok for the last data point, but I need a vector of data. See example from origin integration.
Question is:
How to integrate B over A and get vector of integrated values?

A: C = cumtrapz(A,B)

will do.

data = [
0       0           0
0.041   1812.282    37.15178
0.129   2186.023    213.0772
0.25    2318.906    485.62541
0.407   2141.382    835.75801
0.553   1969.284    1135.83663
0.618   1926.069    1262.4356
0.857   2149.071    1749.41483
1.034   2302.972    2143.42064
1.071   2115.559    2225.16346
1.136   2173.948    2364.57244
1.198   2301.871    2503.32283
1.262   975.241     2608.19041
1.343   0           2647.68767]

A = data(:,1);
B = data(:,2);

C = cumtrapz(A,B)

returning:
C =
0
37.1517810000000
213.077201000000
485.625405500000
835.758013500000
1135.83663150000
1262.43560400000
1749.41483400000
2143.42063950000
2225.16346300000
2364.57244050000
2503.32282950000
2608.19041350000
2647.68767400000