text:
Q: Mostrar elementos de ArrayList en otra ventana Estoy haciendo una pequeña aplicación que realiza un sorteo entre varios participantes y muestra el resultado en un JDialog. Tengo dos errores en el código que no la permiten ejecutar bien:
    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
    //  Convierte el arreglo textoConNombres a una lista listaNombres
    String[] textoConNombres = jTextArea1.getText().split("\n");
    List<String> listaNombres = new ArrayList<>
    (Arrays.asList(textoConNombres));

    Random sorteo = new Random();

    //  Obtiene el valor del comboBox

    //No puedo castear de object a int en la parte de JComboBox1
    int cantTitulares = Integer.parseInt(jComboBox1.getSelectedItem());
    ArrayList ganadorTitular = new ArrayList();

    /*  Hace el sorteo las veces que dice el comboBox
        agrega al ganador a un arrayList aparte
        lo elimina de la lista para hacer el sorteo con el resto
        de los participantes que quedan sin ganar.*/

    for (int i = 0; i < cantTitulares; i++) {
        int ganador = sorteo.nextInt(listaNombres.size());
        ganadorTitular.add(ganador);
        listaNombres.remove(ganador);
    }

    // Muestra el resultado en VentanaGanador, que es otra clase

    VentanaGanador ventGanador = new VentanaGanador();
    for (int i = 0; i < ganadorTitular.size(); i++) {

        // Aquí no puedo seleccionar el índice del array para mostrar el elemento
        ventGanador.etiquetaGanador.setText(/////);

    }

La idea básicamente es que dentro del for se realice el random y se vaya quitando la persona que ganó para que no vuelva a salir sorteada. El problema es que no puedo mostrar los objetos del Array, intenté y busqué pero no sé cómo.

A: Saludos, Martín.
Verás, la forma en que se convierte (o 'castea') un Object es diferente a como se realiza usualmente con String, en tu código estás utilizando la segunda forma:
Integer.parseInt(jComboBox1.getSelectedItem());
Si te das cuenta, esto: jComboBox1.getSelectedItem() retorna un valor de tipo Object, entonces tienes dos opciones, o haces que todo el modelo del JComboBox sean siempre valores enteros (puesto que para eso se utilizarán), o bien, simplemente conviertes el Object retornado a entero.
Para no entrar en muchos detalles, puedes utilizar la segunda forma. Para lograrlo debes hacer algo como esto:
int cantTitulares = (int) ((String) jComboBox1.getSelectedItem());
De esa manera, obtendrás el Object del JComboBox como un entero.
Por otro lado, tienes el problema de mostrar en una etiqueta (supongo que te refieres a un JLabel) el o los ganadores generados. Si lo que deseas es mostrar el nombre del ganador (los que agregaste en la lista listaNombres)  primero debes hacer una modificación en el for donde eliges a los ganadores, ¿por qué?. Bueno, si revisamos tu código:
for (int i = 0; i < cantTitulares; i++) {
    int ganador = sorteo.nextInt(listaNombres.size());
    ganadorTitular.add(ganador); // Aquí estás guardando un entero
    listaNombres.remove(ganador);
}

ganadores un entero, para que guarde el nombre del ganador sería:
for (int i = 0; i < cantTitulares; i++) {
    int ganador = sorteo.nextInt(listaNombres.size());
    ganadorTitular.add(listaNombres.get(ganador));  // Obtienes el nombre de la lista según el entero elegido
    listaNombres.remove(ganador);
}

De esa manera, al momento de mostrarlos en la etiquetaGanador, harías esto:
for (int i = 0; i < ganadorTitular.size(); i++) {
    ventGanador.etiquetaGanador.setText((String) ganadorTitular.get(i));
}

(String) ganadorTitular.get(i) lo que hace es convertir el Object en String para que pueda ser agregado al JLabel como texto. Esto se debe a que en el ArrayList no indicaste el tipo de dato y por defecto los almacena como Object.
EDIT:
Con respecto a tu pregunta en el comentario sobre agregar los demás nombres, una forma realmente sencilla y que te permite mantener todo justo como lo tienes, es utilizando código HTML dentro del texto que le pondrás al JLabel etiquetaGanador.
Además, para esto deberías antes realizar una pequeña modificación en el for que utilizas para poner el nombre de los ganadores en ese JLabel.
Tendría que quedarte algo así:
String ganadoresStr = ""; // Se crea la cadena de texto con la etiqueta inicial
for (int i = 0; i < ganadorTitular.size(); i++) {
    ganadoresStr += ganadorTitular.get(i); // agrega el primer ganador
    if (i + 1 < ganadorTitular.size()) { // verifica si existirán más ganadores
        ganadoresStr += "
"; // si existirán más, agrega salto de línea para agregar al otro debajo de él
    }
}
ganadoresStr += ""; // finaliza la etiqueta
ventanaGanador.etiquetaGanador.setText(ganadoresStr); // ajusta el JLabel con todos los ganadores

Básicamente lo que hace es añadir el nombre de los ganadores en una misma cadena de texto, y cada ganador, lo separa con la etiqueta HTML
 (lo cuál corresponde a un salto de línea). El if dentro del for, solamente verifica si debe o no agregar esa etiqueta (es para evitar agregar un salto de línea al final). Y por último cierras la etiqueta HTML con .
De esta manera, los nombres de los ganadores quedarían como una 'lista' en el mismo JLabel sin necesidad de modificar tus componentes.


text:
Q: iOS localization can i use 2 ttf file in the plist? here is a sample line:
    playLabel = [CCLabelTTF labelWithString:NSLocalizedString(@"play", nil) fontName:@"font.ttf" fontSize:32];

and my font.ttf file only support English/Chinese/Japanese, and if it is korean, nothing will show up. so i want to use Arial font for Korean (but still my custom font.ttf font for chinese/japanese, for french or spanish it's fine though since i can simply ignore the mark above letters.
so how can i do this? or should i make a method like [Helper getFont] and return different font files for different localization?
and also, when adding the language, i have multiple choices for one language (like 'zh' is chinese, but 'zh-hans' is simplified chinese and 'zh-hant' is traditional chinese, so can i just use zh for both case if i don't want to separate them?

A: I am not sure if this will work (seems like it should), but what about if you defined the different font names in your localization files?
NSString *fontName = NSLocalizedString(@"playLabelFontName", nil);

playLabel = [CCLabelTTF labelWithString:NSLocalizedString(@"play", nil) fontName:fontName fontSize:32];

In your English/Chinese/Japenese localization file put:
"playLabelFontName" = "font.ttf"

In your Korean put:
"playLabelFontName" = "Arial.ttf"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing title automatically according to selected layer using QGIS composer I'm working on a project where I have to create different maps for the same area. I have lots of maps and each of them is related to a different theme, that I've grouped into different groups of layers as you can see in the image.
Each group of layers has a name that will be used as the map title. Because I have a lot of them, each time that a select a different group I want to change the map title automatically to have the same name as the layer group that is selected.
How I can do that?

A: For QGIS 2.18.x
In your composer label, go to Item Properties > Insert an expression.... Click the Function Editor tab and either create a new file or use an existing one (these are scripts which can execute some code). Use something like the following code:
from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def func(feature, parent):
    root = QgsProject.instance().layerTreeRoot()
    layer = qgis.utils.iface.activeLayer()
    lyr = root.findLayer(QgsMapLayerRegistry.instance().mapLayersByName(layer.name())[0].id())
    group = lyr.parent().name()
    if group != '':
        return lyr.parent().name()
    else:
        return 'Group not found'

Then click Load. Switch to the Expression tab and type the name of the function, which in this example is:
func()

Hopefully now, when you click on a layer, the name of the group should show up.

Note: you may need to click on the composer window for the name to be refreshed.

For QGIS 3.x
Similar to the above method but in the code, replace:
QgsMapLayerRegistry

with:
QgsProject

So the code should read:
from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom')
def func(feature, parent):
    root = QgsProject.instance().layerTreeRoot()
    layer = qgis.utils.iface.activeLayer()
    lyr = root.findLayer(QgsProject.instance().mapLayersByName(layer.name())[0].id())
    group = lyr.parent().name()
    if group != '':
        return lyr.parent().name()
    else:
        return 'Group not found'


text:
Q: Select layer by attribute for entries in a dictionary (python) I'm kinda new to python (and programming) and having trouble figuring out how to properly specify what I want to do.
Basically, my code compares names of well owners and orps owners and saves all orps that match a given well in a dictionary as
matches[fid of well] = fid of matching orps, fid of matching orps, etc.
Such that some wells are not included in the dictionary, some wells have one entry, and some wells have several entries.
Once created, I then need to:

*

*select the well that the key of the dictionary is referring to

*select the orps pts that the key is referring to

*create a near table of matching orps for that given well. (this part I know how to do)

I guess I'm just unsure of the syntax required to do this. I'm sure the answer to this lies somewhere within the SQL query in the:
arcpy.SelectLayerByAttribute_management(in_layer, {selection_type}, {where_clause})
function, but I'm having trouble constructing the query. Can anyone give me a hand?
Full code:
import arcpy

arcpy.env.overwriteOutput = 1

# define a workspace
arcpy.env.workspace = r"C:\Users\tmc18\Desktop\comp_orps\NYS_Wells.gdb"

# Define input files
orps = r"C:\GIS\Madison_County_orps.gdb\orps_Cazenovia"
wells = r"C:\GIS\NYS_Wells.gdb\Madison_wells_cazenovia"

# Make a feature layer
arcpy.MakeFeatureLayer_management(orps, "orps1")
arcpy.MakeFeatureLayer_management(wells, "wells1")
wellsFL = "wells1"
orpsFL = "orps1"

# Create dictionary of last names of all well owners
well_owners = {}
rows = arcpy.da.SearchCursor(wellsFL, ["OBJECTID", "OWNER_L"])
for row in rows:
    well_owners[row[0]] = str(row[1])
del rows

# create dictionary of addresses of ORPS pts
loc_info = {}
rows = arcpy.da.SearchCursor(orpsFL, ["OBJECTID", "LOC_NUM", "LOC_NAME", "PRINT_KEY"])
for row in rows:
    loc_info[row[0]] = str(row[1]+" "+row[2]+","+" "+row[3])
del rows

matches = {}

y = 0

# Create search cursor which will iterate through wells
with arcpy.da.SearchCursor(wellsFL, ["OBJECTID"]) as cursor:
        for row in cursor:

            match_list = []
            # set well owner name for this record
            record = row[0]
            owner = well_owners[record]

            # create search cursor which will iterate through orps owners
            with arcpy.da.SearchCursor(orpsFL, ["OWNER_L", "OBJECTID"]) as orpscur:
                for row in orpscur:
                    # set orps owner name
                    orpsowner = row[0]
                    ID = row[1]

                    # compare owner's names
                    if owner != orpsowner:
                        pass

                    else:
                        y = y + 1
                        match_list.append(ID)

            matches[record] = match_list

print y, "total matches found"

A: This is more of a few tips than an answer.  You mention that it takes a while to run.  I have to things to point out that can save some you some time.
1) Your code goes through the wells once; no need to do it twice.  You can get the list of well owner's names from the well_owners.values().  That's a python list of all the values in the dictionary.  In your case you would get a list of string values.  Thus we can chop:
# Create search cursor which will iterate through wells
with arcpy.da.SearchCursor(wellsFL, ["OBJECTID"]) as cursor:
        for row in cursor:

            # set well owner name for this record
            record = row[0]
            owner = well_owners[record]
            matches[record] = []

            # create search cursor which will iterate through orps owners
            with arcpy.da.SearchCursor(orpsFL, ["OWNER_L", "OBJECTID"]) as orpscur:
                for row in orpscur:
                    # set orps owner name
                    orpsowner = row[0]
                    ID = row[1]

                    # compare owner's names
                    if owner != orpsowner:
                        pass

                    else:
                        x = x + 1
                        matches[record].append(ID)

to the following.  This method removes iterating through the orpsFL with each well.
# create search cursor which will iterate through orps owners
with arcpy.da.SearchCursor(orpsFL, ["OWNER_L", "OBJECTID"]) as orpscur:
    for row in orpscur:
        # set orps owner name
        orpsowner = row[0]
        ID = row[1]
        # see if orps owner is in list of well owner
        if orpsowner in well_names.values():
            x += 1
            matches[orpsowner].append(ID)

2) SQL has an IN operator that is very useful.  You are adding to the selection for each matching OID.  It's faster to say "OBJECTID IN (1,2,3,4,5)" than selecting 1, then 2, then 3, etc.  So we can change:
for key in matches:
    arcpy.SelectLayerByAttribute_management(wellsFL, "NEW_SELECTION", "OBJECTID =    {}".format(key))
    for element in matches[key]:
        nextmatch = matches[key].pop()
        arcpy.SelectLayerByAttribute_management(orpsFL, "ADD_TO_SELECTION", "OBJECTID = {}".format(nextmatch))

to:
for key in matches:
    arcpy.SelectLayerByAttribute_management(wellsFL, "NEW_SELECTION", "OBJECTID =    {}".format(key))
    # tuple of ids to select
    id_select = tuple(matches[key])
    arcpy.SelectLayerByAttribute_management(orpsFL, "NEW_SELECTION", "OBJECTID in {}".format(id_select))

I hope I didn't change any variable names and that you find this helpful.

A: So, I solved this problem by saving the orps matches for each well in match dictionary as a list, and then selected each one using the list.pop() method, which treats the list as a stack and retrieves and removes the bottom value. The code above is the same, except...
matches = {}
x = 0

# Create search cursor which will iterate through wells
with arcpy.da.SearchCursor(wellsFL, ["OBJECTID"]) as cursor:
        for row in cursor:

            # set well owner name for this record
            record = row[0]
            owner = well_owners[record]
            matches[record] = []

            # create search cursor which will iterate through orps owners
            with arcpy.da.SearchCursor(orpsFL, ["OWNER_L", "OBJECTID"]) as orpscur:
                for row in orpscur:
                    # set orps owner name
                    orpsowner = row[0]
                    ID = row[1]

                    # compare owner's names
                    if owner != orpsowner:
                        pass

                    else:
                        x = x + 1
                        matches[record].append(ID)

print x, "total matches found"
for key in matches:
    arcpy.SelectLayerByAttribute_management(wellsFL, "NEW_SELECTION", "OBJECTID =    {}".format(key))
    for element in matches[key]:
        nextmatch = matches[key].pop()
        arcpy.SelectLayerByAttribute_management(orpsFL, "ADD_TO_SELECTION", "OBJECTID = {}".format(nextmatch))
    arcpy.GenerateNearTable_analysis(wellsFL, orpsFL, "orps_near_well_{}".format(key), "5 kilometers", "LOCATION", "NO_ANGLE", "ALL", "5")
    arcpy.SelectLayerByAttribute_management(orpsFL, "CLEAR_SELECTION")

and, it works perfectly, even if it does take a little bit. Some parts of the full code (such as the loc dictionary) are not 100% necessary right now, but will become more necessary as I flesh out this script to do more things (add the loc info of the best matching orps pt to the well table, etc).


text:
Q: How can I properly generate both TRX files and code coverage results with one call to "dotnet test"? First, some context: I have a Visual Studio solution containing several production class libraries and nine unit test projects. All the projects are targeting .NET 5. I am running .NET 5.0.401. All unit test projects have references to coverlet.collector. I do not use the older coverlet.msbuild package. From my reading, using XPlat Code Coverage is now idiomatic for .NET Core.
I have an Azure Pipelines pipeline that I use for CI builds. As a part of this pipeline, I want to run all the unit tests, generate unit test results for upload to Pipelines, and generate code coverage results for upload to Pipelines. I've already read several blog articles and documentation that would seem to make this simple; however, I've found it's anything but.
Let's start simple by running some commands on my local workstation. For the purposes of this exercise we will assume I have already successfully built the solution using this command:
dotnet build Solution.sln --configuration Debug

If I run tests like this:
dotnet test Solution.sln --configuration Debug --no-build --no-restore --collect:"XPlat Code Coverage" --results-directory artifacts/test-results

then I see code coverage results stored in subdirectories named after GUIDs. Why Microsoft decided to do this I have no idea, but that's out of my control.

(After running this command and taking the screenshot, I deleted the test-results directory.)
Remember that I also want to generate unit test results. To do that, I add the --logger trx parameter to the same command line. This time, lots of other folders are created that contain what appear to be duplicate code coverage results. Additionally, I get the .trx files I'm looking for.

You'll notice there are an additional nine code coverage reports in addition to the nine .trx files I want.
Similar duplicate files are generated on my self-hosted Pipelines build agent. In Pipelines, if I try to execute the following task:
- task: 'PublishCodeCoverageResults@1'
  displayName: 'Publish code coverage results'
  inputs:
    codeCoverageTool: 'Cobertura'
    summaryFileLocation: 'artifacts/test-results/**/coverage.cobertura.xml'

I get an error:
##[warning]Multiple file or directory matches were found. Using the first match: C:\agent\_work\38\s\artifacts\test-results\$redacted\In\redacted\coverage.cobertura.xml
##[error]No code coverage results were found to publish.

The directory it's reporting here is not one of the GUID directories generated when I omit --logger trx but instead one of the duplicate directories.
This answer seems to indicate I'm doing everything properly. I've also posted a comment on that answer hoping for some assistance.
I have several questions:

*

*Am I invoking dotnet test correctly in order to generate code coverage results and .trx files at the same time?

*Does dotnet test support this scenario?

*Is the function of the ReportGenerator extension in the Azure Pipelines marketplace actually built into dotnet now?

*Which code coverage results are the "real" ones? Do I need to copy the GUID folders to another location before publishing code coverage results?

*I want to specify a RunSettings file in order to do things like exclude members with certain attributes from being considered by the code coverage engine. Is RunSettings compatible with my workflow?

A: If you have multiple coverage files, you need merge them first before you publish. You may achieve this with following:
  - task: DotNetCoreCLI@2
    displayName: "dotnet test"
    inputs:
      command: test
      projects: "*.sln"
      publishTestResults: true
      arguments: -c Release --no-restore --no-build /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

  - task: reportgenerator@4
    displayName: "Merge code coverage reports"
    inputs:
      reports: "**/coverage.cobertura.xml"
      targetdir: "$(Build.ArtifactStagingDirectory)/coverlet"
      reporttypes: "Cobertura"
      verbosity: "Verbose"

  - task: PublishCodeCoverageResults@1
    displayName: "Publish code coverage results"
    inputs:
      codeCoverageTool: Cobertura
      summaryFileLocation: "$(Build.ArtifactStagingDirectory)/coverlet/Cobertura.xml"

Note: some parameters probably need to be adjusted to your porject (like directories where you expect to have cobertura files).
I don't have in my code specifig logger for trx and I see in logs that they are produced.
If you want to pass runsettings please check this doc - Configure a test run.


text:
Q: SQL Query Builder and Charting I'm looking for a product that can be placed into an ASP.NET page which will allow users to build their own queries to produced a data set, of which they can create their own reports/charts/graphs based on the data set.
I've looked into EasyQuery.NET, which has a query builder similar to what I'm looking for, but it does not have charting abilities.  I've also seen SiSense's product, which allows users to build their own queries and create reports/charts/graphs based on the results, but it is too expensive for me.
Any suggestion would be greatly appreciated!
Rusty

A: You can use SQL Server Reporting Services and in particular, Report Builder to allow your users to not only view reports, but also create their own, subscribe to them, etc.
Charting is one of the capabilities of the Report Builder see this TechNet article, for example.


text:
Q: Is there a way using jQuery to submit a form without the elaborate field by field breakdown? I'm using jQuery to perform AJAX based page reloads on links - they bring up the "Loading..." div window and then close it when the content returns and load the content.  This works exactly as expected.
I have several different forms in my project that I would like to submit using the same method - on submit bring up a "Loading..." div window and then close it when the content returns.  Is there any way to do this without writing a custom function for each form?  The samples I've seen require you to grab and encode each form field and pass it in the ajax method.  Some forms only have a few fields, others have many so this would be a cumbersome process.  I'd like it to just grab all fields in the form and submit them under the field names.
Any insight on this would be greatly appreciated!

A: It looks like you're looking for something along the lines of .serialize(). It's basically jQuery's utility function for encoding form elements for an AJAX call or a GET query string.
Using that gets you something that looks like myinput=somevalue&myotherinput=someothervalue based on the name properties of your form elements. You can chuck that into whatever call you're making against your server, as long as they recognize the format (versus something like JSON data or a scalar string, for example).

A: It's pretty easy actually, you can do this:
$('form').serialize();

obviously you want to send it your form, but if you call serialize after selecting a form tag, it will serialize the form for you. You can then use that in your ajax call.

A: you can use serialize() in this way
$('#formId').serialize();

A: Maybe one way can be using the $.serialize() function. You can write a function to execute when a form is submitted. For example, if you have three forms withd id "form1", "form2" and "form3":
$(document).ready(function()
{
    $('#form1, #form2, #form3').submit(sendData);
});

function sendData()
{
    var dataString=$(this).serialize();

    $.ajax({
        url: "url_to_send.php",
        data: dataString
    });

    return false;
}

A: Have you read this?
http://api.jquery.com/jQuery.post/
$.post("test.php", $("#testform").serialize());


text:
Q: RSpec - Testing strong parameters I am using the strong_parameters gem in my controllers, but I'm having a hard time understanding how I would test it.
Here's an example of my setup
class UserController < ActionController::Base
  include ActiveModel::ForbiddenAttributesProtection

  def create
    @user = User.new(user_params)
    if @user.save
      ...
    end
  end

  private
  def user_params
    params.require(:user).permit(:first_name, :last_name, :username, :email)
  end
end

I want to test the user_params method to make sure that it is correctly filtering out malicious key/value pairs, but can't figure out how to do it.  Has anyone else been through this?

A: Modify this according to your need,
describe "create action" do
    it 'creates a user' do
      User.should_receive(:create).
        with({name: 'Alan D'}.with_indifferent_access)
      post :create, user:
        { first_name: 'Alan', last_name: 'Donald', username: 'alan77', email: 'mymail@yopmail.com' }
    end
end

or other alternative solution to this problem is:
describe UsersController::UserParams do
  it 'cleans the params' do
    params = ActionController::Parameters.new(user: {foo: 'bar', name: 'baz'})
    user_params = UsersController::UserParams.build(params)
    expect(user_params).to eq({name: 'baz'}.with_indifferent_access)
  end
end

A: You can stub the params hash as
params = ActionController::Parameters.new(your_hash)

This is the class that your URL params are being converted to in your controller, and it gives you the require and permit methods.
I personally extract the functionally out into a new class to handle the authorization policy.

A: I'm not sure I would test strong_parameters, which I am guessing you're using via the gem.
The gem has its own tests, so we can assume it works as expected.
This is an example of 'testing Rails', which I believe is unnecessary. I wouldn't test that attr_accessible works as advertised (Testing Rails), or attr_accessor (Testing Ruby).
IMHO, your integration tests should cover all desired instances of success/failure and implicitly cover your strong_parameter configuration.


text:
Q: how to loop back to scetion if this is outcome I want to loop the end section of the code if you get the 'Error, class not found'. I already tried a, for and while loop but i couldn't get it working.
Health = 0
Damage = 0
Classes = ['Mage','Knight']
Class = ''
print('Select Character Name.')
Name = input()
print('Hello',Name,'please choose your class.')
print('')
print('Mage: 5 Health: 7 Damage')
print('Knight: 7 Health : 5 Damage')

#looped section
Select = input()
if Select in ['Mage']:
        print('Mage Selected')
        Health = 5
        Damage = 7
        Class = 'Mage'
elif Select in ['Knight']:
        print('Knight Selected')
        Health = 7
        Damage = 5
        Class = 'Knight'
else:

    print('Error, class not found')
#loop back if this is outcome

A: when facing problems like this, your default approach should be a while loop making sure that the loop will go on (virtually forever) if the defined conditions aren't met. so this is what you can do:
while True:
    # looped section
    Select = input()
    if Select in ['Mage']:
            print('Mage Selected')
            Health = 5
            Damage = 7
            Class = 'Mage'
            break # break the loop if selection is correct
    elif Select in ['Knight']:
            print('Knight Selected')
            Health = 7
            Damage = 5
            Class = 'Knight'
            break # break the loop if selection is correct
    else:
        print('Error, class not found, try again: ') # will start the loop over


text:
Q: Struggling to get Greensock to animate locally I'm working with greensock and I can't seem to get it to animate anything locally.
I copied and pasted my code into codepen and the animation is working correctly there. The only difference between the two are minor differences in the html file, which are pasted below.
<!DOCTYPE html>
<html lang="en">
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/plugins/CSSPlugin.min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/easing/EasePack.min.js"></script>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.0/TweenLite.min.js"></script>

        <script src="animate.js"></script>
        <link href="style.css" rel="stylesheet" type="text/css">
    </head>
<body>
    <div id="blue">

    </div>
</body>
</html>

I can debug through the JS and see the console.log working and the TweenLite functions appear to be called without any errors, but there is no animation on the screen. I've tried in Edge, Chrome, IE11, and Firefox. None of them show any animations.


text:
Q: Encode javascript string bytes as base64 I have a code in c#
public static string Encriptar(string _cadenaAencriptar)
{
    string result = string.Empty;
    byte[] encodedData = System.Text.Encoding.Unicode.GetBytes(_cadenaAencriptar);
    result = Convert.ToBase64String(encodedData );
    return result;
}

I want this code in javaScript.
Helpme please.

A: So you are taking a utf16 encoded string and converting the utf16 bytes to a Base64 encoded string.
The following JavaScript first converts the string to a array of utf16 bytes.
Then converts the array to a Base64 encoded string.
_arrayBufferToBase64(strToUtf16Bytes(_cadenaAencriptar))

https://stackoverflow.com/a/9458996/361714
function _arrayBufferToBase64( buffer ) {
    var binary = '';
    var bytes = new Uint8Array( buffer );
    var len = bytes.byteLength;
    for (var i = 0; i < len; i++) {
        binary += String.fromCharCode( bytes[ i ] );
    }
    return window.btoa( binary );
}

https://stackoverflow.com/a/51904484/361714
function strToUtf16Bytes(str) {
  const bytes = [];
  for (ii = 0; ii < str.length; ii++) {
    const code = str.charCodeAt(ii); // x00-xFFFF
    bytes.push(code & 255, code >> 8); // low, high
  }
  return bytes;
}

Output from javascript:
_arrayBufferToBase64(strToUtf16Bytes("hi"))
"aABpAA=="

Which matches the output from C#.


text:
Q: Fastest way to decode a hexadecimal digit I am looking for the fastest way to get the decimal value of a hexadecimal ASCII character, i.e. one that is guaranteed to appear in the following string (it can be lower or upper case, but no white space):
0123456789ABCDEFabcdef

So far, the best formula I've come up with is:
char c = 'd';  // or any other hex character
int value = (((c & 0x1F) + 9) % 25;

Note that it is branch-free, but it does contain an expensive modulo operation.
Can I do better?

A: You can do it with no modulos and no branches, just a couple of shifts and subtractions.
int value = (c & 0x0F) + 9 - ((c&0x10)>>1) - ((c&0x10)>>4);

I just started from your formula, and used the fact that c&0x10 will be 0 for letters and 0x10 for 0-9.
Note that as is pointed out in comments, mod by a constant will optimized by compiler to multiplies and additions, but this should still be slightly better, since the compiler doesn't have the precondition that c is a hexadecimal digit.

A: If you have a fast multiply available:
int value = (c & 0x0f) + 9 * (c >> 6)

A: (d & 0xf) + ((d & 0x40) >> 3) + ((d & 0x40) >> 6)

Very straightforward bit fiddling.
Demo
A slightly different variant
(d & 0xf) + (d >> 6) + ((d >> 6) << 3)

saves another bitwise and operation.
Both variants basically multiply the 6th bit by 9 (same as in the Mark Ransom's answer but without hardware multiplication).

A: I'm late to the party but Daniel Lemire benchmarked several versions and came to the conclusion that using a simple lookup table was twice as fast as "fancy mathematical function". Copy-pasting from his article:
uint32_t hex_to_u32_lookup(const uint8_t *src) {
  uint32_t v1 = digittoval[src[0]];
  uint32_t v2 = digittoval[src[1]];
  uint32_t v3 = digittoval[src[2]];
  uint32_t v4 = digittoval[src[3]];
  return v1 << 12 | v2 << 8 | v3 << 4 | v4;
}

where digittoval "is a 256-byte array where 48 (or '0') is mapped to 0, 65 (or 'A') is mapped to 10 and so forth".


text:
Q: CakePHP 3 - Use SQL function in select() by default in table object I am setting up a system for a database with some POINT columns. I used the cookbook example to build a custom type and it seems to be working. However, to process the POINTs I need to SELECT them in a special way:
SELECT ST_AsText(location) as location ...

This isn't hard with the query builder:
$this->Houses->find()->select(['location' => 'ST_AsText(location)'])

However, I would prefer to have this happen by default.
I was thinking of using the beforeFind event, but I cannot find the right functions for the following pseudo-code:
public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
{
    if 'location' in query->getSelectedFields():
         replace 'location' by 'location' => 'ST_AsText(location)'
}

How can I have a field be replaced by a function when it is going to be included? Ideally even when I haven't called ->select(...) yet from a controller.
Older comparable question on CakePHP discourse: https://discourse.cakephp.org/t/read-data-from-spatial-mysql-field-point-polygon/2124

A: Found my solution in CakePHP 3.5 Always apply asText() MySQL function to Spatial field.
This works well for CakePHP 3.8. I decided to put the event handling inside a behavior to make it easy to reuse:
<?php
// src/Model/Behavior/SpatialBehavior.php

namespace App\Model\Behavior;

use Cake\ORM\Behavior;
use Cake\ORM\Table;
use Cake\Event\Event;
use ArrayObject;
use Cake\ORM\Query;

/**
 * Spatial behavior
 *
 * Make sure spatial columns are loaded as text when needed.
 *
 * @property \Cake\ORM\Table $_table
 */
class SpatialBehavior extends Behavior
{

    /**
     * Default configuration.
     *
     * @var array
     */
    protected $_defaultConfig = [];

    /**
     * Callback before each find is executed
     *
     * @param Event $event
     * @param Query $query
     * @param ArrayObject $options
     * @param type $primary
     */
    public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
    {
        $query->traverse(function (&$value) use ($query)
        {
            if (is_array($value) && empty($value))
            {
                // Built up standard query when ->select() was never used
                //$query->all(); // Execute query to learn columns
                $query->select($this->_table);
            }

            $defaultTypes = $query->getDefaultTypes();

            foreach ($value as $key => $field)
            {
                if (in_array($defaultTypes[$field], ['point', 'polygon']))
                {
                    $value[$key] = $query->func()->ST_AsText([
                        $this->_table->aliasField($field) => 'identifier'
                    ]);
                }
            }

            $query->select($value);
        }, ['select']);
    }

}

In my table object:
class HousesTable extends Table
{
    public function initialize(array $config)
    {
        //...
        $this->addBehavior('Spatial');
        //...
    }


text:
Q: Kafka kstream left join with Ktable, but stream not always joinASAP I have below simulation
Source topic A
from source topic A --> use same applicationID, generate two new stream Topic B, C
Create another applicationID
Use Topic B -> generate KTableBuild from B
Topic C left join with KTableBuildFrom B -> create streamFinal
Now My streamFinal are same count as Topic C, which is correct, But the value from Ktable, sometime is not correct. It sometime update the value later than Topic C event timestamp.
currently running one instance, and the Ktable creation and join has same application ID
Since I only has one partition, I enable the thread = 2, since I have Ktable generation and stream join with Ktable
By my understanding, stream will never update value from Ktable, if the timestamp in katble is later than the event from left side stream
kafkastream version 2.8
Thank you
Crystal
Thank you


text:
Q: PHP Any ideas for check ip address with same host in wifi i tried to search , how to find local ip, is worked when i use
$IP = $_SERVER['REMOTE_ADDR'];

$computerName = gethostbyaddr($IP);
it display my host ip address, im using wifi in home, when my PC and other PC , and mobile is display same each other.
and. it possible how to check or detect the different pc with other pc in the same connection (wireless or lan)?

A: When multiple devices access the Internet through a router that implements NAT (as is typical for most home Internet usage), there is no way for servers on the Internet to get any IP address other then the routers Internet facing address.


text:
Q: Loading"Gruntfile.js"tasks...ERROR 'use strict';

module.exports = function (grunt) {
require('load-grunt-tasks')(grunt);

require('time-grunt')(grunt);

var config = {
    app:'app',
    dist:'dist'
}

grunt.initConfig({
    config: config,

    copy: {
        dist_html: {
            src:'<%= config.app %>/index.html',
            dest:'<%= config.dist %>/index.html'
        },
        dist_js: {
            src:'<%= config.app %>/js/index.js',
            dest:'<%= config.dist %>/js/index.js'
        }
    },

    clean: {
        dist: {
            src: '<%= config.dist %>/index.html'
        }
    }
});}}

cmd picture
I input "grunt copy"in cmd,but it error.I started to learn grunt soon,How can I solve this problem?I need help,thinks.

A: You need to register the task to be able to use it in cmd.
For example:
grunt.registerTask(taskName, [description, ] taskFunction)

A: you only have configured what pathes to use you should create a task like so:
grunt.task({
 // Do Stuff here
})

There is more information on grunt tasks here:
http://gruntjs.com/api/grunt.task


text:
Q: Lambda mapping column to uppercase I have a code that uses the python lambda function to convert to uppercase.
df['NAME'] = map(lambda x: x.upper(), df['NAME'])

But i keep encountering the error
AttributeError: 'int' object has no attribute 'upper'

which could be due to some names having integers in it so i tried putting in a if condition
df['NAME'] = map(lambda x: x.upper() if x.isalpha(), df['NAME'])

But it doesn't work and prompts me with
SyntaxError: invalid syntax

Any idea how to solve this?


text:
Q: How do i prove that $C_c(X)$ is a vector space? Let $X$ be a topological space and $C_c(X)$ be the set of all continuous complex functions on $X$ whose support is compact.
Let $f,g\in C_c(X)$.
Trivially, $f+g$ are continuous, but how do i prove that supp$(f+g)$ is compact?

A: And to say why the inclusion holds, just note that if $f(x) = 0$ and $g(x) = 0$ then $(f+g)(x) = 0$.

A: It is contained in $\operatorname{supp}(f)\cup\operatorname{supp}(g)$.

A: Let me complete this answer. I will give the proof for real functions. First, let us recall the definition of support.
Given $\phi:X\subset \mathbb{R}^n\to \mathbb{R}$ a continuous function, the support of $\phi$, denoted by $\operatorname{supp} f$, is the closure (taken in $X$) of the subset of $X$ where f is non-zero, that is, if we write $S_\phi=\{x\in X;\ \phi(x)\neq 0\}$,
$$\operatorname{supp}\phi=\overline{S_\phi}\cap X,$$
where $\overline{S_\phi}$ is the closure taken in $\mathbb{R}^n$.

Given $f,g:X\to \mathbb{R}$, define $h=f+g$.
Claim 1: supp$(f+g)\subset$ supp$(f)$+supp$(g)$
Set $h=f+g$ and note that
$x\not\in S_f\cup S_g \Rightarrow x\not\in S_f$ and $x\not\in S_g \Rightarrow f(x)=0$ and $g(x)=0\Rightarrow h(x)=0\Rightarrow x\not\in S_h$. As a csonequence,
$S_h\subset S_f\cup S_g\Rightarrow$ supp$(h)=\overline{S_h}\cap X\subset (\overline{S_f}\cup\overline{S_g})\cap X= (\overline{S_f}\cap X)\cup(\overline{S_g}\cap X)=$supp$(f)\cup$supp$(g)$

Claim 2: If supp$(f)$ and supp$(g)$ are compact in $\mathbb{R}^n$, then supp$(h)$ is also compact.
It suffices to prove that given $(x_n)$ a sequence in supp$(h)$, there exists a convergente subsequence in supp$(h)$. Indeed, from Claim 1, $(x_n)$ is a sequence in $K=$supp$(f)\cup$ supp$(g)$ that is compact. Hence, there exists a subsequence $(x_{n_k})$ such that $x_{n_k}\to x$ in $K$. It remais to prove that $x\in$ supp$(h)$.
In fact, $x\in K=$supp$(f)\cup$ supp$(g)\subset X$. Since $x_{n_k}\in$ supp$(h)\subset \overline{S_h}$, we have that $x\in \overline{S_h}$. Hence,
$x\in  \overline{S_h}\cap X=$supp$(h)$, as required.

A: $\text{supp }(f+g) \subset \text{supp } f \cup \text{supp } g$.


text:
Q: Implementation for the read class for custom data type I'm trying to create a data type that I can transform into a string and back (for user input). I want a function that goes dataToText :: Colour -> String and the inverse function textToData :: String -> Colour. I came up with the following code to get this to work:
data Colour = Red | Blue | Green deriving (Eq, Read)
instance Show Colour where
    show Red = "R"
    show Blue = "B"
    show Green = "G"

When I run this in GHCi, show Red returns "R", exactly how I want 'dataToText' to work. However, when I run read "R" or read "R" :: Piece, I get the response *** Exception: Prelude.read: no parse.
I thought, but I am probably wrong, that with deriving the Read class, read will work by inverting my show function. Loading my code into GHCi doesn't give an error, so I guess some read functions must be created. I have been looking at al lot of information about read out there online, but I couldn't figure out how to do this basic read functionality. Often readPrec and readsPrec are mentioned, but I wasn't able to create a successful implementation using those. Could someone maybe explain how my example above should be implemented? I feel like I just am missing just a single (but fundamental) piece of the puzzle to understand how Read works.

A: Use -ddump-derive when deriving your instance
Prelude> data Colour = Red | Blue | Green deriving Read

==================== Derived instances ====================
Derived class instances:
  instance GHC.Read.Read Ghci3.Colour where
    GHC.Read.readPrec
      = GHC.Read.parens
          (GHC.Read.choose
             [("Red", GHC.Base.return Ghci3.Red),
              ("Blue", GHC.Base.return Ghci3.Blue),
              ("Green", GHC.Base.return Ghci3.Green)])
    GHC.Read.readList = GHC.Read.readListDefault
    GHC.Read.readListPrec = GHC.Read.readListPrecDefault

Derived type family instances:

==================== Filling in method body ====================
GHC.Read.Read [Ghci3.Colour]
  GHC.Read.readsPrec = GHC.Read.$dmreadsPrec @(Ghci3.Colour)

Then you can easily replace the strings
instance Read Colour where
  readPrec :: ReadPrec Colour
  readPrec = parens $
    choose
      [ ("R", pure Red)
      , ("B", pure Blue)
      , ("G", pure Green)
      ]


text:
Q: Google Apps Script Create form with file upload I'm in the process of creating a basic form that takes user input via text boxes and drop down list and upon submit will log into a spreadsheet. So far this works fine.  What I would like to add to the form is a "file upload" feature, that allows someone to select the file and upon submitting the form the file is uploaded as the data values from text boxes and drop downs are logged into the spreadsheet.  I've reviewed the following link https://developers.google.com/apps-script/class_fileupload but i'm having a hard time inserting / adding the example into the existing doGet function..  Anyone able to help or provide suggestions?  Here is the Google App Script code so far.
*used the following link to base the form on:  https://sites.google.com/site/appsscripttutorial/advanced-examples/insert-data-in-sheet-using-ui-forms
// Script-as-app template.
 var submissionSSKey = 'Spreadsheet Key goes Here';

 function doGet() {
   var app = UiApp.createApplication().setTitle('Loan Registration Processing');
   var panel = app.createVerticalPanel();
   var grid = app.createGrid(8,2).setId('loanGrid');
   var loanTypeLabel = app.createLabel('Loan Type');
   var loanList = app.createListBox().setName('Loan List').setWidth('120px').setName('LoanType');
   loanList.addItem('Select Option');
   loanList.addItem('FHA');
  loanList.addItem('Convential');
  loanList.addItem('VA');
  loanList.addItem('Reverse');
  loanList.addItem('HELOC');
   var borrowerNameLabel = app.createLabel("Borrower's Name");
   var borrowerTextbox = app.createTextBox().setWidth('150px').setName('borrower');
   var loanAmountLabel = app.createLabel('Loan Amount');
   var loanAmountTextbox = app.createTextBox().setWidth('150px').setName('amount');
   var appDateLabel = app.createLabel('Loan Date');
   var appDateTextbox = app.createTextBox().setWidth('150px').setName('date');
   var lienPostition = app.createLabel('Lien Position');
   var lienPos = app.createListBox().setName('Lien Position').setWidth('150px').setName('LienPosition');
  lienPos.addItem('Select Option');
  lienPos.addItem('1st');
  lienPos.addItem('2nd');
   var propertyType = app.createLabel('Property Type');
   var propType = app.createListBox().setName('Property Type').setWidth('150px').setName('PropertyType');
  propType.addItem('Select Option');
  propType.addItem('1-4');
  propType.addItem('Manufactured');
   var submitButton = app.createButton('Submit');

   //Grid layout of items on form
   grid.setWidget(0, 0, loanTypeLabel)
  .setWidget(0, 1, loanList)
  .setWidget(1, 0, borrowerNameLabel)
  .setWidget(1, 1, borrowerTextbox)
  .setWidget(2, 0, loanAmountLabel)
  .setWidget(2, 1, loanAmountTextbox)
  .setWidget(3, 0, appDateLabel)
  .setWidget(3, 1, appDateTextbox)
  .setWidget(4, 0, lienPostition)
  .setWidget(4, 1, lienPos)
  .setWidget(5, 0, propertyType)
  .setWidget(5, 1, propType)
  .setWidget(6, 0, submitButton)

   //Event Handler
   var handler = app.createServerClickHandler('insertInSS');
   handler.addCallbackElement(panel);
   submitButton.addClickHandler(handler);
   panel.add(grid);
   app.add(panel);
   return app;

 }
 //Function to insert data in the sheet on clicking the submit button
 function insertInSS(e){
   var app = UiApp.getActiveApplication();
   var LoanType = e.parameter.LoanType;
   var borrower = e.parameter.borrower;
   var amount = e.parameter.amount;
   var date = e.parameter.date;
   var LienPosition = e.parameter.LienPosition;
   var PropertyType = e.parameter.PropertyType;
   //app.getElementById('info').setVisible(true).setStyleAttribute('color','red');

   var sheet = SpreadsheetApp.openById(submissionSSKey).getActiveSheet();
   var lastRow = sheet.getLastRow();
   var targetRange = sheet.getRange(lastRow+1, 1, 1, 6).setValues([[LoanType,borrower,amount,date,LienPosition,PropertyType]]);
   return app;
 }

A: here is the code properly formatted :
// Script-as-app template.
var submissionSSKey = '*************';

function doGet(e) {
  var app = UiApp.createApplication().setTitle('Loan Registration Processing');
  var panel = app.createFormPanel();
  var grid = app.createGrid(8,2).setId('loanGrid');
  var loanTypeLabel = app.createLabel('Loan Type');
  var loanList = app.createListBox().setName('Loan List').setWidth('120px').setName('LoanType');
      loanList.addItem('Select Option');
      loanList.addItem('FHA');
      loanList.addItem('Convential');
      loanList.addItem('VA');
      loanList.addItem('Reverse');
      loanList.addItem('HELOC');
  var borrowerNameLabel = app.createLabel("Borrower's Name");
  var borrowerTextbox = app.createTextBox().setWidth('150px').setName('borrower');
  var loanAmountLabel = app.createLabel('Loan Amount');
  var loanAmountTextbox = app.createTextBox().setWidth('150px').setName('amount');
  var appDateLabel = app.createLabel('Loan Date');
  var appDateTextbox = app.createDateBox().setWidth('150px').setName('date');
  var lienPostition = app.createLabel('Lien Position');
  var lienPos = app.createListBox().setName('Lien Position').setWidth('150px').setName('LienPosition');
      lienPos.addItem('Select Option');
      lienPos.addItem('1st');
      lienPos.addItem('2nd');
  var propertyType = app.createLabel('Property Type');
  var propType = app.createListBox().setName('Property Type').setWidth('150px').setName('PropertyType');
      propType.addItem('Select Option');
      propType.addItem('1-4');
      propType.addItem('Manufactured');
  var submitButton = app.createSubmitButton('<B>Submit</B>');
  var warning = app.createHTML('<B>PLEASE WAIT WHILE DATA IS UPLOADING<B>').setStyleAttribute('background','yellow').setVisible(false)
  //file upload
  var upLoadTypeLabel = app.createLabel('File Upload');
  var upLoad = (app.createFileUpload().setName('thefile'));

  //Grid layout of items on form
  grid.setWidget(0, 0, loanTypeLabel)
      .setWidget(0, 1, loanList)
      .setWidget(1, 0, borrowerNameLabel)
      .setWidget(1, 1, borrowerTextbox)
      .setWidget(2, 0, loanAmountLabel)
      .setWidget(2, 1, loanAmountTextbox)
      .setWidget(3, 0, appDateLabel)
      .setWidget(3, 1, appDateTextbox)
      .setWidget(4, 0, lienPostition)
      .setWidget(4, 1, lienPos)
      .setWidget(5, 0, propertyType)
      .setWidget(5, 1, propType)
      .setWidget(6, 0, upLoadTypeLabel)
      .setWidget(6, 1, upLoad)
      .setWidget(7, 0, submitButton)
      .setWidget(7, 1, warning)

  var cliHandler = app.createClientHandler().forTargets(warning).setVisible(true)
  submitButton.addClickHandler(cliHandler);
  panel.add(grid);
  app.add(panel);
  return app;

}

 function doPost(e) {
  var app = UiApp.getActiveApplication();
  var LoanType = e.parameter.LoanType;
  var borrower = e.parameter.borrower;
  var amount = e.parameter.amount;
  var date = e.parameter.date;
  var LienPosition = e.parameter.LienPosition;
  var PropertyType = e.parameter.PropertyType;
  //app.getElementById('info').setVisible(true).setStyleAttribute('color','red');

  var sheet = SpreadsheetApp.openById(submissionSSKey).getActiveSheet();
  var lastRow = sheet.getLastRow();
  var targetRange = sheet.getRange(lastRow+1, 1, 1, 6).setValues([[LoanType,borrower,amount,date,LienPosition,PropertyType]]);
   // data returned is a blob for FileUpload widget
   var fileBlob = e.parameter.thefile;
   var doc = DocsList.createFile(fileBlob);
   return app
 }

A: You have to put you panel into a formPanel, use a submitButton  and get all your results in a single doPost function. No need to define a handler nor any callbackElement in this context so you should remove them to avoid conflicts.
If you look at the simple example you showed as reference you'll see the structure that has to be adopted for form submission. I know it works the way you did it too but not for file upload...
Here is you working code : I made a few changes... testable here

*

*changed the textBox for date into a dateBox

*added an client handler to show a warning while the file is uploading since this can take a while if the file is big ;-)

Sorry, the system is buggy, I cannot format the code properly, I'll make another answer...

A: I've figured out how to get the file upload to attach to the grid and display, allow file selection and submittal of data values to the spreadsheet.  It doesn't upload the select file to my drive.
I'm posting the updated code below.  Any thoughts on why its not posting the file to my drive??
// Script-as-app template.
var submissionSSKey = 'Spreadsheet Key';

function doGet(e) {
  var app = UiApp.createApp ication().setTitle('Loan Registration Processing');
  var panel = app.createVerticalPanel();
  var grid = app.createGrid(8,2).setId('loanGrid');
  var loanTypeLabel = app.createLabel('Loan Type');
  var loanList = app.createListBox().setName('Loan List').setWidth('120px').setName('LoanType');
      loanList.addItem('Select Option');
      loanList.addItem('FHA');
      loanList.addItem('Convential');
      loanList.addItem('VA');
      loanList.addItem('Reverse');
      loanList.addItem('HELOC');
  var borrowerNameLabel = app.createLabel("Borrower's Name");
  var borrowerTextbox = app.createTextBox().setWidth('150px').setName('borrower');
  var loanAmountLabel = app.createLabel('Loan Amount');
  var loanAmountTextbox = app.createTextBox().setWidth('150px').setName('amount');
  var appDateLabel = app.createLabel('Loan Date');
  var appDateTextbox = app.createTextBox().setWidth('150px').setName('date');
  var lienPostition = app.createLabel('Lien Position');
  var lienPos = app.createListBox().setName('Lien Position').setWidth('150px').setName('LienPosition');
      lienPos.addItem('Select Option');
      lienPos.addItem('1st');
      lienPos.addItem('2nd');
  var propertyType = app.createLabel('Property Type');
  var propType = app.createListBox().setName('Property Type').setWidth('150px').setName('PropertyType');
      propType.addItem('Select Option');
      propType.addItem('1-4');
      propType.addItem('Manufactured');
  var submitButton = app.createButton('Submit');

  //file upload
  var upLoadTypeLabel = app.createLabel('File Upload');
  var upLoad = (app.createFileUpload().setName('thefile'));

  //Grid layout of items on form
  grid.setWidget(0, 0, loanTypeLabel)
      .setWidget(0, 1, loanList)
      .setWidget(1, 0, borrowerNameLabel)
      .setWidget(1, 1, borrowerTextbox)
      .setWidget(2, 0, loanAmountLabel)
      .setWidget(2, 1, loanAmountTextbox)
      .setWidget(3, 0, appDateLabel)
      .setWidget(3, 1, appDateTextbox)
      .setWidget(4, 0, lienPostition)
      .setWidget(4, 1, lienPos)
      .setWidget(5, 0, propertyType)
      .setWidget(5, 1, propType)
      .setWidget(6, 0, upLoadTypeLabel)
      .setWidget(6, 1, upLoad)
      .setWidget(7, 0, submitButton)

  //Event Handler
  var handler = app.createServerClickHandler('insertInSS');
  handler.addCallbackElement(panel);
  submitButton.addClickHandler(handler);
  panel.add(grid);
  app.add(panel);
  return app;

}
//Function to insert data in the sheet on clicking the submit button
function insertInSS(e){
  var app = UiApp.getActiveApplication();
  var LoanType = e.parameter.LoanType;
  var borrower = e.parameter.borrower;
  var amount = e.parameter.amount;
  var date = e.parameter.date;
  var LienPosition = e.parameter.LienPosition;
  var PropertyType = e.parameter.PropertyType;
  //app.getElementById('info').setVisible(true).setStyleAttribute('color','red');

  var sheet = SpreadsheetApp.openById(submissionSSKey).getActiveSheet();
  var lastRow = sheet.getLastRow();
  var targetRange = sheet.getRange(lastRow+1, 1, 1, 6).setValues([[LoanType,borrower,amount,date,LienPosition,PropertyType]]);
  return app;
}

 function doPost(e) {
   // data returned is a blob for FileUpload widget
   var fileBlob = e.parameter.thefile;
   var doc = DocsList.createFile(fileBlob);
 }


text:
Q: Perform OR/AND operation on Bits argument I am tring to perform a BITOR on a argument that i am passing into a function. so i wrote the below code. Statement 'SET result = arg1 | arg2 ' isnt working. I tried few ways, however i wasnt able to achieve the right result. What do i need to change ?
DELIMITER $$
CREATE FUNCTION BIT_OR(arg1 varchar(255),arg2 varchar(255)) RETURNS varchar(255)
BEGIN
DECLARE result varchar(255);
BEGIN
SET result = arg1 | arg2;
END;
RETURN result;
END $$
DELIMITER ;

select bitwise_OR(00011101,00001111);  -- 12127 ( i am expecting 00011111 or 31 (decimal equivalent))


text:
Q: Create timeseries dataset for TensorFlow v2 I'm trying to feed a model CNN+LSTM with data from a csv. What I'm missing is setting a correct dataset to start training my model.
This is my test model:
def test_model():
    model = models.Sequential()
    model.add(TimeDistributed(Conv1D(32, 4, strides=1, activation='relu', padding="valid"), input_shape=[None, 6, 20]))
    model.add(TimeDistributed(MaxPooling1D(pool_size=2), input_shape=[None, 6, 20]))
    model.add(TimeDistributed(Conv1D(64, 4, strides=1, activation='relu', padding="valid"), input_shape=[None, 6, 20]))
    model.add(TimeDistributed(MaxPooling1D(pool_size=2), input_shape=[None, 6, 20]))
    model.add(TimeDistributed(Flatten(), input_shape=[None, 6, 20]))
    model.add(LSTM(100, activation='relu'))
    model.add(Dropout(0.2))
    model.add(Dense(100, activation="relu"))
    model.add(Dropout(0.4))
    model.add(Dense(5, activation="softmax"))
    model.compile(optimizer=keras.optimizers.Adam(1e-3), loss="binary_crossentropy", metrics=["accuracy"])
    return model

Here you can download test.csv
CSV dataset is made of 6 features + 1 multilabel. I need to create a time series each 20 row, so I think my shape should be [None, 6, 20] ordered by ascending timestamp value.
I'm new in TensorFlow and I don't know how to create an appropriate dataset from scratch, I was able to load a dataset from directory with images (for CNN) but in this scenario I really don't know how to do it.
This is what I tried to generate my dataset:
with open('test.csv') as csvfile:
    dataset = list()
    reader = csv.reader(csvfile, delimiter=',')
    next(reader)
    count = 0
    timeseries = list()
    labels = list()
    for row in reader:
        count = count + 1
        if count <= 20:
            timeseries.append(
                [float(row[0]), float(row[1]), float(row[2]), float(row[3]), float(row[4]), float(row[5])])
        else:
            dataset.append(timeseries)
            labels.append(int(row[6].split("L")[-1]))
            timeseries = list()
            count = 0

After that I transformed it in a tf.DataSet like this:
dataset = tf.data.Dataset.from_tensor_slices(dataset)
labels = tf.data.Dataset.from_tensor_slices(labels)

Here I got a <TensorSliceDataset shapes: (20, 6), types: tf.float32> like I want. Then I fed a K-Fold with it:
estimator = KerasClassifier(build_fn=test_model, epochs=60, batch_size=5, verbose=0)
kfold = KFold(n_splits=10, shuffle=True)
results = cross_val_score(estimator, dataset, labels, cv=kfold)

When running cross_val_score I got this error:

TypeError: Singleton array array(<TensorSliceDataset shapes: (20, 6), types: tf.float32>, dtype=object) cannot be considered a valid collection.

What I'm missing?


text:
Q: How to changing menu item text? When a user hit the "register" menu item it come to the register activity and after hit the button to return to the MainActivity with the menu item from "register" to "unregister" I don't know how would I go about changing the menu item text.
public class register extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        Button register = findViewById(R.id.reg);
        EditText name =findViewById(R.id.name);
        EditText admin = findViewById(R.id.admin);
        EditText email = findViewById(R.id.email);

        register.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                startActivity(new Intent(register.this,MainActivity.class));
            }
        });
    }

A: You can do it with onPrepareOptionsMenu:
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem btn = menu.findItem(R.id.register_menu_item);
    if (/* here check if user is registered or not */) {
        btn.setTitle("Unregister");
    } else {
        btn.setTitle("Register");
    }
    return super.onPrepareOptionsMenu(menu);
}


text:
Q: What standard MCPH3 package belong to? When i go through a diode datasheet, i saw that the device's package is MCPH3 and bellow that i found SC-70 (JEITA), SOT-323 (JEDEC). Can anyone help me to find out the details about MCPH3. Thank you.

A: The MCPH3 package nomenclature is an OnSemi name for the SC-70 package standard:

The package specification document provides the above diagram.

A: Given that every reference to MCPH3 as a semiconductor package is in reference to an ON Semiconductor device, I am going to say that the designation is not controlled by any standards body and is instead only used by ON Semiconductor.


text:
Q: Center Content of v-container on Mobile while using Fill-Height Property in Vuetify I've been struggling with an issue for a while now and I was hoping that a fix would be released and the issue would resolve itself. It did not unfortunately. I have this basic code in my App.vue that is using vuetify elements:
<template>
  <v-app class="app" id="inspire">
    <v-content>
      <v-container class="fill-height" fluid>
        <v-row align="center" justify="center">
          <v-col class="text-center">
            <v-card outlined>
              Source
            </v-card>
          </v-col>
        </v-row>
      </v-container>
    </v-content>
  </v-app>
</template>

This looks fine. However, when I scale down to a mobile device, the v-card is not centered, but pushed to the left. See image below. When I remove the fill-height property on the container, everything looks correctly, but I would like to center the v-card vertically on my page. Is this a Vuetify issue? I could not find this exact issue described anywhere else. Is there maybe something wrong in my setup?

Thanks in advance!
Jeroen

A: The margin-right: -12px and margin-left: -12px that come from the .container.fill-height > .row element are causing the issue. Doesn't seem that they are aware otherwise they would add margin: auto of some kind to resolve it. Hope that helps.


text:
Q: Navbar position I am currently working on building my photography portfolio site.
I try to position my navbar under my logo, but I can't match the navbar to the size and the postion of the logo.
any idea how can I position my  nav using CSS?

Thanks

A: Quick fix. Hero is de flexbox

header {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.logo,
nav {
  width: inherit;
  text-align: center;
}

ul {
  list-style: none;
  width: inherit;
  display: flex;
  justify-content: space-between;
}

Home

About

Portfolio

Contact


text:
Q: VB - Get Visual Studios 2010 to stop recommending VB6 code This is something that annoys me to no end, whenever I have to convert something to a value (for example,lets say I have to convert something to a boolean) visual studios will give you their advice of CBool, which works, but that's VB6 and I do not want that.
I tried looking everywhere, but no luck, does anyone know how I can get Visual Studio to stop suggesting VB 6 solutions and instead suggest .NET solutions (like use convert.ToBoolean)?
If you know of a plugin that does it, I'm open to that as well.
Thank Guys.

A: The CBool() operator and it's companions (even CType) are not VB6.  They are operators rather than functions, and still very much a part of modern VB.Net.  The have syntax that resembles code from the old vb6 style, which is unfortunate, but aside from that there is nothing wrong from them.
The alternative of Convert.ToBoolean(), on the other hand, is a function.  The difference is that Convert.ToBoolean() can convert a much larger range of values, at the cost of drastically reduced performance, while CBool can only cast something that already is (or very nearly already is) a boolean and maybe just doesn't have the exact type match that you need.
The trick here is contrasting casting operators like CBool() with VB6-era functions, like Len(), Trim(), DateAdd(), Ubound(), etc.  The latter should definitely be avoided in favor of a more modern style.


text:
Q: Decrement oracle sequence when an exception occurred I try to insert a new record in my database using pl/sql, so first of all I generate a new sequence like so:
select my_seq.nextval into seqId from dual;

And then i try to insert a new record using the generated seqId like this :
insert into myTable (id) values seqId ;

But when an error occurred during the insertion I want to decrement my sequence in an exception block. Does anyone have an idea please?

A: You can not decrement after the sequence is incremented (A sequence is either incremented or decremented not both) or reinitialize the sequence (start with ...) in Oracle. There is no way of doing that. Hope this helps.
However, if you want to continue this absurdity you can try this but you need to initialize your sequence first which is myseq.nextval;
then you can first try to insert currval and if succeeds then you can increment your sequence otherwise sequence will have its previous value.
Declare
currval pls_integer;
inc pls_integer;
Begin

select seq.currval into currval from dual;

insert into myTable (id) values (currval) ;
select seq.nextval into inc from dual;

Exception
when others then
do the exception handling;
end;

A: As you were already told, you shouldn't be doing this at all. Anyway, here's how you might do it.
Sample table and a sequence:
SQL> create table mytable (id number primary key);

Table created.

SQL> create sequence seq;

Sequence created.

SQL> set serveroutput on

Procedure which inserts seq.nextval into mytable and decrements the sequence in a case of a failure. I'm doing it in a simplest way - dropping it and recreating with the start parameter set to the last fetched value minus 1. DBMS_OUTPUT calls are here just to show what's going on in the procedure.
SQL> create or replace procedure p_test as
  2    seqid number;
  3  begin
  4    seqid := seq.nextval;
  5    dbms_output.put_line('Sequence number to be inserted = ' || seqid);
  6
  7    insert into mytable(id) values (seqid);
  8
  9  exception
 10    when others then
 11      dbms_output.put_line(sqlerrm);
 12      execute immediate 'drop sequence seq';
 13      execute immediate 'create sequence seq start with ' || to_char(seqid - 1);
 14  end;
 15  /

Procedure created.

Let's test it: this should insert 1:
SQL> exec p_test;
Sequence number to be inserted = 1

PL/SQL procedure successfully completed.

SQL> select * from mytable;

        ID
----------
         1

So far so good. Now, I'll manually insert ID = 2 so that the next procedure call violates unique constraint:
SQL> insert into mytable values (2);

1 row created.

Calling the procedure again:
SQL> exec p_test;
Sequence number to be inserted = 2
ORA-00001: unique constraint (SCOTT.SYS_C007547) violated

PL/SQL procedure successfully completed.

OK; procedure silently completed. It didn't insert anything, but it decremented the sequence:
SQL> select * from mytable;

        ID
----------
         1        --> populated with the first P_TEST call
         2        --> populated manually

SQL> select seq.nextval from dual;

   NEXTVAL
----------
         1        --> sequence is decremented from 2 to 1

If I delete the offending ID = 2 and try again:
SQL> delete from mytable where id = 2;

1 row deleted.

SQL> exec p_test;
Sequence number to be inserted = 2

PL/SQL procedure successfully completed.

SQL> select * from mytable;

        ID
----------
         1
         2

SQL> select seq.nextval from dual;

   NEXTVAL
----------
         3

SQL>

Right; kind of works, but it's not worth the pain.
Besides, as you commented that there are 20 rows in a table. What will you do if someone deletes row #13. Will you decrement all values between #14 and 20? What if that's a primary key, referenced by some foreign keys?
Seriously, don't do it.


text:
Q: Why I cannot include AppKit in pure C, even though I can declare the functions myself? I would like to write a MacOS application using more C and less ObjC and Swift. I started by creating a main.c file with the main function. Next is to call NSApplicationMain from the main function. This is defined in AppKit. However, I get a Could not build module 'AppKit' error when I try #include <AppKit/AppKit.h> from main.c. I circumvented this with:
extern int NSApplicationMain(int argc, const char * _Nonnull *argv);

This worked. My question is, clearly NSApplicationMain can be called from C so why do I have to extern it directly instead of including AppKit.h directly? Why they do not let you include it the proper way instead of declaring NSApplicationMain yourself? Am I not supposed to do that?
Why can you not do this:
#include <stdio.h>
#include <AppKit/AppKit.h>
int main(int argc, const char *argv[]) {
    return NSApplicationMain(argc, argv);
}

But you can do this:
#include <stdio.h>
extern int NSApplicationMain(int argc, const char * _Nonnull *argv);
int main(int argc, const char *argv[]) {
    return NSApplicationMain(argc, argv);
}

A: In short, it is not standard C header file though it has .h extension. Note, that even in Objective-C .m files AppKit.h must be imported not included
#import <AppKit/AppKit.h>

A: I'm not an authority on this, but my take would be: AppKit is an Objective-C framework.  It therefore has a header file that is written in Objective-C, and that can't be included in C.  When you declare an AppKit function in C and call it, you are basically relying on the fact that the ABI – the internal calling conventions of registers, stack usage, etc. – are the same between both languages, and so it works (and I'm not actually certain that the ABI is 100% the same, although I think it is); but technically, you are calling an Objective-C function from C.  There's no particular reason why Apple ought to bend over backwards to make that easy; programming in pure C is not common any more.  If you really want to do this, you could always just make your C source file be a .m (Objective-C) file but limit yourself to only pure C language features.  That will let you include the header, while letting you write "C" code (actually Objective-C, limited to the C subset of the language).  Seems like a good solution to me.


text:
Q: Server not responding for some request I am having problem in some request access, in my web application. I am not able to figure out the issue.
In my we application servlet mapping configuration is like this..
 <servlet>
     <servlet-name>default</servlet-name>
     <servlet-class>org.eclipse.jetty.servlet.DefaultServlet</servlet-class>
     <load-on-startup>0</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

and the spring configuration for dispatcher servlet is like this.
In WebApplicationInitializerConfig
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
        dispatcherContext.register(DispatcherConfig.class);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherContext);
        ServletRegistration.Dynamic dispatcher;

        dispatcher = servletContext.addServlet("api/", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);

        String apiMappingPath = /api/*;

        dispatcher.addMapping(apiMappingPath);

When I make some API request, the call goes to the method and method sout also print in server log.But no response comes out.
For information I am deploying the application on glassfish server.
I am not able to get the issue reason also. If any one knows then help me out.
Method code:
 @RequestMapping(value = "/email", method = RequestMethod.POST)
    public Map passwordResetMail(@RequestBody(required = false) String email, HttpServletRequest request, HttpServletResponse response) {

        system.out.println("email"+email);
            Map map = new HashMap();
           map.put("email",email);
          return map;
}


text:
Q: EnterpriseLibrary I have configured logging to be done in a rolling log file and event log. However, what happens is if one fails, the second one don't succeed either. Is there a way I can configure EntLib to try both before failing?

A: The logic on processing the Trace Listeners is deep within the implementation of Enterprise Library so there is no built-in way to configure.
One alternative is to download the source code and make the changes that you want, rebuild and use that custom version of Enterprise Library.
Another approach would be to use Unity to inject custom code to add the additional logic to process multiple trace listeners if an error occurs.  You'll have to recreate much of the Enterprise Library logic but you wouldn't have to directly modify Enterprise Library source.  You can find the full details for the latter approach at http://randylevy.wordpress.com/2012/04/04/enterprise-library-logging-extensions-part-2/.

A: The logging block detects failures based on category, not trace listener. So if one trace listener in a category fails, none of the trace listeners in that category will run from that point on.
Your best bet here is to split the two listeners out into separate categories.


text:
Q: border-radius: 50% for rounded image crossed out in console I'm following standard procedures for creating a round image in ReactJS.
.about-profile {
    display: block;
    width: 260px;
    height: 260px;
    border-radius: 50%;
}

<img className="about-profile" src="./images/profile.jpg"/>

Why is border-radius: 50% not being applied in this case?

A: That's the cascade in CSS in effect. Some other rule is overriding your border radius.
For more details see https://www.w3.org/TR/2011/REC-CSS2-20110607/cascade.html#cascade
What you can do is either change .about-profile to be more "specific", or use !important to override the other rules. I suggest the former.

A: You can use this:
border-radius: 50%!important;

A: some style override this code so use !important
.about-profile {
  display: block;
  width: 260px;
  height: 260px;
  border-radius: 50%;
}


text:
Q: MFMessageComposeViewController shows an black screen I'm using the following code to send in-app sms.
NSString *message = @"this ia the message";
MFMessageComposeViewController *TextSheet = ([MFMessageComposeViewController alloc]);
TextSheet.messageComposeDelegate = self;
[TextSheet setBody:message];
TextSheet.recipients = [NSArray arrayWithObjects:@"0549999999", @"0548888888", nil];
[self presentViewController:TextSheet animated:YES completion:Nil];

I try it on a real device iPhone 5C with IOS 7 and its shows a black
screen only. What am I doing wrong?

A: You have a couple of issues in your code - most importantly, you're not initializing your MFMessageComposeViewController correctly. You need to call alloc and init.
MFMessageComposeViewController *textSheet = [[MFMessageComposeViewController alloc] init];

You could also tidy up your recipients list by using a literal array:
textSheet.recipients = @[ @"0549999999", @"0548888888" ];

Finally, your nil that you're passing for the completion block should not be capitalized:
[self presentViewController:textSheet animated:YES completion:nil];


text:
Q: Is it possible to Implement Azure Ad Authentication in webforms without cookie authentication type? the below is working code.
But I need to implement the solution without sing coockies (UseCookieAuthentication).
After Azure authentication, when we check the AuthenticationTyoe in Identity it shown as Cookies, which i need to avoid. any suggetions/other implementations
public void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Sets the ClientId, authority, RedirectUri as obtained from web.config
            ClientId = clientId,
            Authority = authority,
            RedirectUri = redirectUri,
            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
            PostLogoutRedirectUri = redirectUri,
            Scope = OpenIdConnectScope.OpenIdProfile,
            // ResponseType is set to request the code id_token - which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.CodeIdToken,
            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed
            }
        }
    );
    }


text:
Q: What's a word for "annoyingly posh"? Example:

We were escorted into the old country club, and I made an instant grimace over how ______ the ambiance was."

A:
We were escorted into the old country club, and I made an instant grimace over how
hoity-toity the ambiance was.

Hoity-toity is synonymous with snobby, both terms  are related to posh and are derogative, so while a posh restaurant could be a compliment, and implies that is quite expensive to eat there; a hoity-toity restaurant will suggest it is run by a snobbish (or pretentious) management.

Hoity-toity
  Haughty; snobbish:

*

*the moneyed, hoity-toity inhabitants of the island

*They see people in the country as hoity-toity but nothing could be further from the truth,' he said as we pulled into the driveway of his fifteenth-century home, Kilhenzie Castle.

A: Have a look at
http://www.oxforddictionaries.com/us/definition/american_english/ostentatious
It can be used in proper context to deliver the intended meaning.


text:
Q: Teen Book with Two Boys Transported to Future I am searching for a book I read as a young boy (1980's to early '90s). I don't really recall many key facts other than I think it was either one boy or two brothers, from possibly war time, being transported to the future where they attend a school. At lunch they scan their wrists to pay, and the time projects on their wrist. One of them had a taste for a dessert that, when you peeled the lid back, turned into a spoon to eat it with.

A: Per sq33G's earlier comment, the book you're describing is almost certainly "A Tale of Time City" by Diane Wynne Jones;

Pots that have lids that turn into spoons;

The pots, Vivian found, were sort of stuck to the air. She had to give
  a little pull to get them loose. She discovered that you peeled back
  the lid, and if you needed a spoon or a fork, the lid shrivelled itself
  into a spoon or fork shape. Algae soup was not at all pleasant, like
  salty pond water

Paying by scanning their wrists

"I'm paying," said Jonathan, and recited a string of numbers. "Yes, but are you in credit?" said the waitress. "Show." Jonathan pressed
  one of the buttons on his belt and held his hand out with a row of
  signs shining on his palm. The waitress looked, nodded, and pressed
  buttons on the pink matching belt round her pajamas

There's a complete (and I assume copyright friendly) version available online here.


text:
Q: Finding the radical of an integer
Given a number $x = p_1^{e_1}\cdots p_n^{e_n}$ with different primes $p_i$ and exponents $e_i \ge 1$, is there an efficient way to find $p_1\cdots p_n$?

I ask this because for polynomials it's easy: with $K$ a field of characteristic $0$ and $$f = g_1^{e_1} \cdots g_n^{e_n} \in K[X]$$ irreducible we have $$g_1 \cdots g_n = \frac{f}{\mathrm{gcd}(f,f\,')}$$ where $f\,'$ is the formal derivative.
This proof can't be used for integers, unless there's a trick that I don't see.

A: Currently, no feasible (polynomial time) algorithm is known for
recognizing squarefree integers or for computing the squarefree
part of an integer. In fact it may be the case that this problem
is no easier than the general problem of integer factorization.
Computing the radical $\rm\:rad(n)\:$ is equivalent to computing the squarefree part $\rm\:sf(n)\:$ because
$$\rm rad(n)\, =\, sf(n)\, sf(n/rad(n)) $$
This problem is important because one of the main tasks
of computational algebraic number theory reduces to it (in
deterministic polynomial time). Namely the problem of computing
the ring of integers of an algebraic number field depends upon
the square-free decomposition of a polynomial discriminant
when computing an integral basis, e.g. [2] S.7.3 p.429 or [1]
This is due to Chistov [0]. See also Problems 7,8, p.9 in [3],
which lists 36 open problems in number theoretic complexity.
The primary reason that such problems are simpler in function fields versus number fields
is due to the availability of derivatives. This opens up a powerful
toolbox that is not available in the number field case. For example
once derivatives are available so are Wronskians - which provide powerful
measures of dependence in transcendence theory and diophantine approximation.
A simple yet stunning example is the elementary proof of the polynomial case of Mason's ABC theorem, which yields as a very special case a high-school-level proof of FLT for polynomials, cf.
my  MO post and my old sci.math post [4].
Such observations have motivated searches for "arithmetic analogues of derivations". For example, see Buium's paper by that name in Jnl. Algebra, 198, 1997, 290-99, and see his book  Arithmetic differential equations.
[0] A. L. Chistov. The complexity of constructing the ring of integers
of a global field. Dokl. Akad. Nauk. SSSR, 306:1063--1067, 1989.
English Translation: Soviet Math. Dokl., 39:597--600, 1989. 90g:11170
http://citeseerx.ist.psu.edu/showciting?cid=854849
[1] Lenstra, H. W., Jr.  Algorithms in algebraic number theory.
Bull. Amer. Math. Soc. (N.S.) 26 (1992), no. 2, 211--244.  93g:11131
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.105.8382
[2] Pohst, M.; Zassenhaus, H.  Algorithmic algebraic number theory.
Cambridge University Press, Cambridge, 1997.
[3] Adleman, Leonard M.; McCurley, Kevin S.
Open problems in number-theoretic complexity. II.
Algorithmic number theory (Ithaca, NY, 1994), 291--322,
Lecture Notes in Comput. Sci., 877, Springer, Berlin, 1994. 95m:11142
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.48.4877
[4] Dubuque, Bill. $ $ sci.math.research post, 1996/07/17
poly FLT, abc theorem, Wronskian formalism [was: Entire solutions of f^2+g^2=1]
http://groups.google.com/group/sci.math/msg/4a53c1e94f1705ed
http://groups.google.com/groups?selm=WGD.96Jul17041312@berne.ai.mit.edu


text:
Q: C# Read Javascript Location Response Im trying to read a javascript response on my proyect, but im getting the HTML of the page without executing the javascript, here is my code:
  string Url = "MY URL";

  var webRequest = WebRequest.Create(Url);

  using (var response = webRequest.GetResponse())
  using (var content = response.GetResponseStream())
  using (var reader = new StreamReader(content))
  {
    var strContent = reader.ReadToEnd();
  }

In the StrContent im getting the HTML code of the page but no Javascript response, this is what im getting:

i want to read the Longitude and Latitude in my proyect


text:
Q: SQL hashbytes update statement not as expected I'm trying to update a column on SQL server r2 using the hashbytes command. Here's the simplified version of the command:
COMMAND: "UPDATE [tbl] SET [checksum] = HASHBYTES('MD5',[field1])"

The problem is that, it writes strange characters like this to all the fields:
"˜Iý¸¶C"KéS©c"
However, if I do a select (using the same fields):
select HASHBYTES('MD5',[field1]) from [tbl];

It returns a correct string:
0x9849FDB80C17B64322DA094BE963A963

Anyone know why it would do this. I've tried on a test database and the update command works as expected. But it doesn't work on our production server.

A: The reason you are getting this is because HASHBYTES returns a binary data type, and this is not text.
Using the build in function fn_varbintohexstr you can convert the binary data into text, as follows:
UPDATE [tbl] SET [checksum] = master.dbo.fn_varbintohexstr(HASHBYTES('MD5',[field1]))


text:
Q: .vimrc for C developers There is a question How to set .vimrc for c programs?, but nothing especially interesting in there.
By what .vimrc options do you facilitate your C development in Linux? (e.g. for building, ctags, tabs...) Any ideas welcome, especially for "external building with make".

A: how about this?
https://mislav.net/2011/12/vim-revisited/
set nocompatible                " choose no compatibility with legacy vi
syntax enable
set encoding=utf-8
set showcmd                     " display incomplete commands
filetype plugin indent on       " load file type plugins + indentation

"" Whitespace
set nowrap                      " don't wrap lines
set tabstop=2 shiftwidth=2      " a tab is two spaces (or set this to 4)
set expandtab                   " use spaces, not tabs (optional)
set backspace=indent,eol,start  " backspace through everything in insert mode

"" Searching
set hlsearch                    " highlight matches
set incsearch                   " incremental searching
set ignorecase                  " searches are case insensitive...
set smartcase                   " ... unless they contain at least one capital letter

A: https://github.com/jslim89/dotfiles
This is my repo. Inside already got a few type of vim plugins including c.vim, ctags, autocomplete, etc.

A: Along with options in plan9assembler's answer,
Run make from inside vim, you can just use :make but that won't automatically open the quickfix window with you're errors. To get that to happen, add a second :Make command [1]:
command! -nargs=* Make write | make! <args> | cwindow

Another thing I have is a recursive search for my ctags file. The following will use the tags file in the current directory, then search one directory above recursively till it finds a tag file [2]:
set tags=./tags;


text:
Q: Bing Custom Search Engine What parameters should I use in order to get search result from only a site say abcd.com using bing 2.0 API? I am trying to fetch results in JSON format. Can anybody help?

A: fresh code to the masses
            $query = array
        (
            'AppId' => <API_KEY>,
            'sources' => 'Web',
            'query' => 'site:www.tipografix.ro '.$keywords,
            'Version' => '2.0',
            'Options' => 'EnableHighlighting',
            'Web.Count' => $per_page,
            'Web.Offset' => $page_num,
            'Web.Options' => 'DisableHostCollapsing DisableQueryAlterations'
        );

        $request = 'http://api.bing.net/json.aspx?'.http_build_query($query);

        $response  = file_get_contents($request);
        $jsonobj  = json_decode($response);

A: Not sure how the JSON format of the API works but in the query parameter put in "site:abcd.com bacon" where bacon is your original query.
I'm using the XML format so if I'd send a request to:
http://api.search.live.net/xml.aspx?Appid=________&query=site%3Aabcd.com+bacon&sources=web&web.count=5&web.offset=0


text:
Q: Possible Deadlock on Calling FreeLibrary I have to write a DLL in Delphi XE7. I want to use TParallel.For in the DLL. The DLL is loaded into a C++ application, where everything works. However, when the application terminates, or a call to FreeLibrary is made, the application hangs. If I remove all the TParallel.For loops and replace them with standard loops, the application exits normally.
The TParallel.For loops are very simple:
TParallel.For(0, inImage.Height -1,
  Procedure(ty : integer)
  begin
    SomeProcedure(ty);
  end);

If I create a Delphi application with exactly the same code, everything works perfectly.
After doing a lot of research and debugging, it looks like there is a deadlock which is preventing the C++ application from exiting when FreeLibrary is called, but I can't find where the problem is in TParallel.
Just to summarise the situation:

*

*The TParallel.For loops all complete and produce the correct results.

*The exact same TParallel.For code in a Delphi .exe works correctly.

*The DLL is loaded and the functions are called and perform correctly from within the C++ application.

*The C++ application will exit correctly if there are no TParallel.For loops.

*The C++ application will hang if there are TParallel.For loops.

*I am guessing that there is a deadlock which occurs when FreeLibrary is called.

*If I use the OTL threading library, everything works as it should.

My questions are:
Has anyone else experienced this behaviour?
What is a good debugging strategy to find a deadlock in this situation?
Any advice is greatly appreciated.
UPDATE
OK, so if you want Minimal, Complete and Verifiable example, here you go (thank you Stephen Ball):
library ADelphiDLL;

uses
  System.SysUtils, System.Classes, Threading, SyncObjs;

function IsPrime (N: Integer): Boolean;
var
 Test: Integer;
begin
 IsPrime := True;
 for Test := 2 to N - 1 do
   if (N mod Test) = 0 then
   begin
     IsPrime := False;
     break; {jump out of the for loop}
   end;
end;

function Prime(Max : integer) : boolean;
var
  tot : integer;
begin
   tot := 0;
   TParallel.For(1, Max, procedure (I: Integer)
    begin
      if IsPrime (I) then
        TInterlocked.Increment (Tot);
    end);
   return true;
   end;

exports Prime;

begin
   IsMultiThread := True;
end.

in C++:
#include "stdafx.h"

typedef bool(__stdcall *primesf)(int);

void main()
{
HINSTANCE hGetDLL = LoadLibrary(L"ADelphiDLL.dll");
primesf primes = (primesf)GetProcAddress(hGetProcIDDLL, "Primes");
bool result = primes(100);
FreeLibrary(hGetDLL);// <-- Hangs here forever
}

In response to the very "helpful" comments, "there is a defect in the code " and "debug it yourself", thank you, that is what I have been doing for a too long a time. So, if there is no help forthcoming here, I will try and get permission to switch to OTL, which does work in the DLL in question.
UPDATE 2
OTL works exactly as expected. So, yes, there is a "defect in the code". I give up. I will recommend abandoning Delphi altogether and then we can move everything over to C++ and C#. That has to be a much better short (and long term) solution.

A: I have seen an issue similar to this, although i was using Delphi 10.0 Seattle, and a Delphi EXE loading a Delphi DLL.
Anyway, the solution that I came up with is the following:

*

*In your Delphi DLL, first create your own thread pool.

*Use the overloaded version of TParallel.For that takes a thread pool object as its last parameter, and provide your own thread pool object.

*Before unloading your Delphi DLL, make sure to free your thread pool object.
This approach solved the problem for me.
TParallel.For documentation:
http://docwiki.embarcadero.com/Libraries/Berlin/en/System.Threading.TParallel.For
Example pseudo-code:
MyPool: TThreadPool;
MyPool := TThreadPool.Create;

TParallel.For(1, Max, procedure (I: Integer)
    begin
      if IsPrime (I) then
        TInterlocked.Increment (Tot);
    end,
MyPool
);

MyPool.Free;


text:
Q: Django - querying multiple values using foreign keys I am new to Django and trying to understand the model relationships. I have two models:
class Author(models.Model):
    author_name = models.Charfield(max_length = 15)

class Books(models.Model):
    book_name = models.CharField(max_length = 15)
    authors = models.ForeignKey(Author)

In my views.py I am accessing the records like this:
class BooksViewSet(APIView):
    def get(self, request):
        data = Books.objects.all()

Now suppose I have multiple books with multiple authors, how do I create an API which would include all the authors of the books? I think I need to filter out the values but am not exactly sure how it is done. Currently, I get only one author using the above views.py. Sorry if I missed the obvious. Thanks for your time in advance.


text:
Q: FOSUserBundle, symfony 2.1. How can I add a role to a user at registration? I'm sure this is a simple question but I can't quite see or find the correct way to do it.
How do I add a role to a user when that user is created using the registration form?

A: Found it. I was on the right track :)
Override the registration form handler.
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/overriding_forms.md
Add
$user->addRole('ROLE_MYROLE');

before
parent::onSuccess()


text:
Q: SQL Server : I am working on for time checkin giving error that can not repeat columns with same name I am creating a sql for checkin time for employees.
My table looks like this

I want to display checkin time for employees.
So for example jason timesheet will look something like this
name   | 1st feb  | 2nd feb  | 3rd feb
----------------------------------------------------
jason  |  9:00:00 |  9:00:00 | ...
clark  |  ...     |  ...     | ...

I have found a similar question here  Efficiently convert rows to columns in sql server
But it's not quite working
output that I am getting
**Updated:**following is my sql
     DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

 select @cols = STUFF((SELECT ',' + QUOTENAME(checkin)
                from cico
                group by checkin, id
                order by id
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')

  set @query = N'SELECT ' + @cols + N' from
         (
            select checkin, name
            from cico
        ) x
        pivot
        (
            max(checkin)
            for name in (' + @cols + N')
        ) p '

        exec sp_executesql @query;
     END

A: Try this..
I have edited your query...
DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

 select @cols = STUFF((SELECT ',' + QUOTENAME(DateT)
                from cico
                group by DateT
                order by DateT
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)')
    ,1,1,'')

  set @query = N'SELECT name,' + @cols + N' from
         (
            select name,DateT,checkin
            from cico
        ) x
        pivot
        (
            max(checkin)
            for DateT in (' + @cols + N')
        ) p '

        exec sp_executesql @query;
     END

A: try this
DECLARE @cols AS NVARCHAR(MAX)
    ,@query AS NVARCHAR(MAX)

-- Get all dates and format it in CSV string
SELECT @cols = STUFF((
            SELECT ',' + QUOTENAME(DateT)
            FROM cico
            GROUP BY DateT
            ORDER BY DateT
            FOR XML PATH('')
                ,TYPE
            ).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

-- The pivot query
SET @query = N'SELECT name, ' + @cols + N' from
         (
            select checkin, name, DateT
            from cico
        ) x
        pivot
        (
            max(checkin)
            for DateT in (' + @cols + N')
        ) p '

PRINT @query  -- print out the query

EXEC sp_executesql @query;


text:
Q: Identify iPhones with Notch Programmatically I am trying to identify iPhones with the notch programmatically. I am aware of the screen.size method, but when you have a universal app supporting all interface orientations, it becomes a mess (counting all the possible variations). So I am looking for a simpler and more elegant way to detect the newer iPhones X models.
I have stumbled upon a method online that is supposed to work. In it, you measure the bottom inset of the safe area and if it is not zero, you have an iPhone X model. This makes sense in theory since, the safe area does not reach the bottom of the screen on the iPhone X handsets but does on all other devices. I do the check this way:
if (@available( iOS 11.0, * )) {
    if ([[[UIApplication sharedApplication] keyWindow] safeAreaInsets].bottom > 0) {
        // iPhone with notch
    }
} else {
    // Regular iPhone
}

This, however, does not work. Can someone point out my mistake in the implementation or confirm if this method is even viable?

A: Updated for Swift 5 and iOS14
This solves the keyWindow deprecation warning.
var hasNotch: Bool {

 let bottom = UIApplication.shared.windows.first{ $0.isKeyWindow }?.safeAreaInsets.bottom ?? 0
 return bottom > 0

    }

A: Swift 5 and (iOS12 or Above)
var isNotch: Bool {
   return (UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0) > 0
}

A: I had to dig around quite a bit but found the answer (I'd like to shout out to user6788419 whose right answer was berried deep in another thread).
First of all, the above code is correct. Checking if the safe area's bottom inset is larger than zero will accurately identify iPhones with a notch (as of this writing). So, this is correct:
if (@available( iOS 11.0, * )) {
    if ([[[UIApplication sharedApplication] keyWindow] safeAreaInsets].bottom > 0) {
        // iPhone with notch
    }
}

However, it matters where you put the above statement in your code because UIWindow is not available until the first run loop has concluded. That means, if you check the notch in your viewDidLoad or before it concluded (in your init for example), the bottom inset will always be zero.
If you, similarly to me, need this check to setup your main view, you can just move all your setup into separate function (such as postViewDidLoad) and call it once viewDidLoad has concluded:
[self performSelector:@selector(postViewDidLoad) withObject:nil afterDelay:0.0f];

Or, alternatively, you enclose it:
dispatch_async(dispatch_get_main_queue(), ^{
    // Check notch here
});

UPDATE: code for iOS 13 and up (does the same thing). "areaPosition" is a string argument when you call the function. "top" checks for the notch, everything else checks for the presence of the bottom home indicator.
- (UIWindow *) keyWindow {
    UIWindow *foundWindow   = nil;
    NSArray *windows        = [[UIApplication sharedApplication]windows];
    for (UIWindow *window in windows) {
        if (window.isKeyWindow) {
            foundWindow     = window;
            break;
        }
    }
    return foundWindow;
}

- (BOOL) checkSafeArea:(NSString *)areaPosition {
   if (@available(iOS 13.0, *)) {
       if ([areaPosition isEqualToString:@"top"]) {
           return [self keyWindow].safeAreaInsets.top > 20.0f;
       } else {
           return [self keyWindow].safeAreaInsets.bottom > 0.0f;
       }
   } else {
       if ([areaPosition isEqualToString:@"top"]) {
           return [[[UIApplication sharedApplication] delegate] window].safeAreaInsets.top > 20.0f;
       } else {
           return [[[UIApplication sharedApplication] delegate] window].safeAreaInsets.bottom > 0.0f;
       }
   }
   return  NO;
}


text:
Q: distribution convergence N(0,σ^2/n) Consider the sequence $X_1, X_2 \dots$ where each $X_n$ has a normal distribution $\mathcal{N}(0, σ ^ 2 / n)$. Let us show that $X_n$ converges in distribution to 0.
$$F_{X_n} (x) = \frac{1}{\sqrt{2\pi\sigma^2/n}} \int_{-\infty}^x e^{\frac{-u^2}{2(\sigma^2/n)}}du$$
My question is: Why is the limit of the distribution function as follows? how do you get there from the equation above?
$$\lim_{n\rightarrow \infty} F_{X_n} (x) =  \begin{cases}
      0 & \text{si}\ x < 0, \\
      \frac{1}{2} & \text{si}\ x = 0, \\
      1 & \text{si}\ x > 0.
   \end{cases}
$$

A: Hint: with $v = u\sqrt{n}/\sigma$,
$$\frac{1}{\sqrt{2\pi \sigma^2/n}} \int_{-\infty}^x e^{-u^2 / (2 \sigma^2/n)} \, du = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^{x\sqrt{n}/\sigma} e^{-v^2/2} \, dv.$$
Then take $n \to \infty$.

Instead of working with integrals, it may be easier to note that $X_n = \frac{\sigma}{\sqrt{n}} Z$ where $Z \sim N(0,1)$. So $P(X_n \le x) = P(Z \le \frac{x\sqrt{n}}{\sigma}) = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^{x\sqrt{n}/\sigma} e^{-v^2/2} \, dv$.