Programs & Examples On #Array push

PHP add elements to multidimensional array with array_push

if you want to add the data in the increment order inside your associative array you can do this:

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

this will get added to the recipe or cuisine depending on what was the last index.

Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this

array_push($md_array["cuisine"],$newdata);

How do I load a file into the python console?

From the man page:

-i When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.

So this should do what you want:

python -i file.py

Grid of responsive squares

You could use vw (view-width) units, which would make the squares responsive according to the width of the screen.

A quick mock-up of this would be:

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
div {_x000D_
  height: 25vw;_x000D_
  width: 25vw;_x000D_
  background: tomato;_x000D_
  display: inline-block;_x000D_
  text-align: center;_x000D_
  line-height: 25vw;_x000D_
  font-size: 20vw;_x000D_
  margin-right: -4px;_x000D_
  position: relative;_x000D_
}_x000D_
/*demo only*/_x000D_
_x000D_
div:before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: inherit;_x000D_
  width: inherit;_x000D_
  background: rgba(200, 200, 200, 0.6);_x000D_
  transition: all 0.4s;_x000D_
}_x000D_
div:hover:before {_x000D_
  background: rgba(200, 200, 200, 0);_x000D_
}
_x000D_
<div>1</div>_x000D_
<div>2</div>_x000D_
<div>3</div>_x000D_
<div>4</div>_x000D_
<div>5</div>_x000D_
<div>6</div>_x000D_
<div>7</div>_x000D_
<div>8</div>
_x000D_
_x000D_
_x000D_

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I solved the problem adding a slash at the end of the requesting url

This way: '/data/180/' instead of: '/data/180'

How to remove a variable from a PHP session array

Currently you are clearing the name array, you need to call the array then the index you want to unset within the array:

$ar[0]==2
$ar[1]==7
$ar[2]==9

unset ($ar[2])

Two ways of unsetting values within an array:

<?php
# remove by key:
function array_remove_key ()
{
  $args  = func_get_args();
  return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
  $args = func_get_args();
  return array_diff($args[0],array_slice($args,1));
}

$fruit_inventory = array(
  'apples' => 52,
  'bananas' => 78,
  'peaches' => 'out of season',
  'pears' => 'out of season',
  'oranges' => 'no longer sold',
  'carrots' => 15,
  'beets' => 15,
);

echo "<pre>Original Array:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
                                    "beets",
                                    "carrots");
echo "<pre>Array after key removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
                                      "out of season",
                                      "no longer sold");
echo "<pre>Array after value removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';
?> 

So, unset has no effect to internal array counter!!!

http://us.php.net/unset

HEAD and ORIG_HEAD in Git

My understanding is that HEAD points the current branch, while ORIG_HEAD is used to store the previous HEAD before doing "dangerous" operations.

For example git-rebase and git-am record the original tip of branch before they apply any changes.

How do I get an apk file from an Android device?

If you know (or if you can "guess") the path to the .apk (it seems to be of the format /data/app/com.example.someapp-{1,2,..}.apk to , then you can just copy it from /data/app as well. This worked even on my non-rooted, stock Android phone.

Just use a Terminal Emulator app (such as this one) and run:

# step 1: confirm path
ls /data/app/com.example.someapp-1.apk
# if it doesn't show up, try -2, -3. Note that globbing (using *) doesn't work here.
# step 2: copy (make sure you adapt the path to match what you discovered above)
cp /data/app/com.example.someapp-1.apk /mnt/sdcard/

Then you can move it from the SD-card to wherever you want (or attach it to an email etc). The last bit might be technically optional, but it makes your life a lot easier when trying to do something with the .apk file.

Adding image to JFrame

There is no specialized image component provided in Swing (which is sad in my opinion). So, there are a few options:

  1. As @Reimeus said: Use a JLabel with an icon.
  2. Create in the window builder a JPanel, that will represent the location of the image. Then add your own custom image component to the JPanel using a few lines of code you will never have to change. They should look like this:

    JImageComponent ic = new JImageComponent(myImageGoesHere);
    imagePanel.add(ic);
    

    where JImageComponent is a self created class that extends JComponent that overrides the paintComponent() method to draw the image.

How can I delete Docker's images?

I found the answer in this command:

docker images --no-trunc | grep none | awk '{print $3}' | xargs docker rmi

I had your problem when I deleted some images that were being used, and I didn't realise (using docker ps -a).

How to change the interval time on bootstrap carousel?

        You need to set interval in  main div as data-interval tag .
        so it is working fine and you can give different time to different slides.

       <!--main div -->
      <div data-ride="carousel" class="carousel slide" data-interval="100" id="carousel-example-generic">
  <!-- Indicators -->
  <ol class="carousel-indicators">
                                <li data-target="#carousel-example-generic" data-slide-to="0" class=""></li>
                             i>
                                            </ol>

  <!-- Wrapper for slides -->
  <div role="listbox" class="carousel-inner">
       <div class="item">
          <a class="carousel-image" href="#">
           <img alt="image" src="image.jpg">
          </a>
        </div>
    </div>
 </div>

How to open an Excel file in C#?

Imports

 using Excel= Microsoft.Office.Interop.Excel;
 using Microsoft.VisualStudio.Tools.Applications.Runtime;

Here is the code to open an excel sheet using C#.

    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open("C:\\YourExcelSheet.xlsx");
    Microsoft.Office.Interop.Excel.Worksheet wx = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;

    wbv.Close(true, Type.Missing, Type.Missing);
    excel.Quit();

Here is a video mate on how to open an excel worksheet using C# https://www.youtube.com/watch?v=O5Dnv0tfGv4

How to Calculate Execution Time of a Code Snippet in C++

I have another working example that uses microseconds (UNIX, POSIX, etc).

    #include <sys/time.h>
    typedef unsigned long long timestamp_t;

    static timestamp_t
    get_timestamp ()
    {
      struct timeval now;
      gettimeofday (&now, NULL);
      return  now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
    }

    ...
    timestamp_t t0 = get_timestamp();
    // Process
    timestamp_t t1 = get_timestamp();

    double secs = (t1 - t0) / 1000000.0L;

Here's the file where we coded this:

https://github.com/arhuaco/junkcode/blob/master/emqbit-bench/bench.c

MS Excel showing the formula in a cell instead of the resulting value

I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.

Why doesn't Python have multiline comments?

I doubt you'll get a better answer than, "Guido didn't feel the need for multi-line comments".

Guido has tweeted about this:

Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)

Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs

You have to check unique identifier column and you have to give a diff value to that particular field if you give the same value it will not work. It enforces uniqueness of the key.

Here is the code:

Insert into production.product 
(Name,ProductNumber,MakeFlag,FinishedGoodsFlag,Color,SafetyStockLevel,ReorderPoint,StandardCost,ListPrice,Size
,SizeUnitMeasureCode,WeightUnitMeasureCode,Weight,DaysToManufacture,
    ProductLine, 
    Class, 
    Style ,
    ProductSubcategoryID 
    ,ProductModelID 
    ,SellStartDate 
,SellEndDate 
    ,DiscontinuedDate 
    ,rowguid
    ,ModifiedDate 
  )
  values ('LL lemon' ,'BC-1234',0,0,'blue',400,960,0.00,100.00,Null,Null,Null,null,1,null,null,null,null,null,'1998-06-01 00:00:00.000',null,null,'C4244F0C-ABCE-451B-A895-83C0E6D1F468','2004-03-11 10:01:36.827')

Spring Bean Scopes

Also websocket scope is added:

Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

As the per the content of the documentation, there is also thread scope, that is not registered by default.

Adding an item to an associative array

before for loop :

$data = array();

then in your loop:

$data[] = array($catagory => $question);

How to define Singleton in TypeScript

After implementing a classic pattern like

class Singleton {
  private instance: Singleton;
  
  private constructor() {}

  public getInstance() {
    if (!this.instance) { 
      this.instance = new Singleton();
    }
    return this.instance;
  }
}

I realized it's pretty useless in case you want some other class to be a singleton too. It's not extendable. You have to write that singleton stuff for every class you want to be a singleton.

Decorators for the rescue.

@singleton
class MyClassThatIsSingletonToo {}

You can write decorator by yourself or take some from npm. I found this proxy-based implementation from @keenondrums/singleton package neat enough.

What is the best way to check for Internet connectivity using .NET?

Something like this should work.

System.Net.WebClient

public static bool CheckForInternetConnection()
{
    try
    {
        using (var client = new WebClient())
            using (client.OpenRead("http://google.com/generate_204")) 
                return true; 
    }
    catch
    {
        return false;
    }
}

How do I make a PHP form that submits to self?

  1. change
    <input type="submit" value="Submit" />
    to
    <input type="submit" value="Submit" name='submit'/>

  2. change
    <form method="post" action="<?php echo $PHP_SELF;?>">
    to
    <form method="post" action="">

  3. It will perform the code in if only when it is submitted.
  4. It will always show the form (html code).
  5. what exactly is your question?

Exclude property from type

I've found solution with declaring some variables and using spread operator to infer type:

interface XYZ {
  x: number;
  y: number;
  z: number;
}

declare var { z, ...xy }: XYZ;

type XY = typeof xy; // { x: number; y: number; }

It works, but I would be glad to see a better solution.

JavaFX 2.1 TableView refresh items

UPDATE:
Finally tableview refreshing is resolved in JavaFX 8u60, which is available for early access.


About refreshing see the Updating rows in Tableview.
And about the blank column see the JavaFx 2 create TableView with single column. Basically it is not a column, i.e. you cannot select the item clicking on this blank column items. It is just a blank area styled like a row.


UPDATE: If you are updating the tableView via reseller_table.setItems(data) then you don't need to use SimpleStringProperty. It would be useful if you were updating one row/item only. Here is a working full example of refreshing the table data:

import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Dddeb extends Application {

    public static class Product {
        private String name;
        private String code;

        public Product(String name, String code) {
            this.name = name;
            this.code = code;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    private TableView<Product> productTable = new TableView<Product>();

    @Override
    public void start(Stage stage) {

        Button refreshBtn = new Button("Refresh table");
        refreshBtn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent arg0) {
                // You can get the new data from DB
                List<Product> newProducts = new ArrayList<Product>();
                newProducts.add(new Product("new product A", "1201"));
                newProducts.add(new Product("new product B", "1202"));
                newProducts.add(new Product("new product C", "1203"));
                newProducts.add(new Product("new product D", "1244"));

                productTable.getItems().clear();
                productTable.getItems().addAll(newProducts);
                //productTable.setItems(FXCollections.observableArrayList(newProducts));
            }
        });

        TableColumn nameCol = new TableColumn("Name");
        nameCol.setMinWidth(100);
        nameCol.setCellValueFactory(new PropertyValueFactory<Product, String>("name"));

        TableColumn codeCol = new TableColumn("Code");
        codeCol.setCellValueFactory(new PropertyValueFactory<Product, String>("code"));

        productTable.getColumns().addAll(nameCol, codeCol);
        productTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

        // You can get the data from DB
        List<Product> products = new ArrayList<Product>();
        products.add(new Product("product A", "0001"));
        products.add(new Product("product B", "0002"));
        products.add(new Product("product C", "0003"));

        //productTable.getItems().addAll(products);
        productTable.setItems(FXCollections.observableArrayList(products));

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.getChildren().addAll(productTable, refreshBtn);

        Scene scene = new Scene(new Group());
        ((Group) scene.getRoot()).getChildren().addAll(vbox);
        stage.setScene(scene);
        stage.setWidth(300);
        stage.setHeight(500);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Note that

productTable.setItems(FXCollections.observableArrayList(newProducts));

and

productTable.getItems().clear();
productTable.getItems().addAll(newProducts);

are almost equivalent. So I used the one to fill the table for the first time and other when the table is refreshed. It is for demo purposes only. I have tested the code in JavaFX 2.1. And finally, you can (and should) edit your question to improve it by moving the code pieces in your answer to your question.

How to give a time delay of less than one second in excel vba?

Obviously an old post, but this seems to be working for me....

Application.Wait (Now + TimeValue("0:00:01") / 1000)

Divide by whatever you need. A tenth, a hundredth, etc. all seem to work. By removing the "divide by" portion, the macro does take longer to run, so therefore, with no errors present, I have to believe it works.

Detect Safari using jQuery

Generic FUNCTION

 var getBrowseActive = function (browserName) {
   return navigator.userAgent.indexOf(browserName) > -1;
 };

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

  1. The optimal solution could be to try to transform your solution into a form where you don't need to have two readers open at a time. Ideally it could be a single query. I don't have time to do that now.
  2. If your problem is so special that you really need to have more readers open simultaneously, and your requirements allow not older than SQL Server 2005 DB backend, then the magic word is MARS (Multiple Active Result Sets). http://msdn.microsoft.com/en-us/library/ms345109%28v=SQL.90%29.aspx. Bob Vale's linked topic's solution shows how to enable it: specify MultipleActiveResultSets=true in your connection string. I just tell this as an interesting possibility, but you should rather transform your solution.

    • in order to avoid the mentioned SQL injection possibility, set the parameters to the SQLCommand itself instead of embedding them into the query string. The query string should only contain the references to the parameters what you pass into the SqlCommand.

Get absolute path of initially run script

The correct solution is to use the get_included_files function:

list($scriptPath) = get_included_files();

This will give you the absolute path of the initial script even if:

  • This function is placed inside an included file
  • The current working directory is different from initial script's directory
  • The script is executed with the CLI, as a relative path

Here are two test scripts; the main script and an included file:

# C:\Users\Redacted\Desktop\main.php
include __DIR__ . DIRECTORY_SEPARATOR . 'include.php';
echoScriptPath();

# C:\Users\Redacted\Desktop\include.php
function echoScriptPath() {
    list($scriptPath) = get_included_files();
    echo 'The script being executed is ' . $scriptPath;
}

And the result; notice the current directory:

C:\>php C:\Users\Redacted\Desktop\main.php
The script being executed is C:\Users\Redacted\Desktop\main.php

Ansible: create a user with sudo privileges

To create a user with sudo privileges is to put the user into /etc/sudoers, or make the user a member of a group specified in /etc/sudoers. And to make it password-less is to additionally specify NOPASSWD in /etc/sudoers.

Example of /etc/sudoers:

## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL

## Allows people in group wheel to run all commands
%wheel  ALL=(ALL)       ALL

## Same thing without a password
%wheel  ALL=(ALL)       NOPASSWD: ALL

And instead of fiddling with /etc/sudoers file, we can create a new file in /etc/sudoers.d/ directory since this directory is included by /etc/sudoers by default, which avoids the possibility of breaking existing sudoers file, and also eliminates the dependency on the content inside of /etc/sudoers.

To achieve above in Ansible, refer to the following:

- name: sudo without password for wheel group
  copy:
    content: '%wheel ALL=(ALL:ALL) NOPASSWD:ALL'
    dest: /etc/sudoers.d/wheel_nopasswd
    mode: 0440

You may replace %wheel with other group names like %sudoers or other user names like deployer.

How to post JSON to a server using C#?

Some different and clean way to achieve this is by using HttpClient like this:

public async Task<HttpResponseMessage> PostResult(string url, ResultObject resultObject)
{
    using (var client = new HttpClient())
    {
        HttpResponseMessage response = new HttpResponseMessage();
        try
        {
            response = await client.PostAsJsonAsync(url, resultObject);
        }
        catch (Exception ex)
        {
            throw ex
        }
        return response;
     }
}

C++ performance vs. Java/C#

Whenever I talk managed vs. unmanaged performance, I like to point to the series Rico (and Raymond) did comparing C++ and C# versions of a Chinese/English dictionary. This google search will let you read for yourself, but I like Rico's summary.

So am I ashamed by my crushing defeat? Hardly. The managed code got a very good result for hardly any effort. To defeat the managed Raymond had to:

  • Write his own file I/O stuff
  • Write his own string class
  • Write his own allocator
  • Write his own international mapping

Of course he used available lower level libraries to do this, but that's still a lot of work. Can you call what's left an STL program? I don't think so, I think he kept the std::vector class which ultimately was never a problem and he kept the find function. Pretty much everything else is gone.

So, yup, you can definately beat the CLR. Raymond can make his program go even faster I think.

Interestingly, the time to parse the file as reported by both programs internal timers is about the same -- 30ms for each. The difference is in the overhead.

For me the bottom line is that it took 6 revisions for the unmanaged version to beat the managed version that was a simple port of the original unmanaged code. If you need every last bit of performance (and have the time and expertise to get it), you'll have to go unmanaged, but for me, I'll take the order of magnitude advantage I have on the first versions over the 33% I gain if I try 6 times.

System.Runtime.InteropServices.COMException (0x800A03EC)

Try this as it worked for me...

  1. Go to "Start" -> "Run" and enter "dcomcnfg"
  2. This will bring up the component services window, expand out "Console Root" -> "Computers" -> "DCOM Config"
  3. Find "Microsoft Excel Application" in the list of components.
  4. Right click on the entry and select "Properties"
  5. Go to the "Identity" tab on the properties dialog.
  6. Select "The interactive user."

courtesy of Last paragraph mentioned in here

Center align a column in twitter bootstrap

If you cannot put 1 column, you can simply put 2 column in the middle... (I am just combining answers) For Bootstrap 3

<div class="row">
   <div class="col-lg-5 ">5 columns left</div>
   <div class="col-lg-2 col-centered">2 column middle</div>
   <div class="col-lg-5">5 columns right</div>
</div>

Even, you can text centered column by adding this to style:

.col-centered{
  display: block;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}

Additionally, there is another solution here

Clearing UIWebview cache

I actually think it may retain cached information when you close out the UIWebView. I've tried removing a UIWebView from my UIViewController, releasing it, then creating a new one. The new one remembered exactly where I was at when I went back to an address without having to reload everything (it remembered my previous UIWebView was logged in).

So a couple of suggestions:

[[NSURLCache sharedURLCache] removeCachedResponseForRequest:NSURLRequest];

This would remove a cached response for a specific request. There is also a call that will remove all cached responses for all requests ran on the UIWebView:

[[NSURLCache sharedURLCache] removeAllCachedResponses];

After that, you can try deleting any associated cookies with the UIWebView:

for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

    if([[cookie domain] isEqualToString:someNSStringUrlDomain]) {

        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
}

Swift 3:

// Remove all cache 
URLCache.shared.removeAllCachedResponses()

// Delete any associated cookies     
if let cookies = HTTPCookieStorage.shared.cookies {
    for cookie in cookies {
        HTTPCookieStorage.shared.deleteCookie(cookie)
    }
}

How to position background image in bottom right corner? (CSS)

This should do it:

<style>
body {
    background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>

http://www.w3schools.com/cssref/pr_background-position.asp

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

GO is like the end of a script.

You could have multiple CREATE TABLE statements, separated by GO. It's a way of isolating one part of the script from another, but submitting it all in one block.


BEGIN and END are just like { and } in C/++/#, Java, etc.

They bound a logical block of code. I tend to use BEGIN and END at the start and end of a stored procedure, but it's not strictly necessary there. Where it IS necessary is for loops, and IF statements, etc, where you need more then one step...

IF EXISTS (SELECT * FROM my_table WHERE id = @id)
BEGIN
   INSERT INTO Log SELECT @id, 'deleted'
   DELETE my_table WHERE id = @id
END

How to add "required" attribute to mvc razor viewmodel text input editor

@Erik's answer didn't fly for me.

Following did:

 @Html.TextBoxFor(m => m.ShortName,  new { data_val_required = "You need me" })

plus doing this manually under field I had to add error message container

@Html.ValidationMessageFor(m => m.ShortName, null, new { @class = "field-validation-error", data_valmsg_for = "ShortName" })

Hope this saves you some time.

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

Do we need to execute Commit statement after Update in SQL Server

Sql server unlike oracle does not need commits unless you are using transactions.
Immediatly after your update statement the table will be commited, don't use the commit command in this scenario.

How to allow Cross domain request in apache2

Ubuntu Apache2 solution that worked for me .htaccess edit did not work for me I had to modify the conf file.

nano /etc/apache2/sites-available/mydomain.xyz.conf

my config that worked to allow CORS Support

<IfModule mod_ssl.c>
    <VirtualHost *:443>

        ServerName mydomain.xyz
        ServerAlias www.mydomain.xyz

        ServerAdmin [email protected]
        DocumentRoot /var/www/mydomain.xyz/public

        ### following three lines are for CORS support
        Header add Access-Control-Allow-Origin "*"
        Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
        Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        SSLCertificateFile /etc/letsencrypt/live/mydomain.xyz/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.xyz/privkey.pem

    </VirtualHost>
</IfModule>

then type the following command

a2enmod headers

make sure cache is clear before trying

Detect if a Form Control option button is selected in VBA

You should remove .Value from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.

If you want to run action code when the optionbutton is clicked then don't write an if loop for that.

EXAMPLE:

Sub CommandButton1_Click
    If OptionButton1 = true then
        (action code...)
    End if
End sub

Sub OptionButton1_Click   
    (action code...)
End sub

How to change the default message of the required field in the popover of form-control in bootstrap?

You can use setCustomValidity function when oninvalid event occurs.

Like below:-

<input class="form-control" type="email" required="" 
    placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">
</input>

Update:-

To clear the message once you start entering use oninput="setCustomValidity('') attribute to clear the message.

<input class="form-control" type="email"  required="" placeholder="username"
 oninvalid="this.setCustomValidity('Please Enter valid email')"
 oninput="setCustomValidity('')"></input>

Shrink a YouTube video to responsive width

@magi182's solution is solid, but it lacks the ability to set a maximum width. I think a maximum width of 640px is necessary because otherwhise the youtube thumbnail looks pixelated.

My solution with two wrappers works like a charm for me:

.videoWrapperOuter {
  max-width:640px; 
  margin-left:auto;
  margin-right:auto;
}
.videoWrapperInner {
  float: none;
  clear: both;
  width: 100%;
  position: relative;
  padding-bottom: 50%;
  padding-top: 25px;
  height: 0;
}
.videoWrapperInner iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div class="videoWrapperOuter">
  <div class="videoWrapperInner">
    <iframe src="//www.youtube.com/embed/C6-TWRn0k4I" 
      frameborder="0" allowfullscreen></iframe>
  </div>
</div>

I also set the padding-bottom in the inner wrapper to 50 %, because with @magi182's 56 %, a black bar on top and bottom appeared.

Creating a UITableView Programmatically

- (void)viewDidLoad
{
    [super viewDidLoad];
    tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;

    tableView.backgroundColor = [UIColor grayColor];

    // add to superview
    [self.view addSubview:tableView];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:    (NSInteger)section
{
    return 1;
}

// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"HistoryCell";

    // Similar to UITableViewCell, but 
    UITableViewCell *cell = (UITableViewCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.descriptionLabel.text = @"Testing";
    return cell;
}

How can I plot data with confidence intervals?

Here is part of my program related to plotting confidence interval.

1. Generate the test data

ads = 1
require(stats); require(graphics)
library(splines)
x_raw <- seq(1,10,0.1)
y <- cos(x_raw)+rnorm(len_data,0,0.1)
y[30] <- 1.4 # outlier point
len_data = length(x_raw)
N <- len_data
summary(fm1 <- lm(y~bs(x_raw, df=5), model = TRUE, x =T, y = T))
ht <-seq(1,10,length.out = len_data)
plot(x = x_raw, y = y,type = 'p')
y_e <- predict(fm1, data.frame(height = ht))
lines(x= ht, y = y_e)

Result

enter image description here

2. Fitting the raw data using B-spline smoother method

sigma_e <- sqrt(sum((y-y_e)^2)/N)
print(sigma_e)
H<-fm1$x
A <-solve(t(H) %*% H)
y_e_minus <- rep(0,N)
y_e_plus <- rep(0,N)
y_e_minus[N]
for (i in 1:N)
{
    tmp <-t(matrix(H[i,])) %*% A %*% matrix(H[i,])
    tmp <- 1.96*sqrt(tmp)
    y_e_minus[i] <- y_e[i] - tmp
    y_e_plus[i] <- y_e[i] + tmp
}
plot(x = x_raw, y = y,type = 'p')
polygon(c(ht,rev(ht)),c(y_e_minus,rev(y_e_plus)),col = rgb(1, 0, 0,0.5), border = NA)
#plot(x = x_raw, y = y,type = 'p')
lines(x= ht, y = y_e_plus, lty = 'dashed', col = 'red')
lines(x= ht, y = y_e)
lines(x= ht, y = y_e_minus, lty = 'dashed', col = 'red')

Result

enter image description here

Show an image preview before upload

Here I did with jQuery using FileReader API.

Html Markup:

<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>

jQuery:

Here in jQuery code,first I check for file extension. i.e valid image file to be processed, then will check whether the browser support FileReader API is yes then only processed else display respected message

$("#fileUpload").on('change', function () {

     //Get count of selected files
     var countFiles = $(this)[0].files.length;

     var imgPath = $(this)[0].value;
     var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
     var image_holder = $("#image-holder");
     image_holder.empty();

     if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
         if (typeof (FileReader) != "undefined") {

             //loop for each file selected for uploaded.
             for (var i = 0; i < countFiles; i++) {

                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $("<img />", {
                         "src": e.target.result,
                             "class": "thumb-image"
                     }).appendTo(image_holder);
                 }

                 image_holder.show();
                 reader.readAsDataURL($(this)[0].files[i]);
             }

         } else {
             alert("This browser does not support FileReader.");
         }
     } else {
         alert("Pls select only images");
     }
 });

Detailed Article: How to Preview Image before upload it, jQuery, HTML5 FileReader() with Live Demo

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you really need to use sys.path.insert, consider leaving sys.path[0] as it is:

sys.path.insert(1, path_to_dev_pyworkbooks)

This could be important since 3rd party code may rely on sys.path documentation conformance:

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter.

Why is my Git Submodule HEAD detached from master?

EDIT:

See @Simba Answer for valid solution

submodule.<name>.update is what you want to change, see the docs - default checkout
submodule.<name>.branch specify remote branch to be tracked - default master


OLD ANSWER:

Personally I hate answers here which direct to external links which may stop working over time and check my answer here (Unless question is duplicate) - directing to question which does cover subject between the lines of other subject, but overall equals: "I'm not answering, read the documentation."

So back to the question: Why does it happen?

Situation you described

After pulling changes from server, many times my submodule head gets detached from master branch.

This is a common case when one does not use submodules too often or has just started with submodules. I believe that I am correct in stating, that we all have been there at some point where our submodule's HEAD gets detached.

  • Cause: Your submodule is not tracking correct branch (default master).
    Solution: Make sure your submodule is tracking the correct branch
$ cd <submodule-path>
# if the master branch already exists locally:
# (From git docs - branch)
# -u <upstream>
# --set-upstream-to=<upstream>
#    Set up <branchname>'s tracking information so <upstream>
#    is considered <branchname>'s upstream branch.
#    If no <branchname> is specified, then it defaults to the current branch.
$ git branch -u <origin>/<branch> <branch>
# else:
$ git checkout -b <branch> --track <origin>/<branch>
  • Cause: Your parent repo is not configured to track submodules branch.
    Solution: Make your submodule track its remote branch by adding new submodules with the following two commands.
    • First you tell git to track your remote <branch>.
    • you tell git to perform rebase or merge instead of checkout
    • you tell git to update your submodule from remote.
    $ git submodule add -b <branch> <repository> [<submodule-path>]
    $ git config -f .gitmodules submodule.<submodule-path>.update rebase
    $ git submodule update --remote
  • If you haven't added your existing submodule like this you can easily fix that:
    • First you want to make sure that your submodule has the branch checked out which you want to be tracked.
    $ cd <submodule-path>
    $ git checkout <branch>
    $ cd <parent-repo-path>
    # <submodule-path> is here path releative to parent repo root
    # without starting path separator
    $ git config -f .gitmodules submodule.<submodule-path>.branch <branch>
    $ git config -f .gitmodules submodule.<submodule-path>.update <rebase|merge>

In the common cases, you already have fixed by now your DETACHED HEAD since it was related to one of the configuration issues above.

fixing DETACHED HEAD when .update = checkout

$ cd <submodule-path> # and make modification to your submodule
$ git add .
$ git commit -m"Your modification" # Let's say you forgot to push it to remote.
$ cd <parent-repo-path>
$ git status # you will get
Your branch is up-to-date with '<origin>/<branch>'.
Changes not staged for commit:
    modified:   path/to/submodule (new commits)
# As normally you would commit new commit hash to your parent repo
$ git add -A
$ git commit -m"Updated submodule"
$ git push <origin> <branch>.
$ git status
Your branch is up-to-date with '<origin>/<branch>'.
nothing to commit, working directory clean
# If you now update your submodule
$ git submodule update --remote
Submodule path 'path/to/submodule': checked out 'commit-hash'
$ git status # will show again that (submodule has new commits)
$ cd <submodule-path>
$ git status
HEAD detached at <hash>
# as you see you are DETACHED and you are lucky if you found out now
# since at this point you just asked git to update your submodule
# from remote master which is 1 commit behind your local branch
# since you did not push you submodule chage commit to remote. 
# Here you can fix it simply by. (in submodules path)
$ git checkout <branch>
$ git push <origin>/<branch>
# which will fix the states for both submodule and parent since 
# you told already parent repo which is the submodules commit hash 
# to track so you don't see it anymore as untracked.

But if you managed to make some changes locally already for submodule and commited, pushed these to remote then when you executed 'git checkout ', Git notifies you:

$ git checkout <branch>
Warning: you are leaving 1 commit behind, not connected to any of your branches:
If you want to keep it by creating a new branch, this may be a good time to do so with:

The recommended option to create a temporary branch can be good, and then you can just merge these branches etc. However I personally would use just git cherry-pick <hash> in this case.

$ git cherry-pick <hash> # hash which git showed you related to DETACHED HEAD
# if you get 'error: could not apply...' run mergetool and fix conflicts
$ git mergetool
$ git status # since your modifications are staged just remove untracked junk files
$ rm -rf <untracked junk file(s)>
$ git commit # without arguments
# which should open for you commit message from DETACHED HEAD
# just save it or modify the message.
$ git push <origin> <branch>
$ cd <parent-repo-path>
$ git add -A # or just the unstaged submodule
$ git commit -m"Updated <submodule>"
$ git push <origin> <branch>

Although there are some more cases you can get your submodules into DETACHED HEAD state, I hope that you understand now a bit more how to debug your particular case.

What REALLY happens when you don't free after malloc?

It depends on the scope of the project that you're working on. In the context of your question, and I mean just your question, then it doesn't matter.

For a further explanation (optional), some scenarios I have noticed from this whole discussion is as follow:

(1) - If you're working in an embedded environment where you cannot rely on the main OS' to reclaim the memory for you, then you should free them since memory leaks can really crash the program if done unnoticed.

(2) - If you're working on a personal project where you won't disclose it to anyone else, then you can skip it (assuming you're using it on the main OS') or include it for "best practices" sake.

(3) - If you're working on a project and plan to have it open source, then you need to do more research into your audience and figure out if freeing the memory would be the better choice.

(4) - If you have a large library and your audience consisted of only the main OS', then you don't need to free it as their OS' will help them to do so. In the meantime, by not freeing, your libraries/program may help to make the overall performance snappier since the program does not have to close every data structure, prolonging the shutdown time (imagine a very slow excruciating wait to shut down your computer before leaving the house...)

I can go on and on specifying which course to take, but it ultimately depends on what you want to achieve with your program. Freeing memory is considered good practice in some cases and not so much in some so it ultimately depends on the specific situation you're in and asking the right questions at the right time. Good luck!

.NET - Get protocol, host, and port

Even though @Rick has the accepted answer for this question, there's actually a shorter way to do this, using the poorly named Uri.GetLeftPart() method.

Uri url = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string output = url.GetLeftPart(UriPartial.Authority);

There is one catch to GetLeftPart(), however. If the port is the default port for the scheme, it will strip it out. Since port 80 is the default port for http, the output of GetLeftPart() in my example above will be http://www.mywebsite.com.

If the port number had been something other than 80, it would be included in the result.

Transition of background-color

As far as I know, transitions currently work in Safari, Chrome, Firefox, Opera and Internet Explorer 10+.

This should produce a fade effect for you in these browsers:

_x000D_
_x000D_
a {_x000D_
    background-color: #FF0;_x000D_
}_x000D_
_x000D_
a:hover {_x000D_
    background-color: #AD310B;_x000D_
    -webkit-transition: background-color 1000ms linear;_x000D_
    -ms-transition: background-color 1000ms linear;_x000D_
    transition: background-color 1000ms linear;_x000D_
}
_x000D_
<a>Navigation Link</a>
_x000D_
_x000D_
_x000D_

Note: As pointed out by Gerald in the comments, if you put the transition on the a, instead of on a:hover it will fade back to the original color when your mouse moves away from the link.

This might come in handy, too: CSS Fundamentals: CSS 3 Transitions

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Many times I have been facing this problem, I have experienced ClassNotFoundException. if jar is not at physical location.

So make sure .jar file(mysql connector) in the physical location of WEB-INF lib folder. and make sure restarting Tomcat by using shutdown command in cmd. it should work.

How to redirect to another page in node.js

In another way you can use window.location.href="your URL"

e.g.:

res.send('<script>window.location.href="your URL";</script>');

or:

return res.redirect("your url");

1052: Column 'id' in field list is ambiguous

You would do that by providing a fully qualified name, e.g.:

SELECT tbl_names.id as id, name, section FROM tbl_names, tbl_section WHERE tbl_names.id = tbl_section.id

Which would give you the id of tbl_names

How to correctly save instance state of Fragments in back stack?

To correctly save the instance state of Fragment you should do the following:

1. In the fragment, save instance state by overriding onSaveInstanceState() and restore in onActivityCreated():

class MyFragment extends Fragment {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ...
        if (savedInstanceState != null) {
            //Restore the fragment's state here
        }
    }
    ...
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //Save the fragment's state here
    }

}

2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState() and restore in onCreate().

class MyActivity extends Activity {

    private MyFragment 

    public void onCreate(Bundle savedInstanceState) {
        ...
        if (savedInstanceState != null) {
            //Restore the fragment's instance
            mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
            ...
        }
        ...
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //Save the fragment's instance
        getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
    }

}

Hope this helps.

Add a new column to existing table in a migration

You can add new columns within the initial Schema::create method like this:

Schema::create('users', function($table) {
    $table->integer("paied");
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

If you have already created a table you can add additional columns to that table by creating a new migration and using the Schema::table method:

Schema::table('users', function($table) {
    $table->string("title");
    $table->text("description");
    $table->timestamps();
});

The documentation is fairly thorough about this, and hasn't changed too much from version 3 to version 4.

how to set background image in submit button?

i do it like this cover button and the middle image that

<button><img src="foldername/imagename" width="30px" height= "30px"></button>

checking if number entered is a digit in jquery

Value validation wouldn't be a responsibility of jQuery. You can use pure JavaScript for this. Two ways that come to my mind are:

/^\d+$/.match(value)
Number(value) == value

How to format DateTime to 24 hours time?

Console.WriteLine(curr.ToString("HH:mm"));

How to commit and rollback transaction in sql server?

As per http://msdn.microsoft.com/en-us/library/ms188790.aspx

@@ERROR: Returns the error number for the last Transact-SQL statement executed.

You will have to check after each statement in order to perform the rollback and return.

Commit can be at the end.

HTH

Conditionally change img src based on model data

For angular 4 I have used

<img [src]="data.pic ? data.pic : 'assets/images/no-image.png' " alt="Image" title="Image">

It works for me , I hope it may use to other's also for Angular 4-5. :)

Insert Unicode character into JavaScript

I'm guessing that you actually want Omega to be a string containing an uppercase omega? In that case, you can write:

var Omega = '\u03A9';

(Because Ω is the Unicode character with codepoint U+03A9; that is, 03A9 is 937, except written as four hexadecimal digits.)

Sort ArrayList of custom Objects by property

Since Date implements Comparable, it has a compareTo method just like String does.

So your custom Comparator could look like this:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
}

The compare() method must return an int, so you couldn't directly return a boolean like you were planning to anyway.

Your sorting code would be just about like you wrote:

Collections.sort(Database.arrayList, new CustomComparator());

A slightly shorter way to write all this, if you don't need to reuse your comparator, is to write it as an inline anonymous class:

Collections.sort(Database.arrayList, new Comparator<MyObject>() {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        return o1.getStartDate().compareTo(o2.getStartDate());
    }
});

Since

You can now write the last example in a shorter form by using a lambda expression for the Comparator:

Collections.sort(Database.arrayList, 
                        (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

And List has a sort(Comparator) method, so you can shorten this even further:

Database.arrayList.sort((o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));

This is such a common idiom that there's a built-in method to generate a Comparator for a class with a Comparable key:

Database.arrayList.sort(Comparator.comparing(MyObject::getStartDate));

All of these are equivalent forms.

Get table name by constraint name

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

will give you what you need

How to select last one week data from today's date

to select records for the last 7 days

WHERE Created_Date >= DATEADD(day, -7, GETDATE())

to select records for the current week

SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM
WHERE CreatedDate >= DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE())) 
  AND CreatedDate <  DATEADD(day, 8 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))

if you want to select records for last week instead of the last 7 days

SET DATEFIRST 1 -- Define beginning of week as Monday
SELECT * FROM  
WHERE CreatedDate >= DATEADD(day, -(DATEPART(dw, GETDATE()) + 6), CONVERT(DATE, GETDATE())) 
  AND CreatedDate <  DATEADD(day, 1 - DATEPART(dw, GETDATE()), CONVERT(DATE, GETDATE()))

How to find out which package version is loaded in R?

Search() can give a more simplified list of the attached packages in a session (i.e., without the detailed info given by sessionInfo())

search {base}- R Documentation
Description: Gives a list of attached packages. Search()

search()
#[1] ".GlobalEnv"        "package:Rfacebook" "package:httpuv"   
#"package:rjson"    
#[5] "package:httr"      "package:bindrcpp"  "package:forcats"   # 
#"package:stringr"  
#[9] "package:dplyr"     "package:purrr"     "package:readr"     
#"package:tidyr"    
#[13] "package:tibble"    "package:ggplot2"   "package:tidyverse" 
#"tools:rstudio"    
#[17] "package:stats"     "package:graphics"  "package:grDevices" 
#"package:utils"    
#[21] "package:datasets"  "package:methods"   "Autoloads"         
#"package:base"

How can I autoformat/indent C code in vim?

Their is a tool called indent. You can download it with apt-get install indent, then run indent my_program.c.

How can I start pagenumbers, where the first section occurs in LaTex?

I use

\pagenumbering{roman}

for everything in the frontmatter and then switch over to

\pagenumbering{arabic}

for the actual content. With pdftex, the page numbers come out right in the PDF file.

What is the easiest way to initialize a std::vector with hardcoded elements?

There are a lot of good answers here, but since I independently arrived at my own before reading this, I figured I'd toss mine up here anyway...

Here's a method that I'm using for this which will work universally across compilers and platforms:

Create a struct or class as a container for your collection of objects. Define an operator overload function for <<.

class MyObject;

struct MyObjectList
{
    std::list<MyObject> objects;
    MyObjectList& operator<<( const MyObject o )
    { 
        objects.push_back( o );
        return *this; 
    }
};

You can create functions which take your struct as a parameter, e.g.:

someFunc( MyObjectList &objects );

Then, you can call that function, like this:

someFunc( MyObjectList() << MyObject(1) <<  MyObject(2) <<  MyObject(3) );

That way, you can build and pass a dynamically sized collection of objects to a function in one single clean line!

How can I simulate an array variable in MySQL?

Inspired by the function ELT(index number, string1, string2, string3,…),I think the following example works as an array example:

set @i := 1;
while @i <= 3
do
  insert into table(val) values (ELT(@i ,'val1','val2','val3'...));
set @i = @i + 1;
end while;

Hope it help.

Converting a pointer into an integer

Use intptr_t and uintptr_t.

To ensure it is defined in a portable way, you can use code like this:

#if defined(__BORLANDC__)
    typedef unsigned char uint8_t;
    typedef __int64 int64_t;
    typedef unsigned long uintptr_t;
#elif defined(_MSC_VER)
    typedef unsigned char uint8_t;
    typedef __int64 int64_t;
#else
    #include <stdint.h>
#endif

Just place that in some .h file and include wherever you need it.

Alternatively, you can download Microsoft’s version of the stdint.h file from here or use a portable one from here.

Generate a UUID on iOS from Swift

Try this one:

let uuid = NSUUID().uuidString
print(uuid)

Swift 3/4/5

let uuid = UUID().uuidString
print(uuid)

sequelize findAll sort order in nodejs

In sequelize you can easily add order by clauses.

exports.getStaticCompanies = function () {
    return Company.findAll({
        where: {
            id: [46128, 2865, 49569,  1488,   45600,   61991,  1418,  61919,   53326,   61680]
        }, 
        // Add order conditions here....
        order: [
            ['id', 'DESC'],
            ['name', 'ASC'],
        ],
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at']
    });
};

See how I've added the order array of objects?

order: [
      ['COLUMN_NAME_EXAMPLE', 'ASC'], // Sorts by COLUMN_NAME_EXAMPLE in ascending order
],

Edit:

You might have to order the objects once they've been recieved inside the .then() promise. Checkout this question about ordering an array of objects based on a custom order:

How do I sort an array of objects based on the ordering of another array?

What is the '.well' equivalent class in Bootstrap 4

None of the answers seemed to work well with buttons. Bootstrap v4.1.1

<div class="card bg-light">
    <div class="card-body">
        <button type="submit" class="btn btn-primary">
            Save
        </button>
        <a href="/" class="btn btn-secondary">
            Cancel
        </a>
    </div>
</div>

Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET

I had a similar issue using Apache 2.4 and PHP 7.

My client sent a lot of requests when refreshing (hard reloading) my application page in the browser and every time some of the last requests resulted in this error in console:

GET http://example.com/api/v1/my/resource net::ERR_CONNECTION_RESET

It turned out that my client was reaching the maximum amount of threads that was allowed. The threads exceeding this configured ceiling are simply not handled by Apache at all resulting in the connection reset error response.

The amount of threads can be easily raised by setting the ThreadsPerChild value for the module in question.
The easiest way to make such change is to uncomment the Server-pool management config file conf/extra/httpd-mpm.conf and then editing the preset values in the file to desired values.

1) Uncomment the Server-pool management file

# Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf

2) Open and edit the file conf/extra/httpd-mpm.conf and raise the amount of threads

In my case I had to change the threads for the mpm_winnt_module:

# raised the amount of threads for mpm_winnt_module to 250
<IfModule mpm_winnt_module>
    ThreadsPerChild        250
    MaxConnectionsPerChild   0
</IfModule>

A comprehensive explanation on these Server-pool management configuration settings can be found in this post on StackOverflow.

C free(): invalid pointer

You can't call free on the pointers returned from strsep. Those are not individually allocated strings, but just pointers into the string s that you've already allocated. When you're done with s altogether, you should free it, but you do not have to do that with the return values of strsep.

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

What is causing this error - "Fatal error: Unable to find local grunt"

Could be a few problems here depending on what version of grunt is being used. Newer versions of grunt actually specify that you have a file named Gruntfile.js (instead of the old grunt.js).

You should have the grunt-cli tool be installed globally (this is done via npm install -g grunt-cli). This allows you to actually run grunt commands from the command line.

Secondly make sure you've installed grunt locally for your project. If you see your package.json doesn't have something like "grunt": "0.4.5" in it then you should do npm install grunt --save in your project directory.

Why does Eclipse complain about @Override on interface methods?

You can also try Retroweaver to create the Java5 version from Java6 classes.

How to remove the first Item from a list?

You can use list.reverse() to reverse the list, then list.pop() to remove the last element, for example:

l = [0, 1, 2, 3, 4]
l.reverse()
print l
[4, 3, 2, 1, 0]


l.pop()
0
l.pop()
1
l.pop()
2
l.pop()
3
l.pop()
4

Sending and receiving data over a network using TcpClient

First, I recommend that you use WCF, .NET Remoting, or some other higher-level communication abstraction. The learning curve for "simple" sockets is nearly as high as WCF, because there are so many non-obvious pitfalls when using TCP/IP directly.

If you decide to continue down the TCP/IP path, then review my .NET TCP/IP FAQ, particularly the sections on message framing and application protocol specifications.

Also, use asynchronous socket APIs. The synchronous APIs do not scale and in some error situations may cause deadlocks. The synchronous APIs make for pretty little example code, but real-world production-quality code uses the asynchronous APIs.

AngularJS - Create a directive that uses ng-model

it' s not so complicated: in your dirctive, use an alias: scope:{alias:'=ngModel'}

.directive('dateselect', function () {
return {
    restrict: 'E',
    transclude: true,
    scope:{
        bindModel:'=ngModel'
    },
    template:'<input ng-model="bindModel"/>'
}

in your html, use as normal

<dateselect ng-model="birthday"></dateselect>

Creating a file only if it doesn't exist in Node.js

This method is no longer recommended. fs.exists is deprecated. See comments.

Here are some options:

1) Have 2 "fs" calls. The first one is the "fs.exists" call, and the second is "fs.write / read, etc"

//checks if the file exists. 
//If it does, it just calls back.
//If it doesn't, then the file is created.
function checkForFile(fileName,callback)
{
    fs.exists(fileName, function (exists) {
        if(exists)
        {
            callback();
        }else
        {
            fs.writeFile(fileName, {flag: 'wx'}, function (err, data) 
            { 
                callback();
            })
        }
    });
}

function writeToFile()
{
    checkForFile("file.dat",function()
    {
       //It is now safe to write/read to file.dat
       fs.readFile("file.dat", function (err,data) 
       {
          //do stuff
       });
    });
}

2) Or Create an empty file first:

--- Sync:

//If you want to force the file to be empty then you want to use the 'w' flag:

var fd = fs.openSync(filepath, 'w');

//That will truncate the file if it exists and create it if it doesn't.

//Wrap it in an fs.closeSync call if you don't need the file descriptor it returns.

fs.closeSync(fs.openSync(filepath, 'w'));

--- ASync:

var fs = require("fs");
fs.open(path, "wx", function (err, fd) {
    // handle error
    fs.close(fd, function (err) {
        // handle error
    });
});

3) Or use "touch": https://github.com/isaacs/node-touch

ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored

It means the path you input caused an error. In your LD_PRELOAD command, modify the path like the error tips:

/usr/lib/liblunar-calendar-preload.so

Git Bash: Could not open a connection to your authentication agent

Try using cygwin instead of bash. that worked for me

Convert datetime value into string

This is super old, but I figured I'd add my 2c. DATE_FORMAT does indeed return a string, but I was looking for the CAST function, in the situation that I already had a datetime string in the database and needed to pattern match against it:

http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

In this case, you'd use:

CAST(date_value AS char)

This answers a slightly different question, but the question title seems ambiguous enough that this might help someone searching.

Regex date format validation on Java

Construct a SimpleDateFormat with the mask, and then call: SimpleDateFormat.parse(String s, ParsePosition p)

Can gcc output C code after preprocessing?

I'm using gcc as a preprocessor (for html files.) It does just what you want. It expands "#--" directives, then outputs a readable file. (NONE of the other C/HTML preprocessors I've tried do this- they concatenate lines, choke on special characters, etc.) Asuming you have gcc installed, the command line is:

gcc -E -x c -P -C -traditional-cpp code_before.cpp > code_after.cpp

(Doesn't have to be 'cpp'.) There's an excellent description of this usage at http://www.cs.tut.fi/~jkorpela/html/cpre.html.

The "-traditional-cpp" preserves whitespace & tabs.

round value to 2 decimals javascript

Just multiply the number by 100, round, and divide the resulting number by 100.

Compare two files report difference in python

The difflib library is useful for this, and comes in the standard library. I like the unified diff format.

http://docs.python.org/2/library/difflib.html#difflib.unified_diff

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
        )
        for line in diff:
            sys.stdout.write(line)

Outputs:

--- hosts0
+++ hosts1
@@ -1,5 +1,4 @@
 one
 two
-dogs
 three

And here is a dodgy version that ignores certain lines. There might be edge cases that don't work, and there are surely better ways to do this, but maybe it will be good enough for your purposes.

import difflib
import sys

with open('/tmp/hosts0', 'r') as hosts0:
    with open('/tmp/hosts1', 'r') as hosts1:
        diff = difflib.unified_diff(
            hosts0.readlines(),
            hosts1.readlines(),
            fromfile='hosts0',
            tofile='hosts1',
            n=0,
        )
        for line in diff:
            for prefix in ('---', '+++', '@@'):
                if line.startswith(prefix):
                    break
            else:
                sys.stdout.write(line[1:])

SQL Server copy all rows from one table into another i.e duplicate table

select * into x_history from your_table_here;
truncate table your_table_here;

How to set host_key_checking=false in ansible inventory file?

Adding following to ansible config worked while using ansible ad-hoc commands:

[ssh_connection]
# ssh arguments to use
ssh_args = -o StrictHostKeyChecking=no

Ansible Version

ansible 2.1.6.0
config file = /etc/ansible/ansible.cfg

iframe refuses to display

It means that the http server at cw.na1.hgncloud.com send some http headers to tell web browsers like Chrome to allow iframe loading of that page (https://cw.na1.hgncloud.com/crossmatch/) only from a page hosted on the same domain (cw.na1.hgncloud.com) :

Content-Security-Policy: frame-ancestors 'self' https://cw.na1.hgncloud.com
X-Frame-Options: ALLOW-FROM https://cw.na1.hgncloud.com

You should read that :

How to Execute SQL Server Stored Procedure in SQL Developer?

You need to add a ',' between the paramValue1 and paramValue2. You missed it.

EXEC proc_name 'paramValue1','paramValue2'

How to get request URL in Spring Boot RestController

You may try adding an additional argument of type HttpServletRequest to the getUrlValue() method:

@RequestMapping(value ="/",produces = "application/json")
public String getURLValue(HttpServletRequest request){
    String test = request.getRequestURI();
    return test;
}

How to correctly iterate through getElementsByClassName

If you use the new querySelectorAll you can call forEach directly.

document.querySelectorAll('.edit').forEach(function(button) {
    // Now do something with my button
});

Per the comment below. nodeLists do not have a forEach function.

If using this with babel you can add Array.from and it will convert non node lists to a forEach array. Array.from does not work natively in browsers below and including IE 11.

Array.from(document.querySelectorAll('.edit')).forEach(function(button) {
    // Now do something with my button
});

At our meetup last night I discovered another way to handle node lists not having forEach

[...document.querySelectorAll('.edit')].forEach(function(button) {
    // Now do something with my button
});

Browser Support for [...]

Showing as Node List

Showing as Node List

Showing as Array

Showing as Array

Why should Java 8's Optional not be used in arguments

Accepting Optional as parameters causes unnecessary wrapping at caller level.

For example in the case of:

public int calculateSomething(Optional<String> p1, Optional<BigDecimal> p2 {}

Suppose you have two not-null strings (ie. returned from some other method):

String p1 = "p1"; 
String p2 = "p2";

You're forced to wrap them in Optional even if you know they are not Empty.

This get even worse when you have to compose with other "mappable" structures, ie. Eithers:

Either<Error, String> value = compute().right().map((s) -> calculateSomething(
< here you have to wrap the parameter in a Optional even if you know it's a 
  string >));

ref:

methods shouldn't expect Option as parameters, this is almost always a code smell that indicated a leakage of control flow from the caller to the callee, it should be responsibility of the caller to check the content of an Option

ref. https://github.com/teamdigitale/digital-citizenship-functions/pull/148#discussion_r170862749

Make function wait until element exists

This will only work with modern browsers but I find it easier to just use a then so please test first but:

Code

function rafAsync() {
    return new Promise(resolve => {
        requestAnimationFrame(resolve); //faster than set time out
    });
}

function checkElement(selector) {
    if (document.querySelector(selector) === null) {
        return rafAsync().then(() => checkElement(selector));
    } else {
        return Promise.resolve(true);
    }
}

Or using generator functions

async function checkElement(selector) {
    const querySelector = null;
    while (querySelector === null) {
        await rafAsync();
        querySelector = document.querySelector(selector);
    }
    return querySelector;
}  

Usage

checkElement('body') //use whichever selector you want
.then((element) => {
     console.info(element);
     //Do whatever you want now the element is there
});

How do I get the latest version of my code?

If the above commands didn't help you use this method:

  1. Go to the git archive where you have Fork
  2. Click Settings> Scroll down and click Delete this repository
  3. Confirm delete
  4. Fork again, and re-enter the git clone <url_git>
  5. You already have the latest version

How do I tell Maven to use the latest version of a dependency?

Sometimes you don't want to use version ranges, because it seems that they are "slow" to resolve your dependencies, especially when there is continuous delivery in place and there are tons of versions - mainly during heavy development.

One workaround would be to use the versions-maven-plugin. For example, you can declare a property:

<properties>
    <myname.version>1.1.1</myname.version>
</properties>

and add the versions-maven-plugin to your pom file:

<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>versions-maven-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <properties>
                    <property>
                        <name>myname.version</name>
                        <dependencies>
                            <dependency>
                                <groupId>group-id</groupId>
                                <artifactId>artifact-id</artifactId>
                                <version>latest</version>
                            </dependency>
                        </dependencies>
                    </property>
                </properties>
            </configuration>
        </plugin>
    </plugins>
</build>

Then, in order to update the dependency, you have to execute the goals:

mvn versions:update-properties validate

If there is a version newer than 1.1.1, it will tell you:

[INFO] Updated ${myname.version} from 1.1.1 to 1.3.2

How to convert a DataFrame back to normal RDD in pyspark?

@dapangmao's answer works, but it doesn't give the regular spark RDD, it returns a Row object. If you want to have the regular RDD format.

Try this:

rdd = df.rdd.map(tuple)

or

rdd = df.rdd.map(list)

JSON Invalid UTF-8 middle byte

This awnser solved my problem. Below is a copy of it:

Make sure to start you JVM with -Dfile.encoding=UTF-8. You JVM defaults to the operating system charset

This is a JVM argument which could be added, for example, either to JBoss standalone or JBoss running from Eclipse.

In my case, this problem happened isolatelly on only one of my team people's computer. All the others was working without this problem.

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

I know it's quite an old question, but since this is one of top results in google... I had to somehow cancel scroll bubbling without jQuery and this code works for me:

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
    e.preventDefault();
  e.returnValue = false;  
}

document.getElementById('a').onmousewheel = function(e) { 
  document.getElementById('a').scrollTop -= e. wheelDeltaY; 
  preventDefault(e);
}

Display HTML form values in same page after submit using Ajax

One more way to do it (if you use form), note that input type is button

<input type="button" onclick="showMessage()" value="submit" />

Complete code is:

<!DOCTYPE html>
<html>
<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
        function showMessage(){
            var message = document.getElementById("message").value;
            display_message.innerHTML= message;
        }
    </script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

But you can do it even without form:

<!DOCTYPE html>
<html>
<head>
    <title>HTML JavaScript output on same page</title>
    <script type="text/JavaScript">
        function showMessage(){
            var message = document.getElementById("message").value;
            display_message.innerHTML= message;
        }
    </script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>

Here you can use either submit or button:

<input type="submit" onclick="showMessage()" value="submit" />

No need to set

return false;

from JavaScript function for neither of those two examples.

How to extract filename.tar.gz file

I have the same error the result of command :

file hadoop-2.7.2.tar.gz

is hadoop-2.7.2.tar.gz: HTML document, ASCII text

the reason that the file is not gzip format due to problem in download or other.

Android Completely transparent Status Bar?

To draw your layout under statusbar:

values/styles.xml

<item name="android:windowTranslucentStatus">true</item>

values-v21/styles.xml

<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@color/colorPrimaryDark</item>

Use CoordinatorLayout/DrawerLayout which already take care of the fitsSystemWindows parameter or create your own layout to like this:

public class FitsSystemWindowConstraintLayout extends ConstraintLayout {

    private Drawable mStatusBarBackground;
    private boolean mDrawStatusBarBackground;

    private WindowInsetsCompat mLastInsets;

    private Map<View, int[]> childsMargins = new HashMap<>();

    public FitsSystemWindowConstraintLayout(Context context) {
        this(context, null);
    }

    public FitsSystemWindowConstraintLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FitsSystemWindowConstraintLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        if (ViewCompat.getFitsSystemWindows(this)) {
            ViewCompat.setOnApplyWindowInsetsListener(this, new android.support.v4.view.OnApplyWindowInsetsListener() {
                @Override
                public WindowInsetsCompat onApplyWindowInsets(View view, WindowInsetsCompat insets) {
                    FitsSystemWindowConstraintLayout layout = (FitsSystemWindowConstraintLayout) view;
                    layout.setChildInsets(insets, insets.getSystemWindowInsetTop() > 0);
                    return insets.consumeSystemWindowInsets();
                }
            });
            setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
            TypedArray typedArray = context.obtainStyledAttributes(new int[]{android.R.attr.colorPrimaryDark});
            try {
                mStatusBarBackground = typedArray.getDrawable(0);
            } finally {
                typedArray.recycle();
            }
        } else {
            mStatusBarBackground = null;
        }
    }

    public void setChildInsets(WindowInsetsCompat insets, boolean draw) {
        mLastInsets = insets;
        mDrawStatusBarBackground = draw;
        setWillNotDraw(!draw && getBackground() == null);

        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                if (ViewCompat.getFitsSystemWindows(this)) {
                    ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) child.getLayoutParams();

                    if (ViewCompat.getFitsSystemWindows(child)) {
                        ViewCompat.dispatchApplyWindowInsets(child, insets);
                    } else {
                        int[] childMargins = childsMargins.get(child);
                        if (childMargins == null) {
                            childMargins = new int[]{layoutParams.leftMargin, layoutParams.topMargin, layoutParams.rightMargin, layoutParams.bottomMargin};
                            childsMargins.put(child, childMargins);
                        }
                        if (layoutParams.leftToLeft == LayoutParams.PARENT_ID) {
                            layoutParams.leftMargin = childMargins[0] + insets.getSystemWindowInsetLeft();
                        }
                        if (layoutParams.topToTop == LayoutParams.PARENT_ID) {
                            layoutParams.topMargin = childMargins[1] + insets.getSystemWindowInsetTop();
                        }
                        if (layoutParams.rightToRight == LayoutParams.PARENT_ID) {
                            layoutParams.rightMargin = childMargins[2] + insets.getSystemWindowInsetRight();
                        }
                        if (layoutParams.bottomToBottom == LayoutParams.PARENT_ID) {
                            layoutParams.bottomMargin = childMargins[3] + insets.getSystemWindowInsetBottom();
                        }
                    }
                }
            }
        }

        requestLayout();
    }

    public void setStatusBarBackground(Drawable bg) {
        mStatusBarBackground = bg;
        invalidate();
    }

    public Drawable getStatusBarBackgroundDrawable() {
        return mStatusBarBackground;
    }

    public void setStatusBarBackground(int resId) {
        mStatusBarBackground = resId != 0 ? ContextCompat.getDrawable(getContext(), resId) : null;
        invalidate();
    }

    public void setStatusBarBackgroundColor(@ColorInt int color) {
        mStatusBarBackground = new ColorDrawable(color);
        invalidate();
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mDrawStatusBarBackground && mStatusBarBackground != null) {
            int inset = mLastInsets != null ? mLastInsets.getSystemWindowInsetTop() : 0;
            if (inset > 0) {
                mStatusBarBackground.setBounds(0, 0, getWidth(), inset);
                mStatusBarBackground.draw(canvas);
            }
        }
    }
}

main_activity.xml

<FitsSystemWindowConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:fitsSystemWindows="true"
        android:scaleType="centerCrop"
        android:src="@drawable/toolbar_background"
        app:layout_constraintBottom_toBottomOf="@id/toolbar"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="0dp"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/transparent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:gravity="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolbar">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Content"
            android:textSize="48sp" />
    </LinearLayout>
</FitsSystemWindowConstraintLayout>

Result:

Screenshot:
Screenshot

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Simplest - and I changed the checkbox class to ID as well:

_x000D_
_x000D_
$(function() {_x000D_
  $("#coupon_question").on("click",function() {_x000D_
    $(".answer").toggle(this.checked);_x000D_
  });_x000D_
});
_x000D_
.answer { display:none }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<fieldset class="question">_x000D_
  <label for="coupon_question">Do you have a coupon?</label>_x000D_
  <input id="coupon_question" type="checkbox" name="coupon_question" value="1" />_x000D_
  <span class="item-text">Yes</span>_x000D_
</fieldset>_x000D_
_x000D_
<fieldset class="answer">_x000D_
  <label for="coupon_field">Your coupon:</label>_x000D_
  <input type="text" name="coupon_field" id="coupon_field" />_x000D_
</fieldset>
_x000D_
_x000D_
_x000D_

How to get row number from selected rows in Oracle

There is no inherent ordering to a table. So, the row number itself is a meaningless metric.

However, you can get the row number of a result set by using the ROWNUM psuedocolumn or the ROW_NUMBER() analytic function, which is more powerful.

As there is no ordering to a table both require an explicit ORDER BY clause in order to work.

select rownum, a.*
  from ( select *
           from student
          where name like '%ram%'
          order by branch
                ) a

or using the analytic query

select row_number() over ( order by branch ) as rnum, a.*
  from student
 where name like '%ram%'

Your syntax where name is like ... is incorrect, there's no need for the IS, so I've removed it.

The ORDER BY here relies on a binary sort, so if a branch starts with anything other than B the results may be different, for instance b is greater than B.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

Trivial as it may seem in my case netbeans version maven project 7.2.1 was different. There is a folder in the project called dependencies. Right click and then it brings up a popup window where you can search for packages. In the query area put

mysql-connector

It will bring up the matches (it seems it does this against some repository). Double click then install.

Iteration over std::vector: unsigned vs signed index variable

Use size_t :

for (size_t i=0; i < polygon.size(); i++)

Quoting Wikipedia:

The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.

The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.

How to set socket timeout in C when making multiple connections?

connect timeout has to be handled with a non-blocking socket (GNU LibC documentation on connect). You get connect to return immediately and then use select to wait with a timeout for the connection to complete.

This is also explained here : Operation now in progress error on connect( function) error.

int wait_on_sock(int sock, long timeout, int r, int w)
{
    struct timeval tv = {0,0};
    fd_set fdset;
    fd_set *rfds, *wfds;
    int n, so_error;
    unsigned so_len;

    FD_ZERO (&fdset);
    FD_SET  (sock, &fdset);
    tv.tv_sec = timeout;
    tv.tv_usec = 0;

    TRACES ("wait in progress tv={%ld,%ld} ...\n",
            tv.tv_sec, tv.tv_usec);

    if (r) rfds = &fdset; else rfds = NULL;
    if (w) wfds = &fdset; else wfds = NULL;

    TEMP_FAILURE_RETRY (n = select (sock+1, rfds, wfds, NULL, &tv));
    switch (n) {
    case 0:
        ERROR ("wait timed out\n");
        return -errno;
    case -1:
        ERROR_SYS ("error during wait\n");
        return -errno;
    default:
        // select tell us that sock is ready, test it
        so_len = sizeof(so_error);
        so_error = 0;
        getsockopt (sock, SOL_SOCKET, SO_ERROR, &so_error, &so_len);
        if (so_error == 0)
            return 0;
        errno = so_error;
        ERROR_SYS ("wait failed\n");
        return -errno;
    }
}

Take the content of a list and append it to another list

Take a look at itertools.chain for a fast way to treat many small lists as a single big list (or at least as a single big iterable) without copying the smaller lists:

>>> import itertools
>>> p = ['a', 'b', 'c']
>>> q = ['d', 'e', 'f']
>>> r = ['g', 'h', 'i']
>>> for x in itertools.chain(p, q, r):
        print x.upper()

c# Image resizing to different size while preserving aspect ratio

Maintain aspect Ration and eliminate letterbox and Pillarbox.

static Image FixedSize(Image imgPhoto, int Width, int Height)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int X = 0;
        int Y = 0;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)Width / (float)sourceWidth);
        nPercentH = ((float)Height / (float)sourceHeight);
        if (nPercentH < nPercentW)
        {
            nPercent = nPercentH;
        }
        else
        {
            nPercent = nPercentW;
        }

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);

        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                                         imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);

        grPhoto.DrawImage(imgPhoto,
                new Rectangle(X, Y, destWidth, destHeight),
                new Rectangle(X, Y, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }

Verify object attribute value with mockito

One more possibility, if you don't want to use ArgumentCaptor (for example, because you're also using stubbing), is to use Hamcrest Matchers in combination with Mockito.

import org.mockito.Mockito
import org.hamcrest.Matchers
...

Mockito.verify(mockedObject).someMethodOnMockedObject(MockitoHamcrest.argThat(
    Matchers.<SomeObjectAsArgument>hasProperty("propertyName", desiredValue)));

Nesting await in Parallel.ForEach

You can save effort with the new AsyncEnumerator NuGet Package, which didn't exist 4 years ago when the question was originally posted. It allows you to control the degree of parallelism:

using System.Collections.Async;
...

await ids.ParallelForEachAsync(async i =>
{
    ICustomerRepo repo = new CustomerRepo();
    var cust = await repo.GetCustomer(i);
    customers.Add(cust);
},
maxDegreeOfParallelism: 10);

Disclaimer: I'm the author of the AsyncEnumerator library, which is open source and licensed under MIT, and I'm posting this message just to help the community.

Scaling a System.Drawing.Bitmap to a given size while maintaining aspect ratio

The bitmap constructor has resizing built in.

Bitmap original = (Bitmap)Image.FromFile("DSC_0002.jpg");
Bitmap resized = new Bitmap(original,new Size(original.Width/4,original.Height/4));
resized.Save("DSC_0002_thumb.jpg");

http://msdn.microsoft.com/en-us/library/0wh0045z.aspx

If you want control over interpolation modes see this post.

dd: How to calculate optimal blocksize?

  • for better performace use the biggest blocksize you RAM can accomodate (will send less I/O calls to the OS)
  • for better accurancy and data recovery set the blocksize to the native sector size of the input

As dd copies data with the conv=noerror,sync option, any errors it encounters will result in the remainder of the block being replaced with zero-bytes. Larger block sizes will copy more quickly, but each time an error is encountered the remainder of the block is ignored.

source

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

How do I import CSV file into a MySQL table?

Change servername,username, password,dbname,path of your file, tablename and the field which is in your database you want to insert

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "bd_dashboard";
    //For create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    $query = "LOAD DATA LOCAL INFILE 
                'C:/Users/lenovo/Desktop/my_data.csv'
                INTO TABLE test_tab
                FIELDS TERMINATED BY ','
                LINES TERMINATED BY '\n'
                IGNORE 1 LINES
                (name,mob)";
    if (!$result = mysqli_query($conn, $query)){
        echo '<script>alert("Oops... Some Error occured.");</script>';
        exit();
            //exit(mysqli_error());
       }else{
        echo '<script>alert("Data Inserted Successfully.");</script>'
       }
    ?>

How do I merge changes to a single file, rather than merging commits?

The following command will (1) compare the file of the correct branch, to master (2) interactively ask you which modifications to apply.

git checkout --patch master

How do I change the hover over color for a hover over table in Bootstrap?

Instead of changing the default table-hover class, make a new class ( anotherhover ) and apply it to the table that you need this effect for.

Code as below;

.anotherhover tbody tr:hover td { background: CornflowerBlue; }

Disable Drag and Drop on HTML elements?

You can disable dragging simply by using draggable="false" attribute.
http://www.w3schools.com/tags/att_global_draggable.asp

Is it fine to have foreign key as primary key?

Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship. If you want the same user record to have the possibility of having more than 1 related profile record, go with a separate primary key, otherwise stick with what you have.

How do I check to see if my array includes an object?

This ...

horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.exists?(horse.id)
   @suggested_horses<< horse
end

Should probably be this ...

horse = Horse.find(:first,:offset=>rand(Horse.count))
unless @suggested_horses.include?(horse)
   @suggested_horses<< horse
end

HTML: Select multiple as dropdown

Here is the documentation of <select>. You are using 2 attributes:

multiple
This Boolean attribute indicates that multiple options can be selected in the list. If it is not specified, then only one option can be selected at a time. When multiple is specified, most browsers will show a scrolling list box instead of a single line dropdown.

size
If the control is presented as a scrolling list box (e.g. when multiple is specified), this attribute represents the number of rows in the list that should be visible at one time. Browsers are not required to present a select element as a scrolled list box. The default value is 0.

As described in the docs. <select size="1" multiple> will render a List box only 1 line visible and a scrollbar. So you are loosing the dropdown/arrow with the multiple attribute.

Count if two criteria match - EXCEL formula

If youR data was in A1:C100 then:

Excel - all versions

=SUMPRODUCT(--(A1:A100="M"),--(C1:C100="Yes"))

Excel - 2007 onwards

=COUNTIFS(A1:A100,"M",C1:C100,"Yes")

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

Adding to @Greg Hewgill answer: if you want to be able to match both date-time and only date, you can make the "time" part of the regex optional:

(\d{4})-(\d{2})-(\d{2})( (\d{2}):(\d{2}):(\d{2}))?

this way you will match both 2008-09-01 12:35:42 and 2008-09-01

[Ljava.lang.Object; cannot be cast to

I've faced such an issue and dig tones of material. So, to avoid ugly iteration you can simply tune your hql:

You need to frame your query like this

select entity from Entity as entity where ...

Also check such case, it perfectly works for me:

public List<User> findByRole(String role) {

    Query query = sessionFactory.getCurrentSession().createQuery("select user from User user join user.userRoles where role_name=:role_name");
    query.setString("role_name", role);
    @SuppressWarnings("unchecked")
    List<User> users = (List<User>) query.list();
    return users;
}

So here we are extracting object from query, not a bunch of fields. Also it's looks much more pretty.

How to get jQuery to wait until an effect is finished?

if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.

Order of execution of tests in TestNG

In TestNG, you use dependsOnMethods and/or dependsOnGroups:

@Test(groups = "a")
public void f1() {}

@Test(groups = "a")
public void f2() {}

@Test(dependsOnGroups = "a")
public void g() {}

In this case, g() will only run after f1() and f2() have completed and succeeded.

You will find a lot of examples in the documentation: http://testng.org/doc/documentation-main.html#test-groups

How to center align the ActionBar title in Android?

Just a quick addition to Ahmad's answer. You can't use getSupportActionBar().setTitle anymore when using a custom view with a TextView. So to set the title when you have multiple Activities with this custom ActionBar (using this one xml), in your onCreate() method after you assign a custom view:

TextView textViewTitle = (TextView) findViewById(R.id.mytext);
textViewTitle.setText(R.string.title_for_this_activity);

Rename specific column(s) in pandas

A much faster implementation would be to use list-comprehension if you need to rename a single column.

df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]

If the need arises to rename multiple columns, either use conditional expressions like:

df.columns = ['log(gdp)' if x=='gdp' else 'cap_mod' if x=='cap' else x for x in df.columns]

Or, construct a mapping using a dictionary and perform the list-comprehension with it's get operation by setting default value as the old name:

col_dict = {'gdp': 'log(gdp)', 'cap': 'cap_mod'}   ## key?old name, value?new name

df.columns = [col_dict.get(x, x) for x in df.columns]

Timings:

%%timeit
df.rename(columns={'gdp':'log(gdp)'}, inplace=True)
10000 loops, best of 3: 168 µs per loop

%%timeit
df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]
10000 loops, best of 3: 58.5 µs per loop

Select from one table matching criteria in another?

select a.id, a.object
from table_A a
inner join table_B b on a.id=b.id
where b.tag = 'chair';

How do you replace double quotes with a blank space in Java?

Use String#replace().

To replace them with spaces (as per your question title):

System.out.println("I don't like these \"double\" quotes".replace("\"", " "));

The above can also be done with characters:

System.out.println("I don't like these \"double\" quotes".replace('"', ' '));

To remove them (as per your example):

System.out.println("I don't like these \"double\" quotes".replace("\"", ""));

Cause of No suitable driver found for

It looks like you're not specifying a database name to connect to, should go something like

jdbc:hsqldb:hsql://serverName:port/DBname

How to auto-remove trailing whitespace in Eclipse?

I used this command for git: git config --global core.whitespace cr-at-eol

It removes ^M characters that are trailing.

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

Yes, presumably it wants the path to the javadoc command line tool that comes with the JDK (in the bin directory, same as java and javac).

Eclipse should be able to find it automatically; are you perhaps running it on a JRE? That would explain the request.

How can I catch a ctrl-c event?

You have to catch the SIGINT signal (we are talking POSIX right?)

See @Gab Royer´s answer for sigaction.

Example:

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>

void my_handler(sig_t s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{
   signal (SIGINT,my_handler);

   while(1);
   return 0;

}

Gridview row editing - dynamic binding to a DropDownList

The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.

I used it to change the value of two label controls - lblEditModifiedBy and lblEditModifiedOn - when I was editing a row, so that the correct ModifiedBy and ModifiedOn would be saved to the db on 'Update'.

When I clicked the 'Update' button, in the RowUpdating event it showed the new values I entered in the OldValues list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource attached to the GridView.)

The fix to this is using balexandre's code, but in a modified form in the gv_DataBound event:

protected void gv_DataBound(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in gv.Rows)
    {
        if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            // Here you will get the Control you need like:
            ((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
            ((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
        }
    }
}

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This works perfectly for me, not matter how the date was coded previously.

library(lubridate)
data$created_date1 <- mdy_hm(data$created_at)
data$created_date1 <- as.Date(data$created_date1)

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

Kotlin - Property initialization using "by lazy" vs. "lateinit"

Here are the significant differences between lateinit var and by lazy { ... } delegated property:

  • lazy { ... } delegate can only be used for val properties, whereas lateinit can only be applied to vars, because it can't be compiled to a final field, thus no immutability can be guaranteed;

  • lateinit var has a backing field which stores the value, and by lazy { ... } creates a delegate object in which the value is stored once calculated, stores the reference to the delegate instance in the class object and generates the getter for the property that works with the delegate instance. So if you need the backing field present in the class, use lateinit;

  • In addition to vals, lateinit cannot be used for nullable properties or Java primitive types (this is because of null used for uninitialized value);

  • lateinit var can be initialized from anywhere the object is seen from, e.g. from inside a framework code, and multiple initialization scenarios are possible for different objects of a single class. by lazy { ... }, in turn, defines the only initializer for the property, which can be altered only by overriding the property in a subclass. If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit.

  • Initialization by lazy { ... } is thread-safe by default and guarantees that the initializer is invoked at most once (but this can be altered by using another lazy overload). In the case of lateinit var, it's up to the user's code to initialize the property correctly in multi-threaded environments.

  • A Lazy instance can be saved, passed around and even used for multiple properties. On contrary, lateinit vars do not store any additional runtime state (only null in the field for uninitialized value).

  • If you hold a reference to an instance of Lazy, isInitialized() allows you to check whether it has already been initialized (and you can obtain such instance with reflection from a delegated property). To check whether a lateinit property has been initialized, you can use property::isInitialized since Kotlin 1.2.

  • A lambda passed to by lazy { ... } may capture references from the context where it is used into its closure.. It will then store the references and release them only once the property has been initialized. This may lead to object hierarchies, such as Android activities, not being released for too long (or ever, if the property remains accessible and is never accessed), so you should be careful about what you use inside the initializer lambda.

Also, there's another way not mentioned in the question: Delegates.notNull(), which is suitable for deferred initialization of non-null properties, including those of Java primitive types.

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

Should I put input elements inside a label element?

I usually go with the first two options. I've seen a scenario when the third option was used, when radio choices where embedded in labels and the css contained something like

label input {
    vertical-align: bottom;
}

in order to ensure proper vertical alignment for the radios.

YouTube: How to present embed video with sound muted

<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/ObHKvS2qSp8?list=PLF8tTShmRC6uppiZ_v-Xj-E1EtR3QCTox&autoplay=1&controls=1&loop=1&mute=1" frameborder="0" allowfullscreen></iframe>



<iframe width="560" height="315" src="https://www.youtube.com/embed/ObHKvS2qSp8?list=PLF8tTShmRC6uppiZ_v-Xj-E1EtR3QCTox&autoplay=1&controls=1&loop=1&mute=1" frameborder="0" allowfullscreen></iframe>

How to get last inserted row ID from WordPress database?

Putting the call to mysql_insert_id() inside a transaction, should do it:

mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.

How to change the Text color of Menu item in Android?

I was using Material design and when the toolbar was on a small screen clicking the more options would show a blank white drop down box. To fix this I think added this to the main AppTheme:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="android:itemTextAppearance">@style/menuItem</item>
</style>

And then created a style where you set the textColor for the menu items to your desired colour.

<style name="menuItem" parent="Widget.AppCompat.TextView.SpinnerItem">
    <item name="android:textColor">@color/black</item>
</style>

The parent name Widget.AppCompat.TextView.SpinnerItem I don't think that matters too much, it should still work.

jinja2.exceptions.TemplateNotFound error

You put your template in the wrong place. From the Flask docs:

Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: See the docs for more information: http://flask.pocoo.org/docs/quickstart/#rendering-templates

Using RegEx in SQL Server

You will have to build a CLR procedure that provides regex functionality, as this article illustrates.

Their example function uses VB.NET:

Imports System
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here  


Namespace SimpleTalk.Phil.Factor
    Public Class RegularExpressionFunctions
        'RegExIsMatch function
        <SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
        Public Shared Function RegExIsMatch( _
                                            ByVal pattern As SqlString, _
                                            ByVal input As SqlString, _
                                            ByVal Options As SqlInt32) As SqlBoolean
            If (input.IsNull OrElse pattern.IsNull) Then
                Return SqlBoolean.False
            End If
            Dim RegExOption As New System.Text.RegularExpressions.RegExOptions
            RegExOption = Options
            Return RegEx.IsMatch(input.Value, pattern.Value, RegExOption)
        End Function
    End Class      ' 
End Namespace

...and is installed in SQL Server using the following SQL (replacing '%'-delimted variables by their actual equivalents:

sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE

IF EXISTS ( SELECT   1
            FROM     sys.objects
            WHERE    object_id = OBJECT_ID(N'dbo.RegExIsMatch') ) 
   DROP FUNCTION dbo.RegExIsMatch
go

IF EXISTS ( SELECT   1
            FROM     sys.assemblies asms
            WHERE    asms.name = N'RegExFunction ' ) 
   DROP ASSEMBLY [RegExFunction]

CREATE ASSEMBLY RegExFunction 
           FROM '%FILE%'
GO

CREATE FUNCTION RegExIsMatch
   (
    @Pattern NVARCHAR(4000),
    @Input NVARCHAR(MAX),
    @Options int
   )
RETURNS BIT
AS EXTERNAL NAME 
   RegExFunction.[SimpleTalk.Phil.Factor.RegularExpressionFunctions].RegExIsMatch
GO

--a few tests
---Is this card a valid credit card?
SELECT dbo.RegExIsMatch ('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$','4241825283987487',1)
--is there a number in this string
SELECT dbo.RegExIsMatch( '\d','there is 1 thing I hate',1)
--Verifies number Returns 1
DECLARE @pattern VARCHAR(255)
SELECT @pattern ='[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]'
SELECT  dbo.RegExIsMatch (@pattern, '1298-673-4192',1),
        dbo.RegExIsMatch (@pattern,'A08Z-931-468A',1),
        dbo.RegExIsMatch (@pattern,'[A90-123-129X',1),
        dbo.RegExIsMatch (@pattern,'12345-KKA-1230',1),
        dbo.RegExIsMatch (@pattern,'0919-2893-1256',1)

How to get MAC address of client using PHP?

<?php

    ob_start();
    system('ipconfig/all');
    $mycom=ob_get_contents(); 
    ob_clean(); 
    $findme = "Physical";
    $pmac = strpos($mycom, $findme); 
    $mac=substr($mycom,($pmac+36),17);

    echo $mac;
?>

This prints the mac address of client machine

add allow_url_fopen to my php.ini using .htaccess

If your host is using suPHP, you can try creating a php.ini file in the same folder as the script and adding:

allow_url_fopen = On

(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script

<?php
echo `id`;
?>

To give the same information, assuming shell_exec is not a disabled function)

nodejs module.js:340 error: cannot find module

I had a nearly identical issue, turned out my JS file wasn't actually in the folder I was calling it from, and I had gone one folder too deep. I went up one directory, ran the file, it recognized it, happily ever after.

Alternatively, if you go one folder up, and it gives you the same error, but about a different module, take that same file in your parent folder and move it into the subfolder you were previously trying to run things from.

TL;DR- your file or its module(s) is not in the folder you think it is. Go up one level

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

On my side it was coming from an error in my settings.xml file. I had a bad tag. Just removed it, refreshed and i was good to go.

MS Access: how to compact current database in VBA

If you have the database with a front end and a back end. You can use the following code on the main form of your front end main navigation form:

Dim sDataFile As String, sDataFileTemp As String, sDataFileBackup As String
Dim s1 As Long, s2 As Long

sDataFile = "C:\MyDataFile.mdb"
sDataFileTemp = "C:\MyDataFileTemp.mdb"
sDataFileBackup = "C:\MyDataFile Backup " & Format(Now, "YYYY-MM-DD HHMMSS") & ".mdb"

DoCmd.Hourglass True

'get file size before compact
Open sDataFile For Binary As #1
s1 = LOF(1)
Close #1

'backup data file
FileCopy sDataFile, sDataFileBackup

'only proceed if data file exists
If Dir(sDataFileBackup vbNormal) <> "" Then

        'compact data file to temp file
        On Error Resume Next
        Kill sDataFileTemp
        On Error GoTo 0
        DBEngine.CompactDatabase sDataFile, sDataFileTemp

        If Dir(sDataFileTemp, vbNormal) <> "" Then
            'delete old data file data file
            Kill sDataFile

            'copy temp file to data file
            FileCopy sDataFileTemp, sDataFile

            'get file size after compact
            Open sDataFile For Binary As #1
            s2 = LOF(1)
            Close #1

            DoCmd.Hourglass False
            MsgBox "Compact complete " & vbCrLf & vbCrLf _
                & "Size before: " & Round(s1 / 1024 / 1024, 2) & "Mb" & vbCrLf _
                & "Size after:    " & Round(s2 / 1024 / 1024, 2) & "Mb", vbInformation
        Else
            DoCmd.Hourglass False
            MsgBox "ERROR: Unable to compact data file"
        End If

Else
        DoCmd.Hourglass False
        MsgBox "ERROR: Unable to backup data file"
End If

DoCmd.Hourglass False

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Download it from here:

http://www.iis.net/downloads/microsoft/url-rewrite

or if you already have Web Platform Installer on your machine you can install it from there.

Why must wait() always be in synchronized block

We all know that wait(), notify() and notifyAll() methods are used for inter-threaded communications. To get rid of missed signal and spurious wake up problems, waiting thread always waits on some conditions. e.g.-

boolean wasNotified = false;
while(!wasNotified) {
    wait();
}

Then notifying thread sets wasNotified variable to true and notify.

Every thread has their local cache so all the changes first get written there and then promoted to main memory gradually.

Had these methods not invoked within synchronized block, the wasNotified variable would not be flushed into main memory and would be there in thread's local cache so the waiting thread will keep waiting for the signal although it was reset by notifying thread.

To fix these types of problems, these methods are always invoked inside synchronized block which assures that when synchronized block starts then everything will be read from main memory and will be flushed into main memory before exiting the synchronized block.

synchronized(monitor) {
    boolean wasNotified = false;
    while(!wasNotified) {
        wait();
    }
}

Thanks, hope it clarifies.

Transferring files over SSH

You need to specify both source and destination, and if you want to copy directories you should look at the -r option.

So to recursively copy /home/user/whatever from remote server to your current directory:

scp -pr user@remoteserver:whatever .

ThreadStart with parameters

Thread thread = new Thread(Work);
thread.Start(Parameter);

private void Work(object param)
{
    string Parameter = (string)param;
}

The parameter type must be an object.

EDIT:

While this answer isn't incorrect I do recommend against this approach. Using a lambda expression is much easier to read and doesn't require type casting. See here: https://stackoverflow.com/a/1195915/52551

How to create a dump with Oracle PL/SQL Developer?

Just to keep this up to date:

The current version of SQLDeveloper has an export tool (Tools > Database Export) that will allow you to dump a schema to a file, with filters for object types, object names, table data etc.

It's a fair amount easier to set-up and use than exp and imp if you're used to working in a GUI environment, but not as versatile if you need to use it for scripting anything.

Simulate limited bandwidth from within Chrome?

if you're not familiar with Fiddler - please do. It's a great debugging tool for HTTP. You also have the option to limit the bandwidth.

Easiest way to convert a Blob into a byte array

The easiest way is this.

byte[] bytes = rs.getBytes("my_field");

Inserting string at position x of another string

Quick fix! If you don't want to manually add a space, you can do this:

_x000D_
_x000D_
var a = "I want apple";_x000D_
var b = "an";_x000D_
var position = 6;_x000D_
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');_x000D_
console.log(output);
_x000D_
_x000D_
_x000D_

(edit: i see that this is actually answered above, sorry!)

An error when I add a variable to a string

You have empty $entry_database variable. As you see in error: ListEmail, Title FROM WHERE ID bewteen FROM and WHERE should be name of table. Proper syntax of SELECT:

SELECT columns FROM table [optional things as WHERE/ORDER/GROUP/JOIN etc]

which in your way should become:

SELECT ID, ListStID, ListEmail, Title FROM some_table_you_got WHERE ID = '4'

Adding a newline into a string in C#

Based on your replies to everyone else, something like this is what you're looking for.

string file = @"C:\file.txt";
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
string[] lines = strToProcess.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);

using (StreamWriter writer = new StreamWriter(file))
{
    foreach (string line in lines)
    {
        writer.WriteLine(line + "@");
    }
}

DELETE ... FROM ... WHERE ... IN

Try adding parentheses around the row in table1 e.g.

DELETE 
  FROM table1
 WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);

The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.

Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:

MERGE INTO table1 AS t1
   USING table2 AS s1
      ON t1.stn = s1.stn
         AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;

Apache 13 permission denied in user's home directory

Turns out... we had to also chmod 755 the parent directory, user, in addition to xxx.

Spring Data JPA Update @Query not updating?

I struggled with the same problem where I was trying to execute an update query like the same as you did-

@Modifying
@Transactional
@Query(value = "UPDATE SAMPLE_TABLE st SET st.status=:flag WHERE se.referenceNo in :ids")
public int updateStatus(@Param("flag")String flag, @Param("ids")List<String> references);

This will work if you have put @EnableTransactionManagement annotation on the main class. Spring 3.1 introduces the @EnableTransactionManagement annotation to be used in on @Configuration classes and enable transactional support.

How do I encode and decode a base64 string?

    using System;
    using System.Text;

    public static class Base64Conversions
    {
        public static string EncodeBase64(this string text, Encoding encoding = null)
        { 
            if (text == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = encoding.GetBytes(text);
            return Convert.ToBase64String(bytes);
        }

        public static string DecodeBase64(this string encodedText, Encoding encoding = null)
        {
            if (encodedText == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = Convert.FromBase64String(encodedText);
            return encoding.GetString(bytes);
        }
    }

Usage

    var text = "Sample Text";
    var base64 = text.EncodeBase64();
    base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding

How to get a matplotlib Axes instance to plot to?

You can either

fig, ax = plt.subplots()  #create figure and axes
candlestick(ax, quotes, ...)

or

candlestick(plt.gca(), quotes) #get the axis when calling the function

The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot

How to import Maven dependency in Android Studio/IntelliJ?

Android Studio 3

The answers that talk about Maven Central are dated since Android Studio uses JCenter as the default repository center now. Your project's build.gradle file should have something like this:

repositories {
    google()
    jcenter()
}

So as long as the developer has their Maven repository there (which Picasso does), then all you would have to do is add a single line to the dependencies section of your app's build.gradle file.

dependencies {
    // ...
    implementation 'com.squareup.picasso:picasso:2.5.2'
}

How to get JSON object from Razor Model object in javascript

After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));

You need use JSON.parse(JSON.stringify(json));

What is the difference between a 'closure' and a 'lambda'?

When most people think of functions, they think of named functions:

function foo() { return "This string is returned from the 'foo' function"; }

These are called by name, of course:

foo(); //returns the string above

With lambda expressions, you can have anonymous functions:

 @foo = lambda() {return "This is returned from a function without a name";}

With the above example, you can call the lambda through the variable it was assigned to:

foo();

More useful than assigning anonymous functions to variables, however, are passing them to or from higher-order functions, i.e., functions that accept/return other functions. In a lot of these cases, naming a function is unecessary:

function filter(list, predicate) 
 { @filteredList = [];
   for-each (@x in list) if (predicate(x)) filteredList.add(x);
   return filteredList;
 }

//filter for even numbers
filter([0,1,2,3,4,5,6], lambda(x) {return (x mod 2 == 0)}); 

A closure may be a named or anonymous function, but is known as such when it "closes over" variables in the scope where the function is defined, i.e., the closure will still refer to the environment with any outer variables that are used in the closure itself. Here's a named closure:

@x = 0;

function incrementX() { x = x + 1;}

incrementX(); // x now equals 1

That doesn't seem like much but what if this was all in another function and you passed incrementX to an external function?

function foo()
 { @x = 0;

   function incrementX() 
    { x = x + 1;
      return x;
    }

   return incrementX;
 }

@y = foo(); // y = closure of incrementX over foo.x
y(); //returns 1 (y.x == 0 + 1)
y(); //returns 2 (y.x == 1 + 1)

This is how you get stateful objects in functional programming. Since naming "incrementX" isn't needed, you can use a lambda in this case:

function foo()
 { @x = 0;

   return lambda() 
           { x = x + 1;
             return x;
           };
 }

Using "&times" word in html changes to ×

You need to escape:

<div class="test">&amp;times</div>

And then read the value using text() to get the unescaped value:

alert($(".test").text()); // outputs: &times

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

Remove last commit from remote git repository

If nobody has pulled it, you can probably do something like

git push remote +branch^1:remotebranch

which will forcibly update the remote branch to the last but one commit of your branch.

When to use self over $this?

  • The object pointer $this to refers to the current object.
  • The class value static refers to the current object.
  • The class value self refers to the exact class it was defined in.
  • The class value parent refers to the parent of the exact class it was defined in.

See the following example which shows overloading.

<?php

class A {

    public static function newStaticClass()
    {
        return new static;
    }

    public static function newSelfClass()
    {
        return new self;
    }

    public function newThisClass()
    {
        return new $this;
    }
}

class B extends A
{
    public function newParentClass()
    {
        return new parent;
    }
}


$b = new B;

var_dump($b::newStaticClass()); // B
var_dump($b::newSelfClass()); // A because self belongs to "A"
var_dump($b->newThisClass()); // B
var_dump($b->newParentClass()); // A


class C extends B
{
    public static function newSelfClass()
    {
        return new self;
    }
}


$c = new C;

var_dump($c::newStaticClass()); // C
var_dump($c::newSelfClass()); // C because self now points to "C" class
var_dump($c->newThisClass()); // C
var_dump($b->newParentClass()); // A because parent was defined *way back* in class "B"

Most of the time you want to refer to the current class which is why you use static or $this. However, there are times when you need self because you want the original class regardless of what extends it. (Very, Very seldom)

How do you round to 1 decimal place in Javascript?

var num = 34.7654;

num = Math.round(num * 10) / 10;

console.log(num); // Logs: 34.8

Using 'make' on OS X

If you've installed Xcode 4.3 and its Command Line Tools, just open Terminal and type the following: On Xcode 4.3, type the following in Terminal:

export PATH=$PATH:/Applications/Xcode.app/Contents/Developer/usr/bin

How to render an array of objects in React?

Shubham's answer explains very well. This answer is addition to it as per to avoid some pitfalls and refactoring to a more readable syntax

Pitfall : There is common misconception in rendering array of objects especially if there is an update or delete action performed on data. Use case would be like deleting an item from table row. Sometimes when row which is expected to be deleted, does not get deleted and instead other row gets deleted.

To avoid this, use key prop in root element which is looped over in JSX tree of .map(). Also adding React's Fragment will avoid adding another element in between of ul and li when rendered via calling method.

state = {
    userData: [
        { id: '1', name: 'Joe', user_type: 'Developer' },
        { id: '2', name: 'Hill', user_type: 'Designer' }
    ]
};

deleteUser = id => {
    // delete operation to remove item
};

renderItems = () => {
    const data = this.state.userData;

    const mapRows = data.map((item, index) => (
        <Fragment key={item.id}>
            <li>
                {/* Passing unique value to 'key' prop, eases process for virtual DOM to remove specific element and update HTML tree  */}
                <span>Name : {item.name}</span>
                <span>User Type: {item.user_type}</span>
                <button onClick={() => this.deleteUser(item.id)}>
                    Delete User
                </button>
            </li>
        </Fragment>
    ));
    return mapRows;
};

render() {
    return <ul>{this.renderItems()}</ul>;
}

Important : Decision to use which value should we pass to key prop also matters as common way is to use index parameter provided by .map().

TLDR; But there's a drawback to it and avoid it as much as possible and use any unique id from data which is being iterated such as item.id. There's a good article on this - https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

Conditionally hide CommandField or ButtonField in Gridview

If this was based on roles you could use the multiview panel but not sure if you could do the same against a property of the record.

However, you could do this via code. In your rowdatabound event you can hide or show the button in it.

Display tooltip on Label's hover?

You can use the "title attribute" for label tag.

<label title="Hello This Will Have Some Value">Hello...</label>

If you need more control over the looks,

1 . try http://getbootstrap.com/javascript/#tooltips as shown below. But you will need to include bootstrap.

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Hello This Will Have Some Value">Hello...</button>

2 . try https://jqueryui.com/tooltip/. But you will need to include jQueryUI.

<script type="text/javascript">
$(document).ready(function(){
$(this).tooltip();
});
</script>

Best practices for Storyboard login screen, handling clearing of data upon logout

EDIT: Add logout action.

enter image description here

1. First of all prepare the app delegate file

AppDelegate.h

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic) BOOL authenticated;

@end

AppDelegate.m

#import "AppDelegate.h"
#import "User.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    User *userObj = [[User alloc] init];
    self.authenticated = [userObj userAuthenticated];

    return YES;
}

2. Create a class named User.

User.h

#import <Foundation/Foundation.h>

@interface User : NSObject

- (void)loginWithUsername:(NSString *)username andPassword:(NSString *)password;
- (void)logout;
- (BOOL)userAuthenticated;

@end

User.m

#import "User.h"

@implementation User

- (void)loginWithUsername:(NSString *)username andPassword:(NSString *)password{

    // Validate user here with your implementation
    // and notify the root controller
    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginActionFinished" object:self userInfo:nil];
}

- (void)logout{
    // Here you can delete the account
}

- (BOOL)userAuthenticated {

    // This variable is only for testing
    // Here you have to implement a mechanism to manipulate this
    BOOL auth = NO;

    if (auth) {
        return YES;
    }

    return NO;
}

3. Create a new controller RootViewController and connected with the first view, where login button live. Add also a Storyboard ID: "initialView".

RootViewController.h

#import <UIKit/UIKit.h>
#import "LoginViewController.h"

@protocol LoginViewProtocol <NSObject>

- (void)dismissAndLoginView;

@end

@interface RootViewController : UIViewController

@property (nonatomic, weak) id <LoginViewProtocol> delegate;
@property (nonatomic, retain) LoginViewController *loginView;


@end

RootViewController.m

#import "RootViewController.h"

@interface RootViewController ()

@end

@implementation RootViewController

@synthesize loginView;

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

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

- (IBAction)loginBtnPressed:(id)sender {

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginActionFinished:)
                                                 name:@"loginActionFinished"
                                               object:loginView];

}

#pragma mark - Dismissing Delegate Methods

-(void) loginActionFinished:(NSNotification*)notification {

    AppDelegate *authObj = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    authObj.authenticated = YES;

    [self dismissLoginAndShowProfile];
}

- (void)dismissLoginAndShowProfile {
    [self dismissViewControllerAnimated:NO completion:^{
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UITabBarController *tabView = [storyboard instantiateViewControllerWithIdentifier:@"profileView"];
        [self presentViewController:tabView animated:YES completion:nil];
    }];


}

@end

4. Create a new controller LoginViewController and connected with the login view.

LoginViewController.h

#import <UIKit/UIKit.h>
#import "User.h"

@interface LoginViewController : UIViewController

LoginViewController.m

#import "LoginViewController.h"
#import "AppDelegate.h"

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (IBAction)submitBtnPressed:(id)sender {
    User *userObj = [[User alloc] init];

    // Here you can get the data from login form
    // and proceed to authenticate process
    NSString *username = @"username retrieved through login form";
    NSString *password = @"password retrieved through login form";
    [userObj loginWithUsername:username andPassword:password];
}

@end

5. At the end add a new controller ProfileViewController and connected with the profile view in the tabViewController.

ProfileViewController.h

#import <UIKit/UIKit.h>

@interface ProfileViewController : UIViewController

@end

ProfileViewController.m

#import "ProfileViewController.h"
#import "RootViewController.h"
#import "AppDelegate.h"
#import "User.h"

@interface ProfileViewController ()

@end

@implementation ProfileViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if(![(AppDelegate*)[[UIApplication sharedApplication] delegate] authenticated]) {

        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

        RootViewController *initView =  (RootViewController*)[storyboard instantiateViewControllerWithIdentifier:@"initialView"];
        [initView setModalPresentationStyle:UIModalPresentationFullScreen];
        [self presentViewController:initView animated:NO completion:nil];
    } else{
        // proceed with the profile view
    }
}

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

- (IBAction)logoutAction:(id)sender {

   User *userObj = [[User alloc] init];
   [userObj logout];

   AppDelegate *authObj = (AppDelegate*)[[UIApplication sharedApplication] delegate];
   authObj.authenticated = NO;

   UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

   RootViewController *initView =  (RootViewController*)[storyboard instantiateViewControllerWithIdentifier:@"initialView"];
   [initView setModalPresentationStyle:UIModalPresentationFullScreen];
   [self presentViewController:initView animated:NO completion:nil];

}

@end

LoginExample is a sample project for extra help.

How to use the 'replace' feature for custom AngularJS directives?

replace:true is Deprecated

From the Docs:

replace ([DEPRECATED!], will be removed in next major release - i.e. v2.0)

specify what the template should replace. Defaults to false.

  • true - the template will replace the directive's element.
  • false - the template will replace the contents of the directive's element.

-- AngularJS Comprehensive Directive API

From GitHub:

Caitp-- It's deprecated because there are known, very silly problems with replace: true, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".

-- AngularJS Issue #7636


Update

Note: replace: true is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.

Issues with replace: true

For more information, see

How do I drag and drop files into an application?

Another common gotcha is thinking you can ignore the Form DragOver (or DragEnter) events. I typically use the Form's DragOver event to set the AllowedEffect, and then a specific control's DragDrop event to handle the dropped data.

How do I navigate to a parent route from a child route?

Another way could be like this

this._router.navigateByUrl(this._router.url.substr(0, this._router.url.lastIndexOf('/'))); // go to parent URL

and here is the constructor

constructor(
    private _activatedRoute: ActivatedRoute,
    private _router: Router
  ) { }

How can I get new selection in "select" in Angular 2?

In Angular 8 you can simply use "selectionChange" like this:

 <mat-select  [(value)]="selectedData" (selectionChange)="onChange()" >
  <mat-option *ngFor="let i of data" [value]="i.ItemID">
  {{i.ItemName}}
  </mat-option>
 </mat-select>

how to get the base url in javascript

You can make PHP and JavaScript work together by generating the following line in each page template:

<script>
document.mybaseurl='<?php echo base_url('assets/css/themes/default.css');?>';
</script>

Then you can refer to document.mybaseurl anywhere in your JavaScript. This saves you some debugging and complexity because this variable is always consistent with the PHP calculation.

HTML image bottom alignment inside DIV container

Set the parent div as position:relative and the inner element to position:absolute; bottom:0

How to pass a type as a method parameter in Java

Oh, but that's ugly, non-object-oriented code. The moment you see "if/else" and "typeof", you should be thinking polymorphism. This is the wrong way to go. I think generics are your friend here.

How many types do you plan to deal with?

UPDATE:

If you're just talking about String and int, here's one way you might do it. Start with the interface XmlGenerator (enough with "foo"):

package generics;

public interface XmlGenerator<T>
{
   String getXml(T value);
}

And the concrete implementation XmlGeneratorImpl:

    package generics;

public class XmlGeneratorImpl<T> implements XmlGenerator<T>
{
    private Class<T> valueType;
    private static final int DEFAULT_CAPACITY = 1024;

    public static void main(String [] args)
    {
        Integer x = 42;
        String y = "foobar";

        XmlGenerator<Integer> intXmlGenerator = new XmlGeneratorImpl<Integer>(Integer.class);
        XmlGenerator<String> stringXmlGenerator = new XmlGeneratorImpl<String>(String.class);

        System.out.println("integer: " + intXmlGenerator.getXml(x));
        System.out.println("string : " + stringXmlGenerator.getXml(y));
    }

    public XmlGeneratorImpl(Class<T> clazz)
    {
        this.valueType = clazz;
    }

    public String getXml(T value)
    {
        StringBuilder builder = new StringBuilder(DEFAULT_CAPACITY);

        appendTag(builder);
        builder.append(value);
        appendTag(builder, false);

        return builder.toString();
    }

    private void appendTag(StringBuilder builder) { this.appendTag(builder, false); }

    private void appendTag(StringBuilder builder, boolean isClosing)
    {
        String valueTypeName = valueType.getName();
        builder.append("<").append(valueTypeName);
        if (isClosing)
        {
            builder.append("/");
        }
        builder.append(">");
    }
}

If I run this, I get the following result:

integer: <java.lang.Integer>42<java.lang.Integer>
string : <java.lang.String>foobar<java.lang.String>

I don't know if this is what you had in mind.

Cannot instantiate the type List<Product>

List is an interface. You need a specific class in the end so either try

List l = new ArrayList();

or

List l = new LinkedList();

Whichever suit your needs.

Changing date format in R

After reading your data in via a textConnection, the following seems to work:

dat <- read.table(textConnection(txt), header = TRUE)
dat$date <- strptime(dat$date, format= "%d/%m/%Y")
format(dat$date, format="%Y-%m-%d")

> format(dat$date, format="%Y-%m-%d")
 [1] "2011-08-31" "2011-07-31" "2011-06-30" "2011-05-31" "2011-04-30" "2011-03-31"
 [7] "2011-02-28" "2011-01-31" "2010-12-31" "2010-11-30" "2010-10-31" "2010-09-30"
[13] "2010-08-31" "2010-07-31" "2010-06-30" "2010-05-31" "2010-04-30" "2010-03-31"
[19] "2010-02-28" "2010-01-31" "2009-12-31" "2009-11-30" "2009-10-31"

> str(dat)
'data.frame':   23 obs. of  2 variables:
 $ date    : POSIXlt, format: "2011-08-31" "2011-07-31" "2011-06-30" ...
 $ midpoint: num  0.838 0.846 0.815 0.797 0.788 ...

Can I loop through a table variable in T-SQL?

DECLARE @table1 TABLE (
    idx int identity(1,1),
    col1 int )

DECLARE @counter int

SET @counter = 1

WHILE(@counter < SELECT MAX(idx) FROM @table1)
BEGIN
    DECLARE @colVar INT

    SELECT @colVar = col1 FROM @table1 WHERE idx = @counter

    -- Do your work here

    SET @counter = @counter + 1
END

Believe it or not, this is actually more efficient and performant than using a cursor.

Prolog "or" operator, query

you can 'invoke' alternative bindings on Y this way:

...registered(X, Y), (Y=ct101; Y=ct102; Y=ct103).

Note the parenthesis are required to keep the correct execution control flow. The ;/2 it's the general or operator. For your restricted use you could as well choice the more idiomatic

...registered(X, Y), member(Y, [ct101,ct102,ct103]).

that on backtracking binds Y to each member of the list.

edit I understood with a delay your last requirement. If you want that Y match all 3 values the or is inappropriate, use instead

...registered(X, ct101), registered(X, ct102), registered(X, ct103).

or the more compact

...findall(Y, registered(X, Y), L), sort(L, [ct101,ct102,ct103]).

findall/3 build the list in the very same order that registered/2 succeeds. Then I use sort to ensure the matching.

...setof(Y, registered(X, Y), [ct101,ct102,ct103]).

setof/3 also sorts the result list

WooCommerce - get category for product page

<?php
   $terms = get_the_terms($product->ID, 'product_cat');
      foreach ($terms as $term) {

        $product_cat = $term->name;
           echo $product_cat;
             break;
  }
 ?>

How to use java.Set

Did you override equals and hashCode in the Block class?

EDIT:

I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.

Moment.js - tomorrow, today and yesterday

const date = moment(YOUR_DATE)
return (moment().diff(date, 'days') >= 2) ? date.fromNow() : date.calendar().split(' ')[0]

How to launch a Google Chrome Tab with specific URL using C#

UPDATE: Please see Dylan's or d.c's anwer for a little easier (and more stable) solution, which does not rely on Chrome beeing installed in LocalAppData!


Even if I agree with Daniel Hilgarth to open a new tab in chrome you just need to execute chrome.exe with your URL as the argument:

Process.Start(@"%AppData%\..\Local\Google\Chrome\Application\chrome.exe", 
              "http:\\www.YourUrl.com");

What exactly is node.js used for?

Directly from the tag wiki, make sure watch some of the talk videos linked there to get a better idea.


Node.js is an event based, asynchronous I/O framework that uses Google's V8 JavaScript Engine.

Node.js - or just Node as it's commonly called - is used for developing applications that make heavy use of the ability to run JavaScript both on the client, as well as on server side and therefore benefit from the re-usability of code and the lack of context switching.

It's also possible to use matured JavaScript frameworks like YUI and jQuery for server side DOM manipulation.

To ease the development of complex JavaScript further, Node.js supports the CommonJS standard that allows for modularized development and the distribution of software in packages via the Node Package Manager.

Applications that can be written using Node.js include, but are not limited to:

  • Static file servers
  • Web Application frameworks
  • Messaging middle ware
  • Servers for HTML5 multi player games