text:
Q: Passing an array of Object from Java to PL/SQL function I am trying to create a Java array (java.sql.Array) object using an array of objects. I need to pass this Java Array to PLSQL stored procedure.
conn = ConnectionManager.getConnection();
JournalBean[] journal = listJournal.toArray(new JournalBean[listJournal.size()]);
final Array sqlArray =   conn.createArrayOf("CHMCR.PACK_CHM_CR.FICHIER_CR_TYPE", journal);
cstmt = conn.prepareCall("{call CHMCR.PACK_CHM_CR.CHARGEMENT_CR(?,?,?,?,?)}");
cstmt.setArray(1,sqlArray);
cstmt.setString(2, fileName);
cstmt.registerOutParameter(3, oracle.jdbc.OracleTypes.NUMBER);
cstmt.registerOutParameter(4, oracle.jdbc.OracleTypes.NUMBER);
cstmt.registerOutParameter(5, oracle.jdbc.OracleTypes.VARCHAR);

cstmt.executeUpdate();
conn.commit();

however when I try to create this Array using the method (connection.createArrayOf), I am getting the following exception:
java.sql.SQLException: Fonction non prise en charge
    at oracle.jdbc.driver.PhysicalConnection.createArrayOf(PhysicalConnection.java:9283)

this is my JournalBean is:
public class JournalBean implements  Serializable, SQLData {

    private static final long serialVersionUID = 2199201954799483472L;

    private int idCr;
    private int idChargement;
    private String numAutorisation;
    private String version;

    @Override
    public String getSQLTypeName() throws SQLException {
        return "FICHIER_CR_TYPE";
    }

    @Override
    public void readSQL(SQLInput stream, String typeName) throws SQLException {
        idCr = stream.readInt();
        ...

    }

    @Override
    public void writeSQL(SQLOutput stream) throws SQLException {

        stream.writeInt(idCr);
        ...
    }
}

this is my new DDL (creating the type in database using CREATE TYPE):
create or replace TYPE            CR_TYPE AS OBJECT
( ID_CR NUMBER  ,
ID_CHARGEMENT   NUMBER ,
NUM_AUTORISATION    VARCHAR2(24 BYTE),
VERSION NUMBER
) ;

then creating the table type:
CREATE OR REPLACE TYPE FICHIER_CR_TYPE
AS VARRAY(1000) OF CR_TYPE;

the procedure has became:
create or replace PACKAGE             PACK_CHM_CR
IS
   PROCEDURE CHARGEMENT_CR(
                                                              P_FICHIER_CR                       IN OUT FICHIER_CR_TYPE,
                                                              p_nom_fichier                        IN        VARCHAR2,
                                                              p_id_chargement                       OUT NUMBER,
                                                              NMES                                        OUT NUMBER,
                                                              LMES                                        OUT VARCHAR2);
END PACK_CHM_CR;

I'm using Oracle 11g, java 6 and I had tried ojdbc14 and ojdbc6.

A: According to documentation of createArrayOf()
Array createArrayOf(String typeName, Object[] elements) throws SQLException

If the resulting JDBC type is not the appropriate type for the given
  typeName then it is implementation defined whether an SQLException is
  thrown or the driver supports the resulting conversion.

Your typeName CHMCR.PACK_CHM_CR.FICHIER_CR_TYPE is custom. Try to use defined type and check if exception will disapear.
Please, find additional details here.

A:
create or replace PACKAGE             PACK_CHM_CR
IS
   TYPE fichier_CR_TYPE IS TABLE OF CHMCR.JOURNAL_OPERATION_CHANGE%ROWTYPE index by binary_integer;

You can't for three reasons:

*

*TYPE x IS TABLE OF y INDEX BY z is an associative array. This is solely a PL/SQL data type and JDBC does not support passing associative arrays, only collections or VARRAYs (both non-associative array) data types (unlike in C# which only support associative arrays and not collections/VARRAYs).

*It is defined in a PACKAGE which is a PL/SQL scope. If you want to pass a type it needs to be defined in an SQL scope using a CREATE TYPE statement.

*The JDBC driver doesn't know how to convert from your JournalBean class to a fichier_CR_TYPE database type. You either need to pass to a simple array (there are built-in types that can be used like SYS.ODCIVARCHAR2LIST) or you need to tell Java how to map between the class and the database type (SQLData is one method of doing this).

You need to fix all 3 of these issues.

Update:
The JournalBean class does not map to FICHIER_CR_TYPE as that is an array; they type should be of the object type CR_TYPE:
public class JournalBean implements  Serializable, SQLData {
  // ...
  public static final String SQL_TYPE = "CR_TYPE";

  @Override
  public String getSQLTypeName() throws SQLException {
    return SQL_TYPE;
  }
}

You also need to register the type with the connection:
conn = ConnectionManager.getConnection();

Map<String,Class<?>> typeMap = conn.getTypeMap();
typeMap.put( JournalBean.SQL_TYPE, JournalBean.class );


text:
Q: RF to DC convertor I am working on RF energy harvester and I want to increase the current. Should I connect more rectifiers in parallel to one antenna or more antennas to one rectifier?
Here is my schematic.
My antenna is a printed Helical with 2.3 dBi gain and 66% efficiency.
My transmitter is 1 W 868 MHz.
I want a current of a few milliamps.

__________________________
Added from OP's comments:
My range is about 10m from the 1W transmitter.
I am working on a prototype of low power device with my friend, I think my friend use this article for this design.
The device uses Microamps and low voltage but the problem with bluetooth TX current is about 6mA.
My PCB is 4-layers and My dual band antenna is printed Helical
Ref -  TI Design Note DN038 SWRA416 - Miniature Helical PCB Antenna for 868 MHz or 915/920 MHz
I want to use one antenna and more rectifiers as I see this product use one antenna and more rectifiers chips.
TI RFD-ASSY-01 – Microwave Energy Harvesting System

They say: "The assembly can produce up to 60mA continuous current and ~40% RF-DC conversion efficiency into a 1kOhm load from 18dBm…29dBm input power at
2.45GHz."
[[RM: ie 60 - 800 mW input. ]]

A:
I am working on RF energy harvester and I want to increase the
  current. Should I connect more rectifiers in parallel to one antenna
  or more antennas to one rectifier?

Think about what happens when an antenna emits RF power into its surroundings (assume a vacuum and assume an isotropic antenna). An isotropic antenna is like a perfect light bulb that emits light-power in all directions. So let's say it emits 1 watt in total and then ask the question how much power can be received at some distance.
If that distance was 1 metre and a receiving antenna could be constructed that totally surrounded the antenna, then 1 watt would be received. If the distance was 100 metres and a perfect receiving antenna could be constructed that totally surrounded the antenna, then 1 watt would also be received. In other words, all the power is collected (ignoring inefficiences of course)
Now here's the problem, if you only have a small antenna at some distance, the amount of power it can physically receive is very limited. In other words, at 100 metres with a receiver aperture of (say) 1 sq metre, the total amount of power that can be received is a tiny fraction of that being pushed through the surface of a sphere of radius 100 metres.
The surface of a sphere has an area of \$4\pi r^2\$ so at 100 metres radius that is 126,000 sq metres hence, your antenna with an aperture of 1 sq metres receives only 8 uW from the 1 watt source.
The aperture size of any antenna is this: -

Your antenna antenna has a gain of 2.3 dBi (the "i" stands for isotropic and it means that you have 2.3 dB more gain that an isotropic antenna) hence, at 868 MHz (0.346 metres wavelength), your effective capture area is: -
\$\dfrac{0.346^2}{4\pi}\times 1.303\$ = 0.0124 sq metres.
This area totally governs how much power you can collect from one antenna so, when you ask a question like: -

Should I connect more rectifiers in parallel to one antenna or more
  antennas to one rectifier?

You are missing the big picture - address the big picture of how you are going to collect more power before you ask about current (bearing in mind that the receiving antenna has to deliver power into a 50 ohm load for maximum efficiency and that sets the big scene).

Quick calculation to see how much current can be efficiently liberated at 1 metre distance from the 1 watt transmitter given the gains involved. If both transmit and receive antennas are 2.3 dBi gain then the effective power transmitted is 2.3 dB higher at 1.7 watts.
At 1 metre distance, the sphere area is 12.6 sq metres. The receiver has an effective area of 0.0124 sq metres hence, the received power is 1.7 x 0.0124/12.6 = 1.7 mW. If that power were collected with 100% efficiency, the voltage produced across a 50 ohm load is 0.29 volts RMS with a current of 5.8 mA RMS.
You will probably achive no more than 20% of this given inefficiences and the conversion to DC so don't bank on more than 1 mA at 1 metre and with a pitifully low terminal voltage.
See also this Q and A on RF energy harvesting.

A: You should cite your sources.
You also need to provide as much information as possible as factors that may not seem relevant may prove vital. Things like source to target range are pivotal. Transmit antenna gain /.directionality is crucial if any distance is involved. If you are close enough to be in the near-field and electromagnetic approach may be better.
_________________________
Your circuit diagram appears to come from this paper - intro page to
Enhanced Passive RF-DC Converter Circuit Efficiency for Low RF Energy Harvesting -
and the main point of the paper seems to be that there MAY be a better solution available than this one depending on power levels and other factors.
Full paper - html: http://www.mdpi.com/1424-8220/17/3/546/htm
Full paper - pdf: http://www.mdpi.com/1424-8220/17/3/546/pdf
The paper provides details of efficiency versus number of stages (fig 13), loading (fig 11),  for their suggested converter with a range of power levels.
The paper provides such a range of discussion that it would SEEM to answer your question far better than anyone could here with the amount of information that you have provided. If you are already basing your work on this paper you should say so and state your requirements with reference to the paper, what you have tried, what works and what you still cannot understand.
Note in their fig 15 the nearly 3:1 ratio between their simulated and actual results. Read the text, note the reasons that they consider cause this result and consider whether you can optimise these.
For example, mismatches due to component tolerances are easily addressed.  Schottky-diode-practical versus ideal-diode performance differences MAY be able to be addressed by working at a higher input voltage - perhaps by using an RF 1:N transformer, or higher Q resonance or ...?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Factorial using Task I am looking for a way to use task to compute factorial of a number. My purpose is to compare the result with factorial using a sequential loop. For example
16! task1 = 16*15*14*13*12*11 and task2 = 10*9*8*7*6 and task3 = 5*4*3*2*1
I have searched online but I cannot find a solution that matched my need. Thanks in anticipation.
static long factorialmethod(int number)
         {
            long factorial;
            factorial = number;
            if (number <= 1) { return 1; }
            else
            for (int i = number-1; i >= number; i--)
            {
                factorial *= i;
            }
        return factorial;
           }
      static void Main(string[] args)
         {
        int number;
        Console.WriteLine("Please input your whole number");
        number = int.Parse(Console.ReadLine());
        Console.WriteLine("\nFactorial of the number is {0}",factorialmethod(number));
        Console.ReadKey()
         }

A: An easiest way to try parallel when computing factorial is PLinq (Parallel Linq):
    using System.Linq;

    ...

    static long factorialmethod(int number) {
      if (number <= 1)
        return 1; // strictly speaking, factorial on negative (-N)! = infinity

      return Enumerable
       .Range(1, number)
       .AsParallel() // comment it out if you want sequential version
       .Aggregate(1L, (s, a) => s * a);
    }

Use Stopwatch to benchmark; comment out .AsParallel(): do you really want parallel implementation (let Task alone)?

A: You can use @DmitryBychenko answer if you want to go PLINQ way. But as an alternative, you can directly use the Parallel library too. If you are literally trying to solve your stated problem using Task library, I think PLINQ is a cleaner solution, but if you are using the posted question as a reduced version of some similar problem, where you need more control, then the below solution might help
static long Factorial(int number) {
    if (number < 1)
        return 1;

    var results = new ConcurrentBag<long>();
    Parallel.ForEach(Partitioner.Create(1, number + 1, 5 /*You can select your range size here. You can also derive it based on Environment.ProcessorCount, if you so wish */),
        (range, loopState) => {
            long product = 1;
            for (int i = range.Item1; i < range.Item2; i++) {
                product *= i;
            }
            results.Add(product);
        });

    long factorial = 1;
    foreach (var item in results)
        factorial *= item;
    return factorial;
}


text:
Q: React: Can component constructor have more than 1 parameter? Just curious can a component constructor have more than 1 parameter?
From:
constructor(props) {
    super(props)
}

Into:
constructor(props, parent) {
    super(props)
    this.parent = parent;
}

So the parent can assign this.parent inside the child component.
For example this is the parent component want to initialize the child:
constructor(props) {
    super(props)
    this.helpers = new Child(<i_am_not_sure_here>, this);
}

A: Typically, in React constructors are only used for two purposes:

*

*Initializing local state by assigning an object to this.state.

*Binding event handler methods to an instance.

Check out the official docs for more information:
https://reactjs.org/docs/react-component.html#constructor

A: I tested and I got an error.
Uncaught Error: Module build failed (from ./node_modules/babel-loader/lib/index.js)

In addition, docs didn't mention anything about extra properties.
https://reactjs.org/docs/react-component.html#constructor


text:
Q: Difference between GLIBs UTF16BE and UTF-16BE and how to support UTF16BE I am working doing OBEX push transfers to an embedded system we are building from an Android phone.  The transfers work on my debian desktop but fail on the embedded system with the error
"obexd[741]: disconnected: Unicode conversion failed: Could not open converter from 'UTF16BE' to 'UTF8'  "
Now when I type "iconv -l" I can see that I have the UTF16BE set on my debian desktop but not on my embedded system.  On both systems I have UTF-8 and UTF-16BE but not UTF8 and UTF16BE on the embedded system.  I am stuck with some old versions of certain packages from my build system, so I figured I just needed to build a newer version of glib.  I managed to build 2.27.93, which I think is newer than the debian stable.  After the build it list the same charsets as before.  I also downloaded the debian source and looked for references missing the dash but haven't found anything yet.
How do I get support for the UTF16BE charset along with UTF-16BE? Are they really different?

A: UTF16BE and UTF-16BE are certainly not different from one another. There exist all sorts of variations of character encoding names with different case and punctuation, usually because the names are adapted for use in various contexts that have different limitations on the syntax of names.
You probably have a file /usr/lib/gconv/gconv-modules which can contain aliases like this:
#       from                    to                      module          cost
alias   UTF16BE//               UTF-16BE//

I would suggest just manually editing that file on your embedded system to add the UTF16BE alias.


text:
Q: Sinatra launches after rails console exits Sinatra launches immediately after exiting rails-console:
$ rails c
Loading development environment (Rails 3.1.11)
[1] pry(main)> exit
[2014-02-06 14:01:50] INFO  WEBrick 1.3.1
[2014-02-06 14:01:50] INFO  ruby 1.9.3 (2014-01-09) [java]
== Sinatra/1.3.3 has taken the stage on 4567 for development with backup from WEBrick
[2014-02-06 14:01:50] INFO  WEBrick::HTTPServer#start: pid=4516 port=4567

The problem occurs when irb is used as the rails-console repl as well.
The problem does not occur when rails exits, only when rails console exits.
The problem occurs using jruby-1.7.10 but not jruby-1.6.7.  The problem was originally noticed after upgrading.
Sinatra is available elsewhere in my stack (so it starting is not completely out of left field) but why does it start when rails-console exits.
A temporary fix to this is the following steps:

*

*remove gem 'sinatra' from the Gemfile

*run $ bundle install

*add gem 'sinatra' back to the Gemfile

*run $ bundle install
Unfortunately, after a few modifications to the to Gemfile and another bundle install the issue persists.  I imagine this a bug in bundler, but of all things to happen why would a sintra server launch?

A: We had the same problem. We solved it by changing our Gemfile like this:
gem 'sinatra', require: false

More info about what this does can be found in:
Bundler: What does :require => false in a Gemfile mean?


text:
Q: How can i pass authroziation token in header with multipart/form-data I am using reactjs in my front end, so I am converting an image into base64 data and pass it to nodejs, In my backend I am trying send the base64 data to 3rd part API using fetch call, But it returns

401 unauthorization error

If I pass authorization in header nothing happens
    const formData = new FormData();
    formData.append('file', url);

    const resp = await fetch(requestURL, {
    method: 'POST',
    headers: {
        'Authorization': accessToken,
        'Content-Type': 'multipart/form-data',
      },
    body: formData,
    });

Can anyone help me with this?


text:
Q: Multiple select with "none" option I am building a form that will submit via ajax to a background page. I want to present options as a multiselect control, but with a "None of the Above" option.
The question is, is it possible to make this so that it impossible to select the "None" option AND still select other options? For example:
<select id="country" multiple="multiple">
    <option value>None</option>
    <option value="1">Jamaica</option>
    <option value="2">Cuba</option>
    <option value="3">France</option>
</select>

It would be valid for users to select "None" alone, or "Cuba" and "France" together-- but not "None" and "France". So if a user selected "None" and then anything else, the "None" option would be unselected automatically?
I'm using jQuery in the page if that helps matters.

A: Strange requirements, but anyway this might work for you:
$('#country').change(function() {
    if ($('option:first', this).is(':selected')) {
        $('option:not(:first)', this).prop('selected', false);
    }
});

http://jsfiddle.net/zhKKw/

A: Fiddle:http://jsfiddle.net/sajjansarkar/dRVN4/1/
  var dropdown = $("#country");
  dropdown.click(function() {
    var val = dropdown.val();
    if (val) {
        var arr = val.toString().split(",");
        if (arr.length > 0 && arr[0] == "") {
            dropdown.val("");
        }
    }
});


text:
Q: Zoom and Pan in KineticJS Is there a way one could zoom and pan on a canvas using KineticJS? I found this library kineticjs-viewport, but just wondering if there is any other way of achieving this because this library seems to be using so many extra libraries and am not sure which ones are absolutely necessary to get the job done.
Alternatively, I am even open to the idea of drawing a rectangle around the region of interest and zooming into that one particular area. Any ideas on how to achieve this? A JSFiddle example would be awesome!

A: Here's a very quick and simple implementation of zooming and panning a layer. If you had more layers which would need to pan and zoom at the same time, I would suggest grouping them and then applying the on("click")s to that group to get the same effect.
http://jsfiddle.net/renyn/56/
If it's not obvious, the light blue squares in the top left are clicked to zoom in and out, and the pink squares in the bottom left are clicked to pan left and right.
Edit: As a note, this could of course be changed to support "mousedown" or other events, and I don't see why the transformations couldn't be implemented as Kinetic.Animations to make them smoother.

A: this is what i have done so far.. hope it will help you.
http://jsfiddle.net/v1r00z/ZJE7w/

A: I actually wrote kineticjs-viewport. I'm happy to hear you were interested in it.
It is actually intended for more than merely dragging. It also allows zooming and performance-focused clipping. The things outside of the clip region aren't rendered at all, so you can have great rendering performance even if you have an enormous layer with a ton of objects.
That's the use case I had. For example, a large RTS map which you view via a smaller viewport region -- think Starcraft.
I hope this helps.

A: You can simply add .setDraggable("draggable") to a layer and you will be able to drag it as long as there is an object under the cursor. You could add a large, transparent rect to make everything draggable. The zoom can be achieved by setting the scale of the layer. In this example I'm controlling it though the mousewheel, but it's simply a function where you pass the amount you want to zoom (positive to zoom in, negative to zoom out). Here is the code:
var stage = new Kinetic.Stage({
    container: "canvas",
    width: 500,
    height: 500
});

var draggableLayer = new Kinetic.Layer();
draggableLayer.setDraggable("draggable");

//a large transparent background to make everything draggable
var background = new Kinetic.Rect({
    x: -1000,
    y: -1000,
    width: 2000,
    height: 2000,
    fill: "#000000",
    opacity: 0
});

draggableLayer.add(background);

//don't mind this, just to create fake elements
var addCircle = function(x, y, r){
  draggableLayer.add(new Kinetic.Circle({
        x: x*700,
        y: y*700,
        radius: r*20,
        fill: "rgb("+ parseInt(255*r) +",0,0)"
    })
  );
}

var circles = 300
while (circles) {
  addCircle(Math.random(),Math.random(), Math.random())
  circles--;
}

var zoom = function(e) {
  var zoomAmount = e.wheelDeltaY*0.001;
  draggableLayer.setScale(draggableLayer.getScale().x+zoomAmount)
  draggableLayer.draw();
}

document.addEventListener("mousewheel", zoom, false)

stage.add(draggableLayer)

http://jsfiddle.net/zAUYd/

A: As I was working with Kinetic today I found a SO question that might interest you.
I know it would be better as a comment, but I don't have enough rep for that, anyway, I hope that helps.

A: These answers seems not to work with the KineticJS 5.1.0. These do not work mainly for the signature change of the scale function:
 stage.setScale(newscale); --> stage.setScale({x:newscale,y:newscale});

However, the following solution seems to work with the KineticJS 5.1.0:
JSFiddle: http://jsfiddle.net/rpaul/ckwu7u86/3/

A: Unfortunately, setting state or layer draggable prevents objects not draggable.
Duopixel's zooming solution is good, but I would rather set it for stage level, not layer level.
Her is my solution
var stage = new Kinetic.Stage({
    container : 'container',
    width: $("#container").width(),
    height: $("#container").height(),
});
var layer = new Kinetic.Layer();

//layer.setDraggable("draggable");
var center = { x:stage.getWidth() / 2, y: stage.getHeight() / 2};

var circle = new Kinetic.Circle({
    x: center.x-100,
    y: center.y,
    radius: 50,
    fill: 'green',
    draggable: true
});
layer.add(circle);
layer.add(circle.clone({x: center.x+100}));

// zoom by scrollong
document.getElementById("container").addEventListener("mousewheel", function(e) {
  var zoomAmount = e.wheelDeltaY*0.0001;
  stage.setScale(stage.getScale().x+zoomAmount)
  stage.draw();
  e.preventDefault();
}, false)

// pan by mouse dragging on stage
stage.on("dragstart dragmove", function(e) {window.draggingNode = true;});
stage.on("dragend", function(e) { window.draggingNode = false;});
$("#container").on("mousedown", function(e) {
    if (window.draggingNode) return false;
    if (e.which==1) {
        window.draggingStart = {x: e.pageX, y: e.pageY, stageX: stage.getX(), stageY: stage.getY()};
        window.draggingStage = true;
    }
});
$("#container").on("mousemove", function(e) {
    if (window.draggingNode || !window.draggingStage) return false;
    stage.setX(window.draggingStart.stageX+(e.pageX-window.draggingStart.x));
    stage.setY(window.draggingStart.stageY+(e.pageY-window.draggingStart.y));
    stage.draw();
});
$("#container").on("mouseup", function(e) { window.draggingStage = false } );

stage.add(layer);

http://jsfiddle.net/bighostkim/jsqJ2/


text:
Q: Retrieving all but one elements in a list of lists (Python) I am trying to do a 10-fold cross validation for a sentiment classifier. For this purpose, I have created a list of 10 lists, where each list corresponds to one of the folds and contains movie reviews.
I am trying to create a loop, where for every iteration I use 9 folds for training the classifier and one fold for testing it. However, I am facing difficulties with subsetting the list of lists to create two variables (one for the fold, and one for the 9 remaining folds), which I can pass through my train and test functions.
I created this example as a more-readable version of my code:
list1 = [{"ID":1, "sentiment":"positive", "content": "further lists within lists"}]
list2 = [{"ID":2, "sentiment":"positive", "content": "further lists within lists"}]
list3 = [{"ID":3, "sentiment":"positive", "content": "further lists within lists"}]
list4 = [{"ID":4, "sentiment":"positive", "content": "further lists within lists"}]
list5 = [{"ID":5, "sentiment":"positive", "content": "further lists within lists"}]

list_of_lists = [list1, list2, list3, list4, list5]

for list_ in list_of_lists:
  remaining_lists = list_of_lists[~list_]
  train_classifier(remaining_lists)
  test_classifier(list_)

The error I get is "bad operand type for unary ~: 'list'".
I have seen the answers to a related question at Index all *except* one item in python, but I could not implement the solutions suggested in a loop.

A: Got it!

*

*What you are doing:
    list_of_list = [ [10], [20] , [30] , [40] ]

    for sub_lst in list_of_list:
        print( list_of_list[ ~sub_lst ] )

*What you are getting:
TypeError: bad operand type for unary ~: 'list'

*Reason:
Because you can give only an index in list_of_list[ index_here ] index might be simple in range 0 to length-1 or index can be negated using ~ but you cannot give an instance of a list in index's place while iterating over list_of_list you get an instance of each list (sub_lst) inside list_of_list[ index_here ] one after another
# check type as follow
>>> type(list_of_list[0])
    <class 'list'>

*How will you achieve the desired outcome:
list_of_list = [ [10], [20] , [30] , [40] ]
for index,sub_lst in enumerate(list_of_list):
    remaining_lst = list_of_list[:index] + list_of_list[index+1:]

    print("Sub list: ", sub_lst)
    print("Remaining list: ", remaining_lst)
    print()

*Results:
Sub list:  [10]
Remaining list:  [[20], [30], [40]]

Sub list:  [20]
Remaining list:  [[10], [30], [40]]

Sub list:  [30]
Remaining list:  [[10], [20], [40]]

Sub list:  [40]
Remaining list:  [[10], [20], [30]]

I hope it helps !!!

A: Loop over the indices of the outer list (list_of_lists) and exclude the list at that index on each iteration of the loop.
Example:
for i in range(len(list_of_lists)):
    remaining_lists = list_of_lists[0:i] + list_of_lists[i+1:]
    train_classifier(remaining_lists)
    excluded_list = list_of_lists[i]
    test_classifier(excluded_list)

Resulting IDs of lists per iteration:
Remaining    | Excluded
-------------+---------
[2, 3, 4, 5] | 1
[1, 3, 4, 5] | 2
[1, 2, 4, 5] | 3
[1, 2, 3, 5] | 4
[1, 2, 3, 4] | 5

A: you can do this as follows:
for list_ in list_of_lists:
  newlist=list_of_lists.copy()
  newlist.remove(list_)
  newlist.remove()
  train_classifier(newlist)
  test_classifier(list_)


text:
Q: How to sort a JavaFX ListProperty it seems I have encountered a problem with ListProperties. ObservableLists implement the marker interface SortableList that allows them to be sorted efficiently, firing only a single event. ListProperties do not implement this interface (how could they...?). Instead they use the default implementation of the List interface, firing a lot of changes.
The only solution I can see would be to call sort() on the underlying List directly. But this collides with the scheme of returning the Property itself:
public ObservableList getSomeList()
{
    return someListProperty();
}

which ensures that ListChangeListener remain registered when the underlying List is exchanged.
I would be happy to get some input, maybe I missed something?

A: I guess the SortableList you refer to is the one used in FXCollections.sort.
ListProperty could implement the SortableList interface.
It may indeed be a good idea, since this would allow you to choose the way the wrapped list is sorted, if e.g. FXCollections.sort is used on the property. You could use FXCollections.sort on the contained list in this case.
How could they? Like this:
class MyListProperty<T> extends ListPropertyBase<T> implements SortableList<T> {

    ...

    @Override
    public void sort() {
        ObservableList<T> list = getValue();
        if (list != null) {
            FXCollections.sort((ObservableList<Comparable>) list);
        }
    }

    @Override
    public void sort(Comparator<? super T> comparator) {
        ObservableList<T> list = getValue();
        if (list != null) {
            FXCollections.sort(list, comparator);
        }
    }

}

The only problem is, that SortableList is inside the com.sun.javafx.collections package (see It is a bad practice to use Sun's proprietary Java classes?).
About your collision with the property scheme: there is none, if you define the property the intended way, see Using JavaFX Properties and Binding section Understanding Properties
The property would be implemented like this:
private final ListProperty<MyClass> someList = ...;

public ObservableList<MyClass> getSomeList() {
    return someList.get();
}

public void setSomeList(ObservableList<MyClass> newList) {
    someList.set(newList);
}

public ListProperty<MyClass> someListProperty() {
    return someList;
}

The ListProperty has to ensure the ListChangeListeners registered to it receive the change events from the wrapped list.
Maybe you got confused with readonly list properties used in fxml, but a ListProperty is not readonly.
You could still use this property in a fxml file, but you'd need to use a value of type ObservableList:
<!-- imports -->

<ContainingClass xmlns:fx="http://javafx.com/fxml/1">
    <someList>
        <FXCollections fx:factory="observableArrayList">
            <!-- list content goes here -->
        </FXCollections>
    </someList>
</ContainingClass>


text:
Q: Is it possible to define full SELECT clause in USE GO clause? I'm trying to define full SELECT clause in USE for a list of databases.
I'm trying to query across all databases in a server to list all available functions. There are about 80 databases so I'm going to use variable table to pass the list of databases to USE clause to be able to switch between every database and run simple query to list functions in there, all through a WHILE loop.
Is it possible to do something like,
USE
    (SELECT dBname
     From dBList
     where rowID=@currentRow)
GO

IF not, any suggestion to do it less painfully than querying databases one by one?
This is what I have done in MS SQL Server 2014 but no joy,
declare @dBaseList Table
( RowID int not null primary key identity(1,1), dBname varchar(100)
)
declare @SeldBname varchar(100)
declare @rowsdBaseList int
declare @currentRow int
insert into @dBaseList (dBname)
SELECT name FROM sys.databases

set @rowsdBaseList=@@ROWCOUNT
set @currentRow=0

while @currentRow<@rowsdBaseList
begin
    set @currentRow+=1
    use
        (select @SeldBname=dBname
        from @dBaseList
        where RowID=@currentRow)
    Go

    select * from sys.objects where type='FN'
end

It should look something like,
USE
    dBname1
GO
select * from sys.objects where type='FN'

USE
    dBname2
GO
select * from sys.objects where type='FN'

USE
    dBname3
GO
select * from sys.objects where type='FN'
.
.
.
.
.

A: You should just be able to use a 3 part name in your query:
select * from dBname1.sys.objects where type='FN'
select * from dBname2.sys.objects where type='FN'
select * from dBname3.sys.objects where type='FN'

If you'd prefer to do it programmatically, you can use the (unsupported and undocumented) sp_MSforeachdb proc:
EXEC sp_MSforeachdb 'IF DB_ID(''?'') > 4 BEGIN select * from ?.sys.objects where type=''FN'' END'

The IF DB_ID(''?'') > 4 conditional excludes system databases, which you presumably don't want.
With regard to using a SELECT statement in a USE statement, you can't do it as you have specified in your question. However, you can incorporate it into the sp_MSforeachdb call, should you need to:
EXEC sp_MSforeachdb 'IF DB_ID(''?'') > 4 BEGIN USE ?; select DB_NAME() AS [DatabaseName], * from sys.objects where type=''FN'' END'

A: use sp_MSforeachdb
use [yourdatabase_in_which_you_store_the_results]
go
--create table functions_in_alldb(db nvarchar(100),fn_name nvarchar(200))
declare @functions_in_alldb as table(db nvarchar(100),fn_name nvarchar(200))
go
--truncate table functions_in_alldb
go
DECLARE @command varchar(1000)
SELECT @command = 'USE ?
if ''?'' not in (''master'',''msdb'',''tempdb'',''model'',''msdb'')
insert into @functions_in_alldb(db,fn_name) SELECT ''?'',name FROM sysobjects WHERE xtype = ''FN'' ORDER BY name'
EXEC sp_MSforeachdb @command

select * from @functions_in_alldb

A: Have you tried Dynamic-SQL? Something like the code below, this is just a sample as I don't have right now my machine to actually test it.
SELECT name AS DatabaseName INTO #TEMP FROM master.dbo.sysdatabases

DECLARE @Count INT, @Database VARCHAR(MAX), @Query
    SET @Count = (SELECT COUNT(*) FROM #TEMP)

WHILE (@Count) > 0
BEGIN
    SET @Database = (SELECT TOP(1) DatabaseName FROM #TEMP)

    SET @Query = 'SELECT * FROM ' + @Database + '.sys.objects WHERE type = ''FN'''

    EXEC (@sqlCommand)

    DELETE FROM #TEMP WHERE DatabaseName = @Database

    SET @Count = (SELECT COUNT(*) FROM #TEMP)
END

A: Below is a method to return the query results from all databases as a single result set and include the database name.
DECLARE @SQL nvarchar(MAX) =
    STUFF((
    SELECT ' UNION ALL SELECT N''' + name + N''' AS DatabaseName, * FROM ' + QUOTENAME(name) + N'.sys.objects where type=''FN'''
    FROM sys.databases
    FOR XML PATH(''), TYPE).value('.','nvarchar(MAX)'), 1, 11,'') + N';';
EXEC(@SQL);


text:
Q: Using laravel in domain.com/app folder On a live server (not locally) I want to show my Laravel app like so:
www.domain.com/app, then it would show the site.
How can I do this?
Can .htaccess do this?
My .htaccess is as follows:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /dev
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

Also have my routes as:
Route::group(array('domain' => 'domain.com/dev/'), function() {

Route::get('admin', 'AdminController@login');
Route::post('admin/postlogin', array('as' => 'admin.postlogin', 'uses' => 'AdminController@postlogin'));
Route::get('admin/dashboard', array('as' => 'admin.dashboard', 'uses' => 'AdminController@dashboard'));
Route::get('admin/dashboard', 'AdminController@dashboard')->before('auth');
Route::get('admin/logout', 'AdminController@logout');
Route::get('admin/pages','PagesController@index')->before('auth');
Route::get('admin/pages/create','PagesController@create')->before('auth');
 lots more routes but wont post them all.

 main one
  /*
 * Frontend
 */
Route::get('/{slug}', 'HomeController@showPage');
Route::get('/', function(){
    return Redirect::to('/home');
});

A: In this case I would actually create the folder on the server and upload all the files that are normally in the /public folder to this new /public/app folder.
Then edit the public/app/index.php to reflect this.
Change:
require __DIR__.'/../bootstrap/autoload.php';

...

$app = require_once __DIR__.'/../bootstrap/start.php';

To:
require __DIR__.'/../../bootstrap/autoload.php';

...

$app = require_once __DIR__.'/../../bootstrap/start.php';

Hopefully then you shouldn't have to play around with your .htaccess or your routes file.

A: I did a similar thing and this is what I used to it:
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ app/$1 [L]


text:
Q: Can someone explain how Weinberg's definition of the affine connection for the geodesic equation matches the definition of an affine connection? Consider the geodesic equation
\begin{equation}
0=\frac{d^2 x^\lambda}{d\tau^2}+ \Gamma^\lambda_{\mu\nu} \frac{d x^\nu}{d\tau}\frac{d x^\mu}{d\tau}
\end{equation}
In Gravitation and Cosmology, on page 71 Weinberg derives this equation from the equivalence principle. In the process of doing so, he defines the Christoffel symbol as
\begin{equation}
\Gamma^\lambda_{\mu\nu} \equiv \frac{\partial x^\lambda}{\partial \xi^{\alpha}}\frac{\partial^2 \xi^\alpha}{\partial x^\mu \partial x^\nu}
\end{equation}
I am still confused as to what exactly the Christoffel symbol does mathematically. I gather it is an affine connection. And I have read many times the usual definition of an affine connection in the context of Riemannian geometry, but I still don't see how this fits the definition of an affine connection.
According to do Carmo, in Riemannian Geometry pages 49-50, he says let $\mathcal{X}(M)$ denote the set of all vector fields of class $C^{\infty}$ on $M$. Let $\mathcal{D}(M)$ denote the ring of all real-valued functions of class $C^{\infty}$ defined on $M$. An affine connection $\nabla$ on differential manifold $M$ is a mapping $\nabla : \mathcal{X}(M) \times \mathcal{X}(M) \rightarrow \mathcal{X}(M)$ which is denoted by $(X,Y) \xrightarrow{\nabla} \nabla_{X}Y$ and which satisfies the following properties:

*

*$\nabla_{fX+gY}Z = f\nabla_{X} Z+ g\nabla_{Y}Z$

*$\nabla_{X}(Y+Z) = \nabla_{X}Y + \nabla_{X}Z$

*$\nabla_{X}(fY) = f\nabla_{X}Y+ X(f)Y$

in which $X,Y,Z \in \mathcal{X}(M)$ and $f,g \in \mathcal{D}(M)$.
My Question:
Can someone explain how Weinberg's definition of an affine connection with simple partial derivatives matches do Carmo's complicated definition?
I can't seem to grasp do Carmo's definition but I know it's important. I feel like if I understood the relation between Weinberg's example and do Carmo's definition, I would be able to understand the definition of an affine connection much better. Then I could use Weinberg's explanations of this example as a start point for understanding the formal definition given by do Carmo.

A: When you consider geodesics, it might be easier to compute the Christoffel's symbols using their definition in terms of the metric, i.e.:
$$\Gamma^{\rho}_{\ \mu\nu}=\dfrac{1}{2}g^{\rho\sigma}\left(g_{\sigma\mu,\nu}+g_{\sigma\nu,\mu}-g_{\mu\nu,\sigma}\right)$$
The expression you have arises when you consider how the differentiation operator, $\partial_\mu$, behaves under a general transformation of coordinates. In particular, you should observe that $\partial_\mu A^{\nu}$ does not transform as a $(1,1)$ tensor: there is some left-over term.
$$\begin{align}
\partial_\mu A^\nu\to\partial_{\mu '}A^{\nu '}&=\left(\dfrac{\partial x^{\mu}}{\partial x^{\mu '}}\partial_\mu\right)\left(\dfrac{\partial x^{\nu '}}{\partial x^\nu}A^\nu\right)\\
&=\dfrac{\partial x^{\mu}}{\partial x^{\mu '}}\dfrac{\partial x^{\nu '}}{\partial x^{\nu}}\left(\partial_\mu A^\nu\right)+\dfrac{\partial x^\mu}{\partial x^{\mu '}}\dfrac{\partial^2 x^{\nu '}}{\partial x^\nu\partial x^\mu} A^\mu
\end{align}$$
Now, the left term transforms as we expected, but the right term is the "undesirable left-over". That's where the affine connection comes up. We need to introduce an extra element in our derivative, that will "take care" of this left-over.
We need something that cancels the rightmost term above, but has also a tensor-like part (since we need a clean overall transformation). Therefore:
$$\Gamma^{\nu '}_{\ \mu ' \lambda '}=\dfrac{\partial x^{\mu}}{\partial x^{\mu'}}\dfrac{\partial x^{\nu'}}{\partial x^\nu}\dfrac{\partial x^\lambda}{\partial x^{\lambda'}}\Gamma^{\nu}_{\ \mu\lambda}-\dfrac{\partial x^\mu}{\partial x^{\mu'}}\dfrac{\partial x^\lambda}{\partial x^{\lambda '}}\dfrac{\partial^2x^{\nu'}}{\partial x^\mu\partial x^\nu}$$
We can now define the new covariant derivative:
$$\nabla_\mu A^\nu=\partial_\mu A^\nu+\Gamma^\nu_{\ \mu\lambda}A^\lambda$$
And you can see that the second part of the Christoffel symbol will indeed cancel out the unwanted term, whereas its first part transforms correctly. In effect, $\nabla_\mu A^\nu$ does now transform as a proper $(1,1)$ tensor.

A: The upshot is that Weinberg's definition (3.2.4) on p.71 of the Christoffel symbols $\Gamma^{\lambda}_{\mu\nu}$ can only describe a local flat space (in some local coordinate neighborhood). So Weinberg's definition does not apply to the generic curved case. See also e.g. this related Phys.SE post.


text:
Q: Linear Chain CRF with Feature Function Filtering I am working on collective classification of entities and using the
CRFClassifier class for sequence labelling. I have a requirement that a
certain feature F_i should NOT be considered with certain class label C_i.
I have specified various flags in the property file for CRFClassifier (of Stanford CoreNLP) and accordingly NERFeature factory generates the features. Internally, I think
it generates total L*N binary feature functions (indicator functions) where, L=#classLabels and N=#features. Out of total functions in this cross product, I do not want to consider few pairs of . What is the best way to achieve this?
Note: The L*N functions are I think generated by - getObjectiveFunction at
following location.
CRFClassifier {
    protected double[] trainWeights(int[][][][] data, .......) {
              CRFLogConditionalObjectiveFunction func =
getObjectiveFunction(data, labels);
    }
}

EHat protected variable in Class CRFLogConditionalObjectiveFunction
 contains the empirical counts for these L*N features

For the  combination that I do not want in my classifier,
Will it be okay to explicitly set the empirical count to 0 for these
combination (in EHat variable) before I call the Minimizer? Will it be same as saying that I do not have that  combination in my model?
Does Mallet provide a way for doing this?


text:
Q: bootstrap align nav li with navbar-brand I'm trying to get the nav bar link to align centrally with the nav brand
here is my code so far
http://codepen.io/anon/pen/pivwh
for some reason the contact is lower and I can't get the links to align to the right.
Thanks.

A: Try this..
.navbar-nav {
  margin-top: 60px;
  font-size: 24px;
  text-transform: uppercase;
}

http://codepen.io/anon/pen/GAhwz

A: Is this what you're looking for?
.nav {
  float:right;
}

.nav li a{
  line-height: 99px;
}

.nav li {
  font-size: 24px;
  text-transform: uppercase;
}

http://codepen.io/anon/pen/FtyCg


text:
Q: What #if preprocessor directive to determine if OS is WIN 7 SP1? I'd like conditional compilation based on whether the compiling machine is running Windows 7 SP1 or not.
We have a workaround for http://support.microsoft.com/kb/2517589 but I don't want to check the code in unless it is guarded by an #ifdef _WIN7_SP1 otherwise the other devs won't be able to compile it on their non win7-sp1 machines.
I've had a bit of a google but couldn't find anything useful.

A: You don't.  Things in the environment of the build machine generally don't pollute compilation like that. (Imagine if that happened and what effects it would cause on reproducibility of builds.)
If you really need to, I'd instead have your build system (make, Visual Studio, whatever) execute a program that checks the current Windows version and fails as necessary (or possibly your build system can determine this already).  Based on that, you then could conditionally make own WIN7_SP1 definition via a command-line argument to your compiler.


text:
Q: Bootstrap mobile navigation center it's content I have problem with my bootstrap navigation menu for @media (max-width: 767px) screens. The problem is that I'm floating the ICON-BAR for mobile to the right and I'm trying to center in the middle of the page the content ( page links Home, Pages etc. ). So my idea is to put the icon bar on the right side of the page and when the icon-bar is pressed to scroll down ( centered menu in the middle of the page ).

body { background: red; }
.navbar { float: left; color: #000; margin: 40px 80px 0 0; }
.navbar a { color: #fff; margin-bottom: 3px; }
.navbar a:hover { background: none !important; margin-bottom: 0; border-bottom: 6px solid #11749e; }

.navbar-toggle .icon-bar { display: block; width: 28px; height: 4px; background-color: #cccccc; border-radius: 1px; }

@media (max-width: 767px) {
 .navbar { float: right; }

}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
        Toggle navigation

      </button>

Home

Pages

Features

Extensions

Tutorials

Contact Us


text:
Q: Can not clear rewrite rule in subfolder I have this rule in web.config in the root of website which redirects to HTTPS:
<rewrite>
<rules>
<rule name="HTTPS" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
    <match url="*" negate="false" />
    <conditions logicalGrouping="MatchAny">
        <add input="{HTTPS}" pattern="off" />
    </conditions>
    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>

In a subfolder I have separate Config file and I want to clear redirectiong to HTTPS but this folder also redirects to HTTPS:
    <rewrite>
        <rules>
            <clear />
        </rules>
    </rewrite>

A: You cannot do that. Rules can be stored defined in web.config only. You can have them there or provided a path to the file where the rules are stored (but it's still defined in the web.config) like this:
<system.webServer>
    <rewrite>
        <rules configSource="App_Config\RewriteRules.config" />
        <outboundRules configSource="App_Config\OutboundRewriteRules.config" />
        <rewriteMaps configSource="App_Config\RewriteMaps.config" />
    </rewrite>
</system.webServer>

If you want certain URLs not to be redirected to HTTPS then you need to create a smart rule which will detect this (or have set of rules).


text:
Q: Why two init methods are called in subclassed Objective-C (UIKit) object in Swift? I came across this strange behaviour when I subclassed UIBarButtonItem in Swift. I wrote custom init method that called super.init(customView: ...)
The problem was that badgeLabel text never updated, so I started exploring what is going wrong.
First I discovered that two init methods are called, my custom one "init(target: AnyObject, selector: Selector)" and after that the basic one also "init()"
What was really strange is that badgeLabel (constant) block was also executed two times for each of the init methods. So it happened that I displayed a badge label that was created at first init call, but badgeLabel variable was actually holding reference to a label that was created at second init call and never displayed or added to a view.
Not sure if Apple intended this kind of behaviour or its just necessary strangeness/evil for Swift and Objective-C working together. Any ideas of how to elegantly solve this problem?
Here is the code:
@objc class MYChatBarButton: UIBarButtonItem {

    let badgeLabel: UILabel = {
        let bl = UILabel(frame: CGRectMake(0, 0, 15, 15))
        bl.backgroundColor = UIColor.clearColor()
        bl.text = "0"
        ...
        return bl
    }()

    override init() {
        super.init()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    init(target: AnyObject, selector: Selector) {

        let badgeView = UIView(frame: CGRectMake(27, 2, 15, 15))
        badgeView.backgroundColor = UIColor(hexString: "ff7d00", andAlpha: 1.0)
        badgeView.layer.cornerRadius = badgeView.frame.size.width/2
        badgeView.userInteractionEnabled = false

        badgeView.addSubview(badgeLabel)

        let button = UIButton.buttonWithType(.Custom) as UIButton
        button.frame = CGRectMake(0, 0, 35, 44)
        button.addTarget(target, action: selector, forControlEvents: .TouchUpInside)
        button.tintColor = UIColor.whiteColor()
        button.setImage(UIImage(named: "chat_icon")?.imageWithRenderingMode(.AlwaysTemplate), forState: .Normal)
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 7, bottom: 5, right: 0)

        button.addSubview(badgeView)

        super.init(customView: button)

        updateBadge()

    }

    func unreadChatMsgCountDidChange(n: NSNotification) {
        updateBadge()
    }

    func updateBadge() {
        let unwatchedTotal = ...
        badgeLabel.text = "\(unwatchedTotal)"

        if unwatchedTotal > 0 {
            badgeLabel.hidden = false
        } else {
            badgeLabel.hidden = true
        }

    }

}


text:
Q: Django Celery configuration for multiple servers We have two machines in production ,in both celery is running ? Does it will execute periodic task twice? If yes , then what is the best way to configure it(because there are both asynch and periodic task both)

A: You execute periodic tasks twice only if you schedule them twice.
This means that you can run multiple workers a the same time but not more than one scheduler process.
For more informations have a look at the docs here


text:
Q: C Pointers: Exception Thrown: Read access violation I am writing a program in C that plays the game Craps. After my first roll, when I either land the point (win) or lose, the program just ends instead of calling is_win or is_loss.
But if it calls is_win or is_loss on my first roll, everything works fine.
I'm fairly certain this has something to do with the pointer pbal. I've been getting errors in the debugger saying unable to read memory, also Exception Thrown: Read access violation. I am still fairly new to pointers so I'm assuming this is the root cause of the problem.
# include "header.h"

int print_menu(void) {
    int choice = 0;
    printf("\n1. Enter balance\n2. Play game\n3. Get rules\n4. End game");
    printf("\nEnter which you would like to do: ");
    scanf("%d", &choice);
    return choice;
}

void print_rules(void) {
    printf("\nFirst Roll: If your die roll adds to 7 or 11, you win.\nIf it adds to 2, 3, or 12, you immediately lose.\nIf it adds to another number, that number becomes your 'point'");
    printf("\nSecond Roll: If your die roll adds to your point, you win. If it adds to 7, you lose.\nKeep rolling until you get one of these.\n\n");
}

int get_balance(balance) {

    printf("\nEnter how much money you would like to add (whole dollars): ");
    scanf("%d", &balance);
    return balance;
}

int prompt_bet(balance) {
    int bet = 0;
    do {
        printf("\nEnter how much you would like to bet for this game: ");
        scanf("%d", &bet);
        } while (bet > balance); //repeats until its false that bet>bal
    return bet;
}

int roll_dice(void) {
    srand((unsigned int)time(NULL));

    int enter = 1;
    printf("\nEnter a 0 to roll your dice: ");
    scanf("%d", &enter);

    int die1 = rand() % 6 + 1;
    int die2 = rand() % 6 + 1;
    int dice = die1 + die2;
    printf("You rolled a %d and a %d, with a total of %d.\n", die1, die2, dice);
    return dice;
}

int calc_first_roll(int dice, int bet, int balance, int * pbal) {
    int result0 = 0;

    if (dice == 7 || dice == 11) {
        is_win(bet, balance, pbal);
        }

    else if (dice == 2 || dice == 3 || dice == 12) {
        is_loss(bet, balance, pbal);
        }

    else {

        printf("Your point is %d", dice);
        int point = dice;

        int done = 1;
        do {
            dice = roll_dice();
            done = calc_other_rolls(point, dice, balance, bet, *pbal);

        } while (!done);

        }

    return result0;
}

void is_win(int bet, int balance, int *pbal) {

    /* the pointer *pbal is pointing to mainbalance. I had to pass it
    through everything to get it to affect mainbal the way I wanted it to.
    Think of mainbalance as the permanent memory for keeping their bets & money right,
    and int balance is just a messenger that doesn't get in the way of me trying
    to use a pointer on mainbalance. */

    *pbal = balance + bet;
    printf("You win! Your new balance is %u\n", *pbal);
}

void is_loss(int bet, int balance, int *pbal) {
    *pbal = balance - bet;
    printf("You lost. Your new balance is %u\n", *pbal);
}

int calc_other_rolls(int point, int dice, int balance, int bet, int *pbal) {
    int done = 0;
    if (dice == 7) {  //Goes straight to is_l / is_w instead of looping back to calc_first

        is_loss(bet, balance, *pbal);
        done = 0;
    }

    else if (dice == point) {
        is_win(bet, balance, *pbal);
        done = 0;
    }

    else {
        done = 0;

    }
    return done;
}

# include "header.h"

int main(void) {
    int mainbalance = 0;
    int choice = 0;
    int *pbal = &mainbalance;

    do {
        choice = print_menu();

        if (choice == 1) {
            mainbalance = get_balance();
            printf("Your balance is: %d\n", mainbalance);
            choice = 8; //reprints menu
            }

        if (choice == 3) {
            print_rules();
            choice = 8;
            }

        if (choice == 4)
            exit(1);

        if (choice == 2) {

            int bet = prompt_bet(mainbalance);
            int dice = roll_dice();
            int x = calc_first_roll(dice, bet, mainbalance, pbal);

            choice = 8;

            }

    } while (choice > 4 || choice < 1); //keeps running code until test becomes false.

    return 0;
}

A: In this section:
if (dice == 7) {  //Goes straight to is_l / is_w instead of looping back to calc_first

    is_loss(bet, balance, *pbal);
    done = 0;
}

else if (dice == point) {
    is_win(bet, balance, *pbal);
    done = 0;
}

You're not passing is_loss and is_win the pointer, you're passing the integer value, that pbal points to. * outside of a declaration is always dereferencing.
So if calc_other_rolls gets int *pbal as an argument and you wanna pass it to another function that takes int * then you should do func(pbal) and not func(*pbal), since the second one passes the value not the pointer.
Edit: As @hollow pointed out, this gets flagged by the compiler if you enable warnings, so use them.


text:
Q: Invalid update: invalid number of rows in section 0 error occur This is my struct
struct CommunityListRM: Codable {
    let status       : Bool?
    let communityList: [CommunityList]?

    struct CommunityList: Codable {
        var id              : String?
        var user_id         : String?
        var icon            : String?
        var nickname        : String?
        var profile_image   : String?
        var content         : String?
        var image_1_url     : String?
        var image_2_url     : String?
        var image_3_url     : String?
        var image_4_url     : String?
        var image_5_url     : String?
        var image_ratio1    : String?
        var image_ratio2    : String?
        var image_ratio3    : String?
        var image_ratio4    : String?
        var image_ratio5    : String?
        var comment_qty     : String?
        var like_qty        : String?
        var date            : String?
        var created_at      : String?
        var updated_at      : String?
        var like_it         : String?
    }
}

I want to insertRows like instagram feeds
var posts        : [CommunityListRM.CommunityList] = []

NetworkService().request(.communityList, params, header) { [self] (response: DataResponse<CommunityListRM,AFError>) in
    switch response.result {
        case .success(let data):
        if let nComList = data.communityList {

           self.posts.append(contentsOf: nComList)
           print("selfpostcount\(self.posts.count)")
           self.tableview.beginUpdates()
           self.tableview.insertRows(at: [IndexPath(row: self.posts.count - 1, section: 0)], with: .none)
           self.tableview.endUpdates()
       }
    }
}

If i tried this code error occur
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (10) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out). Table view: <UITableView: 0x104125c00; frame = (0 0; 414 721); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x281a62b20>; layer = <CALayer: 0x2814a0b40>; contentOffset: {0, 0}; contentSize: {414, 0}; adjustedContentInset: {0, 0, 0, 0};
Help me plz

A: First of all begin-/endUpdates() is pointless for a single insert/delete/move operation.

The error occurs because you are adding multiple items to the array but insert only one row. You have to specify all index paths.

*

*If posts is empty map all indices of posts to index paths
self.posts.append(contentsOf: nComList)
let indexPaths = self.posts.indices.map{IndexPath(row: $0, section: 0)}
self.tableview.insertRows(at: indexPaths, with: .automatic)

or – as you don't specify any animation – just reload the table view
self.posts.append(contentsOf: nComList)
self.tableview.reloadData()

*If posts is not empty count the items in the array before and after appending the items to get start and end index
let startIndex = self.posts.count
self.posts.append(contentsOf: newArray)
let endIndex = self.posts.count
let indexPaths = (startIndex..<endIndex).map{IndexPath(row: $0, section: 0)}
self.tableview.insertRows(at: indexPaths, with: .automatic)


text:
Q: Calling a Separate Function on Double Click JQuery I am using the JQuery Double Click function which appends a string of text on a div when the double click happens on that div. What I want to do is make the text append be a part of a separate function which gets called when the double click happens.
My current code is:
$(".class").dblclick(function() {

   $(".class").append(text);

});

What I want to do is have a separate function instead of $(".class").append(text); and then define this function using this line somewhere else in the code. How could I replace this line $(".class").append(text); with a function and then define it somewhere else?
Hope this makes sense, thank you!

A: $(this) function will be help you for using another method.
$('.class').dblclick(function () {
    appendText($(this).text());
})

function appendText(text) {
    console.log(text.trim());
}

A: Simply create a new function and call the  $(".class").append(text); inside of it, then call this function on the Double Click function. Something like this:
$(".class").dblclick(function() {
    appendText();
});

function appendText(){
    $(".class").append(text);
}

Hope this works for you.


text:
Q: Moving MySQL files from Mac to Linux I had a mysql server running on a Mac. Unfortunately, the Mac died. However, I got a backup. I am now trying to restore the server on a Linux machine.
I have moved the mysql files located in /usr/local/var/mysql on the linux.
I gave full 777 permissions to the directly on linux to make sure that I have no permissions issues.
When I try to run the MySQL server, it fails and I get this error in the logs:
InnoDB: Error: log file ./ib_logfile0 is of different size 0 50331648 bytes
InnoDB: than specified in the .cnf file 0 5242880 bytes!

When I delete the log files (ib_logfile0, ib_logfile1), I get: http://pastebin.com/rYMti8DK
Do you have any idea how I can restore my database correctly?

A: You need to use the same MySQL configuration on the Linux system as you used on the Mac. The error message in your question comes because InnoDB log file settings are different in your Linux.


text:
Q: Limit to n number of tests At work we noticed the other day that we have 700 or so unit test cases, so our boss decided to offer an incentive for the author of the 1000th unit test that makes it to production.
Is there a way I can determine which unit test method the 1000th test is? The --debug flag doesn't provide numeration or an obvious option like --limit.

A: Assuming you're running a Unix based environment, you could split up the debug output from PHPUnit to achieve this as it doesn't appear that there is an inbuilt option to limit the number of tests, or specify a certain test in a suite by number.
To highlight the 5th test:
$ phpunit --debug | grep "Starting test" | sed '5q;d'

Example output:
Starting test 'YourTestClass::testYourTestMethod with data set #0 (1, true)'.


text:
Q: vhdl ram module and use of registers Ok another question in VHDL. Below is my code. Suppose that I want my input stored in ram. And lets say I want to add two of them. (do not give emphasis on it, later on it will be replaced). This is my code:
library IEEE;
use IEEE.STD_LOGIC_1164.all;
USE ieee.numeric_std.ALL;

use work.my_package.all;

entity landmark_1 is
  generic
        (data_length :integer := 8;
        address_length:integer:=3 );
        port ( clk:in std_logic;
        vin:in std_logic;
        rst:in std_logic;
        flag: in std_logic;
        din: in signed(data_length -1 downto 0);
        done: out std_logic
        );
end landmark_1;

architecture TB_ARCHITECTURE of landmark_1 is

component ram IS
    generic
    (
        ADDRESS_WIDTH   : integer := 4;
        DATA_WIDTH  : integer := 8
    );
    port
    (
        clock           : IN  std_logic;
        data            : IN  signed(DATA_WIDTH - 1 DOWNTO 0);
        write_address           : IN  unsigned(ADDRESS_WIDTH - 1 DOWNTO 0);
        read_address            : IN  unsigned(ADDRESS_WIDTH - 1 DOWNTO 0);
        we          : IN  std_logic;
        q           : OUT signed(DATA_WIDTH - 1 DOWNTO 0)
    );
end component;

signal inp1,inp2: matrix1_t(0 to address_length);
signal out_temp: signed(data_length-1 downto 0);
signal k:unsigned(address_length-1 downto 0);

signal i: integer range 0 to 100:=0;
begin

read1:ram generic map( ADDRESS_WIDTH=>address_length, DATA_WIDTH=>data_length) port map (clk,din,k,k,vin,out_temp);
inp1(i)<=out_temp;

process (clk)
  begin
  if (clk'event and clk='1') then
    if (flag='1') then out_temp<=inp1(0)+inp1(1);
    end if;
  end if;
end process ;

end TB_ARCHITECTURE;

Below are my questions:

*

*Why to use that ram and not just do inp(i)<=din; . I think that it will help synthesizer understand that this is a ram, but what else? Moreover, do I need inp1 registers. And if I a going to use them, again why use ram as an intermediate?

*If inp1 is unnecessary, how I am going to fetch these two elements in my process? I mean I need something like ram(address1)+ram(address2), right?

Below is my ram_code:
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;

ENTITY ram IS
    GENERIC
    (
        ADDRESS_WIDTH   : integer := 4;
        DATA_WIDTH  : integer := 8
    );
    PORT
    (
        clock           : IN  std_logic;
        data            : IN  signed(DATA_WIDTH - 1 DOWNTO 0);
        write_address           : IN  unsigned(ADDRESS_WIDTH - 1 DOWNTO 0);
        read_address            : IN  unsigned(ADDRESS_WIDTH - 1 DOWNTO 0);
        we          : IN  std_logic;
        q           : OUT signed(DATA_WIDTH - 1 DOWNTO 0)
    );
END ram;

ARCHITECTURE rtl OF ram IS
    TYPE RAM IS ARRAY(0 TO 2 ** ADDRESS_WIDTH - 1) OF signed(DATA_WIDTH - 1 DOWNTO 0);

    SIGNAL ram_block : RAM;
BEGIN
    PROCESS (clock)
    BEGIN
        IF (clock'event AND clock = '1') THEN
            IF (we = '1') THEN
                ram_block(to_integer(unsigned(write_address))) <= data;
            END IF;

            q <= ram_block(to_integer(unsigned(read_address)));
        END IF;
    END PROCESS;
END rtl;

3.can anyone tell me why the q (output) is estimated one clock later?
EDIT: To sum up,I was told that I should use a ram and this is my implementation. The question is what I have gained by changing my inp1(i)<=din; when I inserted the ram model. And there fore how can I use it? (before using the ram I waws just wrote inp1(i)+inp2(i+1) for example).
EDIT2: PACKAGE FOR TYPES.
library IEEE;
use IEEE.std_logic_1164.all;
use ieee.numeric_std.all;

package my_package is
    type matrix1_t is array(integer range<>) of signed(7 downto 0);
    type big_matrix is array(integer range<>) of signed(23 downto 0);
    type matrix2d is array (integer range<>) of big_matrix(0 to 3);

end my_package;

A: You aren't setting i to anything other than 0 so you will only ever assign to inp1(0).
Assuming the RAM is there to store many values, and you need to read two of them every clock cycle in order to do your adding, you need 2 RAM blocks (or a single dual-ported one) and then put the two addresses into those RAM blocks.  The next cycle the two values you want will appear on the data outputs and you can sum them.
The clock-cycle delay you observe is in the nature of synchronous RAMs (which is what most FPGAs have for their "large storage") - some can create smaller asynchronous RAMs where the data appears a short delay after the read address changes, completely asynchronously to the clock.

A:
Why to use that ram and not just do inp(i)<=din;

In real world designs you use RAMs to store large amounts of data because they are smaller (physically, on the chip) that arrays of flip flops. During the synthesis process the RAM is replaced by one from your vendor's library. This RAM looks rather small, but I'm guessing you've been told to use one as an exercise.

Moreover, do I need inp1 registers. And if I a going to use them, again why use ram as an intermediate?

I'm not quite sure what imp1 is, as I don't know what a matrix_t is, but I'm guessing it's a register version of the RAM. In which case it's redundant.

If inp1 is unnecessary, how I am going to fetch these two elements in my process? I mean I need something like ram(address1)+ram(address2), right?

...and there's the real issue. You need to ask yourself 'If you can't read more that one thing in a cycle, how do you add two numbers?'

can anyone tell me why the q (output) is estimated one clock later?

Because that's how RAMs work. You apply an address in one cycle, and the data appears some cycles later (normally one, but not always)
These are real issues that you'll face in real designs. RAMs are necessary because of their smaller size. You need to know the issues that surround using them and how to work with them.

A: I assume you're trying to represent a RAM with the signal inp1. However, the signal that represents the RAM is ram_block in your ram entity.
You are using the entity in a strange way because you connect the signal k as read and write address. There are two problems with that. Firstly, k doesn't seem to be driven anywhere in your design. Secondly, you probably don't want the two addresses to be the same.
I assume you want to write some values to the RAM and at the same time read two values and add them up. I suggest you use a process that sets a write address and a process that sets a read address. You also need at least one register with the width of the RAM output. The first value you read from the RAM is stored in that register. Then you add the value in that register and the second value read from the RAM and store the result in a different register.


text:
Q: Mocked moto rds DB instance is not reading from the EnableIAMDatabaseAuthentication parameter I have this test that I'm trying to check for but it doesn't seem like EnableIAMDatabaseAuthentication is being passed to moto
@mock_rds
def test_iam_database_authentication_enabled(self):
    print(self.client.create_db_instance(
        DBInstanceIdentifier='db-master-1',
        AllocatedStorage=10,
        Engine='postgres',
        DBInstanceClass='db.m1.small',
        EnableIAMDatabaseAuthentication=True,
        MasterUsername='root',
        MasterUserPassword='hunter2',
        Port=1234,
    ))

{'DBInstance': {'DBInstanceIdentifier': 'db-master-1',
  'DBInstanceClass': 'db.m1.small', 'Engine': 'postgres',
  'DBInstanceStatus': 'available', 'MasterUsername': 'root', 'Endpoint':
  {'Address': 'db-master-1.aaaaaaaaaa.us-east-2.rds.amazonaws.com',
  'Port': 1234}, 'AllocatedStorage': 10, 'InstanceCreateTime':
  datetime.datetime(2020, 1, 13, 13, 1, 10, 665000, tzinfo=tzutc()),
  'PreferredBackupWindow': '03:50-04:20', 'BackupRetentionPeriod': 1,
  'DBSecurityGroups': [], 'VpcSecurityGroups': [], 'DBParameterGroups':
  [{'DBParameterGroupName': 'default.postgres9.3',
  'ParameterApplyStatus': 'in-sync'}], 'PreferredMaintenanceWindow':
  'wed:06:38-wed:07:08', 'MultiAZ': False, 'EngineVersion': '9.3.3',
  'AutoMinorVersionUpgrade': False, 'ReadReplicaDBInstanceIdentifiers':
  [], 'LicenseModel': 'general-public-license',
  'OptionGroupMemberships': [{'OptionGroupName': 'default.postgres9.3',
  'Status': 'in-sync'}], 'PubliclyAccessible': False, 'StatusInfos': [],
  'StorageType': 'gp2', 'StorageEncrypted': False, 'DbiResourceId':
  'db-M5ENSHXFPU6XHZ4G4ZEI5QIO2U', 'CopyTagsToSnapshot': False,
  'DBInstanceArn': 'arn:aws:rds:us-east-2:1234567890:db:db-master-1',
  'IAMDatabaseAuthenticationEnabled': False}, 'ResponseMetadata':
  {'RequestId': '523e3218-afc7-11c3-90f5-f90431260ab4',
  'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'},
  'RetryAttempts': 0}}

Am I doing something wrong trying to pass the EnableIAMDatabaseAuthentication param? It should be setting: IAMDatabaseAuthenticationEnabled

A: I can confirm that the moto library itself is not passing the EnableIAMDatabaseAuthentication param from this line of code in moto library.
However, I drew the conclusion from the link above, rather than looking at the return value of the create_db_instance function because I took a look at boto3 rds reference, its response value doesn't return EnableIAMDatabaseAuthentication anyways.
You didn't do anything wrong, that value just doesn't exist in the response from boto3. Even if one day moto does pass in that parameter, it will not show up until boto3. One example of that is the MasterUserPassword param, which moto does pass it, but boto3 doesn't include that in the response.


text:
Q: Is there any PhoneGap View? I can create an activity (extending DroidGap class), but is there any PhoneGap View to use it together with my own views in an ordinary activity? I need to use an xml layout for my activity and PhoneGap features together.
Thanks

A: It is being worked on!
Check out this early work and pls give some feedback https://github.com/infil00p/callback-android/tree/cordova_view


text:
Q: Run the script after error in Laravel I want am using API of Twitter and I am getting the error no 202 and 32 and getting some error massage.
I want to continue the script after getting the error .
Is there any way in Laravel to do this

A: Probably the Twitter API is throwing an exception.. You must catch it and continue executing the script.
try {
   $twitterApi->aMethod($someParams);
} catch (Twitter_Exception $e) {
   // some log of the error message
}

// continue the script here


text:
Q: Find the type of the equation Given

$4u_{xx} +2u_{yy} - 6u_{zz} +6u_{xy} + 10u_{xz} +4u_{yz} + 2u =0$

I need to find the type of the equation, for that i tried to get the canonical form
So, turn into lambdas
$4\lambda_1^2 + 2\lambda_2^2 - 6\lambda_3^2 + 6\lambda_1\lambda_2 + 10\lambda_1\lambda_3 + 4\lambda_2\lambda_3 = 0$
from here i can't get the form which is looks like
$\pm\xi^2 \pm \eta^2 \pm \zeta^2 =0$
any help or advice is much appreciated

A: The equation
$$\sum_{i,j=1}^na_{ij}u_{x_ix_j}+a(x,u,\nabla u)=0$$
can be reduced to canonical form by applying the non singular linear transformation  $\xi=B^Tx$, where B is a matrix such that the transformation $y=B\eta$ reduces the quadratic form $\sum_{i,j=1}^na_{ij}y_iy_j$ to canonical form.
Example. Reduce to canonical form
$$4u_{xx} +2u_{yy} - 6u_{zz} +6u_{xy} + 10u_{xz} +4u_{yz} + 2u =0.$$
$$4\lambda_1^2 + 2\lambda_2^2 - 6\lambda_3^2 + 6\lambda_1\lambda_2 + 10\lambda_1\lambda_3 + 4\lambda_2\lambda_3=
\frac{(4\lambda_1+3\lambda_2+5\lambda_3)^2}{4}-\frac{(\lambda_2+7\lambda_3)^2}{4}$$
Let
$$y_1=\frac{4\lambda_1+3\lambda_2+5\lambda_3}{2},\;y_2=\frac{\lambda_2+7\lambda_3}{2},\;y_3=\lambda_3$$
$\Rightarrow$
$$\lambda_1=\frac12y_1-\frac32y_2+4y_2,\;\lambda_2=2y_2-7y_2,\;\lambda_2=y_3$$
$\Rightarrow$
$$B^T=\begin{pmatrix}\frac{1}{2} & -\frac{3}{2} & 4\\
0 & 2 & -7\\
0 & 0 & 1\end{pmatrix},\quad B=\begin{pmatrix}\frac{1}{2} & 0 & 0\\
-\frac{3}{2} & 2 & 0\\
4 & -7 & 1\end{pmatrix}$$
Transform to canonical form is:
$$\xi=\frac{x}{2},\;\eta=-\frac{3}{2}x+2y,\;\zeta=4x-7 y+z$$
After reducing we get
$$u_{\xi\xi}-u_{\eta\eta}+2u=0$$

A: Your problem is one of diagonalizing a quadratic form. There are several methods available for doing this. You might for instance compute eigenvalues and eigenvectors of the associated symmetric matrix $$Q = \begin{bmatrix}4&3&5\\3&2&2\\5&2&-6\end{bmatrix}.$$ In this case, we're pretty lucky because the characteristic polynomial is fairly "nice:" $\lambda^3-66\lambda$, from which the eigenvalues are $0$ and $\pm\sqrt{66}$. This gives you the information you need to classify the equation, which only requires knowing the spectrum of the quadratic form. To proceed onto the canonical form, you'll need to find a set of corresponding eigenvectors, which doesn't take too much more work.
In practice, the eigenvalues and eigenvectors aren't usually this nice, but there are other ways to diagonalize the quadratic form. Another common method is successively completing squares. One possible result of doing this is $$\frac14\left(4\lambda_1+3\lambda_2+5\lambda_3\right)^2-\frac14\left(\lambda_2+7\lambda_3\right)^2.$$ The spectrum of these terms matches the spectrum obtained from the eigenvalues, which we expect.
If you're not good at completing squares, there's an entirely mechanical algorithm described here for diagonalizing a quadratic form. Omitting the gory details of the computation, for this problem the algorithm eventually produces the augmented matrix $$\left[\begin{array}{ccc|ccc}4&0&0 & 1&0&0 \\ 0&-4&0 & -3&4&0 \\ 0&0&0 & -64&112&-16 \end{array}\right].$$ From the diagonal of the left-hand side, we get the same spectrum as with the previous two methods. To find the canonical form, we must then invert the right-hand side, which produces the diagonalization $$4\left(\lambda_1+\frac34\lambda_2+\frac54\lambda_3\right)^2-4\left(\frac14\lambda_2+\frac74\lambda_3\right)^2$$ that happens to be the same as the one obtained by completing the squares above.


text:
Q: How to put a JavaScript function in an HTML onclick Hello I would like to put my JavaScript function in an onclick html because I have several exercises on my page
<button type="button" onclick="formatTime()">Click</button>

A: Your button should call the javascript function formatTime() onclick, there is nothing wrong with the HTML. Does the Chrome/Firefox Developer Console output any errors on click?
See here for an example.
<button type="button" onclick="foo()">click</button>
<script>
function foo() {
    alert('hello world');
}
</script>


text:
Q: Compare array c# Create a method named ArrayCompare that compares between two arrays and returns a
boolean indicating whether they contain exactly the same elements or not. Its input should be
two integer arrays a and b. Its output should be a boolean, where it will return true if a and b
contain the same elements and false otherwise
Hello, I am new to c#, and I would like to know how this is done. I read up some documents and I can only come up with this.
    static bool ArrayCompare(int [] i , int [] j)
    {
        if (i.Length == j.Length)
        {
            for (int o = 0; o < i.Length; o++)
            {

                //I am stuck here
                return false;
            }
        }
        return false;
    }

A:  static bool ArrayCompare(int [] i , int [] j)
    {
        if (i.Length == j.Length)
        {
            for (int o = 0; o < i.Length; o++)
            {
                if(i[o]!=j[o])
                   return false;
            }
            return true;
        }
        return false;
    }

A: You can check using the code blow
int[] array1 = { 1, 2, 2 };
int[] array2 = { 1, 2, 2 };

bool check = array1.SequenceEqual(array2);

A: This should work!
static bool ArrayCompare(uint [] a, uint [] b)
{
    bool equal = true;
    if(a.Length== b.Length)
    {
        for(int i = 0,j=0; i < a.Length; ++i,++j)
        {
            if (a[i] != b[j])
            {
                   equal = false;
                   break;
           }
        }
    }
    return equal;
}

A:     static bool ArrayCompare(int[]a, int [] b)
    {

        if(a.Length == b.Length)
        {
            for(int i = 0; i < a.Length; i++)
            {
                if (a[i] == b[i])
                {
                    if(a[a.Length - 1] == b[b.Length - 1])
                    {
                        return true;
                    }
                }
                break;

            }
        }

        return false;

    }

This method takes in two int arrays as parameters, we are then checking to first make sure that both the arrays are the same length before we loop. In the for loop we are checking to make sure that if the current index of the first array is the same as the current index of the second array is the same. If it is, we get the to last index of both arrays, and if the same we return true, if the indexes are not the same we return false. We can then create two arrays and console out the method with the two arrays as parameters.


text:
Q: Convert array of strings to array of numbers I have a jQuery array ["3434", "3433"]
And I would like to make it like [3434, 3433]

A: No need for jQuery. Supposing you're sure they're all numbers (that is, we're not checking for errors), you can map them with Number, which converts them from string to numbers.
["3434", "3433"].map(Number);

Considering that Number returns NaN in case of error, you may then want to filter the result to remove undesired elements.

let nums = ["3434", "3433", "foo"].map(Number).filter(n => !isNaN(n));
console.log(nums);


text:
Q: None of my apps are keeping a list of recent documents? Example:
If I open an image in Preview, the "File/Open Recent" menu lists the name of the file.
If I then close the file, but still leave Preview running, the "Open Recent" menu still lists the file.
If I quit Preview, the "Show Recents" menu does not show any files.
If I reopen Preview, the "Open Recent" menu does not show any files.

I have a feeling this is a permissions problem, but repair permissions has not helped.
In Console, Preview is reporting the following error upon opening:
"29/02/2012 14:45:57.183 com.apple.Preview.TrustedBookmarksService: Failure to de-serialize bookmark data file."
I'm using Preview as an example here, but it holds for every app - whether they are bundled or downloaded - on my system.
System Preferences/Appearance/Number of Recent Items is set to 10.
I am running Lion 10.7.3 on an iMac 12,1 with a dual SSD and HDD internal drive setup.

A: I would trash your preview .plist file located at:
~/Library/Preferences/com.apple.Preview.plist

Restart Preview, and it should create a new one.  It sounds corrupted.

A: This worked for me:

*

*Turn on the Mac whilst holding down ⌘+R in order to boot from the recovery partition.

*On the top menu, click Utilities, then click Terminal.

*Type resetpassword and press ↩.

*Click on your main hard drive.

*In the dropdown box under Select the user account make sure to select your username.

*Underneath where it says Reset Home Directory Permissions and ACLs, click the Reset button.

*Press ⌘+Q to quit the Reset Password application.

*Press ⌘+Q again to quit the Terminal.

*Press ⌘+Q one more time and click Restart.

*Click Mac OS X Utilities in the top left of the screen and click the Restart button.

I got the solution over at Apple Discussions:

I'm not sure where that list is stored, but I agree with your feeling that this is a
permissions problem.  However, repairing permissions with Disk Utility is not likely to
help.  That only repairs certain things, and doesn't affect the user folder at all, which is likely to be where the problem lies.  You could try resetting the permissions
on your home folder.


text:
Q: MySQL outer join: why does selecting records in ON gives different results than selecting in WHERE? Why do these two queries give different results?
This query gives all records regardless of the value of the deleted column.  It's as if that selection is ignored:
SELECT mcm.record_id, mc.category, mc.category_id, mc.deleted, mcm.member_id
FROM mailing_category mc
    LEFT OUTER JOIN mailing_category_membership mcm
    ON mc.category_id = mcm.category_id
        AND mcm.member_id = 6346
        AND mc.deleted = 'false'
WHERE mcm.record_id IS NULL

This query only selects records where the deleted column is false, which is what I want.
SELECT mcm.record_id, mc.category, mc.category_id, mc.deleted, mcm.member_id
FROM mailing_category mc
    LEFT OUTER JOIN mailing_category_membership mcm
    ON mc.category_id = mcm.category_id
        AND mcm.member_id = 6346
WHERE mcm.record_id IS NULL
        AND mc.deleted = 'false'

Why do the two queries give different results?  I'm using MySQL version 5.5.37.

A: The logic for a left outer join is to take all the records from the first table.  If there is one or more matches in the second table, then include those matches in the result set.  If there are no matches, then still include the original record in the result set, with all the other columns being NULL.  A match means that the on clause evaluates to true.
This applies to filtering on the first table.  So in this expression:
FROM mailing_category mc LEFT OUTER JOIN
     mailing_category_membership mcm
     ON mc.category_id = mcm.category_id AND mcm.member_id = 6346 AND
        mc.deleted = 'false'

You think that you are filtering on mc.deleted = 'false'.  However, this just means that there is no match (because the on clause evaluates to false).  The record is still kept, because that is the logic of the left outer join.
When you move the condition on mc to the where clause, the filtering happens as you expect it to.

A: Because when an OUTER JOIN is being performed the filtering occurs at different times during query processing
WHERE clauses are performed on the result of the OUTER JOIN.
ON clauses are performed on the input to the OUTER JOIN.
This is also true for an INNER JOIN; but in that case the different processing times still identical results.

A:

It's as if that selection is ignored:

Because you are using an outer join.
A left outer join means return all rows from the first table and if there are rows in the second table that match the join criteria, then line them up in the same row.  Then apply the WHERE clause.  If they don't match, you still get a row, just with NULL values for the second table.
Put another way, an outer join never dis-qualifies rows from being returned.  A WHERE clause will, of course, as will an inner join.
You might ask, what effect do join conditions have for outer joins then if they don't disqualify rows?  Simple, they specify, for a given row on the right, if it should line up with a row on the left.
So you think the filter is not being applied.  It is applied, in fact, to choosing rows from the second table to go with the first.

A: with a left join, all records from the table mailing_category will be returned (then filtered by the WHERE query), regardless of whether the join found any rows in mailing_category_membership and if the join was not successful, every column in mailing_category_membership will be NULL. So, in the first query, your WHERE will also return every row from mailing_category where no match was found for the join.


text:
Q: How to handle notification bar in Selenium Webdriver? When i am clicking on a link a notification bar is appearing over the same webpage.I am not able to pass control on this notification bar.I have to click on cross link and i have to get the text from it.
Please reply with the solution for this problem.


text:
Q: Invalid file path exception My application throws an exception - java.io.FileNotFoundException: Invalid file path. Not sure why. I've read the questions and answers about the theme but no one could help me.
Here is the code:
    String userhome = System.getProperty("user.home");
    String filename = null;
    File rdp = null;
    for (int item = 0; item < darab; item++) {
        filename = toValidFileName(ProgramList.get(item).getP_name());
        filename += ".rdp";
        rdp = new File(userhome, filename);
        try {
            JFrame panel;
            panel = new JFrame();
            panel.setSize(400, 10);
            panel.setLocation(300, 400);
            panel.setTitle("Saving " + rdp.getAbsolutePath());

            try (FileOutputStream fstr = new FileOutputStream(rdp)) {
                panel.setVisible(true);
                char c;
                for (int j = 0; j < 2336; j++) {
                    c = ProgramList.get(item).p_body.charAt(j);
                    fstr.write(c);
                }
                fstr.flush();
                fstr.close();
                panel.setVisible(false);
            }

        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this,
                    ioe.getMessage(), "Save rdp file", JOptionPane.ERROR_MESSAGE);
            System.err.println(ioe.getMessage() + " : "+ rdp.getAbsoluteFile());
        }
    }

And the result:
Invalid file path : C:\Users\LiPI\CosmicLd.rdp
toValidFilename() is remove the forbidden characters from the (KORG RADIAS) program name to create a valid file name.
I've not found my fault :(
The destination directory is not read only, the user has the necessary privilegs. When I view the file.canWrite() after the line:
 rdp = new File (userhome, filename);
it's always false.
What did I do wrong?
Thanks!

A: Try using filewriter instead. Your try will look like this:
try {
     File dir = new File("C:/Users//" + userhome + "/Documents"); //customize this however
     FileWriter fstr = new FileWriter(new File(dir, rdp));
          for (int j = 0; j < 2336; j++) {
                c = ProgramList.get(item).p_body.charAt(j);
                fstr.write(c);
                        }
            fw.close();
        }

Also, try to stick to Java variable naming conventions. userhome should be userHome, etc. Just a minor thing :)

A: The problem was generated in that line:
filename = toValidFileName(ProgramList.get(item).getP_name());

with the getP_name() results, becouse sometimes it has (char) 0 characters...
The code is rewritten -> the (char) 0 characters are changed to (char) 20 characters in the object and in this way everything is working.
The toValidFileName code anyway this:
public static String toValidFileName(String input) {
    return input.replaceAll("[:\\\\/*\"?|<>']", "_");
}

Thank you all for your help! There are some usefully advice especially Arkady's and VGR's advice!


text:
Q: SQL - Select only latest insertion of each ID I have the following SQL table:
autID (auto increment, number) | externalID (NOT unique, string) | title | price | scanDate (datetime)

I also have the following query to calculate the average price:
SELECT AVG(price) AS avgPrice from rs

My goal is to calculate the average price of the latest inserted of each autID only (or based on scanDate). For example:
1 | "baba" | 100 | date
2 | "baba | 50| newerDate
3 | "oo | 100| date

will return:
avgPrice: (50 + 100) / 2 = 75

the first 100 is neglected since it's older of the same ID of baba
Any idea?

A: One method is to use a correlated subquery to get the most recent value and then use average:
select avg(rs.price)
from rs
where rs.scandate = (select max(r2.scandate)
                     from rs rs2
                     where rs2.externalid = rs.externalid
                    ) ;

A: Two steps, first find the newest record for each ID, second, do avg()
WITH CTE123 AS (
Select ID, Title, MAX(Scandate) as Scandate
From avgPrice
GROUP BY ID, Title
)
SELECT avg(rs.price)
FROM avgPrice rs
JOIN CTE123 rp ON rs.id=rp.id and rs.Scandate=rp.Scandate

The first step is to find the ID with its newest scandate, and the second step is to join the first CTE and calculate the average for the results. In this way, the calculation is done based on only the newest records.


text:
Q: Extjs TreePanel: How can I hide nodes by class or attribute? I have a tree with nodes that contain tasks.
Completed tasks have attribute status: 100 and class cls: "done".
I would like to make a button for hiding completed tasks.
What function will hide nodes in a tree by their id or class?
{"id":"45",
"description":"Pay bills",
"status":"100",
"cls":"done",
"uiProvider":"col",
"leaf":true}

A: Try walking the tree starting at the root and testing for the attribute(s) you want. If you get a hit, hide the node:
tree.getRootNode().cascade(function() { // descends into child nodes
    if(this.attributes['status'] == 100) { // test this node
        this.getUI().hide() // hide this node
    }
})

You actually asked about testing by the class "done". In that case just test if this.attributes['cls'] == 'done' instead. I prefer checking "status" than "cls" as the latter can be space-separated and messy.

A: For ExtJS 6, for example, when read config is false, hide the node:
hideItemsReadFalse: function () {
    var me = this,
        items = me.getReferences().treelistRef.itemMap;

    for(var i in items){
        if(items[i].config.node.data.read == false){
            items[i].destroy();
        }
    }
}

Root:
{
    "text": "root",
    "children": [
        {
            "text": "Atualização",
            "iconCls": "x-fa fa-list",
            "children": [
                {
                    "leaf":true,
                    "text": "Empresas",
                    "module": "empresas",
                    "iconCls": "x-fa fa-building",
                    "read": false
                },
                {
                    "leaf":true,
                    "text": "Produtos",
                    "module": "produtos",
                    "iconCls": "x-fa fa-cubes",
                    "read": true
                }
            ]
        }
    ]
}


text:
Q: Missing file from repository this morning. Who do I notify? Aptitude upgrade on 12.04 shows the following:
E: Failed to fetch http://security.ubuntu.com/ubuntu/pool/main/l/linux/linux-libc-dev_3.2.0-84.121_amd64.deb: 404  Not Found [IP: 91.189.91.15 80]

How can i fix this ?

A: After googling linux-libc-dev_3.2.0-84.121_amd64.deb on Ubuntu's website it gives a 404 , probably it's been deleted. Try installing it from aptitude or synaptic


text:
Q: Mirror Displays of 2 different resolutions I am wanting to mirror asymmetrically whereby the main monitor is a lower resolution than the HD TV we are using as a monitor.  When the displays are in non-mirrored mode (spanning?) each monitor display properties allows me to set the resolution the the maximum of each monitor.  When I switch to mirroring the HD TV drops down to the lower setting on the main monitor.
If it is not possible to do with one video card perhaps I can use both my video cards?
AMD Radeon Pro WX 2100 (active)
Intel UHD Graphics 630 (not active)
4K HD TV - 3840x2160
Dell 30" monitor - 2560x1600
Ubuntu 16.04

A: Okay I am trying two answers (it does not help you are not mentioning your OS). I am using Ubuntu 18.04 LTS and I am using a dual monitor set-up. In Ubuntu it is called Join Displays. I am not using Mirror.
Both monitor (27"/28") keep their native resolution (1920x1080,3840x2160).
Problem is hidpi monitors are not well supported yet and usually trying to scale one monitor affects the other one as well.
Following https://wiki.archlinux.org/index.php/HiDPI helped to work around that problem.


text:
Q: window.location.href running in indefinite loop despite return false statement When I'm on page 2.html and I click on .next button it goes into infinite loop instead of navigating to page 3.html.
/* Init current page */
var current_page = localStorage.getItem("current_page");

/* If current page is undefined set set it to first page */
if (current_page === null) {
    current_page = 1;
    localStorage.setItem("current_page", current_page);
}

/* Load first page or where user had left off */
if (current_page != 1){
    window.location.href = current_page + ".html";
    return false
}

/* Navigate to next page */
$('button.next').on('click', function(e){
    e.preventDefault();
    current_page = parseInt(current_page)+1;
    localStorage.setItem("current_page", current_page);
    location.reload();
});

I've defined window.location.href during page load because the user should be taken to the last visited page incase if they drop off and return back.

A: On each page set a variable activePage that matches your filename number and compare to that instead of always comparing to 1 before doing redirect
var activePage = 3;

if (current_page != activePage ){
    window.location.href = current_page + ".html";
}

Alternatively you can parse the url to get the active page number from file name


text:
Q: Hint for Number Theory question. I need a hint for this question please: Find the sum of the orders mod 83 over all elements of the set $\{1,2,3,\ldots,82\}$. (If multiple elements have the same order, add that term multiple times.)
I figured out that all numbers except $1$ (has order $1$) and $82$ (has order $2$) must have orders of $41$ or $82$. But how do I know how many numbers with orders of $41$ or $82$ there are?

A: 83 is prime, so the multiplicative group is equivalent to the cyclic group with $\phi(83)=82$ elements. In a cyclic group of order $n$, there are $\phi(d)$ elements of order $d$ (where $d$ must divide $n$). So the answer is $\sum_{d|n}d\phi(d)$. I'm not sure if there's a closed expression for this, but with $n=82$, I get 4923.


text:
Q: Does VSTO have access to the contents of the Excel Filter check marks? Is it possible to programmatically retrieve and set the check marks in the screenshot??

TIA

A: I created a Console Application in Visual Studio 2010 and added a COM Reference to Microsoft Excel X.0 Object Library.  The X will differ depending on the version of Excel you have installed.  Here is the code you should use:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

namespace OpenExcel {
class Program {
    static void Main(string[] args) {
        Excel.Application xlApp = null;
        try {
            xlApp = new Excel.Application();
            xlApp.Visible = true;
            Excel.Workbook xlWb = xlApp.Workbooks.Open(@"C:\Users\joe.bob\Desktop\tmp\Book1.xlsx"); //include the path to your real Excel file
            Excel.Worksheet xlWSht = xlWb.Sheets["Sheet1"]; //include the name of your worksheet where you have the data
            //here the data is on a Worksheet called Sheet1

            int startRow = 9; //this is the row where the data starts
            string startCol = "A"; //the start column
            int endRow = 15;
            string endCol = "F";
            int filterColumn = 6; //this is an OFFSET
            string[] filterList = new string[] { "DTP-3432", "DTP-343243" }; //this is the list of values you want to show
            Excel.Range myData = xlWSht.get_Range(startCol + startRow, endCol + endRow);
            myData.AutoFilter(filterColumn, filterList.Length > 0 ? filterList : Type.Missing, Excel.XlAutoFilterOperator.xlFilterValues, Type.Missing, true);
            Console.WriteLine("Press a key to quit...");
            Console.ReadKey();
        }
        finally {
            if (xlApp != null) {
                xlApp.Quit();
            }
        }
    } //end main
} //end program
} //end namespace

For more info see the following link:
http://msdn.microsoft.com/en-us/library/office/microsoft.office.interop.excel.range.autofilter%28v=office.15%29.aspx
http://blogs.msdn.com/b/erikaehrli/archive/2005/10/27/excelmanagedautofiltering.aspx

A: Here's how to pull in the checked items in VBA. It will translate pretty easily to C#/VSTO:
Sub GetFilterCriteria()
Dim i As Long
Dim afCriteria1 As Variant

afCriteria1 = ActiveSheet.AutoFilter.Filters(1).Criteria1
For i = LBound(afCriteria1) To UBound(afCriteria1)
    Debug.Print afCriteria1(i)
Next i
End Sub