text:
Q: Temporal tables extension error with array columns I'm using the temporal tables Postgres extension (http://pgxn.org/dist/temporal_tables/) on Postgres 9.5.4 on Windows. This works well for most cases, but I'm running into a weird issue with array columns.
I've created some minimal steps to reproduce this, the setup of the table and the temporal tables extension is the following:
CREATE EXTENSION IF NOT EXISTS temporal_tables;

DROP TABLE IF EXISTS test;
DROP TABLE IF EXISTS test_history;

CREATE TABLE test
(
  id SERIAL PRIMARY KEY,
  a integer,
  directories text[],
  sys_period tstzrange NOT NULL
);

CREATE TABLE test_history (LIKE test);
CREATE TRIGGER versioning_trigger BEFORE INSERT OR UPDATE OR DELETE ON test FOR EACH ROW EXECUTE PROCEDURE versioning('sys_period', 'test_history', true);

And in separate transactions the following two commands:
INSERT INTO test(a) VALUES (1);

UPDATE test SET a = 5 WHERE id = 1;

I get the following error:

ERROR:  column "directories" of relation "test" is of type text[] but column "directories" of history relation "test_history" is of type text[]

The error is nonsensical to me, both columns have the same type and the error even states this. This only happens when a text[] column is present in the table. It is not necessary to write to that column, it just has to be present. If I don't create the array column, there is no error.
The extension does not mention anything about incompatibility with arrays, and I'd expect that kind of restriction to be large enough to be mentioned. I'm wondering if there is anything wrong with the way I set up the tables, or if I'm missing anything else here. Is there any underlying reason why two text[] array columns would be of different type?
Any idea what actually causes this error and how I could get rid of it?

A: The problem is versioning.c:412:
 errmsg("column \"%s\" of relation \"%s\" is of type %s (%i) but column \"%s\" of history relation \"%s\" is of type %s (%i)",
                NameStr(attr->attname),
                RelationGetRelationName(relation),
                format_type_with_typemod(attr->atttypid,
                                                                 attr->atttypmod),
                attr->attndims,
                NameStr(history_attr->attname),
                RelationGetRelationName(history_relation),
                format_type_with_typemod(history_attr->atttypid,
                                                                 history_attr->atttypmod), history_attr->attndims)));

When I changed to show attndims, result was:
ERROR:  column "directories" of relation "test" is of type text[] (1) but column "directories" of history relation "test_history" is of type text[] (0)

I found the problem is in heap_openrv (PostgreSQL function) does not correctly fill this field for tables created by LIKE. I do not know how to repair it. But I found a solution:
CREATE TABLE test_history (
  id SERIAL PRIMARY KEY,
  a integer,
  directories text[],
  sys_period tstzrange NOT NULL
);

After that:
CREATE EXTENSION
DROP TABLE
DROP TABLE
CREATE TABLE
CREATE TABLE
CREATE TRIGGER
INSERT 0 1
UPDATE 1
 id | a | directories |                            sys_period
----+---+-------------+-------------------------------------------------------------------
  1 | 1 |             | ["2017-02-07 15:12:16.383449+02","2017-02-07 15:12:16.387419+02")
(1 row)

A: It is a long-standing PostgreSQL bug.


text:
Q: Change Label text between fade in and fade out transitions I'm trying to change a Label's text in between fadein and fadeout as followed:
    Label label = (Label) this.cardsValueGroup.getChildren().get(1);
    label.textProperty().set(String.valueOf(cardsValue));

    SequentialTransition t = new SequentialTransition();

    if (this.cardsValueGroup.getOpacity() == 1.0) {
        FadeTransition fadeOut = new FadeTransition(Duration.seconds(0.5), this.cardsValueGroup);
        fadeOut.setFromValue(1.0);
        fadeOut.setToValue(0.0);
        t.getChildren().add(fadeOut);
    }

    FadeTransition fadeIn = new FadeTransition(Duration.seconds(0.5), this.cardsValueGroup);
    fadeIn.setFromValue(0.0);
    fadeIn.setToValue(1.0);

    t.getChildren().add(fadeIn);
    t.play();

How can I add Label text transition as well?

A: Try
fadeOut.setOnFinished(event -> label.setText(...));

Or if you're still using JavaFX 2,
fadeOut.setOnFinished(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        label.setText(...);
    }
});

(you have to make label final in this case).

redpajama_set_name: RedPajamaStackExchange


text:
Q: etcd - is the leader node automatically and dynamically elected? newbie question It's been about several hours since I am actively looking into etcd and I have a newbie question:
Is the leader node dynamically and automatically elected or the "human" operator of the cluster must take action?
If yes, then what are the conditions that must be met in order to begin the election of a new leader node?
If no, then what should be done?


text:
Q: Toggle element type on click I have a jquery code that is soposed to change the element type on click and back if the the user click anywere outsite the element.
The problem is that fore some reason in CodePen doesn't change at all on click, but in the original website does that only once then nothing.
The HTML

  <button type="submit" class="btn btn-primary">Go</button>

Javascript:
jQuery(document).ready(function() {

  $.fn.changeElementType = function(newType) {
    var attrs = {};

    $.each(this[0].attributes, function(idx, attr) {
      attrs[attr.nodeName] = attr.nodeValue;
    });

    this.replaceWith(function() {
      return $("<" + newType + "/>", attrs).append($(this).contents());
    });
  }

  $('.input-group-btn button').changeElementType('div');

    $(function() {
  $(".input-group div").on("click", function(e) {
    $('.input-group-btn div').changeElementType('button');

    e.stopPropagation()
  });
  $(document).on("click", function(e) {
    if ($(e.target).is(".input-group input") === false) {
        $('.input-group-btn button').changeElementType('div');
    }
  });
});

});

Here is the pen:
http://codepen.io/florinsimion/pen/AXxKbG
Any ideas?

A: I'd like to instead add a comment, since what I'm about to mention is related to possible corrections on your implementation, and not a proper solution, but unfortunately I don't have enough reputation yet to do that.
I noticed a few problems with your code, but I'm not sure if they're intended or not.
Starting with the HTML, you have this element Go which has class="btn". I'm not sure if you really want it there, since it's already used on its parent.
On the Javascript part, here $(e.target).is(".input-group input") you're expecting to match an element that has a parent with a class .input-group and the element itself is an input. One of the problems here is that you're not using input elements anywhere on your HTML (nor switching from any element on Javascript code for that matter). I believe you want it to be button. The other one (I'm not entirely sure about this), I don't think you'll ever be able to match the selector on the .is() function, since you're using a nested selector. The target will be the element where the event was triggered and it has its own type and/or id or class. That's what you'll have to use to check if that's the element you wanted (since you're using the function .is()).


text:
Q: Why is XCode`s LLVM GCC 4.2 compiler failing to generate correct assembly? I'm using XCode 4.2 on Mac OS X 10.6.8 and running the iOS5 emulator.
I have a workspace with a main project, and a secondary project that the main is dependent on.
My problem is, after I make change to a .cpp or .mm file in the secondary project, even though XCode recompiles the appropriate files, it does not generate new assembly code reflecting the code change.  Thus when stepping over my code in the debugger, stepping to the next line skips any changes I have made.
My only recourse is do a clean and a build.
The main project can be compiled with either LLVM GCC 4.2 or Apple LLVM Compiler 3.0.
However, (due to what I think are unreasonable compile errors regarding templated classes calling functions of parent classes) I can only compile the secondary project with LLVM GCC 4.2.
Both projects contain objective c files, though the secondary project is largely an existing c++ codebase being reused on iOS.
Thanks in advance for any guidance to resolving this.

Example behavior:
regular build:
During debugging, imagine stepping over 3 lines of code.  The 1st line is old code that has been compiled many times.  The 2nd and 3rd lines were just typed and compiled w/o doing a clean + build.  When the program counter is at the 1st line of code, the compiler thinks that all 3 lines of code are really one and is highlighting them all together to indicate the currently executing line. Stepping to the next line skips lines 2 and 3 and moves the program counter to the next valid line of code, i.e. line 4.
clean + build:
This time the debugger behaves as expected.  When the program counter is at line 1, only it is highlighted.  Stepping to the next line moves the program counter to line 2.

Since I can edit the main project's source and debug fine, perhaps my problem is that I have not properly specified the dependency between the two projects.
In the main project's Target->Build Phases->Target Dependencies, Ive set a dependency to be the output of the subproject.
Also in Xcode's project navigator (view via command 1 shortcut), you can see that the sub-project is physically contained inside the main project.


text:
Q: Shiny app for selecting a pair of players? I am developing a shiny app for selecting a pair of players from the below dataset
structure(list(player = c("Samson", "Tausif", "charles", "vinod",
"bhsoley", "sugandhey", "mohit", "ocd", "shankar", "sneha")), class = "data.frame", row.names = c(NA,
-10L))

I am new to r and shiny by reading from multiple sources I am able to develop an app for random selection. the code is as shown below:
ui<-fluidPage(
  fileInput('datafile', 'Choose CSV file',
            accept=c('csv', 'comma-separated-values','.csv')),
  tableOutput('table'),
  tableOutput("table1")
)

server<- function(input, output,session) {
  dataframe<-reactive({
    if (is.null(input$datafile))
      return(NULL)
    data<-read.csv(input$datafile$datapath)
    data
  })

  dataframe1<-reactive({
    if (is.null(input$datafile))
      return(NULL)
    data1<-read.csv(input$datafile$datapath)
    y<-split(sample(data1),rep(1:5,each=2))
    df<-data.frame(matrix(unlist(y), nrow=length(y), byrow=T))
    df
  })
  output$table <- renderTable({
    dataframe()
  })
  output$table1 <- renderTable({
    dataframe1()
  })
}
shinyApp(ui, server)

but each time i run this, it generate the same result however the results are different pair of player in R terminal.
This is screenshot of my app
I am looking for a solution where each time I upload a CSV file it generate different player names.


text:
Q: What is Apache process model? I have been googling this question for some time but got no answers. What's the Apache  process model?
By process model, I mean how Apache manage process or thread to handling HTTP request.
Does it fork one process for each HTTP request?
Does it have process/thread pool?
Can we config it?
Is there any online doc for such Apache details?

A: This depends on your system and configuration : see Core Features and Multi-Processing Modules : you could use, for instance :

*

*Apache MPM winnt on windows -- that one uses threads

*Or Apache MPM prefork -- that one uses processes

*Or even Apache MPM worker -- which uses both several processes and threads.

Quoting the page of the last one, Apache MPM worker :

This Multi-Processing Module (MPM)
  implements a hybrid multi-process
  multi-threaded server.  By using
  threads to serve requests, it is able
  to serve a large number of requests
  with fewer system resources than a
  process-based server. However, it
  retains much of the stability of a
  process-based server by keeping
  multiple processes available, each
  with many threads.


text:
Q: Core Data: how to check relationship existence? I got this error: Unable to parse the format string "createdBy.id = %@ && showAgain = false && like != nil
fr2.predicate = NSPredicate(format: "createdBy.id = %@ && showAgain = false && like != nil", liu.id!)
problem is the last part: like != nil if I remove, it is ok. It is a to-one relationship. Why is it not possible to check its existence? What other way do you know?


text:
Q: Error while installing CCDNForumBundle User entity was not found in the chain configured namespaces I would like to say that is possible that I already have found the solution, too bad it's in french. Below is the link to solution.
http://fr.openclassrooms.com/forum/sujet/mappingexception
Getting error below:

[Doctrine\Common\Persistence\Mapping\MappingException]
  The class 'HUPR\UserBundle\Entity\User' was not found in the chain
  configur     ed namespaces CCDNForum\ForumBundle\Entity,
  FOS\UserBundle\Model

I have this Bundle:
namespace HUPR\UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

    class HUPRUserBundle extends Bundle
    {
        public function getParent() {
            return 'FOSUserBundle';
        }
    }

And this is my app/config/config.yml:
Doctrine Configuration
orm:
  default_entity_manager: default
  auto_generate_proxy_classes: "%kernel.debug%"
      resolve_target_entities:
          Symfony\Component\Security\Core\User\UserInterface: HUPR\UserBundle\Entity\User
      entity_managers:
          default:
              mappings:
                  CCDNForumForumBundle:
                      mapping:              true
                      type:                 yml
                      dir:                  "Resources/config/doctrine"
                      alias:                ~
                      prefix:               CCDNForum\ForumBundle\Entity
                      is_bundle:            true

A: Found the solution, It was needed to map my bundle:
mappings:
FOSUserBundle: ~
HUPRUserBundle:
    mapping:              true
    type:                 annotation
    #dir:                  "Resources/config/doctrine"
    alias:                ~
    prefix:               HUPR\UserBundle\Entity
    is_bundle:            true
CCDNForumForumBundle:
    mapping:              true
    type:                 yml
    dir:                  "Resources/config/doctrine"
    alias:                ~
    prefix:               CCDNForum\ForumBundle\Entity
    is_bundle:            true


text:
Q: How does ASP.NET Webforms decide HTML name of a control? In ASP.NET web forms when a control is rendered on the page, the ID of each field is modified with the ctrl01 as needed to ensure collisions don't happen (aka myField becomes ctrl01$myField or whatnot).
I was wondering where one might find details on HOW the algorithm itself works, or where it might be I can find it.  I am assuming the INamingContainer has something to do with this-- but alas I cannot find the part which actually decides the rendered field name.
Any help would be awesome!

A: It's based on the hierarchical layout of the webpage. But you can control this with the ClientId property.
So a textbox in a usercontrol will be named ctrl01#textboxname (Like you said in your post)

A: You are probably looking for this msdn article.

A: It concatenates it's own name with your original id.
In ASP.NET 4 you can suppress this concatenation and keep your own id in three different ways:

*

*Each server control has an attribute called clientIdMode which you can set to Static

*You can also set clientIdMode in the page directive which will affect all controls on the page.

*Or you can set it in the web.config to affect all controls in all pages. (Unless the page or control is set to a different clientIdMode
Note: If you are using AJAX Control Toolkit you will need to set those controls that are part of the toolkit to a clientIdMode of Predictive

A: Apart from the other answers, if you are using ASP .NET 4, you have much more control over it.
Take a look @ these web pages
http://www.west-wind.com/weblog/posts/54760.aspx
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx


text:
Q: Validating radio buttons and "not required" fields in jQuery So I've been mulling over this particular problem for 2 hours now... at the moment I am trying to validate a form using the following plugin from jQuery:
http://docs.jquery.com/Plugins/Validation

So far I have got the following code:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Patient Form</title>
        <link rel="stylesheet" href="css/styles.css" type="text/css">
        <link rel="stylesheet" href="css/jquery-ui.css" type="text/css">

Patient Form

            <fieldset class="fieldset_form1">
            <legend class="legend">Details 1</legend>
            <form id="form1" method="post" action="form2.php" enctype="application/x-www-form-urlencoded">

First Names:
            <input type="text" name="firstNames" id="firstNames" size="50" maxlength="150">

Surname:
            <input type="text" name="surname" id="surname" size="50" maxlength="150">

Salutation:
            <input name="salutation" id="salutation_1" value="Sir" type="radio" >Sir
            <input name="salutation" id="salutation_2" value="Dr" type="radio" >Dr
            <input name="salutation" id="salutation_3" value="Mr" type="radio" >Mr
            <input name="salutation" id="salutation_4" value="Mrs" type="radio" >Mrs
            <input name="salutation" id="salutation_5" value="Miss" type="radio" >Miss
            <input name="salutation" id="salutation_6" value="Ms" type="radio" >Ms

Home Address:
            <input type="text" name="homeAddress" id="homeAddress" size="50" maxlength="200">

Work Address:
            <input type="text" name="workAddress" id="workAddress" size="50" maxlength="200">

Home Phone:
            <input type="text" name="homePhone" id="homePhone">

Work Phone:
            <input type="text" name="workPhone" id="workPhone">

Cell Phone:
            <input type="text" name="cellPhone" id="cellPhone">

Occupation:
            <input type="text" name="occupation" id="occupation" size="50" maxlength="100">

Date of Birth:
            <input id="dateOfBirth" name="dateOfBirth">

<input type="button" onClick="location.href='index.php'" class="button blue gradient positionLeft" value="Back">
<input type="submit" class="button blue gradient" value="Next">

            </form>
            </fieldset>

Validating most of the fields seem to work fine, except I am not able to validate the radio input options ("salutation"). I am wanting an error message (similar to the other fields with a successful implementation) for if a radio option is not selected.
For the "workPhone" and "cellPhone" text fields, they are not required; however, I would still like to validate any input the user enters in the fields. Even though I have "required" set to false for both the fields, the validation seems to be behaving like they are required.
If someone is able to help me identify why the form validation isn't behaving correctly, please let me know. I also thought it was necessary to include all the code for this form, so if anyone needs this truncated, let me know.
Thanks in advance!

A: The selector ":unchecked" does not exist, you can invert the selector, and change the condition to "greater than"
function countUnchecked() {
    var n = $("input:radio:not(:checked)").length;
    if (n > 0) {
        $("div").html("Please select a salutation.");
    }
}

A: What you did was wrong. Put an id or a unique class on your button and try to trigger the error with click function. Forget about your countUnchecked function because it would trigger always once the page is loaded even if you still dont fill up the form yet. Try this
  $("#buttonid").click(function(){
   var n = $("input:radio[name=salutation]:checked").val();
   if(!n){
       $("div").text("Please select a salutation.");
    }
 });


text:
Q: Sinatra app as rack middleware TimesOut Rails 3 While in the Rails development environment, I am attempting to add a Sinatra app as a middleware. The Sinatra app uses the geoip gem that processes a user's ip address and returns json with their city.
I can view the returned json by going directly to the example url in the browser or using curl in the command line, http://local.fqdn.org/geoip/locate.json?ip=24.18.211.123. However when I attempt to call the url with wget from within a Rails controller, the Rails app stops responding often crashing my browser and my rails server wont exit using the control+C command.
Any clue to what is happening here? Why would going directly to the url in the browser return the proper response but my call in the controller results in a Time Out?
sinatra-geoip.rb
require 'sinatra'
require 'geoip'
require 'json'

# http://localhost/geoip/locate.json?ip=24.18.211.123
#
# {
#     latitude: 47.684700012207
#     country_name: "United States"
#     area_code: 206
#     city: "Seattle"
#     region: "WA"
#     longitude: -122.384803771973
#     postal_code: "98117"
#     country_code3: "USA"
#     country_code: "US"
#     dma_code: 819
# }

class GeoIPServer < Sinatra::Base
    get '/geoip/locate.json' do
        c = GeoIP.new('/var/www/mywebsite.org/current/GeoLiteCity.dat').city(params[:ip])
        body c.to_h.to_json
    end
end

routes.rb
mount GeoIPServer => "/geoip"

config/environments/development.rb
Website::Application.configure do
    require "sinatra-geoip"
    config.middleware.use "GeoIPServer"

...
end

controller
raw_geo_ip = Net::HTTP.get(URI.parse("http://#{geoip_server}/geoip/locate.json?ip=#{request.ip}"))
@geo_ip = JSON.parse(raw_geo_ip)

A: Our solution was difficult to find. We ended up finding a method in the sinatra source code call forward.
new sinatra-geoip.rb
class GeoIPServer < Sinatra::Base
    if defined?(::Rails)
        get '/properties.json' do
            env["geo_ip.lookup"] = geo_ip_lookup(request.ip)
            forward
        end
    end

    def geo_ip_lookup(ip = nil)
        ip = ip.nil? ? params[:ip] : ip
        result = GeoIP.new('/var/www/mywebsite.org/current/GeoLiteCity.dat').city(ip)
        result.to_h.to_json
    end
end

Essentially, we removed the /geoip/locate.json route from the file and converted it to a simple method. We needed the geoip lookup to occur when the properties.json was being called, so a new param was added with the geoip information. Then we set the new param equal to @geo_ip variable in the controller.
New properties controller
if Rails.env.development? or Rails.env.test?
    # Retrieves param set by sinatra-geoip middleware.
    @geo_ip = JSON.parse(env["geo_ip.lookup"] || "{}")
else
    # Production and staging code
end

Rather obscure problem and solution. Hopefully it will help someone out there. Cheers.


text:
Q: Split A SELECT query into several Xml files This is a simplified version of my problem.
Using the following SELECT statement I output my data as Xml.
SET @result = (
    SELECT * FROM MyTable
    FOR XML path('receipts')
)

SELECT @result AS xmloutput

I then write the output into an Xml file that uses a timestamp in the filename:
SET @sqlCommand =
     'bcp "EXEC '  +@db + '.dbo.MyStoreProcedure" queryout "' + @filePath + @fileName + ' "  -T -C 1252 -w'
EXEC master..xp_cmdshell @sqlCommand

In the snippet above:

*

*MyStoreProcedure is basically the code from the first snippet i.e. the SELECT results.

*@filename has a structure like YYYYMMDDHHMMSS_customers.xml.

Now the problem is, the program that is supposed to read this Xml file has a limit of 20000 records. What I should do is split the results into separate Xml files. So if the original SELECT query gives 25000 records. They should be split into two non-overlapping files: First one containing 20000 and the second the remaining 5000.
To avoid overwriting on the same file (in case the process goes very fast), we can have a 1-second wait between each batch so that the next file will get a new name.
How can I implement this split?
Thanks in advance.

A: The function NTILE (Starting with SQL Server 2012) allows you to group your data. If you have a lower version you can easily simulate this with a combination of ROW_NUMBER and integer division.
The following writes your table rows together with a chunk number into a temp table. The WHILE takes chunk after chunk. You can use the chunk-number to add it to your file name.
The function WAITFOR (again 2012+) allows to pause automatically.
DECLARE @ApproxRowsPerChunk INT=10; --will float a little...

SELECT NTILE((SELECT Count(*) FROM sys.objects) / @ApproxRowsPerChunk) OVER(ORDER BY o.object_id) AS ChunkNumber
      ,*
INTO #StagingTable
FROM sys.objects AS o;

DECLARE @nr INT=1;
DECLARE @maxNr INT=(SELECT MAX(ChunkNumber) FROM #StagingTable);

WHILE @nr<=@maxNr
BEGIN
    SELECT * FROM #StagingTable WHERE ChunkNumber=@nr FOR XML PATH('test');
    SET @nr=@nr+1;
    WAITFOR DELAY '00:00:01';
END

Hint
This would allow you, to integrate something like 1 of 17 into your XML (and into the file's name if needed).

A: please see if the below helps.  I basically take your finished myTableresults, assign row_number() and divide them into partitions, I then loop through the partitions as per your batch size, executing your bulk copy in the loop.  You may have some more work to do on dynamically setting the file names (you could use the @current_partition variable in your file name builder).
I have commented my code:
-- Dummy data, represents your results set

IF OBJECT_ID('tempdb..#t1') IS NOT NULL
    DROP TABLE #t1

CREATE TABLE #t1 (
    initials VARCHAR(10)
    ,no_cars VARCHAR(10)
    )

INSERT INTO #t1
VALUES
('AA',1)
,('BB',1)
,('CC',1)
,('DD',1)
,('EE',1)
,('FF',1)
,('GG',1)
,('HH',1)
,('II',1)
,('JJ',1)
,('KK',1)

---- end of test data creation

-- Assign query partition size, in your case would be 20,000. Must be float (or other decimal).

DECLARE @partition_size FLOAT = 3;

IF OBJECT_ID('tempdb..#t2') IS NOT NULL
    DROP TABLE #t2;

-- Assign your results set a row number
WITH [cte1] AS (
SELECT
initials
,no_cars
,ROW_NUMBER() OVER (ORDER BY no_cars ASC) AS row_no
FROM #t1
)
-- Assign the query partition by running a ceiling command on the row number, store the results in a temp table
SELECT
initials
,no_cars
,CEILING(row_no/@partition_size) AS query_partition
INTO #t2
FROM cte1

--- Now, create a loop to go through each partition

-- Your business variables

DECLARE @result XML
DECLARE @sqlcommand NVARCHAR(4000)
DECLARE @db VARCHAR(50) = 'db'
DECLARE @filepath VARCHAR(50) = 'C:\temp'
DECLARE @filename VARCHAR(50) = 'dynamic2017010.xml'

-- Find highest partition
DECLARE @current_partition INT = 1
DECLARE @max_partition INT = (SELECT MAX(query_partition) FROM #t2)

WHILE @current_partition <= @max_partition
BEGIN

    SET @result = (
        SELECT initials
,no_cars FROM #t2
        WHERE query_partition = @current_partition
        FOR XML path('receipts')
    )
SELECT @result AS xmloutput

-- other code..?

    SET @sqlCommand =
         'bcp "EXEC '  +@db + '.dbo.MyStoreProcedure" queryout "' + @filePath + @fileName + ' "  -T -C 1252 -w'
    EXEC master..xp_cmdshell @sqlCommand

    SET @current_partition += 1

END


text:
Q: Why does chrome not accept the letters 'c' or 'h' Using Windows and the latest Chrome version.
The letters work in notepad and in other browsers and application.
In Chrome the letters don't work either in input boxes or even on the URL line to type an address.
I have to copy and paste from notepad to have these characters.
This is as weird as it sounds.  I haven't found any plugins or extensions that would cause this.

A:
I found that if I hit the Windows key (between the left Ctrl and Alt keys) then the problem would correct and the c, v, h keys started working again.

Taken from: Google Forums - Google Chrome Keys Problem


text:
Q: Implementing recently viewed by a user I am using elasticsearch and gem searchkick in my application. I have an Event model, where users are able to click on the event etc.
In the event list I have a requirement for filter "viewed in the last 7 days". I am wondering what's the best way to index data so it serves the requirement appropriately.
At first I thought about storing user ids on the Event model ES index like so :
Event: {
 _id: 1,
 user_ids: [1,2,3,4...]
}

But this would give me all the event views, not only in the last 7 days. How would I create indexed data to accommodate this case?
Update per comments to provide more context:
This is an example of some events (what is being stored) :
[
  {
    _id: 1,
    name: 'Company get together',
    start_time: '10:00',
    start_date: '2022-10-01',
    duration: 3600
    ...
  },
  {
    _id: 2,
    name: 'Company break',
    start_time: '00:05',
    start_date: '2022-01-01',
    duration: 172800
    ...
  },
  {
    _id: 3,
    name: 'Sales webinar',
    start_time: '09:00',
    start_date: '2022-15-01',
    duration: 7200
    ...
  },
  ...
]

This would be an example of what is in the events right now. If some user clicks on this event, we want a record this (somehow) on the event model, so that we could return the list of events that user has clicked on in the last 7 days.
If we used a structure like this:
{
    _id: 3,
    name: 'Sales webinar',
    start_time: '09:00',
    start_date: '2022-15-01',
    duration: 7200,
    user_click_ids: [1, 2, 3]
    ...
  }

And we append to user_click_ids every time the user clicks on a specific event, then I can use user_click_ids to return the list of the users who clicked on that event (and filter on it providing current user id).
But then I need another dimension to this, not only which user clicked, but also was the click in the last 7 days or not.
How do I create an index for this case or how would I solve this?

A: Maybe a solution that uses less searchkick, but you could use another model to handle this? Off the top of my head (haven't run this):
class CreateEventClicks < ActiveRecord::Migration
  def change
    create_table :event_clicks do |t|
      t.belongs_to :event, null: false, foreign_key: true
      t.belongs_to :user, null: false, foreign_key: true
      t.timestamps
    end

    add_index :event_clicks, :event, :user
  end
end

class EventClicks < ApplicationRecord
  belongs_to :user
  belongs_to :event
end

def find_clicked_events(user, event, time)
  EventClicks.where(user_id: user.id, event_id: event.id, created_at: time..Time.now)
end

A: I'm not sure about searchkick since I'm .net guy but I'd store entire information about the click instead of just the id. I.e.
Event: {
 _id: 1,
 user_clicks: [{
   user_id: 1,
   timestamp: 2022-02-24 4:00:00
 }, ...]
}

However, depending on the expected usage pattern (i.e. a lot of users clicking a lot of events) documents might become large. If that is the case you might consider doing additional filtering on your backend instead of elasticsearch.
In such a case you'd go with something like user_activities index
user_id: 1,
event_clicks: [{
  event_id: 1
  timestapmp: 2022-02-24 04:00:00
}, ...]

The obvious downside of such approach is additional code on a backend with might be hard to support and complicate things.
The thing with NoSQL databases (and elasticsearch as well) is that there is no single one-size-fits-all solution and you have to understand your query patterns well. So it's up to you to decide what hinders you more: growing document size with approach 1 or adding some custom logic on your backend with approach 2.


text:
Q: How to wrap a element among dozen of element in jQuery Suppose using .wrap() can wrap a tag on a element, however I want to wrap a tag among dozen of element. How can I do that?
Thanks
BEFORE

AFTER

A: You can use wrapAll():
$('.jw_playlist_playlist li').wrapAll('
');

A: Or thinking about it from a different direction, use wrapInner
http://jsfiddle.net/z9Jah/
$('.jw_playlist_playlist').wrapInner('
');

A: Grab each item, on the first LI, insert a  tag before it. on the last LI, insert a UL tag after it
var listItems = $(".jw_playlist_playlist li");
$.each(listItems, function(i,v){
  if(i==0){
    $(this).insertBefore('
');
  }else if(i == listItems.length - 1){
   $(this).insertAfter('
');
  }
});


text:
Q: Facebook Page Access Token? I'm new with phpsdk v4, and I'm trying to get access token for my pages.
I tried with this:
<?
include getenv('social');
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRequestException;
use Facebook\FacebookSDKException;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookResponse;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
$access_token =  $_SESSION['facebooklogged'];
$session = new FacebookSession($access_token);

And after:
$page_access_token = (new FacebookRequest( $session, 'GET', '/320330478029510?fields=access_token', array( 'fields' => 'access_token' ) ))->execute()->getGraphObject()->asArray();
print_r($page_access_token);

And:
$request = new FacebookRequest($session, 'GET', '/me/accounts?fields=name,access_token,perms');
$pageList = $request->execute()->getGraphObject()->asArray();
print_r($pageList);

Both return or id of page, or a empty array();
    Array ( [id] => 320330478029510 )
    Array ( )
I created $session from login page, with
$logare = new FacebookRedirectLoginHelper('https://mysite/facebook/login.php');

try{$session = $logare->getSessionFromRedirect();}catch(FacebookSDKException $e) {$session = null;}
if($session)$_SESSION['facebooklogged'] = $session->getToken();

What is wrong?

A: I tried with another account, another admin of page, and work with that...but with my account, still nothing ... I will delete this app from used apps, and i will try again.


text:
Q: Having trouble setting up data calling with rmnet_data0 interface I'm trying to set up a data call through rmnet_dataX interface which is referring to a cellular connection through the card inserted, but having trouble doing so. I do the following
ifconfig rmnet_data0 up

I then assign an IP statically
rmnet_data0 Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:10.246.68.132  Mask:255.0.0.0
          UP RUNNING  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

Add the default path in the routing table
ip ro add default via 10.246.68.132 dev rmnet_data0

Add the DNS server
echo "nameserver 8.8.4.4" >> /etc/resolv.conf

Set NAT rules
iptables -t nat -D POSTROUTING -o rmnet_data0 -j MASQUERADE

Routing table
netstat -r

Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface

default         10.246.68.132   0.0.0.0         UG        0 0          0 rmnet_data0
10.0.0.0        *               255.0.0.0       U         0 0          0 rmnet_data0
192.168.225.0   *               255.255.255.0   U         0 0          0 bridge0

ping google.com // fails

Also, the default path really just indicates the packets coming to the gateway IP are routed to the external network which in this case is network data?
Given that, are NAT rules really required?

A: Ok, some network basics (please read up on details, there's plenty of resources online):

*

*The routing tables are both for packets originating on this machine, and for packets incoming from other machines that are forwarded (forwarding needs to be enabled for that). So routing tables are always necessary for any networking.

*Network address translation (NAT) is only necessary when (1) packets coming from other computers are forwarded to your cellular network, and (2) your cellular network only recognizes a single client (which is normally the case), and you need to pretend that packets coming from other computers are coming from this computer, and not from the other computers.

*The steps to get it working are first to get it working on this computer. If you do need forwarding and NAT, that's the second step. So initially, no firewall rules.

*You need to run a specific DHCP client that handles this particular interface. Details depend on your system; the configuration for systemd, network manager, or legacy style configuration etc. are all different. Figure out what runs on your system, google "set up DHCP with systemd" or similar.

*For DHCP, typically the DHCP client is triggered when the interface comes up, and then DHCP client broadcasts a message on the interface "hello, I'm new here, please give me an IP address an additional information". The DHCP server answers that broadcast, and tells you the IP, the gatway, and potentially more. The DHCP client program then uses this information to set up the IP address, the routing tables etc. Some cellular networks use this way, some use different ways. I have no idea what your cellular provider does.


text:
Q: How do I move the bootmgr folder to a different drive? I'd like to delete a FAT16 partition that only has boot information on it. I'm running Windows Server 2008 R2.
I've used BCDEdit to examine the boot configuration(output below).
I'm just unclear how to move the bootmgr from F: to C:.
Windows Boot Manager
--------------------
identifier              {bootmgr}
device                  partition=F:
description             Windows Boot Manager
locale                  en-US
inherit                 {globalsettings}
default                 {current}
resumeobject            {59d84d8a-0888-11e0-9d9c-91c956e448ed}
displayorder            {current}
toolsdisplayorder       {memdiag}
timeout                 30

Windows Boot Loader
-------------------
identifier              {current}
device                  partition=C:
path                    \Windows\system32\winload.exe
description             Windows Server 2008 R2
locale                  en-US
inherit                 {bootloadersettings}
recoverysequence        {59d84d8c-0888-11e0-9d9c-91c956e448ed}
recoveryenabled         Yes
osdevice                partition=C:
systemroot              \Windows
resumeobject            {59d84d8a-0888-11e0-9d9c-91c956e448ed}
nx                      OptOut

A: Probably better for superuser. in fact: https://superuser.com/questions/32164/easiest-way-to-copy-or-clone-boot-partition-onto-new-hard-drive


text:
Q: Usage of "at one point" Someone wrote:

At one point a funny story happened to me.

It continues:

I'm studying English in the private English language school called SPEAK UP. Several days ago one teacher invited the students to a pub quiz, right. When I got there, they had already settled down in the pub....

I changed the first sentence  to:

Some time ago/ once a funny story happened to me.

I think "At one point" is used to begin a story like :

At one point we stopped at a gas station....

Before describing an event, but not a good choice for the sentence above. Right?
In general, what's its usage?
Beside I think the right in the continuation of the story doesn't sound good and is extra. Right?

A: The implication of at one point is "at one point in time", that is, at one point in a series of points in space-time.

Driving along the narrow mountain roads was dangerous. At one point,
  we thought the truck was going to topple into the gorge.

Thus, to begin a statement  with at one point would be a non-sequitur. There would have been no explicit setting of context to explain it, as in the mountain road example above, and so it could confuse the listener or reader. However, a long-standing convention of storytelling is that a storyteller has the freedom to begin a story in medias res.  There, the non-sequitur is a narrative device not a logical shortcoming.

A: At one point is used to describe the situation at one particular, unspecified, time. It is usually used close to the end of a scene in a story to provide additional information about what happened during that scene.
For example, imagine describing an afternoon outing, part of which involved a rowing boat and either incompetent oarsmen or drunk passengers. After telling the story of this scene you might add:

At one point, there were more people in the water than in the boat.

You are not saying when exactly in the scene this happened: it is completely unrelated to the sequence of events. You are simply providing additional information to help the listener or reader visualise what happened.
Note that it is not correct to start a story with

... a funny story happened to me.

The story is a description of what happened, not what actually happened. When telling this kind of story, the conventional word for the event itself is thing

... a funny thing happened to me.

If you want to start a story with a funny thing happened to me, you should really to give a general impression of when, and maybe where, it happened:

A funny thing happened to me at work yesterday...
  A funny thing happened to me last week...

There is actually a musical and a film entitled A funny thing happened on the way to the forum.
Regarding right in your story: this is something that people sometimes say, but rarely write.  It would work if this paragraph is dialogue- something that a character in your story says- but it would not look natural if it were a part of your own story.


text:
Q: Spring-JPA Does not result in insert, after in readOnly transaction? The persist/insert process does not executed, after transaction ReadOnly!
My applicationContext.xml:
<bean id="transactionManagerConstant" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="constant"/>
    <property name="jpaDialect" ref="jpaDialect" />
</bean>

<bean id="constant" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitManager" ref="persistenceUnitManager" />
    <property name="persistenceUnitName" value="JSFSpring" />
</bean>

Java code:
@Transactional(isolation = Isolation.SERIALIZABLE, propagation = Propagation.REQUIRED, readOnly=false)
public String workSaved(){
    em.persist(work);
    work = (Work) ctx.getBean("work");
    return "/list.xhtml";
}

@Transactional(propagation = Propagation.REQUIRED, readOnly=true)
public List<Odev> getWorkedList() {
    return workedList = (List<Work>) em.createNamedQuery("Work.findAll").getResultList();
}

Exception: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not insert: [com.hakdogan.hakdoganjsfspring.entity.Work]
Caused by: java.sql.SQLException: Connection is read-only. Queries leading to data modification are not allowed
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2378)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2345)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2330)
    at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)
    ... 73 more


text:
Q: How to detect change in query params in Angular when done via Javascript I am apending query params in my ASP.NET core app via javascript as below to append it without a reload.
Also I have loaded a angular component in my c# code which is
window.history.pushState({path: currentURL}, '', currentURL)
<app-root></app-root>

I am using activated route in my angular app in constructor to listen the changes as below
this.route.queryParams.subscribe(params => {
let paramObject = {...params['keys'], ...params);
console.log(paramsObject)
})

I can only detect changes when there is a page reload and not when I use pushState method to append the query params
Is there something missing here.


text:
Q: Simple way to add sudo to docker image I'm trying to create a way to easily test my installation scripts for Ubuntu. What I'm doing now is that I create a temporary docker container like this.
docker run --rm -it ubuntu bash and then copy in my script. This gives me a fresh ubuntu install, which instantly gets created and then removed on exit.
The problem is that i can't include the word sudo in my installation script without the script throwing errors. I need to use sudo in real world applications, so I can't remove it.
Is there some simple way to add sudo functionality, or "Ubuntu-like-images" which has this?

A: @KamilCuk provided the solution, where all i needed was just to install sudo.
apt update && apt-get install -y sudo


text:
Q: AVAudioPlayer not playing my mp3 I'm trying to get a short audio file (mp3) to play in my app.  Here is the code i'm using:
   AVAudioPlayer *AudioPlayer;
    NSError *error;

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                         pathForResource:@"filename"
                                         ofType:@"mp3"]];

    AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

    AudioPlayer.delegate = self;

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

    if (error)
    {
        NSLog(@"Error: %@",
              [error localizedDescription]);
    }

    else
    {
        [AudioPlayer play];

    }

I don't really know what i'm missing, the examples i've followed seem to match what i'm doing.
edit: I should also mention that the code runs without error, there is a try catch around this.

A: I had a similar problem due to ARC. Instead of defining the AVAudioPlayer in the same method you are using it, you should should have an instance variable somewhere else, such as the UIViewController. This way ARC doesn't auto release this object and audio can play.

A: I've made some additions and got it work:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface FirstViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *data;
UIButton *playButton_;
}

@property(nonatomic, retain) IBOutlet UIButton *playButton;

-(IBAction)musicPlayButtonClicked:(id)sender;

@end

#import "ViewController.h"

@implementation FirstViewController

@synthesize playButton=playButton_;

- (IBAction)musicPlayButtonClicked:(id)sender {

NSString *name = [[NSString alloc] initWithFormat:@"09 No Money"];
NSString *source = [[NSBundle mainBundle] pathForResource:name ofType:@"mp3"];
if (data) {
    [data stop];
    data = nil;
}
data=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: source] error:NULL];
data.delegate = self;
[data play];
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end

In Interface Builder I've added a button and connected it with IBOutlet and musicPlayButtonClicked IBAction.
And don't forget to add AVFoundation framework to your project.
ps
I'm really sorry for my english, please, be indulgent.

A: I had this problem myself, until I found out that the sound was not coming through the speakers (instead - it was redirected to the calls speaker). Try adding this to redirect the sound through the speakers:
UInt32 doChangeDefaultRoute = 1;
        AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
                                 sizeof (doChangeDefaultRoute),
                                 &doChangeDefaultRoute);


text:
Q: How to use a view multiple times? I'm new to iOS.
I'm adding views to the controller using the code below.
@interface ViewController : UIViewController <CollapseClickDelegate,UITextFieldDelegate> {

    IBOutlet UIView *test1view;
    IBOutlet UIView *test2view;

    __weak IBOutlet CollapseClick *myCollapseClick;
}

I need to create 50 different instances of the view located below. How can I do this? I looked into subviews but as I said at the top I'm a newbie and couldn't figure out what was going on.
-Name:
-Amount:
-Percent:

A: To create your views programatically, use viewDidLoad: of your UIViewController
- (void)viewDidLoad
{
    [super viewDidLoad];

    for(int i=0;i<50;i++){
        //provide some initial frame, set the correct frames in viewWillLayoutSubviews:
        CGRect frame = CGRectMake(0,i*10;100;5);
        //create a new UIView, use your own UIView subclass here if you have one
        UIView *view = [[UIView alloc] initWithFrame:frame];
        //set it's backgroundColor in case you are copy&pasting this code to try it out, so you see that there are actually views added ;)
        view.backgroundColor = [UIColor blueColor];
        //add it to the viewController's view
        [self.view addSubview:view];

        //you might consider creating an NSArray to store references to the views for easier access in other parts of the code
    }
}

To create a view that you designed in a storyboard use something like described here: https://stackoverflow.com/a/13390131/3659846
MyViewController *myViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MyScene"];
[self.view addSubView:myViewController.theViewToAdd];

To create a view from a nib file, use the approach described here: https://stackoverflow.com/a/11836614/3659846
NSArray *nibContents = [[NSBundle mainBundle] loadNibNamed:@"yourNib" owner:nil options:nil];
UIView *view = [nibContents lastObject]; //assuming the nib contains only one view
[self.view addSubview:view];

A: for (int i = 0; i < 50; i++) {
    UIView *someView = [UIView new];
    // this positions each view one under another with height 40px and width 320px like a table
    [someView setFrame:CGRectMake(0,40*i,320,40)];
    // set other view properties
    // put a UILabel on the view
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10,10,200,20)];
    [view addSubview:label];
    // set label properties
    [self.view addSubview:someView]
}

Note the frame is relative to its parent view coordinate system and you need to add the view to its parent view by calling addSubview: method. -good luck


text:
Q: jquery select2 with bloodhound.js suggestion engine I am using the angular-ui selector2 wrapper tom implement some tagging like functionality.
I use bloodhound in other areas of the site for typeahead suggestions and I have a bloodhound engine already initialised for the data set I want to hit use with select2.
I just can't grok the docs on how to use the select two query option to access the data through bloodhound instead of ajax
Does anyone have an example of these two libraries working together?

A: I recently had to do this in a Marionette context, but it shouldn't differ much with angular since we're only dealing with javascript. You'll need to do 2 things to make twitter bloodhound compatible with select2.

*

*In select2's query method, call your bloodhound engine's get method and pass it the search term and a callback. Bloodhound will call this cb and pass it an array of result objects. Select2 wants this array wrapped in an object, like this {results: bloodHoundArray} so your cb needs to do the data wrapping.

*Make sure your bloodhound's prefetch or remote configuration has a filter function that maps raw results into an object with at least an id and a text field, because that's what select2 relies on.

Here is an example to make things clearer:
var engine = new Bloodhound({
      prefetch:{
          url: someUrl,
          filter: function(response){
              return _.map(response.results, function(obj){return {id:obj.tag, text:obj.tag};});
          }
      },
   });
engine.initialize();
$('#elem').select2({quietMillis:300,
                 query: function (query) {
                     engine.get(query.term, function(resultArr){
                         query.callback({results:resultArr});});
                 }
 });

A: For use with select2 v4
var engine = new Bloodhound({
        local: [
            'Andorra',
            'Unitéd Arab Emirates',
            'Antarctica'
        ],
        datumTokenizer: Bloodhound.tokenizers.whitespace,
        queryTokenizer: Bloodhound.tokenizers.whitespace,
    });

    engine.initialize();

    $.fn.select2.amd.require([
        'select2/data/ajax',
        'select2/utils'
    ], function (BaseAdapter, Utils) {
        function CustomData ($element, options) {
            CustomData.__super__.constructor.call(this, $element, options);
        }

        Utils.Extend(CustomData, BaseAdapter);

        CustomData.prototype.query = function (params, callback) {
            console.log(params)
            if (params.term && params.term.length > 3) {
                engine.search(params.term, function (resultArr) {
                    var r = [];
                    for (var i in resultArr) {
                        r.push({id: i, text: resultArr[i]});
                    }

                    callback({results: r});
                });
            }
        };

        $(selector).select2({

            dataAdapter: CustomData
        });

    })


text:
Q: how can Fix prv Arrow this slide show When I go to the second photo and I want to click on the back key, I have to click twice. If I change the value of n and make it 0. The next function breaks down and this is the problem. help me to fix ty for help me ..............................................................................................

// alert('');
let topImg = document.querySelector('.top-img img')
let downImgs = document.querySelectorAll('.imgs-down img')
let ArrayIMg = ["img/3-kid.jpeg","img/men-1.jpg","img/woamn-1.jpeg" ,"img/woman-2.jpg"]
let n = 1;
// let b = 1

downImgs.forEach(img=>{
 img.addEventListener('click' , ()=>{
     topImg.src = img.src
 });
});

function nxt(){

 topImg.setAttribute('src' , ArrayIMg[n])
 n++
  if(n>=ArrayIMg.length){n=0}

}

function prv(){
    if(--n<0){

       n = ArrayIMg.length -1

    }
    topImg.setAttribute('src' , ArrayIMg[n])
    // console.log(n)
}
*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

img{
    width: 150px;
    height: 150px;
}

.parent-all{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.top-img img{
    width: 100%;
    height:450px;
    object-fit: cover;

}
.top-img{
    position: relative;
}

.next,
.prv{
    color:white;
    cursor:pointer;
    top:35%;
    font-size: 30px;
    padding:5px;
    margin:5px;
    background: black;
    position: absolute;
    z-index: 99;
}

.next{
    right:0;
}
.prv{
    left:0;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam slider with if </title>
    <link rel="stylesheet" href="exam.css">

            &#10095
            &#10094

A: Sorry to say, but you have overdone the javascript part for no reason.
Start from n=0, and stick to the basics.
let n = 0;
function nxt(){
   n = n+1 === ArrayIMg.length ? 0 : n+1;
   topImg.setAttribute('src' , ArrayIMg[n]);
}

function prv(){
    n = n === 0 ? ArrayIMg.length-1 : n - 1;
    topImg.setAttribute('src' , ArrayIMg[n])
}

demo: https://jsfiddle.net/mey3puzL/


text:
Q: Java UnZipper error? I'm making a client updater & I'm getting an error in my cmd whilst trying to unzip the file.
What it's supposed to do is:

*

*check if the file exists in the user's home (user.home),

*if it doesn't exist in the user's home, check if the file exists in the project's directory,

*if it doesn't exist in the project's directory, download the file; if it does, then unzip the file into the user's home.

The error:
 Exists in Directory!
file unzip : C:\Users\Ryan T\Desktop\Rezzion Updater\.rezzion.cache\rezzion.cache
java.io.FileNotFoundException: .rezzion.cache\rezzion.cache\Data (The system cannot find the path specified)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at java.io.FileOutputStream.<init>(Unknown Source)
    at rezzion.UnZip.unZipIt(UnZip.java:54)
    at rezzion.Downloader.<init>(Downloader.java:68)
    at rezzion.Downloader.main(Downloader.java:78)
file unzip : C:\Users\Ryan T\Desktop\Rezzion Updater\.rezzion.cache\rezzion.cache\Data

Image of Project Folder:

my Downloader.java (Main Class):
    package rezzion;

import java.awt.FlowLayout;

public class Downloader extends JFrame {
    private static final long serialVersionUID = 1L;

    private static boolean exists = (new File(System.getProperty("user.home") + ".rezzion.cache")).exists();
    private static boolean existsinDir = (new File("rezzion.cache.zip")).exists();
    private static String site = "https://dl.dropboxusercontent.com/s/yoh4d17gfgnv2od/rezzion.cache.zip?dl=1&token_hash=AAE1qdxL_-2y_arb8MBnk8AHSsuhLH1-lwSiGVc0ayQKXA";
    private static String filename = "rezzion.cache.zip";
    private static final String INPUT_ZIP_FILE = "rezzion.cache.zip";
    private static final String OUTPUT_FOLDER = ".rezzion.cache";
    private final int BUFFER = 1024;

    public Downloader() {
        JFrame frm = new JFrame();
        JProgressBar current = new JProgressBar(0, 100);
        current.setBounds(35, 68, 326, 30);
        current.setValue(0);
        current.setStringPainted(true);
        frm.setVisible(true);
        frm.getContentPane().setLayout(null);
        frm.setSize(400, 200);
        frm.setDefaultCloseOperation(EXIT_ON_CLOSE);

        if (!exists) {
            if (!existsinDir) {
            frm.getContentPane().add(current);
        try {
            URL url = new URL(site);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            int filesize = connection.getContentLength();
            float totalDataRead = 0;
            java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream());
            java.io.FileOutputStream fos = new java.io.FileOutputStream(filename);
            java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, BUFFER);
            byte[] data = new byte[BUFFER];
            int i = 0;
            while ((i = in.read(data, 0, BUFFER)) >= 0) {
                totalDataRead = totalDataRead + i;
                bout.write(data, 0, i);
                float Percent = (totalDataRead * 100) / filesize;
                current.setValue((int) Percent);
                if (current.getValue() == 99) {
                    current.setValue(100);
                }
            }
            bout.close();
            in.close();
        } catch (Exception e) {
            javax.swing.JOptionPane.showConfirmDialog((java.awt.Component) null, e.getMessage(), "Error", javax.swing.JOptionPane.DEFAULT_OPTION);
        }
        } else {
            System.out.println("Exists in Directory!");
            UnZip unZip = new UnZip();
            unZip.unZipIt(INPUT_ZIP_FILE, OUTPUT_FOLDER);
            //TODO: Exists in Directory
        }
        } else {
            System.out.println("Exists in User.Home!");
            //TODO: Exists in User.Home
        }
    }

    public static final void main(String[] args) throws Exception {
        new Downloader();
    }

    /**
     *
     */
    public static void unzipComplete() {
        //TODO
        System.out.println("unzip Complete!");
    }
}

My UnZip.java (Self Explanatory):
package rezzion;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZip {
    List<String> fileList;
    private static final String OUTPUT_FOLDER = ".rezzion.cache";

    public void unZipIt(String zipFile, String outputFolder) {

        byte[] buffer = new byte[1024];

        try {

            // create output directory is not exists
            File folder = new File(System.getProperty("user.home")
                    + OUTPUT_FOLDER);
            if (!folder.exists()) {
                folder.mkdir();
            }

            // get the zip file content
            ZipInputStream zis = new ZipInputStream(
                    new FileInputStream(zipFile));
            // get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();

            while (ze != null) {

                String fileName = ze.getName();
                File newFile = new File(outputFolder + File.separator
                        + fileName);

                System.out.println("file unzip : " + newFile.getAbsoluteFile());

                // create all non exists folders
                // else you will hit FileNotFoundException for compressed folder
                new File(newFile.getParent()).mkdirs();

                FileOutputStream fos = new FileOutputStream(newFile);

                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }

                fos.close();
                ze = zis.getNextEntry();
            }

            zis.closeEntry();
            zis.close();

            System.out.println("Done");
            Downloader.unzipComplete();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Sorry for the poor formatting of this post, but if anyone can help I've been reading this error for a bit & looking at exactly what it's telling me to, tried merging the classes & no luck. Thanks to those that are willing to point something out, even if it's obvious & I'm missing it.

A: Since this is apparently a desktop app., the answer seems obvious to me.  For deploying Java desktop apps., the best option is usually to install the app. using Java Web Start.  JWS works on Windows, OS X & *nix.

JWS provides many appealing features including, but not limited to, splash screens, desktop integration, file associations, automatic update (including lazy downloads and programmatic control of updates), partitioning of natives & other resource downloads by platform, architecture or locale, configuration of run-time environment (minimum J2SE version, run-time options, RAM etc.), easy management of common resources using extensions..

..is there a way I could just keep this?

No.

*

*Using automatic updates, you would abandon all that and simply let the JWS client handle it.

*The 'programmatic control of updates' uses an API only available to apps. launched using JWS, specifically the DownloadServiceListener.


text:
Q: On Windows 10, how to send programmatically from C# a set of files to the CD/DVD recorder using the shell execution verb "SendTo" I do have this very specific question regarding the usage of the ShellExecute verbs from inside a C# application, which uses the ProcessStartInfo class from the System.Diagnostics namespace.
What I do have: a set of files (text and binary), which I want to burn on a CD/DVD using the CD/DVD drive of a Windows 10-installed machine.
What I want to do: from a C# .NET Framework 4.x application (regardless of it is a console one or a windows forms one), I want to run a separate process (Process object) using ProcessStartInfo (where the UseShellExecute property is set to true) and specifying the Verb "SendTo", which should take my set of files and "send" them to the ready CD/DVD drive (the required empty disk has been insert).
You could imagine it like selecting that set of files in the Windows Explorer, right-clicking on this set and selecting "Burn to 'CD/DVD Drive Name'. This same function implemented as C# program.
What I do not want: I do not want to use IMAPI2 interfaces, nor I want to write code in other languages (f.e. C/C++). I also would like to avoid using external applications like cdrtools or cdrtfe, because of the Cygwin dependency.
What I've already tried: I've already tried to form a correct ProcessStartInfo object, but it seems I'm not passing the correct information to the underlying ShellExecute procedure:
var info = new ProcessStartInfo(pathNamesSet)
               {
                   Arguments = "\"" + CDRecorderDrive + "\"",
                   CreateNoWindow = false,
                   WindowStyle = ProcessWindowStyle.Normal,
                   UseShellExecute = true,
                   Verb = "SendTo"
               };

    var process = Process.Start(info);

The process ends with the error: 'Win32Exception (1155): The specified file has not been assigned to an application'.
I'm looking for implementation of this specific functionality yet for long time, but still not able to find any useful hints from neither SO nor MS blog pages.
For additional information regarding this specific requirement, pleas ask here.
Thank you in advance for your attention and help.

A: Files ready to be burned are located in \AppData\Local\Microsoft\Windows\Burn. It may be a good idea to go back to basics a little and do a file copy to this location in order to begin your burning process. Its the only way I managed to do this anyway.


text:
Q: How to Authenticate for all tests using TestCafe I know this topic is discussed quite a bit but I have a unique situation.
In order to test our acceptance environment, we need to hit https://authentication-example.com, which runs a script to add a session cookie thus authenticating us. Then we navigate to https://acceptance-site.com to run the tests.
After trying many options, the closest I can get to a solution, is to use a Role
such as
const a3 = Role('https://acceptance-site.com', async testController => {
    await testController.navigateTo('https://authentication-example.com');
    await testController.navigateTo('https://acceptance-site.com');
}, { preserveUrl: true });

fixture('Testing acceptance')
    .beforeEach(async testController => {
        await testController.useRole(authenticate);
});

test('example1', async testController => {
    await testController.debug();
}).disablePageReloads;

test('example2', async testController => {
    await testController.debug();
}).disablePageReloads;

test('example3', async testController => {
    await testController.debug();
}).disablePageReloads;

That solution prevents me from being able to load any new pages that are different from what the Role ends at.
If I remove { preserveUrl: true } from the role, example2 and example3 load blank pages. If I remove .disablePageReloads from the tests, the authentication fails for the escond and third tests, and I get an error "Failed to find a DNS-record for the resource at..."
Also If I have the role as
const a3 = Role('https://authentication-example.com', async testController => {
    await testController.navigateTo('https://acceptance-site.com');
}, { preserveUrl: true });

the authentication fails for all test.
I noticed that when working successfully, the cookie I should be getting is actually saved in the session under application when debugging, and it is changed by this hammerhead storage wrapper.
The base url when testing is the ip and port for the testCafe server preceded by random letters, for example 172.0.0.1:8080/hoi23hh/https://acceptance-site.com
which results in my cookie being saved in the session (not under cookies as normally occurs when not using test cafe) as
hammerhead|storage-wrapper|hoi23hh|acceptance-site.com
When I remove the .disablePageReloads, but keep the preserveUrl: true on the role, the 'cookie' stays the same but the base url changes to something like
172.0.0.1:8080/ohgbo223/https://acceptance-site.com
so the "hoi23hh" changes to "ohgbo223" in the url and the cookie/session key no longer matches the url and authentication fails.
What are your suggestions for persisting the authentication, while still being able to change pages and such

A: I don't recommend using the disablePageReloads feature with roles, because it is internal and it could be unstable.
The preserveUrl option will allow every test to start with the https://acceptance-site.com page. So, I think it's the most preferable way in your case::
const a3 = Role('https://acceptance-site.com', async testController => {
    ...
}, { preserveUrl: true });

fixture('Testing acceptance')
    .beforeEach(async testController => {
        await testController.useRole(authenticate);
});

test('example1', async testController => {
    await testController.debug();
})

test('example2', async testController => {
    await testController.debug();
})


text:
Q: PhpStorm print the script of php instead of html page I'm developping a project of a generator of CV in HTML/PHP/CSS/SQL on a local server. When I use the chrome option to run a php file on PHPStorm, it prints the code between the two php tags and not the html page. It started today, before that all worked perfecty well.

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <title>Page d'inscription</title>
    <link rel="stylesheet" href="style.css">

            Inscription

        <form method="post" action="inscrire.php">

                    <input type = "text" name = "prenom" placeholder="Prenom" required class="input_acceuil">

                    <input type = "text" name = "nom" placeholder ="Nom" required class="input_acceuil">

                    <input type = "email" name = "email" placeholder ="Adresse email" required class="input_acceuil">

                    <input type = "password" name = "password" placeholder ="Mot de passe" required class="input_acceuil">

                <input type="submit" value="S'inscrire" class="bouton">

        </form>

And the file "inscrire.php" is here:
 <?php
$nom = $_POST["nom"];
$nom = ucfirst(strtolower($nom));
$prenom = $_POST["prenom"];
$prenom = ucfirst(strtolower($prenom));
$email = $_POST["email"];
$password = crypt($_POST["password"]);

//se connecter a la base de donee
$bdd = new PDO("mysql:host=localhost;dbname=ifd1_gestion_cv;charset=utf8", "root", "");

// Créer une requête INSERT INTO pour insérer un étudiant
$req = $bdd->prepare("INSERT INTO comptes (nom, prenom, email, password) VALUES (?,?,?,?);");

// Exécuter la requête
$req->execute([ucfirst($nom), ucfirst($prenom), $email, $password]);

header("Location: index.php");

?>

A: update, i desinstalled phpstorm and reinstalled it and now it works, thank you all!


text:
Q: How to save asp.net textbox values with one button click and use that data for another button click? I have a table with a row that allows the user to insert data into two textboxes, and a asp.net button called insert to bind that row to the gridview.  Within the table I have a gridview which shows all the data populated form SQL Server, and any inserted rows which could be one, or many insertions based on button clicks.   Then I have a submit button to submit the changes to SQL SERVER DB.
For example, the user enters some data into 2 textboxes then hits the insert button which just inserts that row into the gridview.  The user can either add more rows, or hit the submit button.  If the user hits the submit button, a stored procedure happens based on how many rows have been inserted.
I am not understanding how to send data from one button event to another button event using C# back-end ASP.NET front-end?

A: One way I can think of is after first insert store the IDENT_current and when you click on submit button include the where clause in store procedure where the given id value is greater than IDENT_Current that way all the effects mentioned in stored procedure will take place on inserted data.


text:
Q: Help with Controller Extension for Save Redirect Function I need help creating a controller extension for a Visualforce page. The extension should cause the Save button to redirect to a visual force page named "ProductSelector".
The relevant portion of my VF page code is as follows:
<apex:page standardController="Quote__c">
<apex:sectionHeader title="Quote__c Edit" subtitle="{!Quote__c.name}"/>
<apex:form >
<apex:pageBlock title="Quote__c Edit" mode="edit">

<apex:pageBlockButtons location="top">
<apex:commandButton value="Save" action="{!save}" id="savebutton"/>
<apex:commandButton value="Cancel" action="{!cancel}"/>
</apex:pageBlockButtons>

<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Save" action="{!save}" id="savebutton"/>
<apex:commandButton value="Cancel" action="{!cancel}"/>
</apex:pageBlockButtons>

A: You add a reference to your extension class like this:
<apex:page standardController="Quote__c" extensions="MyExtension">

and then that class should follow this pattern:
public with sharing class MyExtension {

    public MyExtension(ApexPages.StandardController sc) {
    }

    public PageReference save() {
        // Parameters could be added here for the following page
        return Page.ProductSelector;
    }
}

resulting in the save method taking priority over the default (StandardController) one.


text:
Q: jQuery and Safari Is it possible to turn off (or hide) the jQuery elements if the user's browser is Safari?
Basically I'm using jquery drop shadow and it doesn't play nice in Safari, but it works well on the other browsers. I'd like to keep the effect, but have it turned off (or hidden) in Safari.. Is this possible?

A: This is possible using $.browser:
if(!$.browser.safari) {
    // enable drop shadow or whatever
}

Please note that $.browser is deprecated in jQuery 1.3 and its usage is generally frowned upon. For your purposes, however, I don't think it's particularly evil to use it, just know it's not 100% reliable.

A: Errr, what's the issue you're seeing with shadows? as they were first implemented in safari it seems surprising that that is the browser that you're seeing problems with.  What specifically are you doing?
(and as Paolo said -- browser sniffing is a really really bad idea)

A: the fact that safari loads ok the second time, and breaks when you refresh, might be an image without size issue. If dropShadow is called on domReady it will not know the size of the image the first time. The second time, the image will be cached and the shados will work ok.


text:
Q: i need to insert date into database when user clicks on login button through php <?php
    session_start();
    require_once('dbconfig/config.php');
    //phpinfo();
?>

<!DOCTYPE html>

<title>Login Page</title>
<link rel="stylesheet" href="css/style.css">

Login Form

        <form action="index.php" method="post">

                Username
                <input type="text" placeholder="Enter Username" name="username" required>
                Password
                <input type="password" placeholder="Enter Password" name="password" required>
                <button class="login_button" name="login" type="submit">Login</button>
                <button type="button" class="register_btn">Register</button>

        </form>

        <?php
            if(isset($_POST['login']))
            {
                @$username=$_POST['username'];
                @$password=$_POST['password'];
                                @$date=$_POST[date('Y-m-d')];
                $query = "select * from userinfotbl where username='$username' and password='$password' ";
                                $query1="insert into userinfotbl values('$date')";
                //echo $query;
                $query_run = mysqli_query($con,$query);
                                $query_run1 = mysqli_query($con,query1);
                //echo mysql_num_rows($query_run);
                if($query_run)
                {
                    if(mysqli_num_rows($query_run)>0)
                    {
                    $row = mysqli_fetch_array($query_run,MYSQLI_ASSOC);

                    $_SESSION['username'] = $username;
                    $_SESSION['password'] = $password;

                    header( "Location: homepage1.php");
                    }
                    else
                    {
                        echo '';
                    }
                }
                else
                {
                    echo '';
                }
            }
            else
            {
            }
        ?>

The date field in my database is getting filled with 0000-00-00.where i need to insert that field with the system date when the user clicks on login button.I am unable to detect the problem.I have a variable $date to which i am assigning the function date('Y-m-d').

A: Replace
@$date=$_POST[date('Y-m-d')];

with
$date=date('Y-m-d');

A: In Place of @$date=$_POST[date('Y-m-d')] use @$date = date('Y-m-d H:i:s');
Select datatype DATETIME in Mysql database field.
<?php
    if(isset($_POST['login']))
    {
      @$username=$_POST['username'];
      @$password=$_POST['password'];

      //@$date=$_POST[date('Y-m-d')];
      @$date = date('Y-m-d H:i:s');

    $query = "select * from userinfotbl where username='$username' and password='$password' ";
                    $query1="insert into userinfotbl values('$date')";
    //echo $query;
    $query_run = mysqli_query($con,$query);
                    $query_run1 = mysqli_query($con,query1);
    //echo mysql_num_rows($query_run);
    if($query_run)
    {
        if(mysqli_num_rows($query_run)>0)
        {
        $row = mysqli_fetch_array($query_run,MYSQLI_ASSOC);

        $_SESSION['username'] = $username;
        $_SESSION['password'] = $password;

        header( "Location: homepage1.php");
        }
        else
        {
            echo '';
        }
    }
    else
    {
        echo '';
    }
}

?>

A: Hi you only need to change the date datatype to timestamp and set default CURRENT_TIMESTAMP.
This will automatically add date value column and you don't need to provide date for that in query.


text:
Q: VueJs Change dragged item values I am using Vue Draggable
I have two lists with the "clone" option. Each list has a different Array.
I'm wondering if there is any possibility when dragging an item from list 1 to list 2, To change values to the dropped item in list 2.
For example I have in list 1 this item:
[{"type":"text","icon":"fa fa-text"}]
When dragged and dropped to list 2 it becomes:
[{"type":"text","id":"XXXX", "value":"My Text is Here","style":"...."}]
I don't know what event to list two and how to do it.
Thank you

A: You can use the clone props on the draggable component linked to list1.
Template:
<draggable :clone="clone" ...>

JS:
methods:{
  clone(element){
    return {
       type: element.type,
       value: "My Text is Here",
       style: "...."
    }
  }
}

A: Why dont you use the  onMoveCallback function for the event handeling. The code should be something like this
function onMoveCallback(event, originalEvent){
    event.draggedContext.element = //whatever changes you want to make

}

P.S I am not very clear on whether this is what you want . you can refer to the link in your document you mentioned


text:
Q: Extra Velocity engine output I have a variety of Velocity template files that represent e-mail messages.  I am searching for an elegant way to allow the template file to output a subject line for the message as well as the contents.  I have considered a few options:

*

*Make the first line of the output something like "Subject: Bla" and strip it out in the Java.  I have rejected this approach because performing fancy string manipulation from Java is exactly the problem I'm trying to solve by using Velocity in the first place.

*Throw a settable object into the mapping for some code in the Velocity macro to call a setter on.  Pros: Pretty simple.  Cons: I dislike the idea of setting external objects from Velocity, even as just a form of output.  It might be an unreasonable dislike, though.

*Create some custom Velocity command, like #setSubjectLine.  Pros: More elegant.  Cons: Would apply as a valid command to all of my templates, regardless of whether they're e-mails or not.

*Have separate template files for the subject line and the rest of the email.  Pro: No special tricks at all!  Con: Not all email logic lives in the same place.

*Some cool Velocity trick I don't know.

*???
So what should I do?  Do you have a suggestion for 5 or 6?  A reason I should choose 1, 2, 3, or 4?

A:
2) Throw a settable object into the mapping for some code in the Velocity macro to call a setter on. Pros: Pretty simple. Cons: I dislike the idea of setting external objects from Velocity, even as just a form of output. It might be an unreasonable dislike, though.

This was my approach, and I am pleased with it despite my own similar misgivings at first.  I even set character encoding and other attributes this way.  This leaves the rest of the template as the message body.  Again, I am pleased.
#set ( $myAtts.encoding = "utf-8" )
#set ( $myAtts.from = "stu@nowhere.net" )

A: At $work we do 4. It works fine, and the argument against not all email logic living in the same place seems a bit too strict. You would just have two velocity files next to each other. And even with just one template file, you still have logic to populate the data,  determine the recipients, attach the attachments, and so on, which also does not live in the Velocity file.

I would prefer 2 over 3, just because I do not like Velocity macros. Using Java objects seems more flexible.
$mailContext.setSubjectLine($subject)

With either 2 or 3, you can get closer to your goal of having everything in one place: You could get Velocity to set the recipient list, too, for example. This, one the other hand, seems to conflict with the idea of Velocity being a pure templating technology.
A thing to consider here is who is writing the Velocity templates. The closer it gets to "end-users", the less you want to trouble them with (and keep them from messing with) anything that is not directly related to creating the email content.

Not sure if that is feasible, makes sense or is even possible with the Java Mail API, but just for completeness:
 6. Have velocity create the whole email message including headers, not just content and subject. There difference to 1 is that you do not need to post-process this output, it can go straight to the mail transport agent. Probably does not work with attachments.
To: $to
CC: $cc
Subject: $subject

Here comes the content.


text:
Q: Why can we write lagrangian for gauge theory without the traces? I understand that trace is needed in order to preserve gauge invariance of the lagrangian equation by using the cycling property. But I fail to see why the following equation holds true:
$$-\frac{1}{2}Tr(F^{\mu\nu}F_{\mu\nu})=-\frac{1}{4}F^{a\mu\nu}F_{a\mu\nu}.$$
I also fail to understand how is the gauge symmetry preserved in the right term of this equation, I know that the $a$ index means that we are considering only the components and not the whole field but then I'm not even clear on how should I apply the field transformation such as an $SU(2)$ matrix to such components.

A: This is simply because
$$\text{tr } F^{\mu\nu} F_{\mu\nu} = \text{tr } F^{\mu\nu a} F_{\mu\nu}^b T_a T_b = F^{\mu\nu a} F_{\mu\nu}^b\, \text{tr } T_a T_b = \frac12 F^{\mu\nu a} F_{\mu\nu}^b \,  \delta_{ab} = \frac12 F^{\mu\nu a} F_{\mu\nu}^a$$
where the normalization $\text{tr}(T_aT_b) = \delta_{ab}/2$ is conventional.


text:
Q: How to play vimeo private videos in my iOS Application can you anyone help me how to play vimeo private videos . I have tried this https://github.com/vimeo/VimeoNetworking/ but it is always giving so many errors and pods not found .

A: The only way to play private video in IOS application is that if you have a direct link to the video file then you can play that video anywhere.

*

*You can get video file link using API only if you have Pro Account.

*Or you can get the video file link from the video setting page if you have a Pro account.


text:
Q: Prevent copy of app from overwriting the original I'm working on a windows phone application for an event. The event has an last year's event already had a windows phone application and all I really need to do are some updates. So I made a copy of the old application and started modifying it instead of creating a new solution from scratch.
Now here's my issue: when I deploy the new event application with Visual Studio to my phone it overwrites the old application. This is something I don't want, as I want to be able to compare the two on my phone. I also suspect that this might give me some issues when I upload the application to the store.
I suspect that this has something to do with copying files that are supposed to be unique for each application.
Any help would be appreciated!

A: The way I fixed this was by generating a GUID id using the GUID generator in Visual Studio ( as suggested by @Robert ). And changing the GUID in the WMAppManifest.xml and Package.appxmanifest files.


text:
Q: Load big amount of data in background I have an app that downloads a XML object and save it in a CoreData model. The root view shows this info in a table.
I was wondering, where is the best place to do this task (AppDelegate? viewDidLoad of the root view?)
The answer seems easy for small amounts of data, but where it should be place talking about a large file? And what´s the recommended approach?

A: I would suggest you to load this data in AppDelegate, show an UIActivityIndicator and load data in background, then update your RootView, when it is finished.

A: I would suggest you to load this data in viewDidLoad of the Root view. As mentioned data is not a big so there is no need to show UIActivityIndicator.


text:
Q: greatest or largest number Which of the following statements is correct?
a) 7 is the smallest and 9 is the greatest number
or
b) 7 is the smallest and 9 is the largest number
The research so far indicates that both terms largest and greatest are used in educational material. Largest implies size, but greater implies value, so greater seems more appropriate when dealing with abstract concepts. I am interested in why one may be more appropriate than the other when dealing with young learners, keeping in mind common misconceptions that children can make.

A: In everyday usage, both "larger" or "greater" would be OK. I personally prefer "greater", since that leave less room for interpretation. If I have -1,000,000 compared to 2, the -1,000,000 is "larger number" in that it takes more physical space to write it, but 2 is unambiguously the greater of the two. Also, this terminology makes inequalities easier, since > is usually pronounced "greater than", not "larger than".

A: Have you searched these terms on a search engine?
Personally, I would say "largest number", but maybe both are OK.
Wikipedia has the page http://en.wikipedia.org/wiki/Largest_number :

Largest number is mathematically meaningless (since in the usual system of integers, adding one to any number produces a larger number). However, the term may refer to:

*

*Names of large numbers, for the largest numbers with names

*Infinity, a concept which can be used as a largest number in some contexts

*Graham's number, once claimed as the largest number ever used in a serious mathematical proof

*Large numbers, for notations to exactly specify very large numbers

*Largest known prime number, for the largest known number for which no integer divisors exist

and Google Ngram seems to say that both are equally used nowadays :

A: Both "greater" and "larger" are perfectly acceptable. They mean the same, and have roughly equal usage in Google NGram, which is a good indication (but not infallible).
However, as you are comparing two numbers you should use the comparative not the superlative. It should be "7 is the smaller and 9 is the greater (or larger) number".


text:
Q: Modifying email after button clicked in form getting error Object required In ThisOutlookSession:
Private Sub objInspectors_NewInspector(ByVal Inspector As Inspector)
If Inspector.CurrentItem.Class <> olMail Then Exit Sub
Set objMyNewMail = Inspector.CurrentItem
End Sub

In form code:
Private Sub SendButton_Click()
EmailFlagger.Hide
objMyNewMail.Body = objMyNewMail.Body & EmailFlagger.Exemptions.Text
End Sub

I get the error Object required. How do I fix this?

A: It is not clear what line of code generates the error... Try to switch the lines of code in the Click event handler:
Private Sub SendButton_Click()
  objMyNewMail.Body = objMyNewMail.Body & EmailFlagger.Exemptions.Text
  EmailFlagger.Hide
End Sub

The NewInspector event is not the right place for accessing the mail item object. Use the Activate event instead. For example, in the NewInspector event handler you can subscribe to the Activate event where you can get the valid mail object.


text:
Q: CABasicAnimation disappear when home button is pushed I'm implementing a game, in which i have some CABasicAnimations.
For example, like this :
CABasicAnimation * borddroit = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
borddroit.fromValue = [NSNumber numberWithFloat:0.0f];
borddroit.toValue = [NSNumber numberWithFloat:749.0f];
borddroit.duration = t;
borddroit.repeatCount = 1;
[ImageSuivante2.layer addAnimation:borddroit forKey:@"borddroit"];

I put it in pause with this function :
-(void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

When my application is entering background, because the user push the home button, the animations correctly set in pause, but when i re-open my app, the animations have disappeard.
How could i fix it please ?
Thank you

A: This is correct and built-in behavior. When you leave the app, all animations are removed from their layers: the system calls removeAllAnimations on every layer.
This doesn't matter, usually, for the following reason: suppose you animate a ball from point A to point B and it is halfway to point B in the animation when the user switches away from your app. When the user comes back, the animation is gone, but the ball is at point B, so the app can just continue. All that happens is that we've skipped some of the animation part.

A: Observe UIApplicationWillEnterForegroundNotification and re-animate CAAnimation

A: Just add below code in either your UIViewController or in your UIView class. No need to resume or start again animation. It will handle by its own :)
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive:) name:UIApplicationWillEnterForegroundNotification object:nil];

-(void)becomeActive : (NSNotification*)notification
  {
    NSLog(@"app become active");
  }

A: All animations are removed when view disappears from the visible area (not only when app goes into background). To fix it I created custom CALayer subclass and overrided 2 methods so the system doesn't remove animations - removeAnimation and removeAllAnimations:
class CustomCALayer: CALayer {

    override func removeAnimation(forKey key: String) {

        // prevent iOS to clear animation when view is not visible
    }

    override func removeAllAnimations() {

        // prevent iOS to clear animation when view is not visible
    }

    func forceRemoveAnimation(forKey key: String) {

        super.removeAnimation(forKey: key)
    }
}

In the view where you want this layer to be used as main layer override layerClass property:
override class var layerClass: AnyClass {

    return CustomCALayer.self
}


text:
Q: Unable to locate element using ID, XPath and CSS Selector I am using atata framework with C#. I am trying to locate web element to select all rows but neither Id, CSS Path or XPath are able to find.
I have used ID, XPath and CSS Selector
[FindById("com.kronos.wfc.ngui.genies.selectall")]
public Button<_> SelectAllRows { get; private set; }

[FindByXPath("div[@id=com.kronos.wfc.ngui.genies.selectall]")]
public Button<_> SelectAllRows { get; private set; }

My page object should be located. Details of paths are:
Element:

<button type="button" class="btn btn-rounded widget-button-icon" id="com.kronos.wfc.ngui.genies.selectall_btn">
</button>
Select All Rows

Selector: #com.kronos.wfc.ngui.genies.selectall
XPath: //*[@id="com.kronos.wfc.ngui.genies.selectall"]

A: *

*For the first
 element:

As it is a div, not a button element then use general puprose Control type:
[FindById("com.kronos.wfc.ngui.genies.selectall")]
public Control<_> SelectAllRows { get; private set; }

*For the second <button> element:
<button type="button" class="btn btn-rounded widget-button-icon" id="com.kronos.wfc.ngui.genies.selectall_btn">

The following should find the element if it's actually visible:
[FindById("com.kronos.wfc.ngui.genies.selectall_btn")]
public Button<_> SelectAllRows { get; private set; }

If the element is not visible:
[FindById("com.kronos.wfc.ngui.genies.selectall_btn", Visibility = Visibility.Any)]
public Button<_> SelectAllRows { get; private set; }

Anyway, figure out which element is actually visible and should be interacted with.

A: I think you should perform the click action on the button element instead of the div element. Try the below code:
[FindById("com.kronos.wfc.ngui.genies.selectall_btn")]
public Button<_> SelectAllRows { get; private set; }


text:
Q: OpenAI fine tuning each of the classes must start with a different token error I am trying to run a fine tune similar to the one in openAI cookbook example for a multiclass classification problem. After preparing the train and valid jsonl files with fine_tunes.prepare_data, when I try to run the recommended fine_tunes.create command, I'm getting the following error:

If compute_classification_metrics is True, each of the classes must start with a different token. You can view your class tokenizations at https://beta.openai.com/tokenizer?view=bpe.. Fine-tune failed. For help, please contact OpenAI and include your fine-tune ID.

A: Looks like this error comes when the completion value is of more than a single token. After changing the completion values to numerical ids to ensure that they are of single tokens, the fine tune ran fine.
I'm not sure why the prepare_data step itself didn't say any error regarding this given that I used openai command line tool to prepare that.


text:
Q: Menu Options not working in tablet The menu options created are working perfectly fine in phone(both as overflow menu or left click device button).
But in tablet it only works on ones which have the overflow menu(the 3 dots).
When I click on the device left button nothing shows up. Not sure whats the problem
Layout:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_settings"
        android:title="@string/settings_menu"
        app:showAsAction="never" />

    <item
        android:id="@+id/menu_signout"
        android:title="@string/settings_sign_out"
        app:showAsAction="never" />

</menu>

Code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.overflow_menu, menu);
    settings = menu.findItem(R.id.menu_settings);
    signOut = menu.findItem(R.id.menu_signout);
return true;
}


text:
Q: Are these different versions of completeness or the same? When talking about completeness I have come across two versions

A normed vector space is called complete if every sequence $(x_n)_{n \in \mathbb{N}}$ in $X$ (a vector space over $\mathbb{C}$) which has the Cauchy property is convergent in $(X,||\cdot||)$.

Also on first learning about sturm-liouville theory I hear about eigenfunctions forming a "complete set". An example would be to consider
$$y'' = f(x),\quad y(0) = y(1) = 0$$
the eigenfunctions are $y_k = \sin(k\pi x)$ for negative integers $k$. The version of completeness I have in this case is

$\{y_k\}$ is complete if every $h$ s.t $\int_a^bh^2 < \infty$ can be written as $$h(x) = \sum_{k}^{\infty} c_ky_k$$

I interpret this as:

every $L^2$ function can be written as an infinite linear combination of $\{y_k\}$.

I am trying to see whether these concepts are related, or even if they are the same thing. We can see some similarity in that in order for the sum to be convergent, the sequence of functions $\{y_k\}$ must be convergent. So would it be correct to take "the eigenfunctions form a complete set" as

*

*$y_k$ span $L^2(a,b)$

*$y_k$ are Cauchy (?)

*each $y_k$ satisfy the BVP

I am having doubt with the second point as the eigenfunctions we have just talked about satisfy
$$||y_k-y_l|| = 1$$
My question being

Are these concepts of completeness related?

A: No, these notions of completeness mean different things. The first refers to completeness of metric spaces. We need not have a vector space structure at all. The second refers to orthonormal bases of Hilbert spaces. Basically, an orthonormal subset $\Pi$ of a Hilbert space $H$ is called complete (or an orthonormal basis) if $\overline{\operatorname{span}(\Pi)}=H$.


text:
Q: scrollIntoView does not trigger mousewheel nor scroll event in Angular I use Angular and registered a mousewheel and scroll event. When I use scrollIntoView this event is not triggered. Is there any other event I miss?
  @HostListener('mousewheel', ['$event'])
  mousewheel(event: MouseEvent) {
    console.log("mousewheel");
  }

  @HostListener('scroll', ['$event'])
  scroll(event: MouseEvent) {
    console.log("scroll");
  }

And I use the function as this:
element.scrollIntoView({behavior: 'smooth'});

Does anyone know what I miss here?

A: You can always use addEventListener to add the scroll functionality. Also, don't forget to remove it in ngOnDestroy Here's an example:
export class WindowScrollDirective implements OnInit, OnDestroy{

 ngOnInit() {
    window.addEventListener('scroll', this.handleScroll, true);
 }

 ngOnDestroy() {
     window.removeEventListener('scroll', this.handleScroll, true);
 }

 handleScroll = (event): void => {
   //handle your scroll here

 };
}

NOTE: you can replace the window object by the element you want to use for scrolling.