text:
Q: Excel: How to copy a row if it contains certain text to another worksheet (VBA) I'm looking to use a marco that would be able to search a column in said sheet and if certain text is found - in my case the word "FAIL" - copy that entire rows data/formatting and paste it into another sheet - sheet 4 in my case - along with any other rows that contained that specific text.

i have been using this code but it only copy pastes one row then stops rather than going through and copying any rows with "FAIL"
Sub Test()
For Each Cell In Sheets(1).Range("H:H")
  If Cell.Value = "FAIL" Then
    matchRow = Cell.Row
    Rows(matchRow & ":" & matchRow).Select
    Rows(matchRow & ":" & matchRow).Select
    Selection.Copy

    Sheets(4).Select
    ActiveSheet.Rows(matchRow).Select
    ActiveSheet.Paste
    Sheets(4).Select
   End If
Next
End Sub

First post and brand new to VBA so apologies if too vague.

A: Try the code below (explanation inside the code as comments):
Option Explicit

Sub Test()

Dim Cell As Range

With Sheets(1)
    ' loop column H untill last cell with value (not entire column)
    For Each Cell In .Range("H1:H" & .Cells(.Rows.Count, "H").End(xlUp).Row)
        If Cell.Value = "FAIL" Then
             ' Copy>>Paste in 1-line (no need to use Select)
            .Rows(Cell.Row).Copy Destination:=Sheets(4).Rows(Cell.Row)
        End If
    Next Cell
End With

End Sub

A: Try like this:
Option Explicit

Sub TestMe()

    Dim Cell As Range
    Dim matchRow As Long

    With Worksheets(1)
        For Each Cell In .Range("H:H")
            If Cell.Value = "FAIL" Then
                matchRow = .Cell.Row
                .Rows(matchRow & ":" & matchRow).Select
                .Rows(matchRow & ":" & matchRow).Select
                Selection.Copy
                Worksheets(4).Select
                Worksheets(4).Rows(matchRow).Select
                Worksheets(4).Paste
                .Select
            End If
        Next
    End With
End Sub

The problem in your code is that you do not reference the worksheets all the time correctly. Thus it does not work correctly.
As a 2. step, you can try to avoid all the selections in your code, it is a best practice to avoid using either Select or Activate in Excel VBA.


text:
Q: Passing SQL variable from one PHP to another PHP I'm creating a website for hotels and foods. The page is for registered members only. So, for unregistered users I created a demo of my site. In that demo, the page will show the hotels name(stored in the DB) as a table in the first page.
When they click the submit button next to the hotel name the next page should show the foods under that hotel name only.
Now, I have a problem. How can I pass the specific hotel id to the next function. Here are my codes, I've tried global, public everything.. nothing is working. I've tried to return that variable also, but there are some echos in my function. So, when I call the function the table is printed again.
I need to pass the $data['id'] to the next function to filter the food table.
Can anybody help me on this please...
First Function:
function print_all_hotels(){

    $result = mysql_query("SELECT * FROM hotels "); // selecting data through mysql_query()
    if (!$result) {
        die("Database query failed: " . mysql_error());
    }
    echo '
';  // opening table tag

    echo'

No.

Name

Details	'; //table headers

    while($data = mysql_fetch_array($result))
    {
        // we are running a while loop to print all the rows in a table
        echo'
'; // printing table row
        echo ''.$data['id'].'	'.$data['h_name'].'	<form action="details.php" method="POST" style="margin-left:-30%; margin-bottom:-5%"><input style=" border:1px solid #000" class="login_submit" type="submit" name="submit" value="View Details!"></form>	'; // we are looping all data to be printed till last row in the table
        echo'
'; // closing table row
    }

    echo '
';  //closing table tag
}

Second Function:
function print_all_foods(){
    $counter =1;

    $result = mysql_query("SELECT * FROM foods where /*Here is the problem*/"); // selecting data through mysql_query()
    if (!$result) {
        die("Database query failed: " . mysql_error());
    }
    echo '
';  // opening table tag

    echo'

No.

Foods	'; //table headers

    while($data = mysql_fetch_array($result))
    {
        // we are running a while loop to print all the rows in a table
        echo'
'; // printing table row
        echo ''.$counter++.'	'.$data['name'].'	'; // we are looping all data to be printed till last row in the table
        echo'
'; // closing table row
    }

    echo '
';  //closing table tag
}

A: Change this line to.
echo ''.$data['id'].'	'.$data['h_name'].'	<form action="details.php" method="POST" style="margin-left:-30%; margin-bottom:-5%"><input type="hidden" value="' . $data['id'] . '" name="hotel_id"><input style=" border:1px solid #000" class="login_submit" type="submit" name="submit" value="View Details!"></form>	'

what is did is i put a hidden field inside the form then add the hotel id there like
<input type="hidden" value="' . $data['id'] . '" name="hotel_id">

then in your php get it like
$hotelId = $_POST["hotel_id"];

A: *

*When outputting the form with submit button in print_all_hotels function, add a hidden field with the id of hotel. Suppose, you called it "id".

*In print_all_foods use $_REQUEST['id'] in SQL query to get the foods for the hotel with this id.
Something like this:
<form action="details.php" method="POST" style="margin-left:-30%; margin-bottom:-5%">
<input type="hidden" name="id" value="<?php print $data['id'] ?>">
<input style=" border:1px solid #000" class="login_submit" type="submit" name="submit" value="View Details!">
</form>

A: let's assume your first function is in the first page called hotels.php. in your form html tag you need to past the id through POST or GET
<form method = "GET" action = "foods.php?id={HOTEL_ID}"></form>

then in your second page(foods.php) you need to retrieve the hotel ID using GET.
e.g.
$hotel_id = $_GET["id"];
$sql = "SELECT * FROM FOODS WHERE id = '$hotel_id'";

Then you can get the hotel id on page submit.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Tastypie foreign key recursive relation loading an internal foreign key In Tastypie I've set up the following recursive / reflective connection:
origin = fields.ToOneField('self', 'origin', null=True, full=True, full_detail=True, full_list=True)

In my application I have a class of type Creation that can be connected to a previous instance / record. I want to retrieve this recursive connection, however the tricky part is that each such creation is connected to a user who created it.
While the line code above works fine, the origin field (which is of type 'Creation') has a reference (using a foreign key) to another table - Users, and I cannot seem to load it. I'm trying to preform this load of a creation including it's origin the the origin creator using a single trip to the database. How can I achieve this?
Thanks


text:
Q: How to make Simplify[] work with substitutions? There is a matrix $M$, and as far as it has quite a complicated form, there are several algebraic equations defining some of its parameters. I try to find the inverse of $M$ and simplify it. Unfortunately, $Mathematica$ gives the answer in the form, differing from the one I want: precisely, it substitutes parameters in the inverse matrix instead of giving the answer in terms of parameters (where it is possible).
Concretely, I have
$$\rho = \sqrt{r^2 + a^2 Cos[\Theta]^2}$$
$$\Delta = r^2 - 2 m r + a^2 + e^2$$
and want the answer to be given in terms of $\Delta$ and $\rho$, where it is possible.
I tried to use $\mathsf{Eliminate[]}$ instead of $\mathsf{FullSimplify[]}$, but did not succeed. Moreover, there is a problem with $\mathsf{Eliminate[]}$: there may be no possibility to fully eliminate the parameters.
Is there any way to make $Mathematica$ work as I want?
EDIT:
I have following problem:
\[Rho] = Sqrt[r^2 + a^2 Cos[\[Theta]]^2];

\[CapitalDelta] = r^2 - 2 m r + a^2 + e^2;

Metric = {{\[Rho]^2, 0, 0, 0}, {0, 0, - a Sin[\[Theta]]^2,
1}, {0, -
  a Sin[\[Theta]]^2, \[Rho]^-2 ((r^2 +
     a^2)^2 - \[CapitalDelta] a^2  Sin[\[Theta]]^2) \
Sin[\[Theta]]^2, - a \[Rho]^-2 (2 m r - e^2) Sin[\[Theta]]^2}, {0,
1, - a \[Rho]^-2 (2 m r -
   e^2) Sin[\[Theta]]^2, -(1 - \[Rho]^-2 (2 m r - e^2))}};

InvMetric = Inverse[Metric] // Simplify // MatrixForm

And what I get is:
,
although I want to get $\rho^{-2}$ instead of (0; 0) entry, for example.

A: The following works for your example:
Simplify[
    InvMetric,
    Cos[2 θ]==2Cos[θ]^2-1 && ρ^2==r^2+a^2 Cos[θ]^2 && Δ==r^2-2 m r+a^2+e^2
] //TeXForm

$\left(
\begin{array}{cccc}
 \frac{1}{\rho ^2} & 0 & 0 & 0 \\
 0 & \frac{\Delta }{\rho ^2} & \frac{a}{\rho ^2} & \frac{a^2+r^2}{\rho ^2} \\
 0 & \frac{a}{\rho ^2} & \frac{\csc ^2(\theta )}{\rho ^2} & \frac{a}{\rho ^2} \\
 0 & \frac{a^2+r^2}{\rho ^2} & \frac{a}{\rho ^2} & \frac{a^2 \sin ^2(\theta )}{\rho ^2}
   \\
\end{array}
\right)$


text:
Q: Best way to run Shell commands on VirtualBox Guest What's the best way to run shell commands on a MacOS guest VM? Can't seem to run it through VirtualBox's guestcontrol, only lets you launch apps, not run commands directly. Saw some people suggest SSH, but wanted to see if there's a more direct way before I start down that path. Thanks!

A: Finally got it working after about 8 hours of trying different things:
VBoxManage guestcontrol "vmname" run /bin/sh --username usr --password pass --verbose --wait-stdout --wait-stderr -- -c "echo test"

Hope this helps someone else!

A: If your guest OS is macOS, try having VBoxManage guestcontrol /bin/bash -c "commandToExecute"
SSH is a perfectly fine solution as long as you have a reliable way to get the IP address and your guest VM exposes SSH, has a key setup, etc.


text:
Q: How to join results of multiple tables in Spring JPA repository I'm new to Spring and I'm unable to figure out how to join multiple tables to return some result. I tried to implement a small Library application as shown below.
My Entity Classes - Book, Customer, Bookings

Book.java - books available in the library
@Entity
@Table(name = "books")
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", columnDefinition = "int")
    private int id;

    @NotNull(message = "Book name cannot be null")
    @Column(name = "book_name", columnDefinition = "VARCHAR(255)")
    private String bookName;

    @Column(name = "author", columnDefinition = "VARCHAR(255)")
    private String author;

    // getters and setters

    public Book() {}

    public Book(String bookName, String author) {
        this.bookName = bookName;
        this.author = author;
    }
}

Customer.java - Customers registered in the library
@Entity
@Table(name = "customer", uniqueConstraints = {@UniqueConstraint(columnNames = {"phone"})})
public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", columnDefinition = "int")
    private int id;

    @NotNull(message = "Customer name cannot be null")
    @Column(name = "name", columnDefinition = "VARCHAR(255)")
    private String name;

    @Column(name = "phone", columnDefinition = "VARCHAR(15)")
    private String phone;

    @Column(name = "registered", columnDefinition = "DATETIME")
    private String registered;

    // getters and setters

    public Customer() {}

    public Customer(String name, String phone, String registered) {
        this.name = name;
        this.phone = phone;
        this.registered = registered;
    }
}

Booking.java - All the bookings made by the customers
@Entity
@Table(name = "bookings")
public class Booking {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", columnDefinition = "int")
    private int id;

    @NotNull(message = "Book id cannot be null")
    @Column(name = "book_id", columnDefinition = "int")
    private int bookId;

    @NotNull(message = "Customer id cannot be null")
    @Column(name = "customer_id", columnDefinition = "int")
    private int customerId;

    @Column(name = "issue_date", columnDefinition = "DATETIME")
    private String issueDate;

    @Column(name = "return_date", columnDefinition = "DATETIME")
    private String returnDate;

    // getters and setters

    public Booking() {}

    public Booking(int bookId, int customerId, String issueDate) {
        this.bookId = bookId;
        this.customerId = customerId;
        this.issueDate = issueDate;
    }
}

Now the table schemas for the respective entities are as follows:

books:
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| book_name | varchar(255) | NO   |     | NULL    |                |
| author    | varchar(255) | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
id - primary key

customer:
+------------+--------------+------+-----+-------------------+-------------------+
| Field      | Type         | Null | Key | Default           | Extra             |
+------------+--------------+------+-----+-------------------+-------------------+
| id         | int(11)      | NO   | PRI | NULL              | auto_increment    |
| name       | varchar(255) | NO   |     | NULL              |                   |
| registered | datetime     | YES  |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
| phone      | varchar(15)  | YES  | UNI | NULL              |                   |
+------------+--------------+------+-----+-------------------+-------------------+
id - primary key

bookings:
+-------------+----------+------+-----+-------------------+-------------------+
| Field       | Type     | Null | Key | Default           | Extra             |
+-------------+----------+------+-----+-------------------+-------------------+
| id          | int(11)  | NO   | PRI | NULL              | auto_increment    |
| book_id     | int(11)  | NO   | MUL | NULL              |                   |
| customer_id | int(11)  | NO   | MUL | NULL              |                   |
| issue_date  | datetime | YES  |     | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
| return_date | datetime | YES  |     | NULL              |                   |
+-------------+----------+------+-----+-------------------+-------------------+
id - primary key
book_id - foreign key references books.id
customer_id - foreign key references customer.id

Now What I want to do is given some booking critieria like customer phone or author name etc., I want to return all the bookings related to that order. I'll show a sample Booking api to explain.
Booking Controller:
@RestController
@RequestMapping("/bookings")
public class BookingController {
    @Autowired
    BookingService bookingService;

    // some booking apis which return Booking objects

    @GetMapping
    public List<Booking> getAllBookingsBy(@RequestParam("phone") String phone,
                                         @RequestParam("authors") List<String> authors) {
        return bookingService.getAllBy(phone, authors);
    }

    @PostMapping
    public Booking addBooking(@RequestBody Booking booking) {
        bookingService.saveBooking(booking);
        return booking;
    }
}

Booking Service class:
@Service
public class BookingService {
    @Autowired
    private BookingRepository bookingRepository;

    // some booking service methods

    // get all bookings booked by a customer with matching phone number and books written by a given list of authors
    public List<Booking> getAllBy(String phone, List<String> authors) {
    return bookingRepository.queryBy(phone, authors);
    }

    public void saveBooking(Booking booking) {
        bookingRepository.save(booking);
    }
}

Booking Repository Class:
@Repository
public interface BookingRepository extends JpaRepository<Booking, Integer> {
    // some booking repository methods

    @Query(value = "SELECT * FROM bookings bs WHERE " +
            "EXISTS (SELECT 1 FROM customer c WHERE bs.customer_id = c.id AND c.phone = :phone) " +
            "AND EXISTS (SELECT 1 FROM books b WHERE b.id = bs.book_id AND b.author IN :authors)",
            nativeQuery = true)
    List<Booking> queryBy(@Param("phone") String phone,
                            @Param("authors") List<String> authors);
}

Now hitting the shown booking controller 'll return a booking object which looks like this :
[
    {
        "id": 3,
        "book_id": 5,
        "customer_id": 2,
        "issue_date": "2019-02-04 01:45:21",
        "return_date": null
    }
]

But I don't want it like that, I want to return along with them the name of the customer for that booking and also the name of the book. So I want the booking objects returned by the controller to look like this:
[
    {
        "id": 3,
        "book_id": 5,
        "customer_id": 2,
        "issue_date": "2019-02-04 01:45:21",
        "return_date": null,
        "customer_name": "Cust 2",
        "book_name": "Book_2_2",
    }
]

Can someone please help in doing this? I'm stuck as I'm unable to proceed from here.
###################
EDIT:
I added these unidirectional one-to-one associations in my Booking class:
@OneToOne
@JoinColumn(name = "book_id", insertable = false, updatable = false)
private Book book;

@OneToOne
@JoinColumn(name = "customer_id", insertable = false, updatable = false)
private Customer customer;

But now when I hit my controller, I get the whole Book and Customer objects in my Booking object. So what can I do to just return the bookname and customer name in the booking object? Here's how my Booking object returned looks like now:
[
    {
        "id": 3,
        "book_id": 5,
        "book": {
            "id": 5,
            "book_name": "Book_2_2",
            "author": "author_2"
        },
        "customer_id": 2,
        "customer": {
            "id": 2,
            "name": "Cust 2",
            "phone": "98765431",
            "registered": "2019-02-04 01:13:16"
        },
        "issue_date": "2019-02-04 01:45:21",
        "return_date": null
    }
]

Also now my save() api in my booking controller isn't working because when I'm sending an object of type Booking to it, the bookId and customerId are somehow turning up as 0, which didn't happen before I added these changes.

A: What you do is wrong. You are returning Booking and you expect that it magicaly deserialize into an entity that contains join information like Book Name. But in your select query on the repository you have selected the Booking. The way things are at  your implementation the Booking does not hold information about the Book.
First you need to separate what you will deserialize as JSON and what you will use as persistence layer towards your spring data.

*

*Make a @OneToOne/@OneToMany relationship from Booking to Book as a start.

*Change your query to do eager fetching on the entity/collection you have mapped as Book.

*Make a POJO and annotate it with JSON annotations the way you want it to be returned by the controller.

*Map between your persistence object / Booking with hidrated collection on Book and your newly created POJO

Actualy if you map as OneToOne the default initialization becomes EAGER so your query becomes a bit unnessesary.
If we presume you have your mappings right in the persistent layer your query will look like this:
@Query(value = "SELECT * FROM bookings bs WHERE " +
            "bs.customer.phone = :phone) " +
            "AND  bs.book.author IN :authors)")

Here is your mapping documentation from Hibernate>
http://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#associations

A: The query that you have is not the best way to join tables.
A more intuitive way is like that
SELECT * FROM bookings
WHERE customer_id in (SELECT id FROM customer WHERE phone = :phone)
 AND book_id in (SELECT id FROM books WHERE author IN :authors)

A: You can implement it as per the below steps.

*

*Create a new interface with the getters for all fields that you need in response.

*In your query string inside @Query, you'll need to provide names to your columns in select. Note: These names need to be in sync with the getters you create in your interface.

*Use this interface as a return type of you repository method.

For more info, you can refer Projections in spring data rest.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections


text:
Q: Macro defined when targeting iOS Is there a macro defined when compiling for iOS ?
I found __APPLE__ but I need a macro defined only when targeting iOS.
In a broader view, I'm unable to find a web page describing those macro for Xcode, is there any ?

A: You could probably use one of the macros in TargetConditionals.h
#if TARGET_OS_IPHONE
        // do iPhone work
#endif

#if TARGET_IPHONE_SIMULATOR
        // do iPhone simulator work
#endif

#if TARGET_OS_MAC
        // do Mac work
#endif

A: define TARGET_OS_IPHONE
define TARGET_IPHONE_SIMULATOR
Found in TargetConditionals.h


text:
Q: PDO I can't get the title to show in the select tag from a query made in php I'm trying to get the select tag to show the titles of the posts that are in the DB so i can select them individually and up date them instead of updating all the titles with the same name.
So my problem is that i can't get it to work and maybe someone may be able to help me.
This is what i mean->https://imgur.com/a/ie1g4hF
if you want the full version you can get it from my github:
https://github.com/TwistedZebra/blog
That version up there does not contain the select tags but uses a text box to delete the post that is named but with a disadvantage of deleten every post named the same.
<?php
    require 'config.php';

    if (isset($_POST['submit'])) {
        $updatetitle = $_POST['updatetitle'];
        $title = $_POST['title'];
        $content = $_POST['content'];

        if (empty($title) || empty($content)) {
            header('Location: update.php?=error');
            exit();
        } else {
            $updatedcontent = $connection->prepare('UPDATE posts SET title = :title , content = :content WHERE title = :updatetitle');
            $updatedcontent->execute(['title' => $title, 'content'=> $content, 'updatetitle' => $updatetitle]);
            header('Location: update.php?=success');
        }

    }
 ?>

 <!DOCTYPE html>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="public/css/main.css">
    <title>Control panel</title>

BloggerWorld

                Home

                Posts

                Admin Panel

Update post

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

                <select name="delTitle" class="form-control">
                    <?php foreach ($updatedcontent as $update) { ?>
                    <option><?php echo $post['title'];  ?></option>;
                    <?php } ?>
                </select>

                <input type="text" name="title" class="form-control" placeholder="New title" >

                <textarea name="content" rows="5" cols="60"  class="form-control" placeholder="Enter post"></textarea>

                <button type="submit" name="submit" class="btn btn-success">Update post</button>
            </form>

  enter code here


text:
Q: Buffer() is deprecated due to security and usability issues I want to run a Discord bot, but this code is using Buffer and it keeps producing an error for this code:
const app = express();

app.get("/", (req,res) => {
    if((new Buffer(req.query.key, "base64")).toString("utf-8") == key && req.query.message) {
        let message = (new Buffer(req.query.message, "base64")).toString("utf-8");
        onWebhookMessage(message);
    }
})

app.listen(3000);

module.exports = {getClient:function(){return client;}};

And this is the error:
(node:600332) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
    at Function.from (buffer.js:330:9)
    at new Buffer (buffer.js:286:17)
    at /root/bot/index.js:182:9
    at Layer.handle [as handle_request] (/root/bot/node_modules/express/lib/router/layer.js:95:5)
    at next (/root/bot/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/root/bot/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/root/bot/node_modules/express/lib/router/layer.js:95:5)
    at /root/bot/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/root/bot/node_modules/express/lib/router/index.js:335:12)
    at next (/root/bot/node_modules/express/lib/router/index.js:275:10)

I've changed new Buffer() to Buffer.from() and it's not working. It produces this error:
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
    at Function.from (buffer.js:330:9)
    at /root/bot/index.js:182:17
    at Layer.handle [as handle_request] (/root/bot/node_modules/express/lib/router/layer.js:95:5)
    at next (/root/bot/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/root/bot/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/root/bot/node_modules/express/lib/router/layer.js:95:5)
    at /root/bot/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/root/bot/node_modules/express/lib/router/index.js:335:12)
    at next (/root/bot/node_modules/express/lib/router/index.js:275:10)
    at expressInit (/root/bot/node_modules/express/lib/middleware/init.js:40:5)

I've updated Node.js (NPM not Yarn) to the latest version and the buffers too but still the same. Does anyone know how to fix this? Thank you!

A: You're not checking whether req.query.key is actually a string. Your error reports you're doing Buffer.from(undefined), which would happen if req.query.key is undefined.
Assuming that key should be a string, you can simply compare it directly. Therefore, something like this should be fine for your use case:
if (req.query.key === key && typeof req.query.message === 'string') {

You don't even need to use Buffer here anymore, since Buffer.from(str).toString('utf-8') === str, as utf8 is the default encoding.


text:
Q: How to get the Image of dynamic picturebox in flowLayoutPanel This is how I open a multiple pictures and set to flowLyaoutPanel
DialogResult dr = this.openFileDialog.ShowDialog();
        if (dr == System.Windows.Forms.DialogResult.OK)
        {
            // Read the files
            foreach (String file in openFileDialog.FileNames)
            {
                // Create a PictureBox.
                try
                {
                    PictureBox pb = new PictureBox();
                    Image loadedImage = Image.FromFile(file);
                    pb.Height = loadedImage.Height;
                    pb.Width = loadedImage.Width;
                    pb.Image = loadedImage;
                    flowLayoutPanel1.Controls.Add(pb);
                }
                catch (SecurityException ex)
                {

                    MessageBox.Show("Security error. Please contact your administrator for details.\n\n" +
                        "Error message: " + ex.Message + "\n\n" +
                        "Details (send to Support):\n\n" + ex.StackTrace
                    );
                }
                catch (Exception ex)
                {

                    MessageBox.Show("Cannot display the image: " + file.Substring(file.LastIndexOf('\\'))
                        + ". You may not have permission to read the file, or " +
                        "it may be corrupt.\n\nReported error: " + ex.Message);
                }
            }
        }

This is where Im stuck, I need to get the Image in every picturebox by use of looping
foreach (Control ctrl in flowLayoutPanel1.Controls) {
            if (ctrl is PictureBox) {

                //problem goes here
                Image img = (PictureBox)ctrl.Image;

                byte[] arr;
                ImageConverter converter = new ImageConverter();
                arr = (byte[])converter.ConvertTo(img, typeof(byte[]));
            }
        }

Is there a way to cast the control to picturebox?

A: Use OfType<T> to filter a collection down by the type.
using System.Linq;
...
foreach (PictureBox pictureBox in flowLayoutPanel1.Controls.OfType<PictureBox>())
{
    Image img = pictureBox.Image;

    byte[] arr;
    ImageConverter converter = new ImageConverter();
    arr = (byte[])converter.ConvertTo(img, typeof(byte[]));
}


text:
Q: How to get a Header from xls/xlsx in JavaScript or jQuery? How to get only header values from the xls/xlsx file in JavaScript or jQuery without parsing the whole file?. XLSX.read(data, { type: 'binary' });   taking too much time for parsing. But I need only headers on browser side. I'll do the rest on server-side. Thank you.

A: var url = "your excel file.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
  var arraybuffer = oReq.response;
  var data = new Uint8Array(arraybuffer);
  var arr = new Array();
  for(var i = 0; i != data.length; ++i) {
    arr[i] = String.fromCharCode(data[i]);
  }
  var bstr = arr.join("");
  var workbook = XLSX.read(bstr, {type:"binary"});
  var t = workbook.SheetNames;
}
oReq.send();


text:
Q: How do I use the OneDrive API to upload a file and also check if the file already exists I have to upload a file to OneDrive, sometimes small files, sometimes larger files. This Service should run in the background so i have to check, if the file already exists, and if it already exists, add a timestamp to the filename, or in some cases don't even upload a new version.
I cant just install the OneDrive App and copy to a linked Folder. I have to use the API which requires a clientID etc.
Maybe someone could help me out with this.
Thank you alot


text:
Q: Using Twisted AMP with Database insertion I am learning how to use Twisted AMP.  I am developing a program that sends data from a client to a server and inserts the data in a SQLite3 DB. The server then sends back a result to the client which indicates success or error (try and except might not be the best way to do this but it is only a temporary solution while I work out the main problem). In order to do this I modified an example I found that originally did a sum and returned the result, so I realize that this might not be the most efficient way to do what I am trying to do. In particular I am trying to do some timings on multiple insertions (i.e. send the data to the server multiple times for multiple insertions) and I have included the code I have written. It works but clearly it is not a good way to send multiple data for insertion since I am performing multiple connections before running the reactor.
I have tried several ways to get around this including passing the ClientCreator to  reactor.callWhenRunning() but you cannot do this with a deferred.
Any suggestions, advice or help with how to do this would be much appreciated. Here is the code.
Server:
from twisted.protocols import amp
from twisted.internet import reactor
from twisted.internet.protocol import Factory
import sqlite3, time

class Insert(amp.Command):
    arguments = [('data', amp.Integer())]
    response = [('insert_result', amp.Integer())]

class Protocol(amp.AMP):
    def __init__(self):
       self.conn = sqlite3.connect('biomed1.db')
       self.c =self.conn.cursor()
       self.res=None

    @Insert.responder
    def dbInsert(self, data):
        self.InsertDB(data) #call the DB inserter
        result=self.res     # send back the result of the insertion
        return {'insert_result': result}

    def InsertDB(self,data):
      tm=time.time()
      print "insert time:",tm
      chx=data
      PID=2
      device_ID=5
      try:
        self.c.execute("INSERT INTO btdata4(co2_data, patient_Id, sensor_Id) VALUES ('%s','%s','%s')" % (chx, PID, device_ID))
      except Exception, err:
             print err
             self.res=0
      else:
             self.res=1

      self.conn.commit()

pf = Factory()
pf.protocol = Protocol
reactor.listenTCP(1234, pf)
reactor.run()

Client:
from twisted.internet import reactor
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
import time

class Insert(amp.Command):
    arguments = [('data', amp.Integer())]
    response = [('insert_result', amp.Integer())]

def connected(protocol):
    return protocol.callRemote(Insert, data=5555).addCallback(gotResult)

def gotResult(result):
    print 'insert_result:', result['insert_result']
    tm=time.time()
    print "stop", tm

def error(reason):
    print "error", reason

tm=time.time()
print "start",tm
for i in range (10): #send data over ten times
  ClientCreator(reactor, amp.AMP).connectTCP(
     '127.0.0.1', 1234).addCallback(connected).addErrback(error)

reactor.run()

End of Code.
Thank you.

A: Few things which will improve your Server code.
First and foremost: The use of direct database access functions is discouraged in twisted, as they normally causes block. Twisted has nice abstraction for database access which provides twisted approach to db connection - twisted.adbapi
Now on to reuse of db connection: If you want to reuse certain assets (like database connection) across a number of Protocol instances, you should initialize those in constructor of Factory or if you dont fancy initiating such things at a launch time, create an resource access method, which will initiate resource upon first method call then assign it to class variable and return that on subsequent calls.
When Factory creates a specific Protocol intance, it will add a reference to itself inside the protocol, see line 97 of twisted.internet.protocol
Then within your Protocol instance, you can access shared database connection instance like:
self.factory.whatever_name_for_db_connection.doSomething()

Reworked Server code (I dont have python, twisted or even decent IDE available, so this is pretty much untested, some errors are to be expected)
from twisted.protocols import amp
from twisted.internet import reactor
from twisted.internet.protocol import Factory
import time

class AMPDBAccessProtocolFactory(Factory):
    def getDBConnection(self):
        if 'dbConnection' in dir(self):
            return self.dbConnection
        else:
            self.dbConnection = SQLLiteTestConnection(self.dbURL)
            return self.dbConnection

class SQLLiteTestConnection(object):
    """
    Provides abstraction for database access and some business functions.
    """
    def __init__(self,dbURL):
        self.dbPool =  adbapi.ConnectionPool("sqlite3" , dbURL,  check_same_thread=False)

    def insertBTData4(self,data):
        query = "INSERT INTO btdata4(co2_data, patient_Id, sensor_Id) VALUES (%s,%s,%s)"
        tm=time.time()
        print "insert time:",tm
        chx=data
        PID=2
        device_ID=5
        dF = self.dbPool.runQuery(query,(chx, PID, device_ID))
        dF.addCallback(self.onQuerySuccess,insert_data=data)
        return dF
    def onQuerySuccess(self,insert_data,*r):
        """
        Here you can inspect query results or add any other valuable information to be parsed at client.
        For the test sake we will just return True to a customer if query was a success.
        original data available at kw argument insert_data
        """
        return True

class Insert(amp.Command):
    arguments = [('data', amp.Integer())]
    response = [('insert_result', amp.Integer())]

class MyAMPProtocol(amp.AMP):

    @Insert.responder
    def dbInsert(self, data):
        db = self.factory.getDBConnection()
        dF = db.insertBTData4(data)
        dF.addErrback(self.onInsertError,data)
        return dF

    def onInsertError(self, error, data):
        """
        Here you could do some additional error checking or inspect data
        which was handed for insert here. For now we will just throw the same exception again
        so that the client gets notified
        """
        raise error

if __name__=='__main__':
    pf = AMPDBAccessProtocolFactory()
    pf.protocol = MyAMPProtocol
    pf.dbURL='biomed1.db'
    reactor.listenTCP(1234, pf)
    reactor.run()

Now on to the client. IF AMP follows the overall RPC logic (cant test it currently) it should be able to peruse the same connection across a number of calls. So I have created a ServerProxy class which will hold that perusable protocol instance and provide abstraction for calls:
from twisted.internet import reactor
from twisted.internet.protocol import ClientCreator
from twisted.protocols import amp
import time

class Insert(amp.Command):
    arguments = [('data', amp.Integer())]
    response = [('insert_result', amp.Integer())]

class ServerProxy(object):
    def connected(self,protocol):
        self.serverProxy = protocol # assign protocol as instance variable
        reactor.callLater(5,self.startMultipleInsert) #after five seconds start multiple insert procedure

    def remote_insert(self,data):
        return self.serverProxy.callRemote(Insert, data)

    def startMultipleInsert(self):
        for i in range (10): #send data over ten times
            dF = self.remote_insert(i)
            dF.addCallback(self.gotInsertResult)
            dF.addErrback(error)

    def gotInsertResult(self,result):
        print 'insert_result:', str(result)
        tm=time.time()
        print "stop", tm

def error(reason):
    print "error", reason

def main():
    tm=time.time()
    print "start",tm
    serverProxy = ServerProxy()
    ClientCreator(reactor, amp.AMP).connectTCP('127.0.0.1', 1234).addCallback(serverProxy.connected).addErrback(error)
    reactor.run()

if __name__=='__main__':
    main()


text:
Q: Why is an error not produced when following the Recess 'Controlling the Controller' doc? According to the section 'The Controller-View Relationship' located in http://www.recessframework.org/page/controlling-the-controller :

Try removing the body of the printIt method and refresh to get an error indicating no view template at 'helloWorld/views/printIt.php' can be found.

I tried this and upon refreshing the page, saw []. I checked the response header and it was of type application/json. Could this have something to do with it? I've tried installing Recess on another machine and it resulted in the same behavior.
Can someone tell me how to get an error???


text:
Q: on click for dynamically assigned variable in jQuery I'm fairly new to js and jquery and have been struggling with some code for quite awhile now.  I see some similar questions posted but when I try to implement the solutions I still do not get the behavior I want.
The tweets are loaded, some have urls in them others do not.  If a user clicks on a url in a tweet I want it to open in a new window.  I'm pretty sure something is going on with the onclick function (maybe not being assigned to the variable correctly?) because if I remove the onclick a new window is opened for every url that is brought in.
First, I create the link variable and pull out the rest of the text so I can append the url as a hyperlink.  If the user clicks on the url I want to open the variable link1 (which I've pulled from directly from the api) in a new window.
           var link="";
           if(tweet.entities.urls[0]!=null){
            if(tweet.entities.urls[0].url!=null){
                var link1=tweet.entities.urls[0].url;
                link=replaceLinks(link1);
                $('link').live('click', function(){
                    window.open(link1);
                });
        }
        }
           if(tweet.geo==null){
                $("#geo").append('
'+tweet.text+link+'
');
          }

The $('link').live('click', function(){ line is the last method I tried, though I've tried numerous other onclick assignments.  I've been testing this in firefox and using aptana in case that matters.  I would include more code but after lots of testing I really think the problem(s) are in the lines I've included, though I will gladly include more if this isn't enough to determine the problem.  This is my first web app so if I'm doing something very obviously wrong kindly let me know what it is?!  Thanks so much!

A: I am confused about what is the id of your link. You have quotes around your link variable, if it is supposed to contain the link id then it should be like this:
$(link).live('click', function(){
    window.open(link1);
});

If link is the actual id or a class of your link then it should be like this:
$('#link').live('click', function(){ // id
$('.link').live('click', function(){ // class

Edit:
Also to note, depending on the version of jQuery you are using, live() is deprecated and should be replace by on()
$(selector).on('click', function(){
    window.open(link1);
});


text:
Q: ¿Es posible ejecutar un servlet desde una clase Thread? Estoy haciendo una aplicación web con JSP. Esta aplicación tiene que mostrar el resultado de una consulta en una tabla. La dificultad es que esta se tiene que mostrar cuando se abre la aplicación (url), sin presionar ningún botón.
Pensé en hacer un Thread que se ejecute cada n tiempo y este llamase al servlet (controlador) para que realice lo demas (intancie la clase en la que esta la consulta a la base de datos y entregue los datos al jsp), pero en realidad no se si eso se puede hacer o si existe otra forma mas óptima de hacerlo.

A: No es una buena idea, crear Threads para organizar la ejecución del código de una aplicación web es responsabilidad del contenedor, e.g. Tomcat.
Lo que puedes hacer es registrar tu servlet en web.xml para que escuche en una URL específica:
<servlet>
    <servlet-name>MiServlet</servlet-name>  // nombre del servlet
    <servlet-class>EsteEsMiServlet</servlet-class>  // clase del servlet
</servlet>
<servlet-mapping>
    <servlet-name>MiServlet</servlet-name>   // nombre del servlet
    <url-pattern>/ruta</url-pattern>  // URL asignada al servlet
</servlet-mapping>

De esta forma cada que entras a /ruta el servlet se va a ejecutar, sin necesidad de presionar un botón u otra acción del usuario, siempre que el servlet sobrescriba el método doGet.

A: Te recomiendo tener un Servlet que provea la información que necesitas vía JSON y hacer polling desde tu vista mediante Ajax para refrescar el contenido.
Te dejo un ejemplo de ambos.
Servlet que soporte llamadas ajax (puede ser cualquier servlet en realidad, el nombre es solo como demostración):
@WebServlet("/ajax/ajaxServlet")
public class AjaxServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        DataService dataService = new DataService();
        //método que obtiene los datos desde base de datos u otro
        List<Data> dataList = dataService.getData();
        //Obtenemos el escritor de la respuesta
        //para escribir el contenido de la respuesta manualmente
        Writer writer = response.getWriter();
        //escribimos los datos de la variable data como JSON
        writer.write(codificaEnJson(dataList));
    }

    private String codificaEnJson(Object o) {
        //código para codificar un objeto como JSON...
    }
}

Página web que realiza llamadas ajax utilizando poll mediante setTimeout:
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Uso de ajax</title>
    <!--
        Se asume que tienes jquery en tu proyecto
        y se encuentra en una ruta como
        Web Resources/js/jquery.js
        Cambia la ruta adecuadamente
    -->
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
</head>
<body>
    <script type="text/javascript">
        //función que hace poll
        (function poll() {
           //se llama a Timeout para ejecutar una acción
           //cada
           setTimeout(function() {
              $.ajax({
                 url: "${pageContext.request.contextPath}/ajax/ajaxServlet", //URL del servlet
                 success: function(data) {
                    //función para armar la tabla desde los valores
                 },
                 dataType: "json",
                 complete: poll //al finalizar, se vuelve a llamar a la función poll de manera que es eterno
              });
           }, 30000); //se ejecuta cada 30 segundos, puedes configurarlo al tiempo que requieras
        })();
    </script>

    <!-- la tabla vacía, lista para recibir los datos desde el JSON -->
    <table id="tabla">
    </table>
</body>
</html>

Para convertir un objeto a JSON, puedes utilizar Jackson o Gson. Aquí un ejemplo de cómo hacerlo con Jackson:
private String codificaEnJson(Object o) {
    //código para codificar un objeto como JSON...
    return mapper.writeValueAsString(o);
}

ObjectMapper mapper;

public void init(ServletConfig config)
      throws ServletException {
    mapper = new ObjectMapper();
}


text:
Q: How to select 3 columns and get data from MySQL table? I want to select 3 columns and want to retrieve data from the MySQL table. All the columns exist on a single table called orderTable.  Please check what I am doing:
SELECT * FROM `orderTable` WHERE shipped = 0, reject_order = 0 AND customer_id = '26898'

Kindly suggest what I am doing wrong.

A: You are using a comma instead of AND or OR condition. See the right query
SELECT * FROM `orderTable` WHERE shipped = 0 AND reject_order = 0 AND customer_id = '26898'

or
SELECT * FROM `orderTable` WHERE shipped = 0 OR reject_order = 0 AND customer_id = '26898'

You should choose one of above based on your requirement


text:
Q: Select dynamic DOM Elements in d3 I am trying to draw shapes and select and interact with them using D3. I am learning D3, so need to understand some logic more clearly.
I can draw shapes, I need to drag them while selecting a shape. I cannot seem to select the particular object when there are multiple objects drawn on canvas.
http://jsfiddle.net/nilarya/WKa8F/2/ this is where I have been so far, I request you to take a look at it,(the code is somewhat messy, I'm sorry, its late in here... :() if you draw multiple objects (Circles and/or Rectangles) on the canvas and then try to select one, you will notice the error.
I have tried using
d3.select(this)

and also
d3.select(this.firstChild)

but I need to select a particular circle or rectangle. how do I do this?

A: Update your dragmove listener to handle only the selected shape, i.e. the shape to which this listener is binded to.
All you'll have to do is assign the selection of this by D3 to a variable, and use that instead of the external references, like so:
function dragmove(d) {
    var shape = d3.select(this);
    if (isrectMov == true) {
        shape.attr("x", d3.event.x)
            .attr("y", d3.event.y)
            .attr("cursor", "move");
    } else if (islineMov == true) {
        shape.attr("x1", d3.event.x)
            .attr("y1", d3.event.y)
            .attr("x2", d3.event.x)
            .attr("y2", d3.event.y)
            .attr("cursor", "move");
    } else if (iscircleMov == true) {
        shape.attr("cx", d3.event.x)
            .attr("cy", d3.event.y)
            .attr("cursor", "move");
    } else {}
}

However, this will work only for similar shapes, the code has some more issues that needs to be addressed. I suggest you start from scratch, and try not to use global variables at all, but instead require (or select) any shape when you need it (e.g. inside a handler). This will reduce complexity as you no longer have to try to follow the state of each variable in your minds eyes.

 Demo


text:
Q: MODULE_NOT_FOUND error - Not able to run the node js application with sqlite3 in the docker container I facing this below error while running my nodejs-16 application using docker. I started facing this issue after I update my node from v14 to v16. I googled but couldn't understand.
Can someone throw me light on what can be the fix for this?
Error: Cannot find module '/usr/src/app/node_modules/sqlite3/lib/binding/napi-v6-linux-glibc-x64/node_sqlite3.node'
Require stack:
- /usr/src/app/node_modules/sqlite3/lib/sqlite3-binding.js
- /usr/src/app/node_modules/sqlite3/lib/sqlite3.js
- /usr/src/app/build/entity/data-service/sqlite.helper.js
- /usr/src/app/build/entity/data-service/dataservice.controller.js
- /usr/src/app/build/route.js
- /usr/src/app/build/index.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:985:15)
    at Function.Module._load (node:internal/modules/cjs/loader:833:27)
    at Module.require (node:internal/modules/cjs/loader:1057:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (/usr/src/app/node_modules/sqlite3/lib/sqlite3-binding.js:4:17)
    at Module._compile (node:internal/modules/cjs/loader:1155:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
    at Module.load (node:internal/modules/cjs/loader:1033:32)
    at Function.Module._load (node:internal/modules/cjs/loader:868:12)
    at Module.require (node:internal/modules/cjs/loader:1057:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/usr/src/app/node_modules/sqlite3/lib/sqlite3-binding.js',
    '/usr/src/app/node_modules/sqlite3/lib/sqlite3.js',
    '/usr/src/app/build/entity/data-service/sqlite.helper.js',
    '/usr/src/app/build/entity/data-service/dataservice.controller.js',
    '/usr/src/app/build/route.js',
    '/usr/src/app/build/index.js'

Here is my docker file
FROM node:16-alpine AS builder
RUN mkdir -p /myloc/usr/src/app
WORKDIR /myloc/usr/src/app

COPY package.json ./
#build all the local images in the base node container
RUN npm install
COPY . .

RUN npm run build
#RUN npm run test

FROM node:16-slim
RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app
COPY --from=builder /myloc/usr/src/app .

# Add user nodejsuser
RUN groupadd --gid 2000 nodejsuser \
  && useradd --uid 1300 --gid nodejsuser --shell /bin/bash --create-home nodejsuser
RUN chown -R nodejsuser:nodejsuser /usr/src/app

USER nodejsuser
EXPOSE 4000

EXPOSE 3000

CMD ["npm", "start"]

The image is successfully built but when I run the container, I'm seeing this issue.


text:
Q: perl retrieving page details after mechanize::POST I am trying to gather data from a website. Some anti-patterns make looking finding the right form objects difficult but I have this solved. I am using a post method to get around some javascript acting as a wrapper to submit the form. My problem seems to be in getting the results from the mechanize->post method.
Here's a shortened version of my code.
use strict;
use warnings;
use HTML::Tree;
use LWP::Simple;
use WWW::Mechanize;
use HTTP::Request::Common;
use Data::Dumper;
$| = 1;

my $site_url = "http://someURL";
my $mech = WWW::Mechanize->new( autocheck => 1 );
foreach my $number (@numbers)
{
    my $content = get($site_url);
       $mech->get ($site_url);

    my $tree = HTML::Tree->new();

    $tree->parse($content);

    my ($title) = $tree->look_down( '_tag' , 'a' );
    my $atag = "";
    my $atag1 = "";
    foreach $atag ( $tree->look_down( _tag => q{a}, 'class' => 'button', 'title' => 'SEARCH'     )  )
    {
        print "Tag is ", $atag->attr('id'), "\n";
        $atag1 = Dumper $atag->attr('id');
    }

# Enter permit number in "Number" search field
    my @forms = $mech->forms;
    my @fields = ();
    foreach my $form (@forms)
    {
        @fields = $form->param;
    }
    my ($name, $fnumber) = $fields[2];
    print "field name and number is $name\n";
    $mech->field( $name, $number, $fnumber );
    print "field $name populated with search data $number\n" if $mech->success();

    $mech->post($site_url ,
    [
       '$atag1' => $number,
       'internal.wdk.wdkCommand' => $atag1,
    ]) ;

print $mech->content; # I think this is where the problem is.

}
The data I get from my final print statement is the data from teh original URL not the page the POST command should take me to. What have I done wrong?
Many Thanks
Update
I don't have Firefox installed so I'm avoiding WWW::Mechanize::Firefox intentionally.

A: Turns out I was excluding some required hidden fields from my POST command.


text:
Q: Adding an Image into a cell I have read heaps of questions but can't seem to find the answer
I have a TableView but can't add a image to my cell
cell.imageView.image = UIImage(named: "osx_design_view_messages")

This code should work because I basically copied it from a answer to a question but for some reason it isn't working. Any suggestions?
Im using swift by the way
 override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    let cellIdentifier = "cell"

    var cell : UITableViewCell

    cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell
    cell.textLabel.text = self.recipies[indexPath.row]
    var image : UIImage = UIImage(named: "osx_design_view_messages")
    return cell
}

A: Here are a few possible causes of your issue:

*

*The cell prototype needs to include a UIImageView. If you're using a storyboard select the cell prototype and make sure its style is set to "Basic" in the attributes inspector (right panel).

*The cell identifier doesn't match the identifier typed in for your prototype cell in your storyboard. Make sure that "cell" is entered for "Identifier" also in the attributes inspector.

*The image is not loading from file properly. To test this, add the following line after initializing your image:
println("The loaded image: \(image)")
After checking that everything is set in your storyboard, try running it using this code:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    {
        let cellIdentifier = "cell"

        var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell

        cell.textLabel.text = self.recipes[indexPath.row]

        var image : UIImage = UIImage(named: "osx_design_view_messages")
        println("The loaded image: \(image)")
        cell.imageView.image = image

        return cell
    }

A: Swift 3
// we are using this if your images are at server.
// we are getting images from a url.
// you can set image from your Xcode.
// it's doing using assign a tag to imageView

*

*The URL of images are in an array name = thumbnail i.e self.thumbnail[indexPath.row]

*on UITableviewCell put a imageView on cell

*select UIimageView assign it a tag from storyboard.
let pictureURL = URL(string: self.thumbnail[indexPath.row])!
let pictureData = NSData(contentsOf: pictureURL as URL)
let catPicture = UIImage(data: pictureData as! Data)
var imageV = UIImageView()
imageV = cell?.viewWithTag(1) as! UIImageView
imageV.image = catPicture


text:
Q: DNN Upgrade Module From .Net 3.5 to .Net 4.6.1 I have multiple DNN modules built on .Net 3.5 and DNN 5.2, I upgraded them to DNN 8.1 & .Net 4.6.1, so in the upgraded CMS, some modules are working properly, and others not working (not working without showing any error message or any exception).
To upgrade my modules, I followed these steps:

*

*Changed the Target framework of each module project to be 4.6.1.

*Fix build errors which raised after changing the Target Framework.

*Build the module project successfully.

*Copy and replace the file bin/release/module_name.dll to Portal/bin folder

Note: for those modules which not working, I can't find any error message describing that I have an issue in the code or something can't be loaded !
So probably made a mistake or missing some other steps?
Update:
After checking the Admin -> Event Viewer, I've found that after dropping the module object inside the page, a General Exception record is inserted to the errors says:
StackTrace -> at DotNetNuke.Services.Search.ModuleIndexer.ThrowLogError(ModuleInfo module, Exception ex)
InnerMessage -> Value cannot be null. Parameter name: type
InnerStackTrace ->
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at DotNetNuke.Services.Search.ModuleIndexer.GetModuleList(Int32 portalId)


text:
Q: ColdFusion's Duplicate function won't copy metadata of a query The function Duplicate of ColdFusion 9 is supposed to return a clone, also known as a deep copy, of a variable, with no reference to the original variable. That's supposed to be true for complex objects, such as structures and queries.
I'm working on a code that uses a query object that is in the APPLICATION scope. This query needs to be modified locally for use in a particular page and I need to know what the original query string was (which is in the query object's metadata). So in this case, creating a deep copy of the original query is the most sensible solution.
But unfortunately, it looks like ColdFusion doesn't clone the whole object, but only its result set, thus losing all the metadata.
That's not the behaviour I expected from Duplicate, and I don't find it consistent with what happens when duplicating other kinds of complex objects.
One solution to my problem would be passing the result set AND the sql string as separate arguments to the function.
I'd like to know, however, if you have a more elegant solution, and/or throw a bit of light on the query Duplicate issue.
Here's some code that proves the issues for query Duplicate:
<cfquery name="qry" datasource="mydatasource">
    SELECT "blue" AS colour, "pear" as fruit
</cfquery>
<cfset qry_copy = qry>
<cfset qry_deepcopy = duplicate(qry)>

<cfdump var="#qry#" label="Original query" />
<cfdump var="#qry_copy#" label="Copy of the query (by reference)" />
<cfdump var="#qry_deepcopy#" label="Deep copy of the query (by value)" />

<cfdump var="#qry.getMetaData().getExtendedMetaData()#" label="Metadata of the original query" />
<cfdump var="#qry_copy.getMetaData().getExtendedMetaData()#" label="Metadata of the copy of the query" />
<cfdump var="#qry_deepcopy.getMetaData().getExtendedMetaData()#" label="Metadata of the deep copy of the query" />

Edit:
In a nutshell, these are my conclusions so far:

*

*The metadata doesn't get duplicated because qry.getMetaData() is a JAVA class and, as mentioned in the documentation, If an array element or structure field is a COM, CORBA, or JAVA object, you cannot duplicate the array or structure.

*The documented ColdFusion function to get the metadata of a query is getMetaData(qry).

*I've fixed my problem by storing both qry and getMetaData(qry) in the APPLICATION scope.

A: Hmmm... that is to my way of thinking a bug. My guess would be that there is a reference to the metadata that is not pulled into the deep copy. If it was something else the "getMetaData()" function called on the deep copy would throw an error.
Have you tried adding the "result" attribute to the query tag? As in:
<cfquery name="qry" datasource="mydatasource" result="myresult">
    SELECT "blue" AS colour, "pear" as fruit
</cfquery>

That might create a property or class embedded in the result set - although "result" is actually set in the variables scope I believe. I need to think about this.


text:
Q: Laravel multi tenant migrate Wondering if anyone knows how or of a package that allows migrations to be done on multiple databases without having the additional connection in the config file. Currently I have two different connections, one for the default and another for the tenants. The tenant connection has the credentials input, but it doesn't have the database name since each tenant will have a different database name. Problem is when I'm doing the initial setup and need the migrations to be run it will do it for the default or the tenant(if I edit the file to include the database name). I had found a package that would do it but it is not currently compatible with laravel 5. Obviously if I have to do it manually it can be done. It would just be a pain. Thanks in advance for suggestions.

A: Looking through the tenancy related questions here, I stumbled upon your open one.
What I've done is override the default MigrateCommand provided by Laravel and add the --tenant option. This will allow me to migrate one, more or all tenants. You can check the implementation out at my repository. Knowing the code of conduct here, I'll also add an example implementation:
<?php

namespace Hyn\MultiTenant\Commands\Migrate;

use Hyn\MultiTenant\Traits\TenantDatabaseCommandTrait;
use Illuminate\Database\Migrations\Migrator;
use PDOException;

class MigrateCommand extends \Illuminate\Database\Console\Migrations\MigrateCommand
{
    use TenantDatabaseCommandTrait;

    /**
     * MigrateCommand constructor.
     *
     * @param Migrator $migrator
     */
    public function __construct(Migrator $migrator)
    {
        parent::__construct($migrator);

        $this->website = app('Hyn\MultiTenant\Contracts\WebsiteRepositoryContract');
    }

    public function fire()
    {

        // fallback to default behaviour if we're not talking about multi tenancy
        if (! $this->option('tenant')) {
            $this->info('No running tenancy migration, falling back on native laravel migrate command due to missing tenant option.');

            return parent::fire();
        }

        if (! $this->option('force') && ! $this->confirmToProceed()) {
            $this->error('Stopped no confirmation and not forced.');

            return;
        }

        $websites = $this->getWebsitesFromOption();

        // forces database to tenant
        if (! $this->option('database')) {
            $this->input->setOption('database', 'tenant');
        }

        foreach ($websites as $website) {
            $this->info("Migrating for {$website->id}: {$website->present()->name}");

            $website->database->setCurrent();

            $this->prepareDatabase($website->database->name);

            // The pretend option can be used for "simulating" the migration and grabbing
            // the SQL queries that would fire if the migration were to be run against
            // a database for real, which is helpful for double checking migrations.
            $pretend = $this->input->getOption('pretend');

            // Next, we will check to see if a path option has been defined. If it has
            // we will use the path relative to the root of this installation folder
            // so that migrations may be run for any path within the applications.
            if (! is_null($path = $this->input->getOption('path'))) {
                $path = $this->laravel->basePath().'/'.$path;
            } else {
                $path = $this->getMigrationPath();
            }

            try {
                $this->migrator->run($path, $pretend);
            } catch (PDOException $e) {
                if (str_contains($e->getMessage(), ['Base table or view already exists'])) {
                    $this->comment("Migration failed for existing table; probably a system migration: {$e->getMessage()}");
                    continue;
                }
            }

            // Once the migrator has run we will grab the note output and send it out to
            // the console screen, since the migrator itself functions without having
            // any instances of the OutputInterface contract passed into the class.
            foreach ($this->migrator->getNotes() as $note) {
                $this->output->writeln($note);
            }
        }

        // Finally, if the "seed" option has been given, we will re-run the database
        // seed task to re-populate the database, which is convenient when adding
        // a migration and a seed at the same time, as it is only this command.
        if ($this->input->getOption('seed')) {
            $this->call('db:seed', ['--force' => true, '--tenant' => $this->option('tenant')]);
        }
    }

    /**
     * Prepare the migration database for running.
     *
     * @return void
     */
    protected function prepareDatabase($connection = null)
    {
        if (! $connection) {
            $connection = $this->option('database');
        }

        $this->migrator->setConnection($connection);

        if (! $this->migrator->repositoryExists()) {
            $options = ['--database' => $connection];

            $this->call('migrate:install', $options);
        }
    }

    /**
     * @return array
     */
    protected function getOptions()
    {
        return array_merge(
            parent::getOptions(),
            $this->getTenantOption()
        );
    }
}

If you have any questions to solve this issue, let me know.


text:
Q: Creating Greek Data I heard a term "Greek Text" for dummy unintelligible text for testing in QA.
Is it a correct term? If yes, how do we create this data?
Thanks

A: See http://www.lipsum.com/

A: I think you are referring to Lorem Ipsum.
There is a generator here. Refreshing the page gives you new random text.

A: Besides Lorem Ipsum you could also consider:
The quick brown fox jumped over the lazy sleeping dog.

...repeated as often as necessary.
That particular sentence is used because it holds every letter of the English alphabet. More for graphic design I suppose but still an option for dummy data.

A: This site has a great generator, and offers "regular" latin greeking along with some more entertaining options. Pseudo German and Hillbilly are my personal favorites.
http://www.duckisland.com/GreekMachine.asp


text:
Q: How to respond to bizarre requests in code reviews? I think that code reviews are great and very helpful for everyone. With that being said, from time to time I've received feedback on a pull request (leading to the PR being delayed for at least as long as it takes for another round of responses from everyone involved, if not longer) that I think is so completely out of left field that I don't even know how to reply. For example:

*

*(discussing a single-page website built with an Angular-like framework): "I think we should serve these as separate pages because otherwise users will be confused"

*(discussing a C89/C99/C11 stdlib function): "I think we should avoid this for the sake of portability and re-implement it ourselves"

*(discussing functionality that we need a compiler extension for): "Although we use this in multiple other places, I think we should re-implement it ourselves here for the sake of portability"
Although I don't want to establish a negative tone during code reviews, I find it very hard not to get frustrated with commentary like this, especially when the reviewer is very insistent about it (i.e. multiple rounds of debate back and forth). When I see commentary like this, I strongly suspect that the reviewer is just looking for an excuse to talk, and that he or she would find some reason to semi-randomly permute pretty much any pull request submitted. I feel like this subverts the point of the code review process and drags down the productivity of the team as a whole.
I don't know how to respond to these kinds of questions without coming off negatively, because I find it hard to believe that they are being asked in good faith (e.g. if you genuinely worry that functionality guaranteed by your language's spec isn't portable enough to use, how do you get anything done at all?). How can I reply to this sort of commentary effectively?

A: You need to position code reviews within your development process. Code reviews should probably not be the sole place for feedback, as obviously some feedback should have been voiced/discussed and worked out much earlier.  Still other feedback should spawn its own thread of work without necessarily impacting with the current work item under review.
The first bullet point probably ought to be off-topic to the code review, and instead be on-topic during your customer meetings, scrums, or discussions of user stories.  In other words, it is an issue of the design of customer interaction; as such it should have been raised earlier, and it should have been raised by someone more representing the client/customer rather than fellow programmers (who are reviewing the actual code).
The last two bullet points probably ought to spawn their own refactoring thread(s), but not necessarily hold up the code in question, in particular, when the code in question is not the sole "offender".  It is generally considered best practice to do multiple small check-ins rather than large ones, so significantly expanding the scope of some code change in order to incorporate a broad refactoring (requiring that you fix code outside of the scope of one check-in) is conflating matters, i.e. a step in the wrong direction.  It is also best practice to keep refactoring and feature change separate whenever possible, as separate check-ins, thus, this also suggests that adding a refactoring into the feature check-in (or separate refactoring check-in) is a conflation of purposes.


text:
Q: Avoiding turn-off of zero-crossing optotriac I'm designing a circuit that switches a load using a regular TRIAC (say, a BT-137) being fed by a MOC3063 - an optotriac with zero crossing detection. The circuit being fed by the TRIAC can be either a resistive load or a diode bridge, so there may be no current at the moment the TRIAC turns on. Here's the topology I'm thinking of:

My question is: can I be sure the MOC3063, which has a zero crossing detection circuit, won't turn off? I'm assuming that it can't ever turn off while there is current in the input side, no matter how messed up the load current is - even if it goes below the holding current of the optotriac. Is this a safe assumption?

A: The zero crossing detector in the MOC3063 only inhibits triggering if the voltage across the main terminals (pin 4 and pin 6) is greater than typically 5 volts. So, should the device be previously triggered, the main terminal voltage will be no more than 3 volt (page 6 of data sheet) and therefore the zero-crossing detector cannot inhibit that situation and cause the internal triac to open circuit.

Is this a safe assumption?

Yes.


text:
Q: How do I prepend a Stream? I'm loading blobs out of a database as a byte array and I put them in a memory stream so that I can load them into an xmldocument for parsing.
However there are blobs that have multiple root nodes, this causes the parser to blow up.
My solution is to just make a new root node that encompasses the whole blob.
I can add onto the end just fine with a streamwriter however I can't figure out how to add onto the beginning.
How can I prepend to a stream?

Update
I was having too much trouble getting this to work. The "XML" I was extracting was not proper XML and I kept on having to add more and more regexes to remove bad XML before the XmlDocument Load. I ended up using the HtmlAgilityPack to parse out my valid sections of XML and I put those inside their own xml documents. Not the nicest solution but it works. Sigh

A: Since you already have byte[] array from DB, writing more bytes before and after the array to memory stream should be easy:
// bytes from db
byte[] multipleNodes = Encoding.UTF8.GetBytes("<first>..</first><second>..</second><third>..</third>");

using (var ms = new MemoryStream())
{
    // write opening tag
    byte[] newRoot = Encoding.UTF8.GetBytes("<newRoot>");
    ms.Write(newRoot, 0, newRoot.Length);

    ms.Write(multipleNodes, 0, multipleNodes.Length);

    // write opening tag
    byte[] closeNewRoot = Encoding.UTF8.GetBytes("</newRoot>");
    ms.Write(closeNewRoot, 0, closeNewRoot.Length);

    // reset cursor position before pass it to xmldoc
    ms.Position = 0;

    var xml = new XmlDocument();
    xml.Load(ms);

    Console.WriteLine(xml.InnerXml);
}

But since XmlDocument also provide LoadXml(str), I feel manipulating the string should be more straight forward solution:
// bytes from db
byte[] multipleNodes = Encoding.UTF8.GetBytes("<first>..</first><second>..</second><third>..</third>");

string stringFromBlob = Encoding.UTF8.GetString(multipleNodes);
string withRootNode = string.Format("<newRoot>{0}</newRoot>", stringFromBlob);

var xml = new XmlDocument();
xml.LoadXml(withRootNode);

Console.WriteLine(xml.InnerXml);

A: You can't directly. This leads to two options:

*

*write in an opening tag into the memorystream prior to loading the blobs

*create a second memorystream, write in an opening tag, copy the first into the second...

A: This is the one I use:
public class CompositeStream : FileStream
{
    Stream[] childStreams;
    int currentStreamIndex = 0;
    Stream currentStream;
    public long totalStreamRead{get; private set;}

    public CompositeStream(string pre, FileStream s_file, string post)
        : base(s_file.SafeFileHandle, FileAccess.Read)
    {
        totalStreamRead = 0;

        MemoryStream s_pre = new MemoryStream();
        MemoryStream s_post = new MemoryStream();

        byte[] b_pre = Encoding.UTF8.GetBytes(pre);
        s_pre.Write(b_pre, 0, b_pre.Length);
        s_pre.Flush();
        s_pre.Seek(0, SeekOrigin.Begin);

        byte[] b_post = Encoding.UTF8.GetBytes(post);
        s_post.Write(b_post, 0, b_post.Length);
        s_post.Flush();
        s_post.Seek(0, SeekOrigin.Begin);

        childStreams = new Stream[] { s_pre, s_file, s_post };

        currentStream = childStreams[currentStreamIndex++];
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        int totalBytesRead = 0;
        while (count > 0)
        {
            // Read what we can from the current stream
            int numBytesRead = currentStream.Read(buffer, offset, count);
            totalBytesRead += numBytesRead;
            count -= numBytesRead;
            offset += numBytesRead;

            // If we haven't satisfied the read request,
            // we have exhausted the current stream.
            // Move on to the next stream and loop around to read more data.
            if (count > 0)
            {
                // If we run out of child streams to read from...
                if (currentStreamIndex >= childStreams.Length)
                    break; //get out

                currentStream.Close();
                currentStream = childStreams[currentStreamIndex++];
            }
        }
        totalStreamRead += totalBytesRead;
        return totalBytesRead;
    }
}

A: A clean way to do this is to implement a CompositeStreamReader that will accept a number of streams and then read them out in order.
There is an implementation of one at https://web.archive.org/web/20100721082808/http://blogs.msdn.com/b/paolos/archive/2010/04/08/how-to-boost-message-transformations-using-the-xslcompiledtransform-class-extended.aspx that you can adapt, but you can get away with something simpler.


text:
Q: How to use Python requests to perform NTLM SSPI authentication? My goal is to authenticate my client that uses the requests library (2.11.1) in Python 3.5.2 through NTLM with SSPI so that the user does not have to manually enter her domain credentials (used to login to the PC).
I have found the following possibilities, but none work for me:

*

*HttpNtlmSspiAuth provokes an exception in requests:
import requests
from requests_ntlm import HttpNtlmAuth, HttpNtlmSspiAuth
requests.get(site_url, auth=HttpNtlmSspiAuth())

*

*requests-sspi-ntlm always gets a 401:
import requests
from requests_sspi_ntlm import HttpNtlmAuth
session = requests.Session()
session.auth = HttpNtlmAuth()
session.get("http://ntlm_protected_site.com")

*

*And requests-negotiate-sspi also triggers an exception in requests:
import requests
from requests_negotiate_sspi import HttpNegotiateAuth
r = requests.get('https://iis.contoso.com', auth=HttpNegotiateAuth())

Am I doing something wrong?

A: The package requests-negotiate-sspi works for me.
I probably had the same issue with PO, but I was too lazy to try PO's solution and integrate PO's code into mine. And Google helped me out. In case anyone encounters the same exception raised from sspi.py ValueError: year 30828 is out of range, it's a known issue for python 3.6 of requests-negotiate-sspi. See here: Github-Issue
I solved this by creating a new conda environment with python 3.4. Then reinstall some dependencies as well as requests-negotiate-sspi, boom, all works.

A: Same issue here but solved when I realized I was in a adm account that doesn't have authorization to that resource uri.


text:
Q: Dynamic javascript from web resource I have written a custom web control that validates some input to a textbox client-side. The associated JavaScript is an embedded resource. As part of the validation process the JavaScript displays a confirm alert box.
I want to be able to set the message of the alert from a property of web control, in a similar way to the standard asp.net validation controls have the ErrorMessage property.
Can anyone advise me on the best way to splice this property into my embedded JavaScript?
Embedded js function
function checkDeduction(sender, eventArgs) {
    var dNewVal = eventArgs.get_newValue();
    if (dNewVal > 0) {
        var bRetVal = confirm("custom msg here");
        if (!bRetVal) {
           dNewVal = dNewVal * -1;
           sender.set_value(dNewVal);
        }
    }
}

A: To achieve this I added a custom attribute to my custom control on the PreRender event:
protected override void OnPreRender(EventArgs e)
{
        this.Attributes.Add("ErrorText", "custom error text from public prop");
        ...
        base.OnPreRender(e);
}

I was then able to hold of the error message client-side like so:
confirm(sender.getAttribute('ErrorText'));

Job done!


text:
Q: Ideas on how to handle a javascript widget? My friend has a search engine that he wants to have a widget access that can be put on other web pages. If I send a request to the search engine, it returns an XML file. The request would look something like this:
    http://www.site.com/page.php?keyword=this+is+a+sample&page=1&num_days=3&source_id=site2.com&source_name=site2&source_url=sampleurl.php
I understand how to access this by using Javascript. However, I know that you can't do a cross-domain request. I would have to have it load a new page at the search engines's site and not in the window at the the site they were located at....right? Any ideas or insight are greatly appreciated.

A: Here is a good explanation too:
What is JSONP all about?
EDIT:

jsonpString
Override the callback function name in
  a jsonp request. This value will be
  used instead of callback in the
  callback=? part of the query string
  in the url. So {jsonp:'onJsonPLoad'}
  would result in 'onJsonPLoad=?' passed
  to the server.

jsonpCallbackString
Specify the callback function name for
  a jsonp request. This value will be
  used instead of the random name
  automatically generated by jQuery. It
  is preferable to let jQuery generate a
  unique name as it'll make it easier to
  manage the requests and provide
  callbacks and error handling. You may
  want to specify the callback when you
  want to enable better browser caching
  of GET requests.

taken from:
http://api.jquery.com/jQuery.ajax/


text:
Q: Combining multiple IF/AND/THEN statements Part 2 After having solved the initial programming question by using the following calculation...
=IF(OR(AND($D11="Long",$M11>=$N11),AND($D11="Short",$M11<=$N11)),"Win","Loss")

The secondary question relates to when D11 is blank.  I have tried a number of ways including using ISBLANK in tring to include this in the calculation.
The calculation will reside in R11.  So written out... IF D11 is blank then blank otherwise the above calculation will take place.  Not sure how to place this within the above calculation to make it work.  My efforts have been incorrect.

A: You can just add that first, in this generic form
=IF($D11="","",your_formula)
so specifically that becomes:
=IF($D11="","",IF(OR(AND($D11="Long",$M11>=$N11),AND($D11="Short",$M11<=$N11)), "Win","Loss"))
see screenshot


text:
Q: Mocking variable in method I have DRF API view function to create a new Message:
class MessageCreate(generics.CreateAPIView):
    """Create new message by thread id."""

    serializer_class = MessageNewSerializer
    queryset = Message.objects.all()

    def post(self, request, *args, **kwargs):
        """Check that logged-in user is thread."""
        thread = Thread.objects.filter(pk=request.data["thread"]).first().participants.all()
        user = self.request.user
        request.data["sender"] = user.id #need to mock user.id with return value = 2
        if not user in thread:
            raise ValidationError("You are not in this thread.")
        return self.create(request, *args, **kwargs)

For testing, I need to mock (user.id) with return value = 2. But I can not understand how to implement this.
class TestMessageCreate(unittest.TestCase):
    def setUp(self):
        """Create Theread with two partisipants. Create two users."""
        self.user = User.objects.create_user(email="test@test.te", password="test")
        self.user2 = User.objects.create_user(email="test2@test.te", password="test2")
        self.thread = Thread.objects.create()

    def test_message_create(self):
        """Create new Message."""
        data = {"text": "from_test", "sender": self.user.id, "thread": self.thread.id}
        url = reverse("message-create")
        response = self.client.post(url, data=data, format='json')
        print(response.json())
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

A: Explanation
I think what you need is to authenticate the user in the test so that request.user will return the user that you want.
Solution
You can achieve this by using APIClient.force_authenticate or APIClient.login.
def test_message_create(self):
    ...
    # add this line
    self.client.force_authenticate(user=self.user2)
    response = self.client.post(url, data=data, format='json')
    ...


text:
Q: SlickNav menu doesn't move, prependTo doesn't work I have slicknav on my Wordpress theme but it stays on top of the page. I tried editing the prependto, but still it doesnt move. Here's the HTML:

logo html

this is where I want the slick nav to appear
`

Here's the JS:
;(function ($, document, window) {
    var
    // default settings object.
    defaults = {
        label: 'MENU',
        duplicate: true,
        duration: 200,
        easingOpen: 'swing',
        easingClose: 'swing',
        closedSymbol: '►',
        openedSymbol: '▼',
    //prependTo: 'body',
    prependTo: '#hello',
    parentTag: 'a',
    closeOnClick: false,
    allowParentLinks: false,
    nestedParentLinks: true,
    showChildren: false,
    brand: '',
    init: function () {},
    open: function () {},
    close: function () {}
},
mobileMenu = 'slicknav',
prefix = 'slicknav';

Here's the CSS:
.slicknav_btn { position: relative; display: block; vertical-align: middle; float: right; padding: 0.438rem 0.625rem; line-height: 1.125rem; cursor: pointer; }
.slicknav_menu  .slicknav_menutxt { display: block; line-height: 1.125rem; float: left; }
.slicknav_menu .slicknav_icon { float: left; margin: 0.188rem 0 0 0.438rem; }
.slicknav_menu .slicknav_no-text { margin: 0; }
.slicknav_menu .slicknav_icon-bar { display: block; width: 1.125rem; height: 0.125rem; -webkit-border-radius: 1px; -moz-border-radius: 1px; border-radius: 1px; -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); }
.slicknav_btn .slicknav_icon-bar + .slicknav_icon-bar { margin-top: 0.188rem }
.slicknav_nav { clear: both; }
.slicknav_nav ul, .slicknav_nav li { display: block; }
.slicknav_nav .slicknav_arrow { font-size: 0.8rem; margin: 0 0 0 0.4rem; }
.slicknav_nav .slicknav_item { display: block; cursor: pointer; }
.slicknav_nav a { display: block; }
.slicknav_nav .slicknav_item a { display: inline; }
.slicknav_menu:before, .slicknav_menu:after { content: " "; display: table; }
.slicknav_menu:after { clear: both; }
.slicknav_menu { *zoom: 1; }

.slicknav_menu { font-size: 13px; font-size: 0.8125rem; }
.slicknav_btn { margin: 0 5px; text-decoration: none; background: #9EB058; }
.slicknav_menu .slicknav_menutxt { color: #fff; font-weight: bold; }
.slicknav_menu .slicknav_icon-bar { background: #f5f5f5; }
.slicknav_menu { border-top:1px solid #DCDCCD; border-bottom: 2px solid #9EB058; }
.slicknav_nav { font-size: 16px; font-size: 1rem; font-weight: 600; color: #fff; margin: 0; padding: 0; margin-bottom: 20px; }
.slicknav_nav, .slicknav_nav ul { list-style: none; overflow: hidden; }
.slicknav_nav ul { padding: 20px 0 0 15px; border-top: 2px solid #DCDCCD; }
.slicknav_nav ul ul { border: 0; padding: 0 0 0 15px; }
.slicknav_nav .slicknav_item { padding: 5px 10px; margin: 2px 5px; }
.slicknav_nav a { padding: 5px 10px; margin: 2px 5px; text-decoration: none; color: #4F4322; }
.slicknav_nav .slicknav_item a { padding: 0; margin: 0; }
.slicknav_nav .slicknav_item:hover { background: #9EB058; color: #fff; }
.slicknav_nav a:hover { background: #9EB058; color: #fff; }
.slicknav_nav .slicknav_txtnode { margin-left: 15px; }

How do I move the slicknav menu?


text:
Q: Is it possible to escape the GPL by deriving the same work from multiple sources? Suppose you have an arbitrary code base, C, possibly composed of multiple programs, none of which fall under a copyleft license.
Suppose this code, taken together, does the same job as a nice integrated program, A licensed under some copyleft license like the GPL, but that for whatever reason the GPL code is superior (faster, cleaner, less buggy, whatever).
Now suppose that for each feature in C, you find the equivalent feature in A and, through careful step-by-step refactoring, create two chains of patches that converge on a third program, B.
In other words, you can show step by step, via patches, how to derive any of the three programs from any of the others:
A <--> B <--> C

It seems that through this procedure, you have extracted value from A and even created a derived work, but the new work doesn't necessarily resemble A, and there is a clear chain of evidence showing that B was derived from a different code base entirely.
My question is:
Would a "dialectic" implementation like this provide the same legal effect as a traditional "clean room" implementation?
Note: feel free to replace the licenses of A and C with your most and least favorite options, respectively. The question is about the process in general.

A: Your explanation ends up proving the following:
A <-----> C
     |
     |
     V
     B

That is to say, B is derived from both A and C. Your rights are given in the intersection both both licenses, your obligations by their union.

A: No.
As I understand your proposal, you would be creating a copy of A by artifice.
You don't need to use a computer to copy a work, reading one work and re-producing it is still violating copyright. Copyright law does vary by jurisdiction, but AFAIK is fairly consistent in meaning. Basically, if you copy a work, whether it be computer software, a book, music, or whatever, a copy is a copy, and violates copyright.

A: No.
Copyright doesn't work by "if you could".  It works by "if you did".  If you took C and modified it to get B, you are bound by C's license regardless of how close B is to A.  In theory, if you took a 10,000 line GPL file, deleted all but the first line, and wrote arbitrary code after it, you'd still be bound by the GPL.  In your initial example, if you create any chain of patches from C to B, you are bound by C's license regardless of what you do with A.  What you do with A is completely and utterly irrelevant to the matter.
Note that if you read source to C, walk into another room and type it from memory, you are still creating a derivative work.  A "clean room" implementation rests on the people doing the implementing having no direct knowledge of the original.  That is, someone reads C, figures out the interfaces, creates a basic design document describing those interfaces and gives it to someone else to implement.
Of course if it ever gets to trial, it becomes a matter of whether lawyers can prove based on a preponderance of that evidence that this is what you did and in practice the bulk of this evidence will center around whether you had access to the original and how similar your work is to the original.  Lawyers are going to lay out your work B and work C in front of either a judge or a jury and say "@tangentstorm had access to C and B is very similar, therefore he likely copied the work and is bound by C's license".
A would enter into it is if you claimed that your B derived from A and that similarity to C is pure coincidence.  The more knowledge of C you can be shown to have, and the more similar B is to C, the harder this will be.  You can certainly claim that you derived B from A and use patches/etc. as a defense, but if you actually used the process you describe, this would be perjury.
(Also note that this is civil law, where questions are of "preponderance of evidence", not "beyond reasonable doubt" like criminal cases.  In other words, 51% likelihood not 99.99% likelihood.)
In the situation like you describe, your best options are either to ignore C completely and derive from A alone or derive from C and abide by the GPL.  Trying to "get around" is both unethical and opens you up to legal risk.
NOTE:  I should state that I am NOT a lawyer, and if you are planning on anything like the original question, you should see a real one.  The general takeaway from this answer should really be that you are metaphorically asking if you've found a good way of poking a stick into a hornets nest.

A: The GPL doesn't speak at all about clean rooms or reverse-engineering.
If you study source code from a GPL'd program, and use the knowledge you gain to write your own code yourself, you have not necessarily run afoul of the GPL. An infringement occurs when you use and distribute someone else's code, not when you write your own.
Of course, it must be apparent that it is your code, and not merely a parroting or mechanical transliteration of the original code. IANAL, TANSTAAFL, YMMV.

A: This A <--> B <--> C makes a nice logical thought experiment, but I can't understand the practical application.
I only see two possibilities:
1) A --> B <-- C
If B truly is derived from both (as you suggested), in other words, met-in-the-middle, then it is derived from C, as a means of linking A and C (and vice versa, though that doesn't seem to matter).
There would be no way to arrive at a middle, B, without direct knowledge and work from A, aside from a statistical impossibility as Steven Burnap says.
2)
Or if B is not derived from both, then it is derived from one, and the path to the other is reverse engineered using that source.
In this case, you either went A --> B --> C in which case you are bound by the license.  Or you went
C --> B --> A in which case you could argue you aren't bound by the license, but why would you have created the B --> A link at all?  In this case, if you'd stopped at C --> B, you'd be fine.
So either...

*

*You are bound by the license.

*or you did something you didn't need to do.


text:
Q: how can i pass a powershell variable to terraform I need to pass a powershell/devops variable to terraform, is there a way of doing this? As in the below example i want the below PR number to be used as a variable in terraform.
testvalue-$(System.PullRequest.PullRequestNumber)

A: As far as I know, there is no way to define a variable by the output of a command (shell ..), but you can take a look at this data source external data source ,
the idea is that you define a bash script or any program and use it's output as parameters for other resources.
Example
data "external" "PullRequest" {
  program = [
    "${path.module}/scriptWhichReturnsPullRequestName.sh",
  ]
  result {

  }
}

...
resource ...  {
  value = data.external.PullRequest.property
}

A: I put my variables in a variables.tf and trigger terraform execution from a powershell script. Prior that execution I just replace certain strings in variables.tf.


text:
Q: Allow action from plugin Is it possible to allow an plugin action in appController.php
I can't find and figure out how to do it. What I mean is, I know it is possible to use
$this->allow('action')

in the plugin's controller. But when I add it to the plugin's controller, once I update this plugin, I need to change the source again.
Is there a simpler way, eg. do this in appController.php?

A: You need to check if the current request is to the plugin and controller you are targeting.
public function beforeFilter()
{
    if($this->request->params['plugin'] == 'myplugin' && $this->request->params['controller'] == 'mycontroller')
    {
       $this->Auth->allow('action');
    }
}

I don't know if that code is correct, but it's something like that.


text:
Q: A series converges absolutely if and only if every subseries converges Question:
A subseries of the series $\sum _{n=1}^\infty a_n$ is defined to be a series of the form $\sum _{n=1}^\infty a_{n_k}$, for $n_k \subseteq \Bbb N$. Prove that $\sum _{n=1}^\infty a_n$ converges absolutely if and only if each subseries $\sum _{n=1}^\infty a_{n_k}$ converges.
Suggested solution:
$\Rightarrow$

*

*We assume $\sum _{n=1}^\infty a_n$ converges absolutely $\Rightarrow \lim_{n \to \infty} |a_n|$=0. We know from the definition of series that it's actually the sequence of partial sums so $\sum _{n=1}^\infty a_n = S_n$. Therefore we can treat it like a sequence and say that it converges to L. Since $S_n$ converges to L, each of it's sub sequences also converge to L. Therefore $\sum _{n=1}^\infty a_{n_k} =S_{n_k} \to L$ as well.

$\Leftarrow$

*

*We assume each subseries converges. Specifically the sub series $\sum _{\Bbb N even} a_n = A$  $\sum _{\Bbb N odd} a_n = B$ . Since these two series comprise all of the naturals, then  $\sum _{n=1}^\infty a_n =\sum _{\Bbb N even} a_n+\sum _{\Bbb N odd} a_n = A+B$ . Therefore it converges to A+B.

I would like to verify this proof, because I've given it a lot of thought, and still not 100 percent sure about it. Please hint me, and notify me about any mistakes.
Thanks.

A: The two suggested proofs are wrong
$\Rightarrow$
We have
$$\sum_{k=1}^\infty|a_{n_k}|=0\times|a_1|+\cdots+0\times|a_{n_1-1}|+|a_{n_1}|+0\times|a_{n_1+1}|+\cdots\leq\sum_{n=1}^\infty|a_{n}|$$
hence the series
$$\sum_{k=1}^\infty|a_{n_k}|$$
is convergent by comparaison.
$\Leftarrow$
Let denote by $(a_{n_k})$ the subsequence of $(a_n)$ by choosing all its positive terms and $(a_{n'_k})$ the subsequence of $(a_n)$ by choosing all its negative terms then the series
$$\sum_{k=1}^\infty a_{n_k} \quad\text{and} \quad \sum_{k=1}^\infty a_{n'_k}$$
are absolutely convergent and its clear that
$$\sum_{n=1}^\infty |a_{n}|=\sum_{k=1}^\infty a_{n_k}-\sum_{k=1}^\infty a_{n'_k}$$
hence the series
$$\sum_{n=1}^\infty a_{n}$$
is absolutely convergent.


text:
Q: Optimizing protocol opening operation over tcp connection opening I'm designing a new protocol called DITP. It is a connection oriented protocol that would use TCP as transport layer. With common Internet protocols, when the TCP connection is established, the server starts by sending a greeting message to what the client respond, eventually sending its first request.
I figured out I could save one round trip time by inverting the initial protocol transaction. The client starts by sending the greeting followed by the first request.
The following graphic shows a comparison between the two protocol transaction timings and how it saves one round trip time.

(source: disnetwork.info)
You may want to read the following blog note for a more detailed explanation.
http://www.disnetwork.info/1/post/2008/08/optimizing-ditp-connection-open.html
I had two questions to network programming experts of StackOverflow :

*

*Is this assumption correct ?

*Why common protocols don't use this ?
This method could provide a significant performance optimization for long distance connections where communication latency is high and connections are to be established frequently. HTTP would have been a good candidate.
EDIT: Oops big mistake. HTTP uses the optimized method where the client sends the request directly. There is no greeting transaction as with SMTP.See Wikipedia Hypertext Transfer Protocol page.

A: It isn't done largely because because:
a.) The client may need to know what version of protocol the server uses
b.) You won't even know you really are talking to a server that supports the protocol.
In short, it often makes sense to know what you're talking to before spewing data at it.

A: I wonder if this design might not be said to be a violation of Postel's Law, since it's assuming things about the receiver, and thereby about what is legal to send, before knowing.
I would at least expect this principle to be the reason most protocols are designed so that they spend a roundtrip to figure out more about the other end, before sending data that might not be understood at all.

A: If delay is your main concern, you may want to look at LPT, a protocol that is specifically designed for connections with extremely long round-trip times.
When designing a new transport protocol, you should pay attention to congestion control and what firewall are going to do, when they encounter packets of an unknown protocol.

A: Design goals of the protocols like HTTP,SMTP were not the speed, rather reliability under flaky physical network conditions and the meagre bandwidth utilisation. Largely these conditions have changed now with better hardware.
Your design should be look at in the light of the network conditions you are bound to encounter, reliability required, latency and bandwidth utilisation of your intended application.

A: *

*In theory, this is correct.

*Common protocols don't use this, because it's inefficient. Client would have to split the data streams, so they would have to be distinguishable. Server would have to take care about this, for example by packing each data piece in a container (XML, JSON, Bitorrent-like, You name it). And the container is just an unnecessary data overhead, slowing down the transfer.

Why wouldn't one just open several TCP sockets and send separate requests over those multiple connections? No overhead here! Oh, this is already being done, f.e. by some modern web browsers. Use a wireshark or tcpdump to inspect the packets and see for Yourself.
There's more than that. TCP socket takes time to set up (SYN, some time, SYN+ACK, some time, ACK...). Someone thought it's a waste to reset the connection after each request, so some modern HTTP servers and clients use Connection: keep-alive to indicate that they wish to reuse the connection.
I am sorry but I think Your ideas are great, however You can find them in RFC's. Keep thinking though, I am sure one day You'll invent something brilliant. See f.e. here for an optimized bitorrent client.