text:
Q: Which programming languages work well together for simulations? Every programming language has advantages and disadvantages which make it more suitable to a specific solution. Sometimes it makes sense to combine the advantages of two (sometimes more) languages to solve the "bigger picture" problem in the most efficient manner (execution time vs programming time, etc.).
Some programming languages play better together than others because they are closely related in design, and some also provide better interfaces to other programming languages, which are not directly related.
I know it's impossible to list all the different combinations, but I'm interested in the interaction capability for simulation work between the most commonly used programming languages.
Typically there is a requirement for the following:

*

*Grunt work (fast as possible calculations) should support multi-threading

*Good code library support (e.g. math, statistics)

*User interface (e.g. simulation setup, plotting results)

*Operating system independence (Windows/Linux/Mac)

It's obviously possible to use any two languages together in some way or another, but I know there are instances where it definitely makes more sense to do so.

A: You should probably change that to top 11, because JavaScript is invaluable when it comes to combining languages. Why? Because that's the only one you can run in a browser!
So, my answer is exactly that: Two languages that work well together are JavaScript and X (where X is any top 10 language from your list); JavaScript on the client, X on the server.

A: Your question is very general, but basically, most Win32 languages can work together. You can write fast dll's in C++ and then use Visual Basic 6 to make slow calls to it. ;) Delphi and C++ work well together too, although there isn't much reason to use C++ dlls in Delphi because Delphi will perform just as well.
The same goes for .NET assemblies. All of them can work together, so you can write a framework in C#, while choosing a language with an easier syntax (like VB.NET or Prism) to allow beginning programmers (or those migrating from VB) to use that framework.

A: Almost any scripting language (Perl, Python, Ruby, Lua, etc.) and C. You use the scripting language for rapid prototyping and then C to reimplement the slower parts.
C++ can also be used, but it has some features that are difficult to integrate as, for instance, virtual methods.
Then you have Jython, that's a version of Python running on top of the JVM that plays quite nicely with Java, and there are a bunch of other JVM languages in the same position.
If you use .Net or Mono, at least in theory, all the languages supported should be able to call code in other languages.

A: C#/ASP.NET/JavaScript(jQuery/jQueryUI/jQueryMobile)
That pretty much sums up my life, haha
This is a very broad question, which will have far too many answers. Just because putting two languages together may be difficult for one person, it might be easy for another.

A: For web design,
HTML, CSS, JAVASCRIPT, JQUERY/YUI, PHP, MYSQL. Perfect blend. If you are just starting out, learn the languages in the order i have them listed.


text:
Q: How to get Firebase snapshots length? I've created an app with Firebase but I've got a problem, which is that I
can't count the snapshot length in listview.builder.
StreamBuilder(
        stream:
            _firestore.collection('/posts/${widget.uid}/comments').snapshots(),
        builder: (context, snapshot) {
          final data = snapshot.data.documents;

          if (!snapshot.hasData) {
            return SpinKitChasingDots(
              color: Colors.lightGreen,
            );
          }
          return ListView.builder(
            itemCount: snapshot.data.documents.length,//Here is the problem
            itemBuilder: (context, index) {
              return PostComment(
                commentText: data[index]['commentText'],
                userImage: data[index]['userImage'],
                userName: data[index]['userName'],
              );
            },
          );
        },
      ),

When I run it gives me an error that it doesn't have actually a getter called length.

A: Try to explicitly declare type in your StreamBuilder
StreamBuilder<QuerySnapshot>(
        stream: _firestore.collection('...').snapshots(),

https://dart.dev/guides/language/sound-problems#runtime-errors

A: You can try this:
Firestore.instance.collection('/posts/${widget.uid}/comments').snapshots().length.toString();

A: snapshot.size
Return size array result for request

redpajama_set_name: RedPajamaStackExchange


text:
Q: YII2 sef urls construction I have catalogue with products. Urls for products looks like this domain.com/adv?id=14792.
I want to beautify urls like this domain.com/adv/14792.
In web.php I tried to like this
'urlManager' => [
 'enablePrettyUrl' => true,
 'showScriptName' => false,
 'enableStrictParsing' => true,
 'rules' => [
  'adv/<id:\d+>' => 'site/adv',
  '<alias:[\w-]+>' => 'site/<alias>',
 ],
],

and there is no result.
I tried another variant in rules block:
'rules' => [
  'adv/<id:\d+>' => 'adv',
  '<alias:[\w-]+>' => 'site/<alias>',
 ],

and urls start to look like I want. But on this link I get 404 page.

A: Please use action with adv so that it work.
    'rules' => [
  'adv/<id:\d+>' => 'adv/<add some action here>',
  '<alias:[\w-]+>' => 'site/<alias>',
 ],

A: I solved my problem by myself. This is my urlmanager module now:
'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
      'adv/<id:\d+>' => 'site/adv',
      '<alias:[\w-]+>' => 'site/<alias>',
      '<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
    ],

this construction build url from https://example.com/adv?id=123456 to https://example.com/adv/123456.
In view link build with
Html::a($insideEl,Url::to(['adv','id' => $ladvert->id]))

and in siteController action is
actionAdv($id)

Thanx.


text:
Q: Can I remote desktop into a Windows-based corporate network from my iPad?
Possible duplicate:
iPads in the corporate world

Has anyone remote desktop into a Windows-based corporate network with an iPad? What has been your experience? How do you address the issue of multiple domains? Is this even possible?
Currently, I just connect my laptop to a network cable and remote desktop from one domain into another domain to get to my desktop computer into a different location.
Is this possible with an iPad? How would my regular network cable connect to an iPad?

A: If you're talking about accessing a Remote Desktop via a RDC Client, There are a lot of applications that work fine. I'm personally using iTap Mobile RDP and it's fantastic.

A: To answer your networking question: You can connect an iPad to a computer, or to a Wi-Fi connection (or both), but you can't connect an Ethernet cable to an iPad.


text:
Q: Graph produced by keras.utils.plot_model is not correct I have a model consisting of multiple smaller models. I want to make sure that everything is hooked up correctly and looked at the graph produced by keras.utils.plot_model.
There I stumbled on some parts that don't look correct to me.
Some connections are missing and at the inputs some additional connections are drawn (probably because of the stacking of the models).
Why are there connections missing? Is the model correct? Is the graph correct? What is the best way to check if the information flow is as expected?
from tensorflow.keras.utils import plot_model
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, concatenate, Add

n_input_a0 = 10
# A -> n_input_b0 = n_input_c0

n_input_b0 = 20
n_input_b1 = 21
# B -> n_input_c1, n_input_c1

n_input_c0 = 20
n_input_c1 = 31
# C -> n_output

n_output = 3

# A
ip_a0 = Input(shape=(n_input_a0,), name='ip_a0')
x_a = Dense(units=10)(ip_a0)
x_a = Dense(units=n_input_b0)(x_a)
model_a = Model(inputs=ip_a0, outputs=x_a, name='model_a')

# B
ip_b0 = Input(shape=(n_input_b0,), name='ip_b0')
ip_b1 = Input(shape=(n_input_b1,), name='ip_b1')
ip_b0b1 = concatenate([ip_b0, ip_b1])
x_b = Dense(units=10)(ip_b0b1)
x_b = Dense(units=n_output)(x_b)
x_b_left = Dense(units=n_input_c1)(x_b)
x_b_right = Dense(units=n_input_c1)(x_b)
model_b = Model(inputs=[ip_b0, ip_b1], outputs=[x_b_left, x_b_right], name='model_b')

# C
ip_c0 = Input(shape=(n_input_c0,), name='ip_c0')
ip_c1 = Input(shape=(n_input_c1,), name='ip_c1')
ip_c0c1 = concatenate([ip_c0, ip_c1])
x_c = Dense(units=10)(ip_c0c1)
x_c = Dense(units=n_output)(x_c)
model_c = Model(inputs=[ip_c0, ip_c1], outputs=[x_c], name='model_c')

# Combined Model
ip_a0_external = Input(shape=(n_input_a0,), name='ip_a0_external')
ip_b1_external = Input(shape=(n_input_b1,), name='ip_b1_external')

x_a2 = model_a(ip_a0_external)
x_b_left2, x_b_right2 = model_b([x_a2, ip_b1_external])
x_b2 = Add()([x_b_left2, x_b_right2])
x_c2 = model_c([x_a2, x_b2])

model_total = Model(inputs=[ip_a0_external, ip_b1_external], outputs=[x_c2], name='model_total')
plot_model(model_total, expand_nested=True, show_shapes=True, to_file='model.png', dpi=80)

I also looked at the output of TensorBoard.
The results are a little bit better but the addition of x_b_left + x_b_right is missing as well.
import numpy as np
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
with tf.compat.v1.Session() as sess:
    writer = tf.compat.v1.summary.FileWriter('logs', sess.graph)
    model_total([np.ones((1, n_input_a0)), np.ones((1, n_input_b1))])
    writer.close()

A: I think you corrupted the models when you passed the same input to them twice. This is a strange thing to do.

*

*It's here: x_a2 = model_a(ip_a0)

*And here: x_b_left2, x_b_right2 = model_b([x_a2, ip_b1])
The inputs ip_a0 and ip_b1 are already part of the models and should not be called again.
I'd do it this way (didn't check if the graph gets corrected)
Original code:
from tensorflow.keras.utils import plot_model
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, concatenate, Add

n_input_a0 = 10
# A -> n_input_b0 = n_input_c0

n_input_b0 = 20
n_input_b1 = 21
# B -> n_input_c1, n_input_c1

n_input_c0 = 20
n_input_c1 = 31
# C -> n_output

n_output = 3

# A
ip_a0 = Input(shape=(n_input_a0,), name='ip_a0')
x_a = Dense(units=10)(ip_a0)
x_a = Dense(units=n_input_b0)(x_a)

model_a = Model(inputs=ip_a0, outputs=x_a, name='model_a')

Change here:
#don't call the model on its own inputs!!!!
x_a2 = model_a.output

#alternatively, following the same pattern as followed for model B
#ip_a0_external = Input(shape=(n_input_a0,), name='ip_a0_external')
#x_a2 = model_a(ip_a0_external)

Original code:
# B
ip_b0 = Input(shape=(n_input_b0,), name='ip_b0')
ip_b1 = Input(shape=(n_input_b1,), name='ip_b1')
ip_b0b1 = concatenate([ip_b0, ip_b1])
x_b = Dense(units=10)(ip_b0b1)
x_b_temp = Dense(units=n_output)(x_b)
x_b_left = Dense(units=n_input_c1)(x_b_temp)
x_b_right = Dense(units=n_input_c1)(x_b_temp)

model_b = Model(inputs=[ip_b0, ip_b1], outputs=[x_b_left, x_b_right], name='model_b')

Change here:
#don't call the model on its own inputs!!
#create a new input for this
ip_b1_external = Input(shape=(n_input_b1,), name='ip_b1_external')
x_b_left2, x_b_right2 = model_b([x_a2, ip_b1_external])

Original code:
x_b2 = Add()([x_b_left2, x_b_right2])

# C
ip_c0 = Input(shape=(n_input_c0,), name='ip_c0')
ip_c1 = Input(shape=(n_input_c1,), name='ip_c1')
ip_c0c1 = concatenate([ip_c0, ip_c1])
x_c = Dense(units=10)(ip_c0c1)
x_c = Dense(units=n_output)(x_c)

model_c = Model(inputs=[ip_c0, ip_c1], outputs=[x_c], name='model_c')

#ok, both inputs are from outside
x_c2 = model_c([x_a2, x_b2])

Change here:
# Combined Model
# keep track of what inputs were actual inputs for this model
# and what inputs were only helpers for the submodels:

model_total = Model(inputs=[model_a.input, ip_b1_external], outputs=[x_c2], name='model_total', )
#alternatively
#model_total = Model(inputs=[ip_a0_external, ip_b1_external], outputs=[x_c2])
plot_model(model_total, expand_nested=True, show_shapes=True, to_file='model.png', dpi=64)


text:
Q: THREE.JS Skybox not displayed on screen I am trying to include a skybox to a scene in a web page, so I followed a tutorial I found (https://dev.to/codypearce/how-to-create-a-skybox-with-three-js-2bn8), everything seems to work correctly as my console (on firefox) doesn't display any errors or warning.
First the code creates an array of texture, then assembles the textures in a box and finally adds the box to the scene. I don't have any light in my scene as every objects are visible without any so far (and when I try to add one it doesn't change anything, and the console doesn't show any error either).
I thought it could be a matter of distance of the camera to the skybox so I got the skybox closer to the camera but still nothing.
I put my code down here if you want to see what I did so far. Thanks in advance for your help!
var camera, scene, rendu;
var r, t;

init();

function init() {
    r = 3;
    t = 1.1;
    // ---------- scene et camera --------- //
    camera = new THREE.PerspectiveCamera( 70 , window.innerWidth / window.innerHeight , 0.01 , 2000 );
    camera.position.set( 0 , 0 , 4 );
    camera.lookAt(new THREE.Vector3( 0, 0, 0 ));

    scene = new THREE.Scene();

    loadSkybox();

    // ---------- rendu ------------- //
    rendu = new THREE.WebGLRenderer( { antialias: true} );
    rendu.setSize( window.innerWidth, window.innerHeight );
    rendu.setPixelRatio(window.devicePixelRatio);
    rendu.setAnimationLoop( animation );
    document.body.appendChild( rendu.domElement );

}

function animation() {
    rendu.render( scene, camera );
}

function createPathStrings(filename) {
    const basePath = "./ulukai/";
    const baseFilename = basePath + filename;
    const fileType = ".png";
    const sides = ["ft", "bk", "up", "dn", "rt", "lf"];
    const pathStrings = sides.map(side => {
      return baseFilename + "_" + side + fileType;
    });

    return pathStrings;

}

function createMaterialArray(filename) {
  const skyboxImagepaths = createPathStrings(filename);
  const materialArray = skyboxImagepaths.map(image => {
    let texture = new THREE.TextureLoader().load(image);

    return new THREE.MeshBasicMaterial({ map: texture, side: THREE.DoubleSide });
  });

  return materialArray;

}

function loadSkybox() {
    // ----------- skybox -------------- //
    var skyboxImage = "corona";
    skyboxGeo = new THREE.BoxGeometry(1000, 1000, 1000);
    skybox = new THREE.Mesh(skyboxGeo, createMaterialArray(skyboxImage));
    scene.add(skybox);
}


text:
Q: How to render UIView into a CGContext I Wanted to render a UIView into a CGContextRef
-(void)methodName:(CGContextRef)ctx {
    UIView *someView = [[UIView alloc] init];

    MagicalFunction(ctx, someView);
}

So, the MagicalFunction here is supposed to render the UIView(may be its layer) into current context.
How do I do that?
Thanks in advance!

A: How about the renderInContext method of CALayer?
-(void)methodName:(CGContextRef)ctx {
    UIView *someView = [[UIView alloc] init];
    [someView.layer renderInContext:ctx];
}

EDIT: As noted in the comment, due to a difference in origins in the two coordinate systems involved in the process, the layer will be rendered upside-down. To compensate, you just need to flip the context vertically. This is technically done with a scale and translation transformation, which can be combined in a single matrix transformation:
-(void)methodName:(CGContextRef)ctx {
    UIView *someView = [[UIView alloc] init];
    CGAffineTransform verticalFlip = CGAffineTransformMake(1, 0, 0, -1, 0, someView.frame.size.height);
    CGContextConcatCTM(ctx, verticalFlip);
    [someView.layer renderInContext:ctx];
}


text:
Q: Using split in python script correctly Im making a program that parses .m file into .h file with rearanging some stuff in different order. Im basically new to Python, but I know other language. Program code is:
 with open('D:\\\toolchain\Simulink\data\\application_parameters_data.m','r') as InputFile:
            for j in InputFile:
                for k in range(2): InputFile.readline()
                with open('D:\\\toolchain\Connector\ConDataGenerated.h', 'w') as file1:
                    t1 = Template('$datatype $name $initValue $comment')
                    for i in InputFile:
                        file1.write("\n")
                        Type = [name.strip() for name in i.split(';\n')[0].split(',')]
                        file1.write(t1.safe_substitute(datatype = Type[5], name = Type[0], initValue =Type[1], comment =Type[4]))

I need to change it contence divided by , between elements and ; between lines accordingly. Example of input code:
'ManCtrlInputShaftSpeedSwt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlInputShaftSpeedPar', 0, [0 1], '', 'comment', 'single';
'ManCtrlInputShaftSpeed1Swt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlInputShaftSpeed1Par', 0, [0 1], '', 'comment', 'single';
'ManCtrlInputShaftSpeed2Swt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlInputShaftSpeed2Par', 0, [0 1], '', 'comment', 'single';
'ManCtrlOutputShaftSpeedSwt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlOutputShaftSpeedPar', 0, [0 1], '', 'comment', 'single';
'ManCtrlOutputShaftSpeedDirnSwt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlOutputShaftSpeedDirnPar', 0, [0 1], '', 'comment', 'uint16';

'ManCtrlMeasPositionS1Swt', 0, [0 1], '', 'comment', 'uint16';
'ManCtrlMeasPositionS1Par', 0, [0 1], '', 'comment', 'single';

Here's the thing. Script works fine until it hits the space between strings or something that it doesnt recognise, or, it works with writing only first element of string to new file, in that case it iterates through strings without problems. I think it somehow connected to compiler telling me next:
Traceback (most recent call last):
  File "D:\\StringTemplate.py", line 16, in <module>
    file1.write(t1.safe_substitute(datatype = Type[5], name = Type[0], initValue =Type[1], comment =Type[4]))
IndexError: list index out of range

even though file creates with this problems. example of output code:
'uint16' 'ManCtrlInputShaftSpeedSwt' 0 'comment'
'single' 'ManCtrlInputShaftSpeedPar' 0 'comment'
'uint16' 'ManCtrlInputShaftSpeed1Swt' 0 'comment'
'single' 'ManCtrlInputShaftSpeed1Par' 0 'comment'
'uint16' 'ManCtrlInputShaftSpeed2Swt' 0 'comment'
'single' 'ManCtrlInputShaftSpeed2Par' 0 'comment'
'uint16' 'ManCtrlOutputShaftSpeedSwt' 0 'comment'
'single' 'ManCtrlOutputShaftSpeedPar' 0 'comment'
'uint16' 'ManCtrlOutputShaftSpeedDirnSwt' 0 'comment'
'uint16' 'ManCtrlOutputShaftSpeedDirnPar' 0 'comment'

What should I do?

A: You can add a condition to check if the line has a length of 5 / if it's not empty, something like:
                        Type = [name.strip() for name in i.split(';\n')[0].split(',')]
                        if len(Type) > 5:
                            file1.write(t1.safe_substitute(datatype = Type[5], name = Type[0], initValue =Type[1], comment =Type[4]))


text:
Q: How to make the text/id I give can be brought from the URL I am requesting I need to write an ID (from 1 to 10) and to be displayed on a table but I don't know how to bring the ID I wrote to the print, how do I display ONLY the data from certain ID of the json file?
ID:
<input id="ide" type="search" placeholder="ID" name="ide">
<button id="boton" type="submit">Buscar</button>

            UserID
            ID
            Title
            Completed

function ajax() {
    const url = "https://jsonplaceholder.typicode.com/users";

    axios.get(url)
        .then((res) => {
            show(res.data)
        })
        .catch((err) => {
            console.log(data);
        })
}

function show(data) {
    for (const id of data) {
        tabla.innerHTML += `

                ${id.id}
                ${id.name}
                ${id.username}
                ${id.email}

        `
    }
}

document.getElementById("boton").addEventListener("click", function() {
    ajax();
});

A: Declare a variable for id first
let id = 0

document.getElementById("ide").addEventListener("onchange", function(e) {
    id = e.target.value
});

Your ajax function should be like this:
 function ajax() {
        const url = `https://jsonplaceholder.typicode.com/users/:${id}`;

        axios.get(url)
            .then((res) => {
                show(res.data)
            })
            .catch((err) => {
                console.log(data);
            })
    }


text:
Q: Operand order in where clause for joining tables Does the order at the where clause when joining tables matter? In other words, is G.GuestNo = B.GuestNo the same as B.GuestNo = G.GuestNo?
Select GuestNo, GuestName,
From Booking B, Guest G
Where B.GuestNo=G.GuestNo

A: No, the order of the operands doesn't matter. You'll get the same results either way.

A: No. Ordering does not matter. you can have in either way.


text:
Q: Sequence does not reset after truncating the table I use SELECT lastval() to get wrong serial id  after truncated  the table.
when I truncate the table, I use SELECT lastval(), I got the wrong ID/

A: Use the TRUNCATE SQL command.
For a single table the syntax is the following:
TRUNCATE TABLE table_name RESTART IDENTITY;

For multiple tables:
TRUNCATE TABLE table_foo, table_bar RESTART IDENTITY;

What it does:

Automatically restart sequences owned by columns of the truncated table(s).

Details here: TRUNCATE @ postgresql.org

A: The best way to reset a sequence to start back with number 1 is to execute the following after you have successfully truncate it:
ALTER SEQUENCE <tablename>_<id>_seq RESTART WITH 1

So, for example for the users table it would be:
ALTER SEQUENCE users_id_seq RESTART WITH 1

A: Check the next
ALTER SEQUENCE sequence_name RESTART WITH 1;

A: Try this:
TRUNCATE TABLE table_name RESTART IDENTITY CASCADE;

A: Following is the standard way to reset sequence:
truncate table table_name restart identity;

but in some version & platform, it's syntax error,
in that case, you can truncate without reset sequence, and alter the sequence with another sql, try this:
truncate table table_name;
alter sequence seq_name start 1;

A: If you want to reset the sequence then:
setval('sequence_name', 0)

To list the existent sequence names issue a \ds at the psql prompt.

A: You can use the below sql statement to reset the identity in postgresql:
TRUNCATE TABLE table_name RESTART IDENTITY;

But note, it's not possible to reseed the identity in Redshift. The way around to reset in Redshift is to drop and then create the table again.


text:
Q: How Microsoft Network Monitor works Does Microsoft Network Monitor depends on pcap/winpcap/libpcap libary? Or it has built its own libary/drivers to capture network packets? I cannot find any information about that subject. I am asking, cos Microsoft Network Monitor does not require restart after installation (so it does not load kernel level drivers?) and captures incoming packets even on Windows 7, where raw packets capturing does not work.
Additional information about raw packets limitation: http://social.technet.microsoft.com/Forums/en-US/w7itpronetworking/thread/65ce9bee-897b-4c19-a4c6-4d3da103be44/
Edit: I find answer myself -
The Network Monitor engine is divided into two parts: the capture engine and the parsing engine.
The capture engine is a driver that interfaces with the Network Driver Interface Specification (NDIS) to read frame data. It is a system driver that is installed automatically on Windows Vista. On previous operating systems, the capture driver is part of the system.
The parsing engine, on the other hand, is in user mode. This engine uses Network Monitor Parsing Language (NPL) files to determine how to parse raw frame data. It also filters frames.
The API can access both parts of the engine, as well as save and load capture files.

A: Windows may support loading kernel modules (.sys files) without needing to reboot, so there might not have to be a reboot after installing Network Monitor.
Network Monitor does not use WinPcap; it has, as you note, its own NDIS driver that serves a similar purpose to WinPcap's NDIS driver.


text:
Q: wpdb doesn't execute query using IN operator after binding the array to a placeholder I have this query:
$post_query = "SELECT *
FROM wpps_terms t
INNER JOIN wpps_term_taxonomy tt ON tt.term_id = t.term_id AND t.term_id IN ($placeholder)
WHERE tt.taxonomy = 'property-area' AND t.name LIKE '%s' ";

which use the IN operator, I bind the values like this:
$taxonomiesArr = [4, 8];

$filter = array_map(function($v) {
    return "'" . esc_sql($v) . "'";
}, $taxonomiesArr);
$filter = implode(',', $filter);

$placeholder = implode(',', array_fill(0, count($filter), '%s'));

I'm trying to bind the taxonomiesArr like that:
$like = '%' . $wpdb->esc_like('columbia') . '%';
$result = $wpdb->get_results($wpdb->prepare($post_query, $taxonomiesArr, $like));

the problem's that the query is never execute and wpdb->print_error() doesn't show anything. I'm sure that the query isn't executed 'cause if I look wpdb->last_query I get the previous query executed.
If I change the prepare as:
$result = $wpdb->get_results($wpdb->prepare($post_query, 4, 8, $like));

the query is executed, but why I get this behavior? I can't pass the values manually!

A: These 2 lines of code are causing the problem:
$filter = implode(',', $filter);
$placeholder = implode(',', array_fill(0, count($filter), '%s'));

You are converting $filter to a string before using it in count- you are probably getting the following warning in your logs: "Warning: count(): Parameter must be an array or an object that implements Countable in..."
This means the array_fill function is not working and you're $placeholder string is wrong
How to fix this:
Either move the filter implode line belwo the code where you set up your $placeholder, or save the count of the array into a variable before you implode it and use it instead of count:
$taxonomiesArr = [4, 8];

$filter = array_map(function($v) {
    return "'" . esc_sql($v) . "'";
}, $taxonomiesArr);

/* MOVE THIS LINE (or save count($filter) into a var before it)
   - it converts the array to string but you need an array for count in array_fill */
// $filter = implode(',', $filter);

$placeholder = implode(',', array_fill(0, count($filter), '%s'));

$filter = implode(',', $filter);

If you print_r($placeholder); at the end of the code above, you get %s,%s as expected


text:
Q: Ellipse region in polar coordinates if I want to write the region in $R^2$ bounded by the ellipse
$$10x^2 + 17 y^2 = 29$$
In polar coordinates($x=r\cos \theta, y= r \sin \theta$), how can I find the limit of $r$?

A: Substituting the polar coordinates you get
$$
r^2(10\cos^2\theta+17\sin^2\theta)=29\implies r=\frac{\sqrt{29}}{\sqrt{10\cos^2\theta+17\sin^2\theta}}.
$$
In this type of problem, it is ussually easier to work with modified polar coordinates:
$$
x=a\,r\cos\theta,\quad y=b \,r\sin\theta.
$$
In this examople
$$
a=\sqrt{\frac{29}{10}},\quad b=\sqrt{\frac{29}{17}}.
$$


text:
Q: How do I make a proper for loop with multiple conditions? I am making a game and 'on key down' it moves the character (self) down..  I am trying to fix some things with collision detection. My problem in the example below is that the second line always returns True.  What I am trying to do in the second line is say "if the character collides with a widget but the characters y value is lower than half the height of the widget it's colliding withs height, then move character down.
Because it always returns True, I my character can is moving down regardless of any collision and regardless of the characters y value (it can be above the widgets midway section, and i am still able to move down).
What am I doing wrong here?
elif keycode[1] == 'down':
    if any(self.collide_widget(i) and self.y < (i.y+(i.height/2)) for i in listofwidgets):
        self.y -=6
        self.source='characters/lilmoney/walkdown.zip'
    elif (i.collide_point(self.x, self.top) for i in listofwidgets):
        self.source='characters/lilmoney/lilmoneyfront.png'

A: You're missing an any in the elif statement. So, you're left with a generator, which is always true. So, change that statement to
elif any(i.collide_point(self.x, self.top) for i in listofwidgets):


text:
Q: Python class if of type 'None' I'm fairly new to Python and I'm creating a small project. However, every time I try to create an instance of a class TwitterClient and assign it to the variable api, trying to call methods from api returns 'NoneType object has no attribute (function name). I've looked at what others have done regarding this topic, but so far, changing the parameters of the TwitterClient class hasn't worked. Perhaps my understanding is off, but why is a class being considered a NoneType object? After I run main(), I get this error.
Here's my code:

def TwitterClient():

    def __init__(self):

        api_key = '-------'
        api_key_secret = '----------'

        bearer_token = '--------------'

        access_token = '---------------'
        access_token_secret = '-----------------'

        try:

            self.auth = OAuthHandler(consumer_key, consumer_secret)

            self.auth.set_access_token(access_token, access_token_secret)

            self.api = tweepy.API(self.auth)
        except:
            print("Error: Authentication Failed")

    def clean_tweet(self, tweet):
        return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())

    def get_tweet_sentiment(self, tweet):

        analysis = TextBlob(self.clean_tweet(tweet))

        if analysis.sentiment.polarity > 0:
            return '+'
        elif analysis.sentiment.polarity == 0:
            return 'n'
        else:
            return '-'

    def get_tweets(self, query, count=10):

        tweets = []

        try:

            fetched_tweets = self.api.search(q = query, count = count)

            for tweet in fetched_tweets:

                parsed_tweets = {}

                parsed_tweets['text'] = tweet.text

                parsed_tweet['sentiemnt'] = tweet.sentiment

                if tweet.retweet_count > 0:

                    if parsed_tweet not in tweets:
                        tweets.append(parsed_tweet)
                else:
                    tweets.append(parsed_tweet)

            return parsed_tweets

        except tweepy.TweepError as e:
            print("Error : " + str(e))

def main():

    api = TwitterClient()

    tweets = api.get_tweets(query = "etc", count = 10)

if __name__ == "main":
    main()

A: As mentioned, you didn't define a class, but also didn't properly initialize your function either. But also, tweepy no longer has an API.search() function but is now broken up into API.search_tweets(), API.search_users(), API.search_geo(), and a couple of premium ones that I don't have any experience with since access is both limited and not free. Since it looks like you're using OAuth1.0's user context, and Oauth 2.0 also has a user context handler, you should also know that the OAuthHandler function has been deprecated and you should explicitly call OAuth1UserHandler (or Oauth2UserHandler if you want to use that), since they take different parameters.
The simplest way to fix what you have would be something like:
import tweepy

class TwitterClient(object):

    def __init__(self, consumer_key, consumer_secret, access_token, access_secret):
        self.authclient = tweepy.Oauth1UserHandler(consumer_key, consumer_secret, access_token, access_secret)
        self.api = tweepy.API(self.authclient)

    def get_tweets(self, query, count=10):
        fetched_tweets = self.api.search_tweets(q=query, count=count)
        # add in whatever parsing code you want here, since it returns a collection anyway, fetched_tweets['statuses'] is a list of returned tweets, and you can iterate through their 'text' field if you so wish via list comprehension

Also, I think that the v2 API now has a recent search endpoint that is going to end up being the preferred way of searching for free users, since it returns the last 100 tweets in reverse chronological order, if there are tweets, you shouldn't come up empty with the query. A lot of us are grandfathered into Elevated Access while Twitter is clearly trying to deprecate at some point v1.1 so it's entirely possible that not only does the api return different results for you and me but there's no real telling as to how long they'll keep the current endpoints working as is, so definitely keep an eye out for breaking changes.


text:
Q: How to access an instance relation using strings in Ruby on Rails? Supose I have a class named Classroom and I have another class named Student.
From their relationship I can access Student by using Classroom.students which returns an array of students.
Now, taking that in consideration, if I assign 'Classroom' to a variable and call it with variable.constantize it will return the Class from where I can query normally.
eg:

[1] pry(main)> variable = 'Classroom'
[2] pry(main)> variable.constantize.students
=> [#<Student id: 1, name: 'Foo Smith'>, <Student id: 2, name: 'Bar Obama'>]

All of that works for me but I have no idea on how to access students if the key name is also stored as a string. This works if I'm trying to access a Classroom field but for relations it seems to be impossible.
eg:

[1] pry(main)> variable = 'Classroom'
[2] pry(main)> class_key = 'name'
[3] pry(main)> relation_key = 'students'
[4] pry(main)> variable.constantize.first[class_key]
=> "Happy Classroom"
[5] pry(main)> variable.constantize.first[key]
=> nil

There's also another case in which the string is a method from the class.
What I wanted to do (mock code):

[1] pry(main)> variable = 'Classroom'
[2] pry(main)> method = 'last'
[3] pry(main)> variable.constantize[method]
=> <#Classroom id: 3, name: 'Dubious Classroom'>

Any of those are feasible in Ruby?
Thanks!

A: Use Object.public_send, like this:
'Classroom'.constantize.public_send('students').public_send('first')

Edit: original answer suggested using send instead of public_send. The difference is that the former will call even the private methods, so it's less safe to use than the latter.


text:
Q: "Ternary" operator for different method signatures I'm looking for an elegant way to choose a method signature (overloaded) and pass an argument based on a conditional.  I have an importer that will either produce the most recent file to import, or take an explicit path for the data.
Currently my code looks like this:
if (string.IsNullOrEmpty(arguments.File))
{
    importer.StartImport();
}
else
{
    importer.StartImport(arguments.File);
}

I would like it to look like this (or conceptually similar):
importer.StartImport(string.IsNullOrEmpty(arguments.File) ? Nothing : arguments.File);

The idea being that a different method signature would be called.  A few stipulations:
1) I will not rely on 'null' to indicate an unspecified file (i.e. anything besides null itself).
2) I will not pass the arguments struct to the importer class; that violates the single responsibility principle.
One solution I'm aware of, is having only one StartImport() method that takes a single string, at which point that method resolves the conditional and chooses how to proceed.  I'm currently choosing to avoid this solution because it only moves the if-statement from one method to another.  I'm asking this question because:
1) I would like to reduce "8 lines" of code to 1.
2) I'm genuinely curious if C# is capable of something like this.

A:
I would like to reduce "8 lines" of code to 1.

I think you're asking the wrong question. It's not how many lines of code you have, it's how clear, maintainable, and debuggable they are. From what you've described, importing from a default location and importing with a known file are semantically different - so I think you're correct in separating them as two different overloads. In fact, you may want to go further and actually name them differently to further clarify the difference.

I'm genuinely curious if C# is capable of something like this.

Sure, we can use all sorts of fancy language tricks to make this more compact ... but I don't think they make the code more clear. For instance:
// build a Action delegate based on the argument...
Action importAction = string.IsNullOrEmpty(arguments.File)
                            ? () => importer.StartImport()
                            : () => importer.StartImport(arguments.File)
importAction(); // invoke the delegate...

The code above uses a lambda + closure to create a Action delegate of the right type, which is then invoked. But this is hardly more clear ... it's also slightly less efficient, as it requires creating a delegate and then invoking the method through that delegate. In most cases the performance overhead is completely negligible. The real problem here is the use of the closure - it's very easy to misuse code with closures - and it's entirely possible to introduce bugs by using closures incorrectly.

A: You can't do this using 'strong-typed' C#.  Overload resolution is performed at compile time: the compiler will work out the static (compile-time) type of the argument, and resolve based on that.  If you want to use one of two different overloads, you have to perform two different calls.
In some cases, you can defer overload resolution until runtime using the dynamic type.  However, this has a performance (and clarity!) cost, and won't work in your situation because you need to pass a different number of arguments in the two cases.

A: Yes, it is possible (using reflection). But I wouldn't recommend it at all because you end up with way more code than you had before. The "8-lines" which you have are quite simple and readable. The "one-liner" using reflection is not. But for completeness sake, here's a one-liner:
importer.GetType().GetMethod("StartImport", string.IsNullOrEmpty(arguments.File) ? new Type[0] : new Type[] { typeof(string) }).Invoke(importer, string.IsNullOrEmpty(arguments.File) ? new object[0] : new object[] { arguments.File) }));

A: Frankly, I think your code would be a lot more readable and modular if you combined the overloaded methods back into a single method and moved the conditional inside it instead of making the caller pre-validate the input.
importer.StartImport(arguments.File);

void StartImport(string File) {
  if (string.isNullOrEmpty(File)) {
      ...
  }
  else {
      ...
  }
}

Assuming you call the method from multiple places in your code you don't have the conditional OR ternary expression scattered around violating the DRY principle with this approach.

A: //one line
if (string.IsNullOrEmpty(arguments.File)) {importer.StartImport();} else{importer.StartImport(arguments.File);}


text:
Q: Can I use Examples in Background block? I need background to be run with 2 different roles.
I'm not allowed to do this:
 Background:
    Given I login as existing user with role "<role>"
    And I choose to create new Account

    Examples:
        | role          |
        | Standard User |
        | Site Admin    |

What is the best way to resolve this issue?

A: It's not possible with Background..  you can use Scenario Outline in feature:
For example:
Scenario Outline:

 Given I login as existing user with role "<role>"
 And I choose to create new Account

    Examples:
        | role          |
        | Standard User |
        | Site Admin    |

A: You have two separate pieces of behaviour here so do a scenario, or even a feature for each one.
In most applications different rules will apply for users and admins, and in many systems and even different ui's will be used.
A top rule for scenario writing is that its much better to have lots of simple scenarios than a few complex ones.


text:
Q: Does a CNN object detector always return the same results for the same image? There're many object detectors which use convolutional neural networks to detect objects in images or point clouds, like YOLO, SSD, AVOD.
My question is, if i feed the same image to an object detector many times, will the results of each time be the same? Is there any randomness in a CNN object detector that makes it produce different results for the same image?
Thanks in advance.

A: In general, when we want to predict something, we want the predictive algorithm to return consistent results, i.e. same inputs should lead to same outputs. In some cases it may make sense to randomize the predictions (e.g. classification algorithm predicts two classes with equal probabilities, and you need to force choice of a single category), but this is something to be considered on case-by-case basis.
As about neural networks (including convolutional networks), they are defined in terms of algebraic operations (mostly matrix multiplications), activation functions, and some other stuff that is also deterministic. We can use randomization in neural networks, but even if we use things like dropout during training, we turn it off during the prediction phase.
Different story is if we want to simulate the outputs from neural networks using (e.g. autoencoders, GANs, some algorithms in NLP that generate text), then we want them to be randomized.
TL;DR

My question is, if i feed the same image to an object detector many
  times, will the results of each time be the same?

Yes.


text:
Q: SQL recursion query assistance I have a table in a SQL DB that stores the User, Computer and Date every time an individual logs in to a machine. I need a way of determining what computers are logged in to by a specific person (date is irrelevant), but also a list of all the other people who also logged in to those computers...and any computers they have logged on to...and all the users who logged on to THOSE computers...and so on.
For example,
Bob logs on to computers A, B and C.
John also logs on to B and C but also D.
Frank logs on to D.
Jim logs on to D, E, F.
Andrew logs on to A and F.
I would want to show ALL of these relationships. Doesn't have to be in this format, but:

*

*Bob -> A -> Andrew

*Bob -> B -> John -> D -> Frank

*Bob -> C -> John -> D -> Frank

*Bob -> B -> John -> D -> Jim -> E

*Bob -> C -> John -> D -> Jim -> E

*Bob -> B -> John -> D -> Jim -> F -> Andrew

*Bob -> C -> John -> D -> Jim -> F -> Andrew

I know it's got to use at least one recursive query, but I can't figure out how to get it to work.

A:
Edit:

*

*The query supports two ways starting from both shared computers, and sharing users

*Removing duplicates from terminal chains

It looks like this is possible after a long half-day battling my head with progressive queries.
Using CTE recurrent statements of course, I could list along all the chaining events occured following a time line with some eventual exceptions, the most blatant is recursivity toleration of the server that blows off, just with 50 records i should wait for a remarkable period.
Assuming that the table exists already with the figuring columns : person,computer,at
WITH
recurrent_table as (
       select 0 step , t.person perstart , t.computer compstart , t.at timestart , cast('' as nvarchar) chain , convert (varchar(1) , '') perswait2chain , convert (varchar(1) , '') compwait2chain , t.person persend , t.computer compend , t.at timend
       from @logs t
    union all
       select 1 step , t.person perstart , t.computer compstart , t.at timestart , cast ('' as nvarchar) chain , convert (varchar(1) , '') perswait2chain , convert (varchar(1) , '') compwait2chain , t.person persend , t.computer compend , t.at timend
       from @logs t
    union all
       select step+1 step , r.perstart perstart , r.compstart compstart , r.timestart timestart , convert (nvarchar , r.chain + r.perswait2chain + r.compwait2chain)  chain , convert (varchar(1) , t.person) perswait2chain , convert (varchar(1) , t.computer) compwait2chain , t.person persend , t.computer compend , t.at timend
       from @logs t , recurrent_table r
    where (
       ( r.persend = t.person and step%2 = 1 )
    or
       ( r.compend = t.computer and step%2 = 0 )
    ) and t.at > r.timend
)

This recursive call is a thorough sweeper that compiles all possible junctions, the worst way to deal in sql than any other DB miner, with a case-switch at every alternating step to tell where to compare a common used computer, or a transferring user, the abundant parameters in the recursive table are to be used for filtering purpose, like when user A use machine 1 than machine 1 will be used by B then B use 2, only the longest chain A1B1B2 should count.
select distinct timestart 'started at' , timend 'ended at' , ct.perstart + ct.compstart + ct.chain + ct.perswait2chain + ct.compwait2chain 'chain of events'
from recurrent_table ct
where not exists (
     select chain from recurrent_table rc where
        cast (ct.perstart + ct.compstart + ct.chain + ct.persend + ct.compend as nvarchar) = cast (rc.chain + rc.persend + rc.compend as nvarchar)
     or cast (ct.perstart + ct.compstart + ct.chain + ct.perswait2chain + ct.compwait2chain as nvarchar) = cast (rc.chain + rc.perswait2chain + rc.compwait2chain as nvarchar)
     or cast (ct.perstart + ct.compstart + ct.chain + ct.persend + ct.compend as nvarchar) = cast (rc.perstart + rc.compstart + rc.chain as nvarchar)
     or ( rc.perswait2chain != ''
          and cast (ct.perstart + ct.compstart + ct.chain + ct.perswait2chain + ct.compwait2chain as nvarchar) = cast (rc.perstart + rc.compstart + rc.chain as nvarchar)
     )
)
order by timestart , timend
option ( MAXRECURSION  32767 )

this far, it would be noticable that the conditional filter sided with a sorting order is able to make you feel the keyboard melting between your hands from the heat emitted by your chipset, it's really wise to use a graph generator or an intelligent information digger for larger records. Or should it exist some shorter breakthough that works with implicit calls, both hands sql isn't really your man.
there is another exception where two chains of these forms come togather ...
A1 C1 C2 H2 H4 T4 T1 from 1:00 to 15:00
and
A1 T1 from 1:00 to 15:00
Those symbolic chains are caught within same time difference, where the last one surely implies alot of hidden events folded within it, that's because the query interpreter isn't selective, even selecting the closest timestamp would exclude alot of valid options, making a choice of the longest sequence between same timestamps also is exclusive of some rare eventualities like:
A1 C1 C2 H2 H4 T4 T1 from 1:00 to 15:00
A1 B1 B2 I2 I4 T4 T1 from 1:00 to 15:00
Only if my logic isn't flawed or vulnerable to an invalidating counter-example, either of these configurations are safe, the only walkthrough is making things more complicate by devoting an everlasting sub-sequence finder to match similarities and extract useless ones.
That's the overall:
declare @users table(psn char)
declare @computers table(comp char)

declare @logs table(person varchar(1), computer varchar(1), at DATETIME2 NOT NULL DEFAULT SYSDATETIME())

declare @cnt int
set @cnt=1

WHILE @cnt < 50
BEGIN
   insert @logs(person,computer) values (char(cast(DATEPART(nanosecond,SYSDATETIME())/1050 as int)%10+97), cast( DATEDIFF(nanosecond,cast(GETDATE () as datetime2),SYSDATETIME())/90 as int)%10+1)
   SET @cnt = @cnt + 1;
   WAITFOR DELAY '00:00:00.035';
END;

select person , computer as 'used computer ' , at from  @logs;

WITH
recurrent_table as (
select 0 step, t.person perstart, t.computer compstart,t.at timestart, cast('' as nvarchar) chain , convert(varchar(1),'') perswait2chain , convert(varchar(1),'') compwait2chain, t.person persend , t.computer compend, t.at timend
from @logs t
union all
select 1 step, t.person perstart, t.computer compstart,t.at timestart, cast('' as nvarchar) chain , convert(varchar(1),'') perswait2chain , convert(varchar(1),'') compwait2chain, t.person persend , t.computer compend, t.at timend
from @logs t
union all
select step+1 step , r.perstart perstart, r.compstart compstart,r.timestart timestart, convert(nvarchar,r.chain + r.perswait2chain + r.compwait2chain )  chain , convert(varchar(1),t.person) perswait2chain ,convert(varchar(1),t.computer) compwait2chain , t.person persend , t.computer compend, t.at timend
from @logs t
, recurrent_table r
where (
       ( r.persend = t.person  and step%2 = 1 ) or
       ( r.compend = t.computer and step%2 = 0 )
      ) and t.at > r.timend
)
select distinct timestart 'started at' , timend 'ended at', ct.perstart + ct.compstart + ct.chain + ct.perswait2chain + ct.compwait2chain 'chain of events'
from recurrent_table ct
where not exists ( select chain  from recurrent_table rc
where cast (ct.perstart+ct.compstart+ct.chain+ct.persend+ct.compend as nvarchar) = cast (rc.chain+rc.persend+rc.compend as nvarchar)
or
cast (ct.perstart+ct.compstart+ct.chain+ct.perswait2chain+ct.compwait2chain as nvarchar) = cast (rc.chain+rc.perswait2chain+rc.compwait2chain as nvarchar)
or
cast (ct.perstart+ct.compstart+ct.chain+ct.persend+ct.compend as nvarchar) = cast (rc.perstart+rc.compstart+rc.chain as nvarchar)
or
( rc.perswait2chain != '' and cast (ct.perstart+ct.compstart+ct.chain+ct.perswait2chain+ct.compwait2chain as nvarchar) = cast (rc.perstart+rc.compstart+rc.chain as nvarchar) )
)
order by ct.timestart,ct.timend
option ( MAXRECURSION  32767)
;

Just pay attention the first timestamps used for seeding my random generator, differently that the one used for tagging user-machine occurences.


text:
Q: Consulta linq, igualando propiedades Estoy trabajando con Entity Framework code first, estoy armando una consulta pero de mi entidad solo necesito los dos primeros atributos por la cual tuve que crear otra clase con los atributos que necesito para no traerme toda la entidad.
public class Proveedor
{
    public int ProveedorId { get; set; }
    public string RazonSocial { get; set; }
    public string DocumentoIdentidad { get; set; }
    public string Direccion { get; set; }
    public string Fijo { get; set; }
    public string Celular { get; set; }
    public string Representante { get; set; }
    public string Email { get; set; }

    public virtual ICollection<Producto> Productos { get; set; }
    public virtual ICollection<Marca> Marcas { get; set; }
}

Clase extendida
public class ProveedorExtend
{
    public int Id { get; set; }
    public string Descripcion { get; set; }
}

Necesito igualar las propiedades
public IEnumerable<ProveedorExtend> SelectList(int? codigo, string nombre)
    {
        var result = (from p in Context.Proveedores
                      select new ProveedorExtend()
                      {
                          Id = p.ProveedorId,
                          Descripcion = p.RazonSocial
                      })

De tal manera que le pueda aplicar un Where
where ((!codigo.HasValue) || (p.Codigo.Contains(codigo.Value)))
                        && ((nombre == null) || (p.Nombre.Contains(nombre)))
                 select p).ToList();

Como puedo hacer esta query
public List<ProveedorExtend> SelectList(int? codigo, string nombre)
{
    using(DbContext context = new DbContext())
    {
        var result = (from p in context.Proveedores
                     where ((!Id.HasValue) || (p.Id.Contains(Id.Value)))
                            && ((Descripcion == null) || (p.Descripcion.Contains(nombre)))
                     select p).ToList();;

        return result;
    }
}

Pero necesito igualar las entidades antes de hacer esa consulta.
Espero haberme explicado.
La descripción sería: Trato de hacer una consulta que me sirva para dos condiciones mediante esa query puedo preguntar por el id, como puedo preguntar por la descripción, como por ejempo si tengo una tabla que tenga, 1-Juan 2-Miguel 3-Marcos 4- José. Lo que quiero es hacer un like, investigando constains es el que hace un like, pero el problema es que no puedo aplicarle a toda la entidad, si fuera SQL haria una consulta SELECT Id, descripcion FROM Proveedores, .... pero en EF no puedo hacer eso me traeria toda la entidad es por eso que tengo que separala en mi clase ProveedorExtend donde pongo los atributos que necesito pero para que funcione tengo que igualarla a la de Proveedores, en mi Context no me contempla ProveedorExtends no puedo aplicarla directamente.
Quedo la query gracias Leandro y Carlos Muñoz.
public IEnumerable<ProveedorExtend> SelectList(int? codigo, string nombre)
    {
        var result = (from p in Context.Proveedores
                      where ((!codigo.HasValue) || (p.ProveedorId == codigo.Value)) &&
                      ((nombre == null) || (p.RazonSocial.Contains(nombre)))
                      select new ProveedorExtend()
                      {
                          Id = p.ProveedorId,
                          Descripcion = p.RazonSocial
                      }).ToList();
        return result;
    }

A:
Nota: Creo que tienes errores de sintaxis en tu código. Colocaré el código según como parece que debería ser.

Si necesitas convertir Proveedor en ProveedorExtend antes de aplicar el where te recomiendo la sintaxis usando lambdas:
public List<ProveedorExtend> SelectList(int? codigo, string nombre)
{
    using(DbContext context = new DbContext())
    {
        return context.Proveedores
            .Select(p => new ProveedorExtend
            {
                Id = p.ProveedorId,
                Descripcion = p.RazonSocial
            })
            .Where(p =>
                (!codigo.HasValue || p.Id == codigo.Value) &&
                (nombre == null || p.Descripcion.Contains(nombre)
            )
            .ToList();
    }
}

Por otro esto no es necesario puedes aplicar el .Where() a la colección original y luego proyectar sus propiedades en la nueva clase.
public List<ProveedorExtend> SelectList(int? codigo, string nombre)
{
    using(DbContext context = new DbContext())
    {
        return context.Proveedores
            .Where(p =>
                (!codigo.HasValue || p.ProveedorId == codigo.Value) &&
                (nombre == null || p.RazonSocial.Contains(nombre)
            )
            .Select(p => new ProveedorExtend
            {
                Id = p.ProveedorId,
                Descripcion = p.RazonSocial
            })
            .ToList();
    }
}

A: Seria
public List<ProveedorExtend> SelectList(int? codigo, string nombre)
{
    using(DbContext context = new DbContext())
    {
        var result = (from p in context.Proveedores
                     where ((!Id.HasValue) || (p.Id.Contains(Id.Value)))
                            && ((Descripcion == null) || (p.Descripcion.Contains(nombre)))
                     select new ProveedorExtend()
                      {
                          Id = p.ProveedorId,
                          Descripcion = p.RazonSocial
                      }).ToList();;

        return result;
    }
}

como veras en el select defines el new de la clase ProveedorExtend


text:
Q: Python - numpy : 'dimension dependent indexing' I'm seeking for an elegant (and fast) solution to the following problem, simplification of a heavier real situation. The answer might be elsewhere than numpy, I searched and searched...
So, hypothetically, I have:
a = np.array([[2,7],
              [3,6],
              [2,8]])

And let's take a fake data set:
b = np.random.random((3,10))

Rows in array a represent lower and higher indices of the subset of interest in every row of b: "from the first row in b, I'm interested in the subset [2:7], from the second row I'm interested in the subset [3:6], and from the third and last row the subset [2:8]."
My idea for now is to create a kind of mask array c
c = np.array([0,0,1,1,1,1,1,1,0,0],
              [0,0,0,1,1,1,1,0,0,0],
              [0,0,1,1,1,1,1,1,1,0]])

And then I just work on
d = b*c

and elements I'm not interested in are now 0.

*

*How would you produce c using indices in a?

*Would you have a better nice idea?

Proper masked arrays, np.ix_, twisted np.einsum, I couldn't find anything for this purpose. Of course the whole point is to avoid looping, at list in the visible part of my script.. But is it even avoidable in the end?
Thanks a lot!

A: You can create the mask with broadcasting -
n = b.shape[1]
mask = (np.arange(n) >= a[:,None,0]) & (np.arange(n) <= a[:,None,1])
d = mask*b

Sample run -
In [252]: a
Out[252]:
array([[2, 4],
       [3, 6],
       [2, 3]])

In [253]: b
Out[253]:
array([[908, 867, 917, 649, 758, 950, 692],
       [715, 745, 797, 595, 377, 421, 712],
       [213, 143, 169, 825, 858, 780, 176]])

In [254]: n = b.shape[1]
     ...: mask = (np.arange(n) >= a[:,None,0]) & (np.arange(n) <= a[:,None,1])
     ...:

In [255]: mask
Out[255]:
array([[False, False,  True,  True,  True, False, False],
       [False, False, False,  True,  True,  True,  True],
       [False, False,  True,  True, False, False, False]], dtype=bool)

In [256]: mask*b
Out[256]:
array([[  0,   0, 917, 649, 758,   0,   0],
       [  0,   0,   0, 595, 377, 421, 712],
       [  0,   0, 169, 825,   0,   0,   0]])


text:
Q: With @dataclass get a dictionary of the class variable without variable fild(repr=False) I want to get a dictionary from the data class, but without the class variable that has the field parameter repr = False.
from dataclasses import dataclass, field, asdict
@dataclass
class Person:
    name: str
    age: int = field(repr = False)

person = Person(name = 'Max', age=42)
print(asdict(person))

What I get:
{'name': 'Max', 'age': 42}

what I want:
{'name': 'Max'}

My solution was to create new method like:
def dict_without_repr_field(self) -> dict:
    dict_to_show = self.__dict__.copy()
    for key in self.__dict__.keys():
        if not self.__dataclass_fields__[key].repr:
            dict_to_show.pop(key)
    return dict_to_show

Is there a simpler, nicer or better solution?

A: For the most part, you're doing exactly the right thing. Some small improvements can be made to make it a little more idiomatic:
from dataclasses import dataclass, field, asdict

@dataclass
class Person:
    name: str
    age: int = field(repr = False)

    def asdict_considering_repr(self) -> dict:
        return {k: v for k, v in asdict(self).items() if self.__dataclass_fields__[k].repr}

Note that asdict will unroll any nested dataclasses into dictionaries as well. If you don't want that, use vars instead.


text:
Q: Max from each group LINQ I have tried every possible way and looked up everywhere. I am in frustration because this is really silly.  I want max from each group. I have below records.
ID  Custno  paydt                    rcvDt                  Mon    Tue
17  106505  2009-12-31 00:00:00.000 2012-07-11 07:15:04.523 100     3
18  106505  2009-12-31 00:00:00.000 2012-07-11 07:15:04.543 NULL    NULL
19  106505  2010-12-31 00:00:00.000 2012-07-11 07:15:04.747 3       3
20  106505  2011-12-31 00:00:00.000 2012-07-11 07:15:04.827 3       3

result should be group by Custno and paydt and return with max id
ID  Custno  paydt                    rcvDt                  Mon    Tue
18  106505  2009-12-31 00:00:00.000 2012-07-11 07:15:04.543 NULL    NULL
19  106505  2010-12-31 00:00:00.000 2012-07-11 07:15:04.747 3   3
20  106505  2011-12-31 00:00:00.000 2012-07-11 07:15:04.827 3   3

Tried different way and one of them is below
var q = from x in MyTable.ToList()
                        group x by new { x.custno, x.paydt } into g
                        select new MyTable
                        {
                            custno= g.Key.custno,
                            paydt= g.Key.paydt,
                            ID = g.Max(b => b.ID),
                            rcvDt = g.OrderByDescending(a => a.ID).First().rcvDt ,
                            mon = g.OrderByDescending(a => a.ID).First().mon,
                            tue = g.OrderByDescending(a => a.ID).First().tue
                        };

will appreciate help!

A: You can use:
var q = MyTable.GroupBy(x => new {x.custno, x.paydt})
               .Select(g => g.OrderByDescending(i => i.ID).First());

This groups using your same logic.  It performs the same grouping you were using, but then selects, from within each group, the first record after sorting the group by ID descending.

A: try
var q = MyTable.GroupBy(x => new { x.custno, x.paydt }).Max(y=> y.Max(z => z.ID));

it should work.

A: Not sure if its possible to do in a single query, but you always can do it in two steps:
    var maxIds = MyTable.GroupBy(x => new {x.custno, x.paydt}).Select(g => g.Max(i => i.ID));
    var result = MyTable.Where(x => maxIds.Contains(x.ID));


text:
Q: Highlight text in HTML programmatically I have a raw HTML file looks like this (content may change from time to time, all we know that it's a valid HTML file):

Hello World

            This is my paragraph

            another text

When I open it in browser, it's looks like this:

Now, I want to highlight some textual parts within this HTML file.
Let's say that I want to highlight the text: "World This is my paragraph another".
Expected output:

Hello World

            This is my paragraph

            another text

You have:

*

*Raw HTML file (like shown above)

*A sentence that you know for sure that appear within the textual version of the HTML. Note that this sentence can be placed within multiple HTML nodes (like in the example above. Parent nodes: h1, p and div).

*A python script script file to automate the highlighting process.

I though that Regex is good place to start looking for solution. But I got stuck as soon as I enter a scenario that the text is splited with multiple parents. What's more, another elements can be placed between the words (img's for example).
Looking for hint, where to find the solution?

A: Good software for this purpose is [BeautifulSoup].1 Use the replace_with method to replace strings or tags. Use the new_tag method to create a tag to put in place of an existing tag. Begin by making 'soup' of the existing HTML. There are loads of examples of manipulations involving BeautifulSoup all over the 'net.
This sample code shows how to deal with the first occurrence of 'Hello world' in your HTML.
>>> import bs4
>>> soup = bs4.BeautifulSoup(open('temp.htm').read(), 'lxml')
>>> new_h1 = soup.new_tag('h1')
>>> new_h1.string = 'Hello '
>>> mark = soup.new_tag('mark')
>>> mark.string = 'World'
>>> mark
World
>>> new_h1.append(mark)
>>> new_h1

Hello World

>>> h1 = soup.h1
>>> h1.replace_with(new_h1)

Hello World

>>> for line in soup.prettify().split('\n'):
...     line
...
''
' '
'
'
'   Hello'
'   '
'    World'
'   '
'
'
'
'
'   This is my paragraph'
'
'
'
'
'   another text'
'
'
' '
''

A: Maybe I would use beautifulsoup to get all the children in the body tags (let body be the parent) after getting all the NavigableString
https://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#contents this link contain more information.
You can then reconstruct the string (content) with the mark tag  Content  because you can extract the content and tag from beautiful soup and put the reconstructed string back. regex is too much pain
Or you can use do some recursion down the html tree structure (don't do that) regex is a messy solution for sure

A: As a hint:

Step 1 : Replace all tags with % and save the replaced tag in list
s1 = %%%Hello World%%This is my paragraph%%%%another%text%%%
tags = ['',',
,
,
 , ...]

Step 2 : Search the regex in s1
World(\s|%)+This(\s|%)+is(\s|%)+my(\s|%)+paragraph(\s|%)+another

Step 3: Insert  at the beginning of the match and  in the end. for each % group insert  before the group and  in the end of the group.
%%%Hello World%%This is my paragraph%%%%another%text%%%

Step 4: Now, restore the tags from the list using the tag list.

Hello World

This is my paragraph
 ...


text:
Q: How to store data in localStorage using Backbone.js I'm new with backbone.js. How can I store data in my localstorage and retrieve them? I am using jeromegn's Backbone.localStorage but why can't I add or save it into the localstorage?
Here's my collection:
var Cases = Backbone.Collection.extend({
    localStorage: new Backbone.LocalStorage('dataObject'),
});

Here's my view:
var CreateCase = Backbone.View.extend({
    el: '.case',
    render: function(){
        var template = _.template($('#create-case-view').html(), {});
        this.$el.html(template);
    },
    events: {
        'submit #caseForm': 'createCase',
        'click .back': 'returnBack',
        'focus #c_round': 'datePicker'
    },
    createCase: function(e){
        var caseDetails = $(e.currentTarget).serializeObject();
        var cases = new Cases();
        //console.log(caseDetails);
        cases.add(caseDetails, {
            success: function(cases){
                console.log(cases); //I CAN'T ADD/SAVE IT TO THE COLLECTION
                //router.navigate('', {trigger: true});
            }
        });
        return false;
    }
   });

When user submits the form it should be added to the collection.
How can I retrieve it from the collection? I used cases.fetch(); but there's no data.

A: I'm not aware of any version of Backbone which accepts a success callback for the Collection.add function. Based on your code, it looks like you want the Collection.create function instead, which will not only add your model, but also save it (i.e. perform the sync).
var Cases = Backbone.Collection.extend({
    localStorage: new Backbone.LocalStorage('dataObject'),
});

var cases = new Cases();

cases.create({caseNo: 1, caseName: 'another case'}, {
    success: function(caseModel){ // note, this is the model
        console.log(caseModel);
    }
});

See it in action here: https://jsfiddle.net/vbj2ouey/1/
 (due to sandboxing it only worked in JSFiddle)


text:
Q: MySQL database update gives incorrect result I'm trying to update a field which has a foreign key relationship. As User "Fred" has left the company, I need to change the User field to "exEmployee" for all his transactions. So, I use the following in a ColdFusion CFC:
 `UPDATE prodndb.tblReceiptDetails
 SET tblReceiptDetails.UserID = 'exEmployee'
 WHERE BINARY tblReceiptDetails.UserID = '#uName#'`

The variable "uName" is set to "Fred" and the SQL finds several hundred entries changing them to "fred" - NOT "exEmployee" as requested. What am I doing wrong?


text:
Q: How to grab other local tag data in Swift? I am working on saving data process,
because my data is small, so I want to save in local data storage.
I want a make time schedule.
Because I have single 35 buttons and label(each buttons and label are paired), So I am using UIButton tag now. And I have a problem on using other local data "tag".
I tired to make new func on global swift file(same swift file). but it is not able to call tag, because tag is only can use when UIbutton pressed.
I want to use tag property on viewDidLoad(), not only in UIbuttonPressed.
override func viewDidLoad() {
        if let items = UserDefaults.standard.array(forKey: "SubjectList") as? [String] {
            subjectArray = items
            UITextLabel**1**.text = subjectArray**[1-1]**
            }
        }

@IBAction func buttonPressed(_ sender: UIButton) {

        var textField = UITextField()
        let newItem = textField.text!
        if sender.tag == 1{
            self.subjectArray[sender.tag-1] = newItem
            print("1")
        }
UserDefaults.standard.set(self.subjectArray, forKey: "SubjectList")
        }

A: Create outlet collections for all the paired labels and buttons
@IBOutlet weak var allLbls:[UILabel]!
@IBOutlet weak var allBts:[UIButton]!

In viewDidLoad
if let items = UserDefaults.standard.array(forKey: "SubjectList") as? [String] {
   subjectArray = items
   subjectArray.indices?.forEach {
       allLbls[$0].text = subjectArray[$0]
       allBts[$0].tag = $0
   }
}


text:
Q: Can't play wma, wmv or 3gp files Since I installed ubuntu 14.04 I can no longer play wmv, wma or 3gp files with any player ( gxine - vlc - totem - etc.)
I have installed Ubuntu restricted extras and ffmpeg.
My friends, I found the solution, and the solution is remove all gstreamer packages, then reinstall it.

A: I have the same problem with Xubuntu 14.04, too. Solution above didn't work for me. The only workaround I found was to play wmv files using mplayer from terminal (since skinned version fails to load).
Like mplayer [filename]
Hope it helps.
EDIT: found out, that XBMC can play wmv files as well.

A: I had a similar issue.
Deleting the ~/.gstreamer-0.10 solved the issue. You may need to logout and in again.

A: I had same problem with VLC in Ubuntu 14.04 . and solved the problem by:
1] install last ubuntu-restricted-extras -> sudo apt-get install ubuntu-restricted-extras
2] Then upgrade vlc -> sudo apt-get upgrade vlc

A: I had this same problem too, after some search I found this bug report for vlc. I have installed SMPlayer from software center, now I can play those video files without any problem. you can try it too, see if it solve the problem.


text:
Q: scaling svg to parent container I am using svg.js to draw lines on like a canvas. Is it possible to scale the svg element created by calling SVG() to the size of the parent? As of right now, I am just redrawing all the lines when the element resizes.
<div
  ref={r => this.whiteboard = r}
  id="whiteboard"
  >
</div>
{...}
let { offsetWidth: width, offsetHeight: height } = this.whiteboard;
this.draw = SVG('whiteboard').size(width, height);

I am using React which I know will be hard to mix with svg.js but that is another conversation.

A: Use SVG.ViewBox
http://svgjs.dev/geometry/#svg-viewbox
For example, something like:
this.draw = SVG('whiteboard').size(width, height).viewbox(0,0,500,300);

The actual values you pass will depend on what you are drawing, and where it is on the canvas.  The viewBox() parameters are: minX, minY, width, and height.


text:
Q: Find and mirror data from two worksheets I have been struggling with this program for a while I finally gave up and need help.

*

*I have a list of 500 plus values on sheet 1 "Layout", in Table1[Seat Numbers] column. Some cells contain the same values.

*On sheet 2 "SOFTWARE INFO", there is a master list of those values in column A.

*The master list values have other information on the same row, which is what I need on sheet 1.

What I need to do is find matching values on the sheets and copy the row from sheet 2 onto sheet 1 in the corresponding place. I'm at a complete stop with this so any help is greatly appreciated!

A: If the master list is sorted, a call to =VLOOKUP() might work, otherwise try combining INDEX-MATCH, e.g.:
http://www.randomwok.com/excel/how-to-use-index-match/
http://fiveminutelessons.com/learn-microsoft-excel/how-use-index-match-instead-vlookup
which say:

=INDEX ( Column I want a return value from , ( MATCH ( My Lookup Value , Column I want to Lookup against , Enter "0" ))

So you might have as a formula in Sheet 1:
=INDEX(Sheet2!$B$1:$B$10, MATCH(A1, Sheet2!$A$1:$A$10, 1))

Where A1 is your Seat Numbers cell, Sheet2!A is the master list column and Sheet2!B is the other information column. You would fill this formula down.


text:
Q: Javascript does not call function I am trying to make a game that goes from the start screen to the loading screen when the user clicks. I discovered that I can't even call the function.
function startScreen() { // gets called from begining
  // code that works fine
  canvas.addEventListener("click", function(e) {
    loading();
  }, false);
}

The code looks fine but when I run it it does not work. The link to the project is: https://jsfiddle.net/starlite_developer/pqvcL187/783/


text:
Q: flutter - supabase password recover i am trying to implement supabase password recovey for a client . sadly i was unable thus far.
i followed guides provided in web site on this page
then i take a look at guides provided at this repo
but i was unable to make it work .
here is my supabase auth settings

and here is my supabase and supabaseAuth initialization
void main() async {

 WidgetsFlutterBinding.ensureInitialized();

 await Supabase.initialize(
   url: 'SITEURL',
   anonKey:
       'ANONKEY',
       authCallbackUrlHostname: 'ADDITIONAL AUTH CALLBACK REDIRECT'
 );
 //initializing supabaseAuth we use it for password recovery
 await SupabaseAuth.initialize(
   authCallbackUrlHostname: 'ADDITIONAL AUTH CALLBACK REDIRECT ',

 );
 //runnig the app
 runApp(const MyApp());
}

note that by ADDITIONAL AUTH CALLBACK REDIRECT i mean the full (SITEURL + ://reset-callback)
here is my androidManifest.xml  intent
<intent-filter>
              <action android:name="android.intent.action.VIEW" />
              <category android:name="android.intent.category.DEFAULT" />
              <category android:name="android.intent.category.BROWSABLE" />
              <!-- Accepts URIs that begin with YOUR_SCHEME://YOUR_HOST -->
              <data
                android:scheme="SITEURL"
                android:host="//reset-callback" />
            </intent-filter>

in the app i first navigate to a page called AuthPage where there is a button that takes the user to a ResetPage where user enters his email and call resetpassword method
Future<void> resetPassword(String email) async {
    try {
      final response =
          await Supabase.instance.client.auth.api.resetPasswordForEmail(
        'email',
        options: supabase.AuthOptions(
          redirectTo: 'Additional Auth Callback Redirect'
        )
      );

      debugPrint('reset response ${response}');
    } catch (error) {
      message = error.toString();
      debugPrint(message);
    }
  }

which takes the user back to AuthPage in Auth Page i have StreamBuilder which listens to SupabaseAuth.onAuthStateChange and if the chage is passwordRecover it shows a TextField and a button for the user to reset his password implemented like below
StreamBuilder(
          stream: SupabaseAuth.instance.onAuthChange,
          builder: (context, AsyncSnapshot<AuthChangeEvent> snapshot) {
            print('snap shot auth state changed to ${snapshot.data.toString()}');
            if (snapshot.data == AuthChangeEvent.passwordRecovery) {
              return Column(
                children: [
                  const Text('Set New Password'),
                  TextField(
                    controller: controller,
                    decoration: const InputDecoration(
                      filled: true,
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      if (controller.text.isEmpty ||
                          controller.text.length < 8) {
                        return;
                      }
                      Supabase.instance.client.auth
                          .update(
                              UserAttributes(password: controller.text.trim()))
                          .catchError((error) {
                            ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('ERROR : $error')));
                          })
                          .then((value) => Navigator.of(context)
                              .pushReplacement(MaterialPageRoute(
                                  builder: (ctx) => const AuthScreen())));
                    },
                    child: const Text('Submit'),
                  ),
                ],
              );
            } else {
              SomeOtherWidget(),
            }
          })

having done all that problem arises when the i put in my email and when the recovery link is emailed to me it show nothing i opened the link both in my desktop browser and in my emulator browser and even my real phone the response is like below

i am sure that user exist as it is shown in users section in supabase
i dont know what i am doing wrong and i dont know how to proceed with app recognizing type=recovery parameter in url . any help would be much appreciated .

A: I fixed the problem by changing host name turns out I was setting it wrong in manifest and one more thing is that supabase only allows deeplinks with io.supabase.whatever
As host


text:
Q: Search implementation Questions on android I am a newbie here and hope you can help me out to clear some of my understanding (or misunderstanding). I have been reading for days and trying out based on Android guide to implement search function but it really didn't work out well. Perhaps I've got the whole concept wrong so do help me out here if you can be kind.
I have an app which data is from remote xml and I want to implement search function. I have 1 main activity (under my SRC -> my package)that list all the data retrieved from the xml. My questions:
1) In the guide, it saws we must define a .Searchable Activity. I supposed this is to handle the search query and store the result? If this is a case, do I need to create a new activity or I can use my main activity as .Searchable Activity?
2) After the above item is done, I supposed I need to create an activity to receive the result and do something. I take it as I need to create "public class SearchableActivity extends ListActivity" in the activity I define in item 1? The problem is that I don't know what to do with this as the guide are incomplete.
3) Presumingly I did it successfully and upon search, there are some results return, how do I show (or filter to show the search result) in my main activity? I do not want to have another UI to show the result as I prefer it just get filter to show the matched records
4) Lastly, since my data is from remote xml, do I need to "search" based on remote xml or it will search based on cache info on the app?
I am sorry for being so ignorant but I am totally new here and hope you can help me out. So far I have no problem, getting the dialog shown on my action bar. The only problem is that the search didn't work at all :( upon search, there is just nothing happened.
Thanks very much in advance. Cheers!

A: For searching in a list you can use built-in functions of android, but if you want a good result you can use your own function. The simplest function is:
for(int i = 0 ; i < arraylisy.size() ; i++)
{
    if(arraylist.get(i) == youobject)
        return true;
}
return false;

but there are better functions like binary search that you can use.
Now, how to create search activity?
First: create XML file an add a listview in it.
Second: create java file and link xml file to it.
Now use above code to search an object on your list. If in every search you find several items then add them to new listview.
Now create an adapter and send your search list to that.
Finally set your adapter to listview.


text:
Q: Twitter API from_user replacement I have  rails app and i'm using the twitter gem but I can longer use the from_user method in my view as it was removed in V5.
I just want to create a link so someone can go to that tweet on twitter rather then just displaying the text.
Controller
def tweets
   $client.user_timeline("######", :count => 3)
end

View
<% tweets.each do |t| %>

<%= link_to t.text, "http://twitter.com/#{t.from_user}" %>

<% end %>

A: Unless it's been changed which I don't think it has, the gem will provide you with the url of the tweet.
<%= link_to t.text, t.url %>


text:
Q: Picard group of a finite type $\mathbb{Z}$-algebra
Let $A$ be a finitely generated $\mathbb{Z}$-algebra. Is $\operatorname{Pic}(A)$ finitely generated (as an abelian group)?

Thoughts:

*

*We may assume that $A$ is reduced since $\operatorname{Pic}(A) = \operatorname{Pic}(A_{\mathrm{red}})$.

*If $A$ is reduced, then the group of units $A^{\times}$ is a finitely generated abelian group, see e.g. [1, Appendix 1, no. 3] or [4, Théorème 1] (which I learned about through this question).

*The case $A$ is normal is proved in [3, Chapter 2, Theorem 7.6].

*The following argument is from [2, Lemma 9.6]: Let $B$ be the normalization of $A$, set $X := \operatorname{Spec} A$ and $Y := \operatorname{Spec} B$ and let $\pi : Y \to X$ be the normalization morphism. We have the Leray spectral sequence $$ \mathrm{E}_{2}^{p,q} = \mathrm{H}^{p}(X,\mathbf{R}^{q}\pi_{\ast}\mathbb{G}_{m,Y}) \implies \mathrm{H}^{p+q}(Y,\mathbb{G}_{m,Y}) $$ with differentials $\mathrm{E}_{2}^{p,q} \to \mathrm{E}_{2}^{p+2,q-1}$. Since $\pi$ is a finite morphism (e.g. since $\mathbb{Z}$ is Nagata and [5, 030C]), every invertible sheaf on $Y$ can be trivialized on an open cover obtained as the preimage of an open cover of $X$ (e.g. [5, 0BUT]). Hence $\mathbf{R}^{1}\pi_{\ast}\mathbb{G}_{m,Y} = 0$, so we have $\operatorname{Pic}(Y) \simeq \mathrm{H}^{1}(X,\pi_{\ast}\mathbb{G}_{m,Y})$ from the Leray spectral sequence. Set $Q := \pi_{\ast}\mathbb{G}_{m,Y}/\mathbb{G}_{m,X}$; then the long exact sequence in cohomology associated to the sequence $1 \to \mathbb{G}_{m,X} \to \pi_{\ast}\mathbb{G}_{m,Y} \to Q \to 1$ gives an exact sequence $$ \Gamma(Y,\mathbb{G}_{m,Y}) \to \Gamma(X,Q) \stackrel{\partial}{\to} \operatorname{Pic}(X) \to \operatorname{Pic}(Y) $$ where the first and fourth terms are finitely generated. But what can I say about the sheaf $Q$? I know that it is $0$ on a dense open since $\pi$ is an isomorphism on a dense open (e.g. since $A$ is reduced, the regular locus is an open subset containing the generic points [5, 07R5]).

*I should also note that there is a Hartshorne exercise (II, Exercise 6.9) which relates the Picard group of a singular curve (over a field) to that of its normalization.

References:

*

*Bass, Introduction to Introduction to Some Methods of Algebraic K-Theory, Number 20 in CBMS Regional Conference Series in Mathematics. American Mathematical Society, 1974.

*Jaffe, "Coherent functors, with application to torsion in the
Picard group", Transactions of the American Mathematical Society, vol. 349, no. 2, 1997, pp. 481–527 link

*Lang, Fundamentals of Diophantine Geometry, Springer-Verlag (1983)

*Samuel, "A propos du théorème des unités", Bulletin des Sciences
Mathématiques, vol. 90, 1966, pp. 89–96

*Stacks Project link
Keywords: arithmetic scheme, Picard group, finite type $\mathbb{Z}$-algebra

A: Here I write out some details in R. van Dobben de Bruyn's answer. This argument is from p. 5 of these notes by Konrad Voelkel.

Let $R$ be a Noetherian normal domain with $\mathrm{Pic}(R) = 0$. Set \begin{align*} A := R[x,y]/(x^{3} = y^{2}) \end{align*} which is the cuspidal cubic over $R$. Then \begin{align*} \operatorname{Pic}(A) \simeq R \end{align*} as abelian groups.

The normalization of $A$ is \begin{align*} B := R[t] \end{align*} via the $R$-algebra map $A \to B$ sending $(x,y) \mapsto (t^{2},t^{3})$ which identifies $A$ with the subring $R[t^{2},t^{3}]$ of $B$. Let \begin{align*} I := \{a \in A \;:\; aB \subset A\} \end{align*} be the conductor ideal of the inclusion $A \subseteq B$; it is the largest ideal of $B$ contained in $A$. We have \begin{align*} I = \langle x,y \rangle A \end{align*} (for this, use that $A,B$ are $\mathbb{Z}_{\ge 0}$-graded rings and that $A \subset B$ is a graded ring map, hence $I$ is also a graded ideal of $A$; certainly $\langle x,y \rangle A \subset I$ and if $a \in A$ is nonzero then $a \not\in I$ since otherwise $at \in A$). We have a Milnor square  $\require{AMScd}$
\begin{CD}
A @>>> B \\
@VVV @VVV\\
A/I @>>> B/I
\end{CD} where $A/I \simeq R$ and $B/I \simeq R[t]/(t^{2})$. By [Wei13, I, Theorem 3.10] we have an exact sequence \begin{align*} (A/I)^{\times} \oplus B^{\times} \stackrel{\alpha}{\to} (B/I)^{\times} \to \operatorname{Pic}(A) \to \operatorname{Pic}(A/I) \oplus \operatorname{Pic}(B) \end{align*} of abelian groups (the Units-Pic sequence). Here $\operatorname{Pic}(A/I) = \operatorname{Pic}(R) = 0$ and $\operatorname{Pic}(B) \simeq \operatorname{Pic}(R) = 0$ where the first isomorphism follows from e.g. Traverso's theorem [Wei13, I, Theorem 3.11]. We have $(A/I)^{\times} = R^{\times}$ and $B^{\times} = R^{\times}$ (since $R$ is reduced) and $(B/I)^{\times} = (R[t]/(t^{2}))^{\times} \simeq R \oplus R^{\times}$ (where the "$R$" in "$R \oplus R^{\times}$" is viewed as an abelian group under addition). Under these identifications, the map $\alpha$ sends $(u_{1},u_{2}) \mapsto (0,u_{1}u_{2}^{-1})$ so $\operatorname{coker} \alpha \simeq R$.
References:
[Wei13] Weibel, The K-book: An Introduction to Algebraic K-theory, volume 145 of Graduate Studies in Mathematics. American Mathematical Society (2013)

A: This is false. A counterexample is given in [Kahn06, Rmq. 1 (6)].  The example uses the cuspidal cubic $B = A[x^2,x^3]$ over a finite type $\mathbb Z$-algebra $A$ that is not a finitely generated $\mathbb Z$-module. For example, take $A$ to be $\mathbb Z[x]$ or $\mathbb F_p[x]$.
As usual, one shows that (under suitable hypotheses on $A$) there is an isomorphism
$$\operatorname{Pic}(B) \cong \mathbb G_a(A) = A,$$
which shows that $\operatorname{Pic}(B)$ is not finitely generated. (Details omitted, unfortunately also in the paper.)

References.
[Kahn06] Kahn, Bruno, Sur le groupe des classes d'un schéma arithmétique, Bull. Soc. Math. Fr. 134, No. 3, 395–415 (2006). ZBL1222.14048.


text:
Q: Swift3 Cannot assign value of type '()' to type '[Version]' Hello I am having trouble calling my methods to the controller properly as I am getting this error Cannot assign value of type '()' to type '[Version]'. I need help fixing this, thanks.
Swift 3 Method:
var versions : [Version] = []
func isActiveVersion() -> Bool {

    let api = versionAPI()
    versions = api.getVersionFromAPI(completion: ({_ in }))
    for version in versions{
        if version["version"] == "1.0.0" {
            return true

        }
    }
}

Swift 3 Call
public class versionAPI {

var versions : [Version] = []

//---------------------------------
// MARK: ENDPOINTS
//---------------------------------
let getVersionEndPoint = "http://127.0.0.1:3000/api/v1/versions"

//---------------------------------
// MARK: REQUESTS
//---------------------------------

func getVersionFromAPI(completion: @escaping ([Version]) -> Void){
    let url = URL(string: getVersionEndPoint)

    let task = URLSession.shared.dataTask(with: url! as URL) { data, response, error in

        guard let data = data, error == nil else {
            completion([])
            return
        }

        print(NSString(data: data, encoding: String.Encoding.utf8.rawValue)!)
        self.parseVersionsToJSON(data: data)
        completion(self.versions)
    }
    task.resume()
}
func parseVersionsToJSON(data: Data) {

    do {
        self.versions = []
        if let json = try JSONSerialization.jsonObject(with: data) as? [[String:Any]] {
            for dic in json {
                let version = Version()
                version.version = dic["version"] as! String
                version.active =  dic["active"] as! Bool
                self.versions.append(version)
            }
        }
    }
    catch{

    }
  }
 }

A: Your function getVersionFromAPI sets up an asynchronous task and then immediately returns before that task completes, returning void to its caller. This is why you get the error you report.
The [Version] value produced by the asynchronous task is passed by that task to the completion function passed to getVersionFromAPI. The completion function you pass {_ in } does nothing, so the list of versions is simply discarded.
You cannot simply call an asynchronous task, which will complete at some future time, from a synchronous task, getVersionFromAPI in your case, and have that asynchronous task somehow become synchronous and return its future result immediately.
You need to study asynchronous design. Then either redesign your code so the task done by getVersionFromAPI is itself asynchronous, or use one of the standard techniques to block your synchronous method from proceeding until the asynchronous one has completed.
If after revising your design you have trouble with your code ask a new question, showing your code, and someone will undoubtedly help you.
HTH

A: versions = api.getVersionFromAPI(completion: ({_ in }))

getVersionFromAPI does not return anything. Declare a global struct then pass the data into it and use DispatchQueue when finished to post a NotificationCentre
do {
    GlobalStruct.versions = []
    if let json = try JSONSerialization.jsonObject(with: data) as? [[String:Any]] {
        for dic in json {
            let version = Version()
            version.version = dic["version"] as! String
            version.active =  dic["active"] as! Bool
            GlobalStruct.versions.append(version)
        }
        DispatchQueue.main.async {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "gotIt"), object: nil)
        }
    }
}

your Swift 3 ViewController should have the following:
    var versions: [Version] = []

func viewDidLoad() {
    NotificationCenter.default.addObserver(self, selector: #selector(myFunction), name: NSNotification.Name(rawValue: "gotIt"), object: nil)
    let api = versionAPI()
    api.getVersionFromAPI()
    super.viewDidLoad()
}

func myFunction() {
     versions = GlobalStruct.versions
     if isActiveVersion {
           .....
     }
}


text:
Q: Reverse a matrix with tensorflow I'm a Beginner in bigdata.
I had learned Python.
I want get Reverse a matrix with tensorflow (matrix n*n in input), but office boss will to do it with tensorflow, so i wanna do it without Adjoining matrix.
help me, please.
thank you In advance. <3

A: You are (probably) looking for tf.matrix_inverse.

A: You mean you need to swap rows and columns? If that's the case then you might use tf.transpose.


text:
Q: How to get cookie values when it's coming different subdomains? I have a cookie value set in wordpress site and I would need to read this value when the page redirects to the app which is a django backend. How do I retrieve this value in the app?
So this value should persist from www.example.com to app.example.com


text:
Q: Invalid answer while printing child elements from an XML file in JAVA Im trying to get the number of child elements of a parent element from a XML file using JAVA. Here is the code I'm working with:
File fXmlFile = new File("SearchPromotions.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

NodeList l = doc.getElementsByTagName("TestCase");
Node parentNode = l.item(0);
int count = parentNode.getChildNodes().getLength();

System.out.println(count);

And here is the XML file:
<TestCase>
    <SelectedDataTableNames name="SearchData"> </SelectedDataTableNames>

    <Open page="hsbc"  ms="5000"  />
    <Click object="hsbc.Personal_Link"  />
    <Click object="hsbc.CreditCard_tab"  />
    <Call businessComponent="Global.Verify_Search">
       <Param name="HotelName_Param" value="@SearchData_link" />
    </Call>
    <CheckElementPresent object="hsbc.Img_Hotel_logo"  Identifire="Hotel_Name_PARAM:@SearchData_ResultHotelName"  fail="true"  customErrorMessage="Searched hotel name is not present in the page."  />
</TestCase>

The problem im facing is that it is printing a wrong value. The value printed is 13. But as you can see there are only 6 child elements for the parent element "TestCase". Where did i go wrong. Please help

A: public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        String fileContent = readFile("SearchPromotions.xml");// Read trimmed file
        InputStream in = new ByteArrayInputStream(fileContent.getBytes("UTF-8"));// Create stream to pass it to parser()
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(in);

        NodeList l = doc.getElementsByTagName("TestCase");
        Node parentNode = l.item(0);
        int count = parentNode.getChildNodes().getLength();

        System.out.println(count);
    }

    private static String readFile(String pathname) throws IOException {
        File file = new File(pathname);
        StringBuilder fileContents = new StringBuilder((int) file.length());
        Scanner scanner = new Scanner(file);
        try {
            while (scanner.hasNextLine()) {
                fileContents.append(scanner.nextLine().trim()); // Trim the whitespace. This resuls in TEXT_NODE.
            }
            return fileContents.toString();
        } finally {
            scanner.close();
        }
    }

There are some white space charcters in your XML which will result in extra nodes. Try the above solution hope it helps.

A: The children of a node include whitespace text nodes as well as child element nodes.
Why not just do this with XPath - it's so much less hassle!
With Saxon and XPath 2.0 it would be
Processor p = new Processor(false);
XdmNode doc = p.newDocumentBuilder().build(
    new StreamSource(new File("searchPromotions.xml")));
XdmItem result = p.newXPathCompiler().evaluateSingle("/TestCase/count(*)", doc);
System.out.println(result.getStringValue());

A: Found the answer for the question. It works. The problem i had was ELEMENT_NODE. We have to filter ELEMENT_NODE. Here is the working code. Thanks for all those who helped be over there.
File fXmlFile = new File("SearchPromotions.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

Element docEle = doc.getDocumentElement();
NodeList nl = docEle.getChildNodes();
if (nl != null && nl.getLength() > 0) {
      for (int i = 0; i < nl.getLength(); i++) {
           if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element el = (Element) nl.item(i);
                System.out.println(el);
            }
      }
}


text:
Q: how to deal with unamanaged resoures in case of extension class? There are two Classes ClassA and ClassB. ClassB extends ClassA. There are unmanaged resources in ClassA as well as ClassB.
So the question is : should Dispose() method be provided to both of these Classes or Dispose for ClassA will suffice
Edit1:
By the response I have got so far I think my statement has been misunderstood as ClassB inherits from ClassA. What I meant can be understood by visiting following links :

*

*msdn page

*codeproject page

A: You will have to call the base Dispose from the child one. Implementing Dispose in Class B will overwrite the inherited method. This is because methods are virtual by default in C# (if re-implemented in child classes, the re-implementation will be called).
// Class B

public void Dispose()
{
    base.Dispose();

    // Dispose the rest (unmanaged B)
}

A: It depends whether ClassB introduces new disposable resources. If it does, ClassA's Dispose method will not be able to dispose the new resources of ClassB. Use this pattern in ClassA
// In ClassA

public void Dispose()
{
    Dispose(true);

    // Only if you are using a finalizer
    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        // get rid of managed resources
    }
    // get rid of unmanaged resources
}

In ClassB you can override the virtual Dispose(bool disposing) method and do not have to re-implement the IDisposable interface.
// In ClassB

protected override void Dispose(bool disposing)
{
    base.Dispose(disposing);
    if (disposing)
    {
        // get rid of managed resources declared in ClassB
    }
    // get rid of unmanaged resources declared in ClassB
}

A finalizer would call Dispose(false);.


text:
Q: How to retrieve exact urls from a web page via java jsoup I want to extract  urls of images from a web page.
Related section's html format is as following :

and my code is like following :
Document pages = Jsoup.connect(url).get();
System.out.println(""+pages.select("span[style]"));

And the myoutput is containing all html elements  same as the format in above but my desire is to get only url not the whole element like https://theadressofimage.
I also used attr() or absUrl(); but did not help!
How can i get only the url?
Thanks in advance

A: Following code helped to get exactly what i want
package getlink;
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;

public class GetLink {

public static void main(String[] args) throws IOException {

String address = "http://interestedwebaddress/";

URL pageLocation =new URL(address);
Scanner in = new Scanner(pageLocation.openStream());

while (in.hasNext()){
String line = in.next();

if (line.contains("thespecificexpressionthatlinklinecontains")){

int from = line.indexOf("(");
int to = line.lastIndexOf("\"");
System.out.println(line.substring(from +1, to-1)); //-1,+1 my case  specific
}
}
}