text:
Q: SharePoint 2007 Trim Permissions Looked through a number of threads as well as searched the web for an answer without much luck.
We currently allow users to request a work site and then when we create their site, we add them to a special group called "Leaders". We give them Manage Hierarchy permission by default and want them to be able to add new users to their work site. However, we don't want them or other users outside of the Owners group to be able to add users with Full Control. Is it possible to trim the add users/assign permissions layout so that only users which are in the Owners group can add users with Full Control?

A: Try this.  Don't give them the manage hierarchy permission.  Instead, make the "leaders" group the owner of the Visitors, Contributors, etc. groups (or create new ones)... only groups that have permission levels that you want the leaders to be able to assign.  The "leaders" should then be able to give other users the appropriate access to the site by just adding them to one of the groups, but they won't be able to give them individual permissions or put users in groups they don't own.


text:
Q: find first element in array for which block returns true and return the block's return value I need to iterate over an array and apply a supplied block to each element, and return the first true value returned by the block, which implies that I need to stop immediately as soon as I get a true value.
below is my code. I am a ruby newbie, and I am not sure if this code is reinventing the wheel. Maybe there is a library method or methods that can do that already? or may be this code can be simplified?
RS = {
  :x => %w(\d+ a\d+ bb\d+ ccc\d+).map{|x| /^#{x}$/},
  :y => %w(\w+ 1\w+ 22\w+ 333\w+).map{|x| /^#{x}$/}
}.freeze

def find s, t
  r = RS[s]
  if r
    r.each do |p|
      m = p.match t
      return m if m
    end
    nil
  end
end

p find :x, 'bb12345'

A: If you want the result of the block you could do it this way. This will iterate over the whole array, but wont evaluate any matches after the first one.
def find(s,t)
  RS[s].inject(nil) {|m, p| m || p.match(t)}
end

You can break out early doing something like this
RS[s].inject(nil) {|m, p| (m && (break m)) || p.match(t)}

A: This is duplicated with: Ruby - Array.find, but return the value the block
You want a lazy map:
[nil, 1, 2, 3].lazy.map{|i| i && i.to_s}.find{|i| i}
# => "1"

A: Hopefully still actual: here a solution using detect, i made it possible to verbose the output so you can see which expressions are evaluated before returning a hit.
def find_match symbol, string , verbose = false, match = nil
  if verbose
    RS.detect{|x,v|x==symbol;v.detect{|re|puts re;match=string.match(/#{re}/)}}
  else
    RS.detect{|x,v|x==symbol;v.detect{|re|match=string.match(/#{re}/)}}
  end
  match
end

p find_match :x, 'bb12345'
p find_match :x, 'ee12345' , true #verbose output
p find_match :x, '12345'
p find_match :y, '22abcd'

#<MatchData "bb12345">
(?-mix:^\d+$)
(?-mix:^a\d+$)
(?-mix:^bb\d+$)
(?-mix:^ccc\d+$)
(?-mix:^\w+$)
#<MatchData "ee12345">
#<MatchData "12345">
#<MatchData "22abcd">

A: If your regex patterns are simple, you can just apply the regex again at the end, maybe.
Something like:
def find(s,t)
  r = RS[s] and r.find{|p| p.match(t)}.try(:match, t)
end

Although it makes one redundant call to match, it is easier to understand.
First, find the pattern you want, then use that pattern.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use sympy.Poly on scipy.interpolate.CubicSpline? from scipy.interpolate import CubicSpline
from sympy import Symbol, Poly

xpts = np.linspace(0, 1)
cs = CubicSpline(xpts, np.exp(xpts))
Poly(cs)

How to get the polynomial expression of scipy.interpolate.CubicSpline using sympy.Poly?

A: The cubic spline is made of many different polynomials. You can get their coefficients with the .c attribute:
In [33]: cs.c.shape
Out[33]: (4, 49)

This is an array of 4 rows and 49 columns. Each column gives the coefficients of one polynomial:
In [35]: cs.c[:,0]
Out[35]: array([0.17111101, 0.49985044, 1.00000156, 1.        ])

This represents a polynomial and can be converted to a SymPy polynomial as:
In [41]: x = Symbol('x')

In [42]: Poly(cs.c[:,0], x)
Out[42]: Poly(0.171111008723916*x**3 + 0.499850444583089*x**2 + 1.00000155672475*x + 1.0, x, domain='RR')

This plot shows that this polynomial closely follows the exponential curve near to x=0:
In [40]: plot(Poly(cs.c[:,0], x).as_expr(), exp(x))

That's the first polynomial but there are 48 others which you can get using an index other than 0. The coefficients are the coefficients for a polynomial centred at the origin so shifting is needed to get the right coefficients:
In [46]: plot(Poly(cs.c[:,48], x).as_expr().subs(x, x-xpts[-1]), exp(x))


text:
Q: Failure to change ruby text's font via field codes I run the below macro code that is capable of adding phonetic pinyin to all the selected Chinese text at once. However, that code can only add the ruby text using default settings for font and I need to modify the the font, positioning, and font size of the pinyin.
https://github.com/wuzhuoqing/alltextphonetic/blob/master/alltext.bas
At first, I tried to toggle the field codes to change the settings, and it worked. However, when I saved, exit, and re-opened it, only positioning and font size remained changed, the font was the same before I make changes via field codes.
For example, the original font of the ruby text is Times New Roman. I will change it into "DengXian" by toggling field codes. Then, the ruby text's font will be changed. However, once I save and reopen the document, the ruby text's font reverts back to "Times New Roman" instead of "DengXian".
Is there any solutions to it? Or, is it possible to make adjustments on the macro code so that it can abandon the ruby text's default settings and adopt my own?  By the way, I am tired of using only Phonetic Guide because It would cost me much of time (The document contains more than 10000 words!)
Thank you!

A: Try to use the Document.Save method to make your changes permanent. The following example saves the active document if it has changed since it was last saved:
If ActiveDocument.Saved = False Then ActiveDocument.Save

A: The short answer is that if you apply DengXian font to all the Ruby Text in the EQ fields, Word should get it right.
e.g. if your field looks like this after you have modified the \* "Font:Times New Roman" to \* "Font:DengXian"
{ EQ \* jc2 \* "Font:DengXian" \* hps11 \o\ad(\s\up 10(běn),本}

if you check the font of běn in the field code itself (not the field result) it will probably be Times New Roman. If you manually apply DengXian to běn, then save your document as .docx and re-open it, I think you will get the result you want.
You should be able to apply the correct font to all the ruby texts using an Advanced Find/Replace or maybe VBA if necessary, but longer term I think you need to try to ensure that Word is using the correct font in the first place, and that probably requires you to modify one or more Styles in the document. Right now, I can't tell you how to do that without further investigation of exactly which settings Word uses for that  (by default, on my installation it uses DengXIan anyway for the ruby text).
As background...
When you modify the fontname in the \* "Font:fontname" switch in the EQ field, Word applies the font to the ruby text in the field result, but it does not apply the font to the ruby text in the field code. So in your case, that remains as Times New Roman.
If you save your document in the old .doc format, the field code is saved "as is". When you close and re-open, Word still has field, can still see the font you specified in \* "Font:fontname" and re-applies it to the field result.
But when you save in .docx format, Word does not actually save the field code at all. It translates it into WordProcessingML. At best, it records the font that has actually been applied to the ruby text in the field code. If you didn't actually apply any direct formatting to the ruby text, Word may decide that it has applied one of its Theme styles and record the font something like this (I am simplifying):
<w:rFonts w:asciiTheme="majorBidi">

At that point, it has forgotten that you specified \* "Font:DengXian". When you re-open the document, Word recreates the field, get the font from asciiTheme and generates `* "Font:Times New Roman" instead.
If you actually applied direct formatting to the ruby text, then Word seems to record the font name, more like this:
<w:rFonts w:ascii="DengXian">

Word has still forgotten that you specified \* "Font:DengXian", but gets the font name from the w:rFonts element and recreates  \* "Font:DengXian"


text:
Q: Error: Cannot find module '@package/utils' Nx Monorepo I am having issues importing a function out of a shared lib inside an Nx Monorepo.
This repo consists of a Nextjs web app, React Native mobile app and an Express server.
Both front-end applications import the functions from the util lib fine but for some reason, I get Error: Cannot find module '@package/utils'. The TS configs are similar on all projects. I am wondering if it's the way babel compiles the front end apps vs me just starting the node server but any assistance to help me understand would be appreciated.
API tsconfig compiler options
  "compilerOptions": {
    "allowJs": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "incremental": true,
    "types": [
      "express",
      "node"
    ]
  },

Web tsconfig compiler options
  "compilerOptions": {
    "jsx": "preserve",
    "allowJs": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "incremental": true,
    "types": [
      "jest",
      "node"
    ]
  },


text:
Q: Eclipse CDT build error: make not in path I just recently(actually today) started using Eclipse CDT for windows. Created a project, a test C file(Hello World) added to project. Build the project, I got error as below.
Error: Program make is not found in Path -

So then I read that Eclipse CDT needs Mingw/MSYS, which I did install. Now i See that there is make.exe in
C:\MinGW\msys\1.0\bin

But Since I dont have administrator privileges, I could not add this folder containing make to the Path system variable on Windows. (I am not likely to get administrator privileges)
Now how do I work around this error to build and use CDT on windows? Any Project settings for Eclipse CDT which if added the path to make could help resolve this?

A: Was able to get a fix around this problem.
Added the correct paths for two exes - make and gcc/g++ (installed by Mingw/Ansys) to the User environment variable Path (Was not allowed to edit System variable Path).
But adding these paths to User environment variable Path also helped to resolve this. Now Eclipse CDT built and executed the code fine.

A: *

*check environment variable path has c:/cygwin/bin or c:/mingw/bin or wherever u installed it

*if makefile name is mingw32-make.exe or something else , make a copy and rename that to make.exe

A: The problem is simply that your IDE need to know  where is  the place of GNU Binary Utilities so  how to deal with that simple go to
Windows -> preference -> C/C++ -> new c++ project wizerd   -> makefile

then chose what are u instal for example I use MinGW  so now I will chose GUN elf parse  and now I need the location  for c++ filt  :D

you will go to place where u install minGW in default it will be C:\MinGW

and search for  c++ filt.exe :D and  now u done :D
and you can install minGW from
http://www.mingw.org/

A: Also after adding C:\MinGW\bin to PATH variable. Make sure your new project is created with MinGW GCC toolchain as shown below.


text:
Q: Load one file into another file I have one file called index.html and I have 2 more files whose contents I would like to load in the div of index.html using js.
index.html

.load_content_div{
  height:300px;
  width:300px;
  border:thin black solid;
}

Some Content

  about us

  contact us

about.html
About Us Data
contact.html
Contact Us Data
How can I do this using only javascript?

A: Execute AJAX calls from the main page to the other pages, and then in the return of those AJAX calls set the innerHTML of the desired elements equal to the returned content.


text:
Q: Rails 3 ActiveAdmin. Hiding buttons according to CanCan permissions I have ActiveAdmin and CanCan working together. I already set the administrator and customer permissions.
Now I want to hide the New, Edit and Delete buttons according to the permissions set by CanCan but the following line gives me errors...
config.clear_action_items! :if => proc{can? (:destroy, Shipment)}

This one too
:if => proc{ can?(:destroy, Shipment)}, actions :all, :except => [:new, :create, :update, :edit, :destroy]

A: I use this monkey patch to check permissions before displaying buttons
module ActiveAdmin
  class Resource
    module ActionItems

      # Adds the default action items to each resource
      def add_default_action_items
        # New Link on all actions except :new and :show
        add_action_item :except => [:new] do
          if controller.action_methods.include?('new') and can? :create, active_admin_config.resource_class
            link_to(I18n.t('active_admin.new_model', :model => ''), new_resource_path,
             :class => "new-link"
            )
          end
        end

        # Edit link on show
        add_action_item :only => :show do
          if controller.action_methods.include?('edit') and can? :update, active_admin_config.resource_class

             link_to(I18n.t('active_admin.edit_model', :model => ''), edit_resource_path(resource),
             :class => "edit-link"
            )

          end
        end

        # Destroy link on show
        add_action_item :only => :show do
          if controller.action_methods.include?("destroy") and can? :destroy, active_admin_config.resource_class

             link_to(I18n.t('active_admin.delete_model', :model => ''),
              resource_path(resource),
               :class => "delete-link" ,
              :method => :delete, :data => {:confirm => I18n.t('active_admin.delete_confirmation')})

          end
        end
      end
    end
  end
end


text:
Q: Convert Classic ASP if statement to PHP Am new to php and was wondering if anyone could help me convert a classic asp if statement into php:
<img src="<%If rsRecordset.Fields.Item("image1").Value <> "" then response.write
(replace(rsRecordset.Fields.Item("image1").Value,".jpg","_small.jpg"))Else response.write
("images/NoPic.jpg")End if%>" width="50" height="40" border="0">

php line is like this at the moment:
<img src="<?php echo $row_rsAdminMenu['image1']; ?>">

Any help would be much appreciated
Frank

A: <?php
if ($row_rsAdminMenu['image1']) {
    $src = $row_rsAdminMenu['image1'];
    $src = str_replace('.jpg', '_small.jpg', $src);
} else {
    $src = 'images/NoPic.jpg';
}
echo '';


text:
Q: HTML5 FileReader output to D3.js chart I'm trying to use a local CSV file to populate my D3.js pie chart. The CSV file simply consists of
label,count
Monday,379130
Tuesday,424923
Wednesday,430728
Thursday,432138
Friday,428295
Saturday,368239
Sunday,282701

The d3.js chart is the simple pie chart explained here at ZeroViscosity:
http://zeroviscosity.com/d3-js-step-by-step/step-4-loading-external-data
So far I have,

 (function(d3) {
   ...
<input type="file" id="file_input" accept=".csv"/>

I'm not sure how to get the data and then pass this on to the chart. How would I set this up?

A: Use file API to load the file as data URL. See tutorial. Then, it can used like before d3.csv(url, ...):

function handleFileSelect(evt) {
  var file = evt.target.files[0];
  var reader = new FileReader();
  reader.onload = (function(theFile) {
    return function(e) {
      drawChart(e.target.result);
    };
  })(file);

  reader.readAsDataURL(file);
}

document.getElementById('file_input').addEventListener('change', handleFileSelect, false);

function drawChart(url) {
  var width = 360;
  var height = 360;
  var radius = Math.min(width, height) / 2;
  var donutWidth = 75;
  var legendRectSize = 18;
  var legendSpacing = 4;
  var color = d3.scale.category20b();
  var svg = d3.select('#chart')
    .append('svg')
    .attr('width', width)
    .attr('height', height)
    .append('g')
    .attr('transform', 'translate(' + (width / 2) +
      ',' + (height / 2) + ')');

  var arc = d3.svg.arc()
    .innerRadius(radius - donutWidth)
    .outerRadius(radius);

  var pie = d3.layout.pie()
    .value(function(d) {
      return d.count;
    })
    .sort(null);

  d3.csv(url, function(error, dataset) { // NEW
    dataset.forEach(function(d) { // NEW
      d.count = +d.count; // NEW
    }); // NEW
    var path = svg.selectAll('path')
      .data(pie(dataset))
      .enter()
      .append('path')
      .attr('d', arc)
      .attr('fill', function(d, i) {
        return color(d.data.label);
      });

    var legend = svg.selectAll('.legend')
      .data(color.domain())
      .enter()
      .append('g')
      .attr('class', 'legend')
      .attr('transform', function(d, i) {
        var height = legendRectSize + legendSpacing;
        var offset = height * color.domain().length / 2;
        var horz = -2 * legendRectSize;
        var vert = i * height - offset;
        return 'translate(' + horz + ',' + vert + ')';
      });
    legend.append('rect')
      .attr('width', legendRectSize)
      .attr('height', legendRectSize)
      .style('fill', color)
      .style('stroke', color);

    legend.append('text')
      .attr('x', legendRectSize + legendSpacing)
      .attr('y', legendRectSize - legendSpacing)
      .text(function(d) {
        return d;
      });
  });
}
<input type="file" id="file_input" accept=".csv" />


text:
Q: Can I use NPAPI plugin to filter HTTP Is it possible to use a NPAPI plugin to filter HTTP traffic in modern browsers (namely firefox and chrome)? I was able to build a simple plugin and register it with FF and Chrome.
Is there any way to use it for low level HTTP filtering? I couldn't find any useful information on the net about this.

A: No. NPAPI plugins don't affect the browser or browser stack; they affect the handling of a specific mimetype or they affect a specific page into which they are inserted as an object tag.
see http://npapi.com/extensions


text:
Q: Regular Expressions for ASTM Protocol String What can be the Regular Expression for ASTM Standard protocol String?
"P|1||123456||^|||U" + ProtocolASCII.LF
   + "O|1||138||||||||||||O" + ProtocolASCII.LF
   + "R|1|^^^BE(B)||mmol/L||C||||||20150819144937" + ProtocolASCII.LF
   + "R|2|^^^BEecf||mmol/L||C" + ProtocolASCII.LF
   + "R|3|^^^Ca++|1.17|mmol/L" + ProtocolASCII.LF

Where ProtocolASCII.LF = '\n'. I am writing String parser to extract data from this String.
I have splited String based on \n and now I need to parse each String to extract data.
Is there any Regular Expression so that I can map to and get desired result?
The String P|1||123456||^|||U" + ProtocolASCII.LF present patient number where P means patient tag or patient information and 123456 is patient number.
For String R|3|^^^Ca++|1.17|mmol/L" + ProtocolASCII.LF is the result of laboratory test performed. Where R indicated result, ^^^Ca++ indicates name of the result, 1.17 is result value and mmol/L is unit.
Currently I am parsing String like:
String[] resultArray = dataString.split("[\\r\\n]+");

    HashMap<String, Object> resultData = new HashMap<>();
    List<Result> sampleResults = new ArrayList<>();

    for (String res : resultArray) {
        //Get first character of String
        char startChar = res.charAt(0);
        switch (startChar) {
            case ProtocolASCII.STX:
                //Handle Header information. This is special case
                if (res.charAt(2) == ProtocolASCII.Alphabet.H
                        || res.charAt(1) == ProtocolASCII.Alphabet.H) {
                    resultData.put(Key.MACHINE_INFO, getHeaderInfo(res));
                    //System.out.println(res.charAt(2));
                }
                break;
            case ProtocolASCII.Alphabet.P:
                resultData.put(Key.PATIENT, getPatientInfo(res));
                break;
            case ProtocolASCII.Alphabet.O:
                resultData.put(Key.ORDER, getOrderInfo(res));
                break;
            case ProtocolASCII.Alphabet.R:
                sampleResults.add(getResultInfo(res));
                break;
            case ProtocolASCII.Alphabet.L:
                // TODO - Handle end of line
                break;
        }
    }

This is my complete ASTM Protocol String:
/**
 * Sample string
 */
public static final String MACHINE_STRING_ASTM = ProtocolASCII.STX + "1H|\\^&|||GEM 3000^5.6.1     ^21152^^023665^2.4|||||||||20150819154754" + ProtocolASCII.LF
        + "P|1||322061||^|||U" + ProtocolASCII.LF
        + "O|1||138||||||||||||O" + ProtocolASCII.LF
        + "R|1|^^^BE(B)||mmol/L||C||||||20150819144937" + ProtocolASCII.LF
        + "R|2|^^^BEecf||mmol/L||C" + ProtocolASCII.LF
        + "R|3|^^^Ca++|1.17|mmol/L" + ProtocolASCII.LF
        + "R|4|^^^Ca++(7.4)||mmol/L||C" + ProtocolASCII.LF
        + "R|5|^^^HCO23-||mmol/L||C" + ProtocolASCII.LF
        + "R|6|^^^HCO3std||mmol/L||C" + ProtocolASCII.LF
        + "R|7|^^^K+|5.0|mmol/L" + ProtocolASCII.LF
        + "R|8|^^^Na+|140|mmol/L" + ProtocolASCII.LF
        + "R|9|^^^SO2c||%||C" + ProtocolASCII.LF
        + "R|10|^^^TCO2||mmol/L||C" + ProtocolASCII.LF
        + "R|11|^^^THbc||g/dL||C" + ProtocolASCII.LF
        + "R|12|^^^Temp|37.0|C" + ProtocolASCII.LF
        + "L|1" + ProtocolASCII.EOT;

Is there a way I can extract data using Regular Expressions?
Let me know if further information is required.
Thanks

A: You can try this for R and P:
(?:^(R)\|(\d+)\|\^*([^|]*)\|([^|]*)\|(?:([^|]*)\|)?.*$)|(?:^(P)\|(\d+)\|\|(\d+).*$)

Explanation
Try this:
final String regex = "(?:^(R)\\|(\\d+)\\|\\^*([^|]*)\\|([^|]*)\\|(?:([^|]*)\\|)?.*$)|(?:^(P)\\|(\\d+)\\|\\|(\\d+).*$)";
final String string = "P|1||322061||^|||U \n"
     + "O|1||138||||||||||||O \n"
     + "R|1|^^^BE(B)||mmol/L||C||||||20150819144937 \n"
     + "R|2|^^^BEecf||mmol/L||C \n"
     + "R|3|^^^Ca++|1.17|mmol/L \n"
     + "R|4|^^^Ca++(7.4)||mmol/L||C \n"
     + "R|5|^^^HCO23-||mmol/L||C \n"
     + "R|6|^^^HCO3std||mmol/L||C \n"
     + "R|7|^^^K+|5.0|mmol/L \n"
     + "R|8|^^^Na+|140|mmol/L \n"
     + "R|9|^^^SO2c||%||C \n"
     + "R|10|^^^TCO2||mmol/L||C \n"
     + "R|11|^^^THbc||g/dL||C \n"
     + "R|12|^^^Temp|37.0|C\n";

final Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    //System.out.println("Full match: " + matcher.group(0));

    if(matcher.group(1)!=null && matcher.group(1).equalsIgnoreCase("R"))
    {
        System.out.println("Result NO:"+matcher.group(2));
        System.out.println("Component:"+matcher.group(3));
        System.out.println("value:"+matcher.group(4));
        System.out.println("unit:"+matcher.group(5));

        System.out.println("##############################");
    }
    else if(matcher.group(6)!=null && matcher.group(6).equalsIgnoreCase("P"))
    {
        System.out.println("Patient :"+matcher.group(7));
        System.out.println("Patient Number:"+matcher.group(8));

        System.out.println("##############################");
    }
}

Sample Output:
Patient :1
Patient Number:322061
##############################
Result NO:1
Component:BE(B)
value:
unit:mmol/L
##############################
Result NO:2
Component:BEecf
value:
unit:mmol/L
##############################
Result NO:3
Component:Ca++
value:1.17
unit:mmol/L
R
##############################
Result NO:5
Component:HCO23-
value:
unit:mmol/L
##############################
Result NO:6
Component:HCO3std
value:
unit:mmol/L
##############################
Result NO:7
Component:K+
value:5.0
unit:mmol/L
R
##############################
Result NO:9
Component:SO2c
value:
unit:%
##############################
Result NO:10
Component:TCO2
value:
unit:mmol/L
##############################
Result NO:11
Component:THbc
value:
unit:g/dL
##############################
Result NO:12
Component:Temp
value:37.0
unit:null
##############################


text:
Q: How to make expandable tree in d3.js vertical? I'm trying to implement an expandable and collapsible tree using d3.js.
But it seems like not working.
Can someone suggest how to fix this?
I mean I'm not being able to expand and toggle it like this demo.
Following is my implementation in vue.js:

var app = new Vue({
  el: '#app',
  mounted() {
    var treeData = {
      name: "Top Level",
      children: [{
          name: "Level 2: A",
          children: [{
              name: "Son of A",
            },
            {
              name: "Daughter of A",
            },
          ],
        },
        {
          name: "Level 2: B",
        },
      ],
    };

    // Set the dimensions and margins of the diagram
    var margin = {
        top: 0,
        right: 90,
        bottom: 30,
        left: 90,
      },
      width = 960 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;

    // append the svg object to the body of the page
    // appends a 'group' element to 'svg'
    // moves the 'group' element to the top left margin
    var svg = d3
      .select("#tree-graph")
      .append("svg")
      .attr("width", width + margin.right + margin.left)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var i = 0,
      duration = 750,
      root;

    // declares a tree layout and assigns the size
    var treemap = d3.tree().size([height, width]);

    // Assigns parent, children, height, depth
    root = d3.hierarchy(treeData, function(d) {
      return d.children;
    });
    root.x0 = height / 2;
    root.y0 = 0;

    // Collapse after the second level
    //root.children.forEach(collapse);

    update(root);

    // Collapse the node and all it's children
    function collapse(d) {
      if (d.children) {
        d._children = d.children;
        d._children.forEach(collapse);
        d.children = null;
      }
    }

    function update(source) {
      // Assigns the x and y position for the nodes
      var treeData = treemap(root);

      // Compute the new tree layout.
      var nodes = treeData.descendants(),
        links = treeData.descendants().slice(1);

      // Normalize for fixed-depth.
      nodes.forEach(function(d) {
        d.y = d.depth * 180;
      });

      // ****************** Nodes section ***************************

      // Update the nodes...
      var node = svg.selectAll("g.node").data(nodes, function(d) {
        return d.id || (d.id = ++i);
      });

      // Enter any new modes at the parent's previous position.
      var nodeEnter = node
        .enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", function(e, d) {
          return "translate(" + source.x0 + "," + source.y0 + ")";
        })
        .on("click", click);

      // Add Circle for the nodes
      nodeEnter
        .append("circle")
        .attr("class", "node")
        .attr("r", 1e-6)
        .style("fill", function(d) {
          return d._children ? "lightsteelblue" : "#fff";
        });

      // Add labels for the nodes
      nodeEnter
        .append("text")
        .attr("dy", ".35em")
        .attr("x", function(d) {
          return d.children || d._children ? -13 : 13;
        })
        .attr("text-anchor", function(d) {
          return d.children || d._children ? "end" : "start";
        })
        .text(function(d) {
          return d.data.name;
        });

      // UPDATE
      var nodeUpdate = nodeEnter.merge(node);

      // Transition to the proper position for the node
      nodeUpdate
        .transition()
        .duration(duration)
        .attr("transform", function(d) {
          return "translate(" + d.x + "," + d.y + ")";
        });

      // Update the node attributes and style
      nodeUpdate
        .select("circle.node")
        .attr("r", 10)
        .style("fill", function(d) {
          return d._children ? "lightsteelblue" : "#fff";
        })
        .attr("cursor", "pointer");

      // Remove any exiting nodes
      var nodeExit = node
        .exit()
        .transition()
        .duration(duration)
        .attr("transform", function(d) {
          return "translate(" + source.y + "," + source.x + ")";
        })
        .remove();

      // On exit reduce the node circles size to 0
      nodeExit.select("circle").attr("r", 1e-6);

      // On exit reduce the opacity of text labels
      nodeExit.select("text").style("fill-opacity", 1e-6);

      // ****************** links section ***************************

      // Update the links...
      var link = svg.selectAll("path.link").data(links, function(d) {
        return d.id;
      });

      // Enter any new links at the parent's previous position.
      var linkEnter = link
        .enter()
        .insert("path", "g")
        .attr("class", "link")
        .attr("d", function(d) {
          var o = {
            x: source.x0,
            y: source.y0,
          };
          return diagonal(o, o);
        });

      link
        .enter()
        .insert("text", "g")
        .attr("font-family", "Arial, Helvetica, sans-serif")
        .attr("fill", "Orange")
        .style("font", "normal 12px Arial")
        .attr("transform", function(d) {
          return (
            "translate(" +
            (d.parent.y + d.x) / 2 +
            "," +
            (d.parent.x + d.y) / 2 +
            ")"
          );
        })
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .text(function(d) {
          return d.data.name;
        });

      // UPDATE
      var linkUpdate = linkEnter.merge(link);

      // Transition back to the parent element position
      linkUpdate
        .transition()
        .duration(duration)
        .attr("d", function(d) {
          return diagonal(d, d.parent);
        });

      // Remove any exiting links
      var linkExit = link
        .exit()
        .transition()
        .duration(duration)
        .attr("d", function(d) {
          var o = {
            x: source.x,
            y: source.y,
          };
          return diagonal(o, o);
        })
        .remove();

      // Store the old positions for transition.
      nodes.forEach(function(d) {
        d.x0 = d.x;
        d.y0 = d.y;
      });

      // Creates a curved (diagonal) path from parent to the child nodes
      function diagonal(s, d) {
        let path = `M ${s.y} ${s.x}
    C ${(s.y + d.x) / 2} ${s.x},
      ${(s.y + d.x) / 2} ${d.x},
      ${d.x} ${d.y}`;

        return path;
      }

      // Toggle children on click.
      function click(e, d) {
        if (d.children) {
          d._children = d.children;
          d.children = null;
        } else {
          d.children = d._children;
          d._children = null;
        }
        update(d);
      }
    }
  }
})
.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 3px;
}

.node text {
  font: 12px sans-serif;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 2px;
}

A: All I did was flip the coordinates in the diagonal function from
function diagonal(s, d) {
  let path = `M ${s.y} ${s.x}
    C ${(s.y + d.y) / 2} ${s.x},
      ${(s.y + d.y) / 2} ${d.x},
      ${d.y} ${d.x}`;
  return path;
}

to
function diagonal(s, d) {
  let path = `M ${s.x} ${s.y}
    C ${(s.x + d.x) / 2} ${s.y},
      ${(s.x + d.x) / 2} ${d.y},
      ${d.x} ${d.y}`;
  return path;
}

Now, the links come out of the side. That is because the example uses the average x of the source s and destination d. To make the links come out of and go into the top and bottom of the nodes, use the following instead:
function diagonal(s, d) {
  let path = `M ${s.x} ${s.y}
    C ${s.x} ${(s.y + d.y) / 2},
      ${d.x} ${(s.y + d.y) / 2},
      ${d.x} ${d.y}`;
  return path;
}

And for the labels, you changed (d.parent.y + d.y) / 2 to (d.parent.y + d.x) / 2, but you also need to change which coordinate you take from the parent.

var app = new Vue({
  el: '#app',
  mounted() {
    var treeData = {
      name: "Top Level",
      children: [{
          name: "Level 2: A",
          children: [{
              name: "Son of A",
            },
            {
              name: "Daughter of A",
            },
          ],
        },
        {
          name: "Level 2: B",
        },
      ],
    };

    // Set the dimensions and margins of the diagram
    var margin = {
        top: 0,
        right: 90,
        bottom: 30,
        left: 90,
      },
      width = 960 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;

    // append the svg object to the body of the page
    // appends a 'group' element to 'svg'
    // moves the 'group' element to the top left margin
    var svg = d3
      .select("#tree-graph")
      .append("svg")
      .attr("width", width + margin.right + margin.left)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var i = 0,
      duration = 750,
      root;

    // declares a tree layout and assigns the size
    var treemap = d3.tree().size([width, height]);

    // Assigns parent, children, height, depth
    root = d3.hierarchy(treeData, function(d) {
      return d.children;
    });
    root.x0 = height / 2;
    root.y0 = 0;

    update(root);

    // Collapse the node and all it's children
    function collapse(d) {
      if (d.children) {
        d._children = d.children;
        d._children.forEach(collapse);
        d.children = null;
      }
    }

    function update(source) {
      // Assigns the x and y position for the nodes
      var treeData = treemap(root);

      // Compute the new tree layout.
      var nodes = treeData.descendants(),
        links = treeData.descendants().slice(1);

      // Normalize for fixed-depth.
      nodes.forEach(function(d) {
        d.y = d.depth * 180;
      });

      // ****************** Nodes section ***************************

      // Update the nodes...
      var node = svg.selectAll("g.node").data(nodes, function(d) {
        return d.id || (d.id = ++i);
      });

      // Enter any new modes at the parent's previous position.
      var nodeEnter = node
        .enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", function(e, d) {
          return "translate(" + source.x0 + "," + source.y0 + ")";
        })
        .on("click", click);

      // Add Circle for the nodes
      nodeEnter
        .append("circle")
        .attr("class", "node")
        .attr("r", 1e-6)
        .style("fill", function(d) {
          return d._children ? "lightsteelblue" : "#fff";
        });

      // Add labels for the nodes
      nodeEnter
        .append("text")
        .attr("dy", ".35em")
        .attr("x", function(d) {
          return d.children || d._children ? -13 : 13;
        })
        .attr("text-anchor", function(d) {
          return d.children || d._children ? "end" : "start";
        })
        .text(function(d) {
          return d.data.name;
        });

      // UPDATE
      var nodeUpdate = nodeEnter.merge(node);

      // Transition to the proper position for the node
      nodeUpdate
        .transition()
        .duration(duration)
        .attr("transform", function(d) {
          return "translate(" + d.x + "," + d.y + ")";
        });

      // Update the node attributes and style
      nodeUpdate
        .select("circle.node")
        .attr("r", 10)
        .style("fill", function(d) {
          return d._children ? "lightsteelblue" : "#fff";
        })
        .attr("cursor", "pointer");

      // Remove any exiting nodes
      var nodeExit = node
        .exit()
        .transition()
        .duration(duration)
        .attr("transform", function(d) {
          return "translate(" + source.x + "," + source.y + ")";
        })
        .remove();

      // On exit reduce the node circles size to 0
      nodeExit.select("circle").attr("r", 1e-6);

      // On exit reduce the opacity of text labels
      nodeExit.select("text").style("fill-opacity", 1e-6);

      // ****************** links section ***************************

      // Update the links...
      var link = svg.selectAll("path.link").data(links, function(d) {
        return d.id;
      });

      // Enter any new links at the parent's previous position.
      var linkEnter = link
        .enter()
        .insert("path", "g")
        .attr("class", "link")
        .attr("d", function(d) {
          var o = {
            x: source.x0,
            y: source.y0,
          };
          return diagonal(o, o);
        });

      link
        .enter()
        .insert("text", "g")
        .attr("font-family", "Arial, Helvetica, sans-serif")
        .attr("fill", "Orange")
        .style("font", "normal 12px Arial")
        .attr("transform", function(d) {
          return (
            "translate(" +
            (d.parent.x + d.x) / 2 +
            "," +
            (d.parent.y + d.y) / 2 +
            ")"
          );
        })
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .text(function(d) {
          return d.data.name;
        });

      // UPDATE
      var linkUpdate = linkEnter.merge(link);

      // Transition back to the parent element position
      linkUpdate
        .transition()
        .duration(duration)
        .attr("d", function(d) {
          return diagonal(d, d.parent);
        });

      // Remove any exiting links
      var linkExit = link
        .exit()
        .transition()
        .duration(duration)
        .attr("d", function(d) {
          var o = {
            x: source.x,
            y: source.y,
          };
          return diagonal(o, o);
        })
        .remove();

      // Store the old positions for transition.
      nodes.forEach(function(d) {
        d.x0 = d.x;
        d.y0 = d.y;
      });

      // Creates a curved (diagonal) path from parent to the child nodes
      function diagonal(s, d) {
        let path = `M ${s.x} ${s.y}
    C ${(s.x + d.x) / 2} ${s.y},
      ${(s.x + d.x) / 2} ${d.y},
      ${d.x} ${d.y}`;

        return path;
      }

      // Toggle children on click.
      function click(e, d) {
        if (d.children) {
          d._children = d.children;
          d.children = null;
        } else {
          d.children = d._children;
          d._children = null;
        }
        update(d);
      }
    }
  }
})
.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 3px;
}

.node text {
  font: 12px sans-serif;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 2px;
}


text:
Q: Extender la columnas de una BD con registros Teniendo en cuenta que las cosas cambian conforme pasa el tiempo, una de las dudas más grandes que recorre mi cabeza en este momento es: qué debería hacer si deseo cambiar la lógica de mi negocio para guardar más información sobre una entidad especifica, ya que esta deberá ser persistida y ya existen registros posteriores: ¿Qué sucede con los registros ya existentes?
La todos los nuevos campos deberán permitir null para que los registros anteriores no rompan la bd?
Y algo más controversial: que hay si necesito eliminar una de las columnas? Debo ir directamente a la base de datos, antes de hacer deploy de las nuevas características, y ejecutar una query que elimite todos esos registros para no causar problemas?

A: Es común que sistemas que ya están en producción sufran de actualizaciones, tanto por mejoras/evolución del software mismo, como por cambios en el funcionamiento de las empresas/industrias y el marco legal que las regula.
Con esto, las estructuras de base de datos evolucionan también. La manera de actualizar/evolucionar una estructura de base de datos varía según el motor de base de datos y las herramientas que estén a tu disposición.
Si hablamos de bases de datos relacionales, más allá de los mecanismos utilizados, al final, será sentencias DDL las que cambien las estructuras.
Cuando se crean columnas nuevas, se pueden tomar varias estrategias:

*

*Crear las columnas nullable, de manera que no haya conflicto con registros que ya existan en la base de datos.

*Crear columnas nuevas con un valor default y el atributo not null establecido.

*Crear columnas nuevas como nullable, luego realizar alguna sentencia para derivar el valor que deben tener y posteriormente cambiar la definición de la columna como not null.

Como parte de la evolución, también es común que se creen tablas nuevas, se eliminen columnas que ya son obsoletas en el nuevo modelo y se eliminen también tablas por la misma razón.
Acá también se verán casos donde, luego de crear una tabla nueva, se voltea información desde una tabla existente para llenarla y luego se elimina la tabla existente. Esto es común cuando la estructura ha sufrido procesos de re-ingeniería.
Dependiendo de las capacidades del motor de base de datos, estas operaciones podrían llevarse a cabo en el contexto de una transacción, con lo cual, si algo falla durante la evolución de las estructuras, aplicas un rollback y dejas todo como si nada hubiese pasado.
Si el motor no lo permite, la única manera de ir a la segura es realizar una copia o copia de seguridad y si algo falla, restaurar desde la copia.


text:
Q: change tracking implementation I have an application that needs to identify what has changed on a table. Change Tracking will be suitable for my needs, but I have an assumption that I need to test (with you guys!).
I think I need to persist the last version of the changes I have obtained 'somewhere' in my application. Is this correct?How can i save it?
I will then use this in the next sync call to CHANGETABLE( ......, @last_sync_version) to obtain all the changes that have occured since I last synced.


text:
Q: How do I correctly write distance?
Possible Duplicate:
When is it appropriate to use non-breaking spaces?

If I am writing "I ran X distance", should I leave a space between the value and abbreviated distance, or is it more appropriate to bunch them together:
a) "I ran 5km"
b) "I ran 5 km"

A: The convention in technical contexts may be different, but my own practice it so to insert a space after the numeral, and show that it's plural: I ran 5 kms.


text:
Q: Calculating maximum area of trapezoid With a $40\mathrm{m}$ long fence, it is desired to create a trapezoidal region with a base wall. What is the largest area that can be created? How can I calculate this question?
I've tried all $3$ sides of trapezoid $\frac{40}3$ and creating $3$ triangles. And that : For only $3$ sides from $40\mathrm{m}$:
Let the top side opposite the wall be $x\mathrm{m}$. The other two sides are therefore $\frac{40 - x}2$. The area, $A$, of the trapezoid is therefore $x\frac{40 - x}2 = 20x - \frac{x^2}2$. After that derivatives and etc... But i'm not sure.  (isosceles trapezoid)

A: Knowing that the region to be enclosed must be a trapezoid, this means the middle segment must be parallel to the existing wall.  Since the formula for the area of a trapezoid is $$A = \frac{h}{2}(b_1 + b_2),$$ this means that if the bases are constant and the height is constant, the area is the same even if the location of the two bases are are "shifted" relative to each other.  So for a trapezoid of given fixed area, the one that minimizes the perimeter is the one that has the lateral sides, which we will call $l_1$ and $l_2$, equal--that is to say, the trapezoid is isosceles.  When we reverse this reasoning, it follows that for a fixed length of fencing, we only ever need to consider dividing the fencing into three lengths, say $x, y, z$, such that $x = z$, since any other choice with $x \ne z$ yields a trapezoid with inferior area.  Since $x + y + z = 40$, this gives us a second constraint, so that there is one free variable to consider, say $y$, that uniquely determines how the fence is cut.
However, for a given partitioning of the fencing, there are numerous ways to place it against the wall to enclose a trapezoidal area.  At one extreme, we can simply lay it flat against the wall and enclose no area.  At the other, we can put the ends of the fence as close to each other as possible along the wall, which, depending on whether $2x < y$, might enclose no area, or a triangular area.  This suggests letting the angle $\theta$ be the internal angle between the wall and one of the lateral sides.  We have the base $b_2 = y$, the two lateral sides $x = (40 - y)/2$, and we need to solve for the height $h$ and wall-side base $b_1$ for a given angle $\theta$.
Trigonometry gives us $$\sin \theta = \frac{h}{x}, \\ b_1 = b_2 + 2 x \cos \theta.$$  So the area as a function of $y$ and $\theta$ is $$A(y, \theta) = \frac{40-y}{2} \sin \theta \left(y + \frac{40-y}{2} \cos \theta\right).$$
Now I leave the rest as an exercise to compute the values of $y, \theta$ such that $A$ is maximized.


text:
Q: Как удалить класс у всех элементов через refs У каждого блока есть кнопка при нажатии на которую добавляеться этому блоку класс sticky, когда я нажимаю на кнопку с другого блока я хочу полностью удалить у всех блоков класс sticky. Я делаю через ref чтобы добавить класс но проблема что когда я хочу удалить у всех элементов ничего не происходит в чём может быть проблема?
<div v-for="(item, index) in items" :key="index" :ref="`block-${index}`">
 <button @click="removeClass(index)>click</button>

methods: {
 removeClass(index) {
   this.items.forEach((item, ind) => {
      this.$refs[`block-${ind}`].classList.remove('sticky');
   });
   this.$refs[`block-${index}`][0].classList.add('sticky');
 }
}

A: Если я правильно понял ту задачу, которыю Вы решаете, то у Вас не правильный подход к ее решению.
Ниже пример изменения класса элемента по клику

const app = new Vue({
  el: "#app",
  data() {
    return {
      activeIndex: 0,
    }
  },
});
#app {
  width: 500px;
  border: 1px solid;
}

.block {
  height: 40px;
  margin: 10px 0;
  cursor: pointer;
  border: 1px solid;
}

.block.active {
  background-color: red;
}

Click


text:
Q: AFNetworking request log Chrome gives a granular breakdown of the request lifecycle for a single resource.
The lifecycle shows how much time is spent in the following categories:

*

*Queuing

*Stalled

*Request sent

*Waiting (Time to first byte (TTFB))

*Content Download
I was wondering does AFNetworking give us the ability to captures these categories?
I tried digging but there's not much info about these.
Although I have calculated the complete duration of request hit to response got time, but how could we make use of such granular breakdown through AFNetworking in order to improve our app performance.


text:
Q: Correctly release resources after flipping a bitmap I have an application that writes a very large data set as a bitmap. [~500MB] I am writing the data patch wise from top to down. Due to the nature of BMP's file structure it must be flipped once written to the disk. (I wrote it this way because I assumed that flipping a bitmap would be a common application and I would find libraries to do the task)
I am using a code snippet I found on the internet to flip the bitmap. This one:
// GetInvertedBitmap    - Creates a new bitmap with the inverted image
// Returns      - Handle to a new bitmap with inverted image
// hBitmap      - Bitmap to invert
// bLateral     - Flag to indicate whether to invert laterally or vertically

HBITMAP CRisatImport::GetInvertedBitmap( HBITMAP hBitmap, BOOL bLateral )
{
    // Create a memory DC compatible with the display
    CDC sourceDC, destDC;
    sourceDC.CreateCompatibleDC( NULL );
    destDC.CreateCompatibleDC( NULL );
    // Get logical coordinates
    BITMAP bm;
    ::GetObject( hBitmap, sizeof( bm ), &bm );
    // Create a bitmap to hold the result
    HBITMAP hbmResult = ::CreateCompatibleBitmap(CClientDC(NULL),
                        bm.bmWidth, bm.bmHeight);
    // Select bitmaps into the DCs
    HBITMAP hbmOldSource = (HBITMAP)::SelectObject( sourceDC.m_hDC, hBitmap );
    HBITMAP hbmOldDest = (HBITMAP)::SelectObject( destDC.m_hDC, hbmResult );
    if( bLateral )
        destDC.StretchBlt( 0, 0, bm.bmWidth, bm.bmHeight, &sourceDC,
                bm.bmWidth-1, 0, -bm.bmWidth, bm.bmHeight, SRCCOPY );
    else
        destDC.StretchBlt( 0, 0, bm.bmWidth, bm.bmHeight, &sourceDC,
                0, bm.bmHeight-1, bm.bmWidth, -bm.bmHeight, SRCCOPY );
    // Reselect the old bitmaps
    ::SelectObject( sourceDC.m_hDC, hbmOldSource );
    ::SelectObject( destDC.m_hDC, hbmOldDest );
    return hbmResult;
}

The problem is that I have a limited understanding of the above code. I tried to write a function to use the above snippet the best I could from sample code from MSDN. I do not think I am releasing all resources correctly. And I cant seem to figure out the error - mainly because my lack of knowledge about GDI. I would really appreciate it if some one pointed out what I am doing wrong.
The program crashes if I try to call this function twice - that is why I suspect that I am releasing resources incorrectly.
This is the function I wrote:
void CRisatImport::flipBitMapSaveAsJPG( CString outputFileName, CString outputJPGName, bool saveAsJpg)
{
    // Flip the bitmap to correct odd file structure
        HBITMAP hBitmap;
        hBitmap = (HBITMAP)::LoadImage(NULL, outputFileName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
        hBitmap = GetInvertedBitmap( hBitmap, FALSE );
        CImage image;
        image.Attach(hBitmap);

        image.Save(outputFileName,Gdiplus::ImageFormatBMP);
        if(saveAsJpg){
        image.Save(outputJPGName,Gdiplus::ImageFormatJPEG);
        }

             image.Destroy();

        DeleteObject( hBitmap );
}

I am using MFC and VS2010 for this application - I have 4GB of RAM and no other applications running.
This is the error I get:

A: When you Attach your bitmap handle to CImage you're handing over responsibility for the handle's lifetime to CImage so you don't want to Destory it after. But you're also using the same variable name for your new bitmap. Try this instead:
void CRisatImport::flipBitMapSaveAsJPG( CString outputFileName, CString outputJPGName, bool saveAsJpg)
{
    // Flip the bitmap to correct odd file structure
        HBITMAP hBitmapLoad = (HBITMAP)::LoadImage(NULL, outputFileName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
        HBITMAP hBitmapInverted = GetInvertedBitmap( hBitmapLoad , FALSE );
        DeleteObject( hBitmapLoad );

        CImage image;
        image.Attach(hBitmapInverted );

        image.Save(outputFileName,Gdiplus::ImageFormatBMP);
        if(saveAsJpg){
            image.Save(outputJPGName,Gdiplus::ImageFormatJPEG);
        }

        image.Destroy();

}


text:
Q: how we can edit css for adaptive card? Azure Bot Framework V4 , nodejs, botbuilder-feedback i have used the adaptive card for feedback response using azure bot framework v4. Code has been developed using nodejs.
Module: botbuilder-feedback, now how to style those yes/ no buttons

Now can anybody help me out on how to change the css adaptive card, as also for feedback actions.
how to disable submit button after feedback has been given once.


text:
Q: Trouble using Jackson annotations I'm writing a java EE application using JPA. For convenient JSON output I need some specific Jackson annotations. However, none of the Jackson annotations I'm trying seems to work. I guess I'm doing something wrong in my project configuration. I simply added the three packages jackson-annotations-2.2.3.jar, jackson-databind-2.2.3.jar and jackson-core-2.2.3.jar tot the build path. The code does compile and the annotations are recognized, but they do not work.
My ApplicationConfig file looks as follows:
@javax.ws.rs.ApplicationPath("/")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
        try {
            Class jsonProvider = Class.forName("org.glassfish.jersey.jackson.JacksonFeature");
            resources.add(jsonProvider);
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        addRestResourceClasses(resources);
        return resources;
    }

    private void addRestResourceClasses(Set<Class<?>> resources) {
        // Many resources added here
    }
}

What am I doing wrong?

A: Try using version 1.9, it has a different package name. Aparently Glassfish 3 an 4 include this version of Jackson. I had a similar problem with JBoss AS 7.1.
If your project uses maven you can add this to your pom.
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.13</version>
</dependency>

Or you can download the jar from here.


text:
Q: H2O h2o.importFile Error: 'Cannot determine file type. for nfs://.../model.zip', caused by water.parser.ParseDataset$H2OParse I am trying to import a h2o model as a .zip file exporter as POJO with R. The following error is all I get:
model_file <- "/Users/bernardo/Desktop/DRF_1_AutoML_20190816_133251.zip"
m <- h2o.importFile(model_file)

Error: DistributedException from localhost/127.0.0.1:54321: 'Cannot determine file type. for nfs://Users/bernardo/Desktop/DRF_1_AutoML_20190816_133251.zip', caused by water.parser.ParseDataset$H2OParseException: Cannot determine file type. for nfs://Users/bernardo/Desktop/DRF_1_AutoML_20190816_133251.zip

I already ran file.exists(model_file) and that returns TRUE, so the file exists. Did the same with normalizePath(model_file) and same result. When I try to import it into my R session, it seems that h2o finds the file but can't import it for some reason.
Here's my R Session info:
R version 3.6.0 (2019-04-26)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.6

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] h2o_3.26.0.2      lares_4.7         data.table_1.12.2 lubridate_1.7.4   forcats_0.4.0
 [6] stringr_1.4.0     dplyr_0.8.3       purrr_0.3.2       readr_1.3.1       tidyr_0.8.3
[11] tibble_2.1.3      ggplot2_3.2.1     tidyverse_1.2.1

Hope you guys can help me import my POJO model into R. Thanks!

A: h2o models are not zip files. Try this
# path to your file
model_file <- "/Users/bernardo/Desktop/DRF_1_AutoML_20190816_133251.zip"

# prediction based on your mojo/pojo file.
preds = h2o.mojo_predict_df(df, model_file, genmodel_jar_path = NULL, classpath = NULL, java_options = NULL, verbose = F)

If they are zipped, then unzip and run them again. More info is here http://docs.h2o.ai/h2o/latest-stable/h2o-docs/save-and-load-model.html
https://rdrr.io/cran/h2o/man/h2o.mojo_predict_df.html

A: Ok, I actually found the solution I needed. The trick is to convert your dataframe (df) to json format, and then use the .zip file generated with h2o to predict using the h2o.predict_json instead of h2o.mojo_predict_df. I think it's pretty straight forward and less complicated. At least it worked as I needed it to work.
library(jsonlite)
library(h2o)
json <- toJSON(df)
output <- h2o.predict_json(zip_directory, json)

NOTE: No need to unzip the zip file.
If by any chance you've used the lares package, simply use the h2o_predict_MOJO function.
Hope it helps any other people trying to achieve the same result.


text:
Q: How do I re-enable an sudo lecture, once it's been seen I have sudo set to show the usual lecture on its first use by a user. Without thinking, I accidentally triggered its display for a new user as I was setting them up, and now it's been shown, they won't get to see it again.
How does sudo know that a user has invoked it once before? I'd like to reset that so that this user will see the message first time they use it. I don't want to set it so that the lecture appears on every invocation - once is enough - I'd just like sudo to forget that it's already been shown once.
Any ideas how I do that?

A: On Debian, a user's first use of sudo will create a directory under /var/run/sudo/.  The directory is named "username", where "username" is the name of the user which ran sudo.
Removing [or renaming] this directory will cause the lecture to be displayed upon next use of sudo, as well as recreate the directory.
For example, the directory for my user account would be /var/run/sudo/jscott.


text:
Q: How to navigate to new widget as a child in widget tree in Flutter In the example below when I push new MaterialPageRoute "Child" it is created on the same level as MyApp widget in the Flutter widget tree. I would like to have it as a child of widget MyApp, so MyApp would be a parent of Child widget.
Here is a full code:
import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar:AppBar(),
      body: Column(
        children: <Widget>[
          Center(
            child: Text("This is home"),
          ),
          ListView.builder(
            shrinkWrap:true,
          itemCount:10,
          itemBuilder:(context,index){
            return InkWell(
            onTap:(){
              Navigator.of(context)
                  .push(MaterialPageRoute(builder: (context) => Child(index)));
            },
            child:Container(
            height:50,
            width:50,
            child:Text("item $index",style:TextStyle(color:Colors.white))));
          }),

        ],
      ),
    ),
    );
  }
}

class Child extends StatelessWidget {
  final int index;
  Child(this.index);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:AppBar(),
        body: Container(
      child: Text("Child view $index"),
    ));
  }
}

I understand it can be done using nested navigation but I am unable to use Navigator.

A: You may need to change the InkWell widget with Container as shown below, because the container overlaps the inkwell behavior, thus no action can be performed:
      ListView.builder(shrinkWrap:true, itemCount:10, itemBuilder:(context,index){
        return Container(
          height:50,
          width:50,
          child: InkWell(
            child: Text("item $index",style:TextStyle(color:Colors.white)),
            onTap:(){
             Navigator.of(context)
              .push(MaterialPageRoute(builder: (context) => Child(index)));
          })),
      })


text:
Q: Read var from external javascript file and convert it to php variables I have a javascript file (let's call it external.js) located at some place on my server with the following content:
var exchange = {
"USD": {
    "transfer": 203.49,
    "cash": 90.08,
    "average": 203.49,
},
"EUR": {
    "transfer": 231.16,
    "cash": 102.32,
    "average": 231.16,
},
"USDCOL": {
    "rate": 2625.00,
    "ratecash": 2350.00,
    "ratetrm": 2500.59,
    "trmfactor": 0.05,
    "trmfactorcash": 0.06
},
"EURUSD": {
    "rate": 1.1359
}
"GOLD": {
    "rate": 1203.95
}}
//this code is simplified there is a lot more values

I will like to read that file from PHP (something similar to what is done with external xml files) and split those strings into variables, like this:
$USD_transfer = 203.49;
$USD_cash = 90.08;
$USD_average = 203.49;
$EUR_transfer = 231.16;
$EUR_cash = 102.32;
$EUR_average = 231.16.49;
$GOLD_rate = 1203.95;

Then proceed and execute the rest of my php code.
I tried file_get_contents, reading a section of a file, to extract every variable value one by one, but it is obviously unpractical.
<?php
//Read 6 characters starting from the 166 character to get $USD_transfer
$file = file_get_contents('./external.js', NULL, NULL, 166, 6);
$USD_transfer = $file;
?>

PD: since I am working with a pre-made (unalterable) code that generates (only) that javascript file I can not modify it, if it where my choice I would use a database... but that's not the case.
My coding skills are very limited, can you guys please help me?

A: If you remove it from said variable and make it a json file, i.e.:
{
    "USD": {
        "transfer": 203.49,
        "cash": 90.08,
        "average": 203.49,
    },
.....etc
}

You'd be able to use json_decode() on it. The way you have it now, you'd have to use ajax somehow to send them to the php script that processes it. Where you'd be able to do something like the following to assign the variables as you require, provided you are using that exact data structure as shown.
$json = file_get_contents(getcwd() . '/jsonfile.json');
$data = json_decode($string);
foreach($data as $key => $items) {
    foreach($items as $identifier => $value) {
        ${$key . '_' . $identifier} = $value;
    }
}

Which would harness PHP's variable variables to create the variables like this: KEY_identifier, meaning USD_transfer....etc.
Allowing you to call the variable as such:
echo $USD_transfer;

Working Example

Also, a quick note:
Your JSON object is not a valid object, you can check to see if it's correct at JSONLint.


text:
Q: Need direction in regards to probability based random value generation I have a daily stream discharge data set spanning 10 years whose histogram looks like this:

I would like to use it to set the distribution for a randomly chosen discharge for a given timestep. That is, I want to generate a value for discharge for my model timestep based on the probability of that discharge existing in the dataset.
I realize this sounds like a modeling/programming question, but I'm not looking for code, just direction. I have tried researching probability density functions and fitting a curve to the histogram and then sampling, but I want to be sure I'm headed in the right direction before proceeding further. Thanks much for your time. AM.

A: I'm quickly realizing that I may be over complicating things. I think I will just randomly sample the emirical data, generating a vector based on the empirical values with length of run_time/timestep. In Matlab, as follows:
Qdata = csvread('./missouri_data.csv',1,0);
discharge_data = 0.0283168466 .* Qdata(:,2); % convert cfs column to m3/s
Q_ws(1:run_time/timestep) = 0;
for i = 1:run_time/timestep;
    pull = round(rand() * numel(discharge_data)); % date to pull
    Q_ws(i) = discharge_data(pull);
end

Thanks all, for the help. AM.


text:
Q: Return name of named range for any given cell inside onEdit(e) I can't find any code to get started on this. Here is what I want to do.

*

*Change value of a cell, let's say "A1"

*Capture that change inside onEdit(e)

*Get the name of the named range that that "A1" is inside

*Use the name of the named range in a Switch

Step 3 is what I don't know how to get started on.
All help appreciated.


text:
Q: Datatables Editor : New record to be created with an user ID provided from backend I have a MySQL table in backend that stores user's information and the primary Key is an AUTO iNCREMENT number which I use to identify the user.
I am using Datatables editor to edit / delete / new records on this table. However since ID of each user's is unique I have disabled them for editing at Web page by below function:
editor.on( 'onInitCreate', function () {
    editor.disable('id');
} );
editor.on( 'onInitEdit', function () {
    editor.disable('id');
} );

This way the user viewing the web page cannot edit / modify the uid value. But the issue is that when creating a new User record I have to show the id value next available from the backend at create new web page.
Say the last user id number is 65, so when user clicks on New button it should show an non-editable value of User id as 66 with other editable blank form values and so on each time the new record is getting created.
At present I am just using the below format:
include( "DataTables.php" );

// Alias Editor classes so they are easy to use
use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Join,
    DataTables\Editor\Validate;
Editor::inst( $db, 'datatables_demo' )
    ->fields(
        Field::inst( 'id' ),
        .............

    )
    ->process( $_POST )
    ->json();

EDIT::
On another hand I realized that the value can be unreliable at front end because another web user / admin could also try inserting a row simultaneously. That would mean that when the user clicks on Submit on Create New record form, the new user table should be updated and before the new record form is dismissed the UID value should be displayed.


text:
Q: Как сделать шар (не круг)? подскажите как сделать шар по средством css, чтобы на нем можно было поставить цифру, например шар номер 3,
Понимаю, что это фото, но реально ли и как сделать похожее?

A: Посмотрите эту статью, очень подробно все разбирается.
По сути шар/сфера это тот же круг на css, но с добавлением заливки в виде градиента.

.circle {
  display: block;
  background: black;
  border-radius: 50%;
  height: 300px;
  width: 300px;
  margin: 0;
  background: radial-gradient(circle at 100px 100px, #5cabff, #000);
}
<figure class="circle"></figure>

После просто добавляете нужную цифру псевдо-элементом, либо дополнительным элементом и позиционируете ее.
Codepen


text:
Q: How to formulate weighted differential entropy (multivariate) in integral form? Differential entropy of one variable is
$$h(x_i) = -\int_{-\infty}^{\infty} p(x) \ln p(x) dx,$$
For the entropies of multiple variables $\mathbf{X} = \{x_1, x_2, \dots, x_K\}$, we can place them together in a vector
$$\mathbf{h}(\mathbf{X}) =
\begin{pmatrix} h(x_1) \\ h(x_2) \\ \vdots \\ h(x_K) \end{pmatrix}$$
If we want to weight the entropies in the vector element by element as a summation, a weight vector is pre-multiplied
$$\begin{pmatrix} w_1 \enspace w_2 \enspace \dots \enspace w_K \end{pmatrix} \begin{pmatrix} h(x_1) \\ h(x_2) \\ \vdots \\ h(x_K) \end{pmatrix} $$
Above shows the weighted entropy vector operation in matrix notation. How can I instead write this as one integral? Is the following correct?
$$h(x_i) = -\int_{-\infty}^{\infty} w_i \cdot p(x_i) \ln p(x_i) dx_i$$
If so, this where I'm stuck:

*

*should I add a second subscript to the $p_i$'s since we are integrating them observation by observation, whereas $w_i$ is left as is because we are integrating weights variable-by-variable?

*should there instead be a double integral because of this?

*should I leave the $i$th weight outside of the integral because it's not stochastic (random) like everything else inside of the integral?

(edited $H$ to $h$ because the first represents discrete entropy and the second is for differential entropy)


text:
Q: Using TreeViewer [Antlr4] in java only shows the full tree and not the hierarchichal data I was using this found on How to Display ANTLR Tree GUI but it only shows the full tree like an image and I need to have the hierarchichal tree, similar to a JTree. Is this possible?
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.gui.TreeViewer;

/**
 * A simple demo to show AST GUI with ANTLR
 * @see http://www.antlr.org/api/Java/org/antlr/v4/runtime/tree/gui/TreeViewer.html
 *
 * @author wangdq
 * 2014-5-24
 *
 */
public class HelloTestDrive {
    public static void main(String[] args) {
        //prepare token stream
        CharStream stream = new ANTLRInputStream("hello antlr");
        HelloLexer lexer  = new HelloLexer(stream);
        TokenStream tokenStream = new CommonTokenStream(lexer);
        HelloParser parser = new HelloParser(tokenStream);
        ParseTree tree = parser.r();

        //show AST in console
        System.out.println(tree.toStringTree(parser));

        //show AST in GUI
        JFrame frame = new JFrame("Antlr AST");
        JPanel panel = new JPanel();
        TreeViewer viewr = new TreeViewer(Arrays.asList(
                parser.getRuleNames()),tree);
        viewr.setScale(1.5);//scale a little
        panel.add(viewr);
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200,200);
        frame.setVisible(true);
    }
}

I am getting the right side, but I also want to get the left side of this image

A: If I understand your question correctly, you want to be able to be able to expand or collapse branches in the tree with user interaction. ANTLR's TreeViewer does not support this feature and is therefore not possible out of the box.
I do not have code ready for you, but I think your best approach is to convert ANTLR's ParseTree into a Swing JTree by linking Swing TreeNodes together. This mapping is quite straightforward and then allows you full customisability.
If you would really like to use ANTLR's representation, you would have to adapt the TreeViewer.java to support these user interactions.


text:
Q: Looping through values to make changes in data frame I have a code that makes some changes in a dataframe.
 value <- iris[1:120,]

 cngfunc <- function(day,howmany,howmuch){
   shuffled= day[sample(1:nrow(day)), ]
   n = as.integer((howmany/100)*nrow(day)) #select percentage of data to be changed
   extracted <- shuffled[1:n, ]
   extracted$changed <- extracted[,1]*((howmuch/100)+1) #how much the data changes
   extracted}

cngfunc(value,10,20)

Now I want to loop through the values of howmany and howmuch.
For example, howmuch <- c(10,20,30,40,50) and howmany <- c(10,20,30,40,50)
So the first result would be for cngfunc(value,10,10), cngfunc(value,10,20),cngfunc(value,10,30)....and cngfunc(value,20,10), cngfunc(value,20,20), and so on such that I'll have 25 different data frame.
Is there a way to do that?

A: You can do it with expand.grid to get all of the combinations, and the a map2 to create a list of dataframes:
library(tidyverse)

combos <- expand.grid(c(10,20,30,40,50), c(10,20,30,40,50))

result <- map2(combos$Var1, combos$Var2, function(x, y) cngfunc(value, x, y)) %>%
  setNames(tidyr::unite(combos, Var, Var1:Var2, sep = "-")$Var)

Not sure where you are getting 120 dataframes from, as 5 * 5 = 25. This should be the general idea though.


text:
Q: Update trigger MySQL giving syntax error I want to create trigger to make update on table when inserting rows to other table, but I get a syntax error for this:
CREATE TRIGGER quantity AFTER INSERT ON sale_items
FOR EACH ROW
BEGIN
update products set quantity = quantity -1 where id =(
SELECT product_id
FROM sale_items
ORDER BY id desc
LIMIT 1)
END;

Error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near 'END' at line 7

A: This seems like a silly trigger.  Why are you fetching the last update id using a subquery?  It should be available through new:
DELIMITER //
CREATE TRIGGER quantity AFTER INSERT ON sale_items
    FOR EACH ROW
    BEGIN
    update products
        set quantity = quantity - 1
        where id = new.product_id
    END//
DELIMITER ;

A: Use proper Delimiter in your trigger , the correct code is:
DELIMITER //
CREATE TRIGGER quantity AFTER INSERT ON sale_items
    FOR EACH ROW
    BEGIN
    update products set quantity = quantity - 1
        where id = new.product_id ;
    END//
DELIMITER ;


text:
Q: Flutter: vertically center TextField in a Container? As you can see on the picture the text is sticked to the top of the container. I would prefer if it would be in the center of it...

This is my code:
Padding(
      padding: EdgeInsets.symmetric(horizontal: 8),
      child: Container(
        decoration: BoxDecoration(
            border: Border.all(color: Colors.black, width: 1),
            borderRadius: BorderRadius.all(Radius.circular(20)),
            color: Colors.green),
        child: Center(
          child: Padding(
            padding: EdgeInsets.only(left: 20),
            child: TextField(
              textAlignVertical: TextAlignVertical.bottom,
              textAlign: TextAlign.start,
              cursorColor: Colors.black,
              maxLength: 1,
              decoration: new InputDecoration.collapsed(hintText: ""),
              keyboardType: TextInputType.text,
              autocorrect: false,
              maxLines: 1,
              enableSuggestions: false,
              style: TextStyle(
                color: Colors.white,
                fontSize: 24,
              ),
            ),
          ),
        ),
      ),
    );

I want the text in the center (sorry for my paint skill):

Also I would like to set a padding to the letter counter in the right bottom corner if it is possible?
Thanks in advance.

A: The issue raise from decoration: InputDecoration.collapsed(), the TextField and counter is talking the space and positioning the text like that. You can use  counterText: "", inside InputDecoration.
Container(
  decoration: BoxDecoration(
      border: Border.all(color: Colors.black, width: 1),
      borderRadius: BorderRadius.all(Radius.circular(20)),
      color: Colors.green),
  child: TextField(
    controller: TextEditingController()..text = "A",
    textAlignVertical: TextAlignVertical.center,
    textAlign: TextAlign.start,
    cursorColor: Colors.black,
    maxLength: 1,
    decoration: InputDecoration(
        counterText: "",
        hintText: "",
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(20)),
        )),
    keyboardType: TextInputType.text,
    autocorrect: false,
    maxLines: 1,
    enableSuggestions: false,
    style: TextStyle(
      color: Colors.white,
      fontSize: 24,
    ),
  ),
),

Add the padding and others decoration if needed


text:
Q: Direct file upload from node add form is not working for flysytem_dropbox and flysystem_s3 module for drupal 8 I am using Flysystem module with flysystem_dropbox and flysystem_s3 for storage. I have configured the schemes in settings.php as described in readme.txt files of the modules.
Now when I am syncing the files from local to dropbox or local to s3 the sync process is working fine but if I try to store file directly from a node add form to dropbox or s3 its not working. I am getting the following errors in recent log messages link
Dropbox error :

The upload directory dropboxexample://
  for the file field field_dropbox_file could not be created or is not
  accessible. A newly uploaded file could not be saved in this directory
  as a consequence, and the upload was canceled.

S3 error :

Aws\S3\Exception\S3Exception: Error
  executing "PutObject" on
  "https://s3-eu-west-1.amazonaws.com/drupal8test/"; AWS HTTP
  error: Client error response [url]
  https://s3-eu-west-1.amazonaws.com/drupal8test/ [status code] 400
  [reason phrase] Bad Request IllegalLocationConstraintException
  (client): The unspecified location constraint is incompatible for the
  region specific endpoint this request was sent to. - <?xml
  version="1.0" encoding="UTF-8"?>
  <Error>IllegalLocationConstraintException<Message>The
  unspecified location constraint is incompatible for the region
  specific endpoint this request was sent
  to.</Message><RequestId>A0EFF7B64110C2C5</RequestId><HostId>hze5fRf4JLZYsWLrlT5djroRwL/LrxWgzFX9qU5tP+riDfBeYNn900z36HtwktejaqckD2Gwhss=</HostId></Error>
  in Aws\WrappedHttpHandler->parseError() (line
  153 of /var/www/html/drupal8/core/vendor/aws/aws-sdk-php/src/WrappedHttpHandler.php).

My scheme configuration is like below:
$schemes = [
  'dropboxexample' => [
    'driver' => 'dropbox',
    'config' => [
      'token' => '[my-token]',
      'client_id' => '[my login email id]',
    ],
  ],
  's3example' => [
    'type' => 's3',
    'driver' => 's3',
    'config' => [
      'key'    => '[my-access-key]',
      'secret' => '[my-secret-key]',
      'region' => 'eu-west-1',
      'bucket' => '[bucket-name]',
      'cname' => '[bucket-url]',
    ],
  ],
  'localexample' => [
    'driver' => 'local',
    'config' => [
      'root' => '/var/www/html/drupal8/sites/default/files',
    ],

    'cache' => FALSE,
    'replicate' => 'dropboxexample',

    'serve_js' => TRUE,
    'serve_css' => TRUE,
  ]
];

$settings['flysystem'] = $schemes;

So can anyone tell me if I am missing some configuration settings or something else?

A: I have the same problem, seems is your AWS policy, you need to review S3 policy and then use the simulator to check it would work at least at Amazon S3.  also I opened a ticket with this issue if you want to follow
Drupal issue https://www.drupal.org/node/2666260
You problem is the region, it need to be set just like
//|Region name               |Region id      |
//|:-------------------------|:--------------|
// |US East (N. Virginia)     |us-east-1      |
// |US West (N. California)   |us-west-1      |
// |US West (Oregon)          |us-west-2      |
// |EU (Ireland)              |eu-west-1      |
// |EU (Frankfurt)            |eu-central-1   |
// |Asia Pacific (Tokyo)      |ap-northeast-1 |
// |Asia Pacific (Seoul)      |ap-northeast-2 |
// |Asia Pacific (Singapore)  |ap-southeast-1 |
// |Asia Pacific (Sydney)     |ap-southeast-2 |
// |South America (Sao Paulo) |sa-east-1      |

$schemes = [
  's3' => [
    'driver' => 's3',
    'config' => [
      'key'    => '[your key]',
      'secret' => '[your secret]',
      'region' => '[aws-region-id]',
      'bucket' => '[bucket-name]',

  // Optional configuration settings.

  'options' => [
    'ACL' => 'public-read',
    'StorageClass' => 'REDUCED_REDUNDANCY',
  ],

  'protocol' => 'https',             // Will be autodetected based on the current request.

  'prefix' => 'an/optional/prefix',  // Directory prefix for all uploaded/viewed files.

  'cname' => 'static.example.com',   // A cname that resolves to your bucket. Used for URL generation.
],

'cache' => TRUE, // Creates a metadata cache to speed up lookups.

],
];
$settings['flysystem'] = $schemes;


text:
Q: Prove the limits of type $\infty - \infty$. Need an explanation for
$$\lim_{x\to y} \cot(g(y)-g(x))-g'(y)^{-1}\cot(y-x)=\frac{g''(y)}{2g'(y)^2}$$
This question does not have any additional conditions, clearly the functions $g$ is from $C^2$. The problem is, I am getting $\frac{g''(y)}{g'(y)^2}$ (using mean value theorem), but while I solve by substituting $g$ with some other functions, I get the answer of the form $\frac{g''(y)}{2g'(y)^2}$ (I used mathematica). What I don't understand is how that $\frac{1}{2}$ came over there. Here is my explanation: $\cot(g(y)-g(x))-g'(y)^{-1}\cot(y-x)=\frac{1}{y-x}\left(\frac{y-x}{g(y)-g(x)}(g(y)-g(x))\cot(g(y)-g(x))-g'(y)^{-1}(y-x)\cot(y-x)\right)$
as $x\to y$, $(g(y)-g(x))\cot(g(y)-g(x))$ and $(y-x)\cot(y-x)$ tends to 1. Hence, the total limit must tend to $\frac{d}{dy}\frac{1}{g'(y)}$. If there is any mistake in my explanation kindly point it out.

A: If you set $z=x-y$, $A=g'(y)$ and $B=\frac{1}{2}g''(y)$, the limit can be rewritten, using
$$
g(y+z)=g(y)+g'(y)z+\frac{g''(y)}{2}z^2+o(z^2)
$$
as
$$
\lim_{z\to0}
\frac{\tan(Az+Bz^2+o(z^2))-A\tan z}
     {A\tan z\tan(Az+o(z))}=
\lim_{z\to0}
\frac{Az+Bz^2-Az+o(z^2)}{A^2z^2+o(z^2)}=\frac{B}{A^2}=\frac{g''(y)}{2g'(y)^2}
$$


text:
Q: Extracting latitude and longitude pairs as list from LineString in GeoPandas I have a GeoPandas GeoDataFrame that looks like this:
shape_id    geometry
1000252     LINESTRING (4.91790 52.34725, 4.91797 52.34715...
1000254     LINESTRING (4.80382 52.34495, 4.80413 52.34500...
1000255     LINESTRING (4.89922 52.37811, 4.89923 52.37807...

I would like to extract the coordinates in the geometry column for each shape_id row individually as a list. For example, the output for shape_id = 1000252 should be as follows:
[[52.34725, 4.91790],
 [52.34715, 4.91797],
 [52.34742, 4.91723],
 [52.34752, 4.91713]]

What is the most efficient way to achieve this?

A: Maybe not "most efficient" but it will get you the result you want:
import geopandas as gpd

df = gpd.read_file(r'/home/bera/Drives/Lagring/GISdata/OpenStreetmap/sweden-latest-free.shp/gis_osm_railways_free_1.shp')

def f(frame):
    xy = frame.geometry.xy
    longs = xy[0].tolist()
    lats = xy[1].tolist()
    return [list(z) for z in zip(lats, longs)]

df['coords'] = df.apply(f, axis=1)

1 second for 25000 features

A: You can use this one-liner if you are happy with a list of tuples instead of a list of lists:
df['coords'] = df.geometry.apply(lambda geom: list(geom.coords))

A: Another option is to use the .mapping() method.
import geopandas as gpd
from shapely.geometry import LineString, mapping

d = {
    'id': [1, 2],
    'geometry': [
         LineString([
             (350630.319649, 5333438.389906),
             (410389.192817, 5298093.202727),
             (466139.848883, 5303194.569949),
             (500391.885943, 5310482.237409),
             (522254.888322, 5300643.886338),
             (547761.72443, 5287890.468284),
             (594038.412798, 5288254.851657),
             (620638.399026, 5307931.553798),
             (643230.16815, 5355301.392285)
             ]),
         LineString([
             (465059.389802, 5337643.246403),
             (428840.7437, 5395427.193238)]
             )]
    }

gdf = gpd.GeoDataFrame(d, crs="EPSG:25832")

def line_to_coords(geom):
    m = mapping(geom)
    list_of_tuples = m['coordinates'] # alternative -> geom.coords[:]
    list_of_lists = list(map(list, list_of_tuples))
    return list_of_lists

gdf['coords'] = gdf.apply(lambda row: line_to_coords(row.geometry), axis=1)

print(gdf)

The above code will result in:
   id  ...                                             coords
0   1  ...  [[350630.319649, 5333438.389906], [410389.1928...
1   2  ...  [[465059.389802, 5337643.246403], [428840.7437...

[2 rows x 3 columns]


text:
Q: How to make iterated data render properly in a table with React? Using the following data set how can I make the data render properly in the table?
Each row represents new row for the table and the objects inside each row represents the data for the columns:
"result": {
  "data":[
    {
      "row": [
        {name: "Clark Kent", value: "Superman"},
        {name: "Tony Stark", value: "Iron Man"}
      ]
    },
    {
      "row": [
        {name: "Bruce Wayne", value: "Batman"},
        {name: "Peter Parker", value: "Spiderman"}
      ]
    }
  ]
}

In my component I am doing the following but it doesn't work properly:

  {_.map(Object.values(result), (path, index) => {
    let returnOptions=[];
    _.map(Object.values(path), (data,i) => {
      data.row.map((item, y) => {
        console.log(item)
        returnOptions.push({
          item: _.get(state, item, '')
        })
      })
    })
    // console.log(returnOptions)
    const testtest = returnOptions.map(option => {return option.item})
    return (

{testtest}

    )
  })}

Desired output that I am looking for:
    Table
-----------------
  Col1   | Col2
-----------------
Superman | IronMan
Batman   | Spiderman

A: Something like this?

    {data.result.data.map(item => (

            {item.row.map(row => (
                {row.value}
            	))}

    ))}

For example I used HTML table


text:
Q: Firebase - convert anonymous user to logged in user? Context: In my iOS game, I'd like to allow users to play without logging in (authenticating anonymously in Firebase to save user data), but also give them the option to login with Facebook to unlock additional gameplay.
I'm attempting a modification of this post, replacing Twitter logins with anonymous logins:
"users": {
    "$userid": {
      // Require the user to be logged in, and make sure their current credentials
      // match at least one of the credentials listed below, unless we're creating
      // a new account from scratch.
      ".write": "auth != null &&
        (data.val() === null ||
        (auth.provider === 'facebook' && auth.uid === data.child('facebook/id').val() ||
        (auth.provider === 'anonymous' && auth.uid === data.child('anonymous/id').val()))"
    }
  }

I'm confused how the transition will work with these rules.  In particular, say:

*

*A user authenticates anonymously, and is able to create a canonical user record with their anonymous uid stored under users/"$userid"/anonymous/id.  This is allowed because the user is authenticated and the user object is being set for the first time (auth != null && data.val() === null).

*Any subsequent writes to users/"$userid"/ are allowed because the authenticated user's anonymous id is stored in the user tree (auth != null && (auth.provider === 'anonymous' && auth.uid === data.child('anonymous/id').val())).

*The user logs into facebook.  Now authData contains the facebook uid, which has not yet been written to users/"$userid"/facebook/id.  Writes to that location fail because security rules don't allow it.
So the anonymous user doesn't have access to the facebook uid until after facebook authentication completes.  At that point, it's too late to write to users/"$userid"/facebook/id because the authenticated user is now a facebook user and doesn't have permission to write there.
Am I missing something?  Any ideas on how to remedy this situation?


text:
Q: Reply QR Code on Bot framework with MessagingToolkit.QRCode I want to display a QR Code picture back to the client.
Here is my code in RootDialog,
[LuisIntent("None")]
[LuisIntent("")]
public async Task None(IDialogContext context, LuisResult result)
{
    string qrText = "Photo";
    QRCodeEncoder enc = new QRCodeEncoder();
    Bitmap qrcode = enc.Encode(qrText);

    var message = context.MakeMessage();
    Attachment attachment = new Attachment();
    attachment.ContentType = "image/jpg";
    attachment.Content = qrcode as Image; // This line is not sure...
    attachment.Name = "Image";
    message.Attachments.Add(attachment);
    await context.PostAsync(message);
}

I'm not really sure how to reply an image object as an attachment though..
Thank you very much!

A: You just need a few steps between your QRCode encode and the attachment content: convert the Bitmap to a byte[], then convert to base64 and add it as ContentUrl:
string qrText = "Photo";
QRCodeEncoder enc = new QRCodeEncoder();
Bitmap qrcode = enc.Encode(qrText);

// Convert the Bitmap to byte[]
System.IO.MemoryStream stream = new System.IO.MemoryStream();
qrcode.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();

var message = context.MakeMessage();
Attachment attachment = new Attachment
{
    ContentType = "image/jpg",
    ContentUrl = "data:image/jpg;base64," + Convert.ToBase64String(imageBytes),
    Name = "Image.jpg"
};
message.Attachments.Add(attachment);
await context.PostAsync(message);

Demo:


text:
Q: How to set a local variable from new function in JavaScript I have a function with a variable. I need to run code from a string to modify that variable. How would I set a local variable from new Function() or something similar?

function alertNumber() {
  var number = 5;
  var f = new Function("number = 4");
  f();
  console.log("local " + number); //should alert 4
  console.log("window " + window.number); //instead of the local variable, it sets the property to the window
}
alertNumber();

A: With new Function, it's not possible.

However, unlike eval (which may have access to the local scope), the Function constructor creates functions which execute in the global scope only.

You would need

function alertNumber() {
  var number = 5;
  eval("number = 4");
  console.log("local " + number); //should alert 4
}
alertNumber();

(though having to do this in the first place is quite suspicious - if it were me, I'd consider hard if there were really no alternatives first)

A: Just create a new function that modifies the number and then returns the result of the modified number:
// This should fix your problem

function modifyNumber(number) {
  return number = 4
}

function alertNumber() {
  var number = 5
  number = modifyNumber(number)
  console.log("local " + number) // outputs "local 4"
}


text:
Q: Regex with Replace String Python I have this situation, I have a sentence with wrong dot (.) to process, the sentence:
sentence = 'Hi. Long time no see .how are you ?can you follow .@abcde?'

I am trying to normalize this sentence, if you see it, there is some wrong format sentence (.how, ?can, and .@abcde). I am thinking of using regex to handle this because the sentence keep changing. This is my code so far:
    import re
character = ['.','?','@']

sentence = 'Hi. Long time no see .how are you ?can you follow .@abcde?'

sentence = str(sentence)
for i in character:
    charac = str(i)
    charac_after = re.findall(r'\\'+charac+r'\S*', sentence)
    if charac_after:
        print("Exist")
        sentence = sentence.replace(charac, charac+' ')

print(sentence)

The result some how skip the dot (.) and at (@) it just process the question mark (?). This is the result:
Exist
Hi. Long time no see .how are you ? can you follow .@abcde?

its supposed to be "Hi. Long time no see . how are you ? can you follow . @ abcde?". I don't know if my double backslash in "r'\'+charac+r'\S*'" are wrong or something, did I miss something?
How can I process all the character? please help.

A: Without any knowlegde of python i think you need to do it like this:
(as per suggestion from @Sebastian Proske)
character = ['.','?','@']
sentence = str('Hi. Long time no see .how are you ?can you follow .@abcde?')
sentence = re.sub(r'([' + ''.join(map(re.escape, character)) + r'])(?=\S)', r'\1 ', sentence)
print(sentence)

The code i am not sure about, but the regex. see here:
https://regex101.com/r/HXdeuK/2
see demo here https://repl.it/Fw5b/3


text:
Q: how to stop scroll event Hello i have 2 functions , first detect sroll direction up/down , and launch other function (autoscrolling). How to force stop .scroll() function after call ? now it's look's like infinity loop...
var pageScroll = function(){

    var iScrollPos = 0;

    $(window).scroll(function(e){

        var iCurScrollPos = $(this).scrollTop();

            if (iCurScrollPos > iScrollPos) {

                App.scrollto((currentPage+1));

            } else {

                App.scrollto((currentPage-1));

            }

        iScrollPos = iCurScrollPos;

    });

}

and called functions
    scrollto: function(page){

        var section_offset = $('section[data-page="'+page+'"]').offset().top;

        $('html, body').animate({ scrollTop: section_offset }, 'slow',function(){

            $('html, body').stop();
            currentPage = page;
            console.log(currentPage);

        });

    }

and console log screen http://prntscr.com/4m493q (infinity loop)

A: try this:
HTMLElement.prototype.stopScroll = function(){
    this.scroll({top:this.scrollTop+1});
}

by done, call whatever element you want, assuming you're scrolling < body >:
document.getElementByTagName('body')[0].stopScroll();

or with JQuery:
$('body')[0].stopScroll();

A: You can try to return false at the end of your custom scroll function, or call preventDefault() before calling your custom scroll function.

A: The parameter you defined as e on your scroll callback handler is the event object.
$(window).scroll(function(e){

Every event on Jquery has a method called preventDefault(), that according to the Jquery Docs:

Description: If this method is called, the default action of the event will not be triggered.

So, calling this method will keep your window of scrolling:
$(window).scroll(function(e){
    e.preventDefault();

A: Use $(window).unbind('scroll');: http://api.jquery.com/unbind/


text:
Q: Search engine considerations for wordpress content I am a web development beginner making a website in wordpress. I have been learning/using any and all web dev languages in my site as necessary.
For my site, I am planning on creating custom post types so that users can upload and manage specific kinds of content. I have a question though, with regard to wordpress posts or content and search engines.
Initially, I was thinking that I would create a general page template designed to display a specific post type. Then, when the user would click a link or what have you, the page would load the specific post into the template dynamically. So, for example, I would have a baseball team page that could display information for any baseball team. Then, if a user clicked a Yankees symbol he would be taken to that general page, populated with Yankees information.
However, recently, I have been thinking that this approach could hurt me when users search "Yankees" in google for example. Since my page is not devoted to Yankees and does not have the appropriate Yankees tags or whatever Google is looking for (because it is general), google would not list it in its results.
Should I create a page for every specific post? Is there such a thing as a custom page type?
I realize that this question may be naive or simplistic, sorry about that. Thank in advance

A: I guess new page for post is good; with well formed url, description, keywords and sitemap your blog is seo ready.
Wordpress seo tips may be helpful for u: https://yoast.com/articles/wordpress-seo/

A: Custom post types are a great way to separate content. However, if you are just learning Wordpress, keep in mind that categories can be pretty powerful as well and come 'built in'. Could be an easier way to learn the WordPress Codex basics, and you can build into CPT from there.
That being said, CPT behave just like 'Posts' do in a standard install of WP. So, yes, you can create specific templates for CPT singles and archives: http://codex.wordpress.org/Post_Type_Templates
In your example, you would create a CPT of 'baseball', then archive-baseball.php, single-baseball.php. Then you would want to create a post for each team inside of your 'baseball' CPT.
For SEO, the easiest thing you can do is set your permalinks to be using %postname% somewhere in the path. Done right, this will let you have a path of site.com/baseball/yankees in your sitemap. http://codex.wordpress.org/Using_Permalinks
I'm also a big fan of the Yoast SEO Plugin. Makes it easy to set up a lot of stuff and automatically submit updates to search engines. https://yoast.com/wordpress/plugins/seo/


text:
Q: How to get the real declared types of member varaibles of a subclass of Generic[T] I am trying to get the real type of a variable of Generic Type. I tried many ways, however, none of them looks promising.
Here is the minimal code that demenstrates my question:
from typing import *
T = TypeVar('T')

class G(Generic[T]):
    x: T = None

class R(G[int]):
    pass

I want to get the real type of R.x in runtime. My first try is using get_type_hints. It gives
{'x': ~T}

Looks not very useful.
I also tried with R.__orig_bases__. It does have something:
(__main__.G[int],)

But it is too complex to align base class type arguments to member variables.
Do you guys have ways to get the real type of R.x in runtime? Is it possible?

A: Well, given that R inherits specifically G[int], there's really no need to fetch the inner type at runtime: you know it's specifically int, so you can just hard-code that everywhere.
You could also always do type(instance_of_r.x). Presumably, you defined R.__init__ in such a way that you've guaranteed x is instantiated with a value of the right type, so you can just query that directly.
However, if you're trying to work with multiple subclasses of G[...], where each subclass parameterizes G[...] in a different way, you could potentially modify the definition of G to insist that each subclass specifies the type you want to use. For example, maybe you could do something roughly like this:
from typing import *
T = TypeVar('T')

class G(Generic[T]):
    x_type: ClassVar[Type[T]]
    x: T = None

class R(G[int]):
    x_type = int

class S(G[str]):
    x_type = str

Then, you could do instance_of_g.x_type to get back the appropriate type.
You could perhaps combine these two answers -- for example, maybe set up G's constructor so that it calls type(...) on whatever value of x it was given.