text:
Q: Javascript Regex adding an attribute within  and style=" " So I'm working on this RegEx for an extension I'm building onto Dreamweaver
I've got this snippet to work to search within the  tags to find if there ISN'T a display:block attribute - and subsequently add it.
That's works, but now I need it to search within the inline style tag within the img tags.
i.e.
<img style="border:0px;" src="" alt=""/>

Here is my regex snippet:
if (displayBlock.checked)
            {
                fixIt('<img((?:(?!display:block|/>).)*)/>','<img$1 display:block/>')
            }

if you also have some good reference material for RegEx, that would be greatly appreciated.
Kind regards,
Mike.

A: Using regex on HTML elements is typically a bad practice to use.
Why not just iterate the style property?
This iterates ALL the image tags, but you can modify the selector as you wish. Iterate the tags, check to see if the display is undefined, or, falsy, and then add the style property value.
[].forEach.call(document.querySelectorAll("img"), function(element) {
    if (!element.style.display) {
        element.style.display = "block";
    }
});

Here's a faster, but less secure, but more simple to understand for loop version!
var x = document.querySelectorAll("img");
for (var i=0; i<x.length; i++) {
    if (!x[i].style.display) {
        x[i].style.display = "block";
    }
}


text:
Q: Target class [Micoleccion\Subscription\PayPalClient] does not exist. LARAVEL Estoy desarrollando una aplicación con Laravel 9.X, y estoy intentando implementar subscripciones con la API de PayPal. El problema me aparece cuando llamo a una clase que he creado llamado PayPalClient, que se encuentra en la siguiente ruta:

miAplicacionLaravel/micoleccion/Subscription/PayPalClient.php

En esta clase, he puesto el namespace que corresponde, en este caso: namespace Micoleccion\Subscription;
También tengo un controlador desde el cual intento acceder a esta clase, de la siguiente manera:
<?php
    namespace App\Http\Controllers;
    use Micoleccion\Subscription\PayPalClient;

    class PaypalController extends Controller
    {
        private $paypalClient;

        public function __construct(PayPalClient $payPalClient)
        {
            $this->paypalClient = $payPalClient;
        }

        public function createMicoleccionProduct()
        {
            $product = [
                'name' => 'Suscripción a la herramienta',
                'description' => 'Acceso a todos los beneficios de la plataforma',
                'type' => 'SERVICE',
                'category' => 'SOFTWARE',
            ];

            try {
                return $this->paypalClient->createProduct($product);
            } catch (ClientException $exception) {
                dd($exception->getResponse()->getBody()->getContents());
            }
        }
    }
?>

Y me sale el siguiente error:

Target class [Micoleccion\Subscription\PayPalClient] does not exist.

También he probado a crearlo dentro del constructor directamente, y el error cambia de aspecto pero me sigue diciendo lo mismo, que no encuentra la clase:
public function __construct()
{
    $payPalClient = new \Micoleccion\Subscription\PayPalClient;
    $this->paypalClient = $payPalClient;
}

Class "Micoleccion\Subscription\PayPalClient" not found

También he probado a crear un objeto desde el Tinker, pero el error sigue diciéndome que no la consigue encontrar, ¿Alguien sabe como solucionarlo?

A: Laravel por defecto carga sólo las clases que están indicadas en el archivo composer.json bajo las claves "autoload": { "psr-4": { ... } }
"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/"
    }
},

Como el namespace de tu clase Micoleccion\Subscription no está especificado en el autoload, Laravel simplemente lo desconoce.
Para resolverlo se me ocurren dos opciones:

*

*Mover tu namespace para que quede dentro del namespace App, que ya está incluído por defecto en el autoload. Quedando por ejemplo así App\Micoleccion\Subscription y la estructura de directorios así miAplicacionLaravel/app/Micoleccion/Subscription/.

*Configurar el autoload para que cargue las clases de tu namespace
"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/",
        "Micoleccion\\Subscription\\" : "micoleccion/Subscription/"
    }
},

Y correr composer dump-autoload para que se vuelvan a cargar las clases junto con las del nuevo namespace.
Nota que namespaces y clases deben cumplir con el standard psr-4 que es requerido por Laravel.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to interpret "weight-position" plot when using self-organizing map for clustering? I used MATLAB neural network toolbox to train a self-organizing map for a given data set. The obtained "weight-position" plot is given as follows. I do not think this plot looks good  in comparison to the sample plot given in the MathWorks website.

I followed the standard MATLAB routine to train this SOM. Thus, I am having three questions on this case study.

*

*Which kind of information can I obtain from this plot?

*Given the shape of this plot, what can I say for the input?

*Since the training method is trivial and standard, I am wondering whether SOM can fit to my data set? My data set is composed of 3,000 data points, and each data points has 20,000 dimensions. The example given by MATLAB is only for 4 dimensions.

A: The  SOM weight position is actually a 3D plot( use the Rotate 3D tool), and it operates as described below:

*

*If the input is one dimensional (and there fore the Neuron weights are also one dimensional), MATLAB plots this input data and weight positions in the X axis, and simply completes with zeros the Y axis, and with -1 (height -1) the Z axis.

*If the input is two dimensional (hence, two dimensional weights), it follows the above procedure , but this time poting the input data in the X axis and Y Axis. The z axis is filled with -1.

*If the input is three dimensional (3Dim weights), it plots the whole input data

*If the input/weights are N-dimensional, matlab only plots the first three compoenents of the inputs/weights.

A: I would suggest write the detailed code for SOM in MATLAB. This is what I always do. Play with the Options a lot. Change the dimensions of your SOM, the neighborhood size, training epochs, etc. and check your results with each change.
Regarding your figure, I believe the position of the Weights are not good as some part of your data are not properly modeled by the current position of the weights.
I would change the dimensions and the initial neighborhood and try again. Ideally, the weights should cover all parts of the data so when a new data comes in, they can assign it to the exact cluster.
This figure also shows your data in scattered with regard to the position of the current weights. I would not consider this a good representation of my data and suggest to change the parameters of SOM as I mentioned.
Good luck,
Pey.


text:
Q: Algorithm for checking transitivity of relation? I need to check if relation is transitive or not?
Would you please suggest some algorithm to check the transitivity of relations?
I am storing relation as a boolean matrix there is 1 if elements are related other wise 0 like in graphs.
Thanks.

A: Much simpler algorithm as my Map/Set version (deleted), now with boolean matrix. Maybe this is easier to understand, even if you don't know Java?
public class Trans
{

  final static int SIZE = 4;

  static boolean isTransitive(boolean[][] function)
  {
    for (int i = 0; i < SIZE; i++)
    {
      for (int j = 0; j < SIZE; j++)
      {
        if (function[i][j])
        {
          for (int k = 0; k < SIZE; k++)
          {
            if (function[j][k] && !function[i][k])
            {
              return false;
            }
          }
        }
      }
    }
    return true;
  }

  public static void main(String[] args)
  {
    boolean[][] function = new boolean[SIZE][SIZE];
    for (int i = 0; i < SIZE; i++)
    {
      function[i] = new boolean[SIZE];
    }
    function[0][1] = true;
    function[1][2] = true;
    function[0][2] = true;
    function[0][3] = true;
    function[1][3] = true;
    System.out.println(isTransitive(function));
  }
}

A: Despite this totally sounds like homework...
You'd need to store your relations so that you can look them up by the antecedent very quickly. Then you can discover transitive relations of the type A->B->C, add them to the same storage, and keep going to look up A->B->C->D, etc etc...

A: Topological sorting may be the right direction. The relationship is transitive if there are no loops in its directed graph representation. If you care about speed, graph algorithms are probably the way to go.


text:
Q: Inverting type erasure, i.e. get types back afterwards I have a fairly generic work queue. It takes some number of std::function<void(void)> and executes them on N worker threads. Closures + type erasure working well.
Now however, I would like the functions to "return" some state, and I would prefer the queue know nothing about what the types might be. To that end, I am considering using a queue of
std::function <std::function<void(void)>(void)>

Which, if I can keep the syntax straight, is a function taking void and returning a function taking void and returning void. The idea being to add a second work queue to return the result of the task execution.
This doesn't strictly solve the problem though - I can then call the returned value, but this doesn't obviously allow me to retrieve the state.
I could return boost::any, which doesn't appear to tell me what the contained type is, or boost::variant which means providing the task library with a list of all possible return types. Neither seem ideal.
What I would like to do is encode the information required to interpret the result of the function call within the functor, but I do not see a clean way to achieve this. Bundling an execute() and an extract() method into a single void(void) functor is beyond my cunning.
An alternative workaround is a heterogenous work queue, but such a thing is also quite a pain to write in C++. I feel optimistic that there is an idiomatic solution for getting at the unknown type that results from executing type erased code, but guessing the search keywords has not gone well for me. Guidance would be appreciated.
edit: An outline of the intended workflow for the application code, as distinct from the work queue / thread pool layer

*

*Construct one or more tasks to execute asynchronously

*Package the tasks as std::function</*consistent type*/>

*Push onto queue provided by a library

*Do some other things for a while

*Retrieve an opaque type of some sort from the queue

*Pass this opaque type to a function that works out what it actually is

*All is well from here

edit: As suggested in the comments, type erasure goes both ways.
Let the generic functor be:
struct functor
{
  typedef std::function<void(void)> functype;
  functype async;
  functype result;
};

Then use an instance of queue<functor> for both send and receive. Async gets run on a remote thread. When an instance of functor comes back we have no idea what it represents, but the result() member does and can perform whatever next step is considered reasonable. This will probably suffice.

A: (Copying from my comment):
Instead of having step 6 know the precise concrete type, what about solving your problem by using either dynamic or static polymorphism instead?


text:
Q: How can I call lightning component from Quick Action? I have a lightning page.I click Edit Page. Now there are multiple sections in which Actions are added.
Now I have to add a button / link which will call a custom lightning component.
I have attached a screenshot. Please have a look at this.

A: Add this in your component implements="force:lightningQuickAction"


text:
Q: How to remove duplicate rows as well as old records in Oracle database I search through the net and didn't find answer for this kind.
I have table emp_master_data, which have many columns but I want to use few columns to filter the data ( select query) and then after analyzing, I want to delete those records.
The filter should be applied on three columns emp_card_no, emp_id , enrollment_exp_dt.  An employee can be enrolled multiple times , which means you'll have multiple records with same emp_no, emp_id and same/different enrollment_exp_dt.
Now , I need to do this:

*Remove the duplicate records if there are multiple records with same enrollment_exp_dt, emp_card_no and emp_id.

*If in case I have multiple records for same employee but different enrollment_exp_dt , then remove the old records and keep only the latest record ( doesn't have to be >sysdate).
Please let me know the best way I could do. I did try doing this but doesn't solve all the problems.

SELECT *
FROM brm_staging A
WHERE EXISTS (
  SELECT 1 FROM brm_staging
  WHERE enrollment_exp_dt = A.enrollment_exp_dt
  and emp_id= A.emp_id
  and emp_card_no =A.emp_card_no
  AND ROWID < A.ROWID
);

A: i got really complicated. can you try the select statement first before deleting and see if this is working? (this is for second senario)
DELETE FROM YOUR_TABLE T1
INNER JOIN (
SELECT T2.* FROM YOUR_TABLE T2,
(SELECT EMP_ID, CARD_NO, COUNT(*) FROM
YOUR_TABLE
GROUP BY EMP_ID, CARD_NO
HAVING COUNT(*) > 1) T3
WHERE T2.EMP_ID=T3.EMP_ID AND T2.CARD_NO = T3.CARD_NO AND
T2.ENROLLMENT_EXP_DT NOT IN (SELECT MAX(T4.ENROLLMENT_EXP_DT)
FROM YOUR_TABLE T4) T5 ON
T1.EMP_ID=T5.EMP_ID AND T1.CARD_NO=T5.CARD_NO AND T1.ENROLLMENT_EXP_DT=T5.ENROLLMENT_EXO_DT

(EDIT) i think this work too (more simplified)
DELETE FROM YOUR_TABLE T1
WHERE EXISTS (
SELECT T2.* FROM YOUR_TABLE T2,
(SELECT EMP_ID, CARD_NO, COUNT(*) FROM
YOUR_TABLE
GROUP BY EMP_ID, CARD_NO
HAVING COUNT(*) > 1) T3
WHERE T2.EMP_ID=T3.EMP_ID AND T2.CARD_NO = T3.CARD_NO AND
T2.ENROLLMENT_EXP_DT NOT IN (SELECT MAX(T4.ENROLLMENT_EXP_DT)
FROM YOUR_TABLE T4)


text:
Q: HTML5 input type of range and color can't be empty. What if the database column they are mirroring is null? Among the relatively new HTML form controls are the 'type=range' and 'type=color' controls. The spec states that when a form containing such controls is submitted, there will always be a value submitted for those controls. They can never be empty.
This differs from the type=text control, and other similar controls, whose value can indeed be the empty string.
It seems to be impossible for range and color controls to be used to reflect the state of nullable columns in a database.
Is there any workaround for this?
Edit: The behavior is specified by this link here: HTML5 Specification

A: For ranges, you could set the value of the range to a number that is out of bounds (of course, if you wanted the user to not mess with it):
var range = document.getElementById('rangeInput');
 //let's say your range is 0-10

 rangeInput.style.display = 'none';

 range.min = -1;

 range.value = -1;
 //-1 would be your "null" value

 //now, if you wanted the user to be able to edit the null range...

 range.style.display = '';

 range.addEventListener('change',function(){
     if(this.value < 0) this.value = 0;
     //this should keep people from setting it to "null"
 });

I'm still unsure as to how you would do this for color inputs, because there is no "out of bounds" for it.


text:
Q: Is it possible to specify when a Build Feature is to be run? TeamCity 8.1.4 (build 30168)
I notice that Build Features are always run as first part of first step in the Build Steps, but is it possible to make a Build Feature run e.g. as first part of step2? Or as last part of Step1?
Any help is appreciated!
(If it is of interest, this is my concrete problem;
I have a meta runner that creates a specific build number, I use this as a first step in the build steps. I want to use the build feature "AssemblyInfo patcher", but this runs before the meta runner has done its thing)

A: *

*Create another build configuration, move your meta-runner there.

*Modify your build parameter to report a build number through service message

*Create a snapshot dependency from your build configuration to the new one

*In the configuration with meta-runner go to general page, enter %dep.META_RUNNER_CONFIG_ID.build.number% to 'build number' field. This will take a build number from the dependency and set it as a build number. META_RUNNER_CONFIG_ID is the Build configuration id you will see on the general page of your configuration where you have moved meta runner.

*Use %build.number% as a replacement in AssemblyInfoPatcher


text:
Q: Cannot Access Elements (iframe) using the cypress suggested selector I have a difficulties with some content of the web-page when I am trying to discover the element
For example some part of the web-page is blocked by the following:
[data-testid=shell-content]

Any idea what could possibly cause following?
In the browser, the page isn't blocked and (all buttons) can be accessed by the keyboard or mouse.
Tried to upgrade to the lates version, still the same problem.

A: The problem was described against the iframe, it has to be handled in a similar way in order to access the elements
cy.enter('iframe[data-testid="iframe-content"]').then((getBody) => {
    getBody().find('[data-test-id="create-user-button"]').click();

please note that name shell-content could be different to what was name in your project.


text:
Q: How to fix "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'skill' available as request attribute" error Getting the error seen in the title as well as "Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "profile" - line 35, col 48)" which is line 4 below in html. How can this be fixed? I looked through a lot of similar questions and most were using a method with @RequestMapping instead of the @PostMapping.
@Controller
public class SkillController {

    @Autowired
    private SkillRepository skillRepository;

    @Autowired
    private AccountRepository accountRepository;

    @GetMapping("/profile/{path}/skill")
    public String view(@PathVariable String path, Model model) {
        model.addAttribute("skill", new Skill());
        return "redirect:/profile/" + path;
    }

    @PostMapping("/profile/{path}/skill")
    public String addSkill(@PathVariable String path, @ModelAttribute("skill") Skill skill, BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            return "redirect:/profile/" + path;
        }
        try {
            Account a = accountRepository.findByPath(path);
            a.getSkills().add(skill);
            accountRepository.save(a);
            return "redirect:/profile/" + path;
        } catch (DataIntegrityViolationException ex) {
            bindingResult.rejectValue("name", "name", " Please try again!");
            return "redirect:/profile/" + path;
        }
    }

}

<form th:action="@{/profile/{path}/skill(path=${path})}" th:object="${skill}" method="POST">

                        <input type="text" th:field="*{name}"/>
                        Character error.

                        <button type="submit">Add skill</button>

            </form>

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Skill extends AbstractPersistable<Long> {

    @NotEmpty
    @Size(min = 4, max = 16)
    @Column(unique = true)
    private String name;

}

A: For passing attributes on redirects, RedirectAttributes should be used instead of Model:
@GetMapping("/profile/{path}/skill")
public String view(@PathVariable String path, RedirectAttributes redirectAttrs) {
    redirectAttrs.addFlashAttribute("skill", new Skill());
    return "redirect:/profile/" + path;
}


text:
Q: WPF if statement based on radio button checked or not I'm having difficulty with something which seems like it should be very simple.  I'm coming from Windows Forms and starting up with WPF.  I think I have a simple syntax issue but I can't seem to find a specific example for this radio button issue.
I have a radio button on my GUI for a query to run either via a map selection or a list. When load is clicked, it should perform one operation if map is selected, a different operation for list.  Code looks similar to this:
private void Load_Click(object sender, RoutedEventArgs e)
{
  if (rdBtnList.Checked == true)
  {
    //do this
  }

  // if rdBtnList not checked (ie if rdBtnMap is checked)
  // do this
}

Any help would be greatly appreciated.  Thanks.

A: Change:
if (rdBtnList.Checked == true)

to
if (rdBtnList.IsChecked == true)

Note:
I'm coming from Windows Forms and starting up with WPF

*

*You must forget everything you ever learned in winforms, and embrace MVVM. You should create a ViewModel and bind your rdBtnList.IsChecked property to some boolean value in the ViewModel, then perform your logic in there. The views' code behind is not the right place for application logic.

A: The property in WPF is called IsChecked hence you just need to update the if statement
if (rdBtnList.IsChecked == true) {
  ...
}

The IsChecked property is bool? (nullable value) in WPF so you may choose to be more explicit here by doing the following
if (rdBtnList.IsChecked.HasValue && rdBtnList.IsChecked.Value) {
  ...
}

A: Are you missing a return statement? As is, the posted code will always execute the if not checked path:
private void Load_Click(object sender, RoutedEventArgs e)
{
  if (rdBtnList.IsChecked == true)
  {
    //do this
    return; // return, or the if not checked path below will always win.
  }

  // if rdBtnList not checked (ie if rdBtnMap is checked)
  // do this
}

In WPF, you'll need to use the IsChecked property. See the RadioButton Class for more details.


text:
Q: How to patch an eclipse plugin? I'd like to fix a bug in an eclipse plugin (an official plugin of the WTP).
I locally changed the source code, debugged it - everything is fine.
Now I'd like to propagate this change to my eclipse installation, but I am facing problems.
There seems to be more than one way to achieve this, e.g.:
This site recommended fragments, but the Eclipse FAQ disadvises that.
But I am stuck and no way seems to work for me.
UPDATE:
I tried to create and install a feature patch, as suggested.
After this installation the feature patch is installed, but not the containing patched plugin.
The previous/existing version of the plugin is still present and active.
I'd like to know why this is the case?
Does this something have to do with signing of the official plugins?
Is there a log to see why the patched plugin has not been installed?
FINAL UPDATE:
The problem was that I patched a parent feature (which has been shown in the eclipse installation details), not the direct feature which directly contained the plugin.
After specifying the correct/"lowest-level" feature for patching, everything worked as expected.

A: The best approach is to create what's known as a "feature patch". A feature patch consists of the entire new version of the plugin you are patching along with a feature that describes what's being patched. See this useful blog post:
http://aniefer.blogspot.com/2009/06/patching-features-with-p2.html


text:
Q: Expo and Admob: "Error Domain=com.google.admob Code=1 "Account not approved yet...." I am trying to use expo-ads-admob with Expo but I am getting the following error: Error Domain=com.google.admob Code=1 "Account not approved yet. <https://support.google.com/admob/answer/9905175#1>" UserInfo={NSLocalizedDescription=Account not approved yet. <https://support.google.com/admob/answer/9905175#1>
The steps I have done:

*

*Created an Admob account.

*Create app for both ios and android.

*Created Ad units for ios and android (it has been several hours).

This is my code:
<AdMobBanner
  bannerSize="mediumRectangle"
  adUnitID={ Platform.OS === 'ios' ? "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx" : "ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx" } // Test ID, Replace with your-admob-unit-id
  servePersonalizedAds
  onDidFailToReceiveAdWithError={(err) => console.log("error : ", err)}
/>

And this is my app.json.
{
  "expo": {
    "name": "catch3",
    "slug": "catch3",
    "version": "1.0.0",
    "orientation": "portrait",
    "icon": "./assets/icon.png",
    "splash": {
      "image": "./assets/splash.png",
      "resizeMode": "contain",
      "backgroundColor": "#ffffff"
    },
    "updates": {
      "fallbackToCacheTimeout": 0
    },
    "assetBundlePatterns": [
      "**/*"
    ],
    "ios": {
      "supportsTablet": true,
      "userInterfaceStyle": "light",
      "config": {
        "googleMobileAdsAppId": "ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx"
      }
    },
    "userInterfaceStyle": "automatic",
    "android": {
      "useNextNotificationsApi": true,
      "userInterfaceStyle": "dark",
      "config": {
        "googleMobileAdsAppId": "ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx"
      }
    },
    "web": {
      "favicon": "./assets/favicon.png"
    }
  }
}

Can anyone help me figure out what I'm doing wrong?


text:
Q: How to change the child element in SOAPBODY I have a soapMessage which i am writing to a ByteArrayOutputStream to log the request
But I have to change p803:Credential child element value before i log it, how can I do this?
ByteArrayOutputStream out = new ByteArrayOutputStream();
soapMessageCtx.getMessage().writeTo(out);

Here is the  request xml
<soapenv:Body>
<p803:multiple xmlns:p803="http://www.abc.com/model">

<p803:RequestContext>
<p803:Credential>2222222/iuuiiiuuuu</p803:Credential>

A: Try this :
SOAPMessage soapMsg = soapMessageCtx.getMessage();
NodeList credentials = soapMsg
                        .getSOAPBody()
                        .getElementsByTagNameNS("http://rsi.chase.com/model", "Credential");

int len = credentials.length();
for(int i = 0; i < len; i++) {
    credentials.item(i).setTextContent("new credential content goes here...");
}

ByteArrayOutputStream out = new ByteArrayOutputStream();
soapMsg.writeTo(out);

// ...


text:
Q: Android Studio's windows flickering on OSX VM I installed OSX EL Capitan on VM, and the base OS is Windows 8.
I 'm using Android Studio in VM, and when I type or click in the window, the screen flickers.
But when I stop typing or clicking, or switch to other windows, it does not happen.
Is this kind of a performance issue? Did you face this issue before?
Android Studio version : 2.2.3
OSX version : 10.11
VMWare Workstation version : 11.1.0

A: I was having the same issue also.
I resolved it by updating OSX to the latest version, and the flicking was gone.
Please give it a try.
Thank you.


text:
Q: Refiners for multi-valued managed properties in SharePoint Refiners for multi-valued managed properties do not behave like they do for Site Columns when they are created. Values are being refined to "Value one;Value two;Value three" instead of:

*

*Value one - (3)

*Vaue two - (4)

*Value three - (5)

I've seen SharePoint 2010 posts that answer the question but not 2013. Any help would be a appreciated!

A: Actually separators are not used any longer in SharePoint 2013. The multivalue field needs to be populated using a List of items, e.g. List<string>.
I'm using Content Enrichtment to populate my field using Property<List<string>> ; a good example from Microsoft:
How to: Use the Content Enrichment web service callout for SharePoint Server
I found another interesting sample in the Microsoft forums:
Index a multiple value column in BCS external content type "SharePoint 2013"

A: Create a custom Filter based on the OOB MultiField one. Split the filters into new filters, instead of hex use the actual plain text value.
I have described everything here:
https://hyankov.wordpress.com/2014/12/15/sharepoint-2013-refiner-multi-value-contains-instead-of-an-equals/

A: The simple answer to this question in SharePoint 2013 is to make the Managed Property 'Allow multiple values'.  This is done through Search Schema in the settings list.
This allows a single option to match, even when multi-choices are selected.


text:
Q: Testing private methods in controllers and the provided template by sidewaffle I have been learning how to test my app written in angular stuff and I'm getting confused because it seems there are a few things against each other. I try to follow John Papa's style guide, so that I'm using Sidewaffle templates for everything basically. At the moment, it seems, the suggested template and testability against each other.
The style guide says that there is an

activate()

method in your controller which takes care about the start-up logic of the controller as you can see here. However, general testing guide line says that private method should not be tested. I have the chance to test the result of the activate() method in the provided example, because it will be passed through

vm.avengers

variable. In his Pluralsight videos he uses common.activatecontroller() method where he uses

$q.all()

to combine promises, so that you can easily call many function in controller activation phase. Let say that I have a function which won't have a result can be passed through vm, for example a post message to WebApi to authenticate the user and get the token and set it up to headers, or something like this. Here is an example (service is not injected, it is just an example):
In the controller below the only business logic is that, when the controller is instantiated the activate() method calls the func1() method which calls the OAuthenticationService.authenticate() method. From testing perspective it is important whether the service was called or not. How to test this?
Here is a very similar question where one of the answers suggests that I should use this keyword like this:

this.activate()

But a comment says that it is not working with ControllerAs syntax. I'm following the ControllerAs syntax.
When I create a mock for the service with spy on the authenticate method the test says that I was not called, I think due to that the method is private.
I run out of ideas...
Thanks for any help in advance!
Example

(function () {
    'use strict';

    angular
        .module('app')
        .controller('controller', controller);

    controller.$inject = ['$location'];

    function controller($location) {
        /* jshint validthis:true */
        var vm = this;
        vm.title = 'controller';

        activate();

        function activate() {

            func1();

        }

        function func1() {

            OAuthAuthenticateService.authenticate(user).then(function() {

                //setting up headers and other stuff, nothin will be part of $scope or vm;

            });

        }
    }
})();

Original code:

(function () {
    'use strict';

    var controllerId = 'requestAuthorizationController';

    angular
        .module('myapp')
        .controller(controllerId, requestAuthorizationController);

    requestAuthorizationController.$inject = ['$rootScope',
                                                '$scope',
                                                'requestAuthorizationService'
                                                'Restangular'];

    function requestAuthorizationController($rootScope,
                                            $scope,
                                            requestAuthorizationService
                                            Restangular) {
        /* jshint validthis:true */
        var vm = this;

//other business logic

        activate();

        function activate() {

            requestAuthorization();

        }

        function requestAuthorization() {

            vm.fired = undefined;

            requestAuthorizationService.getDummy();

        }
    }
})();

Jasmine test:
'use strict';

describe('RequestAuthenticationController Specification', function () {

    var RestangularProviderMock,
        localStorageServiceProvider,
        $httpProvider,
        requestAuthorizationController,
        requestAuthorizationServiceMock,
        $rootScope;

    //modules
    beforeEach(function() {

        angular.module('dilib.layout', []);
        angular.module('http-auth-interceptor', []);

    });

    //providers
    beforeEach(function () {

        module('dilib', function(RestangularProvider, _localStorageServiceProvider_, _$httpProvider_, $provide) {

            RestangularProviderMock = RestangularProvider;
            localStorageServiceProvider = _localStorageServiceProvider_;
            $httpProvider = _$httpProvider_;

            $provide.service('requestAuthorizationService', function() {
                this.getDummy = jasmine.createSpy('getDummy').and.callFake(function(num) {
                });
            });
        });

    });

    //to crank up the providers
    beforeEach(inject());

    beforeEach(inject(function (_$rootScope_, _$controller_, _requestAuthorizationService_) {

        $rootScope = _$rootScope_;
        requestAuthorizationController = _$controller_;

        requestAuthorizationServiceMock = _requestAuthorizationService_;

    }));

     describe('requestAuthorization function', function() {

         it('RequestAuthorizationService.getDummy() is called', function() {

            $rootScope.$digest();
            expect(requestAuthorizationServiceMock.getDummy).toHaveBeenCalled();

        });

    });

});

A: I think the whole approach I had is wrong. I have way too much business logic in the controller. According to this article and others I have to reduce the business logic in the controller as much as possible and place it in service public methods. If I follow this rule then there will be no need for private methods. However, the question still stands what to do with the

activate()

method. It is enough to test the result of the executed function which is the populated viewmodel? I think, the answer is yes.
At the moment I'm focusing on whether the viewmodel variables are populated properly or not, and I'm refactoring the business logic into services.
In my opinion it is very easy to write working but hard to test code, than working and easy to test code.
The another aspect of the story is that I have been working as a tester for 10 years with good experience at many aspects of testing. But now, I'm just scratching my head how to write code on testable / test driven development way. :)

A: So in John Papa's style guide the activate() method is meant as an abstraction. If you have a lot of setup that you would be doing in your constructor method, instead abstract it out to the activate() method. Your constructor is then clean. I am not sure there is too much value to this in your posted code.
On a side note, you should only be unit testing the APIs, external interfaces, of your units. So for a controller, the properties and methods that are called by actions in views.


text:
Q: Replace youtube embed iframe by video ID - Javascript I need to replace some youtube iframes by something like a bbcode. Example:
Sample content:

lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
  ipsum
[iframe width="560" height="315"
  src="http://www.youtube.com/embed/RbJjC98ArCI" frameborder="0"
  allowfullscreen][/iframe]
lorem ipsum lorem ipsum lorem ipsum lorem ipsum

*

*note that I needed to replace the characteres < AND > BY [ AND ] or the iframe code wouldnt be shown.

The content replaced:

lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem ipsum lorem
  ipsum
[youtube]RbJjC98ArCI[/youtube]
lorem ipsum lorem ipsum lorem ipsum lorem ipsum

Javascript sample code:
var content_with_bbcodes=content.replace(SOME_REGULAR_EXPRESSION_HERE, '[youtube]$1[/youtube]');

I would also like the inverse. A regular expression to convert the bbcode to iframe...
Someone here experienced about regular expressions?

A: Here's something that should work.
var content_with_bbcodes=content.replace(/\[.+?embed\/(.+?)\".+\]/, '[youtube]$1[/youtube]');

As for the inverse, it's doable but you'll have to add the width and the height.
// sample
var height = 100;
var width = 200;
var content_iframe=content_with_bbcodes.replace(/\[youtube\](.+?)\[\/youtube\]/,'[iframe height="'+height+'" width="'+width+'" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen][/iframe]');


text:
Q: Create Unusual Recurring Outlook Event: First Saturday Following the 18th of Every Month For IT maintenance, I'm about to set up a recurring event in Outlook 365, shared with several attendees across several timezones.
The event is scheduled to occur on the first Saturday Following the 18th of Every Month - thus dates can be 19-25, both included. In other words, this will occur on either the 3rd or 4th Saturday of the month.
I've tried the following:

*

*Looking through the available GUI options, it appear nested rules are impossible.

*In the past have been guided to use VBA to set up the event,
but on Outlook 365 that's not an option.

*It's easy to specify as an iCalendar event like this RRULE:FREQ=MONTHLY;BYDAY=SA;BYMONTHDAY=19,20,21,22,23,24,25 but it appear to be impossible to import it into Outlook, without using an Outlook Desktop Extension and syncing with an entire iCalendar.

*Creating it in crontab is similar easy (here set at 16:00): 0 16 19,20,21,22,23,24,25 * 6, but unfortunately outlook calendar does not seem to support the crontab format in any way.
So I've hit the limit of my ideas, and hope some of you can share some wisdom.


text:
Q: WIFI stopped working on Xubuntu Today I turned on my notebook and I couldn't connect to my network, it just keeps asking for my password. That's weird because I've been using it on this network forever and never saw this error.
So I restarted my router thinking that could be the problem, and nope, both my desktop computers connect fine but my notebook still can't connect.
So I boot my notebook on Windows 7 and it connects just fine, so it's not a hardware thing...
The encryption im using is WPA & WPA2 Personal, and the wireless card is RTL8111/8168 PCI Express Gigabit
Why can't I connect to wifi on my xubuntu notebook?

A: It turns out for some reason the drivers broke... I downloaded the drivers from Realtek and installed them, reboot, and it now works as a charm!
tar -xvzf myDriver.tar.gz
cd myDriver/
sudo make
sudo make install
reboot

Thanks to everyone who helped :)
EDIT: I had to follow this guide for a source code error on their driver code


text:
Q: React and Webpack Issue I have started to build a React App and implemented 3 pages which worked fine.
After structuring the first page, my app crashed and I am not able to restart it since.
I don´t know if it has something to do with it but I use Redux as well.
I tried without the page I created cause I thought maybe I messed up there. But nothing changed. I even rebuilt my app 2 times now without any changes.
Following errors occur:
Errors
Folders:
My folder structure
Package.json
My package.json file
However, the backend is running perfectly fine. Issue is just on the frontend.
I tried multiple tutorials how to fix this but nothing worked
Thanks for help in advance


text:
Q: How to receive property from control to model CanJS (define modules) I have Control with configurable defaults parameters:
   define([
  'jquery',
  'can',
  'moment',
  'controls/base',
  'mustache!./becauseYouShopped_view',
  './becauseYouShopped_model',
  'coreMods/clickHistory/v2/clickHistory_model',
  'coreMods/addToFavorite/addToFavorite_control',
], function ($, can, moment, BaseControl, becauseYouShoppedView, BecauseYouShoppedModel, ClickHistoryModel, AddToFavorite) {
  var startDate = moment().subtract(90, 'days').format('YYYY-MM-DD'),
    endDate = moment().add(1, 'days').format('YYYY-MM-DD');

  var BecauseYouShopped = BaseControl({
    defaults: {
      moduleConfigName: 'becauseYouShopped',
      hideRebatePrefix: true,
      rebateAdditionalPrefix: 'Shop and',
      useOldRebateValueWithoutCurrency: true,
      tiered: {
        rebateAdditionalPrefix: 'Shop and earn',
        useOldRebateValueWithoutCurrency: true
      },
      apiParams: {
        start_date: startDate,
        end_date: endDate,
      },
      headingPrefix: 'Because you shop at',
      dataLimitForGetSimilarMerchant: 14,
    }
  }, {
    init: function (element, options) {
      ClickHistoryModel.findOne(options.apiParams).done(function (data) {
        var memberClicksAndOrders = data.attr().response;

        if (memberClicksAndOrders.length) {
          this.shoppedMerchantsInfo = this.getRecentlyShoppedMerchantName(memberClicksAndOrders);

          if (this.shoppedMerchantsInfo) {
            this.getRecommendedMerchantsAndRender();
          }
        }
      }.bind(this)).fail(function (error) {
        mn.log(error);
      });
    },
  return BecauseYouShopped;
});

And I need to export this parameter      dataLimitForGetSimilarMerchant: 14, to the Model of this Control for use it in getSimilarMerchantData function.
But when I importing it  - in way as You can see on the code here:
   define(['jquery', 'can', 'utils/promiseUtils', 'models/base', 'controls/base', 'coreMods/bonusComponents/becauseYouShopped/becauseYouShopped_control',], function ($, can, promiseUtils, BaseModel, BaseControl, BecauseYouShopped) {
  console.log("1 log: ", BecauseYouShopped);
  return BaseModel.extend({
    /**
     * Get response from one content group and type
     * @param contentGroupIdAndType
     * @returns {*}
     */
    getSimilarMerchantData: function (merchantId, merchantName) {
      var deferred = $.Deferred(),
        self = this;
      var controlOptions = BecauseYouShopped.defaults.dataLimitForGetSimilarMerchant;
      console.log("2 log: ", BecauseYouShopped);
      if (!merchantId) {
        return can.Deferred().reject('merchant id is not specified');
      }

      var options = {
        url: mn.contentAPIEndPoint + '/merchants/' + merchantId + '/similar',
        method: 'GET',
        dataType: 'json',
        headers: self.getAjaxHeaders(),
        data: self.getDefaultAjaxData({limit: controlOptions})
      };

  }, {});
});

I received that BecauseYouShopped is undefined
So, how can I import this parameter to the model?

A: You have the BecauseYouShopped control importing the BecauseYouShopped model, but the model is also importing the control.  This sort of circular dependency can sometimes be resolved by your dependency manager if you are not trying to use the dependency module in-thread -- StealJS does this, for example -- but if you are using RequireJS like it seems you are based on the use of define(), you will need to require() one of your dependencies late rather than define()'ing it on initial load.  More on this at https://requirejs.org/docs/api.html#circular


text:
Q: Hadoop CLI command to get Total Memory Used, etc like shown in Hadoop Web UI on 8088 Is there a CLI command I can use to get the Metrics show in this picture as they appear in the Hadoop Web UI on 8088?

A: yarn top would show this.  It works similar to the UNIX/Linux command top.
Source code at https://github.com/apache/hadoop/blob/trunk/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/TopCLI.java:


text:
Q: why i Should use UnusedMaterialScaffoldPaddingParameter top of Compose function? When I don't use the following code, it is displayed on the page.
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")

A: You should use the PaddingValues of the Scaffold because these values are calculated based on the other items inside of your scaffold. For instance when you use a topBar or BottomBar, your screen will be partially covered with the UI element. When you use the PaddingValues inside the content of your scaffold this won't happen. You can use de PaddingValues like this:
Scaffold(
    topBar = {
        // some TopBar
    },
    bottomBar = {
        // some BottomBar
    },
) { paddingValues ->
    Box(
        modifier = Modifier.padding(bottom = paddingValues.calculateBottomPadding(), top = paddingValues.calculateTopPadding())
    ) {
        // your UI
    }
}


text:
Q: Accessing specific changeItem using Sharepoint REST API I'm trying to get an individual change event using;

GET
* https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges('query')/item

Reference
http://msdn.microsoft.com/en-us/data/jj246759(v=office.12).aspx
And
http://msdn.microsoft.com/en-us/library/office/jj246759(v=office.15).aspx
I'm unable to get it working, and I can't find any example of this call.
I'm trying something like;

GET

*

*https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges('Add=true,Item=true')/item

*https://{sitecollection}/{personal/user_name_domain_onmicrosoft_com}/_api/web/getchanges(query='Add=true,Item=true')/item

but no luck.
FYI:: I'm not trying to get changelogs with this call. I'm trying to get an individual change item. But since the syntax is like that I put a random query in the those braces. The /getchanges(which is a POST call) works fine.
Any help on this?

A: There are at least two options how to construct request for a ChangeCollection endpoint:
Option 1
Post ChangeQuery via request body
function getChanges(webUrl,queryOptions,success,failure)
{
   var changeQueryPayload = {
       'query':{
           '__metadata': { 'type': 'SP.ChangeQuery' },
        }
   };
   for(var key in queryOptions) {
       changeQueryPayload['query'][key] = queryOptions[key];
   }

   $.ajax({
      type: "POST",
      headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
      },
      data: JSON.stringify(changeQueryPayload),
      url: webUrl + '/_api/web/getchanges',
      success: success,
      failure: failure
   });
}

Option 2
Pass ChangeQuery expression via query string:
function getChanges(webUrl,queryOptions, success,failure)
{
   $.ajax({
      type: "POST",
      headers: {
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
      },
      url: webUrl + '/_api/web/getchanges(@qry)?@qry=' + JSON.stringify(queryOptions) + ,
      success: success,
      failure: failure
   });
}

Example
Retrieve updates for a web:
var queryOptions = {"Update":true,"Web":true};

getChanges(_spPageContextInfo.webAbsoluteUrl,queryOptions,
  function(result){
      var changes = result.d.results;
      //print info
      console.log('Found ' + changes.length + ' items');
  },
  function(error){
     console.log(JSON.stringify(error));
  });

Regarding requesting a specific change item, it could be retrieved from a results returned from REST service.

A: There is an example:
http://msdn.microsoft.com/en-us/library/office/dn499819(v=office.15).aspx
executor.executeAsync({
  url: "<app web url>/_api/SP.AppContextSite(@target)/web/getchanges?@target='<host web url>'",
  method: "POST",
  body: "{ 'query': { '__metadata': { 'type': 'SP.ChangeQuery' }, 'Web': true, 'Update': true } }",
  headers: {
    "accept": "application/json;odata=verbose",
    "content-type": "application/json;odata=verbose"
  },
  success: successHandler,
  error: errorHandler
});

A: Please refer https://msdn.microsoft.com/en-us/library/office/dn499819.aspx.
Following code is working for me.
$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getchanges",
    type: "POST",
    data: "{ 'query': { '__metadata': { 'type': 'SP.ChangeQuery' },'Web': true, 'Update': true, 'Add': true } }",
    headers: { "accept": "application/json;odata=verbose", "content-type": "application/json;odata=verbose",'X-RequestDigest':$('#__REQUESTDIGEST').val() },
    success: successHandler,
    error: errorHandler
});

function successHandler(data, textStatus, jqXHR ){
    alert("successHandler " + "textstatus:" +textStatus + "data: " + data);
}

function errorHandler(xhr, ajaxOptions, thrownError) {
    alert('Request failed: ' + xhr.status + '\n' + thrownError + '\n' + xhr.responseText);
}


text:
Q: chef-client run fails to sync cookbooks with EOFError: end of file reached When running a cookbook with chef-client, the run fails with this error:
  EOFError: end of file reached
I'm fairly new to this, and I don't know what this means.  The cookbook is a very simple wrapper around the community cookbook which should be good.
https://supermarket.chef.io/cookbooks/powershell
Here's the error again:
Synchronizing Cookbooks:
  - windows (1.37.0)
  - ms_dotnet2 (0.0.0)
  - ms_dotnet45 (0.0.0)
  - powershell (3.1.0)
  - chef_handler (1.1.8)
  - ewe-powershell (0.1.0)

  ================================================================================
  Error Syncing Cookbooks:
  ================================================================================

  Unexpected Error:
  -----------------
  EOFError: end of file reached

  Running handlers:
[2015-11-18T08:30:15-08:00] ERROR: Running exception handlers
  Running handlers complete
[2015-11-18T08:30:15-08:00] ERROR: Exception handlers complete
  Chef Client failed. 0 resources updated in 24 seconds
[2015-11-18T08:30:15-08:00] FATAL: Stacktrace dumped to c:/chef/cache/chef-stacktrace.out
[2015-11-18T08:30:15-08:00] FATAL: EOFError: end of file reached

C:\WINDOWS\system32>

and here's the stacktrace:
Generated at 2015-11-18 08:30:15 -0800
EOFError: end of file reached
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/protocol.rb:153:in `read_nonblock'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/protocol.rb:153:in `rbuf_fill'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/protocol.rb:134:in `readuntil'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/protocol.rb:144:in `readline'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/http/response.rb:39:in `read_status_line'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/http/response.rb:28:in `read_new'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/http.rb:1412:in `block in transport_request'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/http.rb:1409:in `catch'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/http.rb:1409:in `transport_request'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/http.rb:1382:in `request'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/http.rb:1375:in `block in request'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/http.rb:852:in `start'
C:/opscode/chef/embedded/lib/ruby/2.0.0/net/http.rb:1373:in `request'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/http/basic_client.rb:65:in `request'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/http.rb:264:in `block in send_http_request'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/http.rb:298:in `block in retrying_http_errors'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/http.rb:296:in `loop'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/http.rb:296:in `retrying_http_errors'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/http.rb:260:in `send_http_request'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/http.rb:170:in `streaming_request'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/rest.rb:180:in `streaming_request'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/rest.rb:118:in `get'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/cookbook/synchronizer.rb:277:in `download_file'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/cookbook/synchronizer.rb:254:in `sync_file'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/cookbook/synchronizer.rb:152:in `block (2 levels) in sync_cookbooks'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/util/threaded_job_queue.rb:52:in `call'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/util/threaded_job_queue.rb:52:in `block (3 levels) in process'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/util/threaded_job_queue.rb:50:in `loop'
C:/opscode/chef/embedded/lib/ruby/gems/2.0.0/gems/chef-12.5.1-universal-mingw32/lib/chef/util/threaded_job_queue.rb:50:in `block (2 levels) in process'

Does this mean there is some EOFError in protocol.rb ?
But that's part of the community cookbook, which I thought looked pretty solid.

A: When chef-client starts up, one of the things it has to do is download the cookbook code it is going to use for the run. This is cached locally to speed future runs, but the first time or when files change etc etc. This exception is saying that it is failing while trying to download the ewe-powershell cookbook from the server. This possibly means it was corrupted during the upload process. A quick first check would be to knife cookbook delete that one and re-upload it. If that fails I would start trying to figure out what file is failing to download. If you turn up Chef's log level (-l debug) you should see which URL it is trying to get, which will tell you which file is failing. With that in hand, try curl'ing it directly from Bookshelf (the service with Chef Server that handles file upload and download).

A: These are due to networking errors.  They're not client bugs, and cannot be fixed by deleting and reuploading cookbooks.
There's some information here in a gist I made:
https://gist.github.com/lamont-granquist/e25af8f50cb4ae4f8050
Also more information:
https://discourse.chef.io/t/eoferror-when-decrypting-data-bags/5716/2
https://github.com/chef/chef/issues/1881
EOFErrors have been tracked down to broken proxies, PMTU issues (VPNs or filtering ICMP dest unreachable), jumbo frames, buggy TCP offload in networking drivers/hardware, Xen bugs, etc.
You should be able to replicate the problem on the command line if you use large enough packets.  If your chef server is chef.example.com then you can send a large ping packet on windows with:
ping chef.example.com -f -l 9999

You can also send a large ping package or large GET request on unixes:
ping -s 9999 chef.example.com
curl http://chef.example.com/`printf '%*s' 9999 '' | tr ' ' 'a'`

Approaches like that can help replicate the issue completely outside of any chef-related software and show that its the network.  The ultimate fix will have to come from spending the time to debug the underlying network problem.  In this case, it sounds like the network magically fixed itself.
(and keep in mind by "the network" I include the host TCP stacks and network drivers on either end including any virtualization technology that network communication has to pass through--"the network" in the broadest sense possible...)


text:
Q: Using custom MembershipProvider and Roleprovider in IIS 7.0 I'm writing a ASP.NET MVC 3 web site. This is my custom MembershipProvider (only ValidateUser realized):
public class RFMMembershipProvider : MembershipProvider
{
    IUserService userService = new UserService();

    public override bool ValidateUser(string username, string password)
    {
        return password.GetHashCode().ToString() == userService.GetUser(username).Pass;
    }
...
}

and my Roleprovider (realized only GetRolesForUser)
public class RFMRoleProvider : RoleProvider
{
    IUserService userService = new UserService();

    public override string[] GetRolesForUser(string username)
    {
        return new string[] { userService.GetRolesForUser(username).Name };
    }
...
}

my web.config part
...
<system.web>

<roleManager enabled="true" defaultProvider="RFMRoleProvider">
  <providers>
    <clear/>
    <add name="RFMRoleProvider" type="RFMSite.WebUI.RFMRoleProvider, RFMSite"/>
  </providers>
</roleManager>

<membership defaultProvider="RFMMembershipProvider"
            >
  <providers>
    <clear/>
    <add name="RFMMembershipProvider"
         type="RFMSite.WebUI.RFMMembershipProvider, RFMSite"
         />
  </providers>
</membership>

<authentication mode="Forms" >
  <forms loginUrl="~/Account/LogOn" timeout="2880">
  </forms>
</authentication>

on LogOn action:
...
 if (Membership.ValidateUser(username, password))
            {
                FormsAuthentication.SetAuthCookie(username, true);
                return RedirectToAction("Files", "Admin");
            }
...
return View();

So the question is Why when I publish site on IIS 7.0 Membership.ValidateUser(username, password)
always returns false? It works NORMAL on local asp.net development server.
The connection with MSSQL Server is OK (I can get any data and display it when website deployed)? No exception happens, just always returns false...

A: Are you sure you're calling the exact same code locally and in production? I'm suspicious that your code will ever work except by accident.
Specifically, I doubt that String.GetHashCode() will ever return something that matches a password from your database, unless your users are in the habit of using long random numbers for their passwords. GetHashCode is for building hash tables, not for securing passwords. I think you are confusing it with HashPasswordForStoringInConfigFile, or something similar.
EDIT for clarity:
I don't know for sure that GetHashCode is your problem but I don't see anything else obviously wrong. It would be easy enough to test: log your hash codes to a log file, since they're temporary anyway (as you noted in the comment).
And yes, GetHashCode could easily change when you deployed; if you are running a different architecture, for example, or against a newer version of the Framework, the exact value that gets returned from GetHashCode can definitely be different.

A: Don't use GetHashCode for this purpose! Use MD5 or SHA1 security hashes which are always the same. GetHashCode can return different values between different versions of .NET framework. It also returns different values when used on 32-bit and 64-bit system.


text:
Q: MapController Alloc Init & ViewController alloc init Resulting in loop I Have a very long view controller.m which I'm trying to split into separate files to keep it organised.
I know I can create separate .m .h files and separate them but in doing so I am ending up in loops (which I Understand since the MapController.m is initialising the viewcontroller again causing viewDidLoad to be triggered and repeat.
I have a Map I want to create in my MapController.m
-(void)setMapSettings{
    NSLog(@"test");
    viewController = [[ViewController alloc] init];
    SKMapView *mapView = [[SKMapView alloc] initWithFrame:CGRectMake( 0.0f, 0.0f,  CGRectGetWidth(viewController.view.frame), CGRectGetHeight(viewController.view.frame) )];

}

I want to add the above SKMapView to a UIView called mapViewContainer in my viewController.h
ViewController.m:
- (void)viewDidLoad {
    mapsViewController = [[MapController alloc] init];
    [mapsViewController setMapSettings];
}

Doing this creates a loop resulting in a crash. I know the answer is probably dead simple and I'm just being stupid, but I've spent hours finding a solution and I can't figure it out. Any idea's how I'm suppose to be able to do the above without looping, and without initialising the map views I require all in the ViewController.m?

A: You say that you are splitting the view controller by taking out code from it, but as far as I understand this has resulted in creating a second viewcontroller (either this, or "MapController" isn't the right naming).
Anyways, as you already mentioned the crash is definitely caused by that alloc/init loop: you should reengineer your code to have just one of the two objects instantiating the other.
(please bear in mind that if you are doing that to access one object from the other, you're doing it wrong: alloc/init creates a new instance of that class every time it is called, it does not give you a pointer to an existing one)


text:
Q: how passing many inputs all at once use skfuzzy,python I create a fuzzy model to model student performance use library skfuzzy. my model model is only for one specific one input value enter image description here
and i need it for several
I implemented it as follows enter image description here
but i get the error enter image description here
the documentation says "use .inputs (dict_of_data)" to use, but I don't know how to implement it
please,help me


text:
Q: Nodejs Koa unable to get peer certificate from request I am using Koa@2.13.4 and I am unable to extract the client/peer certificate from the request. Express has a method on socket called getPeerCertificate(), but Koa doesn't have that. I need to extract data from the certificate.
I've tried the solution here: https://github.com/koajs/koa/issues/1519#issuecomment-769231704 but when I tried to add the middleware function is says Types of property 'socket' are incompatible.
interface IKoaContext extends Koa.Context {
  socket: TLSSocket,
}

function middleware (ctx: IKoaContext, next: Koa.Next) {
  ctx.socket.getPeerCertificate()
}

Any help appreciated.
Thanks


text:
Q: How to pass configuration from spark-submit to yarn cluster? I'm wondering is there any way for spark-submit to temporarily change yarn job's configuration?
The question is because our Spark over yarn cluster's history server only allows admin to access, which is not convenience for user to retrieve their own job's log. I learned "mapreduce.job.acl-view-job" in mapreduce-default.xml can changes specific job's ACL. As I'm using spark-submit to launch job, and "--conf" is reserved for spark itself's, but how can I set yarn's configuration from command line along with application?

A: You can modify Spark's Hadoop Configuration (obtained via SparkContaxt.hadoopConfiguration) by adding a --conf with a spark.hadoop. prefixed.
In you example it would be
spark-submit --conf spark.hadoop.mapreduce.job.acl-view-job=YOUR_ACL_STATEMENT ...


text:
Q: How to configure a site to automatically link domains Source:
https://developers.google.com/analytics/devguides/collection/gtagjs/cross-domain#configuring_a_site_to_accept_linker_parameters
Reference:
If the destination domain has been configured to automatically link domains, it will accept linker parameters by default.

I assume there is an HTML based solution for me to implement configuring a destination domain to automatically link domains.
How can I do this?

A: We have been using this approach. I'm not sure if it is correct, but it is an answer.
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-66686611-1', {
  'linker': {
    'domains': ['every.com','domain.com','that.com','I.com','will.com','link.com','to.com','or.com','from.com'],
    'accept_incoming': true,
    'decorate_forms': true
  },

});
</script>


text:
Q: HTML/CSS: how to put text both right and left aligned in a paragraph What would be the best code to have two bits of text in a single paragraph, one left aligned, the other right aligned, that also is:

*

*the least code as possible

*the easiest for clients to render (i.e. using least resources)

I add this last one to be sure

 would get ruled out. Not only is this a beast of code compared to a couple of properly styled
,  or
's,  it's also a beast if you know what a HTML render engine has to load and calculate to decide on the cell sizes before it even get's to painting text in them...
If you're not sure what I mean, here's an example: a page footer with left aligned the name of the user currently logged on, and on the same line right aligned the current date and time and/or website version.

A: The only half-way proper way to do this is

  Text on the right
  Text on the left

however, this will get you into trouble if the text overflows. If you can, use divs (block level elements) and give them a fixed width.
A table (or a number of divs with the according display: table / table-row / table-cell properties) would in fact be the safest solution for this - it will be impossible to break, even if you have lots of difficult content.

A: I wouldn't put it in the same
, since IMHO the two infos are semantically too different. If you must, I'd suggest this:

 I'll be on the left
 I'll be on the right

A: Least amount of markup possible (you only need one span):

This text is left. This text is right.

How you want to achieve the left/right styles is up to you, but I would recommend an external style on an ID or a class.
The full HTML:

This text is left. This text is right.

And the CSS:
.split-para      { display:block;margin:10px;}
.split-para span { display:block;float:right;width:50%;margin-left:10px;}

A:
If the texts has different sizes and they must be underlined this is the solution:

    January
    2014

css:
table{
    width: 100%;
    border-bottom: 2px solid black;
    /*this is the size of the small text's baseline over part  (≈25px*3/4)*/
    line-height: 19.5px;
}
table td{
    vertical-align: baseline;
}
.left{
    font-family: Arial;
    font-size: 40px;
    text-align: left;

}
.right{
    font-size: 25px;
    text-align: right;
}

demo here

A: I have used this in the past:
html
January2014

Css
.right {
    margin-left:100%;
}

Demonstration

A: Ok what you probably want will be provide to you by result of:

*

*in CSS:
div {
      column-count: 2;
    }

*in html:

 some text, bla bla bla

In CSS you make div to split your paragraph on to column, you can make them 3, 4...
If you want to have many differend paragraf like that, then put id or class in your div:


text:
Q: Is there anything like Unity for simple things that don't require an interface? Perhaps I'm misapplying Unity, but here goes.  I have a couple of applications, both of which load the same plugin assemblies.  All assemblies require a library, and I want them to be able to access this library via Unity.  However, in order to use Unity, or any other IoC framework, I'd have to write an interface for this library.  I will probably do this, but since an interface isn't really needed for anything other than to support Unity, I am afraid that this means that I am 1) missing the point, or 2) misapplying the framework.  If I avoid something that offers me DI, then I'd have to make the library class a singleton, and then pass it to all of the plugin constructors, or via a public property, and I don't want to do this.
That said, and without actually implementing anything with Unity yet, I'm not getting one other detail -- although Unity will let me request the library via Resolve<>, my plugins will still need to have a reference to the Unity instance that is created in the main applications.  So is this a case where your only option is to pass the Unity reference to all of the plugins, but then it's convenient from that point on, merely because you can use Unity to get at all of the other dependencies?
UPDATE
I realized that I missed the point, but hopefully someone can clarify for me -- I shouldn't be passing a ref to Unity everywhere!  I should only have to create the container in my app, and then register all of the types afterward.  Then when I instantiate all of my plugins, they should just magically be able to use those registered interfaces, with almost no extra effort, right?  In my case, my constructors must be parameterless because my plugin loader can't deal with arguments, and in that case, I'll have to use property injection to give them access to the interfaces, right?
ANOTHER UPDATE
I went ahead and tried out Unity.  I registered the instance of my class that's needed by all plugins.  I also know that I would eventually run into a problem with my plugin loader since they are parameterless (and I might need to pass it a ref to Unity to make them work).  However, just for now I am directly creating a plugin, and I am doing that via the Resolve method.  So here's basically what the code looks like:
// app code
ICandySettings _candy_settings = new CandySettings();
IUnityContainer unity = new UnityContainer().RegisterInstance<ICandySettings>( _candy_settings);
CandyPlugin _plugin = unity.Resolve<Candy>(); // throws null reference exception, see below.

// plugin code
public class Candy
{
  [Dependency]
  ICandySettings CandySettings { get; set; }

  ...

  public Candy()
  {
    CandySettings.GetSetting("box"); // CandySettings is null!  why?  Didn't Unity do this for me?
  }
}

So my problem right now is that I would expect (given my limited knowledge), that Unity is going to automagically set the plugin's CandySettings reference to whatever instance was registered via RegisterInstance, but it's not.
A WORKING OPTION
If I skip the smoke and mirrors stuff and just pass my UnityContainer into the plugin's constructor, then I can call Unity.Resolve() to set the value of my CandySettings property, and everything works great.  I'd love to know why the [Dependency] attribute isn't doing what I thought it would.  If I'm not mistaken, I actually shouldn't need to pass Unity to each constructor in my plugin loader.  I should just use Unity.Resolve() and it would presumably work if [Dependency] is working.  However, now I understand what everyone is saying about how picking an IoC container will then force it on your entire development team.
MEF!
So far, MEF is winning the battle for me.  It's pretty simple, and the magical smoke and mirrors stuff works great for my needs (currently).  But I'd still like to get Unity working.  I find it strange that for MEF, I only need to compose the parts and everything else just falls into place, whereas I can't seem to get Unity to just inject stuff automatically, and I have to Resolve everything through a reference to Unity passed everywhere.  This can't be right.
More MEF
I like the idea that I can resolve multiple objects with MEF very easily, but what about cases where I'm using the Strategy pattern to dictate code behavior?  Currently, it's as simple as changing the reference from one implementation of a behavior to another, and it just works.  Does anyone do this with MEF?  Is the right way to do it to use ImportMany, and then use extra code to determine which behavior in the list should get invoked?

A: If your dependency injection requirements are minor (which, from the sounds of it, they are), you might want to consider trying MEF.  This is lightweight and easy to use, and has the advantage of being in the framework directly in .NET 4, which means no extra requirements to deploy if you ever move to .NET 4.
In the interim, it's supported on 3.5 via the Codeplex site.
MEF is nice in this since it can work on any type, not just interfaces.
That being said, if you want plugins to use a "library" provided by your application, you're most likely going to always need that library to be available and referenced by your plugins (or at least a set of base classes or interfaces for the API).

A: Most IoC containers can map concrete classes as well as interfaces, it's just that using interfaces is considered by most to be a better practice as it relates to design and testing.
If all you want to do is allow provisioning of a few common types, you might want to roll your own using System.IServiceProvider. it's built-in so you wouldn't need to cascade your IoC dependencies to your consuming code.
public class SomePlugin
{
 public SomePlugin(IServiceProvider serviceProvider)
 {
  _foo = serviceProvider.GetService(typeof(IFoo)) as IFoo;
 }
}

Or you could have a singleton service locator as in the Common Service Locator library
public class SomePlugin
{
 public SomePlugin()
 {
  _foo = ServiceLocator.Current.GetService(typeof(IFoo)) as IFoo;
 }
}

EDIT: Given your updates, i'd suggest using BuildUp to inject property dependencies on your plugin instances after you've instantiated them. See this article
PluginInstance plugin = // already loaded from whatever you're already doing
container.BuildUp<PluginInstance>(plugin);

A: First, I have a singleton which holds a reference to my Unity container instance, so I don't have to pass it around everywhere.
Second, you are free to use unityContainer.RegisterInstance(myInstance); or unityContainer.RegisterType<MyClass, MyClass>();

A: The reason why Unity was not working properly in the posted example is that in
[Dependency]
ICandySettings CandySettings { get; set; }

the default accessibility is private.  Unity requires the property to be public (so it can call the setter).
In the latest version of Unity (the error message/behavior might have been different with an older version) using your posted code I get an exception: "The property CandySettings on type ConsoleApplication32.Candy is not settable."

However, now I understand what everyone is saying about how picking an
  IoC container will then force it on your entire development team.

Yes and no.  Obviously classes will need to be wired up so that dependencies are properly injected (hopefully in the Composition Root ).  However, the application code does not (or should not) reference the container (e.g. using DependencyAttribute or passing in IUnityContainer).  In the posted example this can be done by registering an InjectionProperty for the Candy class:
ICandySettings _candy_settings = new CandySettings();
IUnityContainer unity = new UnityContainer().RegisterInstance<ICandySettings>( _candy_settings);
unity.RegisterType<Candy>(new InjectionProperty("CandySettings"));
CandyPlugin _plugin = unity.Resolve<Candy>();

I (along with many others) also prefer injecting the dependencies in the Constructor (Constructor Injection) in which case Unity will just do the right thing and inject the dependency in the constructor:
public class Candy
{
    public ICandySettings CandySettings { get; private set; }

    ...

    public Candy(ICandySettings candySettings)
    {
        this.CandySettings = candySettings;
        this.CandySettings.GetSetting("box");
    }
}

The registration code would just be the same as in the original question:
ICandySettings _candy_settings = new CandySettings();
IUnityContainer unity = new UnityContainer().RegisterInstance<ICandySettings>(_candy_settings);

var _plugin = unity.Resolve<Candy>(); // Everything is OK :)


text: Q: List Chat messages for a user in MS Teams throws forbidden error - Graph Api I am using GraphAPI to list all the chats for a user in MS Teams using '/users/{Id}/chats' API. I have given Delegated permission type for both Chat.Read and Chat.ReadWrite. Still I am getting 403 forbidden error. Any help?


text:
Q: Two questions about Independence of two RVs (building understanding) Situation A:
You are a math teacher writing a word problem for a quiz. You start off by stating,

*

*$X \sim Uniform(0,1)$

*$Y \sim Uniform(1,2)$

*$X$ and $Y$ are dependent
My first question: Does the last bullet point above make any sense? I don't think so... if I was writing a quiz question I couldn't use all the above bullet points at the same time. My thinking is the distributions of $X$ and $Y$ are fully known and independent of eachother. Therefore $X$ and $Y$ can never be dependent.

Situation B:

*

*$X \sim Uniform(0,1)$

*$Y = X+1$

*Clearly $X$ and $Y$ are dependent since $X$ and $X+1$ are dependent.
My second question: What If I say, since $Y=X+1$ which means I fully know the unconditional distribution of $Y$ and that is $Y \sim Uniform(1,2)$, and therefore $X$ and $Y$ are independent. I know this isn't fair to say, because give you know $X$ that means you know $Y$, but what is wrong with the "fully know the distribution" argument above?
Thanks for your help and patience.

A: Comment: There are infinitely many joint distributions on
the rectangle with vertices at $(0,1)$ and $(1,2)$
that have your specified uniform marginal distributions, and yet
are not independent.
An important principle here is that it is impossible, in general, to find the joint distribution corresponding to two marginal distributions (without additional information). However, if you know the two
marginal distributions are independent, then
the joint distribution can be found by multiplication.
In the upper half of the plot below (based on a simulation for
convenience in plotting), I illustrate an example where independence fails. Your example with
$X \sim \mathsf{Unif}(0,1)$ and $Y = X+1$ has what is sometimes called a
'degenerate joint distribution' with all probability
on a line. It is illustrated at the bottom of the figure.
In both cases, $X$ and $Y$ cannot be independent because
$P(X < 1/2) = P(Y < 3/2) = 1/2,$ but
$P(X < 1/2,\,Y < 3/2) = 1/2 \ne 1/4.$

Note: The R code for making the figure is shown below
in case anyone is interested.
par(mfrow=c(2,3));  m = 50000

 x = runif(m, 0, 1);  v = runif(m, 1 ,1.5)
 y = v;  y[x>1/2] = v[x>1/2]+ .5
   plot(x,y, pch=".")
   hist(x, br=10, prob=T, col="skyblue2")
   hist(y, br=10, prob=T, col="skyblue2")

 x = runif(m, 0, 1);  y = x+1
   plot(x,y, pch=".")
   hist(x, br=10, prob=T, col="skyblue2")
   hist(y, br=10, prob=T, col="skyblue2")

par(mfrow=c(1,1))


text:
Q: How to override navigation options in functional component? To override navigation options using class components, it would be something like
export default class SomeClass extends Component {

    static navigationOptions = ({ navigation }) => {
        return {
            title: navigation.getParam('headerTitle'),
        }
    }

    componentDidMount() {
        this.props.navigation.setParams({ headerTitle: someVariableThatComesFromExternalCall })
    }

    ...
}

But how can I do this using functional component??
export default function SomeFunctionalCompoenent({ navigation }) {

    // How and Where do I change the header title ?

    useEffect(() => { navigation.setParams({ headerTitle: someVariableThatComesFromExternalCall })})
    return (
        ...
    )
}

A: You still need to define navigationOptions on your functional component. You do it like this:
export default function SomeFunctionalComponent({ navigation }) {
    useEffect(() => {
        navigation.setParams({
            headerTitle: someVariableThatComesFromExternalCall
        })
    }, [])
}

SomeFunctionalComponent.navigationOptions = ({ navigation }) => {
    return {
        title: navigation.getParam('headerTitle'),
    }
}

A: I've got a suspicion the accepted answer isn't for the currently latest version of react navigation (5), and it definitely doesn't work for this version, so here's a working example for @react-navigation/native v5.7.2 :
export default function SomeFunctionalComponent({ navigation }) {
  useLayoutEffect(() => {
    navigation.setOptions({
      headerTitle: 'some other title',
    })
  }, [])
}

I've used this to access react context - to get the user's name and avatar so I can set a nice title bar for them. I've pasted in the code for this in case it helps anyone:
import React, { useContext, useLayoutEffect } from 'react';
import UserContext from '../context/UserContext';

const HomeScreen = ({ navigation }) => {

  const userContext = useContext(UserContext);

  useLayoutEffect(() => {
    navigation.setOptions({
      title : userContext.name,
      headerLeft : () => (
        <TouchableOpacity
          onPress={() => {
            navigation.openDrawer();
          }}
        >
          <FastImage
            style={styles.userPhoto}
            resizeMode={FastImage.resizeMode.cover}
            source={{ uri: userContext.avatar }}
          />
        </TouchableOpacity>
      ),
    });
  }, [ userContext ]);

  return (
    // etc
  );
}


text:
Q: public Modbus server I've been programming a Modbus Client through TCP and I think I'm finally done but I'd like to test it in real life scenarios and that's why I'm coming here:
¿Is there any Modbus Server available online? I mean, any kind of modbus server even though it servers only trash bytes is OK.
¿Any ideas?

A: Well, you can use the Modbus Simulator from the following link.
http://www.plcsimulator.org/
It is free.
Other than that, you can also use Docklight.
Docklight is a more powerful simulator.
It can be used to simulate all sort of serial and TCP simulation.
http://docklight.de/

A: I'm not aware of any public servers. However, why don't you test your client against a local simulator, maybe this one? http://www.plcsimulator.org/Home


text:
Q: Code issue with AngularJS and JSON I have a JSON source and want to get results from it with a post request.
When I test with POSTMAN extension in chorme it works really well. But when I do that with angularJS the page keep loading and chrome consoles shows errors.
My code is here:
angular.module('loginApp', []).controller('loginController', function ($scope, $http) {
$scope.userName = '';
$scope.userPass = '';
$scope.output = function () {
    var params = JSON.stringify({
            username: '******',
            password: '******'
        });
    $http({url: "http://xx.xx.xx.xx/api/user/login.json",
        method: 'POST',
        data: params,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }).then(function (response) {
        return response;
    });
};
});

Any help would be appreciated :)

A: Try this:
$scope.output = function () {
    var params = {
      username: '******',
      password: '******'
    };

    $http.post("http://xx.xx.xx.xx/api/user/login.json", params)
      .then(function (response) {
        return response;
      });
};

Also you should move your http request to a service. It's a bad practice put it in a controller.

A: try this, and after post error if occured:
var LoginApp = angular.module('loginApp', []);
LoginApp.controller('loginController', function ($scope, $common) {
    $scope.userName = '';
    $scope.userPass = '';

    $scope.output = function () {
        var params = JSON.stringify({
            username: '******',
            password: '******'
        });

        $common.ajax("http://xx.xx.xx.xx/api/user/login.json", params, "POST").then(function (response) {
            console.log(response);
            return response;
        });
    };
});

LoginApp.factory("$common", function($http, $q) {
    function ajax(url, param, method) {
        var request = $http({
            method: method,
            url: url,
            data:param
        });

        var promise = request.then(
            function(response) {
                return(response.data);
            },
            function(response) {
                console.log("Ocurred error: " + response);
                return($q.reject("Something went wrong"));
            }
        );
        return promise;
    }
    return({
        ajax:ajax
    });
});


text:
Q: GRUB installation failed Xubuntu 20.04 My computer is an old Lenovo a57. It gives this error when I tried to install Xubuntu 20.04. I used manual partitioning during the installation to create /boot, swap, /home, and root / partitions, but it still gives an error. I  tried to install GRUB with a live CD with Boot-Repair, but it didn't work.
When I try to load the system the only thing that appears is a black screen with Read Error.

A: As the OS has likely been installed, the issue could be caused by one of three issues:

*

*The cable connecting the disk to the motherboard is loose

*The OS was installed for UEFI, but your system requires BIOS mode to boot

*The disk is failing

For the first item, check the cables. For the second, you'll want to reinstall and make sure it's done with a "Legacy Boot" setup. For the third, you will need to boot with a Live USB or DVD, open Terminal (Ctrl+Alt+T) and perform the following:

*

*If needs be, determine which device you've installed Ubuntu onto:
sudo fdisk -l

You will see something like /dev/sda1

*Check the disk for errors:
sudo fsck -f /dev/sda1

*Do the same for any other disks or partitions you may have.

*Once done, reboot.
So long as the disks are good, you should be able to boot. If you continue to see issues, the drive is likely bad.


text:
Q: how to get width and height of videoview after video added layout xml of videoview :
   <RelativeLayout
        android:id="@+id/videoEditorParent"
        android:layout_width="match_parent"
        android:layout_height="400dp">

        <RelativeLayout
            android:id="@+id/vidEditorWrapper"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:background="@color/colorAccent">

            <VideoView
                android:id="@+id/vidEditor"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

        </RelativeLayout>

    </RelativeLayout>

when i get height and width of video view it gives me match_parent's width and height, but not aspect ratio width and height of video is playing in videoview(whatever width and height is covered in videoview by video).
here, my code :
            viewWidth = vidEditor.getWidth();
            viewHeight = vidEditor.getHeight();

            ViewGroup.LayoutParams layoutParams = vidEditorWrapper.getLayoutParams();

            dpWidthView = utilities.pxToDp(viewWidth);
            dpHeightView = utilities.pxToDp(viewHeight);

            dpWidthViewPerVal = (dpWidthView * 2) / 100;

            layoutParams.width = viewWidth;
            layoutParams.height = viewHeight;
            vidEditorWrapper.setLayoutParams(layoutParams);

my screen shot :

i want width and height of black area that is video playing in videoview.
but getWidth() or getMeasuredWidth() and getHeight() or getMeasuredHeight() of videoview gives me match_parent width and height.
so, how can i get width and height of video area(only dark area that is visible to us in picture not full width) that is covered in videoview.

A: Try applying your code inside OnPreparedListener
For eg:
    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

        @Override
        public void onPrepared(MediaPlayer mp) {
            viewWidth = vidEditor.getWidth();
            viewHeight = vidEditor.getHeight();

            ViewGroup.LayoutParams layoutParams =
            vidEditorWrapper.getLayoutParams();

            dpWidthView = utilities.pxToDp(viewWidth);
            dpHeightView = utilities.pxToDp(viewHeight);

            dpWidthViewPerVal = (dpWidthView * 2) / 100;

            layoutParams.width = viewWidth;
            layoutParams.height = viewHeight;
            vidEditorWrapper.setLayoutParams(layoutParams);
        }
    });


text:
Q: How to integrate $\int \frac{\sin^2 x \cos^2 x}{(\sin^3 x+\cos^3 x)^2} \, dx$? How to find

$$\int \frac{\sin^2 x \cos^2 x}{(\sin^3 x+\cos^3 x)^2} \, dx.$$

I have tried but not been able to find a solution.
Thank you.

A: Hint:
$$\dfrac{\sin^2x\cos^2x}{(\sin^3x+\cos^3x)^2}=\dfrac{\sin^2x\cos^2x}{\cos^6x(\tan^3x+1)^2}=\dfrac{\tan^2x\sec^2x}{(\tan^3x+1)^2}$$
Set $\tan^3x+1=u$


text:
Q: xcode global nsmutablearray that keeps values Did a search but cant seem to find exactly what I'm looking for
Basically I load values into a nsmutablearray in one method and then I want to access these values in another method to print them to a table
I declared the array in the app.h
NSMutableArray *clients;
Then in the app.m
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
      [connection release];
      NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
      [responseData release];
      NSArray *results = [responseString JSONValue];
      clients = [[NSMutableArray alloc]init];

      // Loop through each entry and add clients to array
      for (NSDictionary *entry in results)
      {
           if (![clients containsObject:[entry objectForKey:@"client"]])
           {
                [clients addObject:[entry objectForKey:@"client"]];
           }
      }
}

Now Im try to acces the clients array in another method
I have seen some suggestions to use extern in the app.h? Some sort of global variable?
Any help would be appreciated
Thanks

A: Take the clients array in app delegate class.declare the property,synthesizes in the app delegate class.Then in the below method write like this.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
      [connection release];

YourApplicationDelegate *delegate = [UIApplication sharedApplication]delegate];
  NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  [responseData release];
  NSArray *results = [responseString JSONValue];

      clients = [[NSMutableArray alloc]init];

      // Loop through each entry and add clients to array
      for (NSDictionary *entry in results)
      {
           if (![clients containsObject:[entry objectForKey:@"client"]])
           {
                [delegate.clients addObject:[entry objectForKey:@"client"]];
           }
      }

}

after that suppose you if you want to use the clients array in another class do like this.
YourApplicationDelegate *delegate = [UIApplication sharedApplication]delegate];
NSLog(@"client array is %@",delegate.clients);


text:
Q: log4j debug message configuration I am able to use my Logger with the simple call:
logger.debug("blablablalbal");

It is also configured by an xml file and writes into a txt.
Problem is:
Sometimes i am looping over int values in a large array and therefore the output becomes extremely long in terms of lines used.
For Example:
for(int i = 0; i < largeArray.length; i++){
    logger.debug(largeArray[i])
}

I know that i could use:
for(int i = 0; i < largeArray.length; i++){
    System.out.print(largeArray[i])
}

But i want to have everything together and utilize the logger for this task. Does someone know how to "imitate" System.out.print() with log4j?

A: Use Arrays.toString() (Java 5 or above)
logger.debug(Arrays.toString(largeArray));
for(int i = 0; i < largeArray.length; i++){
    ...
}


text:
Q: Why does a null value automatically get converted into empty string when using string.Join? I have a JArray that contains null values. And while I'm doing string.Join, null values are getting converted into empty string.
Original array values:
[
  null,
  null,
  "America/Boise",
  false,
  "2021-02-04T06:51:33.9686227Z"
]

String.Join:
var val = $"('{string.Join("','", valuesArray)}')";

Current Result:
"('','','America/Boise','False','2/4/2021 6:51:33 AM')"

Expected Result:
"(null,null,'America/Boise',False,'2/4/2021 6:51:33 AM')"

Producing Example:
https://dotnetfiddle.net/5nRTyL
How do I get the expected result using string.Join?

A: Because that's how it was designed. See the documentation for String.Join:

If separator is null, an empty string (String.Empty) is used instead. If any element in value is null, an empty string is used instead.

A: null values in a JArray are stored as JTokens with a JTokenType of Null.  So you'll need to check for this and convert them to the string "null".  Secondly, since you only want to quote some of the values, you should not put the quotes in the separator value when you join them, but instead only quote the values that need it based on their types.
Define the following helper function:
string TokenToString(JToken token)
{
    switch (token.Type)
    {
        case JTokenType.Null:
            return "null";
        case JTokenType.Date:
        case JTokenType.String:
            return $"'{token}'";
        default:
            return token.ToString();
    }
}

Then you can get the result you want like this:
string val = $"({string.Join(",", valuesArray.Select(v => TokenToString(v)))})";

Working demo here: https://dotnetfiddle.net/Q62Uck

A: just replace "''" to "null".
var val = $"('{string.Join("','", valuesArray)}')".Replace("''", "null");


text:
Q: Searching by text with Mechanize/Nogokiri I'm trying to scrape some data on average GPA and more from a lot of pages similar to this one:
http://www.ptcas.org/ptcas/public/Listing.aspx?seqn=3200&navid=10737426783
require 'mechanize'

agent = Mechanize.new
page = agent.get('http://www.ptcas.org/ptcas/public/Listing.aspx?seqn=3200&navid=10737426783')
gpa_headers = page.xpath('//h3[contains(text(), "GPA")]')
pp gpa_headers

My issue is that gpa_headers is nil but there is at least one h3 element containing "GPA".
What could be causing this issue? I thought it may be that since the page has dynamic elements that Mechanize had some issue with that yet I can puts page.body and the output includes:
...
GPA REQUIREMENT
 ...

Which, by my understanding should be found with the xpath I used.
If there is a better approach to this I would like to know that too.

A: This looks to be a problem with the DOM structure of the site, as it contains a tag named style which isn't being closed and looks like this:


text:
Q: When does prime elements remain prime in certain integral extension Let $R$ be an integral domain and $\bar R$ denote its integral closure in the fraction field (i.e. normalization). If $p\in R$ is a prime element in $R$, then does $p$ remain prime in $\bar R$ also ?
If this is not true in general, then what if we also assume $R$ is Noetherian ?
By a prime element in an integral domain $R$, I mean a non-zero non unit $p\in R$ such that $p |ab $ for some $a,b \in R$ implies $p|a$ or $p|b$ i.e. if $pR$ is a prime ideal in $R$ . I can see that $p$ still remains a non-unit in $\bar R$ , but I'm unable to say anything about the ideal $p\bar R$.
UPDATE : The claim is true for any Noetherian domain. This is Lemma 4.7 in ; On finite generation of $R$-subalgebras of $R[X]$ , Amartya K. Dutta; Nobuharu Onoda; Journal of Algebra 320 (2008) 57- 80. On finite generation of R-subalgebras of R[X] - ScienceDirect
https://www.sciencedirect.com › pii

A: This is true when $R$ is reasonable. The properties that I use are:

*

*$R$ is Noetherian;

*$\tilde R$ is Noetherian;

*$\tilde R$ is catenary and equidimensional (i.e. every maximal chain $0 = \mathfrak q_0 \subsetneq \ldots \subsetneq \mathfrak q_d$ of prime ideals in $\tilde R$ has the same length).

For example, these are all satisfied if $R$ is of finite type over a field or over $\mathbb Z$. It might be possible to weaken some of these hypotheses.
Lemma. Let $f\colon R \to S$ be an integral ring map, let $\mathfrak q \subseteq S$ be a prime, and let $\mathfrak p = f^{-1}(\mathfrak q)$. Then
$$\dim R/\mathfrak p = \dim S/\mathfrak q.$$
Proof. This is poset-theoretic, using only the going up theorem for integral maps [AM, Thm. 5.11]. Indeed, the going up theorem implies that a chain $\mathfrak p = \mathfrak p_0 \subsetneq \mathfrak p_1 \subsetneq \ldots$ of primes of $R$ containing $\mathfrak p$ can be lifted to some chain $\mathfrak q = \mathfrak q_0 \subsetneq \mathfrak q_1 \subsetneq \ldots$ of $S$, whence $\dim S/\mathfrak q \geq \dim R/\mathfrak p$.
Conversely, if $\mathfrak q_1 \subseteq \mathfrak q_2$ are primes of $S$ with $f^{-1}(\mathfrak q_1) = f^{-1}(\mathfrak q_2) = \mathfrak p$, then we must have $\mathfrak q_1 = \mathfrak q_2$. Indeed, they correspond to primes in the integral ring map $\kappa(\mathfrak p) \to S \otimes_R \kappa(\mathfrak p)$, and there are no inclusions between prime ideals of $S \otimes_R \kappa(\mathfrak p)$ [Tag 00GS(3)]. Hence, the inverse image of a chain $\mathfrak q = \mathfrak q_0 \subsetneq \mathfrak q_1 \subsetneq \ldots$ of primes of $S$ containing $\mathfrak q$ is a strict chain $\mathfrak p = \mathfrak p_0 \subsetneq \mathfrak p_1 \subsetneq \ldots$ of primes of $R$ containing $\mathfrak p$, whence $\dim R/\mathfrak p \geq \dim S/\mathfrak q$. $\square$
Remark. In the proof below, we want to relate the heights of $\mathfrak q$ and $\mathfrak p$ as in the lemma. We can do this under assumption (3), for this forces $\operatorname{ht}(\mathfrak p) = \dim R - \dim R/\mathfrak p$ (and similarly for $\mathfrak q$).

Proposition. Let $R$ be a domain satisfying properties (1)-(3) above. If $p \in R$ is a prime element, then $p$ is a prime element in $\tilde R$.

Proof. By assumption, $\mathfrak p = (p)$ is a prime ideal. By Krull's Hauptidealsatz [AM, Cor. 11.17], this implies that $\mathfrak p$ has height $1$, i.e. $R_\mathfrak p$ is a $1$-dimensional domain. Since its maximal ideal $\mathfrak pR_\mathfrak p$ is principal, we conclude that $R_\mathfrak p$ is a DVR [AM, Prop. 9.2] with uniformiser $p$; in particular $R_\mathfrak p$ is normal.
On the other hand, normalisation commutes with localisation [AM, Prop. 5.12]. Thus,
$$(\tilde R)_\mathfrak p = (R_\mathfrak p)^\sim = R_\mathfrak p,$$
since $R_\mathfrak p$ is normal. That is, the natural map $R \to \tilde R$ becomes an isomorphism when tensoring with $R_\mathfrak p$, hence also when tensoring with $\kappa(\mathfrak p) = R_\mathfrak p/\mathfrak pR_\mathfrak p$. The primes of $\tilde R \otimes_R \kappa(\mathfrak p)$ are the primes of $\tilde R$ lying over $\mathfrak p$ [AM, Exc. 3.21(iv)], so we conclude that there is a unique such prime $\mathfrak q$. Note that $\mathfrak q$ is minimal over $\mathfrak p\tilde R$, hence has height $1$ by Krull's Hauptidealsatz.
If $\mathfrak r \subseteq \tilde R$ is another height $1$ prime, then $p \not\in \mathfrak r$. Indeed, if $p \in \mathfrak r$, then $\mathfrak p' = \mathfrak r \cap R$ contains $\mathfrak p$. Applying the lemma and the remark above, we conclude that $\operatorname{ht}(\mathfrak p') = \operatorname{ht}(\mathfrak r) = 1$. Hence $\mathfrak p' = \mathfrak p$ since $\mathfrak p \subseteq \mathfrak p'$ and both have height $1$.
Hence, for a height $1$ prime $\mathfrak r \subseteq \tilde R$, we have
$$v_{\mathfrak r}(p) = \left\{\begin{array}{cc} 1, & \mathfrak r = \mathfrak q,\\ 0, & \mathfrak r \neq \mathfrak q, \end{array}\right.$$
since $p$ is a uniformiser of the DVR $\tilde R_\mathfrak q \cong R_\mathfrak p$. If $q \in \mathfrak q$, then $v_\mathfrak r(q) \geq v_\mathfrak r(p)$ for all height $1$ primes $\mathfrak r \subseteq \tilde R$. Hence, $\frac{q}{p} \in \tilde R$ [Eis, Cor. 11.4], which shows that $\mathfrak q \subseteq (p)$. The reverse inclusion follows since $\mathfrak q \cap R = \mathfrak p$, hence $(p) = \mathfrak q$ is prime. $\square$
Remark. In geometric language, we proved:

*

*There is a unique irreducible divisor $V(\mathfrak q) \subseteq \operatorname{Spec} \tilde R$ dominating the irreducible divisor $V(\mathfrak p) \subseteq \operatorname{Spec} R$;

*The locus $V(p) \subseteq \operatorname{Spec} \tilde R$ does not split off a new component of higher codimension;

*The uniformiser $p$ for the divisor $V(\mathfrak p) \subseteq \operatorname{Spec} R$ remains a uniformiser for $V(\mathfrak q) \subseteq \operatorname{Spec} \tilde R$ (there is no ramification).

References.
[AM] Atiyah, M.F.; Macdonald, I.G., Introduction to commutative algebra. Addison-Wesley Publishing Company (1969). ZBL0175.03601.
[Eis] Eisenbud, D., Commutative algebra with a view toward algebraic geometry. Graduate Texts in Mathematics 150, Springer-Verlag (1995). ZBL0819.13001.