Programs & Examples On #Rendertransform

How to add a vertical Separator?

From http://social.msdn.microsoft.com/Forums/vstudio/en-US/12ead5d4-1d57-4dbb-ba81-bc13084ba370/how-can-i-add-a-line-as-a-visual-separator-to-the-content-control-like-grid?forum=wpf:

Try this example and see if it fits your needs, there are three main aspects to it.

  1. Line.Stretch is set to fill.

  2. For horizontal lines the VerticalAlignment of the line is set Bottom, and for VerticalLines the HorizontalAlignment is set to Right.

  3. We then need to tell the line how many rows or columns to span, this is done by binding to either RowDefinitions or ColumnDefintions count property.



        <Style x:Key="horizontalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">  
            <Setter Property="X2" Value="1" /> 
            <Setter Property="VerticalAlignment" Value="Bottom" /> 
            <Setter Property="Grid.ColumnSpan" 
                    Value="{Binding   
                                Path=ColumnDefinitions.Count,  
                                RelativeSource={RelativeSource AncestorType=Grid}}"/> 
        </Style> 
    
        <Style x:Key="verticalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">  
            <Setter Property="Y2" Value="1" /> 
            <Setter Property="HorizontalAlignment" Value="Right" /> 
            <Setter Property="Grid.RowSpan"   
                    Value="{Binding   
                                Path=RowDefinitions.Count,  
                                RelativeSource={RelativeSource AncestorType=Grid}}"/> 
        </Style> 
    </Grid.Resources>        
    
    <Grid.RowDefinitions> 
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
    </Grid.RowDefinitions> 
    
    <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
    </Grid.ColumnDefinitions> 
    
    <Line Grid.Column="0" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="1" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="2" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="3" Style="{StaticResource verticalLineStyle}"/>  
    
    <Line Grid.Row="0" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="1" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="2" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="3" Style="{StaticResource horizontalLineStyle}"/>  
    

Ignore files that have already been committed to a Git repository

Remove trailing whitespace in .gitignore

Also, make sure you have no trailing whitespace in your .gitignore. I got to this question because I was searching for an answer, then I had a funny feeling I should open the editor instead of just cat'ing .gitignore. Removed a single extra space from the end and poof it works now :)

Java 8 List<V> into Map<K, V>

As an alternative to guava one can use kotlin-stdlib

private Map<String, Choice> nameMap(List<Choice> choices) {
    return CollectionsKt.associateBy(choices, Choice::getName);
}

What's the proper way to "go get" a private repository?

You have one thing to configure. The example is based on GitHub but this shouldn't change the process:

$ git config --global [email protected]:.insteadOf https://github.com/
$ cat ~/.gitconfig
[url "[email protected]:"]
    insteadOf = https://github.com/
$ go get github.com/private/repo

For Go modules to work (with Go 1.11 or newer), you'll also need to set the GOPRIVATE variable, to avoid using the public servers to fetch the code:

export GOPRIVATE=github.com/private/repo

Parsing ISO 8601 date in Javascript

Maybe, you can use moment.js which in my opinion is the best JavaScript library for parsing, formatting and working with dates client-side. You could use something like:

_x000D_
_x000D_
var momentDate = moment('1890-09-30T23:59:59+01:16:20', 'YYYY-MM-DDTHH:mm:ss+-HH:mm:ss');_x000D_
var jsDate = momentDate.toDate();_x000D_
_x000D_
// Now, you can run any JavaScript Date method_x000D_
_x000D_
jsDate.toLocaleString();
_x000D_
_x000D_
_x000D_

The advantage of using a library like moment.js is that your code will work perfectly even in legacy browsers like IE 8+.

Here is the documenation about parsing methods: https://momentjs.com/docs/#/parsing/

Fragment transaction animation: slide in and slide out

This is another solution which I use:

public class CustomAnimator {
    private static final String TAG = "com.example.CustomAnimator";

    private static Stack<AnimationEntry> animation_stack    = new Stack<>();

    public static final int                 DIRECTION_LEFT  = 1;
    public static final int                 DIRECTION_RIGHT = -1;
    public static final int                 DIRECTION_UP    = 2;
    public static final int                 DIRECTION_DOWN  = -2;

    static class AnimationEntry {
        View in;
        View    out;
        int     direction;
        long    duration;
    }

    public static boolean hasHistory() {
        return !animation_stack.empty();
    }

    public static void reversePrevious() {
        if (!animation_stack.empty()) {
            AnimationEntry entry = animation_stack.pop();
            slide(entry.out, entry.in, -entry.direction, entry.duration, false);
        }
    }

    public static void clearHistory() {
        animation_stack.clear();
    }

    public static void slide(final View in, View out, final int direction, long duration) {
        slide(in, out, direction, duration, true);
    }

    private static void slide(final View in, final View out, final int direction, final long duration, final boolean save) {

        ViewGroup in_parent = (ViewGroup) in.getParent();
        ViewGroup out_parent = (ViewGroup) out.getParent();

        if (!in_parent.equals(out_parent)) {
            return;
        }

        int parent_width = in_parent.getWidth();
        int parent_height = in_parent.getHeight();

        ObjectAnimator slide_out;
        ObjectAnimator slide_in;

        switch (direction) {
            case DIRECTION_LEFT:
            default:
                slide_in = ObjectAnimator.ofFloat(in, "translationX", parent_width, 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, -out.getWidth());
                break;
            case DIRECTION_RIGHT:
                slide_in = ObjectAnimator.ofFloat(in, "translationX", -out.getWidth(), 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, parent_width);
                break;
            case DIRECTION_UP:
                slide_in = ObjectAnimator.ofFloat(in, "translationY", parent_height, 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, -out.getHeight());
                break;
            case DIRECTION_DOWN:
                slide_in = ObjectAnimator.ofFloat(in, "translationY", -out.getHeight(), 0);
                slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, parent_height);
                break;
        }

        AnimatorSet animations = new AnimatorSet();
        animations.setDuration(duration);
        animations.playTogether(slide_in, slide_out);
        animations.addListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationCancel(Animator arg0) {
            }

            @Override
            public void onAnimationEnd(Animator arg0) {
                out.setVisibility(View.INVISIBLE);
                if (save) {
                    AnimationEntry ae = new AnimationEntry();
                    ae.in = in;
                    ae.out = out;
                    ae.direction = direction;
                    ae.duration = duration;
                    animation_stack.push(ae);
                }
            }

            @Override
            public void onAnimationRepeat(Animator arg0) {
            }

            @Override
            public void onAnimationStart(Animator arg0) {
                in.setVisibility(View.VISIBLE);
            }
        });
        animations.start();
    }
}

The usage of class. Let's say you have two fragments (list and details fragments)as shown below

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ui_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/list_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <FrameLayout
        android:id="@+id/details_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />
</FrameLayout>

Usage

View details_container = findViewById(R.id.details_container);
View list_container = findViewById(R.id.list_container);
// You can select the direction left/right/up/down and the duration
CustomAnimator.slide(list_container, details_container,CustomAnimator.DIRECTION_LEFT, 400);

You can use the function CustomAnimator.reversePrevious();to get the previous view when the user pressed back.

How to tell if UIViewController's view is visible

I found those function in UIViewController.h.

/*
  These four methods can be used in a view controller's appearance callbacks to determine if it is being
  presented, dismissed, or added or removed as a child view controller. For example, a view controller can
  check if it is disappearing because it was dismissed or popped by asking itself in its viewWillDisappear:
  method by checking the expression ([self isBeingDismissed] || [self isMovingFromParentViewController]).
*/

- (BOOL)isBeingPresented NS_AVAILABLE_IOS(5_0);
- (BOOL)isBeingDismissed NS_AVAILABLE_IOS(5_0);

- (BOOL)isMovingToParentViewController NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingFromParentViewController NS_AVAILABLE_IOS(5_0);

Maybe the above functions can detect the ViewController is appeared or not.

How to use jQuery in chrome extension?

In my case got a working solution through Cross-document Messaging (XDM) and Executing Chrome extension onclick instead of page load.

manifest.json

{
  "name": "JQuery Light",
  "version": "1",
  "manifest_version": 2,

  "browser_action": {
    "default_icon": "icon.png"
  },

  "content_scripts": [
    {
      "matches": [
        "https://*.google.com/*"
      ],
      "js": [
        "jquery-3.3.1.min.js",
        "myscript.js"
      ]
    }
  ],

  "background": {
    "scripts": [
      "background.js"
    ]
  }

}

background.js

chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "clicked_browser_action"});
  });
});

myscript.js

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.message === "clicked_browser_action") {
        console.log('Hello world!')
        }
    }
);

How do I make a list of data frames?

You can also access specific columns and values in each list element with [ and [[. Here are a couple of examples. First, we can access only the first column of each data frame in the list with lapply(ldf, "[", 1), where 1 signifies the column number.

ldf <- list(d1 = d1, d2 = d2)  ## create a named list of your data frames
lapply(ldf, "[", 1)
# $d1
#   y1
# 1  1
# 2  2
# 3  3
#
# $d2
#   y1
# 1  3
# 2  2
# 3  1

Similarly, we can access the first value in the second column with

lapply(ldf, "[", 1, 2)
# $d1
# [1] 4
# 
# $d2
# [1] 6

Then we can also access the column values directly, as a vector, with [[

lapply(ldf, "[[", 1)
# $d1
# [1] 1 2 3
#
# $d2
# [1] 3 2 1

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

Bypass invalid SSL certificate errors when calling web services in .Net

For newbies, you can extend your partial service class in a separate cs file and add the code the code provided by "imanabidi" to get it integrated

How do I check that a number is float or integer?

As others mentioned, you only have doubles in JS. So how do you define a number being an integer? Just check if the rounded number is equal to itself:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }

Word wrap for a label in Windows Forms

I would recommend setting AutoEllipsis property of label to true and AutoSize to false. If text length exceeds label bounds, it'll add three dots (...) at the end and automatically set the complete text as a tooltip. So users can see the complete text by hovering over the label.

How to find sum of several integers input by user using do/while, While statement or For statement

A simple program shows how to use for loop to find sum of serveral integers.

#include <iostream>    
using namespace std;

int main ()
{
    int sum = 0;

    int endnum = 2;

    for(int i = 0; i<=endnum; i++){
        sum += i;
    }
    cout<<sum;
}

Setting environment variables on OS X

It's simple:

Edit ~/.profile and put your variables as follow

$ vim ~/.profile

In file put:

MY_ENV_VAR=value

  1. Save ( :wq )

  2. Restart the terminal (Quit and open it again)

  3. Make sure that`s all be fine:

$ echo $MY_ENV_VAR

$ value


How to reset the use/password of jenkins on windows?

Read Initial password :

C:\Program Files(x86)\Jenkins\secrets\initialAdminPassword

Default username is 'admin' and the password is the one from initialAdminPassword when you follow the above path.

'Manage Jenkins' --> 'Manage Users' --> Password

Then logout and login to make sure new password works.

SyntaxError: expected expression, got '<'

This should work for you. If you are using SPA.

app.use('/', express.static(path.join(__dirname, 'your folder')));
// Send all other requests to the SPA
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'your folder/index.html'));
});

How can I format DateTime to web UTC format?

string.Format("{0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow)

returns 2017-02-10T08:12:39.483Z

Procedure expects parameter which was not supplied

I come across similar problem while calling stored procedure

CREATE PROCEDURE UserPreference_Search
    @UserPreferencesId int,
    @SpecialOfferMails char(1),
    @NewsLetters char(1),
    @UserLoginId int,
    @Currency varchar(50)
AS
DECLARE @QueryString nvarchar(4000)

SET @QueryString = 'SELECT UserPreferencesId,SpecialOfferMails,NewsLetters,UserLoginId,Currency FROM UserPreference'
IF(@UserPreferencesId IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE UserPreferencesId = @DummyUserPreferencesId';
END

IF(@SpecialOfferMails IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE SpecialOfferMails = @DummySpecialOfferMails';
END

IF(@NewsLetters IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE NewsLetters = @DummyNewsLetters';
END

IF(@UserLoginId IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE UserLoginId = @DummyUserLoginId';
END

IF(@Currency IS NOT NULL)
BEGIN
SET @QueryString = @QueryString + ' WHERE Currency = @DummyCurrency';
END

EXECUTE SP_EXECUTESQL @QueryString
                     ,N'@DummyUserPreferencesId int, @DummySpecialOfferMails char(1), @DummyNewsLetters char(1), @DummyUserLoginId int, @DummyCurrency varchar(50)'
                     ,@DummyUserPreferencesId=@UserPreferencesId
                     ,@DummySpecialOfferMails=@SpecialOfferMails
                     ,@DummyNewsLetters=@NewsLetters
                     ,@DummyUserLoginId=@UserLoginId
                     ,@DummyCurrency=@Currency;

Which dynamically constructing the query for search I was calling above one by:

public DataSet Search(int? AccessRightId, int? RoleId, int? ModuleId, char? CanAdd, char? CanEdit, char? CanDelete, DateTime? CreatedDatetime, DateTime? LastAccessDatetime, char? Deleted)
    {
        dbManager.ConnectionString = ConfigurationManager.ConnectionStrings["MSSQL"].ToString();
        DataSet ds = new DataSet();
        try
        {
            dbManager.Open();
            dbManager.CreateParameters(9);
            dbManager.AddParameters(0, "@AccessRightId", AccessRightId, ParameterDirection.Input);
            dbManager.AddParameters(1, "@RoleId", RoleId, ParameterDirection.Input);
            dbManager.AddParameters(2, "@ModuleId", ModuleId, ParameterDirection.Input);
            dbManager.AddParameters(3, "@CanAdd", CanAdd, ParameterDirection.Input);
            dbManager.AddParameters(4, "@CanEdit", CanEdit, ParameterDirection.Input);
            dbManager.AddParameters(5, "@CanDelete", CanDelete, ParameterDirection.Input);
            dbManager.AddParameters(6, "@CreatedDatetime", CreatedDatetime, ParameterDirection.Input);
            dbManager.AddParameters(7, "@LastAccessDatetime", LastAccessDatetime, ParameterDirection.Input);
            dbManager.AddParameters(8, "@Deleted", Deleted, ParameterDirection.Input);
            ds = dbManager.ExecuteDataSet(CommandType.StoredProcedure, "AccessRight_Search");
            return ds;
        }
        catch (Exception ex)
        {
        }
        finally
        {
            dbManager.Dispose();
        }
        return ds;
    }

Then after lot of head scratching I modified stored procedure to:

ALTER PROCEDURE [dbo].[AccessRight_Search]
    @AccessRightId int=null,
    @RoleId int=null,
    @ModuleId int=null,
    @CanAdd char(1)=null,
    @CanEdit char(1)=null,
    @CanDelete char(1)=null,
    @CreatedDatetime datetime=null,
    @LastAccessDatetime datetime=null,
    @Deleted char(1)=null
AS
DECLARE @QueryString nvarchar(4000)
DECLARE @HasWhere bit
SET @HasWhere=0

SET @QueryString = 'SELECT a.AccessRightId, a.RoleId,a.ModuleId, a.CanAdd, a.CanEdit, a.CanDelete, a.CreatedDatetime, a.LastAccessDatetime, a.Deleted, b.RoleName, c.ModuleName FROM AccessRight a, Role b, Module c WHERE a.RoleId = b.RoleId AND a.ModuleId = c.ModuleId'

SET @HasWhere=1;

IF(@AccessRightId IS NOT NULL)
    BEGIN
        IF(@HasWhere=0) 
            BEGIN
                SET @QueryString = @QueryString + ' WHERE a.AccessRightId = @DummyAccessRightId';
                SET @HasWhere=1;
            END
        ELSE                SET @QueryString = @QueryString + ' AND a.AccessRightId = @DummyAccessRightId';
    END

IF(@RoleId IS NOT NULL)
    BEGIN
        IF(@HasWhere=0)
            BEGIN   
                SET @QueryString = @QueryString + ' WHERE a.RoleId = @DummyRoleId';
                SET @HasWhere=1;
            END
        ELSE            SET @QueryString = @QueryString + ' AND a.RoleId = @DummyRoleId';
    END

IF(@ModuleId IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
            BEGIN   
                SET @QueryString = @QueryString + ' WHERE a.ModuleId = @DummyModuleId';
                SET @HasWhere=1;
            END
    ELSE SET @QueryString = @QueryString + ' AND a.ModuleId = @DummyModuleId';
END

IF(@CanAdd IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
            BEGIN       
                SET @QueryString = @QueryString + ' WHERE a.CanAdd = @DummyCanAdd';
                SET @HasWhere=1;
            END
    ELSE SET @QueryString = @QueryString + ' AND a.CanAdd = @DummyCanAdd';
END

IF(@CanEdit IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
        BEGIN
            SET @QueryString = @QueryString + ' WHERE a.CanEdit = @DummyCanEdit';
            SET @HasWhere=1;
        END
    ELSE SET @QueryString = @QueryString + ' AND a.CanEdit = @DummyCanEdit';
END

IF(@CanDelete IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
        BEGIN
            SET @QueryString = @QueryString + ' WHERE a.CanDelete = @DummyCanDelete';
            SET @HasWhere=1;
        END
    ELSE SET @QueryString = @QueryString + ' AND a.CanDelete = @DummyCanDelete';
END

IF(@CreatedDatetime IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
    BEGIN
        SET @QueryString = @QueryString + ' WHERE a.CreatedDatetime = @DummyCreatedDatetime';
        SET @HasWhere=1;
    END
    ELSE SET @QueryString = @QueryString + ' AND a.CreatedDatetime = @DummyCreatedDatetime';
END

IF(@LastAccessDatetime IS NOT NULL)
BEGIN
    IF(@HasWhere=0) 
        BEGIN
            SET @QueryString = @QueryString + ' WHERE a.LastAccessDatetime = @DummyLastAccessDatetime';
            SET @HasWhere=1;
        END
    ELSE SET @QueryString = @QueryString + ' AND a.LastAccessDatetime = @DummyLastAccessDatetime';
END

IF(@Deleted IS NOT NULL)
BEGIN
  IF(@HasWhere=0)   
    BEGIN
        SET @QueryString = @QueryString + ' WHERE a.Deleted = @DummyDeleted';
        SET @HasWhere=1;
    END
  ELSE SET @QueryString = @QueryString + ' AND a.Deleted = @DummyDeleted';
END

PRINT @QueryString

EXECUTE SP_EXECUTESQL @QueryString
                      ,N'@DummyAccessRightId int, @DummyRoleId int, @DummyModuleId int, @DummyCanAdd char(1), @DummyCanEdit char(1), @DummyCanDelete char(1), @DummyCreatedDatetime datetime, @DummyLastAccessDatetime datetime, @DummyDeleted char(1)'
                      ,@DummyAccessRightId=@AccessRightId
                      ,@DummyRoleId=@RoleId
                      ,@DummyModuleId=@ModuleId
                      ,@DummyCanAdd=@CanAdd
                      ,@DummyCanEdit=@CanEdit
                      ,@DummyCanDelete=@CanDelete
                      ,@DummyCreatedDatetime=@CreatedDatetime
                      ,@DummyLastAccessDatetime=@LastAccessDatetime
                      ,@DummyDeleted=@Deleted;

HERE I am Initializing the Input Params of Stored Procedure to null as Follows

    @AccessRightId int=null,
@RoleId int=null,
@ModuleId int=null,
@CanAdd char(1)=null,
@CanEdit char(1)=null,
@CanDelete char(1)=null,
@CreatedDatetime datetime=null,
@LastAccessDatetime datetime=null,
@Deleted char(1)=null

that did the trick for Me.

I hope this will be helpfull to someone who fall in similar trap.

How to create websockets server in PHP

As far as I'm aware Ratchet is the best PHP WebSocket solution available at the moment. And since it's open source you can see how the author has built this WebSocket solution using PHP.

When using SASS how can I import a file from a different directory?

I ran into the same problem. From my solution i came into this. So here is your code:

- root_directory
    - sub_directory_a
        - _common.scss
        - template.scss
    - sub_directory_b
        - more_styles.scss

As far i know if you want to import one scss to another its has to be a partial. When you are importing from different directory name your more_styles.scss to _more_styles.scss. Then import it into your template.scss like this @import ../sub_directory_b/_more_styles.scss. It worked for me. But as you mentioned ../sub_directory_a/_common.scss not working. That's the same directory of the template.scss. That is why it wont work.

How do I install Python packages on Windows?

As mentioned by Blauhirn after 2.7 pip is preinstalled. If it is not working for you it might need to be added to path.

However if you run Windows 10 you no longer have to open a terminal to install a module. The same goes for opening Python as well.

You can type directly into the search menu pip install mechanize, select command and it will install:

enter image description here

If anything goes wrong however it may close before you can read the error but still it's a useful shortcut.

How do I clone a subdirectory only of a Git repository?

Just to clarify some of the great answers here, the steps outlined in many of the answers assume that you already have a remote repository somewhere.

Given: an existing git repository, e.g. [email protected]:some-user/full-repo.git, with one or more directories that you wish to pull independently of the rest of the repo, e.g. directories named app1 and app2

Assuming you have a git repository as the above...

Then: you can run steps like the following to pull only specific directories from that larger repo:

mkdir app1
cd app1
git init
git remote add origin [email protected]:some-user/full-repo.git
git config core.sparsecheckout true
echo "app1/" >> .git/info/sparse-checkout
git pull origin master

I had mistakenly thought that the sparse-checkout options had to be set on the original repository, but this is not the case: you define which directories you want locally, prior to pulling from the remote. The remote repo doesn't know or care about your only wanting to track a part of the repo.

Hope this clarification helps someone else.

regular expression for DOT

...

[.]{1}

or

[.]{2}

?

Get the system date and split day, month and year

Without opening an IDE to check my brain works properly for syntax at this time of day...

If you simply want the date in a particular format you can use DateTime's .ToString(string format). There are a number of examples of standard and custom formatting strings if you follow that link.

So

DateTime _date = DateTime.Now;
var _dateString = _date.ToString("dd/MM/yyyy");

would give you the date as a string in the format you request.

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

AngularJS - Animate ng-view transitions

Angularjs 1.1.4 has now introduced the ng-animate directive to help animating different elements, in particular ng-view.

You can also watch the video about this new featue

UPDATE as of angularjs 1.2, the way animations work has changed drastically, most of it is now controlled with CSS, without having to setup javascript callbacks, etc.. You can check the updated tutorial on Year Of Moo. @dfsq pointed out in the comments a nice set of examples.

Connect Android to WiFi Enterprise network EAP(PEAP)

Thanks for enlightening us Cypawer.

I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi

and it worked flawlessly.

Leap Wifi Connector

How to reset radiobuttons in jQuery so that none is checked

Finally after a lot of tests, I think the most convenient and efficient way to preset is:

var presetValue = "black";
$("input[name=correctAnswer]").filter("[value=" + presetValue + "]").prop("checked",true);
$("input[name=correctAnswer]").button( "refresh" );//JQuery UI only

The refresh is required with the JQueryUI object.

Retrieving the value is easy :

alert($('input[name=correctAnswer]:checked').val())

Tested with JQuery 1.6.1, JQuery UI 1.8.

How can I make a time delay in Python?

Delays can be also implemented by using the following methods.

The first method:

import time
time.sleep(5) # Delay for 5 seconds.

The second method to delay would be using the implicit wait method:

 driver.implicitly_wait(5)

The third method is more useful when you have to wait until a particular action is completed or until an element is found:

self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))

PostgreSQL wildcard LIKE for any of a list of words

PostgreSQL also supports full POSIX regular expressions:

select * from table where value ~* 'foo|bar|baz';

The ~* is for a case insensitive match, ~ is case sensitive.

Another option is to use ANY:

select * from table where value  like any (array['%foo%', '%bar%', '%baz%']);
select * from table where value ilike any (array['%foo%', '%bar%', '%baz%']);

You can use ANY with any operator that yields a boolean. I suspect that the regex options would be quicker but ANY is a useful tool to have in your toolbox.

Calling a function when ng-repeat has finished

If you’re not averse to using double-dollar scope props and you’re writing a directive whose only content is a repeat, there is a pretty simple solution (assuming you only care about the initial render). In the link function:

const dereg = scope.$watch('$$childTail.$last', last => {
    if (last) {
        dereg();
        // do yr stuff -- you may still need a $timeout here
    }
});

This is useful for cases where you have a directive that needs to do DOM manip based on the widths or heights of the members of a rendered list (which I think is the most likely reason one would ask this question), but it’s not as generic as the other solutions that have been proposed.

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

If you add the android:theme="@style/Theme.AppCompat.Light" to <application> in AndroidManifest.xml file, problem is solving.

Checking Bash exit status of several commands efficiently

You can write a function that launches and tests the command for you. Assume command1 and command2 are environment variables that have been set to a command.

function mytest {
    "$@"
    local status=$?
    if (( status != 0 )); then
        echo "error with $1" >&2
    fi
    return $status
}

mytest "$command1"
mytest "$command2"

Why is __init__() always called after __new__()?

__new__ is static class method, while __init__ is instance method. __new__ has to create the instance first, so __init__ can initialize it. Note that __init__ takes self as parameter. Until you create instance there is no self.

Now, I gather, that you're trying to implement singleton pattern in Python. There are a few ways to do that.

Also, as of Python 2.6, you can use class decorators.

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
  ...

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

Try this (edited):

ctx.Database.ExecuteSqlCommand(sql, new SqlParameter("FirstName", firstName), 
                                    new SqlParameter("Id", id));

Previous idea was wrong.

Prevent users from submitting a form by hitting Enter

I had to catch all three events related to pressing keys in order to prevent the form from being submitted:

    var preventSubmit = function(event) {
        if(event.keyCode == 13) {
            console.log("caught ya!");
            event.preventDefault();
            //event.stopPropagation();
            return false;
        }
    }
    $("#search").keypress(preventSubmit);
    $("#search").keydown(preventSubmit);
    $("#search").keyup(preventSubmit);

You can combine all the above into a nice compact version:

    $('#search').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13) { e.preventDefault(); }
    });

Proxy Basic Authentication in C#: HTTP 407 error

You can use like this, it works!

        WebProxy proxy = new WebProxy
        {
            Address = new Uri(""),
            Credentials = new NetworkCredential("", "")
        };

        HttpClientHandler httpClientHandler = new HttpClientHandler
        {
            Proxy = proxy,
            UseProxy = true
        };

        HttpClient client = new HttpClient(httpClientHandler);

        HttpResponseMessage response = await client.PostAsync("...");

Generate a random date between two other dates

from random import randrange
from datetime import timedelta

def random_date(start, end):
    """
    This function will return a random datetime between two datetime 
    objects.
    """
    delta = end - start
    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
    random_second = randrange(int_delta)
    return start + timedelta(seconds=random_second)

The precision is seconds. You can increase precision up to microseconds, or decrease to, say, half-hours, if you want. For that just change the last line's calculation.

example run:

from datetime import datetime

d1 = datetime.strptime('1/1/2008 1:30 PM', '%m/%d/%Y %I:%M %p')
d2 = datetime.strptime('1/1/2009 4:50 AM', '%m/%d/%Y %I:%M %p')

print(random_date(d1, d2))

output:

2008-12-04 01:50:17

How to change a DIV padding without affecting the width/height ?

try this trick

div{
 -webkit-box-sizing: border-box; 
 -moz-box-sizing: border-box;    
 box-sizing: border-box;      
}

this will force the browser to calculate the width acording to the "outer"-width of the div, it means the padding will be substracted from the width.

show validation error messages on submit in angularjs

I can come up with 2 ways to achieve it.

The first one is to remove novalidate to enable the browser's validation.

Second, you can disable the save button when the form is not valid like this

<input ng-disabled="!frmRegister.$valid" type="submit" value="Save" />

Hope it helps.

Postgresql 9.2 pg_dump version mismatch

Macs have a builtin /usr/bin/pg_dump command that is used as default.

With the postgresql install you get another binary at /Library/PostgreSQL/<version>/bin/pg_dump

How to set up java logging using a properties file? (java.util.logging)

Logger log = Logger.getLogger("myApp");
log.setLevel(Level.ALL);
log.info("initializing - trying to load configuration file ...");

//Properties preferences = new Properties();
try {
    //FileInputStream configFile = new //FileInputStream("/path/to/app.properties");
    //preferences.load(configFile);
    InputStream configFile = myApp.class.getResourceAsStream("app.properties");
    LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException ex)
{
    System.out.println("WARNING: Could not open configuration file");
    System.out.println("WARNING: Logging not configured (console output only)");
}
log.info("starting myApp");

this is working..:) you have to pass InputStream in readConfiguration().

Bitbucket git credentials if signed up with Google

You should do a one-time setup of creating an "App password" in Bitbucket web UI with permissions to at least read your repositories and then use it in the command line.

How-to:

  1. Login to Bitbucket
  2. Click on your profile image on the right (now on the bottom left)
  3. Choose Bitbucket settings (now Personal settings)
  4. Under Access management section look for the App passwords option (https://bitbucket.org/account/settings/app-passwords/)
  5. Create an app password with permissions at least to Read under Repositories section. A password will be generated for you. Remember to save it, it will be shown only once!
  6. The username will be your Google username.

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

[Uu]

Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

r'(?<![a-zA-Z])[uU](?![a-zA-Z])'

Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

Of course, you can remove the spaces around you from the replacement string.

If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'

And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

r'(?<!\w)[uU](?!\w)'

Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)

or

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)

depending on your preference.

I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

Make column fixed position in bootstrap

Use .col instead of col-lg-3 :

<div class="row">
   <div class="col">
      Fixed content
   </div>
   <div class="col-lg-9">
      Normal scrollable content
   </div>
</div>

throwing exceptions out of a destructor

Your destructor might be executing inside a chain of other destructors. Throwing an exception that is not caught by your immediate caller can leave multiple objects in an inconsistent state, thus causing even more problems then ignoring the error in the cleanup operation.

How do you add a scroll bar to a div?

If you want to add a scroll bar using jquery the following will work. If your div had a id of 'mydiv' you could us the following jquery id selector with css property:

jQuery('#mydiv').css("overflow-y", "scroll");

How to redirect from one URL to another URL?

window.location.href = "URL2"

inside a JS block on the page or in an included file; that's assuming you really want to do it on the client. Usually, the server sends the redirect via a 300-series response.

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)

GIT: Checkout to a specific folder

If you're working under your feature and don't want to checkout back to master, you can run:

cd ./myrepo

git worktree add ../myrepo_master master

git worktree remove ../myrepo_master

It will create ../myrepo_master directory with master branch commits, where you can continue work

Java: Difference between the setPreferredSize() and setSize() methods in components

setSize() or setBounds() can be used when no layout manager is being used.

However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize() methods like setPreferredSize() and setMinimumSize() etc.

And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout, GridBagLayout, and SpringLayout managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout and GridLayout usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.

Deleting rows with MySQL LEFT JOIN

DELETE FROM deadline where ID IN (
    SELECT d.ID FROM `deadline` d LEFT JOIN `job` ON deadline.job_id = job.job_id WHERE `status` =  'szamlazva' OR `status` = 'szamlazhato' OR `status` = 'fizetve' OR `status` = 'szallitva' OR `status` = 'storno');

I am not sure if that kind of sub query works in MySQL, but try it. I am assuming you have an ID column in your deadline table.

Turn off display errors using file "php.ini"

Open your php.ini file (If you are using Linux - sudo vim /etc/php5/apache2/php.ini)

Add this lines into that file

   error_reporting = E_ALL & ~E_WARNING 

(If you need to disabled any other errors -> error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE & ~E_WARNING)

    display_errors = On

And finally you need to restart your APACHE server.

What is the Java equivalent of PHP var_dump?

It is not quite as baked-in in Java, so you don't get this for free. It is done with convention rather than language constructs. In all data transfer classes (and maybe even in all classes you write...), you should implement a sensible toString method. So here you need to override toString() in your Person class and return the desired state.

There are utilities available that help with writing a good toString method, or most IDEs have an automatic toString() writing shortcut.

Regex pattern for checking if a string starts with a certain substring?

The StartsWith method will be faster, as there is no overhead of interpreting a regular expression, but here is how you do it:

if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...

The ^ mathes the start of the string. You can put any protocols between the parentheses separated by | characters.

edit:

Another approach that is much faster, is to get the start of the string and use in a switch. The switch sets up a hash table with the strings, so it's faster than comparing all the strings:

int index = theString.IndexOf(':');
if (index != -1) {
  switch (theString.Substring(0, index)) {
    case "mailto":
    case "ftp":
    case "joe":
      // do something
      break;
  }
}

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

I assume you are using gcc, to simply link object files do:

$ gcc -o output file1.o file2.o

To get the object-files simply compile using

$ gcc -c file1.c

this yields file1.o and so on.

If you want to link your files to an executable do

$ gcc -o output file1.c file2.c

error: RPC failed; curl transfer closed with outstanding read data remaining

can be two reason

  1. Internet is slow (this was in my case)
  2. buffer size is less,in this case you can run command git config --global http.postBuffer 524288000

belongs_to through associations

You can also delegate:

class Company < ActiveRecord::Base
  has_many :employees
  has_many :dogs, :through => :employees
end

class Employee < ActiveRescord::Base
  belongs_to :company
  has_many :dogs
end

class Dog < ActiveRecord::Base
  belongs_to :employee

  delegate :company, :to => :employee, :allow_nil => true
end

how to find seconds since 1970 in java

Based on your desire that 1317427200 be the output, there are several layers of issue to address.

  • First as others have mentioned, java already uses a UTC 1/1/1970 epoch. There is normally no need to calculate the epoch and perform subtraction unless you have weird locale rules.

  • Second, when you create a new Calendar it's initialized to 'now' so it includes the time of day. Changing the year/month/day doesn't affect the time of day fields. So if you want it to represent midnight of the date, you need to zero out the calendar before you set the date.

  • Third, you haven't specified how you're supposed to handle time zones. Daylight Savings can cause differences in the absolute number of seconds represented by a particular calendar-on-the-wall-date, depending on where your JVM is running. Since epoch is in UTC, we probably want to work in UTC times? You may need to seek clarification from the makers of the system you're interfacing with.

  • Fourth, months in Java are zero indexed. January is 0, October is 9.

Putting all that together

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(2011, Calendar.OCTOBER, 1);
long secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;

that will give you 1317427200

Pointer to incomplete class type is not allowed

Check out if you are missing some import.

How to extract multiple JSON objects from one file?

So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.

The basic idea is to signal the reader to split on the carriage character "\n" (or "\r\n" for Windows). Python can do this with the file.readline() function.

import json
def json_reader(filename):
    with open(filename) as f:
        for line in f:
            yield json.loads(line)

However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.

def json_writer(file, json_objects):
    with open(file, "w") as f:
        for jsonobj in json_objects:
            jsonstr = json.dumps(jsonobj)
            f.write(jsonstr + "\n")

You could also do the same operation with file.writelines() and a list comprehension:

...
    json_strs = [json.dumps(j) + "\n" for j in json_objects]
    f.writelines(json_strs)
...

And if you wanted to append the data instead of writing a new file just change open(file, "w") to open(file, "a").

In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.

On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write

lst = list(json_reader(file))

Number format in excel: Showing % value without multiplying with 100

Pretty easy to do this across multiple cells, without having to add '%' to each individually.

Select all the cells you want to change to percent, right Click, then format Cells, choose Custom. Type in 0.0\%.

Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL

I also have a site that has numerous urls with urlencoded characters. I am finding that many web APIs (including Google webmaster tools and several Drupal modules) trip over urlencoded characters. Many APIs automatically decode urls at some point in their process and then use the result as a URL or HTML. When I find one of these problems, I usually double encode the results (which turns %2f into %252f) for that API. However, this will break other APIs which are not expecting double encoding, so this is not a universal solution.

Personally I am getting rid of as many special characters in my URLs as possible.

Also, I am using id numbers in my URLs which do not depend on urldecoding:

example.com/blog/my-amazing-blog%2fstory/yesterday

becomes:

example.com/blog/12354/my-amazing-blog%2fstory/yesterday

in this case, my code only uses 12354 to look for the article, and the rest of the URL gets ignored by my system (but is still used for SEO.) Also, this number should appear BEFORE the unused URL components. that way, the url will still work, even if the %2f gets decoded incorrectly.

Also, be sure to use canonical tags to ensure that url mistakes don't translate into duplicate content.

CSS media queries: max-width OR max-height

There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:

@media only screen 
and (min-width : 415px){
    /* Styles */
}

@media only screen 
and (min-width : 769px){
    /* Styles */
}

@media only screen 
and (min-width : 992px){
    /* Styles */
}

But if you are writing media queries for smaller device first, then it would be something like:

@media only screen 
and (max-width : 991px){
    /* Styles */
}

@media only screen 
and (max-width : 768px){
    /* Styles */
}

@media only screen 
and (max-width : 414px){
    /* Styles */
}

Java :Add scroll into text area

My naive assumption was that the size of scroll pane will be determined automatically...

The only solution that actually worked for me was explicitly seeting bounds of JScrollPane:

import javax.swing.*;

public class MyFrame extends JFrame {

    public MyFrame()
    {
        setBounds(100, 100, 491, 310);
        getContentPane().setLayout(null);

        JTextArea textField = new JTextArea();
        textField.setEditable(false);

        String str = "";
        for (int i = 0; i < 50; ++i)
            str += "Some text\n";
        textField.setText(str);

        JScrollPane scroll = new JScrollPane(textField);
        scroll.setBounds(10, 11, 455, 249);                     // <-- THIS

        getContentPane().add(scroll);
        setLocationRelativeTo ( null );
    }
}

Maybe it will help some future visitors :)

Correct modification of state arrays in React.js

Here's a 2020, Reactjs Hook example that I thought could help others. I am using it to add new rows to a Reactjs table. Let me know if I could improve on something.

Adding a new element to a functional state component:

Define the state data:

    const [data, setData] = useState([
        { id: 1, name: 'John', age: 16 },
        { id: 2, name: 'Jane', age: 22 },
        { id: 3, name: 'Josh', age: 21 }
    ]);

Have a button trigger a function to add a new element

<Button
    // pass the current state data to the handleAdd function so we can append to it.
    onClick={() => handleAdd(data)}>
    Add a row
</Button>
function handleAdd(currentData) {

        // return last data array element
        let lastDataObject = currentTableData[currentTableData.length - 1]

        // assign last elements ID to a variable.
        let lastID = Object.values(lastDataObject)[0] 

        // build a new element with a new ID based off the last element in the array
        let newDataElement = {
            id: lastID + 1,
            name: 'Jill',
            age: 55,
        }

        // build a new state object 
        const newStateData = [...currentData, newDataElement ]

        // update the state
        setData(newStateData);

        // print newly updated state
        for (const element of newStateData) {
            console.log('New Data: ' + Object.values(element).join(', '))
        }

}

Get the current file name in gulp.src()

If you want to use @OverZealous' answer (https://stackoverflow.com/a/21806974/1019307) in Typescript, you need to import instead of require:

import * as debug from 'gulp-debug';

...

    return gulp.src('./examples/*.html')
        .pipe(debug({title: 'example src:'}))
        .pipe(gulp.dest('./build'));

(I also added a title).

Raise an error manually in T-SQL to jump to BEGIN CATCH block

You could use THROW (available in SQL Server 2012+):

THROW 50000, 'Your custom error message', 1
THROW <error_number>, <message>, <state>

MSDN THROW (Transact-SQL)

Differences Between RAISERROR and THROW in Sql Server

Good ways to sort a queryset? - Django

I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by method accepts multiple arguments, you could easily chain them:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):

>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name:

>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
... 
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)

And now the combined order_by call:

>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
... 
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)

As you can see it is the same result as the first one, meaning it doesn't work as you would expect.

How to get JavaScript caller function line number? How to get JavaScript caller source URL?

the following code works for me in Mozilla and Chrome.

Its log function that shows the file's name and the line of the caller.

log: function (arg) {
    var toPrint = [];
    for (var i = 0; i < arguments.length; ++i) {
        toPrint.push(arguments[i]);
    }

    function getErrorObject(){
        try { throw Error('') } catch(err) { return err; }
    }

    var err = getErrorObject(),
        caller;

    if ($.browser.mozilla) {
        caller = err.stack.split("\n")[2];
    } else {
        caller = err.stack.split("\n")[4];
    }

    var index = caller.indexOf('.js');

    var str = caller.substr(0, index + 3);
    index = str.lastIndexOf('/');
    str = str.substr(index + 1, str.length);

    var info = "\t\tFile: " + str;

    if ($.browser.mozilla) {
        str = caller;
    } else {
        index = caller.lastIndexOf(':');
        str = caller.substr(0, index);
    }
    index = str.lastIndexOf(':');
    str = str.substr(index + 1, str.length);
    info += " Line: " + str;
    toPrint.push(info);

    console.log.apply(console, toPrint);
}

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

ng-mouseover and leave to toggle item using mouse in angularjs

I'd probably change your example to look like this:

<ul ng-repeat="task in tasks">
  <li ng-mouseover="enableEdit(task)" ng-mouseleave="disableEdit(task)">{{task.name}}</li>
  <span ng-show="task.editable"><a>Edit</a></span>
</ul>

//js
$scope.enableEdit = function(item){
  item.editable = true;
};

$scope.disableEdit = function(item){
  item.editable = false;
};

I know it's a subtle difference, but makes the domain a little less bound to UI actions. Mentally it makes it easier to think about an item being editable rather than having been moused over.

Example jsFiddle.

EXCEL VBA Check if entry is empty or not 'space'

A common trick is to check like this:

trim(TextBox1.Value & vbnullstring) = vbnullstring

this will work for spaces, empty strings, and genuine null values

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

You might consider using double slashes on your directory e.g

_x000D_
_x000D_
app.get('/',(req,res)=>{_x000D_
    res.sendFile('C:\\Users\\DOREEN\\Desktop\\Fitness Finder' + '/index.html')_x000D_
})
_x000D_
_x000D_
_x000D_

Insert into C# with SQLCommand

public class customer
{
    public void InsertCustomer(string name,int age,string address)
    {
        // create and open a connection object
        using(SqlConnection Con=DbConnection.GetDbConnection())
        {
            // 1. create a command object identifying the stored procedure
            SqlCommand cmd = new SqlCommand("spInsertCustomerData",Con);

            // 2. set the command object so it knows to execute a stored procedure
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter paramName = new SqlParameter();
            paramName.ParameterName = "@nvcname";
            paramName.Value = name;
            cmd.Parameters.Add(paramName);

            SqlParameter paramAge = new SqlParameter();
            paramAge.ParameterName = "@inage";
            paramAge.Value = age;
            cmd.Parameters.Add(paramAge);

            SqlParameter paramAddress = new SqlParameter();
            paramAddress.ParameterName = "@nvcaddress";
            paramAddress.Value = address;
            cmd.Parameters.Add(paramAddress);

            cmd.ExecuteNonQuery();
        }
    }
}

Get domain name

I found this question by the title. If anyone else is looking for the answer on how to just get the domain name, use the following environment variable.

System.Environment.UserDomainName

I'm aware that the author to the question mentions this, but I missed it at the first glance and thought someone else might do the same.

What the description of the question then ask for is the fully qualified domain name (FQDN).

How to use the CSV MIME-type?

With Internet Explorer you often have to specify the Pragma: public header as well for the download to function properly..

header('Pragma: public');

Just my 2 cents..

Warp \ bend effect on a UIView?

What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.

I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)

Angular get object from array by Id

getDimensions(id) {
    var obj = questions.filter(function(node) {
        return node.id==id;
    });

    return obj;   
}

How to get unique values in an array

Since I went on about it in the comments for @Rocket's answer, I may as well provide an example that uses no libraries. This requires two new prototype functions, contains and unique

_x000D_
_x000D_
Array.prototype.contains = function(v) {_x000D_
  for (var i = 0; i < this.length; i++) {_x000D_
    if (this[i] === v) return true;_x000D_
  }_x000D_
  return false;_x000D_
};_x000D_
_x000D_
Array.prototype.unique = function() {_x000D_
  var arr = [];_x000D_
  for (var i = 0; i < this.length; i++) {_x000D_
    if (!arr.contains(this[i])) {_x000D_
      arr.push(this[i]);_x000D_
    }_x000D_
  }_x000D_
  return arr;_x000D_
}_x000D_
_x000D_
var duplicates = [1, 3, 4, 2, 1, 2, 3, 8];_x000D_
var uniques = duplicates.unique(); // result = [1,3,4,2,8]_x000D_
_x000D_
console.log(uniques);
_x000D_
_x000D_
_x000D_

For more reliability, you can replace contains with MDN's indexOf shim and check if each element's indexOf is equal to -1: documentation

how can I set visible back to true in jquery

Remove the visible="false" attribute and add a CSS class that is not visible by default. Then you should be able to reference the dropdown by the correct id, for example:

$("#ctl00_cphTest_test1").show();

Above ID you should serach for in the source of the rendered page in your browser.

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

_x000D_
_x000D_
.selectmenu{_x000D_
  _x000D_
 -webkit-appearance: none;  /*Removes default chrome and safari style*/_x000D_
 -moz-appearance: none; /* Removes Default Firefox style*/_x000D_
 background: #0088cc ;_x000D_
 width: 200px; /*Width of select dropdown to give space for arrow image*/_x000D_
 text-indent: 0.01px; /* Removes default arrow from firefox*/_x000D_
 text-overflow: "";  /*Removes default arrow from firefox*/ /*My custom style for fonts*/_x000D_
 color: #FFF;_x000D_
 border-radius: 2px;_x000D_
 padding: 5px;_x000D_
    border:0 !important;_x000D_
 box-shadow: inset 0 0 5px rgba(000,000,000, 0.5);_x000D_
}_x000D_
.hideoption { display:none; visibility:hidden; height:0; font-size:0; }
_x000D_
Try this html_x000D_
_x000D_
<select class="selectmenu">_x000D_
<option selected disabled class="hideoption">Select language</option>_x000D_
<option>Option 1</option>_x000D_
<option>Option 2</option>_x000D_
<option>Option 3</option>_x000D_
<option>Option 4</option>_x000D_
<option>Option 5</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Rails where condition using NOT NIL

The canonical way to do this with Rails 3:

Foo.includes(:bar).where("bars.id IS NOT NULL")

ActiveRecord 4.0 and above adds where.not so you can do this:

Foo.includes(:bar).where.not('bars.id' => nil)
Foo.includes(:bar).where.not(bars: { id: nil })

When working with scopes between tables, I prefer to leverage merge so that I can use existing scopes more easily.

Foo.includes(:bar).merge(Bar.where.not(id: nil))

Also, since includes does not always choose a join strategy, you should use references here as well, otherwise you may end up with invalid SQL.

Foo.includes(:bar)
   .references(:bar)
   .merge(Bar.where.not(id: nil))

Scroll to a div using jquery

First, your code does not contain a contact div, it has a contacts div!

In sidebar you have contact in the div at the bottom of the page you have contacts. I removed the final s for the code sample. (you also misspelled the projectslink id in the sidebar).

Second, take a look at some of the examples for click on the jQuery reference page. You have to use click like, object.click( function() { // Your code here } ); in order to bind a click event handler to the object.... Like in my example below. As an aside, you can also just trigger a click on an object by using it without arguments, like object.click().

Third, scrollTo is a plugin in jQuery. I don't know if you have the plugin installed. You can't use scrollTo() without the plugin. In this case, the functionality you desire is only 2 lines of code, so I see no reason to use the plugin.

Ok, now on to a solution.

The code below will scroll to the correct div if you click a link in the sidebar. The window does have to be big enough to allow scrolling:

// This is a functions that scrolls to #{blah}link
function goToByScroll(id) {
    // Remove "link" from the ID
    id = id.replace("link", "");
    // Scroll
    $('html,body').animate({
        scrollTop: $("#" + id).offset().top
    }, 'slow');
}

$("#sidebar > ul > li > a").click(function(e) {
    // Prevent a page reload when a link is pressed
    e.preventDefault();
    // Call the scroll function
    goToByScroll(this.id);
});

Live Example

( Scroll to function taken from here )


PS: Obviously you should have a compelling reason to go this route instead of using anchor tags <a href="#gohere">blah</a> ... <a name="gohere">blah title</a>

Getting a directory name from a filename

I'm so surprised no one has mentioned the standard way in Posix

Please use basename / dirname constructs.

man basename

Store boolean value in SQLite

You could simplify the above equations using the following:

boolean flag = sqlInt != 0;

If the int representation (sqlInt) of the boolean is 0 (false), the boolean (flag) will be false, otherwise it will be true.

Concise code is always nicer to work with :)

return SQL table as JSON in python

One simple example for return SQL table as formatted JSON and fix error as he had @Whitecat

I get the error datetime.datetime(1941, 10, 31, 0, 0) is not JSON serializable

In that example you should use JSONEncoder.

import json
import pymssql

# subclass JSONEncoder
class DateTimeEncoder(JSONEncoder):
        #Override the default method
        def default(self, obj):
            if isinstance(obj, (datetime.date, datetime.datetime)):
                return obj.isoformat()

def mssql_connection():
    try:
        return pymssql.connect(server="IP.COM", user="USERNAME", password="PASSWORD", database="DATABASE")
    except Exception:
        print("\nERROR: Unable to connect to the server.")
        exit(-1)

def query_db(query):
    cur = mssql_connection().cursor()
    cur.execute(query)
    r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()]
    cur.connection.close()
    return r

def write_json(query_path):
    # read sql from file
    with open("../sql/my_sql.txt", 'r') as f:
        sql = f.read().replace('\n', ' ')
    # creating and writing to a json file and Encode DateTime Object into JSON using custom JSONEncoder
    with open("../output/my_json.json", 'w', encoding='utf-8') as f:
        json.dump(query_db(sql), f, ensure_ascii=False, indent=4, cls=DateTimeEncoder) 

if __name__ == "__main__":
    write_json()

# You get formatted my_json.json, for example:
[
   {
      "divroad":"N",
      "featcat":null,
      "countyfp":"001",
      "date":"2020-08-28"
   }
]

Extract a substring from a string in Ruby using a regular expression

A simpler scan would be:

String1.scan(/<(\S+)>/).last

Convert CString to const char*

Generic Conversion Macros (TN059 Other Considerations section is important):

A2CW     (LPCSTR)  -> (LPCWSTR)  
A2W      (LPCSTR)  -> (LPWSTR)  
W2CA     (LPCWSTR) -> (LPCSTR)  
W2A      (LPCWSTR) -> (LPSTR) 

Spark - load CSV file as DataFrame?

With Spark 2.0, following is how you can read CSV

val conf = new SparkConf().setMaster("local[2]").setAppName("my app")
val sc = new SparkContext(conf)
val sparkSession = SparkSession.builder
  .config(conf = conf)
  .appName("spark session example")
  .getOrCreate()

val path = "/Users/xxx/Downloads/usermsg.csv"
val base_df = sparkSession.read.option("header","true").
  csv(path)

Calculating the SUM of (Quantity*Price) from 2 different tables

I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.

select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
    select o.orderID, o.price * o.qty as subtotal
    from product p inner join orderitem o on p.ProductID= o.productID
    where o.orderID = @OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal

javascript function wait until another function to finish

In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.

Here is an example I have just written to demonstrate how you could do it using deferreds/promises.

Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.

Hope this helps!

$(function(){
    function1().done(function(){
        // function1 is done, we can now call function2
        console.log('function1 is done!');

        function2().done(function(){
            //function2 is done
            console.log('function2 is done!');
        });
    });
});

function function1(){
    var dfrd1 = $.Deferred();
    var dfrd2= $.Deferred();

    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function1 is done!');
        dfrd1.resolve();
    }, 1000);

    setTimeout(function(){
        // doing more async stuff
        console.log('task 2 in function1 is done!');
        dfrd2.resolve();
    }, 750);

    return $.when(dfrd1, dfrd2).done(function(){
        console.log('both tasks in function1 are done');
        // Both asyncs tasks are done
    }).promise();
}

function function2(){
    var dfrd1 = $.Deferred();
    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function2 is done!');
        dfrd1.resolve();
    }, 2000);
    return dfrd1.promise();
}

In Angular, how to pass JSON object/array into directive?

What you need is properly a service:

.factory('DataLayer', ['$http',

    function($http) {

        var factory = {};
        var locations;

        factory.getLocations = function(success) {
            if(locations){
                success(locations);
                return;
            }
            $http.get('locations/locations.json').success(function(data) {
                locations = data;
                success(locations);
            });
        };

        return factory;
    }
]);

The locations would be cached in the service which worked as singleton model. This is the right way to fetch data.

Use this service DataLayer in your controller and directive is ok as following:

appControllers.controller('dummyCtrl', function ($scope, DataLayer) {
    DataLayer.getLocations(function(data){
        $scope.locations = data;
    });
});

.directive('map', function(DataLayer) {
    return {
        restrict: 'E',
        replace: true,
        template: '<div></div>',
        link: function(scope, element, attrs) {

            DataLayer.getLocations(function(data) {
                angular.forEach(data, function(location, key){
                    //do something
                });
            });
        }
    };
});

Php header location redirect not working

I had also the similar issue in godaddy hosting. But after putting ob_start(); at the beginning of the php page from where page was redirecting, it was working fine.

Please find the example of the fix:

fileName:index.php

<?php
ob_start();
...
header('Location: page1.php');
...
ob_end_flush();
?>

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

Use '=' or LIKE to compare strings in SQL?

In my small experience:

"=" for Exact Matches.

"LIKE" for Partial Matches.

Styling twitter bootstrap buttons

If you are already loading your own custom CSS file after loading bootstrap.css (version 3) you can add these 2 CSS styles to your custom.css and they will override the bootstrap defaults for the default button style.

.btn-primary:hover, .btn-primary:focus, .btn-primary:active, .btn-primary.active, .open .dropdown-toggle.btn-primary {

  background-color: #A6A8C1;
  border-color: #31347B;
 }

.btn
{
  background-color: #9F418F;
  border-color: #9F418F;
}

jQuery: count number of rows in a table

If you use <tbody> or <tfoot> in your table, you'll have to use the following syntax or you'll get a incorrect value:

var rowCount = $('#myTable >tbody >tr').length;

How do you get the list of targets in a makefile?

@nobar's answer helpfully shows how to use tab completion to list a makefile's targets.

  • This works great for platforms that provide this functionality by default (e.g., Debian, Fedora).

  • On other platforms (e.g., Ubuntu) you must explicitly load this functionality, as implied by @hek2mgl's answer:

    • . /etc/bash_completion installs several tab-completion functions, including the one for make
    • Alternatively, to install only tab completion for make:
      • . /usr/share/bash-completion/completions/make
  • For platforms that don't offer this functionality at all, such as OSX, you can source the following commands (adapated from here) to implement it:
_complete_make() { COMPREPLY=($(compgen -W "$(make -pRrq : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($1 !~ "^[#.]") {print $1}}' | egrep -v '^[^[:alnum:]]' | sort | xargs)" -- "${COMP_WORDS[$COMP_CWORD]}")); }
complete -F _complete_make make
  • Note: This is not as sophisticated as the tab-completion functionality that comes with Linux distributions: most notably, it invariably targets the makefile in the current directory, even if the command line targets a different makefile with -f <file>.

How to resolve a Java Rounding Double issue

Better yet use JScience as BigDecimal is fairly limited (e.g., no sqrt function)

double dCommission = 1586.6 - 708.75;
System.out.println(dCommission);
> 877.8499999999999

Real dCommissionR = Real.valueOf(1586.6 - 708.75);
System.out.println(dCommissionR);
> 877.850000000000

Checking if a textbox is empty in Javascript

your validation should be occur before your event suppose you are going to submit your form.

anyway if you want this on onchange, so here is code.

function valid(id)
{
    var textVal=document.getElementById(id).value;
    if (!textVal.match(/\S/)) 
    {
        alert("Field is blank");
        return false;
    } 
    else 
    {
        return true;
    }
 }

How do I change the figure size with subplots?

Alternatively, create a figure() object using the figsize argument and then use add_subplot to add your subplots. E.g.

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

Simple Example

Benefits of this method are that the syntax is closer to calls of subplot() instead of subplots(). E.g. subplots doesn't seem to support using a GridSpec for controlling the spacing of the subplots, but both subplot() and add_subplot() do.

How to execute VBA Access module?

You're not running a module -- you're running subroutines/functions that happen to be stored in modules.

If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).

Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:

  SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
  FROM MyTable;

That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.

Subroutines (i.e., code that returns no value) are not callable from within SQL statements.

How To Upload Files on GitHub

If you want to upload a folder or a file to Github

1- Create a repository on the Github

2- make: git remote add origin "Your Link" as it is described on the Github

3- Then use git push -u origin master.

4- You have to enter your username and Password.

5- After the authentication, the transfer will start

receiving json and deserializing as List of object at spring mvc controller

I believe this will solve the issue

var z = '[{"name":"1","age":"2"},{"name":"1","age":"3"}]';
z = JSON.stringify(JSON.parse(z));
$.ajax({
    url: "/setTest",
    data: z,
    type: "POST",
    dataType:"json",
    contentType:'application/json'               
});

Get number days in a specified month using JavaScript?

// Month here is 1-indexed (January is 1, February is 2, etc). This is
// because we're using 0 as the day so that it returns the last day
// of the last month, so you have to add 1 to the month number 
// so it returns the correct amount of days
function daysInMonth (month, year) {
    return new Date(year, month, 0).getDate();
}

// July
daysInMonth(7,2009); // 31
// February
daysInMonth(2,2009); // 28
daysInMonth(2,2008); // 29

Java: splitting the filename into a base and extension

File extensions are a broken concept

And there exists no reliable function for it. Consider for example this filename:

archive.tar.gz

What is the extension? DOS users would have preferred the name archive.tgz. Sometimes you see stupid Windows applications that first decompress the file (yielding a .tar file), then you have to open it again to see the archive contents.

In this case, a more reasonable notion of file extension would have been .tar.gz. There are also .tar.bz2, .tar.xz, .tar.lz and .tar.lzma file "extensions" in use. But how would you decide, whether to split at the last dot, or the second-to-last dot?

Use mime-types instead.

The Java 7 function Files.probeContentType will likely be much more reliable to detect file types than trusting the file extension. Pretty much all the Unix/Linux world as well as your Webbrowser and Smartphone already does it this way.

Combining the results of two SQL queries as separate columns

how to club the 4 query's as a single query

show below query

  1. total number of cases pending + 2.cases filed during this month ( base on sysdate) + total number of cases (1+2) + no. cases disposed where nse= disposed + no. of cases pending (other than nse <> disposed)

nsc = nature of case

report is taken on 06th of every month

( monthly report will be counted from 05th previous month to 05th present of present month)

Psql list all tables

In SQL Query, you can write this code:

select table_name from information_schema.tables where table_schema='YOUR_TABLE_SCHEME';

Replace your table scheme with YOUR_TABLE_SCHEME;

Example:

select table_name from information_schema.tables where table_schema='eLearningProject';

To see all scheme and all tables, there is no need of where clause:

select table_name from information_schema.tables

Drop data frame columns by name

Out of interest, this flags up one of R's weird multiple syntax inconsistencies. For example given a two-column data frame:

df <- data.frame(x=1, y=2)

This gives a data frame

subset(df, select=-y)

but this gives a vector

df[,-2]

This is all explained in ?[ but it's not exactly expected behaviour. Well at least not to me...

How can I take a screenshot with Selenium WebDriver?

/**
 * Take a screenshot and move to the given folder location.
 *
 * @param driver
 * @param folderLocation
 * @return screenShotFilePath
 */
public static String captureScreenshot(WebDriver driver, String folderLocation) {

    // Variable to store screenshot's file path.
    String screenShotFilePath = null;

    // Generate unique id for screen shot name.
    String uniqueId = UUID.randomUUID().toString().substring(31);

    if (driver != null) {

        // Generate screenshot as a file
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

        // New screenshot file path with having file name
        screenShotFilePath = folderLocation + File.separator + uniqueId + ".png";

        // Move file to the destination location.
        FileUtils.moveFile(scrFile, new File(screenShotFilePath));
    }

    return screenShotFilePath;
}

'AND' vs '&&' as operator

which version are you using?

If the coding standards for the particular codebase I am writing code for specifies which operator should be used, I'll definitely use that. If not, and the code dictates which should be used (not often, can be easily worked around) then I'll use that. Otherwise, probably &&.

Is 'and' more readable than '&&'?

Is it more readable to you. The answer is yes and no depending on many factors including the code around the operator and indeed the person reading it!

|| there is ~ difference?

Yes. See logical operators for || and bitwise operators for ~.

Select statement to find duplicates on certain fields

If you're using SQL Server 2005 or later (and the tags for your question indicate SQL Server 2008), you can use ranking functions to return the duplicate records after the first one if using joins is less desirable or impractical for some reason. The following example shows this in action, where it also works with null values in the columns examined.

create table Table1 (
 Field1 int,
 Field2 int,
 Field3 int,
 Field4 int 
)

insert  Table1 
values    (1,1,1,1)
        , (1,1,1,2)
        , (1,1,1,3)
        , (2,2,2,1)
        , (3,3,3,1)
        , (3,3,3,2)
        , (null, null, 2, 1)
        , (null, null, 2, 3)

select    *
from     (select      Field1
                    , Field2
                    , Field3
                    , Field4
                    , row_number() over (partition by   Field1
                                                      , Field2
                                                      , Field3
                                         order by       Field4) as occurrence
          from      Table1) x
where     occurrence > 1

Notice after running this example that the first record out of every "group" is excluded, and that records with null values are handled properly.

If you don't have a column available to order the records within a group, you can use the partition-by columns as the order-by columns.

IDEA: javac: source release 1.7 requires target release 1.7

You need to change Java compiler version in in build config.

enter image description here

Masking password input from the console : Java

If you're dealing with a Java character array (such as password characters that you read from the console), you can convert it to a JRuby string with the following Ruby code:

# GIST: "pw_from_console.rb" under "https://gist.github.com/drhuffman12"

jconsole = Java::java.lang.System.console()
password = jconsole.readPassword()
ruby_string = ''
password.to_a.each {|c| ruby_string << c.chr}

# .. do something with 'password' variable ..    
puts "password_chars: #{password_chars.inspect}"
puts "password_string: #{password_string}"

See also "https://stackoverflow.com/a/27628738/4390019" and "https://stackoverflow.com/a/27628756/4390019"

How to show empty data message in Datatables

By default the grid view will take care, just pass empty data set.

error C2220: warning treated as error - no 'object' file generated

The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.

In case you don't know how to find them: Open the Error List (View > Error List) and click on Warning.

Getting list of items inside div using Selenium Webdriver

You're asking for all the elements of class facetContainerDiv, of which there is only one (your outer-most div). Why not do

List<WebElement> checks =  driver.findElements(By.class("facetCheck"));
// click the 3rd checkbox
checks.get(2).click();

Check if value exists in column in VBA

Try adding WorksheetFunction:

If Not IsError(Application.WorksheetFunction.Match(ValueToSearchFor, RangeToSearchIn, 0)) Then
' String is in range

Given URL is not allowed by the Application configuration Facebook application error

Try to check at Settings > Advanced. At Valid OAuth redirect URIs, make sure you have a correct domain.

Hope it works.

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

For example folder named new under E: drive

type the command:

e:\cd new

e:\new\attrib *.* -s -h /s /d

and all the files and folders are un-hidden

Min/Max-value validators in asp.net mvc

A complete example of how this could be done. To avoid having to write client-side validation scripts, the existing ValidationType = "range" has been used.

public class MinValueAttribute : ValidationAttribute, IClientValidatable
{
    private readonly double _minValue;

    public MinValueAttribute(double minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;  
    }

    public MinValueAttribute(int minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;
    }

    public override bool IsValid(object value)
    {
        return Convert.ToDouble(value) >= _minValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = ErrorMessage;
        rule.ValidationParameters.Add("min", _minValue);
        rule.ValidationParameters.Add("max", Double.MaxValue);
        rule.ValidationType = "range";
        yield return rule;
    }

}

array of string with unknown size

string[ ] array = {};

// it is not null instead it is empty.

Format JavaScript date as yyyy-mm-dd

formatDate(date) {
  const d = new Date(date)
  const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
  const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
  const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
  return `${da}-${mo}-${ye}`;
}

console.log("Formatated Date : ", formatDate("09/25/2020") )
// Output :: Formatated Date : 25-Sep-2020

jQuery validation plugin: accept only alphabetical characters?

Just a small addition to Nick's answer (which works great !) :

If you want to allow spaces in between letters, for example , you may restrict to enter only letters in full name, but it should allow space as well - just list the space as below with a comma. And in the same way if you need to allow any other specific character:

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please");       

How to define several include path in Makefile

You have to prepend every directory with -I:

INC=-I/usr/informix/incl/c++ -I/opt/informix/incl/public

Python: download a file from an FTP server

Try using the wget library for python. You can find the documentation for it here.

import wget
link = 'ftp://example.com/foo.txt'
wget.download(link)

How to Extract Year from DATE in POSTGRESQL

You may try to_char(now()::date, 'yyyy')
If text, you've to cast your text to date to_char('2018-01-01'::date, 'yyyy')

See the PostgreSQL Documentation Data Type Formatting Functions

Where is Android Studio layout preview?

Go to File > Settings > Appearance & Behavior > Appearance > Show tool window bars

Error including image in Latex

I use MacTex, and my editor is TexShop. It probably has to do with what compiler you are using. When I use pdftex, the command:

\includegraphics[height=60mm, width=100mm]{number2.png}

works fine, but when I use "Tex and Ghostscript", I get the same error as you, about not being able to get the size information. Use pdftex.

Incidentally, you can change this in TexShop from the "Typeset" menu.

Hope this helps.

How to set a Default Route (To an Area) in MVC

This is how I did it. I don't know why MapRoute() doesn't allow you to set the area, but it does return the route object so you can continue to make any additional changes you would like. I use this because I have a modular MVC site that is sold to enterprise customers and they need to be able to drop dlls into the bin folder to add new modules. I allow them to change the "HomeArea" in the AppSettings config.

var route = routes.MapRoute(
                "Home_Default", 
                "", 
                new {controller = "Home", action = "index" },
                new[] { "IPC.Web.Core.Controllers" }
               );
route.DataTokens["area"] = area;

Edit: You can try this as well in your AreaRegistration.RegisterArea for the area you want the user going to by default. I haven't tested it but AreaRegistrationContext.MapRoute does sets route.DataTokens["area"] = this.AreaName; for you.

context.MapRoute(
                    "Home_Default", 
                    "", 
                    new {controller = "Home", action = "index" },
                    new[] { "IPC.Web.Core.Controllers" }
                   );

Strip / trim all strings of a dataframe

You can use the apply function of the Series object:

>>> df = pd.DataFrame([['  a  ', 10], ['  c  ', 5]])
>>> df[0][0]
'  a  '
>>> df[0] = df[0].apply(lambda x: x.strip())
>>> df[0][0]
'a'

Note the usage of strip and not the regex which is much faster

Another option - use the apply function of the DataFrame object:

>>> df = pd.DataFrame([['  a  ', 10], ['  c  ', 5]])
>>> df.apply(lambda x: x.apply(lambda y: y.strip() if type(y) == type('') else y), axis=0)

   0   1
0  a  10
1  c   5

Should I call Close() or Dispose() for stream objects?

No, you shouldn't call those methods manually. At the end of the using block the Dispose() method is automatically called which will take care to free unmanaged resources (at least for standard .NET BCL classes such as streams, readers/writers, ...). So you could also write your code like this:

using (Stream responseStream = response.GetResponseStream())
    using (StreamReader reader = new StreamReader(responseStream))
        using (StreamWriter writer = new StreamWriter(filename))
        {
            int chunkSize = 1024;
            while (!reader.EndOfStream)
            {
                 char[] buffer = new char[chunkSize];
                 int count = reader.Read(buffer, 0, chunkSize);
                 if (count != 0)
                 {
                     writer.Write(buffer, 0, count);
                 }
            }
         }

The Close() method calls Dispose().

socket.emit() vs. socket.send()

TL;DR:

socket.send(data, callback) is essentially equivalent to calling socket.emit('message', JSON.stringify(data), callback)

Without looking at the source code, I would assume that the send function is more efficient edit: for sending string messages, at least?

So yeah basically emit allows you to send objects, which is very handy.

Take this example with socket.emit:

sendMessage: function(type, message) {
    socket.emit('message', {
        type: type,
        message: message
    });
}

and for those keeping score at home, here is what it looks like using socket.send:

sendMessage: function(type, message) {
    socket.send(JSON.stringify({
        type: type,
        message: message
    }));
}

Choice between vector::resize() and vector::reserve()

resize() not only allocates memory, it also creates as many instances as the desired size which you pass to resize() as argument. But reserve() only allocates memory, it doesn't create instances. That is,

std::vector<int> v1;
v1.resize(1000); //allocation + instance creation
cout <<(v1.size() == 1000)<< endl;   //prints 1
cout <<(v1.capacity()==1000)<< endl; //prints 1

std::vector<int> v2;
v2.reserve(1000); //only allocation
cout <<(v2.size() == 1000)<< endl;   //prints 0
cout <<(v2.capacity()==1000)<< endl; //prints 1

Output (online demo):

1
1
0
1

So resize() may not be desirable, if you don't want the default-created objects. It will be slow as well. Besides, if you push_back() new elements to it, the size() of the vector will further increase by allocating new memory (which also means moving the existing elements to the newly allocated memory space). If you have used reserve() at the start to ensure there is already enough allocated memory, the size() of the vector will increase when you push_back() to it, but it will not allocate new memory again until it runs out of the space you reserved for it.

How to split a string in Ruby and get all items except the first one?

Since you've got an array, what you really want is Array#slice, not split.

rest = ex.slice(1 .. -1)
# or
rest = ex[1 .. -1]

Windows- Pyinstaller Error "failed to execute script " When App Clicked

Well I guess I have found the solution for my own question, here is how I did it:

Eventhough I was being able to successfully run the program using normal python command as well as successfully run pyinstaller and be able to execute the app "new_app.exe" using the command line mentioned in the question which in both cases display the GUI with no problem at all. However, only when I click the application it won't allow to display the GUI and no error is generated.

So, What I did is I added an extra parameter --debug in the pyinstaller command and removing the --windowed parameter so that I can see what is actually happening when the app is clicked and I found out there was an error which made a lot of sense when I trace it, it basically complained that "some_image.jpg" no such file or directory.

The reason why it complains and didn't complain when I ran the script from the first place or even using the command line "./" is because the file image existed in the same path as the script located but when pyinstaller created "dist" directory which has the app product it makes a perfect sense that the image file is not there and so I basically moved it to that dist directory where the clickable app is there!

FCM getting MismatchSenderId

For eliminate this error for mismatch sender Id In fcm

{"multicast_id":7751536172966571167,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

there is error occured,

  1. So we required first, In FCM, register Application e.g MyDemoApplication

  2. After that FCM will generate server key i.e AIzaSyB9krC8mLHzO_TtECb5qg7NDZPxeG03jHU and sender Id i.e 346252831806 these format like these.

  3. After In Android Studio, our project is connect to these FCM created project i.e MyDemoApplication

  4. And most important step is there required to device token or registration id. These token must created in Android Studio..

  5. After that using Sender Id and API key in web API project u will be definitely getting notification

CSV new-line character seen in unquoted field error

It'll be good to see the csv file itself, but this might work for you, give it a try, replace:

file_read = csv.reader(self.file)

with:

file_read = csv.reader(self.file, dialect=csv.excel_tab)

Or, open a file with universal newline mode and pass it to csv.reader, like:

reader = csv.reader(open(self.file, 'rU'), dialect=csv.excel_tab)

Or, use splitlines(), like this:

def read_file(self):
    with open(self.file, 'r') as f:
        data = [row for row in csv.reader(f.read().splitlines())]
    return data

C# with MySQL INSERT parameters

I had the same issue -- Finally tried the ? sigil instead of @, and it worked.

According to the docs:

Note. Prior versions of the provider used the '@' symbol to mark parameters in SQL. This is incompatible with MySQL user variables, so the provider now uses the '?' symbol to locate parameters in SQL. To support older code, you can set 'old syntax=yes' on your connection string. If you do this, please be aware that an exception will not be throw if you fail to define a parameter that you intended to use in your SQL.

Really? Why don't you just throw an exception if someone tries to use the so called old syntax? A few hours down the drain for a 20 line program...

MySQL::MySQLCommand

Change hash without reload in jQuery

You can simply assign it a new value as follows,

window.location.hash

Angular 6: How to set response type as text while making http call

On your backEnd, you should add:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

On the frontEnd (Service):

methodBlabla() 
{
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});
}

htaccess redirect all pages to single page

Add this for pages not currently on your site...

ErrorDocument 404 http://example.com/

Along with your Redirect 301 / http://www.thenewdomain.com/ that should cover all the bases...

Good luck!

How to wait for the 'end' of 'resize' event and only then perform an action?

i wrote a litte wrapper function on my own...

onResize  =   function(fn) {
    if(!fn || typeof fn != 'function')
        return 0;

    var args    = Array.prototype.slice.call(arguments, 1);

    onResize.fnArr    = onResize.fnArr || [];
    onResize.fnArr.push([fn, args]);

    onResize.loop   = function() {
        $.each(onResize.fnArr, function(index, fnWithArgs) {
            fnWithArgs[0].apply(undefined, fnWithArgs[1]);
        });
    };

    $(window).on('resize', function(e) {
        window.clearTimeout(onResize.timeout);
        onResize.timeout    = window.setTimeout("onResize.loop();", 300);
    });
};

Here is the usage:

var testFn  = function(arg1, arg2) {
    console.log('[testFn] arg1: '+arg1);
    console.log('[testFn] arg2: '+arg2);
};

// document ready
$(function() {
    onResize(testFn, 'argument1', 'argument2');
});

Adding class to element using Angular JS

Try this..

If jQuery is available, angular.element is an alias for the jQuery function.

var app = angular.module('myApp',[]);

app.controller('Ctrl', function($scope) {

    $scope.click=function(){

      angular.element('#div1').addClass("alpha");
    };
});
<div id='div1'>Text</div>
<button ng-click="click()">action</button>

Ref:https://docs.angularjs.org/api/ng/function/angular.element

How to insert a picture into Excel at a specified cell position with VBA

Try this:

With xlApp.ActiveSheet.Pictures.Insert(PicPath)
    With .ShapeRange
        .LockAspectRatio = msoTrue
        .Width = 75
        .Height = 100
    End With
    .Left = xlApp.ActiveSheet.Cells(i, 20).Left
    .Top = xlApp.ActiveSheet.Cells(i, 20).Top
    .Placement = 1
    .PrintObject = True
End With

It's better not to .select anything in Excel, it is usually never necessary and slows down your code.

Java 8 stream map to list of keys sorted by values

Here is the simple solution with StreamEx

EntryStream.of(countByType).sortedBy(e -> e.getValue()).keys().toList();

Second line in li starts under the bullet after CSS-reset

Here is a good example -

ul li{
    list-style-type: disc;
    list-style-position: inside;
    padding: 10px 0 10px 20px;
    text-indent: -1em;
}

Working Demo: http://jsfiddle.net/d9VNk/

Get an object's class name at runtime

You need to first cast the instance to any because Function's type definition does not have a name property.

class MyClass {
  getName() {
    return (<any>this).constructor.name;
    // OR return (this as any).constructor.name;
  }
}

// From outside the class:
var className = (<any>new MyClass()).constructor.name;
// OR var className = (new MyClass() as any).constructor.name;
console.log(className); // Should output "MyClass"

// From inside the class:
var instance = new MyClass();
console.log(instance.getName()); // Should output "MyClass"

Update:

With TypeScript 2.4 (and potentially earlier) the code can be even cleaner:

class MyClass {
  getName() {
    return this.constructor.name;
  }
}

// From outside the class:
var className = (new MyClass).constructor.name;
console.log(className); // Should output "MyClass"

// From inside the class:
var instance = new MyClass();
console.log(instance.getName()); // Should output "MyClass"

What are all the escape characters?

Java Escape Sequences:

\u{0000-FFFF}  /* Unicode [Basic Multilingual Plane only, see below] hex value 
                  does not handle unicode values higher than 0xFFFF (65535),
                  the high surrogate has to be separate: \uD852\uDF62
                  Four hex characters only (no variable width) */
\b             /* \u0008: backspace (BS) */
\t             /* \u0009: horizontal tab (HT) */
\n             /* \u000a: linefeed (LF) */
\f             /* \u000c: form feed (FF) */
\r             /* \u000d: carriage return (CR) */
\"             /* \u0022: double quote (") */
\'             /* \u0027: single quote (') */
\\             /* \u005c: backslash (\) */
\{0-377}       /* \u0000 to \u00ff: from octal value 
                  1 to 3 octal digits (variable width) */

The Basic Multilingual Plane is the unicode values from 0x0000 - 0xFFFF (0 - 65535). Additional planes can only be specified in Java by multiple characters: the egyptian heiroglyph A054 (laying down dude) is U+1303F / &#77887; and would have to be broken into "\uD80C\uDC3F" (UTF-16) for Java strings. Some other languages support higher planes with "\U0001303F".

matching query does not exist Error in Django

You can use this in your case, it will work fine.

user = UniversityDetails.objects.filter(email=email).first()

This Row already belongs to another table error when trying to add rows?

This isn't the cleanest/quickest/easiest/most elegant solution, but it is a brute force one that I created to get the job done in a similar scenario:

DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();

// Create new DataColumns for dtSpecificOrders that are the same as in "dt"
DataColumn dcID = new DataColumn("ID", typeof(int));
DataColumn dcName = new DataColumn("Name", typeof(string));
dtSpecificOrders.Columns.Add(dtID);
dtSpecificOrders.Columns.Add(dcName);

DataRow[] orderRows = dt.Select("CustomerID = 2");

foreach (DataRow dr in orderRows)
{
    DataRow myRow = dtSpecificOrders.NewRow();  // <-- create a brand-new row
    myRow[dcID] = int.Parse(dr["ID"]);
    myRow[dcName] = dr["Name"].ToString();
    dtSpecificOrders.Rows.Add(myRow);   // <-- this will add the new row
}

The names in the DataColumns must match those in your original table for it to work. I just used "ID" and "Name" as examples.

Parse JSON response using jQuery

jQuery.ajax({
            type: 'GET',
            url: "../struktur2/load.php",
            async: false,
            contentType: "application/json",
            dataType: 'json',
            success: function(json) {
              items = json;
            },
            error: function(e) {
              console.log("jQuery error message = "+e.message);
            }
        });

Why do people say that Ruby is slow?

The answer is simple: people say ruby is slow because it is slow based on measured comparisons to other languages. Bear in mind, though, "slow" is relative. Often, ruby and other "slow" languages are plenty fast enough.

How could I create a list in c++?

Create list using C++ templates

i.e

template <class T> struct Node 
{
    T data;
    Node * next;
};
    
template <class T> class List 
{
    Node<T> *head,*tail;
        
    public: 
        void push(T const&);  // push element 
        void pop();           // pop element 
        bool empty()          // return true if empty. 
}; 

Then you can write the code like:

List<MyClass>;

The type T is not dynamic in run time.It is only for the compile time.

For complete example click here.

For C++ templates tutorial click here.

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will allow the user to copy text from it. Disabled will not.

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

The problem is in this method:

  public static byte[] encrypt(String toEncrypt) throws Exception{

This is the method signature which pretty much says:

  • what the method name is: encrypt
  • what parameter it receives: a String named toEncrypt
  • its access modifier: public static
  • and if it may or not throw an exception when invoked.

In this case the method signature says that when invoked this method "could" potentially throw an exception of type "Exception".

    ....
    concatURL = padString(concatURL, ' ', 16);
    byte[] encrypted = encrypt(concatURL); <-- HERE!!!!!
    String encryptedString = bytesToHex(encrypted);
    content.removeAll();
    ......

So the compilers is saying: Either you surround that with a try/catch construct or you declare the method ( where is being used ) to throw "Exception" it self.

The real problem is the "encrypt" method definition. No method should ever return "Exception", because it is too generic and may hide some other kinds of exception better is to have an specific exception.

Try this:

public static byte[] encrypt(String toEncrypt) {
    try{
      String plaintext = toEncrypt;
      String key = "01234567890abcde";
      String iv = "fedcba9876543210";

      SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
      IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

      Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
      byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());

      return encrypted;
    } catch ( NoSuchAlgorithmException nsae ) { 
        // What can you do if the algorithm doesn't exists??
        // this usually won't happen because you would test 
        // your code before shipping. 
        // So in this case is ok to transform to another kind 
        throw new IllegalStateException( nsae );
    } catch ( NoSuchPaddingException nspe ) { 
       // What can you do when there is no such padding ( whatever that means ) ??
       // I guess not much, in either case you won't be able to encrypt the given string
        throw new IllegalStateException( nsae );
    }
    // line 109 won't say it needs a return anymore.
  }

Basically in this particular case you should make sure the cryptography package is available in the system.

Java needs an extension for the cryptography package, so, the exceptions are declared as "checked" exceptions. For you to handle when they are not present.

In this small program you cannot do anything if the cryptography package is not available, so you check that at "development" time. If those exceptions are thrown when your program is running is because you did something wrong in "development" thus a RuntimeException subclass is more appropriate.

The last line don't need a return statement anymore, in the first version you were catching the exception and doing nothing with it, that's wrong.

try { 
    // risky code ... 
} catch( Exception e ) { 
    // a bomb has just exploited
    // you should NOT ignore it 
} 

// The code continues here, but what should it do???

If the code is to fail, it is better to Fail fast

Here are some related answers:

Populating a data frame in R in a loop

this works too.

df = NULL
for (k in 1:10)
    {
       x = 1
       y = 2
       z = 3
       df = rbind(df, data.frame(x,y,z))
     }

output will look like this

df #enter

x y z #col names
1 2 3

How to print a list with integers without the brackets, commas and no quotes?

You can convert it to a string, and then to an int:

print(int("".join(str(x) for x in [7,7,7,7])))

Difference between HttpModule and HttpClientModule

There is a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

A reason for existing

When you use HttpClient with Observable, you have to use .subscribe(x=>...) in the rest of your code.

This is because Observable<HttpResponse<T>> is tied to HttpResponse.

This tightly couples the http layer with the rest of your code.

This library encapsulates the .subscribe(x => ...) part and exposes only the data and error through your Models.

With strongly-typed callbacks, you only have to deal with your Models in the rest of your code.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the getRaceInfo API called as shown below.

  ngOnInit() {    
    this.service.getRaceInfo(response => this.result = response.result,
                                error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Also, you can still use the traditional route and return Observable<HttpResponse<T>> from Service API.

Why does the C++ STL not provide any "tree" containers?

The STL's philosophy is that you choose a container based on guarantees and not based on how the container is implemented. For example, your choice of container may be based on a need for fast lookups. For all you care, the container may be implemented as a unidirectional list -- as long as searching is very fast you'd be happy. That's because you're not touching the internals anyhow, you're using iterators or member functions for the access. Your code is not bound to how the container is implemented but to how fast it is, or whether it has a fixed and defined ordering, or whether it is efficient on space, and so on.

MySQL update CASE WHEN/THEN/ELSE

Try this

UPDATE `table` SET `uid` = CASE
    WHEN id = 1 THEN 2952
    WHEN id = 2 THEN 4925
    WHEN id = 3 THEN 1592
    ELSE `uid`
    END
WHERE id  in (1,2,3)

How can I refresh a page with jQuery?

If you are using jQuery and want to refresh, then try adding your jQuery in a javascript function:

I wanted to hide an iframe from a page when clicking oh an h3, for me it worked but I wasn't able to click the item that allowed me to view the iframe to begin with unless I refreshed the browser manually...not ideal.

I tried the following:

var hide = () => {
    $("#frame").hide();//jQuery
    location.reload(true);//javascript
};

Mixing plain Jane javascript with your jQuery should work.

// code where hide (where location.reload was used)function was integrated, below    
    iFrameInsert = () => {
        var file = `Fe1FVoW0Nt4`;
        $("#frame").html(`<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/${file}\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe><h3>Close Player</h3>`);
        $("h3").enter code hereclick(hide);
}

// View Player 
$("#id-to-be-clicked").click(iFrameInsert);

Django CSRF check failing with an Ajax POST request

The issue is because django is expecting the value from the cookie to be passed back as part of the form data. The code from the previous answer is getting javascript to hunt out the cookie value and put it into the form data. Thats a lovely way of doing it from a technical point of view, but it does look a bit verbose.

In the past, I have done it more simply by getting the javascript to put the token value into the post data.

If you use {% csrf_token %} in your template, you will get a hidden form field emitted that carries the value. But, if you use {{ csrf_token }} you will just get the bare value of the token, so you can use this in javascript like this....

csrf_token = "{{ csrf_token }}";

Then you can include that, with the required key name in the hash you then submit as the data to the ajax call.

Android Closing Activity Programmatically

You Can use just finish(); everywhere after Activity Start for clear that Activity from Stack.

How do I use WebRequest to access an SSL encrypted site using https?

You're doing it the correct way but users may be providing urls to sites that have invalid SSL certs installed. You can ignore those cert problems if you put this line in before you make the actual web request:

ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

where AcceptAllCertifications is defined as

public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

Numpy: Creating a complex array from 2 real ones?

I use the following method:

import numpy as np

real = np.ones((2, 3))
imag = 2*np.ones((2, 3))

complex = np.vectorize(complex)(real, imag)
# OR
complex = real + 1j*imag

auto refresh for every 5 mins

Page should be refresh auto using meta tag

<meta http-equiv="Refresh" content="60"> 

content value in seconds.after one minute page should be refresh

chai test array equality doesn't work as expected

import chai from 'chai';
const arr1 = [2, 1];
const arr2 = [2, 1];
chai.expect(arr1).to.eql(arr2); // Will pass. `eql` is data compare instead of object compare.

How to find out when an Oracle table was updated the last time

I'm really late to this party but here's how I did it:

SELECT SCN_TO_TIMESTAMP(MAX(ora_rowscn)) from myTable;

It's close enough for my purposes.

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

I got the same error in the same tutorial because I had forgot the export keyword for the interface.

Easy way to export multiple data.frame to multiple Excel worksheets

for a lapply-friendly version..

library(data.table)
library(xlsx)

path2txtlist <- your.list.of.txt.files
wb <- createWorkbook()
lapply(seq_along(path2txtlist), function (j) {
sheet <- createSheet(wb, paste("sheetname", j))
addDataFrame(fread(path2txtlist[j]), sheet=sheet, startColumn=1, row.names=FALSE)
})

saveWorkbook(wb, "My_File.xlsx")

Process list on Linux via Python

from psutil import process_iter
from termcolor import colored

names = []
ids = []

x = 0
z = 0
k = 0
for proc in process_iter():
    name = proc.name()
    y = len(name)
    if y>x:
        x = y
    if y<x:
        k = y
    id = proc.pid
    names.insert(z, name)
    ids.insert(z, id)
    z += 1

print(colored("Process Name", 'yellow'), (x-k-5)*" ", colored("Process Id", 'magenta'))
for b in range(len(names)-1):
    z = x
    print(colored(names[b], 'cyan'),(x-len(names[b]))*" ",colored(ids[b], 'white'))

CSS way to horizontally align table

This should work:

<div style="text-align:center;">
  <table style="margin: 0 auto;">
    <!-- table markup here. -->
  </table>
</div>

How can I change CSS display none or block property using jQuery?

(function($){
    $.fn.displayChange = function(fn){
        $this = $(this);
        var state = {};
        state.old = $this.css('display');
        var intervalID = setInterval(function(){
            if( $this.css('display') != state.old ){
                state.change = $this.css('display');
                fn(state);
                state.old = $this.css('display');
            }
        }, 100);        
    }

    $(function(){
        var tag = $('#content');
        tag.displayChange(function(obj){
            console.log(obj);
        });  
    })   
})(jQuery);

How can I create a simple message box in Python?

A recent message box version is the prompt_box module. It has two packages: alert and message. Message gives you greater control over the box, but takes longer to type up.

Example Alert code:

import prompt_box

prompt_box.alert('Hello') #This will output a dialog box with title Neutrino and the 
#text you inputted. The buttons will be Yes, No and Cancel

Example Message code:

import prompt_box

prompt_box.message('Hello', 'Neutrino', 'You pressed yes', 'You pressed no', 'You 
pressed cancel') #The first two are text and title, and the other three are what is 
#printed when you press a certain button

How do I get a div to float to the bottom of its container?

If you set the parent element as position:relative, you can set the child to the bottom setting position:absolute; and bottom:0;

_x000D_
_x000D_
#outer {_x000D_
  width:10em;_x000D_
  height:10em;_x000D_
  background-color:blue;_x000D_
  position:relative; _x000D_
}_x000D_
_x000D_
#inner {_x000D_
  position:absolute;_x000D_
  bottom:0;_x000D_
  background-color:white; _x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <h1>done</h1>_x000D_
  </div>_x000D_
</div>_x000D_
  
_x000D_
_x000D_
_x000D_

Alternative to google finance api

I followed the top answer and started looking at yahoo finance. Their API can be accessed a number of different ways, but I found a nice reference for getting stock info as a CSV here: http://www.jarloo.com/

Using that I wrote this script. I'm not really a ruby guy but this might help you hack something together. I haven't come up with variable names for all the fields yahoo offers yet, so you can fill those in if you need them.

Here's the usage

TICKERS_SP500 = "GICS,CIK,MMM,ABT,ABBV,ACN,ACE,ACT,ADBE,ADT,AES,AET,AFL,AMG,A,GAS,APD,ARG,AKAM,AA,ALXN,ATI,ALLE,ADS,ALL,ALTR,MO,AMZN,AEE,AAL,AEP,AXP,AIG,AMT,AMP,ABC,AME,AMGN,APH,APC,ADI,AON,APA,AIV,AAPL,AMAT,ADM,AIZ,T,ADSK,ADP,AN,AZO,AVGO,AVB,AVY,BHI,BLL,BAC,BK,BCR,BAX,BBT,BDX,BBBY,BBY,BIIB,BLK,HRB,BA,BWA,BXP,BSX,BMY,BRCM,BFB,CHRW,CA,CVC,COG,CAM,CPB,COF,CAH,HSIC,KMX,CCL,CAT,CBG,CBS,CELG,CNP,CTL,CERN,CF,SCHW,CHK,CVX,CMG,CB,CI,XEC,CINF,CTAS,CSCO,C,CTXS,CLX,CME,CMS,COH,KO,CCE,CTSH,CL,CMA,CSC,CAG,COP,CNX,ED,STZ,GLW,COST,CCI,CSX,CMI,CVS,DHI,DHR,DRI,DVA,DE,DLPH,DAL,XRAY,DVN,DO,DTV,DFS,DG,DLTR,D,DOV,DOW,DPS,DTE,DD,DUK,DNB,ETFC,EMN,ETN,EBAY,ECL,EIX,EW,EA,EMC,EMR,ENDP,ESV,ETR,EOG,EQT,EFX,EQIX,EQR,ESS,EL,ES,EXC,EXPE,EXPD,ESRX,XOM,FFIV,FB,FDO,FAST,FDX,FIS,FITB,FSLR,FE,FISV,FLIR,FLS,FLR,FMC,FTI,F,FOSL,BEN,FCX,FTR,GME,GCI,GPS,GRMN,GD,GE,GGP,GIS,GM,GPC,GNW,GILD,GS,GT,GOOG,GWW,HAL,HBI,HOG,HAR,HRS,HIG,HAS,HCA,HCP,HCN,HP,HES,HPQ,HD,HON,HRL,HSP,HST,HCBK,HUM,HBAN,ITW,IR,TEG,INTC,ICE,IBM,IP,IPG,IFF,INTU,ISRG,IVZ,IRM,JEC,JNJ,JCI,JOY,JPM,JNPR,KSU,K,KEY,GMCR,KMB,KIM,KMI,KLAC,KSS,KRFT,KR,LB,LLL,LH,LRCX,LM,LEG,LEN,LVLT,LUK,LLY,LNC,LLTC,LMT,L,LO,LOW,LYB,MTB,MAC,M,MNK,MRO,MPC,MAR,MMC,MLM,MAS,MA,MAT,MKC,MCD,MHFI,MCK,MJN,MWV,MDT,MRK,MET,KORS,MCHP,MU,MSFT,MHK,TAP,MDLZ,MON,MNST,MCO,MS,MOS,MSI,MUR,MYL,NDAQ,NOV,NAVI,NTAP,NFLX,NWL,NFX,NEM,NWSA,NEE,NLSN,NKE,NI,NE,NBL,JWN,NSC,NTRS,NOC,NRG,NUE,NVDA,ORLY,OXY,OMC,OKE,ORCL,OI,PCAR,PLL,PH,PDCO,PAYX,PNR,PBCT,POM,PEP,PKI,PRGO,PFE,PCG,PM,PSX,PNW,PXD,PBI,PCL,PNC,RL,PPG,PPL,PX,PCP,PCLN,PFG,PG,PGR,PLD,PRU,PEG,PSA,PHM,PVH,QEP,PWR,QCOM,DGX,RRC,RTN,RHT,REGN,RF,RSG,RAI,RHI,ROK,COL,ROP,ROST,RCL,R,CRM,SNDK,SCG,SLB,SNI,STX,SEE,SRE,SHW,SIAL,SPG,SWKS,SLG,SJM,SNA,SO,LUV,SWN,SE,STJ,SWK,SPLS,SBUX,HOT,STT,SRCL,SYK,STI,SYMC,SYY,TROW,TGT,TEL,TE,THC,TDC,TSO,TXN,TXT,HSY,TRV,TMO,TIF,TWX,TWC,TJX,TMK,TSS,TSCO,RIG,TRIP,FOXA,TSN,TYC,USB,UA,UNP,UNH,UPS,URI,UTX,UHS,UNM,URBN,VFC,VLO,VAR,VTR,VRSN,VZ,VRTX,VIAB,V,VNO,VMC,WMT,WBA,DIS,WM,WAT,ANTM,WFC,WDC,WU,WY,WHR,WFM,WMB,WIN,WEC,WYN,WYNN,XEL,XRX,XLNX,XL,XYL,YHOO,YUM,ZMH,ZION,ZTS,SAIC,AP"

AllData = loadStockInfo(TICKERS_SP500, allParameters())

SpecificData = loadStockInfo("GOOG,CIK", "ask,dps")

loadStockInfo returns a hash, such that SpecificData["GOOG"]["name"] is "Google Inc."

Finally, the actual code to run that...

require 'net/http'

# Jack Franzen & Garin Bedian
# Based on http://www.jarloo.com/yahoo_finance/

$parametersData = Hash[[

    ["symbol", ["s", "Symbol"]],
    ["ask", ["a", "Ask"]],
    ["divYield", ["y", "Dividend Yield"]],
    ["bid", ["b", "Bid"]],
    ["dps", ["d", "Dividend per Share"]],
    #["noname", ["b2", "Ask (Realtime)"]],
    #["noname", ["r1", "Dividend Pay Date"]],
    #["noname", ["b3", "Bid (Realtime)"]],
    #["noname", ["q", "Ex-Dividend Date"]],
    #["noname", ["p", "Previous Close"]],
    #["noname", ["o", "Open"]],
    #["noname", ["c1", "Change"]],
    #["noname", ["d1", "Last Trade Date"]],
    #["noname", ["c", "Change &amp; Percent Change"]],
    #["noname", ["d2", "Trade Date"]],
    #["noname", ["c6", "Change (Realtime)"]],
    #["noname", ["t1", "Last Trade Time"]],
    #["noname", ["k2", "Change Percent (Realtime)"]],
    #["noname", ["p2", "Change in Percent"]],
    #["noname", ["c8", "After Hours Change (Realtime)"]],
    #["noname", ["m5", "Change From 200 Day Moving Average"]],
    #["noname", ["c3", "Commission"]],
    #["noname", ["m6", "Percent Change From 200 Day Moving Average"]],
    #["noname", ["g", "Day’s Low"]],
    #["noname", ["m7", "Change From 50 Day Moving Average"]],
    #["noname", ["h", "Day’s High"]],
    #["noname", ["m8", "Percent Change From 50 Day Moving Average"]],
    #["noname", ["k1", "Last Trade (Realtime) With Time"]],
    #["noname", ["m3", "50 Day Moving Average"]],
    #["noname", ["l", "Last Trade (With Time)"]],
    #["noname", ["m4", "200 Day Moving Average"]],
    #["noname", ["l1", "Last Trade (Price Only)"]],
    #["noname", ["t8", "1 yr Target Price"]],
    #["noname", ["w1", "Day’s Value Change"]],
    #["noname", ["g1", "Holdings Gain Percent"]],
    #["noname", ["w4", "Day’s Value Change (Realtime)"]],
    #["noname", ["g3", "Annualized Gain"]],
    #["noname", ["p1", "Price Paid"]],
    #["noname", ["g4", "Holdings Gain"]],
    #["noname", ["m", "Day’s Range"]],
    #["noname", ["g5", "Holdings Gain Percent (Realtime)"]],
    #["noname", ["m2", "Day’s Range (Realtime)"]],
    #["noname", ["g6", "Holdings Gain (Realtime)"]],
    #["noname", ["k", "52 Week High"]],
    #["noname", ["v", "More Info"]],
    #["noname", ["j", "52 week Low"]],
    #["noname", ["j1", "Market Capitalization"]],
    #["noname", ["j5", "Change From 52 Week Low"]],
    #["noname", ["j3", "Market Cap (Realtime)"]],
    #["noname", ["k4", "Change From 52 week High"]],
    #["noname", ["f6", "Float Shares"]],
    #["noname", ["j6", "Percent Change From 52 week Low"]],
    ["name", ["n", "Company Name"]],
    #["noname", ["k5", "Percent Change From 52 week High"]],
    #["noname", ["n4", "Notes"]],
    #["noname", ["w", "52 week Range"]],
    #["noname", ["s1", "Shares Owned"]],
    #["noname", ["x", "Stock Exchange"]],
    #["noname", ["j2", "Shares Outstanding"]],
    #["noname", ["v", "Volume"]],
    #["noname", ["a5", "Ask Size"]],
    #["noname", ["b6", "Bid Size"]],
    #["noname", ["k3", "Last Trade Size"]],
    #["noname", ["t7", "Ticker Trend"]],
    #["noname", ["a2", "Average Daily Volume"]],
    #["noname", ["t6", "Trade Links"]],
    #["noname", ["i5", "Order Book (Realtime)"]],
    #["noname", ["l2", "High Limit"]],
    #["noname", ["e", "Earnings per Share"]],
    #["noname", ["l3", "Low Limit"]],
    #["noname", ["e7", "EPS Estimate Current Year"]],
    #["noname", ["v1", "Holdings Value"]],
    #["noname", ["e8", "EPS Estimate Next Year"]],
    #["noname", ["v7", "Holdings Value (Realtime)"]],
    #["noname", ["e9", "EPS Estimate Next Quarter"]],
    #["noname", ["s6", "evenue"]],
    #["noname", ["b4", "Book Value"]],
    #["noname", ["j4", "EBITDA"]],
    #["noname", ["p5", "Price / Sales"]],
    #["noname", ["p6", "Price / Book"]],
    #["noname", ["r", "P/E Ratio"]],
    #["noname", ["r2", "P/E Ratio (Realtime)"]],
    #["noname", ["r5", "PEG Ratio"]],
    #["noname", ["r6", "Price / EPS Estimate Current Year"]],
    #["noname", ["r7", "Price / EPS Estimate Next Year"]],
    #["noname", ["s7", "Short Ratio"]

]]

def replaceCommas(data)
    s = ""
    inQuote = false
    data.split("").each do |a|
        if a=='"'
            inQuote = !inQuote
            s += '"'
        elsif !inQuote && a == ","
            s += "#"
        else
            s += a
        end
    end
    return s
end

def allParameters()
    s = ""
    $parametersData.keys.each do |i|
        s  = s + i + ","
    end
    return s
end

def prepareParameters(parametersText)
    pt = parametersText.split(",")
    if !pt.include? 'symbol'; pt.push("symbol"); end;
    if !pt.include? 'name'; pt.push("name"); end;
    p = []
    pt.each do |i|
        p.push([i, $parametersData[i][0]])
    end
    return p
end

def prepareURL(tickers, parameters)
    urlParameters = ""
    parameters.each do |i|
        urlParameters += i[1]
    end
    s = "http://download.finance.yahoo.com/d/quotes.csv?"
    s = s + "s=" + tickers + "&"
    s = s + "f=" + urlParameters
    return URI(s)
end

def loadStockInfo(tickers, parametersRaw)
    parameters = prepareParameters(parametersRaw)
    url = prepareURL(tickers, parameters)
    data = Net::HTTP.get(url)
    data = replaceCommas(data)
    h = CSVtoObject(data, parameters)
    logStockObjects(h, true)
end

#parse csv
def printCodes(substring, length)

    a = data.index(substring)
    b = data.byteslice(a, 10)
    puts "printing codes of string: "
    puts b
    puts b.split('').map(&:ord).to_s
end

def CSVtoObject(data, parameters)
    rawData = []
    lineBreaks = data.split(10.chr)
    lineBreaks.each_index do |i|
        rawData.push(lineBreaks[i].split("#"))
    end

    #puts "Found " + rawData.length.to_s + " Stocks"
    #puts "   w/ " + rawData[0].length.to_s + " Fields"

    h = Hash.new("MainHash")
    rawData.each_index do |i|
        o = Hash.new("StockObject"+i.to_s)
        #puts "parsing object" + rawData[i][0]
        rawData[i].each_index do |n|
            #puts "parsing parameter" + n.to_s + " " +parameters[n][0]
            o[ parameters[n][0] ] = rawData[i][n].gsub!(/^\"|\"?$/, '')
        end
        h[o["symbol"]] = o;
    end
    return h
end

def logStockObjects(h, concise)
    h.keys.each do |i|
        if concise
            puts "(" + h[i]["symbol"] + ")\t\t" + h[i]["name"]
        else
            puts ""
            puts h[i]["name"]
            h[i].keys.each do |p|
                puts "    " + $parametersData[p][1] + " : " + h[i][p].to_s
            end
        end
    end
end

Can I return the 'id' field after a LINQ insert?

Try this:

MyContext Context = new MyContext(); 
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;

CharSequence VS String in Java?

I believe it is best to use CharSequence. The reason is that String implements CharSequence, therefore you can pass a String into a CharSequence, HOWEVER you cannot pass a CharSequence into a String, as CharSequence doesn't not implement String. ALSO, in Android the EditText.getText() method returns an Editable, which also implements CharSequence and can be passed easily into one, while not easily into a String. CharSequence handles all!

From io.Reader to string in Go

func copyToString(r io.Reader) (res string, err error) {
    var sb strings.Builder
    if _, err = io.Copy(&sb, r); err == nil {
        res = sb.String()
    }
    return
}

jQuery function to get all unique elements from an array?

You can use a jQuery plugin called Array Utilities to get an array of unique items. It can be done like this:

var distinctArray = $.distinct([1, 2, 2, 3])

distinctArray = [1,2,3]

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

MySQL Error 1215: Cannot add foreign key constraint

i had the same issue, my solution:

Before:

CREATE TABLE EMPRES
( NoFilm smallint NOT NULL

  PRIMARY KEY (NoFilm)

  FOREIGN KEY (NoFilm) REFERENCES cassettes

);

Solution:

CREATE TABLE EMPRES
(NoFilm smallint NOT NULL REFERENCES cassettes,

 PRIMARY KEY (NoFilm)

);

I hope it's help ;)

Using JQuery hover with HTML image map

You should check out this plugin:

https://github.com/kemayo/maphilight

and the demo:

http://davidlynch.org/js/maphilight/docs/demo_usa.html

if anything, you might be able to borrow some code from it to fix yours.

How do I quickly rename a MySQL database (change schema name)?

The simple way

Change to the database directory:

cd /var/lib/mysql/

Shut down MySQL... This is important!

/etc/init.d/mysql stop

Okay, this way doesn't work for InnoDB or BDB-Databases.

Rename database:

mv old-name new-name

...or the table...

cd database/

mv old-name.frm new-name.frm

mv old-name.MYD new-name.MYD

mv old-name.MYI new-name.MYI

Restart MySQL

/etc/init.d/mysql start

Done...

OK, this way doesn't work with InnoDB or BDB databases. In this case you have to dump the database and re-import it.

How to verify CuDNN installation?

How about checking with python code:

from tensorflow.python.platform import build_info as tf_build_info

print(tf_build_info.cudnn_version_number)
# 7 in v1.10.0

Best way to log POST data in Apache?

Use Apache's mod_dumpio. Be careful for obvious reasons.

Note that mod_dumpio stops logging binary payloads at the first null character. For example a multipart/form-data upload of a gzip'd file will probably only show the first few bytes with mod_dumpio.

Also note that Apache might not mention this module in httpd.conf even when it's present in the /modules folder. Just manually adding LoadModule will work fine.

Is there a combination of "LIKE" and "IN" in SQL?

you're stuck with the

WHERE something LIKE 'bla%'
OR something LIKE '%foo%'
OR something LIKE 'batz%'

unless you populate a temp table (include the wild cards in with the data) and join like this:

FROM YourTable                y
    INNER JOIN YourTempTable  t On y.something LIKE t.something

try it out (using SQL Server syntax):

declare @x table (x varchar(10))
declare @y table (y varchar(10))

insert @x values ('abcdefg')
insert @x values ('abc')
insert @x values ('mnop')

insert @y values ('%abc%')
insert @y values ('%b%')

select distinct *
FROM @x x
WHERE x.x LIKE '%abc%' 
   or x.x LIKE '%b%'


select distinct x.*  
FROM @x             x
    INNER JOIN  @y  y On x.x LIKE y.y

OUTPUT:

x
----------
abcdefg
abc

(2 row(s) affected)

x
----------
abc
abcdefg

(2 row(s) affected)

Easy login script without database

FacebookConnect or OpenID are two great options.

Basically, your users login to other sites they are already members of (Facebook, or Google), and then you get confirmation from that site telling you the user is trustworthy - start a session, and they're logged in. No database needed (unless you want to associate more data to their account).

Can you disable tabs in Bootstrap?

You can disable a tab in bootstrap 4 by adding class disabled to the child of nav-item as follows

<li class="nav-item">
    <a class="nav-link disabled" data-toggle="tab" href="#messages7" role="tab" aria-expanded="false">
        <i class="icofont icofont-ui-message"></i>Home</a>
    <div class="slide"></div>
</li>

Disable Copy or Paste action for text box?

Best way to do this is to add a data attribute to the field (textbox) where you want to avoid the cut,copy and paste.

Just create a method for the same which is as follows :-

function ignorePaste() {

$("[data-ignorepaste]").bind("cut copy paste", function (e) {
            e.preventDefault(); //prevent the default behaviour 
        });

};

Then once when you add the above code simply add the data attribute to the field where you want to ignore cut copy paste. in our case your add a data attribute to confirm email text box as below :-

Confirm Email: <input type="textbox" id= "confirmEmail" data-ignorepaste=""/>

Call the method ignorePaste()

So in this way you will be able to use this throughout the application, all you need to do is just add the data attribute where you want to ignore cut copy paste

https://jsfiddle.net/0ac6pkbf/21/

angular 2 ngIf and CSS transition/animation

    trigger('slideIn', [
      state('*', style({ 'overflow-y': 'hidden' })),
      state('void', style({ 'overflow-y': 'hidden' })),
      transition('* => void', [
        style({ height: '*' }),
        animate(250, style({ height: 0 }))
      ]),
      transition('void => *', [
        style({ height: '0' }),
        animate(250, style({ height: '*' }))
      ])
    ])

Angular pass callback function to child component as @Input similar to AngularJS way

Another alternative.

The OP asked a way to use a callback. In this case he was referring specifically to a function that process an event (in his example: a click event), which shall be treated as the accepted answer from @serginho suggests: with @Output and EventEmitter.

However, there is a difference between a callback and an event: With a callback your child component can retrieve some feedback or information from the parent, but an event only can inform that something happened without expect any feedback.

There are use cases where a feedback is necessary, ex. get a color, or a list of elements that the component needs to handle. You can use bound functions as some answers have suggested, or you can use interfaces (that's always my preference).

Example

Let's suppose you have a generic component that operates over a list of elements {id, name} that you want to use with all your database tables that have these fields. This component should:

  • retrieve a range of elements (page) and show them in a list
  • allow remove an element
  • inform that an element was clicked, so the parent can take some action(s).
  • allow retrieve the next page of elements.

Child Component

Using normal binding we would need 1 @Input() and 3 @Output() parameters (but without any feedback from the parent). Ex. <list-ctrl [items]="list" (itemClicked)="click($event)" (itemRemoved)="removeItem($event)" (loadNextPage)="load($event)" ...>, but creating an interface we will need only one @Input():

import {Component, Input, OnInit} from '@angular/core';

export interface IdName{
  id: number;
  name: string;
}

export interface IListComponentCallback<T extends IdName> {
    getList(page: number, limit: number): Promise< T[] >;
    removeItem(item: T): Promise<boolean>;
    click(item: T): void;
}

@Component({
    selector: 'list-ctrl',
    template: `
      <button class="item" (click)="loadMore()">Load page {{page+1}}</button>
      <div class="item" *ngFor="let item of list">
          <button (click)="onDel(item)">DEL</button>
          <div (click)="onClick(item)">
            Id: {{item.id}}, Name: "{{item.name}}"
          </div>
      </div>
    `,
    styles: [`
      .item{ margin: -1px .25rem 0; border: 1px solid #888; padding: .5rem; width: 100%; cursor:pointer; }
      .item > button{ float: right; }
      button.item{margin:.25rem;}
    `]
})
export class ListComponent implements OnInit {
    @Input() callback: IListComponentCallback<IdName>; // <-- CALLBACK
    list: IdName[];
    page = -1; 
    limit = 10;

    async ngOnInit() {
      this.loadMore();
    }
    onClick(item: IdName) {
      this.callback.click(item);   
    }
    async onDel(item: IdName){ 
        if(await this.callback.removeItem(item)) {
          const i = this.list.findIndex(i=>i.id == item.id);
          this.list.splice(i, 1);
        }
    }
    async loadMore(){
      this.page++;
      this.list = await this.callback.getList(this.page, this.limit); 
    }
}

Parent Component

Now we can use the list component in the parent.

import { Component } from "@angular/core";
import { SuggestionService } from "./suggestion.service";
import { IdName, IListComponentCallback } from "./list.component";

type Suggestion = IdName;

@Component({
  selector: "my-app",
  template: `
    <list-ctrl class="left" [callback]="this"></list-ctrl>
    <div class="right" *ngIf="msg">{{ msg }}<br/><pre>{{item|json}}</pre></div>
  `,
  styles:[`
    .left{ width: 50%; }
    .left,.right{ color: blue; display: inline-block; vertical-align: top}
    .right{max-width:50%;overflow-x:scroll;padding-left:1rem}
  `]
})
export class ParentComponent implements IListComponentCallback<Suggestion> {
  msg: string;
  item: Suggestion;

  constructor(private suggApi: SuggestionService) {}

  getList(page: number, limit: number): Promise<Suggestion[]> {
    return this.suggApi.getSuggestions(page, limit);
  }
  removeItem(item: Suggestion): Promise<boolean> {
    return this.suggApi.removeSuggestion(item.id)
      .then(() => {
        this.showMessage('removed', item);
        return true;
      })
      .catch(() => false);
  }
  click(item: Suggestion): void {
    this.showMessage('clicked', item);
  }
  private showMessage(msg: string, item: Suggestion) {
    this.item = item;
    this.msg = 'last ' + msg;
  }
}

Note that the <list-ctrl> receives this (parent component) as the callback object. One additional advantage is that it's not required to send the parent instance, it can be a service or any object that implements the interface if your use case allows it.

The complete example is on this stackblitz.

Pass multiple arguments into std::thread

If you're getting this, you may have forgotten to put #include <thread> at the beginning of your file. OP's signature seems like it should work.

Show Console in Windows Application?

Check this source code out. All commented code – used to create a console in a Windows app. Uncommented – to hide the console in a console app. From here. (Previously here.) Project reg2run.

// Copyright (C) 2005-2015 Alexander Batishchev (abatishchev at gmail.com)

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace Reg2Run
{
    static class ManualConsole
    {
        #region DllImport
        /*
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool AllocConsole();
        */

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        /*
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        private static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)]string fileName, [MarshalAs(UnmanagedType.I4)]int desiredAccess, [MarshalAs(UnmanagedType.I4)]int shareMode, IntPtr securityAttributes, [MarshalAs(UnmanagedType.I4)]int creationDisposition, [MarshalAs(UnmanagedType.I4)]int flagsAndAttributes, IntPtr templateFile);
        */

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool FreeConsole();

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        private static extern IntPtr GetStdHandle([MarshalAs(UnmanagedType.I4)]int nStdHandle);

        /*
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetStdHandle(int nStdHandle, IntPtr handle);
        */
        #endregion

        #region Methods
        /*
        public static void Create()
        {
            var ptr = GetStdHandle(-11);
            if (!AllocConsole())
            {
                throw new Win32Exception("AllocConsole");
            }
            ptr = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
            if (!SetStdHandle(-11, ptr))
            {
                throw new Win32Exception("SetStdHandle");
            }
            var newOut = new StreamWriter(Console.OpenStandardOutput());
            newOut.AutoFlush = true;
            Console.SetOut(newOut);
            Console.SetError(newOut);
        }
        */

        public static void Hide()
        {
            var ptr = GetStdHandle(-11);
            if (!CloseHandle(ptr))
            {
                throw new Win32Exception();
            }
            ptr = IntPtr.Zero;
            if (!FreeConsole())
            {
                throw new Win32Exception();
            }
        }
        #endregion
    }
}

How do you render primitives as wireframes in OpenGL?

From http://cone3d.gamedev.net/cgi-bin/index.pl?page=tutorials/ogladv/tut5

// Turn on wireframe mode
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);

// Draw the box
DrawBox();

// Turn off wireframe mode
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);