Programs & Examples On #Django tinymce

django-tinymce is a pluggable django app that contains a widget to render a form field as a TinyMCE editor.

How do you join on the same table, twice, in mysql?

you'd use another join, something along these lines:

SELECT toD.dom_url AS ToURL, 
    fromD.dom_url AS FromUrl, 
    rvw.*

FROM reviews AS rvw

LEFT JOIN domain AS toD 
    ON toD.Dom_ID = rvw.rev_dom_for

LEFT JOIN domain AS fromD 
    ON fromD.Dom_ID = rvw.rev_dom_from

EDIT:

All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).

At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.

Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.

For more info about aliasing in SQL, read here.

Scrolling a flexbox with overflowing content

One issue that I've come across is that to have a scrollbar a n element needs a height to be specified (and not as a %).

The trick is to nest another set of divs within each column, and set the column parent's display to flex with flex-direction: column.

<style>
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }

    body {
        overflow-y: hidden;
        overflow-x: hidden;
        color: white;
    }

    .base-container {
        display: flex;
        flex: 1;
        flex-direction: column;
        width: 100%;
        height: 100%;
        overflow-y: hidden;
        align-items: stretch;
    }

    .title {
        flex: 0 0 50px;
        color: black;
    }

    .container {
        flex: 1 1 auto;
        display: flex;
        flex-direction: column;
    }

        .container .header {
            flex: 0 0 50px;
            background-color: red;
        }

        .container .body {
            flex: 1 1 auto;
            display: flex;
            flex-direction: row;
        }

            .container .body .left {
                display: flex;
                flex-direction: column;
                flex: 0 0 80px;
                background-color: blue;
            }
                .container .body .left .content,
                .container .body .main .content,
                .container .body .right .content {
                    flex: 1 1 auto;
                    overflow-y: auto;
                    height: 100px;
                }
                .container .body .main .content.noscrollbar {
                    overflow-y: hidden;
                }

            .container .body .main {
                display: flex;
                flex-direction: column;
                flex: 1 1 auto;
                background-color: green;
            }

            .container .body .right {
                display: flex;
                flex-direction: column;
                flex: 0 0 300px;
                background-color: yellow;
                color: black;
            }

    .test {
        margin: 5px 5px;
        border: 1px solid white;
        height: calc(100% - 10px);
    }
</style>

And here's the html:

<div class="base-container">
    <div class="title">
        Title
    </div>
    <div class="container">
        <div class="header">
            Header
        </div>
        <div class="body">
            <div class="left">
                <div class="content">
                    <ul>
                        <li>1</li>
                        <li>2</li>
                        <li>3</li>
                        <li>4</li>
                        <li>5</li>
                        <li>6</li>
                        <li>7</li>
                        <li>8</li>
                        <li>9</li>
                        <li>10</li>
                        <li>12</li>
                        <li>13</li>
                        <li>14</li>
                        <li>15</li>
                        <li>16</li>
                        <li>17</li>
                        <li>18</li>
                        <li>19</li>
                        <li>20</li>
                        <li>21</li>
                        <li>22</li>
                        <li>23</li>
                        <li>24</li>
                    </ul>
                </div>
            </div>
            <div class="main">
                <div class="content noscrollbar">
                    <div class="test">Test</div>
                </div>
            </div>
            <div class="right">
                <div class="content">
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>End</div>
                </div>
            </div>
        </div>
    </div>
</div>

https://jsfiddle.net/LiamFlavelle/czpjdfr4/

What does the question mark and the colon (?: ternary operator) mean in objective-c?

This is part of C, so it's not Objective-C specific. Here's a translation into an if statement:

if (inPseudoEditMode)
    label.frame = kLabelIndentedRec;
else
    label.frame = kLabelRect;

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

My application is using Mura CMS and I faced this issue. However the solution was the password mismatch between my mysql local server and the password in the config files. As soon as I synched them it worked.

Observable.of is not a function

In rxjs v6, of operator should be imported as import { of } from 'rxjs';

How can I use a local image as the base image with a dockerfile?

Verified: it works well in Docker 1.7.0.

Don't specify --pull=true when running the docker build command

From this thread on reference locally-built image using FROM at dockerfile:

If you want use the local image as the base image, pass without the option --pull=true
--pull=true will always attempt to pull a newer version of the image.

Sys is undefined

I found the error when using a combination of the Ajax Control Toolkit ToolkitScriptManager and URL Write 2.0.

In my <rewrite> <outboundRules> I had a precondition:

<preConditions>
    <preCondition name="IsHTML">
        <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html"/>
    </preCondition>
</preConditions>

But apparently some of my outbound rules weren't set to use the precondition.

Once I had that preCondition set on all my outbound rules:

<rule preCondition="IsHTML" name="MyOutboundRule">

No more problem.

How do I vertically align text in a paragraph?

you could use

    line-height:35px;

You really shouldnt set a height on paragraph as its not good for accessibility (what happens if the user increase text size etc)

Instead use a Div with a hight and the p inside it with the correct line-height:

    <div style="height:35px;"><p style="line-height:35px;">text</p></div>

How to save data file into .RData?

There are three ways to save objects from your R session:

Saving all objects in your R session:

The save.image() function will save all objects currently in your R session:

save.image(file="1.RData") 

These objects can then be loaded back into a new R session using the load() function:

load(file="1.RData")

Saving some objects in your R session:

If you want to save some, but not all objects, you can use the save() function:

save(city, country, file="1.RData")

Again, these can be reloaded into another R session using the load() function:

load(file="1.RData") 

Saving a single object

If you want to save a single object you can use the saveRDS() function:

saveRDS(city, file="city.rds")
saveRDS(country, file="country.rds") 

You can load these into your R session using the readRDS() function, but you will need to assign the result into a the desired variable:

city <- readRDS("city.rds")
country <- readRDS("country.rds")

But this also means you can give these objects new variable names if needed (i.e. if those variables already exist in your new R session but contain different objects):

city_list <- readRDS("city.rds")
country_vector <- readRDS("country.rds")

Download Excel file via AJAX MVC

I may sound quite naive, and may attract quite a criticism, but here's how I did it,
(It doesn't involve ajax for export, but it doesn't do a full postback either )

Thanks for this post and this answer.
Create a simple controller

public class HomeController : Controller
{               
   /* A demo action
    public ActionResult Index()
    {           
        return View(model);
    }
   */
    [HttpPost]
    public FileResult ExportData()
    {
        /* An example filter
        var filter = TempData["filterKeys"] as MyFilter;
        TempData.Keep();            */
        var someList = db.GetDataFromDb(/*filter*/) // filter as an example

    /*May be here's the trick, I'm setting my filter in TempData["filterKeys"] 
     in an action,(GetFilteredPartial() illustrated below) when 'searching' for the data,
     so do not really need ajax here..to pass my filters.. */

     //Some utility to convert list to Datatable
     var dt = Utility.ConvertToDataTable(someList); 

      //  I am using EPPlus nuget package 
      using (ExcelPackage pck = new ExcelPackage())
      {
          ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
          ws.Cells["A1"].LoadFromDataTable(dt, true);

            using (var memoryStream = new MemoryStream())
            {                   
              pck.SaveAs(memoryStream);
              return File(memoryStream.ToArray(),
              "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
              "ExportFileName.xlsx");                    
            }                
        }   
    }

    //This is just a supporting example to illustrate setting up filters ..        
   /* [HttpPost]
    public PartialViewResult GetFilteredPartial(MyFilter filter)
    {            
        TempData["filterKeys"] = filter;
        var filteredData = db.GetConcernedData(filter);
        var model = new MainViewModel();
        model.PartialViewModel = filteredData;

        return PartialView("_SomePartialView", model);
    } */     
} 

And here are the Views..

/*Commenting out the View code, in order to focus on the imp. code     
 @model Models.MainViewModel
 @{Layout...}     

      Some code for, say, a partial View  
      <div id="tblSampleBody">
        @Html.Partial("_SomePartialView", Model.PartialViewModel)
      </div>
  */                                                       
//The actual part.. Just **posting** this bit of data from the complete View...
//Here, you are not posting the full Form..or the complete View
   @using (Html.BeginForm("ExportData", "Home", FormMethod.Post))
    {
        <input type="submit" value="Export Data" />
    }
//...
//</div>

/*And you may require to pass search/filter values.. as said in the accepted answer..
That can be done while 'searching' the data.. and not while
 we need an export..for instance:-             

<script>             
  var filterData = {
      SkipCount: someValue,
      TakeCount: 20,
      UserName: $("#UserName").val(),
      DepartmentId: $("#DepartmentId").val(),     
   }

  function GetFilteredData() {
       $("#loader").show();
       filterData.SkipCount = 0;
       $.ajax({
          url: '@Url.Action("GetFilteredPartial","Home")',
          type: 'POST',
          dataType: "html",
          data: filterData,
          success: function (dataHTML) {
          if ((dataHTML === null) || (dataHTML == "")) {
              $("#tblSampleBody").html('<tr><td>No Data Returned</td></tr>');
                $("#loader").hide();
            } else {
                $("#tblSampleBody").html(dataHTML);                    
                $("#loader").hide();
            }
        }
     });
   }    
</script>*/

The whole point of the trick seems that, we are posting a form (a part of the Razor View ) upon which we are calling an Action method, which returns: a FileResult, and this FileResult returns the Excel File..
And for posting the filter values, as said, ( and if you require to), I am making a post request to another action, as has been attempted to describe..

jQuery - add additional parameters on submit (NOT ajax)

This one did it for me:

var input = $("<input>")
               .attr("type", "hidden")
               .attr("name", "mydata").val("bla");
$('#form1').append(input);

is based on the Daff's answer, but added the NAME attribute to let it show in the form collection and changed VALUE to VAL Also checked the ID of the FORM (form1 in my case)

used the Firefox firebug to check whether the element was inserted.

Hidden elements do get posted back in the form collection, only read-only fields are discarded.

Michel

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
                .SpecialCells(xlCellTypeConstants).ClearContents
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

How to set image for bar button with swift?

If your UIBarButtonItem is already allocated like in a storyboard. (printBtn)

    let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    btn.setImage(UIImage(named: Constants.ImageName.print)?.withRenderingMode(.alwaysTemplate), for: .normal)
    btn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handlePrintPress(tapGesture:))))
    printBtn.customView = btn

Setting selected option in laravel form

Try this

<select class="form-control" name="country_code" value="{{ old('country_code') }}">
   @foreach (\App\SystemCountry::orderBy('country')->get() as $country)
       <option value="{{ $country->country_code }}"
           @if ($country->country_code == "LKA")
             {{'selected="selected"'}}
           @endif
       >
          {{ $country->country }}
       </option>
   @endforeach
</select>

Get device token for push notification

Objective C for iOS 13+, courtesy of Wasif Saood's answer

Copy and paste below code into AppDelegate.m to print the device APN token.

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  NSUInteger dataLength = deviceToken.length;
  if (dataLength == 0) {
    return;
  }
  const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
  NSMutableString *hexString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
  for (int i = 0; i < dataLength; ++i) {
    [hexString appendFormat:@"%02x", dataBuffer[i]];
  }
  NSLog(@"APN token:%@", hexString);
}

How can I create numbered map markers in Google Maps V3?

Here are custom icons with the updated "visual refresh" style that you can generate quickly via a simple .vbs script. I also included a large pre-generated set that you can use immediately with multiple color options: https://github.com/Concept211/Google-Maps-Markers

Use the following format when linking to the GitHub-hosted image files:

https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_[color][character].png

color
red, black, blue, green, grey, orange, purple, white, yellow

character
A-Z, 1-100, !, @, $, +, -, =, (%23 = #), (%25 = %), (%26 = &), (blank = •)

Examples:

red1 https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_red1.png

blue2 https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_blue2.png

green3 https://raw.githubusercontent.com/Concept211/Google-Maps-Markers/master/images/marker_green3.png

Append values to a set in Python

This question is the first one that shows up on Google when one looks up "Python how to add elements to set", so it's worth noting explicitly that, if you want to add a whole string to a set, it should be added with .add(), not .update().

Say you have a string foo_str whose contents are 'this is a sentence', and you have some set bar_set equal to set().

If you do bar_set.update(foo_str), the contents of your set will be {'t', 'a', ' ', 'e', 's', 'n', 'h', 'c', 'i'}.

If you do bar_set.add(foo_str), the contents of your set will be {'this is a sentence'}.

"id cannot be resolved or is not a field" error?

In main.xml (or wherever your item is defined) make sure that the ID for the R item is defined with @+id/... Here is an example with a button:

<Button android:text="B1" android:id="@+id/button_one"
        android:layout_gravity="center_horizontal|center"
        android:layout_height="fill_parent" android:layout_width="wrap_content" />

Each of these is important because:

  • @ must precede the string
  • + indicates it will create if not existing (whatever your item is)

How to create a directory and give permission in single command

you can use following command to create directory and give permissions at the same time

mkdir -m777 path/foldername 

Is there a way to use PhantomJS in Python?

The easiest way to use PhantomJS in python is via Selenium. The simplest installation method is

  1. Install NodeJS
  2. Using Node's package manager install phantomjs: npm -g install phantomjs-prebuilt
  3. install selenium (in your virtualenv, if you are using that)

After installation, you may use phantom as simple as:

from selenium import webdriver

driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()

If your system path environment variable isn't set correctly, you'll need to specify the exact path as an argument to webdriver.PhantomJS(). Replace this:

driver = webdriver.PhantomJS() # or add to your PATH

... with the following:

driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')

References:

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

just delete this part Class.forName("com.mysql.jdbc.Driver") from your code

because the machine is throwing a warning that

The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary."

meaning that no need to include it beacuse the driver is automatically registered for you by default.

Programmatically create a UIView with color gradient

Its a good idea to call the solutions above to update layer on the

viewDidLayoutSubviews 

to get the views updated correctly

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

Is there a way to automatically generate getters and setters in Eclipse?

Sure.

Use Generate Getters and Setters from the Source menu or the context menu on a selected field or type, or a text selection in a type to open the dialog. The Generate Getters and Setters dialog shows getters and setters for all fields of the selected type. The methods are grouped by the type's fields.

Take a look at the help documentation for more information.

How to round double to nearest whole number and then convert to a float?

float b = (float)Math.ceil(a); or float b = (float)Math.round(a);

Depending on whether you meant "round to the nearest whole number" (round) or "round up" (ceil).

Beware of loss of precision in converting a double to a float, but that shouldn't be an issue here.

An existing connection was forcibly closed by the remote host

This error occurred in my application with the CIP-protocol whenever I didn't Send or received data in less than 10s.

This was caused by the use of the forward open method. You can avoid this by working with an other method, or to install an update rate of less the 10s that maintain your forward-open-connection.

What does .class mean in Java?

When you write .class after a class name, it references the class literal - java.lang.Class object that represents information about given class.

For example, if your class is Print, then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.

Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());

Doctrine findBy 'does not equal'

There is no built-in method that allows what you intend to do.

You have to add a method to your repository, like this:

public function getWhatYouWant()
{
    $qb = $this->createQueryBuilder('u');
    $qb->where('u.id != :identifier')
       ->setParameter('identifier', 1);

    return $qb->getQuery()
          ->getResult();
}

Hope this helps.

How do you create a custom AuthorizeAttribute in ASP.NET Core?

You can create your own AuthorizationHandler that will find custom attributes on your Controllers and Actions, and pass them to the HandleRequirementAsync method.

public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
    {
        var attributes = new List<TAttribute>();

        var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
        if (action != null)
        {
            attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
            attributes.AddRange(GetAttributes(action.MethodInfo));
        }

        return HandleRequirementAsync(context, requirement, attributes);
    }

    protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);

    private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo)
    {
        return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
    }
}

Then you can use it for any custom attributes you need on your controllers or actions. For example to add permission requirements. Just create your custom attribute.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class PermissionAttribute : AuthorizeAttribute
{
    public string Name { get; }

    public PermissionAttribute(string name) : base("Permission")
    {
        Name = name;
    }
}

Then create a Requirement to add to your Policy

public class PermissionAuthorizationRequirement : IAuthorizationRequirement
{
    //Add any custom requirement properties if you have them
}

Then create the AuthorizationHandler for your custom attribute, inheriting the AttributeAuthorizationHandler that we created earlier. It will be passed an IEnumerable for all your custom attributes in the HandleRequirementsAsync method, accumulated from your Controller and Action.

public class PermissionAuthorizationHandler : AttributeAuthorizationHandler<PermissionAuthorizationRequirement, PermissionAttribute>
{
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement, IEnumerable<PermissionAttribute> attributes)
    {
        foreach (var permissionAttribute in attributes)
        {
            if (!await AuthorizeAsync(context.User, permissionAttribute.Name))
            {
                return;
            }
        }

        context.Succeed(requirement);
    }

    private Task<bool> AuthorizeAsync(ClaimsPrincipal user, string permission)
    {
        //Implement your custom user permission logic here
    }
}

And finally, in your Startup.cs ConfigureServices method, add your custom AuthorizationHandler to the services, and add your Policy.

        services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();

        services.AddAuthorization(options =>
        {
            options.AddPolicy("Permission", policyBuilder =>
            {
                policyBuilder.Requirements.Add(new PermissionAuthorizationRequirement());
            });
        });

Now you can simply decorate your Controllers and Actions with your custom attribute.

[Permission("AccessCustomers")]
public class CustomersController
{
    [Permission("AddCustomer")]
    IActionResult AddCustomer([FromBody] Customer customer)
    {
        //Add customer
    }
}

double free or corruption (!prev) error in c program

1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory

Here is the program with all the changes needed. I compiled and ran... no errors or warnings.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

I'm using this for string values:

<%#(String.IsNullOrEmpty(Eval("Data").ToString()) ? "0" : Eval("Data"))%>

You can also use following for nullable values:

<%#(Eval("Data") == null ? "0" : Eval("Data"))%>

Also if you're using .net 4.5 and above I suggest you use strongly typed data binding:

<asp:Repeater runat="server" DataSourceID="odsUsers" ItemType="Entity.User">
    <ItemTemplate>
        <%# Item.Title %>
    </ItemTemplate>
</asp:Repeater>

How to import a module in Python with importlib.import_module

And don't forget to create a __init__.py with each folder/subfolder (even if they are empty)

Has Facebook sharer.php changed to no longer accept detailed parameters?

Starting from July 18, 2017 Facebook has decided to disregard custom parameters set by users. This choice blocks many of the possibilities offered by this answer and it also breaks buttons used on several websites.

The quote and hashtag parameters work as of Dec 2018.


Does anyone know if there have been recent changes which could have suddenly stopped this from working?

The parameters have changed. The currently accepted answer states:

Facebook no longer supports custom parameters in sharer.php

But this is not entirely correct. Well, maybe they do not support or endorse them, but custom parameters can be used if you know the correct names. These include:

  • URL (of course) ? u
  • custom image ? picture
  • custom title ? title
  • custom quote ? quote
  • custom description ? description
  • caption (aka website name) ? caption

For instance, you can share this very question with the following URL:

https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Fstackoverflow.com%2Fq%2F20956229%2F1101509&picture=http%3A%2F%2Fwww.applezein.net%2Fwordpress%2Fwp-content%2Fuploads%2F2015%2F03%2Ffacebook-logo.jpg&title=A+nice+question+about+Facebook&quote=Does+anyone+know+if+there+have+been+recent+changes+which+could+have+suddenly+stopped+this+from+working%3F&description=Apparently%2C+the+accepted+answer+is+not+correct.

Try it!

I've built a tool which makes it easier to share URLs on Facebook with custom parameters. You can use it to generate your sharer.php link, just press the button and copy the URL from the tab that opens.

Conditional formatting, entire row based

Use the "indirect" function on conditional formatting.

  1. Select Conditional Formatting
  2. Select New Rule
  3. Select "Use a Formula to determine which cells to format"
  4. Enter the Formula, =INDIRECT("g"&ROW())="X"
  5. Enter the Format you want (text color, fill color, etc).
  6. Select OK to save the new format
  7. Open "Manage Rules" in Conditional Formatting
  8. Select "This Worksheet" if you can't see your new rule.
  9. In the "Applies to" box of your new rule, enter =$A$1:$Z$1500 (or however wide/long you want the conditional formatting to extend depending on your worksheet)

For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.

You can repeat this to do multiple row formatting depending on a column value. Just change either the g column or x specific text in the formula and set different formats.

For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR", then it will format every row that has CAR in the H Column as the format you specified.

How to loop over files in directory and change path and add suffix to filename

A couple of notes first: when you use Data/data1.txt as an argument, should it really be /Data/data1.txt (with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt and .txt files only:

#!/bin/bash
for filename in /Data/*.txt; do
    for ((i=0; i<=3; i++)); do
        ./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
    done
done

Notes:

  • /Data/*.txt expands to the paths of the text files in /Data (including the /Data/ part)
  • $( ... ) runs a shell command and inserts its output at that point in the command line
  • basename somepath .txt outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt -> file)

If you needed to run MyProgram with Data/file.txt instead of /Data/file.txt, use "${filename#/}" to remove the leading slash. On the other hand, if it's really Data not /Data you want to scan, just use for filename in Data/*.txt.

$(document).click() not working correctly on iPhone. jquery

CSS Cursor:Pointer; is a great solution. FastClick https://github.com/ftlabs/fastclick is another solution which doesn't require you to change css if you didn't want Cursor:Pointer; on an element for some reason. I use fastclick now anyway to eliminate the 300ms delay on iOS devices.

jQuery getTime function

Digital Clock with jQuery

  <script type="text/javascript" src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js?ver=1.3.2'></script>
  <script type="text/javascript">
  $(document).ready(function() {
  function myDate(){
  var now = new Date();

  var outHour = now.getHours();
  if (outHour >12){newHour = outHour-12;outHour = newHour;}
  if(outHour<10){document.getElementById('HourDiv').innerHTML="0"+outHour;}
  else{document.getElementById('HourDiv').innerHTML=outHour;}

  var outMin = now.getMinutes();
  if(outMin<10){document.getElementById('MinutDiv').innerHTML="0"+outMin;}
  else{document.getElementById('MinutDiv').innerHTML=outMin;}

  var outSec = now.getSeconds();
  if(outSec<10){document.getElementById('SecDiv').innerHTML="0"+outSec;}
  else{document.getElementById('SecDiv').innerHTML=outSec;}

} myDate(); setInterval(function(){ myDate();}, 1000); }); </script> <style> body {font-family:"Comic Sans MS", cursive;} h1 {text-align:center;background: gray;color:#fff;padding:5px;padding-bottom:10px;} #Content {margin:0 auto;border:solid 1px gray;width:140px;display:table;background:gray;} #HourDiv, #MinutDiv, #SecDiv {float:left;color:#fff;width:40px;text-align:center;font-size:25px;} span {float:left;color:#fff;font-size:25px;} </style> <div id="clockDiv"></div> <h1>My jQery Clock</h1> <div id="Content"> <div id="HourDiv"></div><span>:</span><div id="MinutDiv"></div><span>:</span><div id="SecDiv"></div> </div>

How to set character limit on the_content() and the_excerpt() in wordpress

This also balances HTML tags so that they won't be left open and doesn't break words.

add_filter("the_content", "break_text");
function break_text($text){
    $length = 500;
    if(strlen($text)<$length+10) return $text;//don't cut if too short

    $break_pos = strpos($text, ' ', $length);//find next space after desired length
    $visible = substr($text, 0, $break_pos);
    return balanceTags($visible) . " […]";
} 

Undefined reference to pthread_create in Linux

In Anjuta, go to the Build menu, then Configure Project. In the Configure Options box, add:

LDFLAGS='-lpthread'

Hope it'll help somebody too...

The module was expected to contain an assembly manifest

I got the error in the following case:

  1. A .NET EXE file (#1) was referencing another .NET EXE file (#2)
  2. I was trying to obfuscate EXE #2 with Themida
  3. when running the EXE #1 it was crashing with the error "The module was expected to contain an assembly manifest"

I simply avoided the obfuscation and the error is gone. not a real solution, but at least I know what caused it...

TypeError: 'module' object is not callable

Add to the main __init__.py in YourClassParentDir, e.g.:

from .YourClass import YourClass

Then, you will have an instance of your class ready when you import it into another script:

from YourClassParentDir import YourClass

Setting up foreign keys in phpMyAdmin?

In phpmyadmin, you can assign Foreign key simply by its GUI. Click on the table and go to Structure tab. find the Relation View on just bellow of table (shown in below image).

enter image description here

You can assign the forging key from the list box near by the primary key.(See image below). and save

enter image description here

corresponding SQL query automatically generated and executed.

How to loop through a dataset in powershell?

The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()

for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{ 
  write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}

Additionally foreach allows you to iterate through a collection or array without needing to figure out the length.

Rewritten (and edited for compile) -

foreach ($Row in $ds.Tables[1].Rows)
{ 
  write-host "value is : $($Row[0])"
}

go to character in vim

:goto 21490 will take you to the 21490th byte in the buffer.

Replace all whitespace with a line break/paragraph mark to make a word list

You can also do it with xargs:

cat old | xargs -n1 > new

or

xargs -n1 < old > new

What are "res" and "req" parameters in Express functions?

req is an object containing information about the HTTP request that raised the event. In response to req, you use res to send back the desired HTTP response.

Those parameters can be named anything. You could change that code to this if it's more clear:

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

Edit:

Say you have this method:

app.get('/people.json', function(request, response) { });

The request will be an object with properties like these (just to name a few):

  • request.url, which will be "/people.json" when this particular action is triggered
  • request.method, which will be "GET" in this case, hence the app.get() call.
  • An array of HTTP headers in request.headers, containing items like request.headers.accept, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.
  • An array of query string parameters if there were any, in request.query (e.g. /people.json?foo=bar would result in request.query.foo containing the string "bar").

To respond to that request, you use the response object to build your response. To expand on the people.json example:

app.get('/people.json', function(request, response) {
  // We want to set the content-type header so that the browser understands
  //  the content of the response.
  response.contentType('application/json');

  // Normally, the data is fetched from a database, but we can cheat:
  var people = [
    { name: 'Dave', location: 'Atlanta' },
    { name: 'Santa Claus', location: 'North Pole' },
    { name: 'Man in the Moon', location: 'The Moon' }
  ];

  // Since the request is for a JSON representation of the people, we
  //  should JSON serialize them. The built-in JSON.stringify() function
  //  does that.
  var peopleJSON = JSON.stringify(people);

  // Now, we can use the response object's send method to push that string
  //  of people JSON back to the browser in response to this request:
  response.send(peopleJSON);
});

Peak-finding algorithm for Python/SciPy

First things first, the definition of "peak" is vague if without further specifications. For example, for the following series, would you call 5-4-5 one peak or two?

1-2-1-2-1-1-5-4-5-1-1-5-1

In this case, you'll need at least two thresholds: 1) a high threshold only above which can an extreme value register as a peak; and 2) a low threshold so that extreme values separated by small values below it will become two peaks.

Peak detection is a well-studied topic in Extreme Value Theory literature, also known as "declustering of extreme values". Its typical applications include identifying hazard events based on continuous readings of environmental variables e.g. analysing wind speed to detect storm events.

Difference between rake db:migrate db:reset and db:schema:load

  • db:migrate runs (single) migrations that have not run yet.

  • db:create creates the database

  • db:drop deletes the database

  • db:schema:load creates tables and columns within the existing database following schema.rb. This will delete existing data.

  • db:setup does db:create, db:schema:load, db:seed

  • db:reset does db:drop, db:setup

  • db:migrate:reset does db:drop, db:create, db:migrate

Typically, you would use db:migrate after having made changes to the schema via new migration files (this makes sense only if there is already data in the database). db:schema:load is used when you setup a new instance of your app.

I hope that helps.


UPDATE for rails 3.2.12:

I just checked the source and the dependencies are like this now:

  • db:create creates the database for the current env

  • db:create:all creates the databases for all envs

  • db:drop drops the database for the current env

  • db:drop:all drops the databases for all envs

  • db:migrate runs migrations for the current env that have not run yet

  • db:migrate:up runs one specific migration

  • db:migrate:down rolls back one specific migration

  • db:migrate:status shows current migration status

  • db:rollback rolls back the last migration

  • db:forward advances the current schema version to the next one

  • db:seed (only) runs the db/seed.rb file

  • db:schema:load loads the schema into the current env's database

  • db:schema:dump dumps the current env's schema (and seems to create the db as well)

  • db:setup runs db:schema:load, db:seed

  • db:reset runs db:drop db:setup

  • db:migrate:redo runs (db:migrate:down db:migrate:up) or (db:rollback db:migrate) depending on the specified migration

  • db:migrate:reset runs db:drop db:create db:migrate

For further information please have a look at https://github.com/rails/rails/blob/v3.2.12/activerecord/lib/active_record/railties/databases.rake (for Rails 3.2.x) and https://github.com/rails/rails/blob/v4.0.5/activerecord/lib/active_record/railties/databases.rake (for Rails 4.0.x)

Pass request headers in a jQuery AJAX GET call

Use beforeSend:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }
      });

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

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

RookieRick is right, using DataGridTemplateColumn instead of DataGridComboBoxColumn gives a much simpler XAML.

Moreover, putting the CompanyItem list directly accessible from the GridItem allows you to get rid of the RelativeSource.

IMHO, this give you a very clean solution.

XAML:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GridItems}" >
    <DataGrid.Resources>
        <DataTemplate x:Key="CompanyDisplayTemplate" DataType="vm:GridItem">
            <TextBlock Text="{Binding Company}" />
        </DataTemplate>
        <DataTemplate x:Key="CompanyEditingTemplate" DataType="vm:GridItem">
            <ComboBox SelectedItem="{Binding Company}" ItemsSource="{Binding CompanyList}" />
        </DataTemplate>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Name}" />
        <DataGridTemplateColumn CellTemplate="{StaticResource CompanyDisplayTemplate}"
                                CellEditingTemplate="{StaticResource CompanyEditingTemplate}" />
    </DataGrid.Columns>
</DataGrid>

View model:

public class GridItem
{
    public string Name { get; set; }
    public CompanyItem Company { get; set; }
    public IEnumerable<CompanyItem> CompanyList { get; set; }
}

public class CompanyItem
{
    public int ID { get; set; }
    public string Name { get; set; }

    public override string ToString() { return Name; }
}

public class ViewModel
{
    readonly ObservableCollection<CompanyItem> companies;

    public ViewModel()
    {
        companies = new ObservableCollection<CompanyItem>{
            new CompanyItem { ID = 1, Name = "Company 1" },
            new CompanyItem { ID = 2, Name = "Company 2" }
        };

        GridItems = new ObservableCollection<GridItem> {
            new GridItem { Name = "Jim", Company = companies[0], CompanyList = companies}
        };
    }

    public ObservableCollection<GridItem> GridItems { get; set; }
}

XAMPP Apache Webserver localhost not working on MAC OS

Run xampp services by command line

To start apache service

sudo /Applications/XAMPP/xamppfiles/bin/apachectl start

To start mysql service

sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start

Both commands are working like charm :)

How to sort with lambda in Python

You're trying to use key functions with lambda functions.

Python and other languages like C# or F# use lambda functions.

Also, when it comes to key functions and according to the documentation

Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

...

The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.

So, key functions have a parameter key and it can indeed receive a lambda function.

In Real Python there's a nice example of its usage. Let's say you have the following list

ids = ['id1', 'id100', 'id2', 'id22', 'id3', 'id30']

and want to sort through its "integers". Then, you'd do something like

sorted_ids = sorted(ids, key=lambda x: int(x[2:])) # Integer sort

and printing it would give

['id1', 'id2', 'id3', 'id22', 'id30', 'id100']

In your particular case, you're only missing to write key= before lambda. So, you'd want to use the following

a = sorted(a, key=lambda x: x.modified, reverse=True)

How to format a JavaScript date

To obtain "10-Aug-2010", try:

var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})

For browser support, see toLocaleDateString.

How do I list all the files in a directory and subdirectories in reverse chronological order?

ls -lR is to display all files, directories and sub directories of the current directory ls -lR | more is used to show all the files in a flow.

Is there a way to specify a max height or width for an image?

set a style for the image

<asp:Image ID="Image1" runat="server" style="max-height:1000px;max-width:900px;height:auto;width:auto;" />

String representation of an Enum

A lot of great answers here but in my case did not solve what I wanted out of an "string enum", which was:

  1. Usable in a switch statement e.g switch(myEnum)
  2. Can be used in function parameters e.g. foo(myEnum type)
  3. Can be referenced e.g. myEnum.FirstElement
  4. I can use strings e.g. foo("FirstElement") == foo(myEnum.FirstElement)

1,2 & 4 can actually be solved with a C# Typedef of a string (since strings are switchable in c#)

3 can be solved by static const strings. So if you have the same needs, this is the simplest approach:

public sealed class Types
{

    private readonly String name;

    private Types(String name)
    {
        this.name = name;

    }

    public override String ToString()
    {
        return name;
    }

    public static implicit operator Types(string str)
    {
        return new Types(str);

    }
    public static implicit operator string(Types str)
    {
        return str.ToString();
    }


    #region enum

    public const string DataType = "Data";
    public const string ImageType = "Image";
    public const string Folder = "Folder";
    #endregion

}

This allows for example:

    public TypeArgs(Types SelectedType)
    {
        Types SelectedType = SelectedType
    }

and

public TypeObject CreateType(Types type)
    {
        switch (type)
        {

            case Types.ImageType:
              //
                break;

            case Types.DataType:
             //
                break;

        }
    }

Where CreateType can be called with a string or a type. However the downside is that any string is automatically a valid enum, this could be modified but then it would require some kind of init function...or possibly make they explicit cast internal?

Now if an int value was important to you (perhaps for comparison speed), you could use some ideas from Jakub Šturc fantastic answer and do something a bit crazy, this is my stab at it:

    public sealed class Types
{
    private static readonly Dictionary<string, Types> strInstance = new Dictionary<string, Types>();
    private static readonly Dictionary<int, Types> intInstance = new Dictionary<int, Types>();

    private readonly String name;
    private static int layerTypeCount = 0;
    private int value;
    private Types(String name)
    {
        this.name = name;
        value = layerTypeCount++;
        strInstance[name] = this;
        intInstance[value] = this;
    }

    public override String ToString()
    {
        return name;
    }


    public static implicit operator Types(int val)
    {
        Types result;
        if (intInstance.TryGetValue(val, out result))
            return result;
        else
            throw new InvalidCastException();
    }

    public static implicit operator Types(string str)
    {
        Types result;
        if (strInstance.TryGetValue(str, out result))
        {
            return result;
        }
        else
        {
            result = new Types(str);
            return result;
        }

    }
    public static implicit operator string(Types str)
    {
        return str.ToString();
    }

    public static bool operator ==(Types a, Types b)
    {
        return a.value == b.value;
    }
    public static bool operator !=(Types a, Types b)
    {
        return a.value != b.value;
    }

    #region enum

    public const string DataType = "Data";
    public const string ImageType = "Image";

    #endregion

}

but of course "Types bob = 4;" would be meaningless unless you had initialized them first which would sort of defeat the point...

But in theory TypeA == TypeB would be quicker...

Get list of a class' instance methods

$ irb --simple-prompt

class TestClass
  def method1
  end

  def method2
  end

  def method3
  end
end

tc_list = TestClass.instance_methods(false)
#[:method1, :method2, :method3]
puts tc_list
#method1
#method2
#method3

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

Yes, I know I'm late to this party but it might help others.

The servlet container chooses the mapping based on the longest path that matches. So you can put this mapping in for your JSPs and it will be chosen over the /* mapping.

<servlet-mapping>
  <servlet-name>jsp</servlet-name>
  <url-pattern>/WEB-INF/pages/*</url-pattern>
 </servlet-mapping>

Actually for Tomcat that's all you'll need since jsp is a servlet that exists out of the box. For other containers you either need to find out the name of the JSP servlet or add a servlet definition like:

<servlet>
  <servlet-name>jsp</servlet-name>
  <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
</servlet>

How to insert data using wpdb

You have to check your quotes properly,

$sql = $wpdb->prepare(
    "INSERT INTO `wp_submitted_form`      
       (`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`) 
 values ($name, $email, $phone, $country, $course, $message, $datesent)");
$wpdb->query($sql);

OR you can use like,

$sql = "INSERT INTO `wp_submitted_form`
          (`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`) 
   values ($name, $email, $phone, $country, $course, $message, $datesent)";

$wpdb->query($sql);

Read http://codex.wordpress.org/Class_Reference/wpdb

Echo newline in Bash prints literal \n

There is a new parameter expansion added in bash 4.4 that interprets escape sequences:

${parameter@operator} - E operator

The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $'…' quoting mechanism.

$ foo='hello\nworld'
$ echo "${foo@E}"
hello
world

Is there a portable way to get the current username in Python?

If you are needing this to get user's home dir, below could be considered as portable (win32 and linux at least), part of a standard library.

>>> os.path.expanduser('~')
'C:\\Documents and Settings\\johnsmith'

Also you could parse such string to get only last path component (ie. user name).

See: os.path.expanduser

Set language for syntax highlighting in Visual Studio Code

Syntax Highlighting for custom file extension

Any custom file extension can be associated with standard syntax highlighting with custom files association in User Settings as follows.

Changing File Association settings for permanent Syntax Highlighting

Note that this will be a permanent setting. In order to set for the current session alone, type in the preferred language in Select Language Mode box (without changing file association settings)

Installing new Syntax Package

If the required syntax package is not available by default, you can add them via the Extension Marketplace (Ctrl+Shift+X) and search for the language package.

You can further reproduce the above steps to map the file extensions with the new syntax package.

How to get the command line args passed to a running process on unix/linux systems?

If you want to get a long-as-possible (not sure what limits there are), similar to Solaris' pargs, you can use this on Linux & OSX:

ps -ww -o pid,command [-p <pid> ... ]

Django - Static file not found

{'document_root', settings.STATIC_ROOT} needs to be {'document_root': settings.STATIC_ROOT}

or you'll get an error like dictionary update sequence element #0 has length 6; 2 is required

Can I pass parameters by reference in Java?

From James Gosling in "The Java Programming Language":

"...There is exactly one parameter passing mode in Java - pass by value - and that keeps things simple. .."

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

Wrong quoting: (and missing option closing tag xd)

$out.='<option value="'.$key.'">'.$value["name"].'</option>';

How to generate random number with the specific length in python

You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:

import random

def generate_random_number(length):
    return int(''.join([str(random.randint(0,10)) for _ in range(length)]))

How to import multiple csv files in a single load?

Using Spark 2.0+, we can load multiple CSV files from different directories using df = spark.read.csv(['directory_1','directory_2','directory_3'.....], header=True). For more information, refer the documentation here

How to use if-else logic in Java 8 stream forEach

In most cases, when you find yourself using forEach on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.

Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Maps and Lists, but no out of-the-box collector for combining two different collectors, based on a predicate.

Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as

Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
    .collect(conditional(entry -> entry.getValue() != null,
            Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
            Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;

But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:

List<KeyType> myList=animalMap.entrySet().stream()
    .filter(pair -> pair.getValue() == null)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

animalMap.keySet().removeAll(myList);

Note that you can remove mappings to null even without having the list of the other keys:

animalMap.values().removeIf(Objects::isNull);

or

animalMap.values().removeAll(Collections.singleton(null));

If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy is going into the right direction, but you may simplify it:

Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
    .collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
                 Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());

The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.

How do I decode a string with escaped unicode?

I don't have enough rep to put this under comments to the existing answers:

unescape is only deprecated for working with URIs (or any encoded utf-8) which is probably the case for most people's needs. encodeURIComponent converts a js string to escaped UTF-8 and decodeURIComponent only works on escaped UTF-8 bytes. It throws an error for something like decodeURIComponent('%a9'); // error because extended ascii isn't valid utf-8 (even though that's still a unicode value), whereas unescape('%a9'); // © So you need to know your data when using decodeURIComponent.

decodeURIComponent won't work on "%C2" or any lone byte over 0x7f because in utf-8 that indicates part of a surrogate. However decodeURIComponent("%C2%A9") //gives you © Unescape wouldn't work properly on that // © AND it wouldn't throw an error, so unescape can lead to buggy code if you don't know your data.

How to install packages offline?

For Pip 8.1.2 you can use pip download -r requ.txt to download packages to your local machine.

Simplest way to wait some asynchronous tasks complete, in Javascript?

Expanding upon @freakish answer, async also offers a each method, which seems especially suited for your case:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    conn.collection(name).drop( callback );
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

IMHO, this makes the code both more efficient and more legible. I've taken the liberty of removing the console.log('dropped') - if you want it, use this instead:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    // if you really want the console.log( 'dropped' ),
    // replace the 'callback' here with an anonymous function
    conn.collection(name).drop( function(err) {
        if( err ) { return callback(err); }
        console.log('dropped');
        callback()
    });
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

Pipenv: Command Not Found

On Mac OS X Catalina it appears to follow the Linux path. Using any of:

pip install pipenv
pip3 install pipenv
sudo pip install pipenv
sudo pip3 install pipenv

Essentially installs pipenv here:

/Users/mike/Library/Python/3.7/lib/python/site-packages/pipenv

But its not the executable and so is never found. The only thing that worked for me was

pip install --user pipenv

This seems to result in an __init__.py file in the above directory that has contents to correctly expose the pipenv command.

and everything started working, when all other posted and commented suggestions on this question failed.

The pipenv package certainly seems quite picky.

Should I use encodeURI or encodeURIComponent for encoding URLs?

Difference between encodeURI and encodeURIComponent:

encodeURIComponent(value) is mainly used to encode queryString parameter values, and it encodes every applicable character in value. encodeURI ignores protocol prefix (http://) and domain name.


In very, very rare cases, when you want to implement manual encoding to encode additional characters (though they don't need to be encoded in typical cases) like: ! * , then you might use:

function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

(source)

How to resize an image with OpenCV2.0 and Python2.6

Example doubling the image size

There are two ways to resize an image. The new size can be specified:

  1. Manually;

    height, width = src.shape[:2]

    dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)

  2. By a scaling factor.

    dst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC), where fx is the scaling factor along the horizontal axis and fy along the vertical axis.

To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK).

Example shrink image to fit a max height/width (keeping aspect ratio)

import cv2

img = cv2.imread('YOUR_PATH_TO_IMG')

height, width = img.shape[:2]
max_height = 300
max_width = 300

# only shrink if img is bigger than required
if max_height < height or max_width < width:
    # get scaling factor
    scaling_factor = max_height / float(height)
    if max_width/float(width) < scaling_factor:
        scaling_factor = max_width / float(width)
    # resize image
    img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)

cv2.imshow("Shrinked image", img)
key = cv2.waitKey()

Using your code with cv2

import cv2 as cv

im = cv.imread(path)

height, width = im.shape[:2]

thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA)

cv.imshow('exampleshq', thumbnail)
cv.waitKey(0)
cv.destroyAllWindows()

Python basics printing 1 to 100

I would guess it makes an infinite loop bc you skip the number 100. If you set the critera to be less than 101 it should do the trick :)

def gukan(count):
    while count<100:
      print(count)
      count=count+3;
gukan(0)

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?

Extract filename and extension in Bash

You can force cut to display all fields and subsequent ones adding - to field number.

NAME=`basename "$FILE"`
EXTENSION=`echo "$NAME" | cut -d'.' -f2-`

So if FILE is eth0.pcap.gz, the EXTENSION will be pcap.gz

Using the same logic, you can also fetch the file name using '-' with cut as follows :

NAME=`basename "$FILE" | cut -d'.' -f-1`

This works even for filenames that do not have any extension.

how to get bounding box for div element in jquery

You can get the bounding box of any element by calling getBoundingClientRect

var rect = document.getElementById("myElement").getBoundingClientRect();

That will return an object with left, top, width and height fields.

How to check whether a variable is a class or not?

>>> class X(object):
...     pass
... 
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We faced the same problem:

ORA-29913: error in executing ODCIEXTTABLEOPEN callout
ORA-29400: data cartridge error error opening file /fs01/app/rms01/external/logs/SH_EXT_TAB_VGAG_DELIV_SCHED.log

In our case we had a RAC with 2 nodes. After giving write permission on the log directory, on both sides, everything worked fine.

Setting the focus to a text field

I have had a similar scenario where I needed to set the focus on a text box within a panel when the panel was shown. The panel was loaded on application startup, so I couldn't set the focus in the constructor. As the panel wasn't being loaded or being given focus on show, this meant that I had no event to fire the focus request from.

To solve this, I added a global method to my main that called a method in the panel that invoked requestFocusInWindow() on the text area. I put the call to the global method in the button that showed the panel, after the call to show. This meant that the panel would be shown and then the text area assigned the focus after showing the panel. Hope that makes sense and helps!

Also, you can edit most of the auto-generated code by right clicking on the object in design view and selecting customize code, however I don't think that it allows you to edit panels.

Is it possible to use an input value attribute as a CSS selector?

As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:

<style>
input:not([value=""]){
border:2px solid red;
}
</style>

<input type="text" onkeyup="this.setAttribute('value', this.value);"/>

What does the "+" (plus sign) CSS selector mean?

+ presents one of the relative selectors. Here is a list of all relative selectors:

div p - All <p> elements inside of a <div> element are selected.

div > p - All <p> elements whose direct parent is <div> are selected. It works backwards too (p < div)

div + p - All <p> elements placed immediately after a <div> element are selected.

div ~ p - All <p> elements that are preceded by a <div> element are selected.

Here is some more about selectors.

Dynamic constant assignment

In Ruby, any variable whose name starts with a capital letter is a constant and you can only assign to it once. Choose one of these alternatives:

class MyClass
  MYCONSTANT = "blah"

  def mymethod
    MYCONSTANT
  end
end

class MyClass
  def mymethod
    my_constant = "blah"
  end
end

Batch file to delete files older than N days

More flexible way is to use FileTimeFilterJS.bat:

@echo off

::::::::::::::::::::::
set "_DIR=C:\Users\npocmaka\Downloads"
set "_DAYS=-5"
::::::::::::::::::::::

for /f "tokens=* delims=" %%# in ('FileTimeFilterJS.bat  "%_DIR%" -dd %_DAYS%') do (
    echo deleting  "%%~f#"
    echo del /q /f "%%~f#"
)

The script will allow you to use measurements like days, minutes ,seconds or hours. To choose weather to filter the files by time of creation, access or modification To list files before or after a certain date (or between two dates) To choose if to show files or dirs (or both) To be recursive or not

How to Export-CSV of Active Directory Objects?

the first command is correct but change from convert to export to csv, as below,

Get-ADUser -Filter * -Properties * `
    | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization `
    | Sort-Object -Property Name `
    | Export-Csv -path  C:\Users\*\Desktop\file1.csv

APR based Apache Tomcat Native library was not found on the java.library.path?

My case: Seeing the same INFO message.

Centos 6.2 x86_64 Tomcat 6.0.24

This fixed the problem for me:

yum install tomcat-native

boom!

The pipe ' ' could not be found angular2 custom pipe

You need to include your pipe in module declaration:

declarations: [ UsersPipe ],
providers: [UsersPipe]

pySerial write() won't take my string

I had the same "TypeError: an integer is required" error message when attempting to write. Thanks, the .encode() solved it for me. I'm running python 3.4 on a Dell D530 running 32 bit Windows XP Pro.

I'm omitting the com port settings here:

>>>import serial

>>>ser = serial.Serial(5)

>>>ser.close()

>>>ser.open()

>>>ser.write("1".encode())

1

>>>

Java String array: is there a size of method?

If you want a function to do this

Object array = new String[10];
int size = Array.getlength(array);

This can be useful if you don't know what type of array you have e.g. int[], byte[] or Object[].

How do you make websites with Java?

Read the tutorial on Java Web applications.

Basically Web applications are a part of the Java EE standard. A lot of people only use the Web (servlets) part with additional frameworks thrown in, most notably Spring but also Struts, Seam and others.

All you need is an IDE like IntelliJ, Eclipse or Netbeans, the JDK, the Java EE download and a servlet container like Tomcat (or a full-blown application server like Glassfish or JBoss).

Here is a Tomcat tutorial.

Simple way to encode a string according to a password?

The "encoded_c" mentioned in the @smehmood's Vigenere cipher answer should be "key_c".

Here are working encode/decode functions.

import base64
def encode(key, clear):
    enc = []
    for i in range(len(clear)):
        key_c = key[i % len(key)]
        enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
        enc.append(enc_c)
    return base64.urlsafe_b64encode("".join(enc))

def decode(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc)
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)

Disclaimer: As implied by the comments, this should not be used to protect data in a real application, unless you read this and don't mind talking with lawyers:

What's wrong with XOR encryption?

Unable to auto-detect email address

This problem has very simple solution. Just open your SmartGit, then go to Repository option(On top left), then go to settings. It will open a dialog box of Repository Settings. Now, click on Commit TAB and write your UserName and EmailId which you give on BitBucke website. Now click ok and again try to Commit and it works fine now.

Kill process by name?

For me the only thing that worked is been:

For example

import subprocess
proc = subprocess.Popen(["pkill", "-f", "scriptName.py"], stdout=subprocess.PIPE)
proc.wait()

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Try this:

    private void comboBox1_KeyDown(object sender, KeyEventArgs e)
    {
        // comboBox1 is readonly
        e.SuppressKeyPress = true;
    }

how to convert image to byte array in java?

Using RandomAccessFile would be simple and handy.

RandomAccessFile f = new RandomAccessFile(filepath, "r");
byte[] bytes = new byte[(int) f.length()];
f.read(bytes);
f.close();

PHP: Count a stdClass object

Just use this

$i=0;
foreach ($object as $key =>$value)
{
$i++;
}

the variable $i is number of keys.

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

I had the similar issue. I solved it the following way after a number of attempts to follow the pieces of advice in the forums. I am reposting the solution because it could be helpful for others.

I am running Windows 7 (Apache 2.2 & PHP 5.2.17 & MySQL 5.0.51a), the syntax in the file "httpd.conf" (C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\httpd.conf) was sensitive to slashes. You can check if "php.ini" is read from the right directory. Just type in your browser "localhost/index.php". The code of index.php is the following:

<?php echo phpinfo(); ?>

There is the row (not far from the top) called "Loaded Configuration File". So, if there is nothing added, then the problem could be that your "php.ini" is not read, even you uncommented (extension=php_mysql.dll and extension=php_mysqli.dll). So, in order to make it work I did the following step. I needed to change from

PHPIniDir 'c:\PHP\'

to

PHPIniDir 'c:\PHP'

Pay the attention that the last slash disturbed everything!

Now the row "Loaded Configuration File" gets "C:\PHP\php.ini" after refreshing "localhost/index.php" (before I restarted Apache2.2) as well as mysql block is there. MySQL and PHP are working together!

How can I use numpy.correlate to do autocorrelation?

Your question 1 has been already extensively discussed in several excellent answers here.

I thought to share with you a few lines of code that allow you to compute the autocorrelation of a signal based only on the mathematical properties of the autocorrelation. That is, the autocorrelation may be computed in the following way:

  1. subtract the mean from the signal and obtain an unbiased signal

  2. compute the Fourier transform of the unbiased signal

  3. compute the power spectral density of the signal, by taking the square norm of each value of the Fourier transform of the unbiased signal

  4. compute the inverse Fourier transform of the power spectral density

  5. normalize the inverse Fourier transform of the power spectral density by the sum of the squares of the unbiased signal, and take only half of the resulting vector

The code to do this is the following:

def autocorrelation (x) :
    """
    Compute the autocorrelation of the signal, based on the properties of the
    power spectral density of the signal.
    """
    xp = x-np.mean(x)
    f = np.fft.fft(xp)
    p = np.array([np.real(v)**2+np.imag(v)**2 for v in f])
    pi = np.fft.ifft(p)
    return np.real(pi)[:x.size/2]/np.sum(xp**2)

null vs empty string in Oracle

This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.

On the other hand, SQL Server would let you do what you are trying to achieve.

There are 2 workarounds here:

  1. Use another column that states whether the 'description' field is valid or not
  2. Use some dummy value for the 'description' field where you want it to store empty string. (i.e. set the field to be 'stackoverflowrocks' assuming your real data will never encounter such a description value)

Both are, of course, stupid workarounds :)

Sublime Text 2 - Show file navigation in sidebar

You may drag'n'drop your folder to Side bar. To enable Side bar you should do View -> Side bar -> show opened files. You'll got opened files (tabs) tree and folder structure at Side bar.

UITextField border color

Import the following class:

#import <QuartzCore/QuartzCore.h> 

//Code for setting the grey color for the border of the text field

[[textField layer] setBorderColor:[[UIColor colorWithRed:171.0/255.0
                                                   green:171.0/255.0
                                                    blue:171.0/255.0
                                                   alpha:1.0] CGColor]];

Replace 171.0 with the respective color number as required.

Check if element exists in jQuery

If you have a class on your element, then you can try the following:

if( $('.exists_content').hasClass('exists_content') ){
 //element available
}

What is the best Java library to use for HTTP POST, GET etc.?

imho: Apache HTTP Client

usage example:

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {

  private static String url = "http://www.apache.org/";

  public static void main(String[] args) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    GetMethod method = new GetMethod(url);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
            new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: " + method.getStatusLine());
      }

      // Read the response body.
      byte[] responseBody = method.getResponseBody();

      // Deal with the response.
      // Use caution: ensure correct character encoding and is not binary data
      System.out.println(new String(responseBody));

    } catch (HttpException e) {
      System.err.println("Fatal protocol violation: " + e.getMessage());
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    } finally {
      // Release the connection.
      method.releaseConnection();
    }  
  }
}

some highlight features:

  • Standards based, pure Java, implementation of HTTP versions 1.0 and 1.1
    • Full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework.
    • Supports encryption with HTTPS (HTTP over SSL) protocol.
    • Granular non-standards configuration and tracking.
    • Transparent connections through HTTP proxies.
    • Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
    • Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
    • Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
    • Plug-in mechanism for custom authentication methods.
    • Multi-Part form POST for uploading large files.
    • Pluggable secure sockets implementations, making it easier to use third party solutions
    • Connection management support for use in multi-threaded applications. Supports setting the maximum total connections as well as the maximum connections per host. Detects and closes stale connections.
    • Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
    • Plug-in mechanism for custom cookie policies.
    • Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
    • Response input streams to efficiently read the response body by streaming directly from the socket to the server.
    • Persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
    • Direct access to the response code and headers sent by the server.
    • The ability to set connection timeouts.
    • HttpMethods implement the Command Pattern to allow for parallel requests and efficient re-use of connections.
    • Source code is freely available under the Apache Software License.

Use stored procedure to insert some data into a table

If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.

insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)

There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:

CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int

AS 

If you want to know what the ID of the newly inserted record is add

SELECT @@IDENTITY

to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx

You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.

P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.

PSQLException: current transaction is aborted, commands ignored until end of transaction block

This is very weird behavior of PostgreSQL, it is even not " in-line with the PostgreSQL philosophy of forcing the user to make everything explicit" - as the exception was caught and ignored explicitly. So even this defense does not hold. Oracle in this case behaves much more user-friendly and (as for me) correctly - it leaves a choice to the developer.

Difference between "module.exports" and "exports" in the CommonJs Module System

module is a plain JavaScript object with an exports property. exports is a plain JavaScript variable that happens to be set to module.exports. At the end of your file, node.js will basically 'return' module.exports to the require function. A simplified way to view a JS file in Node could be this:

var module = { exports: {} };
var exports = module.exports;

// your code

return module.exports;

If you set a property on exports, like exports.a = 9;, that will set module.exports.a as well because objects are passed around as references in JavaScript, which means that if you set multiple variables to the same object, they are all the same object; so then exports and module.exports are the same object.
But if you set exports to something new, it will no longer be set to module.exports, so exports and module.exports are no longer the same object.

Is there a minlength validation attribute in HTML5?

I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:

autocomplete="off"

<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />

C# Convert a Base64 -> byte[]

This may be helpful

byte[] bytes = System.Convert.FromBase64String(stringInBase64);

Copy row but with new id

INSERT into table_name (  
    `product_id`, 
    `other_products_url_id`, 
    `brand`, 
    `title`, 
    `price`, 
    `category`, 
    `sub_category`, 
    `quantity`, 
    `buy_now`, 
    `buy_now_url`, 
    `is_available`, 
    `description`, 
    `image_url`, 
    `image_type`, 
    `server_image_url`, 
    `reviews`, 
    `hits`, 
    `rating`, 
    `seller_name`, 
    `seller_desc`, 
    `created_on`, 
    `modified_on`, 
    `status`) 
SELECT 
    `product_id`, 
    `other_products_url_id`, 
    `brand`, 
    `title`, 
    `price`, 
    `category`, 
    `sub_category`, 
    `quantity`, 
    `buy_now`, 
    concat(`buy_now_url`,'','#test123456'), 
    `is_available`, 
    `description`, 
    `image_url`, 
    `image_type`, 
    `server_image_url`, 
    `reviews`, 
    `hits`, 
    `rating`, 
    `seller_name`, 
    `seller_desc`, 
    `created_on`, 
    `modified_on`, 
    `status` 
FROM `table_name` WHERE id='YourRowID';

"inappropriate ioctl for device"

"files" in *nix type systems are very much an abstract concept.

They can be areas on disk organized by a file system, but they could equally well be a network connection, a bit of shared memory, the buffer output from another process, a screen or a keyboard.

In order for perl to be really useful it mirrors this model very closely, and does not treat files by emulating a magnetic tape as many 4gls do.

So it tried an "IOCTL" operation 'open for write' on a file handle which does not allow write operations which is an inappropriate IOCTL operation for that device/file.

The easiest thing to do is stick an " or die 'Cannot open $myfile' statement at the end of you open and you can choose your own meaningful message.

Datatables - Search Box outside datatable

You could move the div when the table is drawn using the fnDrawCallback function.

    $("#myTable").dataTable({
    "fnDrawCallback": function (oSettings) {
        $(".dataTables_filter").each(function () {
            $(this).appendTo($(this).parent().siblings(".panel-body"));
        });
    }
});

CSS background image in :after element

As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.

Should I use Java's String.format() if performance is important?

I just modified hhafez's test to include StringBuilder. StringBuilder is 33 times faster than String.format using jdk 1.6.0_10 client on XP. Using the -server switch lowers the factor to 20.

public class StringTest {

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

   private static void test() {
      int i = 0;
      long prev_time = System.currentTimeMillis();
      long time;

      for ( i = 0; i < 1000000; i++ ) {
         String s = "Blah" + i + "Blah";
      }
      time = System.currentTimeMillis() - prev_time;

      System.out.println("Time after for loop " + time);

      prev_time = System.currentTimeMillis();
      for ( i = 0; i < 1000000; i++ ) {
         String s = String.format("Blah %d Blah", i);
      }
      time = System.currentTimeMillis() - prev_time;
      System.out.println("Time after for loop " + time);

      prev_time = System.currentTimeMillis();
      for ( i = 0; i < 1000000; i++ ) {
         new StringBuilder("Blah").append(i).append("Blah");
      }
      time = System.currentTimeMillis() - prev_time;
      System.out.println("Time after for loop " + time);
   }
}

While this might sound drastic, I consider it to be relevant only in rare cases, because the absolute numbers are pretty low: 4 s for 1 million simple String.format calls is sort of ok - as long as I use them for logging or the like.

Update: As pointed out by sjbotha in the comments, the StringBuilder test is invalid, since it is missing a final .toString().

The correct speed-up factor from String.format(.) to StringBuilder is 23 on my machine (16 with the -server switch).

JBoss default password

If you are using Talend MDM Server, the login is: login: admin password: talend

See more: http://wiki.glitchdata.com/index.php?title=TOS:_Accessing_the_Talend_MDM_Server

This differs from the default JBoss login of admin/admin The password setup file is also login-config.xml in this case.

How To Set Up GUI On Amazon EC2 Ubuntu server

1) Launch Ubuntu Instance on EC2.
2) Open SSH Port in instance security.
3) Do SSH to instance.
4) Execute:

sudo apt-get update    sudo apt-get upgrade

5) Because you will be connecting from Windows Remote Desktop, edit the sshd_config file on your Linux instance to allow password authentication.

sudo vim /etc/ssh/sshd_config

6) Change PasswordAuthentication to yes from no, then save and exit.
7) Restart the SSH daemon to make this change take effect.

sudo /etc/init.d/ssh restart

8) Temporarily gain root privileges and change the password for the ubuntu user to a complex password to enhance security. Press the Enter key after typing the command passwd ubuntu, and you will be prompted to enter the new password twice.

sudo –i
passwd ubuntu

9) Switch back to the ubuntu user account and cd to the ubuntu home directory.

su ubuntu
cd

10) Install Ubuntu desktop functionality on your Linux instance, the last command can take up to 15 minutes to complete.

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get update
sudo -E apt-get install -y ubuntu-desktop

11) Install xrdp

sudo apt-get install xfce4
sudo apt-get install xfce4 xfce4-goodies

12) Make xfce4 the default window manager for RDP connections.

echo xfce4-session > ~/.xsession

13) Copy .xsession to the /etc/skel folder so that xfce4 is set as the default window manager for any new user accounts that are created.

sudo cp /home/ubuntu/.xsession /etc/skel

14) Open the xrdp.ini file to allow changing of the host port you will connect to.

sudo vim /etc/xrdp/xrdp.ini

(xrdp is not installed till now. First Install the xrdp with sudo apt-get install xrdp then edit the above mentioned file)

15) Look for the section [xrdp1] and change the following text (then save and exit [:wq]).

port=-1
- to -
port=ask-1

16) Restart xrdp.

sudo service xrdp restart

17) On Windows, open the Remote Desktop Connection client, paste the fully qualified name of your Amazon EC2 instance for the Computer, and then click Connect.

18) When prompted to Login to xrdp, ensure that the sesman-Xvnc module is selected, and enter the username ubuntu with the new password that you created in step 8. When you start a session, the port number is -1.

19) When the system connects, several status messages are displayed on the Connection Log screen. Pay close attention to these status messages and make note of the VNC port number displayed. If you want to return to a session later, specify this number in the port field of the xrdp login dialog box.

See more details: https://aws.amazon.com/premiumsupport/knowledge-center/connect-to-linux-desktop-from-windows/
http://c-nergy.be/blog/?p=5305

Best way to use PHP to encrypt and decrypt passwords?

Check out mycrypt(): http://us.php.net/manual/en/book.mcrypt.php

And if you're using postgres there's pgcrypto for database level encryption. (makes it easier to search and sort)

Difference between window.location.href=window.location.href and window.location.reload()

Came across this question researching some aberrant behavior in IE, specifically IE9, didn't check older versions. It seems

window.location.reload();

results in a refresh that blanks out the entire screen for a second, where as

 window.location = document.URL;

refreshes the page much more quickly, almost imperceptibly.

Doing a bit more research, and some experimentation with fiddler, it seems that window.location.reload() will bypass the cache and reload from the server regardless if you pass the boolean with it or not, this includes getting all of your assets (images, scripts, style sheets, etc) again. So if you just want the page to refresh the HTML, the window.location = document.URL will return much quicker and with less traffic.

A difference in behavior between browsers is that when IE9 uses the reload method it clears the visible page and seemingly rebuilds it from scratch, where FF and chrome wait till they get the new assets and rebuild them if they are different.

How to fix: Error device not found with ADB.exe

I solved:

Just turn off USB debugging and re-enable debugging it immediately

git stash apply version

Since version 2.11, it's pretty easy, you can use the N stack number instead of saying "stash@{n}". So now instead of using:

git stash apply "stash@{n}"

You can type:

git stash apply n

For example, in your list:

stash@{0}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{1}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{2}: WIP on design: eb65635... Email Adjust
stash@{3}: WIP on design: eb65635... Email Adjust

If you want to apply stash@{1} you could type:

git stash apply 1

Otherwise, you can use it even if you have some changes in your directory since 1.7.5.1, but you must be sure the stash won't overwrite your working directory changes if it does you'll get an error:

error: Your local changes to the following files would be overwritten by merge:
        file
Please commit your changes or stash them before you merge.

In versions prior to 1.7.5.1, it refused to work if there was a change in the working directory.


Git release notes:

The user always has to say "stash@{$N}" when naming a single element in the default location of the stash, i.e. reflogs in refs/stash. The "git stash" command learned to accept "git stash apply 4" as a short-hand for "git stash apply stash@{4}"

git stash apply" used to refuse to work if there was any change in the working tree, even when the change did not overlap with the change the stash recorded

Setting user agent of a java URLConnection

its work for me set the User-Agent in the addRequestProperty.

URL url = new URL(<URL>);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0");

Setting device orientation in Swift iOS

This will disable autorotation of the view:

override func shouldAutorotate() -> Bool {
    return false;
}

Update

override func shouldAutorotate() -> Bool {
    if (UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft ||
        UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight ||
        UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
            return false;
    }
    else {
        return true;
    }
}

If app is in landscape mode and you show a view which must be showed in portrait mode, this will allow app to change it's orientation to portrait (of course when device will be rotated to such orientation).

Could not open ServletContext resource

I think currently the application-context.xml file is into src/main/resources AND the social.properties file is into src/main/java... so when you package (mvn package) or when you run tomcat (mvn tomcat:run) your social.properties disappeared (I know you said when you checked into the .war the files are here... but your exception says the opposite).

The solution is simply to put all your configuration files (application-context.xml and social.properties) into src/main/resources to follow the maven standard structure.

How to deploy a Java Web Application (.war) on tomcat?

Log in :URL = "localhost:8080/" Enter username and pass word Click Manager App Scroll Down and find "WAR file to deploy" Chose file and click deploy

Done

Go to Webapp folder of you Apache tomcat you will see a folder name matching with your war file name.

Type link in your url address bar:: localhost:8080/HelloWorld/HelloWorld.html and press enter

Done

Force an Android activity to always use landscape mode

The following is the code which I used to display all activity in landscape mode:

<activity android:screenOrientation="landscape"
          android:configChanges="orientation|keyboardHidden"
          android:name="abcActivty"/>

`export const` vs. `export default` in ES6

From the documentation:

Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.

Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the "main" exported value since it will be the simplest to import.

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

Here's a simple script that generally does the trick for me:

SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time
  FROM sys.dm_exec_requests
  WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE') 

Android: How do I prevent the soft keyboard from pushing my view up?

There are two ways of solving this problem. Go to the AndroidManifist.xml, and in the name of your activity, add this line

   android:windowSoftInputMode="adjustPan"

As in the below code, I have added to the Register Activity.

 <activity android:name=".Register"
            android:windowSoftInputMode="adjustPan">

In the second way, go to your activity, and in your onCreate method, add this code.

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

Could not load file or assembly '***.dll' or one of its dependencies

This answer is totally unrelated to the OP's situation, and is a very unlikely scenario for anyone else too, but just in case it may help someone ...

In my case I was getting "Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0 ..." because I had disassembled and reassembled the program using ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 2. Switching to ILDAsm.exe and ILAsm.exe from .Net Framework / SDK version 4 fixed the problem.

(Strangely, even though doing what I did may seem like an obvious error, the resulting EXE file that didn't work did indicate that it targeted .Net 4 when examined with JetBrains dotPeek.)

Interface/enum listing standard mime-type constants

Java 7 to the rescue!

You can either pass the file or the file name and it will return the MIME type.

String mimeType = MimetypesFileTypeMap
    .getDefaultFileTypeMap()
    .getContentType(attachment.getFileName());

http://docs.oracle.com/javase/7/docs/api/javax/activation/MimetypesFileTypeMap.html

ASP.NET MVC JsonResult Date Format

What worked for me was to create a viewmodel that contained the date property as a string. Assigning the DateTime property from the domain model and calling the .ToString() on the date property while assigning the value to the viewmodel.

A JSON result from an MVC action method will return the date in a format compatible with the view.

View Model

public class TransactionsViewModel
{
    public string DateInitiated { get; set; }
    public string DateCompleted { get; set; }
}

Domain Model

public class Transaction{
   public DateTime? DateInitiated {get; set;}
   public DateTime? DateCompleted {get; set;}
}

Controller Action Method

public JsonResult GetTransactions(){

var transactions = _transactionsRepository.All;
        var model = new List<TransactionsViewModel>();

        foreach (var transaction in transactions)
        {
            var item = new TransactionsViewModel
            {
                ...............
                DateInitiated = transaction.DateInitiated.ToString(),
                DateCompleted = transaction.DateCompleted.ToString(),
            };

            model.Add(item);
        }
        return Json(model, JsonRequestBehavior.AllowGet);
}

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

C# how to wait for a webpage to finish loading before continuing

yuna and bnl code failed in the case below;

failing example:

1st one waits for completed.but, 2nd one with the invokemember("submit") didnt . invoke works. but ReadyState.Complete acts like its Completed before its REALLY completed:

wb.Navigate(url);
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
MessageBox.Show("ok this waits Complete");

//navigates to new page
wb.Document.GetElementById("formId").InvokeMember("submit");
while(wb.ReadyState != WebBrowserReadyState.Complete)
{
   Application.DoEvents();
}
MessageBox.Show("webBrowser havent navigated  yet. it gave me previous page's html.");  
var html = wb.Document.GetElementsByTagName("HTML")[0].OuterHtml;

how to fix this unwanted situation:

usage

    public myForm1 {

        myForm1_load() { }

        // func to make browser wait is inside the Extended class More tidy.
        WebBrowserEX wbEX = new WebBrowserEX();

        button1_click(){
            wbEX.Navigate("site1.com");
            wbEX.waitWebBrowserToComplete(wb);

            wbEX.Document.GetElementById("input1").SetAttribute("Value", "hello");
            //submit does navigation
            wbEX.Document.GetElementById("formid").InvokeMember("submit");
            wbEX.waitWebBrowserToComplete(wb);
            // this actually waits for document Compelete. worked for me.

            var processedHtml = wbEX.Document.GetElementsByTagName("HTML")[0].OuterHtml;
            var rawHtml = wbEX.DocumentText;
         }
     }

//put this  extended class in your code.
//(ie right below form class, or seperate cs file doesnt matter)
public class WebBrowserEX : WebBrowser
{
   //ctor
   WebBrowserEX()
   {
     //wired aumatically here. we dont need to worry our sweet brain.
     this.DocumentCompleted += (o, e) => { webbrowserDocumentCompleted = true;};
   }
     //instead of checking  readState, get state from DocumentCompleted Event 
     // via bool value
     bool webbrowserDocumentCompleted = false;
     public void waitWebBrowserToComplete()
     {
       while (!webbrowserDocumentCompleted )
       { Application.DoEvents();  }
       webbrowserDocumentCompleted = false;
     }

 }

How to add image in a TextView text?

This answer is based on this excellent answer by 18446744073709551615. Their solution, though helpful, does not size the image icon with the surrounding text. It also doesn't set the icon colour to that of the surrounding text.

The solution below takes a white, square icon and makes it fit the size and colour of the surrounding text.

public class TextViewWithImages extends TextView {

    private static final String DRAWABLE = "drawable";
    /**
     * Regex pattern that looks for embedded images of the format: [img src=imageName/]
     */
    public static final String PATTERN = "\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E";

    public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public TextViewWithImages(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TextViewWithImages(Context context) {
        super(context);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        final Spannable spannable = getTextWithImages(getContext(), text, getLineHeight(), getCurrentTextColor());
        super.setText(spannable, BufferType.SPANNABLE);
    }

    private static Spannable getTextWithImages(Context context, CharSequence text, int lineHeight, int colour) {
        final Spannable spannable = Spannable.Factory.getInstance().newSpannable(text);
        addImages(context, spannable, lineHeight, colour);
        return spannable;
    }

    private static boolean addImages(Context context, Spannable spannable, int lineHeight, int colour) {
        final Pattern refImg = Pattern.compile(PATTERN);
        boolean hasChanges = false;

        final Matcher matcher = refImg.matcher(spannable);
        while (matcher.find()) {
            boolean set = true;
            for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
                if (spannable.getSpanStart(span) >= matcher.start()
                        && spannable.getSpanEnd(span) <= matcher.end()) {
                    spannable.removeSpan(span);
                } else {
                    set = false;
                    break;
                }
            }
            final String resName = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
            final int id = context.getResources().getIdentifier(resName, DRAWABLE, context.getPackageName());
            if (set) {
                hasChanges = true;
                spannable.setSpan(makeImageSpan(context, id, lineHeight, colour),
                        matcher.start(),
                        matcher.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                );
            }
        }
        return hasChanges;
    }

    /**
     * Create an ImageSpan for the given icon drawable. This also sets the image size and colour.
     * Works best with a white, square icon because of the colouring and resizing.
     *
     * @param context       The Android Context.
     * @param drawableResId A drawable resource Id.
     * @param size          The desired size (i.e. width and height) of the image icon in pixels.
     *                      Use the lineHeight of the TextView to make the image inline with the
     *                      surrounding text.
     * @param colour        The colour (careful: NOT a resource Id) to apply to the image.
     * @return An ImageSpan, aligned with the bottom of the text.
     */
    private static ImageSpan makeImageSpan(Context context, int drawableResId, int size, int colour) {
        final Drawable drawable = context.getResources().getDrawable(drawableResId);
        drawable.mutate();
        drawable.setColorFilter(colour, PorterDuff.Mode.MULTIPLY);
        drawable.setBounds(0, 0, size, size);
        return new ImageSpan(drawable, ImageSpan.ALIGN_BOTTOM);
    }

}

How to use:

Simply embed references to the desired icons in the text. It doesn't matter whether the text is set programatically through textView.setText(R.string.string_resource); or if it's set in xml.

To embed a drawable icon named example.png, include the following string in the text: [img src=example/].

For example, a string resource might look like this:

<string name="string_resource">This [img src=example/] is an icon.</string>

create table in postgreSQL

Please try this:

CREATE TABLE article (
  article_id bigint(20) NOT NULL serial,
  article_name varchar(20) NOT NULL,
  article_desc text NOT NULL,
  date_added datetime default NULL,
  PRIMARY KEY (article_id)
);

How to filter by object property in angularJS

We have Collection as below:


enter image description here

Syntax:

{{(Collection/array/list | filter:{Value : (object value)})[0].KeyName}}

Example:

{{(Collectionstatus | filter:{Value:dt.Status})[0].KeyName}}

-OR-

Syntax:

ng-bind="(input | filter)"

Example:

ng-bind="(Collectionstatus | filter:{Value:dt.Status})[0].KeyName"

Service has zero application (non-infrastructure) endpoints

I just ran into this issue and checked all of the above answers to make sure I wasn't missing anything obvious. Well, I had a semi-obvious issue. My casing of my classname in code and the classname I used in the configuration file didn't match.

For example: if the class name is CalculatorService and the configuration file refers to Calculatorservice ... you will get this error.

How to print jquery object/array

What you have from the server is a string like below:

var data = '[{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}]';

Then you can use JSON.parse function to change it to an object. Then you access the category like below:

var dataObj = JSON.parse(data);

console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Meskie

How to install maven on redhat linux

I made the following script:

#!/bin/bash

# Target installation location
MAVEN_HOME="/your/path/here"

# Link to binary tar.gz archive
# See https://maven.apache.org/download.cgi?html_a_name#Files
MAVEN_BINARY_TAR_GZ_ARCHIVE="http://www.trieuvan.com/apache/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.tar.gz"

# Configuration parameters used to start up the JVM running Maven, i.e. "-Xms256m -Xmx512m"
# See https://maven.apache.org/configure.html
MAVEN_OPTS="" # Optional (not needed)

if [[ ! -d $MAVEN_HOME ]]; then
  # Create nonexistent subdirectories recursively
  mkdir -p $MAVEN_HOME

  # Curl location of tar.gz archive & extract without first directory
  curl -L $MAVEN_BINARY_TAR_GZ_ARCHIVE | tar -xzf - -C $MAVEN_HOME --strip 1

  # Creating a symbolic/soft link to Maven in the primary directory of executable commands on the system
  ln -s $MAVEN_HOME/bin/mvn /usr/bin/mvn

  # Permanently set environmental variable (if not null)
  if [[ -n $MAVEN_OPTS ]]; then
    echo "export MAVEN_OPTS=$MAVEN_OPTS" >> ~/.bashrc
  fi

  # Using MAVEN_HOME, MVN_HOME, or M2 as your env var is irrelevant, what counts
  # is your $PATH environment.
  # See http://stackoverflow.com/questions/26609922/maven-home-mvn-home-or-m2-home
  echo "export PATH=$MAVEN_HOME/bin:$PATH" >> ~/.bashrc
else
  # Do nothing if target installation directory already exists
  echo "'$MAVEN_HOME' already exists, please uninstall existing maven first."
fi

SELECT inside a COUNT

You don't really need a sub-select:

SELECT a, COUNT(*) AS b,
   SUM( CASE WHEN c = 'const' THEN 1 ELSE 0 END ) as d,
   from t group by a order by b desc

Static method in a generic class?

Something like the following would get you closer

class Clazz
{
   public static <U extends Clazz> void doIt(U thing)
   {
   }
}

EDIT: Updated example with more detail

public abstract class Thingo 
{

    public static <U extends Thingo> void doIt(U p_thingo)
    {
        p_thingo.thing();
    }

    protected abstract void thing();

}

class SubThingoOne extends Thingo
{
    @Override
    protected void thing() 
    {
        System.out.println("SubThingoOne");
    }
}

class SubThingoTwo extends Thingo
{

    @Override
    protected void thing() 
    {
        System.out.println("SuThingoTwo");
    }

}

public class ThingoTest 
{

    @Test
    public void test() 
    {
        Thingo t1 = new SubThingoOne();
        Thingo t2 = new SubThingoTwo();

        Thingo.doIt(t1);
        Thingo.doIt(t2);

        // compile error -->  Thingo.doIt(new Object());
    }
}

How can I detect the touch event of an UIImageView?

Add gesture on that view. Add an image into that view, and then it would be detecting a gesture on the image too. You could try with the delegate method of the touch event. Then in that case it also might be detecting.

How to update value of a key in dictionary in c#?

Have you tried just

dictionary["cat"] = 5;

:)

Update

dictionary["cat"] = 5+2;
dictionary["cat"] = dictionary["cat"]+2;
dictionary["cat"] += 2;

Beware of non-existing keys :)

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

how can select from drop down menu and call javascript function

<select name="aa" onchange="report(this.value)"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>
</select>

using

function report(period) {
  if (period=="") return; // please select - possibly you want something else here

  const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
  loadXMLDoc(report,'responseTag');
  document.getElementById('responseTag').style.visibility='visible';
  document.getElementById('list_report').style.visibility='hidden';
  document.getElementById('formTag').style.visibility='hidden'; 
} 

Unobtrusive version:

<select id="aa" name="aa"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>
</select>

using

window.addEventListener("load",function() {
  document.getElementById("aa").addEventListener("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
    loadXMLDoc(report,'responseTag');
    document.getElementById('responseTag').style.visibility='visible';
    document.getElementById('list_report').style.visibility='hidden';
    document.getElementById('formTag').style.visibility='hidden'; 
  }); 
});

jQuery version - same select with ID

$(function() {
  $("#aa").on("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
    loadXMLDoc(report,'responseTag');
    $('#responseTag').show();
    $('#list_report').hide();
    $('#formTag').hide(); 
  }); 
});

How to define an enumerated type (enum) in C?

When you say

enum {RANDOM, IMMEDIATE, SEARCH} strategy;

you create a single instance variable, called 'strategy' of a nameless enum. This is not a very useful thing to do - you need a typedef:

typedef enum {RANDOM, IMMEDIATE, SEARCH} StrategyType; 
StrategyType strategy = IMMEDIATE;

Collectors.toMap() keyMapper -- more succinct expression?

List<Person> roster = ...;

Map<String, Person> map = 
    roster
        .stream()
        .collect(
            Collectors.toMap(p -> p.getLast(), p -> p)
        );

that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)

clear data inside text file in c++

If you set the trunc flag.

#include<fstream>

using namespace std;

fstream ofs;

int main(){
ofs.open("test.txt", ios::out | ios::trunc);
ofs<<"Your content here";
ofs.close(); //Using microsoft incremental linker version 14
}

I tested this thouroughly for my own needs in a common programming situation I had. Definitely be sure to preform the ".close();" operation. If you don't do this there is no telling whether or not you you trunc or just app to the begging of the file. Depending on the file type you might just append over the file which depending on your needs may not fullfill its purpose. Be sure to call ".close();" explicity on the fstream you are trying to replace.

How do I keep two side-by-side divs the same height?

you can use jQuery to achieve this easily.

CSS

.left, .right {border:1px solid #cccccc;}

jQuery

$(document).ready(function() {
    var leftHeight = $('.left').height();
    $('.right').css({'height':leftHeight});
});

HTML

   <div class="left">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada, lacus eu dapibus tempus, ante odio aliquet risus, ac ornare orci velit in sapien. Duis suscipit sapien vel nunc scelerisque in pretium velit mattis. Cras vitae odio sed eros mollis malesuada et eu nunc.</p>
   </div>
   <div class="right">
    <p>Lorem ipsum dolor sit amet.</p>
   </div>

You'll need to include jQuery

how to count the spaces in a java string?

A solution using java.util.regex.Pattern / java.util.regex.Matcher

String test = "foo bar baz ";
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(test);
int count = 0;
while (matcher.find()) {
    count++;
}
System.out.println(count);

Android SeekBar setOnSeekBarChangeListener

Override all methods

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {


    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {


    }

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {


    }

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

Simply changing HTTP to HTTPS solved this issue for me.

WRONG :

<script src="http://code.jquery.com/jquery-3.5.1.js"></script>

CORRECT :

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>

BeautifulSoup Grab Visible Webpage Text

I completely respect using Beautiful Soup to get rendered content, but it may not be the ideal package for acquiring the rendered content on a page.

I had a similar problem to get rendered content, or the visible content in a typical browser. In particular I had many perhaps atypical cases to work with such a simple example below. In this case the non displayable tag is nested in a style tag, and is not visible in many browsers that I have checked. Other variations exist such as defining a class tag setting display to none. Then using this class for the div.

<html>
  <title>  Title here</title>

  <body>

    lots of text here <p> <br>
    <h1> even headings </h1>

    <style type="text/css"> 
        <div > this will not be visible </div> 
    </style>


  </body>

</html>

One solution posted above is:

html = Utilities.ReadFile('simple.html')
soup = BeautifulSoup.BeautifulSoup(html)
texts = soup.findAll(text=True)
visible_texts = filter(visible, texts)
print(visible_texts)


[u'\n', u'\n', u'\n\n        lots of text here ', u' ', u'\n', u' even headings ', u'\n', u' this will not be visible ', u'\n', u'\n']

This solution certainly has applications in many cases and does the job quite well generally but in the html posted above it retains the text that is not rendered. After searching SO a couple solutions came up here BeautifulSoup get_text does not strip all tags and JavaScript and here Rendered HTML to plain text using Python

I tried both these solutions: html2text and nltk.clean_html and was surprised by the timing results so thought they warranted an answer for posterity. Of course, the speeds highly depend on the contents of the data...

One answer here from @Helge was about using nltk of all things.

import nltk

%timeit nltk.clean_html(html)
was returning 153 us per loop

It worked really well to return a string with rendered html. This nltk module was faster than even html2text, though perhaps html2text is more robust.

betterHTML = html.decode(errors='ignore')
%timeit html2text.html2text(betterHTML)
%3.09 ms per loop

What regex will match every character except comma ',' or semi-colon ';'?

[^,;]+         

You haven't specified the regex implementation you are using. Most of them have a Split method that takes delimiters and split by them. You might want to use that one with a "normal" (without ^) character class:

[,;]+

In PHP, how can I add an object element to an array?

Here is a clean method I've discovered:

$myArray = [];

array_push($myArray, (object)[
        'key1' => 'someValue',
        'key2' => 'someValue2',
        'key3' => 'someValue3',
]);

return $myArray;

Laravel 5 Carbon format datetime

If you are using eloquent model (by looking at your code, i think you are), you dont need to convert it into array. Just use it as object. Becaus elike Thomas Kim said, by default it is a Carbon instance

So it should be

$suborder['payment_date'] = $item->created_at->format('Y-m-d')

But if it is not then, you need convert it to Carbon object as Milan Maharjan answer

$createdAt = Carbon::parse($item['created_at']);

JWT (JSON Web Token) automatic prolongation of expiration

Ref - Refresh Expired JWT Example

Another alternative is that once the JWT has expired, the user/system will make a call to another url suppose /refreshtoken. Also along with this request the expired JWT should be passed. The Server will then return a new JWT which can be used by the user/system.

enter image description here

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

scrollbars in JTextArea

            txtarea = new JTextArea(); 
    txtarea.setRows(25);
    txtarea.setColumns(25);
    txtarea.setWrapStyleWord(true);
    JScrollPane scroll = new JScrollPane (txtarea);
    panel2.add(scroll); //Object of Jpanel

Above given lines automatically shows you both horizontal & vertical Scrollbars..

Html.Raw() in ASP.NET MVC Razor view

You shouldn't be calling .ToString().

As the error message clearly states, you're writing a conditional in which one half is an IHtmlString and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.


There is never a reason to call Html.Raw(...).ToString().
Html.Raw returns an HtmlString instance that wraps the original string.
The Razor page output knows not to escape HtmlString instances.

However, calling HtmlString.ToString() just returns the original string value again; it doesn't accomplish anything.

LEFT function in Oracle

There is no documented LEFT() function in Oracle. Find the full set here.

Probably what you have is a user-defined function. You can check that easily enough by querying the data dictionary:

select * from all_objects
where object_name = 'LEFT'

But there is the question of why the stored procedure works and the query doesn't. One possible solution is that the stored procedure is owned by another schema, which also owns the LEFT() function. They have granted rights on the procedure but not its dependencies. This works because stored procedures run with DEFINER privileges by default, so you run the stored procedure as if you were its owner.

If this is so then the data dictionary query I listed above won't help you: it will only return rows for objects you have rights on. In which case you will need to run the query as the stored procedure's owner or connect as a user with the rights to query DBA_OBJECTS instead.

How to check if Receiver is registered in Android?

I am using this solution

_x000D_
_x000D_
public class ReceiverManager {
    private WeakReference<Context> cReference;
    private static List<BroadcastReceiver> receivers = new ArrayList<BroadcastReceiver>();
    private static ReceiverManager ref;

    private ReceiverManager(Context context) {
        cReference = new WeakReference<>(context);
    }

    public static synchronized ReceiverManager init(Context context) {
        if (ref == null) ref = new ReceiverManager(context);
        return ref;
    }

    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter intentFilter) {
        receivers.add(receiver);
        Intent intent = cReference.get().registerReceiver(receiver, intentFilter);
        Log.i(getClass().getSimpleName(), "registered receiver: " + receiver + "  with filter: " + intentFilter);
        Log.i(getClass().getSimpleName(), "receiver Intent: " + intent);
        return intent;
    }

    public boolean isReceiverRegistered(BroadcastReceiver receiver) {
        boolean registered = receivers.contains(receiver);
        Log.i(getClass().getSimpleName(), "is receiver " + receiver + " registered? " + registered);
        return registered;
    }

    public void unregisterReceiver(BroadcastReceiver receiver) {
        if (isReceiverRegistered(receiver)) {
            receivers.remove(receiver);
            cReference.get().unregisterReceiver(receiver);
            Log.i(getClass().getSimpleName(), "unregistered receiver: " + receiver);
        }
    }
}
_x000D_
_x000D_
_x000D_

Alternating Row Colors in Bootstrap 3 - No Table

There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type (or :nth-child -- either would work in this case.)

Smallest viewport:

@media (max-width:$smallest-breakpoint) {

  .row div {
     background: #eee;
   }

  .row div:nth-of-type(2n) {
     background: #fff;
   }

}

Medium viewport:

@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
    background: #fff;
  }

}

Largest viewport:

@media (min-width:$mid-breakpoint) and (max-width:9999px) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(6n+4), 
  .row div:nth-of-type(6n+5), 
  .row div:nth-of-type(6n+6) {
      background: #fff;
  }
}

Working fiddle here

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

byte[] strToByteArray(string str)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetBytes(str);
}

Hive query output to file

Enter this line into Hive command line interface:

insert overwrite directory '/data/test' row format delimited fields terminated by '\t' stored as textfile select * from testViewQuery;

testViewQuery - some specific view

How to assign string to bytes array

Arrays are values... slices are more like pointers. That is [n]type is not compatible with []type as they are fundamentally two different things. You can get a slice that points to an array by using arr[:] which returns a slice that has arr as it's backing storage.

One way to convert a slice of for example []byte to [20]byte is to actually allocate a [20]byte which you can do by using var [20]byte (as it's a value... no make needed) and then copy data into it:

buf := make([]byte, 10)
var arr [10]byte
copy(arr[:], buf)

Essentially what a lot of other answers get wrong is that []type is NOT an array.

[n]T and []T are completely different things!

When using reflect []T is not of kind Array but of kind Slice and [n]T is of kind Array.

You also can't use map[[]byte]T but you can use map[[n]byte]T.

This can sometimes be cumbersome because a lot of functions operate for example on []byte whereas some functions return [n]byte (most notably the hash functions in crypto/*). A sha256 hash for example is [32]byte and not []byte so when beginners try to write it to a file for example:

sum := sha256.Sum256(data)
w.Write(sum)

they will get an error. The correct way of is to use

w.Write(sum[:])

However, what is it that you want? Just accessing the string bytewise? You can easily convert a string to []byte using:

bytes := []byte(str)

but this isn't an array, it's a slice. Also, byte != rune. In case you want to operate on "characters" you need to use rune... not byte.

phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

This worked for me on Kali-linux 2018 :

apt-get install php7.0-mbstring

service apache2 restart

int *array = new int[n]; what is this function actually doing?

In C/C++, pointers and arrays are (almost) equivalent. int *a; a[0]; will return *a, and a[1]; will return *(a + 1)

But array can't change the pointer it points to while pointer can.

new int[n] will allocate some spaces for the "array"

How to declare string constants in JavaScript?

Well, you can do it like so:

(function() {
    var localByaka;
    Object.defineProperty(window, 'Byaka', {
        get: function() {
            return localByaka;
        },
        set: function(val) {
            localByaka = window.Byaka || val;
        }
    });
}());
window.Byaka = "foo"; //set constant
window.Byaka = "bar"; // try resetting it for shits and giggles
window.Byaka; // will allways return foo!

If you do this as above in global scope this will be a true constant, because you cannot overwrite the window object.

I've created a library to create constants and immutable objects in javascript. Its still version 0.2 but it does the trick nicely. http://beckafly.github.io/insulatejs

Why do I get access denied to data folder when using adb?

The problem could be that we need to specifically give adb root access in the developnent options in the latest CMs.. Here is what i did.

abc@abc-L655:~$ sudo adb kill-server
abc@abc-L655:~$ sudo adb root start-server * daemon not running. starting it now on port 5037 * * daemon started successfully * root access is disabled by system setting - enable in settings -> development options

after altering the development options...

abc@abc-L655:~$ sudo adb kill-server
abc@abc-L655:~$ sudo adb root start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
restarting adbd as root
abc@abc-L655:~$ adb shell
root@android:/ # ls /data/ .... good to go.. 

Read .csv file in C

A complete example which leaves the fields as NULL-terminated strings in the original input buffer and provides access to them via an array of char pointers. The CSV processor has been confirmed to work with fields enclosed in "double quotes", ignoring any delimiter chars within them.

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

// adjust BUFFER_SIZE to suit longest line 
#define BUFFER_SIZE 1024 * 1024
#define NUM_FIELDS 10
#define MAXERRS 5
#define RET_OK 0
#define RET_FAIL 1
#define FALSE 0
#define TRUE 1

// char* array will point to fields
char *pFields[NUM_FIELDS];
// field offsets into pFields array:
#define LP          0
#define IMIE        1
#define NAZWISKo    2
#define ULICA       3
#define NUMER       4
#define KOD         5
#define MIEJSCOw    6
#define TELEFON     7
#define EMAIL       8
#define DATA_UR     9

long loadFile(FILE *pFile, long *errcount);
static int  loadValues(char *line, long lineno);
static char delim;

long loadFile(FILE *pFile, long *errcount){

    char sInputBuf [BUFFER_SIZE];
    long lineno = 0L;

    if(pFile == NULL)
        return RET_FAIL;

    while (!feof(pFile)) {

        // load line into static buffer
        if(fgets(sInputBuf, BUFFER_SIZE-1, pFile)==NULL)
            break;

        // skip first line (headers)
        if(++lineno==1)
            continue;

        // jump over empty lines
        if(strlen(sInputBuf)==0)
            continue;
        // set pFields array pointers to null-terminated string fields in sInputBuf
        if(loadValues(sInputBuf,lineno)==RET_FAIL){
           (*errcount)++;
            if(*errcount > MAXERRS)
                break;
        } else {    
            // On return pFields array pointers point to loaded fields ready for load into DB or whatever
            // Fields can be accessed via pFields, e.g.
            printf("lp=%s, imie=%s, data_ur=%s\n", pFields[LP], pFields[IMIE], pFields[DATA_UR]);
        }
    }
    return lineno;
}


static int  loadValues(char *line, long lineno){
    if(line == NULL)
        return RET_FAIL;

    // chop of last char of input if it is a CR or LF (e.g.Windows file loading in Unix env.)
    // can be removed if sure fgets has removed both CR and LF from end of line
    if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1) == '\n')
        *(line + strlen(line)-1) = '\0';
    if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1 )== '\n')
        *(line + strlen(line)-1) = '\0';

    char *cptr = line;
    int fld = 0;
    int inquote = FALSE;
    char ch;

    pFields[fld]=cptr;
    while((ch=*cptr) != '\0' && fld < NUM_FIELDS){
        if(ch == '"') {
            if(! inquote)
                pFields[fld]=cptr+1;
            else {
                *cptr = '\0';               // zero out " and jump over it
            }
            inquote = ! inquote;
        } else if(ch == delim && ! inquote){
            *cptr = '\0';                   // end of field, null terminate it
            pFields[++fld]=cptr+1;
        }
        cptr++;
    }   
    if(fld > NUM_FIELDS-1){
        fprintf(stderr, "Expected field count (%d) exceeded on line %ld\n", NUM_FIELDS, lineno);
        return RET_FAIL;
    } else if (fld < NUM_FIELDS-1){
        fprintf(stderr, "Expected field count (%d) not reached on line %ld\n", NUM_FIELDS, lineno);
        return RET_FAIL;    
    }
    return RET_OK;
}

int main(int argc, char **argv)
{
   FILE *fp;
   long errcount = 0L;
   long lines = 0L;

   if(argc!=3){
       printf("Usage: %s csvfilepath delimiter\n", basename(argv[0]));
       return (RET_FAIL);
   }   
   if((delim=argv[2][0])=='\0'){
       fprintf(stderr,"delimiter must be specified\n");
       return (RET_FAIL);
   }
   fp = fopen(argv[1] , "r");
   if(fp == NULL) {
      fprintf(stderr,"Error opening file: %d\n",errno);
      return(RET_FAIL);
   }
   lines=loadFile(fp,&errcount);
   fclose(fp);
   printf("Processed %ld lines, encountered %ld error(s)\n", lines, errcount);
   if(errcount>0)
        return(RET_FAIL);
    return(RET_OK); 
}

How can I remove the decimal part from JavaScript number?

For an ES6 implementation, use something like the following:

const millisToMinutesAndSeconds = (millis) => {
  const minutes = Math.floor(millis / 60000);
  const seconds = ((millis % 60000) / 1000).toFixed(0);
  return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
}

SELECT INTO using Oracle

Use:

create table new_table_name 
as
select column_name,[more columns] from Existed_table;

Example:

create table dept
as
select empno, ename from emp;

If the table already exists:

insert into new_tablename select columns_list from Existed_table;

Get month and year from date cells Excel

I had a requirement to provide a report showing details by month where the date field was formatted as date & time, I simply changed the formatting of the date column to "General" and then used the following formula in a new column,

=CONCATENATE(YEAR(C2),MONTH(C2)) 

How to convert Windows end of line in Unix end of line (CR/LF to LF)

Did you try the python script by Bryan Maupin found here ? (I've modified it a little bit to be more generic)

#!/usr/bin/env python

import sys

input_file_name = sys.argv[1]
output_file_name = sys.argv[2]

input_file = open(input_file_name)
output_file = open(output_file_name, 'w')

line_number = 0

for input_line in input_file:
    line_number += 1
    try:  # first try to decode it using cp1252 (Windows, Western Europe)
        output_line = input_line.decode('cp1252').encode('utf8')
    except UnicodeDecodeError, error:  # if there's an error
        sys.stderr.write('ERROR (line %s):\t%s\n' % (line_number, error))  # write to stderr
        try:  # then if that fails, try to decode using latin1 (ISO 8859-1)         
            output_line = input_line.decode('latin1').encode('utf8')
        except UnicodeDecodeError, error:  # if there's an error
            sys.stderr.write('ERROR (line %s):\t%s\n' % (line_number, error))  # write to stderr
            sys.exit(1)  # and just keep going
    output_file.write(output_line)

input_file.close()
output_file.close()

You can use that script with

$ ./cp1252_utf8.py file_cp1252.sql file_utf8.sql

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

Question 3: Can you offer me some hints how to optimize these implementations without changing the way I determine the factors? Optimization in any way: nicer, faster, more "native" to the language.

The C implementation is suboptimal (as hinted at by Thomas M. DuBuisson), the version uses 64-bit integers (i.e. long datatype). I'll investigate the assembly listing later, but with an educated guess, there are some memory accesses going on in the compiled code, which make using 64-bit integers significantly slower. It's that or generated code (be it the fact that you can fit less 64-bit ints in a SSE register or round a double to a 64-bit integer is slower).

Here is the modified code (simply replace long with int and I explicitly inlined factorCount, although I do not think that this is necessary with gcc -O3):

#include <stdio.h>
#include <math.h>

static inline int factorCount(int n)
{
    double square = sqrt (n);
    int isquare = (int)square;
    int count = isquare == square ? -1 : 0;
    int candidate;
    for (candidate = 1; candidate <= isquare; candidate ++)
        if (0 == n % candidate) count += 2;
    return count;
}

int main ()
{
    int triangle = 1;
    int index = 1;
    while (factorCount (triangle) < 1001)
    {
        index++;
        triangle += index;
    }
    printf ("%d\n", triangle);
}

Running + timing it gives:

$ gcc -O3 -lm -o euler12 euler12.c; time ./euler12
842161320
./euler12  2.95s user 0.00s system 99% cpu 2.956 total

For reference, the haskell implementation by Thomas in the earlier answer gives:

$ ghc -O2 -fllvm -fforce-recomp euler12.hs; time ./euler12                                                                                      [9:40]
[1 of 1] Compiling Main             ( euler12.hs, euler12.o )
Linking euler12 ...
842161320
./euler12  9.43s user 0.13s system 99% cpu 9.602 total

Conclusion: Taking nothing away from ghc, its a great compiler, but gcc normally generates faster code.

Dictionary of dictionaries in Python?

Using collections.defaultdict is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.

Here it's used twice: for the resulting dict, and for each of the values in the dict.

import collections

def aggregate_names(errors):
    result = collections.defaultdict(lambda: collections.defaultdict(list))
    for real_name, false_name, location in errors:
        result[real_name][false_name].append(location)
    return result

Combining this with your code:

dictionary = aggregate_names(previousFunction(string))

Or to test:

EXAMPLES = [
    ('Fred', 'Frad', 123),
    ('Jim', 'Jam', 100),
    ('Fred', 'Frod', 200),
    ('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)

Fast check for NaN in NumPy

There are two general approaches here:

  • Check each array item for nan and take any.
  • Apply some cumulative operation that preserves nans (like sum) and check its result.

While the first approach is certainly the cleanest, the heavy optimization of some of the cumulative operations (particularly the ones that are executed in BLAS, like dot) can make those quite fast. Note that dot, like some other BLAS operations, are multithreaded under certain conditions. This explains the difference in speed between different machines.

enter image description here

import numpy
import perfplot


def min(a):
    return numpy.isnan(numpy.min(a))


def sum(a):
    return numpy.isnan(numpy.sum(a))


def dot(a):
    return numpy.isnan(numpy.dot(a, a))


def any(a):
    return numpy.any(numpy.isnan(a))


def einsum(a):
    return numpy.isnan(numpy.einsum("i->", a))


perfplot.show(
    setup=lambda n: numpy.random.rand(n),
    kernels=[min, sum, dot, any, einsum],
    n_range=[2 ** k for k in range(20)],
    logx=True,
    logy=True,
    xlabel="len(a)",
)

How to update data in one table from corresponding data in another table in SQL Server 2005

use test1

insert into employee(deptid) select deptid from test2.dbo.employee

Convert InputStream to JSONObject

Since you're already using Google's Json-Simple library, you can parse the json from an InputStream like this:

InputStream inputStream = ... //Read from a file, or a HttpRequest, or whatever.
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(
      new InputStreamReader(inputStream, "UTF-8"));

What is the list of supported languages/locales on Android?

If you're using Android Studio you can:

  1. Right click a directory on your project > New > Android Resource File
  2. In the Available qualifiers section select Locale and click >>

You will see a list of all Languages and if you choose them you will see Specific Regions for each. You can also type in the list to filter languages.

enter image description here

enter image description here

enter image description here

check output from CalledProcessError

In the list of arguments, each entry must be on its own. Using

output = subprocess.check_output(["ping", "-c","2", "-W","2", "1.1.1.1"])

should fix your problem.

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

How to find the array index with a value?

Array.indexOf doesnt work in some versions of internet explorer - there are lots of alternative ways of doing it though ... see this question / answer : How do I check if an array includes an object in JavaScript?

How to deal with ModalDialog using selenium webdriver?

Use

following methods to switch to modelframe

driver.switchTo().frame("ModelFrameTitle");

or

driver.switchTo().activeElement()

Hope this will work

Get latest from Git branch

Your modifications are in a different branch than the original branch, which simplifies stuff because you get updates in one branch, and your work is in another branch.

Assuming the original branch is named master, which the case in 99% of git repos, you have to fetch the state of origin, and merge origin/master updates into your local master:

 git fetch origin
 git checkout master
 git merge origin/master

To switch to your branch, just do

 git checkout branch1

How do I pass a variable to the layout using Laravel' Blade templating?

For future Google'rs that use Laravel 5, you can now also use it with includes,

@include('views.otherView', ['variable' => 1])

Decimal number regular expression, where digit after decimal is optional

try this. ^[0-9]\d{0,9}(\.\d{1,3})?%?$ it is tested and worked for me.

HTML display result in text (input) field?

Do you really want the result to come up in an input box? If not, consider a table with borders set to other than transparent and use

document.getElementById('sum').innerHTML = sum;

Get element of JS object with an index

var myobj = {"A":["Abe"], "B":["Bob"]};

var keysArray = Object.keys(myobj);

var valuesArray = Object.keys(myobj).map(function(k) {

   return String(myobj[k]);

});

var mydata = valuesArray[keysArray.indexOf("A")]; // Abe

How to use CMAKE_INSTALL_PREFIX

That should be (see the docs):

cmake -DCMAKE_INSTALL_PREFIX=/usr ..

Waiting on a list of Future

You can use a CompletionService to receive the futures as soon as they are ready and if one of them throws an exception cancel the processing. Something like this:

Executor executor = Executors.newFixedThreadPool(4);
CompletionService<SomeResult> completionService = 
       new ExecutorCompletionService<SomeResult>(executor);

//4 tasks
for(int i = 0; i < 4; i++) {
   completionService.submit(new Callable<SomeResult>() {
       public SomeResult call() {
           ...
           return result;
       }
   });
}

int received = 0;
boolean errors = false;

while(received < 4 && !errors) {
      Future<SomeResult> resultFuture = completionService.take(); //blocks if none available
      try {
         SomeResult result = resultFuture.get();
         received ++;
         ... // do something with the result
      }
      catch(Exception e) {
             //log
         errors = true;
      }
}

I think you can further improve to cancel any still executing tasks if one of them throws an error.

C++ "Access violation reading location" Error

Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

Because findVertex can return NULL if it can't find the vertex.

Otherwise this f->adj; is trying to do

NULL->adj;

Which causes access violation.

what is the size of an enum type data in C++?

I like the explanation From EdX (Microsoft: DEV210x Introduction to C++) for a similar problem:

"The enum represents the literal values of days as integers. Referring to the numeric types table, you see that an int takes 4 bytes of memory. 7 days x 4 bytes each would require 28 bytes of memory if the entire enum were stored but the compiler only uses a single element of the enum, therefore the size in memory is actually 4 bytes."

How to center a <p> element inside a <div> container?

This solution works fine for all major browsers, except IE. So keep that in mind.

In this example, basicaly I use positioning, horizontal and vertical transform for the UI element to center it.

_x000D_
_x000D_
        .container {_x000D_
            /* set the the position to relative */_x000D_
            position: relative;_x000D_
            width: 30rem;_x000D_
            height: 20rem;_x000D_
            background-color: #2196F3;_x000D_
        }_x000D_
_x000D_
_x000D_
        .paragh {_x000D_
            /* set the the position to absolute */_x000D_
            position: absolute;_x000D_
            /* set the the position of the helper container into the middle of its space */_x000D_
            top: 50%;_x000D_
            left: 50%;_x000D_
            font-size: 30px;_x000D_
            /* make sure padding and margin do not disturb the calculation of the center point */_x000D_
            padding: 0;_x000D_
            margin: 0;_x000D_
            /* using centers for the transform */_x000D_
            transform-origin: center center;_x000D_
            /* calling calc() function for the calculation to move left and up the element from the center point */_x000D_
            transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1)));_x000D_
        }
_x000D_
<div class="container">_x000D_
    <p class="paragh">Text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I hope this help.

How do I add more members to my ENUM-type column in MySQL?

The discussion I had with Asaph may be unclear to follow as we went back and forth quite a bit.

I thought that I might clarify the upshot of our discourse for others who might face similar situations in the future to benefit from:

ENUM-type columns are very difficult beasts to manipulate. I wanted to add two countries (Malaysia & Sweden) to the existing set of countries in my ENUM.

It seems that MySQL 5.1 (which is what I am running) can only update the ENUM by redefining the existing set in addition to what I want:

This did not work:

ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia') DEFAULT NULL;

The reason was that the MySQL statement was replacing the existing ENUM with another containing the entries 'Malaysia' and 'Sweden' only. MySQL threw up an error because the carmake table already had values like 'England' and 'USA' which were not part of the new ENUM's definition.

Surprisingly, the following did not work either:

ALTER TABLE carmake CHANGE country country ENUM('Australia','England','USA'...'Sweden','Malaysia') DEFAULT NULL;

It turns out that even the order of elements of the existing ENUM needs to be preserved while adding new members to it. So if my existing ENUM looks something like ENUM('England','USA'), then my new ENUM has to be defined as ENUM('England','USA','Sweden','Malaysia') and not ENUM('USA','England','Sweden','Malaysia'). This problem only becomes manifest when there are records in the existing table that use 'USA' or 'England' values.

BOTTOM LINE:

Only use ENUMs when you do not expect your set of members to change once defined. Otherwise, lookup tables are much easier to update and modify.

How to initialize an array of custom objects

Use a "Here-String" and cast to XML.

[xml]$myxml = @"
<stuff>
 <item name="Joe" age="32">
  <info>something about him</info>
 </item>
 <item name="Sue" age="29">
  <info>something about her</info>
 </item>
 <item name="Cat" age="12">
  <info>something else</info>
 </item>
</stuff>
"@

[array]$myitems = $myxml.stuff.Item

$myitems

Pandas dataframe fillna() only some columns in place

You can avoid making a copy of the object using Wen's solution and inplace=True:

df.fillna({'a':0, 'b':0}, inplace=True)
print(df)

Which yields:

     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0