text:
Q: javafx how to refresh table after adding record i saw so many answers but its not suitable with me because i am using loop to generate my table not specific class
i want to refresh the table who generate the data from a loop.
i tried to refresh table but now working
i tried to build date again but it duplicates the table
Here is where cells generated by a loop
            while(rs.next()){
                //Iterate Row
                 ObservableList<String> row = FXCollections.observableArrayList();
                for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
                    //Iterate Column
                    row.add(rs.getString(i));
                }
                System.out.println("Row [1] added "+row );
                data.add(row);
                table.setItems(data);

            }

Here is add button
        buttonAdd.setOnAction(new EventHandler<ActionEvent>(){
        @Override
        public void handle(ActionEvent t){
            try {
                stmt.executeUpdate("INSERT into stock VALUES('"
                + fieldCategoryID.getText()+ "','" + fieldCategoryName.getText() + "','" + fieldAmount.getText() + "','" + fieldCostPrice.getText()+ "','" + fieldSellingPrice.getText()
                        + "','" + fieldCategoryProfit.getText()+ "','" + fieldSupplier.getText()+ "','" + fieldCategoryProfitRate.getText()+
                        "','" + fieldTotalCategoryProfit.getText()+"','" + fieldOnStock.getText()+ "')");

        content.getChildren().removeAll(table);
        table.refresh();
        content.getChildren().add(table);
        } catch (SQLException ex) {
                Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        });

Here is delete button
  buttonDelete.setOnAction(new EventHandler<ActionEvent>(){
        @Override
        public void handle(ActionEvent t){
            try {
                                Alert alertConfirmation = new
table.getSelectionModel().getSelectedIndex();

                TablePosition pos = (TablePosition) table.getSelectionModel().getSelectedCells().get(0);
                            int row = pos.getRow();
                            TableColumn col = pos.getTableColumn();
                             String data = (String) col.getCellObservableValue(table.getItems().get(row)).getValue();
                String query = "DELETE FROM stock where category_code = ?";
                pst = con.prepareStatement(query);
                pst.setString(1, data);
                pst.execute();
}

A: i add a refresh method that clear observableList data Then i declare Statement and ResultSet again then added rows again
public void refreshTable() throws SQLException{
data.clear();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
      rs = stmt.executeQuery("select * from stock");
      while(rs.next()){
                //Iterate Row
                  row = FXCollections.observableArrayList();
                for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++){
                    //Iterate Column
                    row.add(rs.getString(i));
                }
                System.out.println("Row [1] added "+row );
                data.add(row);
                table.setItems(data);

            }
}


text:
Q: How to pass parameters from several sub functions to a major one I need your help on how to figure out the following:
With the following functions called AddSub# I want to pass to the main add function (AddAll) the variables called string#
function AddSub1()
{       string11 = '11';
        string12= '12';
        string13= '13';
        AddAll(string11, string12, string13);
}

function AddSub2()
{       string21 = '21';
        string22= '22';
        string23= '23';
        AddAll(string21, string22, string23);
}

But if I do:
function AddAll(string11, string12, string13, string21, string22, string23){
    document.write(string11);
    document.write(string12);
    document.write(string13);
    document.write(string21);
    document.write(string22);
    document.write(string23);
}

And I call function AddSub1 I get: 11 12 13 undefined undefined undefined
Then, if I call AddSub2 I get: 21 22 23 undefined undefined undefined
How can I pass the variables to the AddAll function properly so I can get 11 12 13 21 22 23?
Thanks a lot!

A: You should use arguments, an Array-like object corresponding to the arguments passed to a function.
function AddAll(){
    var args = arguments; // arguments will give you an array
                          // of all passed arguments to this function

    // here I keep just a reference in args,
    // you can also use argumetns itself directly

    // To retrieve those arguements use this

    document.write(args[0]);
    document.write(args[1]); // ...etc

    // You can also make a loop over arguments

    for (var i = 1; i < arguments.length; i++) {
      document.write(arguments[i]);
    }
}

Read more about arguments
NOTE:

*

*Don't use global variable unnecessarily

*Not need to pass arguments to AddAll() as Array, just comma(,) separated

A: You can change your function so that it takes an array of strings.
function AddAll(strings) {
    for (var i = 0; i < strings.length; i++) {
        document.write(strings[i]);
    }
}

AddAll(["hello", "world"]);

or to use code from your example:
function AddSub2() {
    string21 = '21';
    string22= '22';
    string23= '23';
    AddAll([string21, string22, string23]);
}

A: I would use a modified version of the answer by @thecodeparadox
function AddAll(){
var args = arguments; // arguments will give you an array

for(var i=0,j=args.length;i<j;i++)
document.write(args[i]);

}

that way it does not matter how many strings you pass to the function they will all get written.
from your question it seems that this function will have multiple iterations.

A: you can use global variables:
var string11,string12,string13,string21,string22,string23;

function AddSub1()
{
    string11= '11';
    string12= '12';
    string13= '13';
}

function AddSub2()
{
    string21= '21';
    string22= '22';
    string23= '23';
}

function AddAll(){
    document.write(string11);
    document.write(string12);
    document.write(string13);
    document.write(string21);
    document.write(string22);
    document.write(string23);
}

and then you call:
AddSub1();
AddSub2();
AddAll();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java Spliterator : How to process large Stream splits equally? The code I'm working with
package com.skimmer;

import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.LongStream;
import java.util.stream.Stream;

public class App {

  public static void main(String[] args) throws InterruptedException, ExecutionException {

    // Simply creating some 'test' data
    Stream<String> test = LongStream.range(0, 10000000L).mapToObj(i -> i + "-test");

    Spliterator<String> spliterator = test.parallel().spliterator();
    List<Callable<Long>> callableList = new ArrayList<Callable<Long>>();

    // Creating a future for each split to process concurrently
    int totalSplits = 0;
    while ((spliterator = spliterator.trySplit()) != null) {

      totalSplits++;
      callableList.add(new Worker(spliterator, "future-" + totalSplits));
    }

    ExecutorService executor = Executors.newFixedThreadPool(totalSplits);
    List<Future<Long>> futures = executor.invokeAll(callableList);
    AtomicLong counter = new AtomicLong(0);

    for (Future<Long> future : futures)
      counter.getAndAdd(future.get());

    System.out.println("Total processed " + counter.get());
    System.out.println("Total splits " + totalSplits);

    executor.shutdown();
  }

  public static class Worker implements Callable<Long> {

    private Spliterator<String> spliterator;
    private String name;

    public Worker(Spliterator<String> spliterator, String name) {
      this.spliterator = spliterator;
      this.name = name;
    }

    @Override
    public Long call() {

      AtomicLong counter = new AtomicLong(0);
      spliterator.forEachRemaining(s -> {

        // We'll assume busy processing code here
        counter.getAndIncrement();

      });

      System.out.println(name + " Total processed : " + counter.get());

      return counter.get();
    }
  }
}

The output
furture-11 Total processed : 244
furture-10 Total processed : 488
furture-9 Total processed : 977
furture-12 Total processed : 122
furture-7 Total processed : 3906
furture-13 Total processed : 61
furture-8 Total processed : 1953
furture-6 Total processed : 7813
furture-14 Total processed : 31
furture-5 Total processed : 15625
furture-15 Total processed : 15
furture-4 Total processed : 31250
furture-17 Total processed : 4
furture-18 Total processed : 2
furture-19 Total processed : 1
furture-16 Total processed : 8
furture-3 Total processed : 62500
furture-2 Total processed : 125000
furture-1 Total processed : 250000
future-0 Total processed : 500000
Total processed 1000000
Total splits 20

My problem/Question :
The first trySplit (and future task 'future-0') gets exactly n/2 total elements to begin processing. The first couple splits take a long time to complete - this gets worse as n grows. Is there any other way to process a stream where each future/callable gets an equal distribution of elements to process such as (N/splits) ie. 1000000/20 = 50000
Desired results
furture-11 Total processed : 50000
furture-10 Total processed : 50000
furture-9 Total processed : 50000
furture-12 Total processed : 50000
furture-7 Total processed : 50000
furture-13 Total processed : 50000
furture-8 Total processed : 50000
furture-6 Total processed : 50000
furture-14 Total processed : 50000
furture-5 Total processed : 50000
furture-15 Total processed : 50000
furture-4 Total processed : 50000
furture-17 Total processed : 50000
furture-18 Total processed : 50000
furture-19 Total processed : 50000
furture-16 Total processed : 50000
furture-3 Total processed : 50000
furture-2 Total processed : 50000
furture-1 Total processed : 50000
future-0 Total processed : 50000
Total processed 1000000
Total splits 20

Follow up question : If Spliterator is unable to do this what other approach/solution would be best used to process large streams concurrently.
Practical case scenario : Processing a large (6GB) CSV file that is too large to hold in memory

A: You are getting perfectly balanced splits here. The problem is, each time you split a sequence of elements into two halves, represented by two Spliterator instances, you create a job for one of the halves, not even attempting to split it further, but only subdividing the other halve.
So right after the first split, you create a job covering 500,000 elements. Then, you call trySplit on the other 500,000 elements, getting a perfect split into two chunks of 250,000 elements, create another job covering one chunk of 250,000 elements and only try to subdivide the other. And so on. It's your code creating unbalanced jobs.
When you change your first part to
// Simply creating some 'test' data
Stream<String> test = LongStream.range(0, 10000000L).mapToObj(i -> i + "-test");
// Creating a future for each split to process concurrently
List<Callable<Long>> callableList = new ArrayList<>();
int workChunkTarget = 5000;
Deque<Spliterator<String>> spliterators = new ArrayDeque<>();
spliterators.add(test.parallel().spliterator());
int totalSplits = 0;
while(!spliterators.isEmpty()) {
    Spliterator<String> spliterator = spliterators.pop();
    Spliterator<String> prefix;
    while(spliterator.estimateSize() > workChunkTarget
              && (prefix = spliterator.trySplit()) != null) {
        spliterators.push(spliterator);
        spliterator = prefix;
    }
    totalSplits++;
    callableList.add(new Worker(spliterator, "future-" + totalSplits));
}

you get quiet close to your desired target workload size (as close as we can, given that the numbers are not powers of two).
The Spliterator design works much smoother with tools like ForkJoinTask, where a new job can be submitted after each successful trySplit and the job itself will decide to split and spawn new jobs concurrently when the worker threads are not saturated (like parallel stream operations are done in the reference implementation).


text:
Q: I'm getting the error "LINK : error LNK2001: unresolved external symbol _WinMainCRTStartup" Please help.
On Visual Studio 2008, I'm getting the following errors.
============================================================

   1>Microsoft (R) Windows Resource To Object Converter Version 9.00.30729.01
   1>Copyright (C) Microsoft Corporation.  All rights reserved.
   1>adding resource. type:ICON, name:1, language:0x0409, flags:0x1010, size:744
   1>adding resource. type:ICON, name:2, language:0x0409, flags:0x1010, size:296
   1>adding resource. type:GROUP_ICON, name:128, language:0x0409, flags:0x1030, size:34
   1>adding resource. type:DIALOG, name:100, language:0x0409, flags:0x1030, size:374
   1>adding resource. type:DIALOG, name:102, language:0x0409, flags:0x1030, size:784
   1>adding resource. type:VERSION, name:1, language:0x0409, flags:0x30, size:928
   1>adding resource. type:STRING, name:7, language:0x0409, flags:0x1030, size:68

   1>LINK : error LNK2001: unresolved external symbol _WinMainCRTStartup

   1>.\Release/DiskTest.exe : fatal error LNK1120: 1 unresolved externals

   1>Build log was saved at "file://c:\WinIRDir\Utilities\DiskTest\Release\BuildLog.htm"
   1>DiskTest - 2 error(s), 0 warning(s)
   1>Build log was saved at "file://c:\WinIRDir\Utilities\CommApp\Release\BuildLog.htm"
==============================================================

Here is the situation.
- DiskTest.exe is one of 3 projects in my solution
- This project builds perfectly for Debug x64, Release x64, and Debug Win32.  Release Win32 is the only one generating these errors.
- I have spend hours comparing the properties pages for all 4 config/machine combinations, and am confident that no properties are missing from one version to the next.  I paid special attention to  "Additional dependencies", "Additional Librari Directories", "Input", etc.  Ofcourse, paths to .lib files point to either \Debug or \Release, and \x86 or \x64 for the respective config or platform.
The only "additional dependency" this project has is SBF_Util.lib and SBF_Utild.lib for Debug.  I made sure that all 4 versions (debug win32 and x64, and Release win32 and x64) of this library exist in the folder specified in each "additional library directory"  I also checked dumpbin on each version of the library to make sure the platform matches.
I have seen other situations where a main entry point is missing, but in this case, all other versions build with no problems, it is only on Win32 Relase version that generates this error, so I don't think I need to change anything in the code.
Can anybody provide any clues?, I'm out of ideas.  Any ideas will be very much appreciated.  Thanks.

A: UNBELIEVABLE!!!
I found the problem!
It was an incredibly simple thing what was causing this criptic error: A "SPACE"
It turns out that under Configuration->C/C++->OutputFiles->Object File Name: I had:
"$(IntDir)\ "
Didn't notice the space until I paid very close attention to the Kdiff3 window, and noticed this tiny underscore to signal a space.
This space had been there for months, as this project had been left unattended (before I came on board), because nobody could find the fix for it, so they just stopped using it.
Most likely a copy-paste error.
Thank you all guys for your ideas. Specially the first answer from Xearinox that made me think about comparing all modes.  I'll try to find some time to write a tool to parse the project/solution files into a 4-column sheet that lists all properties for all configurations and platforms, so we can easily compare them.  Thank you all again.

A: Open up your project's settings page, go to Linker → System and examine the SubSystem property.  Make sure it's set to the same value in all project configurations by switching the configuration from the configuration drop-down box.
Assuming that your intended entry point is main (or one of its variants such as _tmain or wmain), you want to make sure to use the SubSystem property is set to CONSOLE.

A: WinMain as entry point is missing.

A: In my case, the file I was trying to compile had the wrong properties.
I had created the file with a stray character in the file extension, and so my project gave it the wrong Item Type: Does not participate in build.
After renaming it I went into its properties, and changed the Item Type to <reset to default>, which reset it to C/C++ Compiler.


text:
Q: document.getElementByID doesn't work when using browserify I have a file which finds an select element and then sets the function for it's onchange. However, this doesn't work with the file browserify outputs.
Here is a minimum reproducible sample:

*

*A select tag with a unique id

*The following javascript file:

let locationSelector = document.getElementById('location');
locationSelector.onchange = function () {
    console.log('location changed');
};

The above works when I use the script above. However, when I use the file browserify outputs instead I get the following error: Uncaught TypeError: Cannot set properties of null (setting 'onchange').
Logging locationSelector before the the second line shows the locationSelector in the original file but logs null in the browserify file.


text:
Q: VS2013 Dynamically create chart c# Can't create standart chart. I tried these methods:
http://timbar.blogspot.com/2012/04/creating-chart-programmatically-in-c.html
Chart creating dynamically. in .net, c#
For example code:
private void Form2_Load(object sender, EventArgs e)
    {

var xvals = new[]
            {
                new DateTime(2012, 4, 4),
                new DateTime(2012, 4, 5),
                new DateTime(2012, 4, 6),
                new DateTime(2012, 4, 7)
            };
        var yvals = new[] { 1,3,7,12 };

        // create the chart
        var chart = new Chart();
        chart.Size = new Size(600, 250);

        var chartArea = new ChartArea();
        chartArea.AxisX.LabelStyle.Format = "dd/MMM\nhh:mm";
        chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
        chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
        chartArea.AxisX.LabelStyle.Font = new Font("Consolas", 8);
        chartArea.AxisY.LabelStyle.Font = new Font("Consolas", 8);
        chart.ChartAreas.Add(chartArea);

        var series = new Series();
        series.Name = "Series1";
        series.ChartType = SeriesChartType.FastLine;
        series.XValueType = ChartValueType.DateTime;
        chart.Series.Add(series);

        // bind the datapoints
        chart.Series["Series1"].Points.DataBindXY(xvals, yvals);

        // copy the series and manipulate the copy
        chart.DataManipulator.CopySeriesValues("Series1", "Series2");
        chart.DataManipulator.FinancialFormula(
            FinancialFormula.WeightedMovingAverage,
            "Series2"
        );
        chart.Series["Series2"].ChartType = SeriesChartType.FastLine;

        // draw!
        chart.Invalidate();
}

But it gives me empty form.
How to create chart? Please help!

A: You need to add the chart to your form:
this.Controls.Add(chart);


text:
Q: Real time validation for input box using Primefaces/JSF I need to know if there is a way to do real-time validation using Primefaces/JSF?
My requirement looks simple:

I've an input box which would take only unique name. For eg.., if an user is looking to input an name which already exists in database, it
  should throw error message like "User Name already exists."  This
  should happen as soon as the user has moved out of the input box

Reference can be inferred from Google registration page
I've spent a lot of time researching on internet but haven't arrived at any concrete solution.
I'm primarily looking for a solution in Primefaces/JSF. Is it possible?

A: You can do that with plain JSF. You just have to use a validator and add ajax behavior to your input field, e.g.
facelet
<h:form id="form">
    <h:messages id="messages" />
    <h:inputText value="#{anyBean.username}" validator="userValidator">
        <f:ajax render="@this messages" />
    </h:inputText>
</h:form>

validator
@FacesConverter("userValidator")
public class UserValidator implements Validator {

    @Override
    public void validate(FacesContext fc, UIComponent component, Object value) throws ValidatorException {
        String username = (String) value;
        if (usernameExists(username)) {
            throw new ValidatorException(new FacesMessage("User Name already exists."));
        }
    }

    private boolean usernameExists(String username) {
        // check if username exists here
    }
}

Of course you can also use the equivalent PrimeFaces components p:messages, p:inputText and p:ajax.


text:
Q: R - Refactor list of lists Suppose I have a length M list of lists, each sub-list is of the same length (N).
How could I efficiently refactor these lists so that I now have N lists of length M?
It would be similar to if you made a matrix of the lists and sliced by a different dimension.
I.E.
original <- list(list(1:3, 4:6), list(2:4, 5:7))
> final
[[1]]
[[1]][[1]]
1, 2, 3
[[1]][[2]]
2, 3, 4

[[2]]
[[2]][[1]]
4, 5, 6
[[2]]
[[2]][[2]]
5, 6, 7


text:
Q: SQL Server on ssd seems slow We recently moved SQL Server to SSD and the performance gain is not that great.
SQLIO shows enormous gains (15-100 times faster), getting sequential read/write speed up to 6GB/s.
But when we do a simple query:
select *
into table2
from table1

it gets roughly like 60MB/s. 2GB table takes 30 seconds to finish.
Is this normal? What speed is considered average for SSD for such a simple query?
Don't believe it's a RAM issue, 50GB of RAM..?

A: Problem solved, there were IO limits on that VM.
As for SQLIO, it was lieing on hyper-v:
https://social.technet.microsoft.com/Forums/azure/en-US/b8e1674d-f1c7-4e46-b1f1-09fb0d75d82e/strange-blazingfast-io-performance-inside-hyperv-vm?forum=winserverhyperv
https://serverfault.com/questions/287311/does-sqlio-lie-when-run-from-a-hyper-v-guest-on-a-vhd

A: Depending on your SQL Server version, there are various things that can impact the performance of your query.

*

*SQL Server Version:  SQL server 2014 allows parallel inserts into heap tables if you use the TABLOCK hint (SELECT INTO only).  SQL Server 2016 expands this to allow parallel inserts into heaps or clustered columnstore indexes with INSERT SELECT

*SQL Server Edition:  Enterprise edition will issue more outstanding IO's for read-aheads than standard edition.

*Fragmentation : Even though SSD's have no seek latency, they still do perform best with large sequential reads.  High levels of fragemention will hinder the effectiveness of read-ahead reads.

*Fill Factor:  Rebuild an index with a fill factor of 5% and it will be 20x larger on disk, hence 20x more IO to read it.  A freshly rebuilt index will be optimal from both a fragmentation and read-ahead perspective.

Wait statistics analysis can tell you what your current bottleneck is.  If you are seeing PAGEIOLATCH_S, then reading is the issue.  Rebuild the clustered index on the source table.  If you aren't seeing an IO bottleneck, then I would assume that you are CPU bound.  Look for 1 CPU to be at 100% (if your query is running single threaded).  Solution there is to add the TABLOCK hint to try to get some parallelism.
SELECT INTO is a bulk logged operation, and won't be using TEMPDB, so no need to look into file placement for the log files or tempdb.


text:
Q: Migrate complex svn structure to git I'm working on the conversion of a group of old svn repositories into git. The current svn structure looks like this:
/RootRepository
    /FatClient
        /branches
            /1.1
            /1.2
        /tags
            /1.1.1
            /1.1.2
        /trunk
    /WebApp
        /branches
            /1.1
            /1.2
        /tags
            /1.1.1
            /1.1.2
        /trunk
    /CommonLibrary
        /branches
            /1.1
            /1.2
        /tags
            /1.1.1
            /1.1.2
        /trunk

When working on the new bits, the development team checks out:
/RootRepository/FatClient/trunk
/RootRepository/WebApp/trunk
/RootRepository/CommonLibrary/trunk

Changes are made very frequently across the three "projects" which results in 3 commits, and (because they are in the same repository on the server) each commit gets the next sequential revision. The three projects are always released together as components of an Application.
I would like to migrate from the svn structure with history into a single git structure that looks like this:
/RootRepository
    /master
        /FatClient
        /WebApp
        /CommonLibrary
    /branch-1.1
        /FatClient
        /WebApp
        /CommonLibrary
    /branch-1.2
        /FatClient
        /WebApp
        /CommonLibrary

When I run:
git svn clone --stdlayout https://somesvnserver.com/RootRepository/FatClient
git svn clone --stdlayout https://somesvnserver.com/RootRepository/WebApp
git svn clone --stdlayout https://somesvnserver.com/RootRepository/CommonLibrary

I end up with 3 git repositories with trunk, branches and history. If I run:
git svn clone https://somesvnserver.com/RootRepository

I have 1 git repository with history, but all the code is in master.
So, the question is: what is the best way to achieve this while retaining the svn history.

A: Atlassian provides migration scripts to help you migrate your existing development workflow from SVN to Git along with the write up to use them here.
I too written blog long time back which can help you to achieve what you are looking for here - Migrating from SVN to Git .


text:
Q: Specify border for svg path element I am trying to to border for svg path element using stroke attribute but its not drawing border on all four borders.Any idea how to draw on all four borders
<!DOCTYPE html>

My first SVG

<svg >
<path fill="rgba(103,103,103,.35)" d="M 149.5 8 L 149.5 40 316.5 40 316.5 8" stroke-width="3" stroke='#3fa9f5' ></path>
</svg>

A: You seem to have forgotten to close your path with Z like

<svg  width=320 height=50 viewBox="0 0 320 50">
  <path fill="rgba(103,103,103,.35)" d="M 149.5 8 L 149.5 40 316.5 40 316.5 8 Z" stroke-width="3" stroke='#3fa9f5' ></path>
</svg>

This will draw the missing line too. It is also a good idea to include the width and height attributes into the <svg> tag.
Some more unsolicited advice ...
Maybe you should also include a viewBox="0 0 320 50" attribute into your <svg> tag too, as in a general case (when the svg resides in a separate file) this will make the inclusion of the svg content into other pages much easier. It will allow scaling of the svg-contents if you include it with an <object data="mysvgdata.svg" type="image/svg+xml" width="640"> tag. The result would be similar to this:

<svg  width=640 viewBox="0 0 320 50">
  <path fill="rgba(103,103,103,.35)" d="M 149.5 8 L 149.5 40 316.5 40 316.5 8 Z" stroke-width="3" stroke='#3fa9f5' ></path>
</svg>


text:
Q: Set Vuex Store state with typescript Is there a way for me to set a Vuex Store with typescript, but have it be empty?
My current code for this is:
export default new Vuex.Store({
  strict: true,
  state: {
    username: string
  },
});

But I currently get: "'string' only refers to a type, but is being used as a value here". I know I can then put a string in username, but I require it to be empty.

A: export default new Vuex.Store({
    strict: true,
    state: {
      username: ""
    },
  });

This way username is declared as a string and still empty at the beginning.
Personally I would go the following route though:
/* location: '/src/models/state.ts': */
interface IState {
    username?: string;
}

/* location: '/src/store.ts': */
const state: IState = {username: undefined};

export default new Vuex.Store({strict: true, state});

This way you can have better typing for your store state and leave the username undefined as in your question. You also don't need to remember checking for undefined, as your IDE will remind you that you need to check state.username !== undefined whenever you want to use the username as a string.
So consider using an empty string as initial value and not allowing undefined by removing the ? in the interface.


text:
Q: What is an `invalid token in class` error? I've been using a tutorial guide for the game I'm making to figure out the basics and I ran into 2 errors while coding the collisions:

*

*Invalid token "{" in class, struct, or interface member of declaration and

*Type or namespace definition, or end of file expected.

Here is the code:
using UnityEngine;

public class PlayerCollision : MonoBehaviour
{
 public PlayerMovement movement;
 {
  void OnCollisionEnter (Collision collisonInfo)
  {
   if (collisonInfo.collider.tag == "Obstacles")
    movement.enabled = false;
  }
 }
}

A: Looks like you have too many curly braces:
public class PlayerCollision : MonoBehaviour
{
    public PlayerMovement movement;
    void OnCollisionEnter(Collision collisonInfo)
    {
        if (collisonInfo.collider.tag == "Obstacles")
            movement.enabled = false;
    }
}


text:
Q: How to have featured image show in standard RSS Widget Is there a way of showing featured images in the standard RSS Widget in WordPress?

A: This widget class uses the functionwp_widget_rss_output(), and there is no filter to change its output. So the answer is: no.
But you can create your own RSS widget and replace the default widget with an improved version.


text:
Q: How to create css file form sass file in the same directory I am learning SASS. I am using VS Code as my code editor. I have installed Live SASS Compiler extension to compile SASS file.
I have created a folder. In this folder I have multiple folders. I want to create css file in each folder not main folder.
Check the image:

In SCSS folder there is a folder named "Partials-and-Imports". I want to create the css folder in the "Partials-and-Imports" folder not in main folder(CSS) because I have to create multiple folders in the main folder.
How can I do that?

A: Just copy and past this block of code in your sass compiler setting - Set your exported CSS Styles, Formats & save location - :)
  "liveSassCompile.settings.formats": [

    {
      "format": "expanded",
      "extensionName": ".css",
      "savePath": "~/../css/"
    }
  ]


text:
Q: How to get customers details using Quickbooks QBXML I used QuickBooks API. Through this API i try to get all customer details like FullName, Addresses(Addr1,Addr2....), City, State, PostalCode etc.
Below is my code:
RequestProcessor2Class rp = new RequestProcessor2Class();

public void connectToQB()
        {
            rp = new RequestProcessor2Class();
            rp.OpenConnection(appID, appName);
            ticket = rp.BeginSession(companyFile, mode);
            string[] versions = rp.get_QBXMLVersionsForSession(ticket);
            maxVersion = versions[versions.Length - 1];
        }

public string processRequestFromQB(string request)
        {
            try
            {
                return rp.ProcessRequest(ticket, request);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return null;
            }
        }

string request = "CustomerQueryRq";
            objConnect.connectToQB();
            int count = objConnect.getCount(request);
            string response = objConnect.processRequestFromQB(objConnect.buildCustomerQueryRqXML(new string[] { "FullName", "City" }, null));
            string[] customerList = objConnect.parseCustomerQueryRs(response, count);
            objConnect.disconnectFromQB();

Let me know if you want more information.
Thanks,

A: This is a sample code for get customer name.
   ICustomerRetList customerRetList = (ICustomerRetList)response.Detail;
   ICustomerRet customerRet = customerRetList.GetAt(0);
   textBox1.Text = customerRet.Name.GetValue().ToString();

Please learn more.
->> for get other detail.


text:
Q: How to get the return value of a function by using 'this' in javascript in below context Hi i'm trying to call a function which is an attribute value in a JSON.
Getting different results in different scenarios
var x = 3;
var foo = {
    x: 2,
    inner: {
        x: 1,
        reValue: function() {
            return this.x
        }
    }
}

var go = foo.inner.reValue;

Case 1:
console.log(go()) // 3

Case 2:
console.log(foo.inner.reValue()) // 1

Can anyone explain case 1?

A: Creating a variable in global scope, automatically assigns it to window, so:
 var x = 3;
 var go = foo.inner.reValue;
 go()

does the same as:
 window.x = 3;
 window.go = foo.inner.reValue;
 window.go();

And the last line will call go with the context (aka this) being window, therefore this.x will be window.x.

If a function is called on an object, such as in obj.myMethod() or the equivalent obj["myMethod"](), then ThisBinding is set to the object (obj in the example; §13.2.1).  ~ How does the this keyword work?

A: You should have a look at bind() to bind the context.
If you re-bind go to foo.inner, it behaves as intended:
go=go.bind(foo.inner)

Or initially:
var go = foo.inner.reValue.bind(foo.inner);

As long as you did not specify the context, the global context (in case of a browser this is window) is chosen per default.
So this refers in your example to window.x, which is 3

A: The value of this is determined based upon where the function was called. Here is an example:

let foo = {
  bar: this,
  baz: function() {
    console.log(this)
  }
}

console.log(foo.bar); // logs window
foo.baz();            // logs foo

let hey = foo.baz;

hey();                // logs window

A new value of this is created when a method is invoked on a object. Therefore, our first log logs window because we haven't invoked any method. However, our second example logs foo because now a method on foo is called and therefore the value of this inside the baz function is foo. You can usually derive the value of this taking the object left of the dot of the function which is called.
For example foo.baz(), foo is left of the dot of baz() so foo is the value of this.
The last example is a bit tricky. The function object gets stored inside the variable hey. Now when hey gets executed it will log window. This is because the value of this is determined when hey() gets executed. Because hey is a global variable it sits on the window object. Using the rule we just learned we can take the object left of the dot of hey(). This is window, because all variables on the global scope are window.variable.
If you fully want to understand the value of this you should also know how the execution context works in JS. Here is some information about that.

A: this.x may be "local" to the function by interpretation.
remove the "this" to de-localize , but if that has trouble you may need to write in a way that disambiguates x.


text:
Q: Is it sensible to input user names and passwords as command line arguments to python script in task scheduler? I'm not the first person to run python scripts that require plain text credentials for third party web services as scheduled tasks.
 Answers to these questions provide some ways to obscure or otherwise keep sensitive information out of sight. I like the ssh-agent solution because it avoids the need for a file somewhere containing this information but I don't think I can implement it in my environment.
I'm curious as to why the general approach is not to require the user to input the information as command line arguments like
python myPythonScript.py UserName Password

If these parameters are defined in the scheduled task, I think only the logged in user would be able to access the task definitions.  This probably isnt any worse than obfuscation.
I have to use Windows; surely scheduled task definitions are not accessible by all users...  (I checked using the answer to How to find the location of the Scheduled Tasks folder and you need admin rights to access that folder)
Before I go ahead and use this approach, is there a reason why this would be a bad idea?

A: I would encrypt my password(s) rather than doing something like that.  Another potential problem is your bash history will now have your password in it.


text:
Q: Azure tables : how to manage class versions I am trying to get started with using Azure tables. I learnt that Azure tables store objects of a particular class. Could you please tell me how the table accomodates versioining of classes?
Suppose there is a class A with property p1 to start with and say we have stored objects o1 and o2 of type A into a table T. Lets say later we add another property p2 to A. Now, what kind of behavior would we get when we use the new definition of A to retrieve o1 and o2? Will it throw some error? If not, what would be the value of p2 for thee objects when retrieved?
Or is the developer responsible for managing different class definitions in his application?

A: Very important note: Don't think of Azure Tables as an object store! Think of it as a key-value store with non-fixed schema.
Going for you particular example. When you store o1 and o2 from class A, you will have 2 rows in your table:

*

*PartitionKey_1, RowKey_1, p1_1

*PartitionKey_2, RowKey_2, p1_2

Then you add new property to that class and store the object. The result will be a third row:

*

*PartitionKey_3, RowKey_3, p_3, p2_1

Later you can retrieve all the data you need and map it to an instance of a class that has property names corresponding to the table columns!
If you try to fetch the first two records into the latest class A, you will simply get a NULL (or default value for value types) for the p2 property.
If you try to fetch row 3 into earlier class A, you will only get the p1 property value. (Eventually you may see an error, but not a crucial one, you will still be able to map P1 column from the table to the P1 property of your object).
As a reference Understanding Table Service data model is very good starting point for you.
As you just begin, I also suggest that you go through the Windows Azure Storage Client library 2.0 - Tables Deep Dive. This article describes in very details how to save and fetch data from Azure tables.

A: Precisely, when you retrieve the first three objects, they will simply come out without p2. If you are using the default deserialization methods of class TableEntity, your objects will have p2 as null.


text:
Q: ISerializationCallbackReceiver Interface and Serialization in Unity My problem started when I began using the ISerializationCallbackReciever to create a Serializable Dictionary in Unity, It worked fine for most of my classes but when I nested 2 Serializable Dictionaries I started getting trouble with Enumeration.
I believe it was during OnBeforeSerialize where the dictionary had trouble adding KeyValue Pairs after a certain count, I solved this by defining a dictionary property and used it to access the data in my keys and lists, so to be a bit clearer, I was working on a Custom Inspector which had to variations of keys, so I thought using a Serializable Dictionary would work best since I have more than a hundred variations, what my object does is it collects data from my assets and divides that data depending on the key I gave it.
the code for my Scriptable Object:
[System.Serializable]
public class LetterDataObject : ScriptableObject
{
    [SerializeField]
    public DictionaryOfLettersData lettersData;

    [SerializeField]
    public bool isText = false;

    [SerializeField]
    public bool [] folds;
}

[System.Serializable]
public class Letter_Data
{
    [SerializeField]
    public string letterText;
    [SerializeField]
    public Sprite letterSprite;
    [SerializeField]
    public AudioClip letterAudio;
}

[System.Serializable]
public class LetterDataDictionary : SerializableDict<int, Letter_Data>
{

}

[System.Serializable]
public class DictionaryOfLettersData : SerializableDict<int, LetterDataDictionary>
{

}

As you can see every data type is Serializable, I believe my problem is the dictionary is getting modified during OnBeforeSerialize() probably since am accessing a Serializable Dictionary of another object, so to solve this I used a dictionary property.
[Serializable]
public class SerializableDict<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
{

  [SerializeField, HideInInspector]
    private List<TKey> keys = new List<TKey>();
    [SerializeField, HideInInspector]
    private List<TValue> values = new List<TValue>();

    public Dictionary<TKey, TValue> serializedDictionary
    {
         get;
        private set;
    }

    public void OnBeforeSerialize()
    {

        foreach (var item in serializedDictionary)
            {
                if (!keys.Contains(item.Key))
                    keys.Add(item.Key);

                if (!values.Contains(item.Value))
                    values.Add(item.Value);
            }
    }

    public void OnAfterDeserialize()
    {
        serializedDictionary = new Dictionary<TKey, TValue>();
            for (var i = 0; i < keys.Count; i++)
            {
                serializedDictionary[keys[i]] = values[i];
            }
    }
}

This might not be a problem since it is solved now but am curious if someone could give a hint on what is going on ? Maybe there is something I did not know about with unity's serialization so I would love it if anyone faced the same problem and could help me understand it further, I can not move on without understanding my little hack.


text:
Q: Best way to pass data from custom annotation to spring @PostConstruct? i am writting a framework  and I need to pass some information from an annotation to a PostConstruct method.
What iam currently failing at is getting the data in a nice way.
How can i get from here:
@EnableCoolFeature(data1="foo", data2="bar")
public class MainApp {
    public static void main (){ //SpringApp init etc }
}

To here:
@Configuration
public class CoolFeatureConfiguration{

    @PostConstruct
    void processData(){
        //how to get the data in here?
    }
}

Also note that the user can enable "@EnableCoolFeature" multiple times on different Configurations
EDIT: i found a way which works for me
var beanNamesForAnnotation = applicationContext.getBeansWithAnnotation(EnableCoolFeature.class);

for (var tuple : beanNamesForAnnotation.entrySet()) {
    var result = applicationContext.findAnnotationOnBean(tuple.getKey(), EnableCoolFeature.class);
    //the magic!
}

A: An example can be found here.
You need to implement something like this:
import java.lang.annotation.Annotation;
import org.springframework.core.annotation.AnnotationUtils;

@EnableCoolFeature(data1 = "foo", data2 = "bar")
public class MainApp {

  public static void main ()
  {
    try {
      Annotation enableCoolFeatureAnnotation = AnnotationUtils.findAnnotation(MainApp.class, EnableCoolFeature.class);
      System.out.println("@EnableCoolFeature of MainApp.class is: "+enableCoolFeatureAnnotation);

      System.out.println("@EnableCoolFeature value: "+AnnotationUtils.getValue(enableCoolFeatureAnnotation));
      System.out.println("@EnableCoolFeature default value data1: "+AnnotationUtils.getDefaultValue(enableCoolFeatureAnnotation, "data1"));
      System.out.println("@EnableCoolFeature default value data2: "+AnnotationUtils.getDefaultValue(enableCoolFeatureAnnotation, "data2"));
      System.out.println("@EnableCoolFeature data1: "+AnnotationUtils.getValue(enableCoolFeatureAnnotation, "data1"));
      System.out.println("@EnableCoolFeature data2: "+AnnotationUtils.getValue(enableCoolFeatureAnnotation, "data2"));

      String data1 = (String)AnnotationUtils.getValue(enableCoolFeatureAnnotation, "data1");
      String data2 = (String)AnnotationUtils.getValue(enableCoolFeatureAnnotation, "data2");

      // ... pass the arguments to Spring Boot: https://www.baeldung.com/spring-boot-command-line-arguments
      String[] args = { data1, data2 };
      SpringApplication.run(MainApp.class, args);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Edit: As the author asked how could unknown annotations be processed dynamically, here is an example. Before the code above can be executed, we need to retrieve the annotation classes and the field names according to a defined criteria. Paste the following code right after try { in the code above:
    try {
        MergedAnnotations mas = MergedAnnotations.from(MainApp.class);
        for (MergedAnnotation<Annotation> ma : mas)
        {
            Class<Annotation> annotationClass = ma.getType();

            Field[] fields = annotationClass.getFields();

            for (Field field:fields)
            {
                String fieldName = field.getName();

                // Retrieve the values as shown below with data1 and data2 but this time using annotationClass and fieldName.
            }
        }
    ....

In the original code example MainApp.class must be replaced by a parameter Class<?> appClass that must be supplied by your users when they call the main() method from their code. Or a better solution would be to rename the method and make it an instance method (not static), then let your users inherit from MainApp and then you can use directly getClass() to get your user's app class:
// This is part of your framework:
public class MainApp {

  protected void runSpring() {
     // ... same code
  }
}

// This is the code your users would have to write:
@EnableCoolFeature(data1 = "foo", data2 = "bar")
public class YourUsersApp extends MainApp {

  public static void main ()
  {
    new YourUsersApp().runSpring();
  }
}


text:
Q: How to delegate DNS for a subdomain to my own BIND9 server? I have a VPS (running Debian) and a domain ("mydomain.net"). What I want to achieve is this: I want to create a subdomain "home.mydomain.net" for dynamic hosts in my home, e.g. my NAS etc., so that I can resolve my NAS from everywhere with "nas.home.mydomain.net". (In the end I want to build my own DynDNS service, but the update part etc. is not the point here, I can handle that.)
Let's assume that I want to have a DNS entry for test.home.mydomain.net that points to 8.8.8.8 for now (as I can be sure that there will be an ICMP echo, I can change that later).
From what I read while researching how to configure things, I think I need to have these things:

*

*a BIND9 DNS server running on my VPS

*an A record in mydomain.net's DNS zone pointing to my own DNS server

*an NS record in mydomain.net's DNS zone that delegates requests for home.mydomain.net to the aforementioned nameserver on my VPS

In my VPS administration backend I can edit the DNS zone for my mydomain.net and I added the entries mentioned above, these are the entries now (123.123.123.123 stands for the fixed IPv4 address of my VPS):
mydomain.net        86400   SOA 0   ns1.myprovider.net. hostmaster.myprovider.net. 2018041707 3600 1200 2419200 86400
mydomain.net        86400   NS  0   ns1.myprovider.net
mydomain.net        86400   NS  0   ns2.myprovider.net
mydomain.net        86400   NS  0   ns3.myprovider.net
home.mydomain.net   86400   NS  0   ns.mydomain.net
ns.mydomain.net     86400   A   0   123.123.123.123
mydomain.net        86400   A   0   123.123.123.123
www.mydomain.net    86400   A   0   123.123.123.123

Is this correct so far? At this point I can successfully ping ns.mydomain.net.
When I do an nslookup www.mydomain.net from a separate Windows box, it gets resolved correctly to 123.123.123.123.
When I try to lookup something not existing like nslookup xyz.mydomain.net, I get an instant answer that the domain is not existing.
When I try to resolve e.g. test.home.mydomain.net, it takes some seconds until I get DNS request timed out.. From what I understand, this is correct so far, is it? The DNS request gets delegated to ns.mydomain.net, but there's nothing answering yet, so I get a timeout.
Next step: installing and configuring BIND9 on my Debian VPS. I freshly installed it (apt install bind9). Now I want to set it up in such a way that it only takes care of resolving hosts in home.mydomain.net. I don't need a full-grown DNS server that forwards for arbitrary requests etc., all I need is that it "feels responsible" for hosts in home.mydomain.net and (for now) resolves test.home.mydomain.net to 8.8.8.8. There's an overwhelming amount of information on bind9 configuration, but I did not manage to find out what exactly I need to do. Here's what I tried:
(Updated)
This is my /etc/bind/named.conf.local:
zone "home.mydomain.net" {
    type master;
    file "/etc/bind/db.home.mydomain.net";
};

And this is the corresponding /etc/bind/db.home.mydomain.net:
$TTL 5
@ IN SOA ns.mydomain.net. root.mydomain.net. (
    10;
    3600;
    1200;
    2419200;
    86400;
);
ns.mydomain.net  IN      A    [My NS IPv4 address]
ns.mydomain.net  IN      AAAA [My NS IPv6 address]
test             IN      A    8.8.8.8

This does not work after restarting bind9, I can't resolve test.home.mydomain.netto 8.8.8.8., I'm still running into a request timeout. I think I might not have completely understood the role of the SOA record, otherwise I missed something else. Can anybody tell me what's missing and/or wrong?
Update:
The above configuration works now - after adding A and/or AAAA records for my nameserver. It feels a bit strange that you have to give these records as they point to itself? Why is that?


text:
Q: Are there any equivalent for groovy """ in python? I'm very new to python. I'm from groovy and I use """" to write some text into files the way I wish.
Are there any equivalent way in python to?
Note that I want to create a file that has more than 20 lines. So I need some easy and elegant way.
Thanks in advance.

A: It's not clear what exactly you're asking about.
The ability to use ''' or """ for multi-line strings in Groovy was borrowed directly from Python, so of course you can do the exact same thing in Python.
However, the ability to use " or """ for interpolated strings in Groovy was borrowed from sh, and Python does not have the same feature. In Python, ' and " strings are identical, and neither does interpolation.
The idiomatic Python alternative is format. This is a method on the str and unicode classes, which you use like this:
s = """This is a string with a {variable} to fill in.
Here's a {second} one
""".format(variable="field", second="'nother")

If you write that to a file, you'll get this:
This is a string with a field to fill in.
Here's a 'nother one

There are plenty of variations. If you want to pass arguments by position instead of name, you can use {0} instead of {variable}—or, for simple cases where they're inserted in order, just use {} (but be careful with i18n). You can also put formatting information in, e.g., to print the repr (sort of "what you would type to get this value") instead of the str (a human-readable representation). Read the docs linked above for details.
Python also has an older mechanism, which is being gradually phased out, that uses the % operator and a format spec based on, but pretty different from, C-style printf. For example:
s = """This is a string with a %(variable)s to fill in.
Here's a %(second)s one
""" % {"variable": "field", "second": "'nother"}

Again, there are plenty of variations available; again, read the docs linked above for details. But really, you only want to use this if you're dealing with a lot of old code, or translating from printf or Windows-style or similar formats, or need to run on Python 2.5 or earlier.
If none of this is sufficient for you, there are 69,105 modules on PyPI (and recipes on ActiveState, etc.) for doing everything from as-close-to-perl-as-possible interpolation to templating HTML pages.

A: Python supports """ for escaping multi-line strings. Variable substitution is not immediately available, however.
multi_line_variable = """This
Is
The
Coolest
Ever."""

If you need variable substitution, you can use Python's printf formatting support or use a templating library like Jinja or the Django templating language.
Python 'printf' formatting:
>>> echo """Massive %s!""".format("string")
"Massive string!"

A: f = open(name_of_file, 'w')
f.writelines(list_of_lines_to_write)
f.close()

Or instead of writelines(), use f.write("""text_to_write_to_file""")


text:
Q: How do I ceil number (etc: 5 to 10) I have a problem with Math.ceil in Java, because it ceils and floors only decimal numbers. I need a function which can ceil or floor any number including an integer. For example if I have 5, I would want it to become 10 or if I have, for example 2, I would want it to become 0.
I am pretty sure that some easy function exists for this, but I could not find it. I would be really grateful for some examples on how to do that.

A: public class CustomCeiling {

    public static double getCeiling(double number){
        return Math.round(number/10)*10;
    }

    public static void main(String args[]){
        System.out.println(getCeiling(2));
        System.out.println(getCeiling(4));
        System.out.println(getCeiling(5));
        System.out.println(getCeiling(10));
    }
}


text:
Q: How to Convert to Hexadecimal using only while and if-else loops I have to convert a given number from decimal to hexadecimal using only the loops mentioned in the title. Meaning no for loops. So far everything works like converting 683. It prints 2AB no problem, and 34821 prints 8805. The issue is when there needs to be an integer in between two digits. For example I am unable to convert 31388 to 7A9C. I have an idea of what my issue is but I dont know how to fix it.
import java.util.Scanner;
public class Lab12abHexNumbersTEST
{
   public static void main(String[] args)
   {
     Scanner decimal = new Scanner(System.in);
     System.out.println("Enter a decimal number between 1 and 50,000: ");
     int num = decimal.nextInt();

     String hex1 = "";
     String letter = "";
     String hex3 = "";
     String hex_last = "";
     int dec = num;
     while (dec > 0)
     {
         hex1 = (dec % 16) + hex1;

         if(dec % 16 >= 9){
            hex1 = "";

            if(dec % 16 == 15) {
               letter = "F" + letter + hex1;
            } else if (dec % 16 == 14) {
               letter = "E" + letter + hex1;
            } else if (dec % 16 == 13) {
               letter = "D" + letter + hex1;
            } else if (dec % 16 == 12) {
               letter = "C" + letter + hex1;
            } else if (dec % 16 == 11) {
               letter = "B" + letter + hex1;
            } else if (dec % 16 == 10) {
               letter = "A" + letter + hex1;
            }

            System.out.println(letter);
         }
         hex3 = hex1 + letter;

         dec = dec / 16;

      }

      hex_last = hex3;
      System.out.println("The decimal number " + num + " in hexadecimal is "
+ hex_last);
  }
}

A: I have provided a solution to this problem.
Note: I have used switch statements to make the code cleaner, but I'm sure you know how to convert them back into if/else cases. If you need help, please ask.
Note: I have used a StringBuilder instead of strings directly. You can easily change these to strings, but I have chosen stringbuilder because again, it makes the code cleaner.
public static void main(String[] args) {
        int dec = 31388 ;
        StringBuilder hexString = new StringBuilder();

        while (dec != 0){
            int hexDigit = dec%16; // obtain this remainder
            dec /= 16; //update dec

            if (hexDigit < 10) hexString.insert(0, hexDigit);
            else {
                switch (hexDigit) {
                    case 10 :
                        hexString.insert(0, "A");
                        break;
                    case 11 :
                        hexString.insert(0, "B");
                        break;
                    case 12 :
                        hexString.insert(0, "C");
                        break;
                    case 13 :
                        hexString.insert(0, "D");
                        break;
                    case 14 :
                        hexString.insert(0, "E");
                        break;
                    case 15 :
                        hexString.insert(0, "F");
                        break;
                    default: break;
            }
        }
    } // while
    System.out.println(hexString);
}

Output: 7A9C
converted to an if/else block on request:
else {
            if (hexDigit == 10) {
                hexString.insert(0, "A");
            } else if (hexDigit == 11) {
                hexString.insert(0, "B");
            } else if (hexDigit == 12) {
                hexString.insert(0, "C");
            } else if (hexDigit == 13) {
                hexString.insert(0, "D");
            } else if (hexDigit == 14) {
                hexString.insert(0, "E");
            } else if (hexDigit == 15) {
                hexString.insert(0, "F");
            }
        }

Using strings, the solution is:
public static void main(String[] args) {
    int dec = 31388;
    String answer = "";

    while (dec != 0){
        int hexDigit = dec%16; // obtain this remainder
        dec /= 16; //update dec

        if (hexDigit < 10) {
            answer = hexDigit + answer;
        }
        else {
            if (hexDigit == 10) {
                answer = "A" + answer;
            } else if (hexDigit == 11) {
                answer = "B" + answer;
            } else if (hexDigit == 12) {
                answer = "C" + answer;
            } else if (hexDigit == 13) {
                answer = "D" + answer;
            } else if (hexDigit == 14) {
                answer = "E" + answer;
            } else if (hexDigit == 15) {
                answer = "F" + answer;
            }
        }
    } // while
    System.out.println(answer);
}

A: If String functions are allowed:
import java.util.*;

public static void main(String[] args){
    int dec = 31388 ;
    String digits = "0123456789ABCEDF";
    StringBuilder hexString = new StringBuilder();

    while(dec != 0){
        hexString.insert(0, digits.indexOf(dec % 16));
        dec /= 16;
    }

    System.out.println(hexString);
}


text:
Q: SQL Server 2008 - Log file out of control & cant shrink it
Possible Duplicate:
Why Does the Transaction Log Keep Growing or Run Out of Space?

I am having trouble with my database, the log files is currently 250GB in size, I need to shrink this down somehow.
I have tried backing up the transactional log files, performing a full backup, running various shrink scripts but to no avail.
What are the correct steps to make this happen?
Can I somehow just truncate the whole log file then perform a full backup?
Thank You,
Paul

A: Do you need point it time recovery?  If not then change the database's recovery model to Simple.
Does the database have mirroring or replication configured?  That can also cause the transaction log to blow up quite large.

A: Paul Randal has a good post on this topic: http://sqlskills.com/BLOGS/PAUL/post/Search-Engine-QA-1-Running-out-of-transaction-log-space.aspx


text:
Q: SwiftUI: TabView and NavigationView play nicely on iPhone but not on iPad? My app has a home screen showing a list of options and a few entirely different pages. Each leads to a dispatcher view with a tag indicating which page to show. I also want to be able to swipe between the pages. So I have this code (hugely simplified from the actual app, of course, but behaving in the same way):
struct Tab: Hashable {
    let name: String
    let id: Int
}

struct ContentView: View {

    let tabs: [Tab] = [Tab(name: "first", id: 1), Tab(name: "second", id: 2), Tab(name: "third", id: 3)]

    var body: some View {
        NavigationView {
            Form {
                List (tabs, id: \.self) { tab in
                    NavigationLink(destination: Dispatcher(which: tab.id)) {
                        VStack (alignment: .leading) {
                            Text(tab.name).font(.headline).bold()
                        }
                    }
                }
            }.navigationTitle("test")
            Text("hello")
        }
    }
}

struct Dispatcher: View {
    var which: Int
    @State private var tab = 2

    var body: some View {
        TabView(selection: $tab) {
            Text("first page").tag(1)
            Text("second page").tag(2)
            Text("third page").tag(3)
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
        .onAppear(perform: { tab = which })

    }
}

On an iPhone, it works fine. But on an iPad, in either orientation, tapping any option in the home page takes me to the same sub-page, the one set by the initial value of the @State variable tab. The assignment in .onAppear is being executed, but the new value of tab is being ignored.
Any ideas gratefully received.
Jeremy

A: why not just do this:
struct Dispatcher: View {
    @State var which: Int

    var body: some View {
        TabView(selection: $which) {
            Text("first page").tag(1)
            Text("second page").tag(2)
            Text("third page").tag(3)
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
    }
}

A: Now that workingdog has answered my question, can I perhaps expand it?
I implement his (or her, of course) solution on the iPad. I click on a selection in the NavigationView list (say, "second"). The clicked line highlights and the second page appears.
I then swipe to show another page (say "third"). That's fine.
But "second" remains highlighted in the NavigationView list, so I can't click on it to return to the second page.
Can I tell the NavigationView list to highlight the entry corresponding to the actual shown page? Or to highlight nothing?


text:
Q: How to export unicode data into word document using php com I am exporting unicode data using Php COM. I have written in top of my web page the below line:
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>

But when I export the unicode data into a word document using Php COM, It is not coming properly like a unicode, Instood it is coming as shown below:
ಆದಿಯಲà³à²²à²¿ ದೇವರೠಆಕಾಶವನà³à²¨à³

I use the Php COM code to export the data to word document as below:
$unicode_data = "ಆದಿಯಲ್ಲಿ";
$word = new variant(com_get_active_object("word.application"));
$word->Selection->TypeText($unicode_data);

So please suggest me what else should be included to above code to get a unicode in correct format in the word document.
(From comment)
CREATE TABLE kan (
    id int(15) NOT NULL AUTO_INCREMENT,
    content text CHARACTER SET utf8 NOT NULL,
    PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=31105 DEFAULT CHARSET=latin1

A: You wanted some Kannada text like 'ಆದಿಯಲ...'?
You should not have to mention "unicode" anywhere.
Your 'meta' and connection look correct.
Please go to Trouble with utf8 characters; what I see is not what I stored and look at the recommended SELECT .. HEX.  Does the hex look something like this (but without spaces)?
E0B286 E0B2A6 E0B2BF E0B2AF

If so, it was stored correctly.  If not, then you have "double encoding" and the hex will be more like
C3A0 C2B2 E280A0 C3A0 C2B2 C2A6 C3A0 C2B2

utf8 E0B286   is Unicode  3206=x0C86 representing [ಆ] KANNADA LETTER AA


text:
Q: Reading A File including tabs I have a file consisting of 23 rows. In every row, there are six different strings and these are separated from one another via \t(tab character). In other words, I have a tab separated file.
1)Is it possible to read this file by using fread of fscanf ?
2)If it is not possible, How can I read the file ?

A: You could use sscanf function:
 char string1[SIZE];
 char string2[SIZE];
 char string3[SIZE];
 char string4[SIZE];
 char string5[SIZE];
 char string6[SIZE];

 char line[200];

  FILE *inFile;
  char *inName = "myFile.txt";

  int i = 0;

  inFile = fopen(inName, "r");
  if (!inFile) {
    printf("Couldn't open %s for reading\n");
    return 0;
  }

  while(i < 23 && fgets(line, sizeof(line), inFile) != NULL){
        sscanf( line, "%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\t]\t%[^\n]\n", string1, string2, string3, string4, string5, string6 );
        printf( "%s\t%s\t%s\t%s\t%s\t%s\n", string1, string2, string3, string4, string5, string6 );
        i++;
 }


text:
Q: How to convert a blob from db to a List in java All I'm trying to do is to convert my java List to BLOB and vice-versa. I have successfully done the first part where I have converted my List and stored it as BLOB in DB. However, I'm to get the BLOB but unable to convert it back to List. I have tried searching at many places but not able to figure out a way to solve this problem I'm facing. Hope I'll get a solution here.
Converting the List and storing it as BLOB in DB:
List<CustomerDTO> customersList = new ArrayList<CustomerDTO>();
.
.
some code to store the data in to List<CustomerDTO>
.
.

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(customersList);
byte[] bytes = baos.toByteArray();

// set parameters
    pstmt.setBinaryStream(1, new ByteArrayInputStream(bytes));
    pstmt.executeUpdate();

Failed attempts of converting BLOB to List:
1)
Blob blob = rs.getBlob("CUSTOMERS_LIST");
byte[] bdata = blob.getBytes(1, (int) blob.length());
ByteArrayInputStream bais = new ByteArrayInputStream(bdata);
ObjectInputStream ois = new ObjectInputStream(bais);

List<CustomerDTO> list = (ArrayList<CustomerDTO>) ois.readObject();

This attempt has given me empty list
2)
Stream<T> stream = (Stream<T>) rs.getBinaryStream("CUSTOMERS_LIST");
List<CustomerDTO> list = (List<CustomerDTO>) stream.collect(Collectors.toList());

This attempt thrown me error java.lang.ClassCastException: java.io.ByteArrayInputStream cannot be cast to java.util.stream.Stream
3)
IntStream bais = (IntStream) rs.getBinaryStream("CUSTOMERS_LIST");
Stream<Integer> stream = (Stream<Integer>) bais.boxed().collect(Collectors.toList());
List<Integer> ll = (List<Integer>)stream.collect(Collectors.toList());

I'm lost here as I don't get how to convert List<Integer> to List<CustomerDTO>
Looking forward for your help.. TIA!

A: I have modified your first attempt slightly as follows:
Blob blob = rs.getBlob("CUSTOMERS_LIST");
byte[] bdata = blob.getBytes(1, (int) blob.length());
ArrayList<Object> arraylist = new ArrayList<>();
for(byte b : bdata) {
    arraylist.add(new Byte(b));
}


text:
Q: Unclear TLS Rec Layer-1 Encrypted Alert I am trying to access a remote webservice from an asp.net application in an iis 6 server to a remote webserver.
As I wasn't able to connect, I used MS Network Monitor to look over what was happening.
This is the TLS progress
2   15:26:31 14.03.2013 0.0000000       yyy.yyy.yyy.yyy XXX.XXX.XXX.XXX TLS TLS:TLS Rec Layer-1 HandShake: Client Hello.    {TLS:4, SSLVersionSelector:3, TCP:2, IPv4:1}
3   15:26:31 14.03.2013 0.0312500       XXX.XXX.XXX.XXX yyy.yyy.yyy.yyy TLS TLS:TLS Rec Layer-1 HandShake: Server Hello.; TLS Rec Layer-2 HandShake: Certificate.   {TLS:4, SSLVersionSelector:3, TCP:2, IPv4:1}
4   15:26:31 14.03.2013 0.0312500       yyy.yyy.yyy.yyy XXX.XXX.XXX.XXX TLS TLS:TLS Rec Layer-1 HandShake: Certificate. Client Key Exchange. Certificate Verify.; TLS Rec Layer-2 Cipher Change Spec; TLS Rec Layer-3 HandShake: Encrypted Handshake Message.   {TLS:4, SSLVersionSelector:3, TCP:2, IPv4:1}
5   15:26:31 14.03.2013 0.0468750       XXX.XXX.XXX.XXX yyy.yyy.yyy.yyy TLS TLS:TLS Rec Layer-1 Cipher Change Spec; TLS Rec Layer-2 HandShake: Encrypted Handshake Message. {TLS:4, SSLVersionSelector:3, TCP:2, IPv4:1}
6   15:26:31 14.03.2013 0.0781250       XXX.XXX.XXX.XXX yyy.yyy.yyy.yyy TLS TLS:TLS Rec Layer-1 Encrypted Alert {TLS:4, SSLVersionSelector:3, TCP:2, IPv4:1}

And this is final TLS transaction with the alert
  - TlsRecordLayer: TLS Rec Layer-1 Encrypted Alert
     ContentType: Encrypted Alert
   - Version: TLS 1.0
      Major: 3 (0x3)
      Minor: 1 (0x1)
     Length: 18 (0x12)
     EncryptedData: Binary Large Object (18 Bytes)

And finaly this is the hex dump for the alert part.
15 03 01 00 12 CE CA A3 1C C9 44 5C AC A2 3C BB 3C F3 F9 8A A6 4F 22

According to http://en.wikipedia.org/wiki/Transport_Layer_Security#Alert_protocol I tried to decode the meaning
15 = 21 dec <- always 21
03 01 = major and minor Version
00 12  = lentgh

And now it gets weird. Normaly the next two bytes should be the level and description of the alert. But they make no sense. Beside that, they differ every trace I run. While the front part stays constantly the same.
Any ideas how i can decrypt the alert?
My first thought was that the other side may not allow TLS 1, while IIS 6 only supports TLS 1 (atleast that is what i thougt).
Thanks alot in advanced

A: The alert itself is encrypted, because the handshake was successful. So before you know what it says, you have to decrypt it - you could use ssldump, in case you have the server's private key.
Found this here: http://www.wireshark.org/lists/ethereal-users/200110/msg00055.html - after I puzzled about the same problem for a while.
This is about ssldump: http://www.rtfm.com/ssldump/
Using Wireshark, you can decrypt everything, in case you have the private key that was used for encryption: http://support.citrix.com/article/ctx116557


text:
Q: Distribution of random Fourier coefficients Let $f : \{0, 1\}^{n} \rightarrow \{-1, 1\}$ be a Boolean function. Let the Fourier coefficients of this function be given by
$$ \hat f(z) = \frac{1}{2^{n}} \sum_{x \in \{0, 1\}^{n}} f(x)(-1)^{x \cdot z}$$
for each $z \in \{0, 1\}^{n}$, where $x \cdot z$ is the bitwise inner product between $x$ and $z$. Let me choose a function uniformly at random from the set of all Boolean functions $$\{f : \{0, 1\}^{n} \rightarrow \{-1, 1\}\}. $$
What is the distribution that the square of each Fourier coefficient $\hat f(z)^{2}$ is distributed as?

A: $\hat{f}(z)$ is $\frac{1}{2^n}$ times the sum of $2^n$ iid Bernoulli random variables taking on the values $1, -1$ with probability $\frac{1}{2}$ each, for every $z$ (the signs $(-1)^{x \cdot z}$ don't affect this!). So it has a binomial distribution: we have
$$\mathbb{P} \left( \hat{f}(z) = \frac{2^n - 2k}{2^n} \right) = \frac{1}{2^{2^n}} {2^n \choose k}.$$
So the square is distributed as the square of this binomial distribution; I don't know if it has a name but its properties are deducible from the properties of a binomial distribution. In particular its mean is the variance of $\hat{f}(z)$, which is $\frac{1}{2^n}$. As a sanity check, Parseval's theorem gives
$$\| f \|^2 = 1 = \| \hat{f} \| = \sum_{z \in \{ 0, 1 \}^n} \hat{f}(z)^2$$
so if $\mathbb{E}(\hat{f}(z)^2)$ is independent of $z$ it must be equal to $\frac{1}{2^n}$.


text:
Q: JQuery Events only affecting the first element? Alright, so I am making a site using PHP. It's a site that allows users to log in and create flashcards to view online. I added in some JQuery for a slick design and it is looking much better.
However, I've reached a snag.
I made a jQuery command that hides the answer and when you roll over the flashcard, it shows it.
And it works... only for the first first flash card.
First, it would work out just fine... All of the answers are hidden. And when I roll over the first flash card, it shows my answer. However, for the others it doesn't work out that way. They just stay hidden.
Here is my code:
$(document).ready(function(){

        $('mark').hide();
        $('#card').mouseover(function() {
                $('mark',this).show();
        });
        $('#card').mouseout(function() {
                $('mark',this).hide();
        });
});

And here is the structure for each flashcard:

Question is here!

 Answer is here!

What do you think I'm missing here?
If you want to play with it for yourself, here's my github:
https://github.com/Lalien/Test_Site

A: From a syntax perspective, first line should be $('#mark').hide();
And to answer your question, define 'card' as a class if you want the behaviour on multiple cards. A page can have multiple classes but only 1 ID from the perspective of javascript due to which all the divs with id as 'cards' except the first one are ignored.


text:
Q: How to highlight where a calcuation/value equals BETWEEN two prices/levels? I am looking for a quick solution in Pine Script where an alert is triggered where a series of conditions are met.
Upon further analysis, I noticed that more accurate signals occur where outK3ref1 sits within the range from 70 to 80
buy_alert1 = crossUpAll and (outK3ref1 = *******) and (stfcheckB<20) ? 1 : 0

None of the standard operators sound like they would give me the result I am after, I have tried a few combinations with no luck...

A: You should use the and operator as well as greater-or-equal >= and lesser-or-equal <= enclosed in brackets to accomplish what you need.
buy_alert1 = crossUpAll and (outK3ref1 >= 70 and outK3ref1 <= 80) and (stfcheckB<20) ? 1 : 0

Also be careful, = is for assignment of value to a variable, == is for checking if two expressions are equal to each other.
a = 1 // assign 1 to a
a == 1 // returns true if a is equal to 1


text:
Q: Lookup using multiple columns I have a sheet filled with data below (and in the image):

Now there's this other sheet where the user will only be inputting the column "Gender" and "Age" values and the excel formula should be fetching the associated factor. Please help me with one such formula.
For e.g. If the user puts Male and 23, the formula should return 3. say Male was entered in Cell D46 and 23 was entered in E46 of Sheet named "Sheet4" and the table shown above happens to be in "Sheet1"
Please advise.

A: Right, now I can visualize what you meant in your other comments in your previous question, it's a rather easy redo of our other formula.

Formula in F3:
=INDEX(C1:C13,MATCH(1,(ROW(C1:C13)>=MATCH(F1,A1:A13,0))*(B1:B13=F2),0))

Entered through CtrlShiftEnter
Notice that these formulas will return a wrong result if, lets say you extend till females age of 29, and you will search for male, it will still return the value for female. It will however not fail when your searchcriteria would be always right.
You could prevent this in this case (because you only really have one criteria and a fixed range with this formula in F3:
=IFERROR(IF(F1="Male",INDEX(C2:C9,MATCH(F2,B2:B9,0)),INDEX(C10:C13,MATCH(F2,B10:B13,0))),"No result")

Just enter normally. What it does is it checks what gender type is chosen and choses it's lookup index accordingly.
Another option would be to use SUMPRODUCT() like so :
=IF(F1="Male",SUMPRODUCT((B2:B9=F2)*(C2:C9)),SUMPRODUCT((B10:B13=F2)*(C10:C13)))

Also, if you are curious what formulas do and want to learn from them, a great way to do so is using the build-in formula evaluate function, that will show you step by step what the formula will calculate.
EDIT
Tried, as per your comment, to break it down for you so you understand what is going on:

A: For situations like this, I've learned a good trick how to fill in the blank cells:

*

*Select all cells in the column with the "gender" values.

*Goto Special, Blanks. (You active cell should be A3)

*In the formula bar, type =A2. (I believe that A2 contains the word "Male")

*Press Ctrl+ENTER (don't forget the Control key for filling all selected cells)

As a result, A3 will be copied from A2 and contain the word "Male", A4 will be copied from A3 and will now also contain the word "Male", ...
Further: this stops at the first occurence of the word "Female" (this cell is not selected), and for the later cells, the copying happens in the same way as before.
From here, it should be far easier to achieve your goal.


text:
Q: OCMock is not cleaning up stubbed class methods I'm trying to use OCMock to mock out internal class dependencies (e.g. my class uses an NSMutableData and verifying against a mock NSMutableData). Specifically I'm mocking factory methods to return mock objects.
As far as I can tell the mock objects are not cleaning up class method mocks, or only cleaning them up partially. This is having pretty adverse effects on unrelated tests that may end up invoking the same class methods.
A short example I've been able to repro locally to illustrate:
id data1 = [NSMutableData data];    // new instance
id data2 = [NSMutableData data];    // new instance

// mock +data and have it return data1
id mock = [OCMockObject mockForClass:[NSMutableData class]];
[[[[mock stub] classMethod] andReturn:data1] data];

id foo = [NSMutableData data];  // foo == data1 ok that's good

[mock stopMocking];
mock = nil;                     // using ARC so no explicit -release

id bar = [NSMutableData data];  // bar == data1, wait what? shouldn't this be new?

I've found the problem even worse if you mock +new. That last line where I create bar blows up with either a bad string hash or a stack overflow (I'm not sure how to consistently get one or the other, I've seen both).
I realize there's ways around this. I could inject an NSMutableData instance into my class, which feels like overkill since it's not a hard dependency. I could have an instance method on my class that creates NSMutableData and I partially mock my class instead to inject the mock. That's fine but I would really like to know why this particular case doesn't work. Mocking internal dependencies would be quite a bit easier if I could actually stub out the factory methods!
This issue is not limited to anything particular about NS classes (I'm aware of the limitations around mocking NSString for example) as I can repro the above issue with one of my own classes just as easily.


text:
Q: PHP variable won't print I have an html file with a form (with method=get) with inputs that takes a username with name user, and password pwd.
The submit button then directs to a file called admin.php which looks like this:
admin.php:
<html>
<body>
<?php
    echo "user: $user";
?>
</body>
</html>

I can see the variables in the url being passed over, but when I load my admin.php it only prints user: and nothing else. I know this is probably a stupid question, but why is this so?

A: This will make it work.
$user = $_GET['user'];

A: Try printing it like so:
echo "user: " . $_GET['user'];

A: echo "user: " . $_POST['user'];


text:
Q: file not creating in android internal storage This is function for saving images. I am trying to save the image name (from gallery) to a file (preferably csv file). but the android is not creating the file. need help in creating the file in android internal storage.
public void saveImage(String imagePath){
    String[] arrOfStr = imagePath.split("/");             //splitting full image path by / to only get the image name e.g 00001.jpg
    String imageName = null;

    for (String a : arrOfStr)
        imageName = a;                             // imageName only contains the imageName i.e 00001.jpg

    String filename = "test_ids.txt";

    try {
        File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, filename);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(imageName);
        writer.flush();
        writer.close();
        Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "Not Saved", Toast.LENGTH_SHORT).show();
    }

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
    //super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_CANCELED) {
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK && data != null) {
                    Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
                    imageView.setImageBitmap(selectedImage);

                }

                break;
            case 1:

                if (resultCode == RESULT_OK && data != null) {

                    Uri selectedImage = data.getData();

                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    if (selectedImage != null) {
                        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                        if (cursor != null) {
                            cursor.moveToFirst();

                            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                            String picturePath = cursor.getString(columnIndex);

                            saveImage(picturePath);                     // a function to save images
                            imageView.setImageURI(selectedImage);

                            cursor.close();

                        }
                    }

                }
                break;


text:
Q: A code with "getElementsByClassName( )[ ]" with square bracket? What does it do? How can it be converted to jQuery? I have a code in the snippet that has a document.getElementsByClassName("close")[0], what the [0] is doing?
I never seen a square brackets being used in getElementsByClassName for what purpose is it used for?
Also, how can I convert it to jQuery?

var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
  modal.style.display = "block";
}
span.onclick = function() {
  modal.style.display = "none";
}
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
body {font-family: Arial, Helvetica, sans-serif;}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0,0,0);
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

Modal

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

A: document.getElementsByClassName returns array-like object of elements.
[0] takes first element of that array.
Basically:
let elements = document.getElementsByClassName('close');

let span = elements[0];


text:
Q: How to get bit from bytearray in python? I want to get the particular bit value from bytearray. I tried and its working fine, but let me know is there any optimize way to do this.
in_bytes = bytearray()
in_bytes .extend([5,10,15]) # output : bytearray(b'\x05\n\x0f')
tk = in_bytes [0]
bk = in_bytes [1]
sk = in_bytes [2]
print(tk, bk, sk) # 5 10 15
bk = 10 << 8
sk = 15 << 16
res = sk | bk | tk
print(res) # 985605

def get_bit_value(number, bit_position):
    return (number >> bit_position) & 1
bit_value = get_bit_value(985605, 2)
print(bit_value) #

From this bytearray b'\x05\n\x0f', how can i get particular bit value?


text:
Q: Proving the exponential laws for rational exponents I have managed to prove the usual exponent laws for integer exponents, using induction on the natural numbers.  I am now trying to prove that the laws also hold for rational exponents.  I'm starting by trying to prove the law $x^nx^m = x^{n+m}$, where $n = \frac a b$ and $m = \frac c d$.
Using the following definition:
$x = y^{\frac a b} \iff x^b = y^a$
I can prove it as follows:
$x^{\frac a b}x^{\frac c d} = x^{\frac {ad} {bd}}x^{\frac {bc} {bd}} = (x^{ad})^{\frac 1 {bd}}(x^{bc})^{\frac 1 {bd}} = (x^{ad}x^{bc})^{\frac 1 {bd}} = (x^{ad+bc})^{\frac 1 {bd}} = x^{\frac {ad + bc} {bd}} = x^{{\frac a b}+{\frac c d}}$
Aside from the definition, I have proved no other things about rational exponents.  So, the problem I have is that I use the following assumptions in this proof:

*

*$x^{\frac a b} = (x^a)^{\frac 1 b}$

*$(xy)^{\frac a b} = x^{\frac a b}y^{\frac a b}$

Both assumptions I need to prove but I cannot figure out how.  Can anyone help?
Edit:  I now realize the proof of (1.) is trivial: $y = (x^a)^{\frac 1 b} \iff y^b = (x^a)^1 = x^a \iff y = x^{\frac a b}$.  For (2.) as far as I get is proving that $(xy)^{\frac a b} = (x^ay^a)^{\frac 1 b}$

A: Let $x, y$ be not negative, $a=1$ and $b$ odd.
$$y=x^{\frac{1}{b}} \overset{def.}\Leftrightarrow y^b=x \Leftrightarrow y= \sqrt[b]{x}.$$
Now let $x, y$ not negative, $a$ be arbitrary and $b$ odd.
$$y=x^{\frac{a}{b}} \overset{def.}\Leftrightarrow y^b = x^a \Leftrightarrow \sqrt[b]{y^b} = \sqrt[b]{x^a} \Leftrightarrow y = \sqrt[b]{x^a} $$
Since $(\sqrt[b]{x^a})^b = x^a$ and by your proof for integer exponents $((\sqrt[b]{x})^a)^b = (\sqrt[b]{x})^{ab} = x^a$, we have $(\sqrt[b]{x^a})=(\sqrt[b]{x})^a$.
Now let $x, y$ be not negative and $b, d$ odd.
$$x^{\frac{a}{b}}x^{\frac{c}{d}}=x^{\frac{ad}{bd}}x^{\frac{bc}{bd}} = (\sqrt[bd]{x})^{ad} (\sqrt[bd]{x})^{bc} \overset{\text{form the integer result}}=(\sqrt[bd]{x})^{ad+bc}= x^{\frac{ad+bc}{bd}}.$$
For even denominators you basically do the same, but pay attention because even roots are not unique ($x^2 = 2 \Rightarrow x= \sqrt{2}$ or $- \sqrt{2}$).
Also note that you have to place proper restrictions on the domain of $x$ and $y$, as for example you might not want to have $\sqrt{-1}$.


text:
Q: I am trying to send.keys a value that I calculated and then click the save button but the value isn't saving, why is this? The value I want to calculate is being calculated properly, and the value is being sent and I can see it being typed, but when I click the save button, the value isn't saving.
When I go back to look at the value it isn't there.
How do I change this?
Correction - it saves some times but it doesn't other times, I don't get it.


text:
Q: Can't create foreign key on mysql table When I try this
ALTER TABLE Comp_Entry
ADD FOREIGN KEY(CompetitionID) REFERENCES Comp__Competition(CompetitionID)

I get this error
#1005 - Can't create table 'chris_db.#sql-1464b_66' (errno: 150) (Details...)

My Comp_Competition table has CompetitionID set as the primary key. Is anyone familiar with this problem?

A: Your Comp_Entry table needs an existing index for CompetitionID. Also, your command has a double __ characters in the name for table Comp__Competition, but in your explanation you have only one. Which one is right?

A: Because there is data in your table which does not feet to your constraint (for example nonexistent keys)
try to make
     select * from Comp_Entry where CompetitionID not in
        (select distinct CompetitionID from Comp__Competition)


text:
Q: error message on page close I have a Visualforce Page that will show an error message if a user tries to exit page without hitting one of the command buttons. It shouldn't trigger if the user clicks on the command buttons.
This works as long as the user doesn't try to leave page and hits 'stay on page'. Once they do this - it shows the error message no matter what button is selected.
Any suggestions?
Here is command button onclick code:
onclick="NoPrompt();"

Here is the script on page:
<script LANGUAGE="JavaScript1.2" TYPE="text/javascript">

    var allowPrompt=true;

    function unloadMessage(){
        if(allowPrompt){
            message = "Wait! Please hit 'Save and Close' before exiting the page."
        }
        else{
            allowPrompt = true;
        }
        return message;
    }

    function setBunload(on){
        window.onbeforeunload = (on) ? unloadMessage : null;
    }

    setBunload(true);

    function NoPrompt()
    {
      allowPrompt = false;
    }

</script>


text:
Q: Reading data from Excel sheet containg multiple tables using C# Let's say I have an Excel file contains one sheet, and in this sheet there is 2 tables one for employee with fields [empID,empName,title] and another table for department with fields [deptId,deptName].
I want to know how can I read data from that Excel file and load both tables in datatables, one for emplyee and the other for department.
I have searched and find that I can query through sheet by "select * from [sheet$]" after making an oleDbconnection with Excel but in my case the sheet contains two tables different in structure.
I am working on a Windows application using VS2010 C#.

A: Firstly, make a SheetSelectionForm. Then put these codes on your form, and call PopulateSheetsOfExcelFile(excelFilePath) method. This Form will show you to names of Excel sheets and you can select which sheet you want to read from Excel.
As you say, these tables have different structure, so you need to make different DataTables for each sheet of Excel.
There is another way to read whole Excel with DataAdapter. With my method, you create custom DataTable, and fill that with giving excel column/row index.
using System.Data.OleDb;

private void SelectItem()
        {
            ExcelSheetName = excelSheetsListBox.SelectedItem != null ?
                excelSheetsListBox.SelectedItem.ToString() : string.Empty;
            Close();
        }

private void PopulateSheetsOfExcelFile(string excelFilePath)
        {
            try
            {
                String connString = string.Empty;

                try
                {
                                      connString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"", excelFilePath);
                    using (OleDbConnection objConn = new OleDbConnection(connString))
                    {
                        objConn.Open();
                        using (DataTable dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))
                        {
                            if (dt == null)
                                return;

                            excelSheetsListBox.Items.Clear();

                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                DataRow row = dt.Rows[i];
                                excelSheetsListBox.Items.Add(row["TABLE_NAME"].ToString());
                            }
                        }
                    }
                }
                catch (Exception exA1)
                {
                                        connString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"", excelFilePath);
                    using (OleDbConnection objConn = new OleDbConnection(connString))
                    {
                        objConn.Open();
                        using (DataTable dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))
                        {
                            if (dt == null)
                                return;

                            excelSheetsListBox.Items.Clear();

                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                DataRow row = dt.Rows[i];
                                excelSheetsListBox.Items.Add(row["TABLE_NAME"].ToString());
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
               MessageBox.Show("HATA");

                ExcelSheetName = string.Empty;
                Close();
            }
        }


text:
Q: Getting new records from query based on values of older records I have a query scope that checks which matches have to be add on to the query based on what the current time is.
 Matches will be displayed if the start_date from that match is between this Tuesday and the next Tuesday and they also need a status field of SCHEDULED.
A new set of matches has to be loaded when that matchday comes to an end. This can either be Sunday or Monday. now I noticed that the next matchday will start on november 24th, this means that on Tuesday november 13th, no matches will be add on to the query. Working with times will not be a useful method if I still want the upcoming matches to be displayed the day after the last match has finished.
My goal is to always add the new upcoming matches when all current matches have ended.
Code
Query
 $matches = Match::thisWeekScheduled()->get();

Scope for getting correct matches based on time
public function scopeThisWeekScheduled($query) {
    $start_date = now()->previous(Carbon::TUESDAY);
    $end_date = now()->next(Carbon::TUESDAY);
    return $query->whereDate('date','>', $start_date)->whereDate('date','<', $end_date)->where('status', 'SCHEDULED');
}

Match migration
Schema::create('matches', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
    $table->integer('match_id');
    $table->string('homeTeam');
    $table->string('awayTeam');
    $table->string('status');
    $table->dateTime('date');
    $table->integer('matchday');
    $table->integer('homeScore')->nullable();
    $table->integer('awayScore')->nullable();
});

// last match of this matchday

// match_id  = 233136
// homeTeam  = Arsenal FC
// awayTeam  = Wolverhampton Wanderers FC
// status    = FINISHED
// date      = 2018-11-11 16:30:00
// matchday  = 12
// homeScore = 1
// awayScore = 1

// First upcoming match

// match_id  = 233144
// homeTeam  = Fulham FC
// awayTeam  = Southampton FC
// status    = SCHEDULED
// date      = 2018-11-24 15:00:00
// matchday  = 13
// homeScore = NULL
// awayScore = NULL

Extra information:

*

*I have every match of the season in my database. Matches have a
status of SCHEDULED or FINISHED.

*Im using a scheduled task that gets the updated match information from an API. Status of the match gets updated when the API has different values.

*A matchday has 10 matches

Any tips on approaching my issue?

A: $matches = Match::where('created_at', '>=', Carbon::now()->subDays(14)->toDateTimeString());
here You can use subDays() has value as you want to show previous days ..i use for 14 days


text:
Q: deploy XSLT list view webpart using "AllUserWebPart" through a feature from the solution package I am trying to deploy custom pages from feature. I came to know that the webparts(oob or custom) are to be deployed from the elements file using the "AllUserWebPart" wherein we have to include the ".webpart" or ".dwp" file of the webpart on our page(if you export the webpart you can have its .webpart file).
However once i deploy my feature and activate it, the pages get deployed with the webpart. But the custom view which i attached to my xsltlistview before extracting is changed and set back to the default view of the list.
I need help in fixing the rendering of correct list view with the webpart.

A: Unfortunately, the custom view that you created is not expored with the XSLTListView web part. This is why it is resetting to the default view.
The only solution I've found to this was to include my view in the list definition of the list I was going to create an XSLTListViewWebPart for, and then I could point my XSLTListViewWebPart at that view using the BaseViewID.
I'd also expect to put this in a "View" tag, not an "AllUserWebPart" tag - something like:
<View List="303" BaseViewID="0" WebPartZoneID="BlogNavigator" WebPartOrder="1">
<![CDATA[
    <webParts>
        <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
        <metaData>
            <type name="Microsoft.SharePoint.WebPartPages.XsltListViewWebPart,Microsoft.SharePoint,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" />
            <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
        </metaData>
        <data>
        <properties>
            <property name="ChromeType" type="chrometype">None</property>
        </properties>
        </data>
        </webPart>
    </webParts>
]]>
</View>


text:
Q: Read Sharepoint list into object I need to compare an xml document with the records in a SharePoint list in a vb.Net client side application. Using Visual Studio 2015.
My plan was to read all list items in an object. I am fine until I read the list into an XElement object, but cannot really go further. I wanted to deserialize it, but running into issues.
The parsed XML looks like (I removed lots of attributes):
<?xml version="1.0" encoding="utf-8"?>
<rs:data ItemCount="3" xmlns:rs="urn:schemas-microsoft-com:rowset">
    <z:row ows_Title="Customer1" xmlns:z="#RowsetSchema" />
    <z:row ows_Title="Customer2" xmlns:z="#RowsetSchema" />
    <z:row ows_Title="Customer3" xmlns:z="#RowsetSchema" />
</rs:data>

And when I try to serialize this, I get the error message:
Message=<data xmlns='urn:schemas-microsoft-com:rowset'> was not expected.

I tried to deserialize every single row, but then another, similar message appeared:
Message=<row xmlns='#RowsetSchema'> was not expected.

This is the relevant part of the code:
result = lists.GetListItems(strListID, strViewID, query, viewFields, 2000, queryOptions, Nothing)

Dim customerslist As XElement = XElement.Parse(result.ToString)
Dim customers As XElement = XElement.Parse(customerslist.Nodes(0).ToString)
Dim kwcusts As New kwCustomers
For i As Integer = 0 To customers.Nodes.Count
    Dim customer As XElement = XElement.Parse(customers.Nodes(i).ToString)
    Dim kwcust As New kwCustomer
    Dim reader As IO.StringReader = New IO.StringReader(customer.ToString)
    Dim xRoot As New Xml.Serialization.XmlRootAttribute
    xRoot.Namespace = "#RowsetSchema"
    Dim xmlserializer As New Xml.Serialization.XmlSerializer(kwcust.GetType, xRoot)
    kwcust = xmlserializer.Deserialize(reader)
    kwcusts.customers.Add(kwcust)
Next

Probably I am missing something trivial, so in anyone sees it, please give me a hint. Thanks.
I did further research on this. I noticed that the .ToString method does not add XML declaration to the string, so I need to add it myself. Still this does not solve the issue with the namespaces and prefixes that I don't know how to handle with deserialization.