Programs & Examples On #Peripherals

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

I tried with and it works

use mysql; # use mysql table
update user set authentication_string="" where User='root'; 

flush privileges;
quit;

How to use an environment variable inside a quoted string in Bash

If unsure, you might use the 'cols' request on the terminal, and forget COLUMNS:

COLS=$(tput cols)

NullInjectorError: No provider for AngularFirestore

Adding AngularFirestoreModule.enablePersistence() in import section resolved my issue:

imports: [
    BrowserModule, AngularFireModule, 
    AngularFireModule.initializeApp(config),
    AngularFirestoreModule.enablePersistence()
]

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

remove all variables except functions

You can use the following command to clear out ALL variables. Be careful because it you cannot get your variables back.

rm(list=ls(all=TRUE))

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

1) When the user logs out (Forms signout in Action) I want to redirect to a login page.

public ActionResult Logout() {
    //log out the user
    return RedirectToAction("Login");
}

2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)

Why would you want to redirect from a controller init?

the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:

public ActionResult Index() {
    return RedirectToAction("whateverAction", "whateverController");
}

How to convert color code into media.brush?

In code, you need to explicitly create a Brush instance:

Fill = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0x90))

Change tab bar item selected color in a storyboard

Somehow we are not able to change the Tab Bar selected item Tint color using storyboard alone, hence I added below code in my ViewDidLoad, hope this helps.

[[UITabBar appearance] setTintColor:[UIColor whiteColor]]; 

How to implement debounce in Vue2?

Although pretty much all answers here are already correct, if anyone is in search of a quick solution I have a directive for this. https://www.npmjs.com/package/vue-lazy-input

It applies to @input and v-model, supports custom components and DOM elements, debounce and throttle.

_x000D_
_x000D_
Vue.use(VueLazyInput)_x000D_
  new Vue({_x000D_
    el: '#app', _x000D_
    data() {_x000D_
      return {_x000D_
        val: 42_x000D_
      }_x000D_
    },_x000D_
    methods:{_x000D_
      onLazyInput(e){_x000D_
        console.log(e.target.value)_x000D_
      }_x000D_
    }_x000D_
  })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<script src="https://unpkg.com/lodash/lodash.min.js"></script><!-- dependency -->_x000D_
<script src="https://unpkg.com/vue-lazy-input@latest"></script> _x000D_
_x000D_
<div id="app">_x000D_
  <input type="range" v-model="val" @input="onLazyInput" v-lazy-input /> {{val}}_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert "0" and "1" to false and true

If you want the conversion to always succeed, probably the best way to convert the string would be to consider "1" as true and anything else as false (as Kevin does). If you wanted the conversion to fail if anything other than "1" or "0" is returned, then the following would suffice (you could put it in a helper method):

if (returnValue == "1")
{
    return true;
}
else if (returnValue == "0")
{
    return false;
}
else
{
    throw new FormatException("The string is not a recognized as a valid boolean value.");
}

getting the table row values with jquery

All Elements

$('#tabla > tbody  > tr').each(function() {
    $(this).find("td:gt(0)").each(function(){
       alert($(this).html());
       });
});

Change the borderColor of the TextBox

With PictureBox1
    .Visible = False
    .Width = TextBox1.Width + 4
    .Height = TextBox1.Height + 4
    .Left = TextBox1.Left - 2
    .Top = TextBox1.Top - 2
    .SendToBack()
    .Visible = True
End With

How to get the previous URL in JavaScript?

<script type="text/javascript">
    document.write(document.referrer);
</script>

document.referrer serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.

It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.

How to reset or change the passphrase for a GitHub SSH key?

You can change the passphrase for your private key by doing:

ssh-keygen -f ~/.ssh/id_rsa -p

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

i followed all the suggested steps, in particular the ones provided from ios_dev but my iPhone was not recognized from Xcode and i was not able to debug over WiFi. Right click on the left panel over my iDevice in "Devices and Simulators" window, then "Connect via IP Address...", inserted the iPhone IP and now it correctly works

SQL: parse the first, middle and last name from a fullname field

This query is working fine.

SELECT name
    ,Ltrim(SubString(name, 1, Isnull(Nullif(CHARINDEX(' ', name), 0), 1000))) AS FirstName
    ,Ltrim(SUBSTRING(name, CharIndex(' ', name), CASE 
                WHEN (CHARINDEX(' ', name, CHARINDEX(' ', name) + 1) - CHARINDEX(' ', name)) <= 0
                    THEN 0
                ELSE CHARINDEX(' ', name, CHARINDEX(' ', name) + 1) - CHARINDEX(' ', name)
                END)) AS MiddleName
    ,Ltrim(SUBSTRING(name, Isnull(Nullif(CHARINDEX(' ', name, Charindex(' ', name) + 1), 0), CHARINDEX(' ', name)), CASE 
                WHEN Charindex(' ', name) = 0
                    THEN 0
                ELSE LEN(name)
                END)) AS LastName
FROM yourtableName

Recommended add-ons/plugins for Microsoft Visual Studio

Visual Assist: you cannot live without it!

Binding ItemsSource of a ComboBoxColumn in WPF DataGrid

Your ComboBox is trying to bind to bind to GridItem[x].CompanyItems, which doesn't exist.

Your RelativeBinding is close, however it needs to bind to DataContext.CompanyItems because Window.CompanyItems does not exist

Is there a 'box-shadow-color' property?

No:

http://www.w3.org/TR/css3-background/#the-box-shadow

You can verify this in Chrome and Firefox by checking the list of computed styles. Other properties that have shorthand methods (like border-radius) have their variations defined in the spec.

As with most missing "long-hand" CSS properties, CSS variables can solve this problem:

#el {
    --box-shadow-color: palegoldenrod;
    box-shadow: 1px 2px 3px var(--box-shadow-color);
}

#el:hover {
    --box-shadow-color: goldenrod;
}

How to write LDAP query to test if user is member of a group?

I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".

Does Java SE 8 have Pairs or Tuples?

Sadly, Java 8 did not introduce pairs or tuples. You can always use org.apache.commons.lang3.tuple of course (which personally I do use in combination with Java 8) or you can create your own wrappers. Or use Maps. Or stuff like that, as is explained in the accepted answer to that question you linked to.


UPDATE: JDK 14 is introducing records as a preview feature. These aren't tuples, but can be used to save many of the same problems. In your specific example from above, that could look something like this:

public class Jdk14Example {
    record CountForIndex(int index, long count) {}

    public static void main(String[] args) {
        boolean [][] directed_acyclic_graph = new boolean[][]{
                {false,  true, false,  true, false,  true},
                {false, false, false,  true, false,  true},
                {false, false, false,  true, false,  true},
                {false, false, false, false, false,  true},
                {false, false, false, false, false,  true},
                {false, false, false, false, false, false}
        };

        System.out.println(
                IntStream.range(0, directed_acyclic_graph.length)
                        .parallel()
                        .mapToObj(i -> {
                            long count = IntStream.range(0, directed_acyclic_graph[i].length)
                                            .filter(j -> directed_acyclic_graph[j][i])
                                            .count();
                            return new CountForIndex(i, count);
                        }
                        )
                        .filter(n -> n.count == 0)
                        .collect(() -> new ArrayList<CountForIndex>(), (c, e) -> c.add(e), (c1, c2) -> c1.addAll(c2))
        );
    }
}

When compiled and run with JDK 14 (at the time of writing, this an early access build) using the --enable-preview flag, you get the following result:

[CountForIndex[index=0, count=0], CountForIndex[index=2, count=0], CountForIndex[index=4, count=0]]

Python dictionary: are keys() and values() always the same order?

Yes, what you observed is indeed a guaranteed property -- keys(), values() and items() return lists in congruent order if the dict is not altered. iterkeys() &c also iterate in the same order as the corresponding lists.

How to make <input type="file"/> accept only these types?

for image write this

<input type=file accept="image/*">

For other, You can use the accept attribute on your form to suggest to the browser to restrict certain types. However, you'll want to re-validate in your server-side code to make sure. Never trust what the client sends you

scale Image in an UIButton to AspectFit?

If you simply want to reduce your button image:

yourButton.contentMode = UIViewContentModeScaleAspectFit;
yourButton.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);

how can I enable scrollbars on the WPF Datagrid?

In my case I had to set MaxHeight and replace IsEnabled="False" by IsReadOnly="True"

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

Press F4 at the project root and select the the root source pressing the source button. It resolved my problem!

for(; ;){
  makeGoodCode();
}

Checking something isEmpty in Javascript?

Here my simplest solution.

Inspired by PHP empty function

_x000D_
_x000D_
function empty(n){_x000D_
 return !(!!n ? typeof n === 'object' ? Array.isArray(n) ? !!n.length : !!Object.keys(n).length : true : false);_x000D_
}_x000D_
_x000D_
//with number_x000D_
console.log(empty(0));        //true_x000D_
console.log(empty(10));       //false_x000D_
_x000D_
//with object_x000D_
console.log(empty({}));       //true_x000D_
console.log(empty({a:'a'}));  //false_x000D_
_x000D_
//with array_x000D_
console.log(empty([]));       //true_x000D_
console.log(empty([1,2]));    //false_x000D_
_x000D_
//with string_x000D_
console.log(empty(''));       //true_x000D_
console.log(empty('a'));      //false
_x000D_
_x000D_
_x000D_

Suppress Scientific Notation in Numpy When Creating Array From Nested List

for 1D and 2D arrays you can use np.savetxt to print using a specific format string:

>>> import sys
>>> x = numpy.arange(20).reshape((4,5))
>>> numpy.savetxt(sys.stdout, x, '%5.2f')
 0.00  1.00  2.00  3.00  4.00
 5.00  6.00  7.00  8.00  9.00
10.00 11.00 12.00 13.00 14.00
15.00 16.00 17.00 18.00 19.00

Your options with numpy.set_printoptions or numpy.array2string in v1.3 are pretty clunky and limited (for example no way to suppress scientific notation for large numbers). It looks like this will change with future versions, with numpy.set_printoptions(formatter=..) and numpy.array2string(style=..).

How to use random in BATCH script?

set /a number=%random% %% [maximum]-[minimum]

example "

set /a number=%random% %% 100-50

will give a random number between 100 and 50. Be sure to only use one percentage sign as the operand if you are not using the line in a batch script!

Passing data into "router-outlet" child components

<router-outlet [node]="..."></router-outlet> 

is just invalid. The component added by the router is added as sibling to <router-outlet> and does not replace it.

See also https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

@Injectable() 
export class NodeService {
  private node:Subject<Node> = new BehaviorSubject<Node>([]);

  get node$(){
    return this.node.asObservable().filter(node => !!node);
  }

  addNode(data:Node) {
    this.node.next(data);
  }
}
@Component({
    selector : 'node-display',
    providers: [NodeService],
    template : `
        <router-outlet></router-outlet>
    `
})
export class NodeDisplayComponent implements OnInit {
    constructor(private nodeService:NodeService) {}
    node: Node;
    ngOnInit(): void {
        this.nodeService.getNode(path)
            .subscribe(
                node => {
                    this.nodeService.addNode(node);
                },
                err => {
                    console.log(err);
                }
            );
    }
}
export class ChildDisplay implements OnInit{
    constructor(nodeService:NodeService) {
      nodeService.node$.subscribe(n => this.node = n);
    }
}

GridView Hide Column by code

Since you want to hide your column you can always hide the column in preRender event of the gridview . This helps you with reducing one operation for every rowdatabound event per row . You will need only one operation for prerender event .

protected void gvVoucherList_PreRender(object sender, EventArgs e)
    {
        try
        {
            int RoleID = Convert.ToInt32(Session["RoleID"]);

            switch (RoleID)
            {
                case 6: gvVoucherList.Columns[11].Visible = false;
                    break;
                case 1: gvVoucherList.Columns[10].Visible = false;
                    break;
            }
            if(hideActionColumn == "ActionSM")
            {
                gvVoucherList.Columns[10].Visible = false;
                hideActionColumn = string.Empty;
            }
        }
        catch (Exception Ex)
        {

        }
    }

Detect changed input text box

onkeyup, onpaste, onchange, oninput seems to be failing when the browser performs autofill on the textboxes. To handle such a case include "autocomplete='off'" in your textfield to prevent browser from autofilling the textbox,

Eg,

<input id="inputDatabaseName" autocomplete='off' onchange="check();"
 onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();" />

<script>
     function check(){
          alert("Input box changed");
          // Things to do when the textbox changes
     }
</script>

select count(*) from table of mysql in php

For mysqli users, the code will look like this:

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

$result = $mysqli->query("SELECT COUNT(*) AS Students_count FROM Students")->fetch_array();
var_dump($result['Students_count']);

or:

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);

$result = $mysqli->query("SELECT COUNT(*) FROM Students")->fetch_array();
var_dump($result[0]);

Convert MySQL to SQlite

If you have experience write simple scripts by Perl\Python\etc, and convert MySQL to SQLite. Read data from Mysql and write it on SQLite.

Difference between Amazon EC2 and AWS Elastic Beanstalk

First off, EC2 and Elastic Compute Cloud are the same thing.

Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.

EC2

EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n number of instances.

Elastic Beanstalk

Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.

Running Wordpress

For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.

What to pick?

In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.

Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/

How to find the path of Flutter SDK

If flutter SDK is already downloaded in the system, then just add path using the below command. This tested on MAC OS

export PATH='sdkpath':$PATH 

Eg:

export PATH='/Users/apple/dev/flutter/sdk/flutter/bin':$PATH 

Select from one table where not in another

You can LEFT JOIN the two tables. If there is no corresponding row in the second table, the values will be NULL.

SELECT id FROM partmaster LEFT JOIN product_details ON (...) WHERE product_details.part_num IS NULL

Best way to generate a random float in C#

Here is another way that I came up with: Let's say you want to get a float between 5.5 and 7, with 3 decimals.

float myFloat;
int myInt;
System.Random rnd = new System.Random();

void GenerateFloat()
{
myInt = rnd.Next(1, 2000);
myFloat = (myInt / 1000) + 5.5f;
}

That way you will always get a bigger number than 5.5 and a smaller number than 7.

Converting cv::Mat to IplImage*

One problem might be: when using external ipl and defining HAVE_IPL in your project, the ctor

_IplImage::_IplImage(const cv::Mat& m)
{
    CV_Assert( m.dims <= 2 );
    cvInitImageHeader(this, m.size(), cvIplDepth(m.flags), m.channels());
    cvSetData(this, m.data, (int)m.step[0]);
}

found in ../OpenCV/modules/core/src/matrix.cpp is not used/instanciated and conversion fails.

You may reimplement it in a way similar to :

IplImage& FromMat(IplImage& img, const cv::Mat& m)
{
    CV_Assert(m.dims <= 2);
    cvInitImageHeader(&img, m.size(), cvIplDepth(m.flags), m.channels());
    cvSetData(&img, m.data, (int)m.step[0]);
    return img;
}

IplImage img;
FromMat(img,myMat);

Comparing Java enum members: == or equals()?

Using == to compare two enum values works, because there is only one object for each enum constant.

On a side note, there is actually no need to use == to write null-safe code, if you write your equals() like this:

public useEnums(final SomeEnum a) {
    if (SomeEnum.SOME_ENUM_VALUE.equals(a)) {
        …
    }
    …
}

This is a best practice known as Compare Constants From The Left that you definitely should follow.

Running multiple commands in one line in shell

You are using | (pipe) to direct the output of a command into another command. What you are looking for is && operator to execute the next command only if the previous one succeeded:

cp /templates/apple /templates/used && cp /templates/apple /templates/inuse && rm /templates/apple

Or

cp /templates/apple /templates/used && mv /templates/apple /templates/inuse

To summarize (non-exhaustively) bash's command operators/separators:

  • | pipes (pipelines) the standard output (stdout) of one command into the standard input of another one. Note that stderr still goes into its default destination, whatever that happen to be.
  • |&pipes both stdout and stderr of one command into the standard input of another one. Very useful, available in bash version 4 and above.
  • && executes the right-hand command of && only if the previous one succeeded.
  • || executes the right-hand command of || only it the previous one failed.
  • ; executes the right-hand command of ; always regardless whether the previous command succeeded or failed. Unless set -e was previously invoked, which causes bash to fail on an error.

Hibernate Group by Criteria Object

You can use the approach @Ken Chan mentions, and add a single line of code after that if you want a specific list of Objects, example:

    session.createCriteria(SomeTable.class)       
                    .add(Restrictions.ge("someColumn", xxxxx))      
                    .setProjection(Projections.projectionList()
                            .add(Projections.groupProperty("someColumn"))
                            .add(Projections.max("someColumn"))
                            .add(Projections.min("someColumn"))
                            .add(Projections.count("someColumn"))           
                    ).setResultTransformer(Transformers.aliasToBean(SomeClazz.class));

List<SomeClazz> objectList = (List<SomeClazz>) criteria.list();

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

What is the difference between a static method and a non-static method?

Static method example

class StaticDemo
{

 public static void copyArg(String str1, String str2)
    {
       str2 = str1;
       System.out.println("First String arg is: "+str1);
       System.out.println("Second String arg is: "+str2);
    }
    public static void main(String agrs[])
    {
      //StaticDemo.copyArg("XYZ", "ABC");
      copyArg("XYZ", "ABC");
    }
}

Output:

First String arg is: XYZ

Second String arg is: XYZ

As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.

Non-static method example

class Test
{
    public void display()
    {
       System.out.println("I'm non-static method");
    }
    public static void main(String agrs[])
    {
       Test obj=new Test();
       obj.display();
    }
}

Output:

I'm non-static method

A non-static method is always be called by using the object of class as shown in the above example.

Key Points:

How to call static methods: direct or using class name:

StaticDemo.copyArg(s1, s2);

or

copyArg(s1, s2);

How to call a non-static method: using object of the class:

Test obj = new Test();

jQuery: How can I create a simple overlay?

An overlay is, simply put, a div that stays fixed on the screen (no matter if you scroll) and has some sort of opacity.

This will be your CSS for cross browser opacity of 0.5:

#overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
    z-index: 10000;
}

This will be your jQuery code (no UI needed). You're just going to create a new element with the ID #overlay. Creating and destroying the DIV should be all you need.

var overlay = jQuery('<div id="overlay"> </div>');
overlay.appendTo(document.body)

For performance reasons you might wanna have the DIV hidden and setting the display to block and none as you need it or not.

Hope it helps!

Edit: As @Vitaly so well put it, be sure to check your DocType. Read more on the comments on his findings..

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

Try -

$("#column_select").change(function () {
    $("#layout_select").children('option').hide();
    $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})  

If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -

$(document).ready(function() {
    $("#layout_select").children('option:gt(0)').hide();
    $("#column_select").change(function() {
        $("#layout_select").children('option').hide();
        $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
    })
})

Demo - http://jsfiddle.net/Mxkfr/2

EDIT

I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -

$(document).ready(function() {
    var optarray = $("#layout_select").children('option').map(function() {
        return {
            "value": this.value,
            "option": "<option value='" + this.value + "'>" + this.text + "</option>"
        }
    })

    $("#column_select").change(function() {
        $("#layout_select").children('option').remove();
        var addoptarr = [];
        for (i = 0; i < optarray.length; i++) {
            if (optarray[i].value.indexOf($(this).val()) > -1) {
                addoptarr.push(optarray[i].option);
            }
        }
        $("#layout_select").html(addoptarr.join(''))
    }).change();
})

Demo - http://jsfiddle.net/N7Xpb/1/

jQuery: Count number of list elements?

and of course the following:

var count = $("#myList").children().length;

can be condensed down to: (by removing the 'var' which is not necessary to set a variable)

count = $("#myList").children().length;

however this is cleaner:

count = $("#mylist li").size();

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

Map with Key as String and Value as List in Groovy

you don't need to declare Map groovy internally recognizes it

def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']

// print the values..
    println "First Name: ${personDetails.firstName}"
    println "Last Name: ${personDetails.lastName}"

http://grails.asia/groovy-map-tutorial

What does "Could not find or load main class" mean?

  • in Intellij Check your Global libraries and local libraries
  • check in pom.xml the libraries version , maybe it is an old library
  • they are so many possibilities mention above that need to be tried too

Changing the row height of a datagridview

You also need to change the resizable property to true

    dataGridView1.RowTemplate.Resizable = DataGridViewTriState.True;
    dataGridView1.RowTemplate.Height = 50;

PowerShell - Start-Process and Cmdline Switches

Warning

If you run PowerShell from a cmd.exe window created by Powershell, the 2nd instance no longer waits for jobs to complete.

cmd>  PowerShell
PS> Start-Process cmd.exe -Wait 

Now from the new cmd window, run PowerShell again and within it start a 2nd cmd window: cmd2> PowerShell

PS> Start-Process cmd.exe -Wait
PS>   

The 2nd instance of PowerShell no longer honors the -Wait request and ALL background process/jobs return 'Completed' status even thou they are still running !

I discovered this when my C# Explorer program is used to open a cmd.exe window and PS is run from that window, it also ignores the -Wait request. It appears that any PowerShell which is a 'win32 job' of cmd.exe fails to honor the wait request.

I ran into this with PowerShell version 3.0 on windows 7/x64

Extracting date from a string in Python

Using Pygrok, you can define abstracted extensions to the Regular Expression syntax.

The custom patterns can be included in your regex in the format %{PATTERN_NAME}.

You can also create a label for that pattern, by separating with a colon: %s{PATTERN_NAME:matched_string}. If the pattern matches, the value will be returned as part of the resulting dictionary (e.g. result.get('matched_string'))

For example:

from pygrok import Grok

input_string = 'monkey 2010-07-10 love banana'
date_pattern = '%{YEAR:year}-%{MONTHNUM:month}-%{MONTHDAY:day}'

grok = Grok(date_pattern)
print(grok.match(input_string))

The resulting value will be a dictionary:

{'month': '07', 'day': '10', 'year': '2010'}

If the date_pattern does not exist in the input_string, the return value will be None. By contrast, if your pattern does not have any labels, it will return an empty dictionary {}

References:

DevTools failed to load SourceMap: Could not load content for chrome-extension

Extensions without enough permission on chrome can cause these warnings, for example for React developer tools, check if the following procedure solves your problem:

  1. Right click on the extension icon.

Or

  1. Go to extensions.
  2. Click the three-dot in the row of React developer tool.

Then choose "this can read and write site data". You should see 3 options in the list, pick one that is strict enough based on how much you trust the extension and also satisfies the extensions's needs.

How to Change color of Button in Android when Clicked?

1-make 1 shape for Button right click on drawable nd new drawable resource file . change Root element to shape and make your shape.

enter image description here

2-now make 1 copy from your shape and change name and change solid color. enter image description here

3-right click on drawable and new drawable resource file just set root element to selector.

go to file and set "state_pressed"

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"android:drawable="@drawable/YourShape1"/>
<item android:state_pressed="false" android:drawable="@drawable/YourShape2"/>

</selector>

4-the end go to xml layout and set your Button background "your selector"

(sorry for my english weak)

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

no overload for matches delegate 'system.eventhandler'

You need to change public void klik(PaintEventArgs pea, EventArgs e) to public void klik(object sender, System.EventArgs e) because there is no Click event handler with parameters PaintEventArgs pea, EventArgs e.

How to quickly drop a user with existing privileges

I faced the same problem and now found a way to solve it. First you have to delete the database of the user that you wish to drop. Then the user can be easily deleted.

I created an user named "msf" and struggled a while to delete the user and recreate it. I followed the below steps and Got succeeded.

1) Drop the database

dropdb msf

2) drop the user

dropuser msf

Now I got the user successfully dropped.

How to trim white spaces of array values in php

Trim in array_map change type if you have NULL in value.

Better way to do it:

$result = array_map(function($v){ 
  return is_string($v)?trim($v):$v; 
}, $array);

PHP: Possible to automatically get all POSTed data?

Yes you can use simply

     $input_data = $_POST;

or extract() may be useful for you.

SimpleDateFormat parse loses timezone

All I needed was this :

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));

SimpleDateFormat sdfLocal = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

try {
    String d = sdf.format(new Date());
    System.out.println(d);
    System.out.println(sdfLocal.parse(d));
} catch (Exception e) {
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}

Output : slightly dubious, but I want only the date to be consistent

2013.08.08 11:01:08
Thu Aug 08 11:01:08 GMT+08:00 2013

How many characters can you store with 1 byte?

The syntax of TINYINT data type is TINYINT(M),

where M indicates the maximum display width (used only if your MySQL client supports it).

The (m) indicates the column width in SELECT statements; however, it doesn't control the accepted range of numbers for that field.

A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 >bits, BIT(64). For a boolean values, BIT(1) is pretty common.

TINYINT()

Redirect to external URL with return in laravel

For Laravel 5.x we can redirect with just

return redirect()->to($url);

ViewDidAppear is not called when opening app from background

I think registering for the UIApplicationWillEnterForegroundNotification is risky as you may end up with more than one controller reacting to that notification. Nothing garanties that these controllers are still visible when the notification is received.

Here is what I do: I force call viewDidAppear on the active controller directly from the App's delegate didBecomeActive method:

Add the code below to - (void)applicationDidBecomeActive:(UIApplication *)application

UIViewController *activeController = window.rootViewController;
if ([activeController isKindOfClass:[UINavigationController class]]) {
    activeController = [(UINavigationController*)window.rootViewController topViewController];
}
[activeController viewDidAppear:NO];

What's the HTML to have a horizontal space between two objects?

<div> looks nice, but a bit complicated in setting all these display: block, float: left... Maybe because the general idea behind <div> is a block of a paragraph size or more.

I have found the following nice way for spacing:

<button>Button 1></button>
<button style="margin-left: 4em">Button 2</button>

dd: How to calculate optimal blocksize?

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

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

source

How to pass form input value to php function

You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>

This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Generating random numbers in Objective-C

As of iOS 9 and OS X 10.11, you can use the new GameplayKit classes to generate random numbers in a variety of ways.

You have four source types to choose from: a general random source (unnamed, down to the system to choose what it does), linear congruential, ARC4 and Mersenne Twister. These can generate random ints, floats and bools.

At the simplest level, you can generate a random number from the system's built-in random source like this:

NSInteger rand = [[GKRandomSource sharedRandom] nextInt];

That generates a number between -2,147,483,648 and 2,147,483,647. If you want a number between 0 and an upper bound (exclusive) you'd use this:

NSInteger rand6 = [[GKRandomSource sharedRandom] nextIntWithUpperBound:6];

GameplayKit has some convenience constructors built in to work with dice. For example, you can roll a six-sided die like this:

GKRandomDistribution *d6 = [GKRandomDistribution d6];
[d6 nextInt];

Plus you can shape the random distribution by using things like GKShuffledDistribution.

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

SELECT t.*,
       @rownum := @rownum +1 AS rank
  FROM TBL_FOO t
  JOIN (SELECT @rownum := 0) r
 WHERE t.name = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

jQuery-- Populate select from json

$(JSON.parse(response)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#selectorId');

Change div height on button click

Just remove the "px" in the style.height assignation, like:

<button type="button" onClick = "document.getElementById('chartdiv').style.height = 200px"> </button>

Should be

<button type="button" onClick = "document.getElementById('chartdiv').style.height = 200">Click Me!</button>

Passing multiple argument through CommandArgument of Button in Asp.net

A little more elegant way of doing the same adding on to the above comment ..

<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
                           AutoGenerateColumns="false"
                            OnRowDeleting="deleteRow"
                         GridLines="Vertical">
      <asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
      <asp:BoundField DataField="EntityId" HeaderText="EntityId"  />
    <asp:TemplateField ShowHeader="false">
        <ItemTemplate>
           <asp:LinkButton ID="lnkCustomize" Text="Delete"  CommandName="Delete"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 
           </asp:LinkButton>   
        </ItemTemplate>   
    </asp:TemplateField>
     </asp:GridView>

And on the server side:

protected void deleteRow(object sender, GridViewDeleteEventArgs e)
{
    string IdTemplate= e.Values["IdTemplate"].ToString();
    string EntityId = e.Values["EntityId"].ToString();

   // Do stuff..
}

Which to use <div class="name"> or <div id="name">?

ID is suitable for the elements which appears only once Like Logo sidebar container

And Class is suitable for the elements which has same UI but they can be appear more than once. Like

.feed in the #feeds Container

Getting and removing the first character of a string

Use this function from stringi package

> x <- 'hello stackoverflow'
> stri_sub(x,2)
[1] "ello stackoverflow"

Creating a PHP header/footer

Besides just using include() or include_once() to include the header and footer, one thing I have found useful is being able to have a custom page title or custom head tags to be included for each page, yet still have the header in a partial include. I usually accomplish this as follows:

In the site pages:

<?php

$PageTitle="New Page Title";

function customPageHeader(){?>
  <!--Arbitrary HTML Tags-->
<?php }

include_once('header.php');

//body contents go here

include_once('footer.php');
?>

And, in the header.php file:

<!doctype html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title><?= isset($PageTitle) ? $PageTitle : "Default Title"?></title>
    <!-- Additional tags here -->
    <?php if (function_exists('customPageHeader')){
      customPageHeader();
    }?>
  </head>
  <body>

Maybe a bit beyond the scope of your original question, but it is useful to allow a bit more flexibility with the include.

How to move a marker in Google Maps API

use panTo(x,y).This will help u

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

By default, Tomcat container doesn’t contain any jstl library. To fix it, declares jstl.jar in your Maven pom.xml file if you are working in Maven project or add it to your application's classpath

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>

How do I log errors and warnings into a file?

Simply put these codes at top of your PHP/index file:

error_reporting(E_ALL); // Error/Exception engine, always use E_ALL

ini_set('ignore_repeated_errors', TRUE); // always use TRUE

ini_set('display_errors', FALSE); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment

ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'your/path/to/errors.log'); // Logging file path

Why catch and rethrow an exception in C#?

Most of answers talking about scenario catch-log-rethrow.

Instead of writing it in your code consider to use AOP, in particular Postsharp.Diagnostic.Toolkit with OnExceptionOptions IncludeParameterValue and IncludeThisArgument

Adding one day to a date

Simplest solution:

$date = new DateTime('+1 day');
echo $date->format('Y-m-d H:i:s');

How do you test running time of VBA code?

Seconds with 2 decimal spaces:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) / 1000000, "#,##0.00") & " seconds") 'end timer

seconds format

Milliseconds:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime), "#,##0.00") & " milliseconds") 'end timer

milliseconds format

Milliseconds with comma seperator:

Dim startTime As Single 'start timer
MsgBox ("run time: " & Format((Timer - startTime) * 1000, "#,##0.00") & " milliseconds") 'end timer

Milliseconds with comma seperator

Just leaving this here for anyone that was looking for a simple timer formatted with seconds to 2 decimal spaces like I was. These are short and sweet little timers I like to use. They only take up one line of code at the beginning of the sub or function and one line of code again at the end. These aren't meant to be crazy accurate, I generally don't care about anything less then 1/100th of a second personally, but the milliseconds timer will give you the most accurate run time of these 3. I've also read you can get the incorrect read out if it happens to run while crossing over midnight, a rare instance but just FYI.

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT * FROM 
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

Angular 2: Passing Data to Routes?

1. Set up your routes to accept data

{
    path: 'some-route',
    loadChildren: 
      () => import(
        './some-component/some-component.module'
      ).then(
        m => m.SomeComponentModule
      ),
    data: {
      key: 'value',
      ...
    },
}

2. Navigate to route:

From HTML:

<a [routerLink]=['/some-component', { key: 'value', ... }> ... </a>

Or from Typescript:

import {Router} from '@angular/router';

...

 this.router.navigate(
    [
       '/some-component',
       {
          key: 'value',
          ...
       }
    ]
 );

3. Get data from route

import {ActivatedRoute} from '@angular/router';

...

this.value = this.route.snapshot.params['key'];

Check if DataRow exists by column name in c#?

You can use the DataColumnCollection of Your datatable to check if the column is in the collection.

Something like:

DataColumnCollection Columns = dtItems.Columns;

if (Columns.Contains(ColNameToCheck))
{
  row["ColNameToCheck"] = "Checked";
}

Comparing two vectors in an if statement

I'd probably use all.equal and which to get the information you want. It's not recommended to use all.equal in an if...else block for some reason, so we wrap it in isTRUE(). See ?all.equal for more:

foo <- function(A,B){
  if (!isTRUE(all.equal(A,B))){
    mismatches <- paste(which(A != B), collapse = ",")
    stop("error the A and B does not match at the following columns: ", mismatches )
  } else {
    message("Yahtzee!")
  }
}

And in use:

> foo(A,A)
Yahtzee!
> foo(A,B)
Yahtzee!
> foo(A,C)
Error in foo(A, C) : 
  error the A and B does not match at the following columns: 2,4

Recursive Fibonacci

This is my solution to fibonacci problem with recursion.

#include <iostream>
using namespace std;

int fibonacci(int n){
    if(n<=0)
        return 0;
    else if(n==1 || n==2)
        return 1;
    else
        return (fibonacci(n-1)+fibonacci(n-2));
}

int main() {
    cout << fibonacci(8);
    return 0;
}

CSS: center element within a <div> element

To center only the specific child :

_x000D_
_x000D_
.parent {_x000D_
  height: 100px;_x000D_
  background-color: gray;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  background-color: white;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  width: 20px;_x000D_
  height:20px;_x000D_
  margin: auto;_x000D_
_x000D_
}
_x000D_
<div class="parent">_x000D_
   <span class="child">hi</span>_x000D_
</div>  
_x000D_
_x000D_
_x000D_

OR, you can use flex too, but that would center all children

_x000D_
_x000D_
.parent {_x000D_
  height: 100px;_x000D_
  background-color: gray;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  background-color: white;  _x000D_
}
_x000D_
<div class="parent">_x000D_
   <span class="child">hi</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ant: How to execute a command for each file in directory?

I know this post is realy old but now that some time and ant versions passed there is a way to do this with basic ant features and i thought i should share it.

It's done via a recursive macrodef that calls nested tasks (even other macros may be called). The only convention is to use a fixed variable name (element here).

<project name="iteration-test" default="execute" xmlns="antlib:org.apache.tools.ant" xmlns:if="ant:if" xmlns:unless="ant:unless">

    <macrodef name="iterate">
        <attribute name="list" />
        <element name="call" implicit="yes" />
        <sequential>
            <local name="element" />
            <local name="tail" />
            <local name="hasMoreElements" />
            <!-- unless to not get a error on empty lists -->
            <loadresource property="element" unless:blank="@{list}" >
                <concat>@{list}</concat>
                <filterchain>
                    <replaceregex pattern="([^;]*).*" replace="\1" />
                </filterchain>
            </loadresource>
            <!-- call the tasks that handle the element -->
            <call />

            <!-- recursion -->
            <condition property="hasMoreElements">
                <contains string="@{list}" substring=";" />
            </condition>

            <loadresource property="tail" if:true="${hasMoreElements}">
                <concat>@{list}</concat>
                <filterchain>
                    <replaceregex pattern="[^;]*;(.*)" replace="\1" />
                </filterchain>
            </loadresource>

            <iterate list="${tail}" if:true="${hasMoreElements}">
                <call />
            </iterate>
        </sequential>
    </macrodef>

    <target name="execute">
        <fileset id="artifacts.fs" dir="build/lib">
            <include name="*.jar" />
            <include name="*.war" />
        </fileset>

        <pathconvert refid="artifacts.fs" property="artifacts.str" />

        <echo message="$${artifacts.str}: ${artifacts.str}" />
        <!-- unless is required for empty lists to not call the enclosed tasks -->
        <iterate list="${artifacts.str}" unless:blank="${artifacts.str}">
            <echo message="I see:" />
            <echo message="${element}" />
        </iterate>
        <!-- local variable is now empty -->
        <echo message="${element}" />
    </target>
</project>

The key features needed where:

I didnt manage to make the delimiter variabel, but this may not be a major downside.

How to include a font .ttf using CSS?

Did you try format?

@font-face {
  font-family: 'The name of the Font Family Here';
  src: URL('font.ttf') format('truetype');
}

Read this article: http://css-tricks.com/snippets/css/using-font-face/

Also, might depend on browser as well.

How to install wkhtmltopdf on a linux based (shared hosting) web server

If you have sudo access...

Ubuntu 14.04 / 15.04 / 18.04:

sudo apt-get install wkhtmltopdf
# or
sudo apt install wkhtmltopdf

Others

Look at the other answers.

What possibilities can cause "Service Unavailable 503" error?

Primarily what that means is that there are too many concurrent requests and further that they exceed the default 1000 queued requests. That is there are 1000 or more queued requests to your website.

This could happen (assuming there are no faults in your app) if there are long running tasks and as a result the Request queue is backed up.

Depending on how the application pool has been set up you may see this kind of thing. Typically, the app pool's Process Model has an item called Maximum Worker Processes. By default this is 1. If you set it to more than 1 (typically up to a max of the number of cores on the hardware) you may not see this happen.

Just to note that unless the site is extremely busy you should not see this. If you do, it's really pointing to long running tasks

How to set or change the default Java (JDK) version on OS X?

tl;dr

Add the line:

export JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home'

to the file

~/.bash_profile

(replace jdk1.8.0_144.jdk with your downloaded version)

then source ~/.bash_profile

Best practices for circular shift (rotate) operations in C++

--- Substituting RLC in 8051 C for speed --- Rotate left carry
Here is an example using RLC to update a serial 8 bit DAC msb first:
                               (r=DACVAL, P1.4= SDO, P1.5= SCLK)
MOV     A, r
?1:
MOV     B, #8
RLC     A
MOV     P1.4, C
CLR     P1.5
SETB    P1.5
DJNZ    B, ?1

Here is the code in 8051 C at its fastest:
sbit ACC_7  = ACC ^ 7 ; //define this at the top to access bit 7 of ACC
ACC     =   r;
B       =   8;  
do  {
P1_4    =   ACC_7;  // this assembles into mov c, acc.7  mov P1.4, c 
ACC     <<= 1;
P1_5    =   0;
P1_5    =   1;
B       --  ; 
    } while ( B!=0 );
The keil compiler will use DJNZ when a loop is written this way.
I am cheating here by using registers ACC and B in c code.
If you cannot cheat then substitute with:
P1_4    =   ( r & 128 ) ? 1 : 0 ;
r     <<=   1;
This only takes a few extra instructions.
Also, changing B for a local var char n is the same.
Keil does rotate ACC left by ADD A, ACC which is the same as multiply 2.
It only takes one extra opcode i think.
Keeping code entirely in C keeps things simpler sometimes.

How can I fix WebStorm warning "Unresolved function or method" for "require" (Firefox Add-on SDK)

In PHPStorm, it's a bit easier: you can just search for NPM in settings or:

File > Settings > Language & Frameworks > Node.js and NPM

Then click the enable button (apparently in new versions, it is called "Coding assistance for Node").

How to change the name of an iOS app?

You can change from info.plist having attribute "Bundle Name" .

TypeError: Can't convert 'int' object to str implicitly

def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
    print("Your SP balance is now 0.")
    attributeConfirmation()
elif strength < 0:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif strength > balance:
    print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
    attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
    print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
    print("That is an invalid input. Restarting attribute selection.")
    attributeSelection()

How to POST request using RestSharp

I added this helper method to handle my POST requests that return an object I care about.

For REST purists, I know, POSTs should not return anything besides a status. However, I had a large collection of ids that was too big for a query string parameter.

Helper Method:

    public TResponse Post<TResponse>(string relativeUri, object postBody) where TResponse : new()
    {
        //Note: Ideally the RestClient isn't created for each request. 
        var restClient = new RestClient("http://localhost:999");

        var restRequest = new RestRequest(relativeUri, Method.POST)
        {
            RequestFormat = DataFormat.Json
        };

        restRequest.AddBody(postBody);

        var result = restClient.Post<TResponse>(restRequest);

        if (!result.IsSuccessful)
        {
            throw new HttpException($"Item not found: {result.ErrorMessage}");
        }

        return result.Data;
    }

Usage:

    public List<WhateverReturnType> GetFromApi()
    {
        var idsForLookup = new List<int> {1, 2, 3, 4, 5};

        var relativeUri = "/api/idLookup";

        var restResponse = Post<List<WhateverReturnType>>(relativeUri, idsForLookup);

        return restResponse;
    }

How do I start a program with arguments when debugging?

for .NET Core console apps you can do this 2 ways - from the launchsettings.json or the properties menu.

Launchsettings.json

enter image description here

or right click the project > properties > debug tab on left

see "Application Arguments:"

  • this is " " (space) delimited, no need for any commas. just start typing. each space " " will represent a new input parameter.
  • (whatever changes you make here will be reflected in the launchsettings.json file...)

enter image description here

ES6 export default with multiple functions referring to each other

tl;dr: baz() { this.foo(); this.bar() }

In ES2015 this construct:

var obj = {
    foo() { console.log('foo') }
}

is equal to this ES5 code:

var obj = {
    foo : function foo() { console.log('foo') }
}

exports.default = {} is like creating an object, your default export translates to ES5 code like this:

exports['default'] = {
    foo: function foo() {
        console.log('foo');
    },
    bar: function bar() {
        console.log('bar');
    },
    baz: function baz() {
        foo();bar();
    }
};

now it's kind of obvious (I hope) that baz tries to call foo and bar defined somewhere in the outer scope, which are undefined. But this.foo and this.bar will resolve to the keys defined in exports['default'] object. So the default export referencing its own methods shold look like this:

export default {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { this.foo(); this.bar() }
}

See babel repl transpiled code.

How do I suspend painting for a control and its children?

This is even simpler, and perhaps hacky - as I can see a lot of GDI muscle on this thread, and is obviously only a good fit for certain scenarios. YMMV

In my scenario, I use what I'll refer to as a "Parent" UserControl - and during the Load event, I simply remove the control-to-be-manipulated from the Parent's .Controls collection, and the Parent's OnPaint takes care of completely painting the child control in whatever special way.. fully taking the child's paint capabilities offline.

Now, I hand off my child paint routine to an extension method based off this concept from Mike Gold for printing windows forms.

Here I'm needing a sub-set of labels to render perpendicular to the layout:

simple diagram of your Visual Studio IDE

Then, I exempt the child control from being painted, with this code in the ParentUserControl.Load event handler:

Private Sub ParentUserControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    SetStyle(ControlStyles.UserPaint, True)
    SetStyle(ControlStyles.AllPaintingInWmPaint, True)

    'exempt this control from standard painting: 
    Me.Controls.Remove(Me.HostedControlToBeRotated) 
End Sub

Then, in the same ParentUserControl, we paint the control-to-be-manipulated from the ground up:

Protected Overrides Sub OnPaint(e As PaintEventArgs)
    'here, we will custom paint the HostedControlToBeRotated instance...

    'twist rendering mode 90 counter clockwise, and shift rendering over to right-most end 
    e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
    e.Graphics.TranslateTransform(Me.Width - Me.HostedControlToBeRotated.Height, Me.Height)
    e.Graphics.RotateTransform(-90)
    MyCompany.Forms.CustomGDI.DrawControlAndChildren(Me.HostedControlToBeRotated, e.Graphics)

    e.Graphics.ResetTransform()
    e.Graphics.Dispose()

    GC.Collect()
End Sub

Once you host the ParentUserControl somewhere, e.g. a Windows Form - I'm finding that my Visual Studio 2015 renders the form correctly at Design Time as well as runtime: ParentUserControl hosted in a Windows Form or perhaps other user control

Now, since my particular manipulation rotates the child control 90 degrees, I'm sure all the hot spots and interactivity has been destroyed in that region - but, the problem I was solving was all for a package label that needed to preview and print, which worked out fine for me.

If there are ways to reintroduce the hot spots and control-ness to my purposely orphaned control - I'd love to learn about that someday (not for this scenario, of course, but.. just to learn). Of course, WPF supports such craziness OOTB.. but.. hey.. WinForms is so much fun still, amiright?

How do I pass a command line argument while starting up GDB in Linux?

Once gdb starts, you can run the program using "r args".

So if you are running your code by:

$ executablefile arg1 arg2 arg3 

Debug it on gdb by:

$ gdb executablefile  
(gdb) r arg1 arg2 arg3

How do I change the IntelliJ IDEA default JDK?

I have found out that in recent versions of IntelliJ IDEA requires Java 1.8 but is not configured by default.

We can change the path or configure from Project Settings > Project > Project SDK

here we can edit or add the JDK´s path.

(in my case the path is located in C:\Program Files\Java\jdk1.8.0_102)

enter image description here

enter image description here

Force div element to stay in same place, when page is scrolled

You can do this replacing position:absolute; by position:fixed;.

how to draw smooth curve through N points using javascript HTML5 canvas?

The first answer will not pass through all the points. This graph will exactly pass through all the points and will be a perfect curve with the points as [{x:,y:}] n such points.

var points = [{x:1,y:1},{x:2,y:3},{x:3,y:4},{x:4,y:2},{x:5,y:6}] //took 5 example points
ctx.moveTo((points[0].x), points[0].y);

for(var i = 0; i < points.length-1; i ++)
{

  var x_mid = (points[i].x + points[i+1].x) / 2;
  var y_mid = (points[i].y + points[i+1].y) / 2;
  var cp_x1 = (x_mid + points[i].x) / 2;
  var cp_x2 = (x_mid + points[i+1].x) / 2;
  ctx.quadraticCurveTo(cp_x1,points[i].y ,x_mid, y_mid);
  ctx.quadraticCurveTo(cp_x2,points[i+1].y ,points[i+1].x,points[i+1].y);
}

UTF-8 output from PowerShell

Not an expert on encoding, but after reading these...

... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.

If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding parameter on the out-file cmdlet e.g.

write-output "hello" | out-file "enctest.txt" -encoding utf8

Nothing else you can do on the PowerShell front then, but the following post may well help you:.

Best way to check for null values in Java?

  • Do not catch NullPointerException. That is a bad practice. It is better to ensure that the value is not null.
  • Method #4 will work for you. It will not evaluate the second condition, because Java has short-circuiting (i.e., subsequent conditions will not be evaluated if they do not change the end-result of the boolean expression). In this case, if the first expression of a logical AND evaluates to false, subsequent expressions do not need to be evaluated.

How to find the width of a div using vanilla JavaScript?

Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.

var elem = document.getElementById("myDiv");
if(elem) {
   var rect = elem.getBoundingClientRect();
   console.log(rect.width);  
}

Document Root PHP

Just / refers to the root of your website from the public html folder. DOCUMENT_ROOT refers to the local path to the folder on the server that contains your website.

For example, I have EasyPHP setup on a machine...

$_SERVER["DOCUMENT_ROOT"] gives me file:///C:/Program%20Files%20(x86)/EasyPHP-5.3.9/www but any file I link to with just / will be relative to my www folder.

If you want to give the absolute path to a file on your server (from the server's root) you can use DOCUMENT_ROOT. if you want to give the absolute path to a file from your website's root, use just /.

How to send 500 Internal Server Error error from a PHP script

PHP 5.4 has a function called http_response_code, so if you're using PHP 5.4 you can just do:

http_response_code(500);

I've written a polyfill for this function (Gist) if you're running a version of PHP under 5.4.


To answer your follow-up question, the HTTP 1.1 RFC says:

The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol.

That means you can use whatever text you want (excluding carriage returns or line feeds) after the code itself, and it'll work. Generally, though, there's usually a better response code to use. For example, instead of using a 500 for no record found, you could send a 404 (not found), and for something like "conditions failed" (I'm guessing a validation error), you could send something like a 422 (unprocessable entity).

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

I was trying to run docker(just installed) in an instance of AWS when the message appears. I just write sudo service docker start and works fine for me.

Also see AWS with Docker

How to access static resources when mapping a global front controller servlet on /*

With regard to Tomcat, a lot depends on the particular version. There was a bug fix https://bz.apache.org/bugzilla/show_bug.cgi?id=50026 which means the servlet-mapping (other than for '/') for the default servlet behaves differently in Tomcat 6.0.29 (and earlier) compared with later versions.

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

In order to clear all selection, I am using like this and its working fine for me. here is the script:

 $("#ddlMultiselect").multiselect("clearSelection");

 $("#ddlMultiselect").multiselect( 'refresh' );

Entity Framework - Include Multiple Levels of Properties

Let me state it clearly that you can use the string overload to include nested levels regardless of the multiplicities of the corresponding relationships, if you don't mind using string literals:

query.Include("Collection.Property")

HMAC-SHA256 Algorithm for signature calculation

If you're using Guava, its latest release now lets you use

 Hashing.hmacSha256()

Further documentation here: https://guava.dev/releases/23.0/api/docs/com/google/common/hash/Hashing.html#hmacSha256-byte:A-

Wait some seconds without blocking UI execution

Omar's solution is decent* if you cannot upgrade your environment to .NET 4.5 in order to gain access to the async and await APIs. That said, there here is one important change that should be made in order to avoid poor performance. A slight delay should be added between calls to Application.DoEvents() in order to prevent excessive CPU usage. By adding

Thread.Sleep(1);

before the call to Application.DoEvents(), you can add such a delay (1 millisecond) and prevent the application from using all of the cpu cycles available to it.

private void WaitNSeconds(int seconds)
{
    if (seconds < 1) return;
    DateTime _desired = DateTime.Now.AddSeconds(seconds);
    while (DateTime.Now < _desired) {
         Thread.Sleep(1);
         System.Windows.Forms.Application.DoEvents();
    }
}

*See https://blog.codinghorror.com/is-doevents-evil/ for a more detailed discussion on the potential pitfalls of using Application.DoEvents().

Laravel Eloquent: How to get only certain columns from joined tables

In Laravel 4 you can hide certain fields from being returned by adding the following in your model.

protected $hidden = array('password','secret_field');

http://laravel.com/docs/eloquent#converting-to-arrays-or-json

C# code to validate email address

Email address validation is not as easy as it might seem. It's actually theoretically impossible to fully validate an email address using just a regular expression.

Check out my blog post about it for a discussion on the subject and a F# implementation using FParsec. [/shameless_plug]

error: Libtool library used but 'LIBTOOL' is undefined

A good answer for me was to install libtool:

sudo apt-get install libtool

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

If you are using a linux machine then check,

  • do you have Openssh installed
  • if you do, then do you have an existing public key otherwise you'll have to generate one.
  • is your public key added to your github account.

Generating new SSH keys and adding them to my Github account solved my problem. You can look into this page for more details. GitHelp.

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Short answer

For those who are already familiar with setting up a RecyclerView to make a list, the good news is that making a grid is largely the same. You just use a GridLayoutManager instead of a LinearLayoutManager when you set the RecyclerView up.

recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));

If you need more help than that, then check out the following example.

Full example

The following is a minimal example that will look like the image below.

enter image description here

Start with an empty activity. You will perform the following tasks to add the RecyclerView grid. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

  • Add dependencies to gradle
  • Add the xml layout files for the activity and for the grid cell
  • Make the RecyclerView adapter
  • Initialize the RecyclerView in your activity

Update Gradle dependencies

Make sure the following dependencies are in your app gradle.build file:

compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support:recyclerview-v7:27.1.1'

You can update the version numbers to whatever is the most current.

Create activity layout

Add the RecyclerView to your xml layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvNumbers"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Create grid cell layout

Each cell in our RecyclerView grid is only going to have a single TextView. Create a new layout resource file.

recyclerview_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:padding="5dp"
    android:layout_width="50dp"
    android:layout_height="50dp">

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:background="@color/colorAccent"/>

</LinearLayout>

Create the adapter

The RecyclerView needs an adapter to populate the views in each cell with your data. Create a new java file.

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private String[] mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MyRecyclerViewAdapter(Context context, String[] data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the cell layout from xml when needed
    @Override
    @NonNull 
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each cell
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.myTextView.setText(mData[position]);
    }

    // total number of cells
    @Override
    public int getItemCount() {
        return mData.length;
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.info_text);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mData[id];
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

Notes

  • Although not strictly necessary, I included the functionality for listening for click events on the cells. This was available in the old GridView and is a common need. You can remove this code if you don't need it.

Initialize RecyclerView in Activity

Add the following code to your main activity.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48"};

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvNumbers);
        int numberOfColumns = 6;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numberOfColumns));
        adapter = new MyRecyclerViewAdapter(this, data);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Log.i("TAG", "You clicked number " + adapter.getItem(position) + ", which is at cell position " + position);
    }
}

Notes

  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle cell click events in onItemClick.

Finished

That's it. You should be able to run your project now and get something similar to the image at the top.

Going on

Rounded corners

Auto-fitting columns

Further study

Convert java.util.date default format to Timestamp in Java

Best one

String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date); 
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;

css to make bootstrap navbar transparent

_x000D_
_x000D_
<nav class="navbar navbar-expand-lg navbar-light fixed-top bg-transparent">
              <a class="navbar-brand" href="#">Navbar w/ text</a>
              <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
              </button>
              <div class="collapse navbar-collapse" id="navbarText">
                <ul class="navbar-nav mr-auto">
                  <li class="nav-item active">
                    <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link" href="#">Features</a>
                  </li>
                  <li class="nav-item">
                    <a class="nav-link" href="#">Pricing</a>
                  </li>
                </ul>
                <span class="navbar-text">
                  Navbar text with an inline element
                </span>
              </div>
            </nav>
_x000D_
_x000D_
_x000D_

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

Show loading image while $.ajax is performed

Before your call either insert the loading image in a div/span somewhere and then on the success function remove that image. Alternatively you can set up a css class like loading that might look like this

.loading
{
    width: 16px;
    height: 16px;
    background:transparent url('loading.gif') no-repeat 0 0;
    font-size: 0px;
    display: inline-block;
}

And then assign this class to a span/div and clear it in the success function

Get json value from response

If the response is in json then it would be like:

alert(response.id);

Otherwise

var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

String.Replace ignoring case

(Edited: wasn't aware of the `naked link' problem, sorry about that)

Taken from here:

string myString = "find Me and replace ME";
string strReplace = "me";
myString = Regex.Replace(myString, "me", strReplace, RegexOptions.IgnoreCase);

Seems you are not the first to complain of the lack of case insensitive string.Replace.

Javascript / Chrome - How to copy an object from the webkit inspector as code

So,. I had this issue,. except I got [object object]

I'm sure you could do this with recursion but this worked for me:

Here is what I did in my console:

var object_that_is_not_shallow = $("all_obects_with_this_class_name");
var str = '';
object_that_is_not_shallow.map(function(_,e){
    str += $(e).html();
});
copy(str);

Then paste into your editor.

How do I parse JSON into an int?

The question is kind of old, but I get a good result creating a function to convert an object in a Json string from a string variable to an integer

function getInt(arr, prop) {
    var int;
    for (var i=0 ; i<arr.length ; i++) {
        int = parseInt(arr[i][prop])
            arr[i][prop] = int;
    }
    return arr;
  }

the function just go thru the array and return all elements of the object of your selection as an integer

Android: Proper Way to use onBackPressed() with Toast

Use this, it may help.

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
            .setTitle("Message")
            .setMessage("Do you want to exit app?")
            .setNegativeButton("NO", null)
            .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    UserLogin.super.onBackPressed();
                }
            }).create().show();
}

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

Check these steps.

  1. go to Sql Server Configuration management->SQL Server network config->protocols for 'servername' and check TCP/IP is enabled.
  2. Open SSMS in run, and check you are able to login to server using specfied username/password and/or using windows authentication.
  3. repeat step 1 for SQL native client config also

how do I get the bullet points of a <ul> to center with the text?

I found the answer today. Maybe its too late but still I think its a much better one. Check this one https://jsfiddle.net/Amar_newDev/khb2oyru/5/

Try to change the CSS code : <ul> max-width:1%; margin:auto; text-align:left; </ul>

max-width:80% or something like that.

Try experimenting you might find something new.

Why can't Python find shared objects that are in directories in sys.path?

I use python setup.py build_ext -R/usr/local/lib -I/usr/local/include/libcalg-1.0 and the compiled .so file is under the build folder. you can type python setup.py --help build_ext to see the explanations of -R and -I

how to get the value of a textarea in jquery?

Value of textarea is also taken with val method:

var message = $('textarea#message').val();

Remove Item from ArrayList

If you use "=", a replica is created for the original arraylist in the second one, but the reference is same so if you change in one list , the other one will also get modified. Use this instead of "="

        List_Of_Array1.addAll(List_Of_Array);

What's the difference between isset() and array_key_exists()?

The PHP function array_key_exists() determines if a particular key, or numerical index, exists for an element of an array. However, if you want to determine if a key exists and is associated with a value, the PHP language construct isset() can tell you that (and that the value is not null). array_key_exists()cannot return information about the value of a key/index.

Stopword removal with NLTK

@alvas has a good answer. But again it depends on the nature of the task, for example in your application you want to consider all conjunction e.g. and, or, but, if, while and all determiner e.g. the, a, some, most, every, no as stop words considering all others parts of speech as legitimate, then you might want to look into this solution which use Part-of-Speech Tagset to discard words, Check table 5.1:

import nltk

STOP_TYPES = ['DET', 'CNJ']

text = "some data here "
tokens = nltk.pos_tag(nltk.word_tokenize(text))
good_words = [w for w, wtype in tokens if wtype not in STOP_TYPES]

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

Check if a string within a list contains a specific string with Linq

Thast should be easy enough

if( myList.Any( s => s.Contains(stringToCheck))){
  //do your stuff here
}

Given URL is not permitted by the application configuration

Sometimes this error occurs for old javascript sdk. If you save locally javascript file. Update it. I prefer to load it form the facebook server all the time.

How to list the properties of a JavaScript object?

This will work in most browsers, even in IE8 , and no libraries of any sort are required. var i is your key.

var myJSONObject =  {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; 
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);

Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

I used the header("Access-Control-Allow-Origin: *"); method but still received the CORS error. It turns out that the PHP script that was being requested had an error in it (I had forgotten to add a period (.) when concatenating two variables). Once I fixed that typo, it worked!

So, It seems that the remote script being called cannot have errors within it.

what is the difference between XSD and WSDL

XSD : XML Schema Definition.

XML : eXtensible Markup Language.

WSDL : Web Service Definition Language.

I am not going to answer in technical terms. I am aiming this explanation at beginners.

It is not easy to communicate between two different applications that are developed using two different technologies. For example, a company in Chicago might develop a web application using Java and another company in New York might develop an application in C# and when these two companies decided to share information then XML comes into picture. It helps to store and transport data between two different applications that are developed using different technologies. Note: It is not limited to a programming language, please do research on the information transportation between two different apps.

XSD is a schema definition. By that what I mean is, it is telling users to develop their XML in such a schema. Please see below images, and please watch closely with "load-on-startup" element and its type which is integer. In the XSD image you can see it is meant to be integer value for the "load-on-startup" and hence when user created his/her XML they passed an int value to that particular element. As a reminder, XSD is a schema and style whereas XML is a form to communicate with another application or system. One has to see XSD and create XML in such a way or else it won't communicate with another application or system which has been developed with a different technology. A company in Chicago provides a XSD template for a company in Texas to write or generate their XML in the given XSD format. If the company in Texas failed to adhere with those rules or schema mentioned in XSD then it is impossible to expect correct information from the company in Chicago. There is so much to do after the above said story, which an amateur or newbie have to know while coding for some thing like I said above. If you really want to know what happens later then it is better to sit with senior software engineers who actually developed web services. Next comes WSDL, please follow the images and try to figure out where the WSDL will fit in.

***************========Below is partial XML image ==========*************** XML image partial

***************========Below is partial XSD image ==========***************

XSD image partial

***************========Below is the partial WSDL image =======*************

WSDL image partial

I had to create a sample WSDL for a web service called Book. Note, it is an XSD but you have to call it WSDL (Web Service Definition Language) because it is very specific for Web Services. The above WSDL (or in other words XSD) is created for a class called Book.java and it has created a SOAP service. How the SOAP web service created it is a different topic. One has to write a Java class and before executing it create as a web service the user has to make sure Axis2 API is installed and Tomcat to host web service is in place.

As a servicer (the one who allows others (clients) to access information or data from their systems ) actually gives the client (the one who needs to use servicer information or data) complete access to data through a Web Service, because no company on the earth willing to expose their Database for outsiders. Like my company, decided to give some information about products via Web Services, hence we had to create XSD template and pass-on to few of our clients who wants to work with us. They have to write some code to make complete use of the given XSD and make Web Service calls to fetch data from servicer and convert data returned into their suitable requirement and then display or publish data or information about the product on their website. A simple example would be FLIGHT Ticket booking. An airline will let third parties to use flight data on their site for ticket sales. But again there is much more to it, it is just not letting third party flight ticket agent to sell tickets, there will be synchronize and security in place. If there is no sync then there is 100 % chances more than 1 customer might buy same flight ticket from various sources.

I am hoping experts will contribute to my answer. It is really hard for newbie or novice to understand XML, XSD and then to work on Web Services.

How to create a JavaScript callback for knowing when an image is loaded?

If the goal is to style the img after browser has rendered image, you should:

const img = new Image();
img.src = 'path/to/img.jpg';

img.decode().then(() => {
/* set styles */
/* add img to DOM */ 
});

because the browser first loads the compressed version of image, then decodes it, finally paints it. since there is no event for paint you should run your logic after browser has decoded the img tag.

jquery <a> tag click event

<a href="javascript:void(0)" class="aaf" id="users_id">add as a friend</a>

on jquery

$('.aaf').on("click",function(){
  var usersid =  $(this).attr("id");
  //post code
})

//other method is to use the data attribute

<a href="javascript:void(0)" class="aaf" data-id="102" data-username="sample_username">add as a friend</a>

on jquery

$('.aaf').on("click",function(){
    var usersid =  $(this).data("id");
    var username = $(this).data("username");
})

Create a Dropdown List for MVC3 using Entity Framework (.edmx Model) & Razor Views && Insert A Database Record to Multiple Tables

Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:

  1. You should never send your model to the view => This is correct
  2. If you create a ViewModel, and include the Model as member in the ViewModel, then you effectively sent your model to the View => this is BAD
  3. Using dictionaries to send the options to the view => this not good style

So how can you create a better coupling?

I would use a tool like AutoMapper or ValueInjecter to map between ViewModel and Model. AutoMapper does seem to have the better syntax and feel to it, but the current version lacks a very severe topic: It is not able to perform the mapping from ViewModel to Model (under certain circumstances like flattening, etc., but this is off topic) So at present I prefer to use ValueInjecter.

So you create a ViewModel with the fields you need in the view. You add the SelectList items you need as lookups. And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist: You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList from the view to the controller.

  // StaffTypes is an IEnumerable<StaffType> from dbContext
  // viewModel is the viewModel initialized to copy content of Model Employee  
  // viewModel.StaffTypes is of type SelectList

  viewModel.StaffTypes =
    new SelectList(
        StaffTypes.OrderBy( item => item.Name )
        "StaffTypeID",
        "Type",
        viewModel.StaffTypeID
    );

In the view you just have to call

@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )

Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel. You then check for validation. If the validation fails, you have to remember to re-populate the viewModel.StaffTypes SelectList, because this item will be null on entering the post function. So I tend to have those population things separated into a function. You just call back return new View(viewModel) if anything is wrong. Validation errors found by MVC3 will automatically be shown in the view.

If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState to get info on that.

If the viewModel is valid you have to perform the next step:

If it is a create of a new item, you have to populate a model from the viewModel (best suited is ValueInjecter). Then you can add it to the EF collection of that type and commit changes.

If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel back to the model (again using ValueInjecter gets you do that very quick). After that you can SaveChanges and are done.

Feel free to ask if anything is unclear.

Python's most efficient way to choose longest string in list?

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456

Postgres: INSERT if does not exist already

How can I write an 'INSERT unless this row already exists' SQL statement?

There is a nice way of doing conditional INSERT in PostgreSQL:

INSERT INTO example_table
    (id, name)
SELECT 1, 'John'
WHERE
    NOT EXISTS (
        SELECT id FROM example_table WHERE id = 1
    );

CAVEAT This approach is not 100% reliable for concurrent write operations, though. There is a very tiny race condition between the SELECT in the NOT EXISTS anti-semi-join and the INSERT itself. It can fail under such conditions.

Another Repeated column in mapping for entity error

If you are stuck with a legacy database where someone already placed JPA annotations on but did NOT define the relationships and you are now trying to define them for use in your code, then you might NOT be able to delete the customerId @Column since other code may directly reference it already. In that case, define the relationships as follows:

@ManyToOne(optional=false)
@JoinColumn(name="productId",referencedColumnName="id_product", insertable=false, updatable=false)
private Product product;

@ManyToOne(optional=false)
@JoinColumn(name="customerId",referencedColumnName="id_customer", insertable=false, updatable=false)
private Customer customer;

This allows you to access the relationships. However, to add/update to the relationships you will have to manipulate the foreign keys directly via their defined @Column values. It's not an ideal situation, but if you are handed this sort of situation, at least you can define the relationships so that you can use JPQL successfully.

How do I check whether a checkbox is checked in jQuery?

This is some different method to do the same thing:

_x000D_
_x000D_
$(document).ready(function (){_x000D_
_x000D_
    $('#isAgeSelected').click(function() {_x000D_
        // $("#txtAge").toggle(this.checked);_x000D_
_x000D_
        // Using a pure CSS selector_x000D_
        if ($(this.checked)) {_x000D_
            alert('on check 1');_x000D_
        };_x000D_
_x000D_
        // Using jQuery's is() method_x000D_
        if ($(this).is(':checked')) {_x000D_
            alert('on checked 2');_x000D_
        };_x000D_
_x000D_
        //  // Using jQuery's filter() method_x000D_
        if ($(this).filter(':checked')) {_x000D_
            alert('on checked 3');_x000D_
        };_x000D_
    });_x000D_
});
_x000D_
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>_x000D_
<input type="checkbox" id="isAgeSelected"/>_x000D_
<div id="txtAge" style="display:none">Age is something</div>
_x000D_
_x000D_
_x000D_

Sending Arguments To Background Worker?

Check out the DoWorkEventArgs.Argument Property:

...
backgroundWorker1.RunWorkerAsync(yourInt);
...

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    // Do not access the form's BackgroundWorker reference directly.
    // Instead, use the reference provided by the sender parameter.
    BackgroundWorker bw = sender as BackgroundWorker;

    // Extract the argument.
    int arg = (int)e.Argument;

    // Start the time-consuming operation.
    e.Result = TimeConsumingOperation(bw, arg);

    // If the operation was canceled by the user, 
    // set the DoWorkEventArgs.Cancel property to true.
    if (bw.CancellationPending)
    {
        e.Cancel = true;
    }
}

SVN Repository Search

Painfully slow (and crudely implemented) but a combination of svn log and svn cat works if you are searching the history of single files or small repositories:

svn log filetosearch |
    grep '^r' |
    cut -f1 -d' ' |
    xargs -i bash -c "echo '{}'; svn cat filetosearch -'{}'" 

will output each revision number where file changed and the file. You could always cat each revision into a different file and then grep for changes.

PS. Massive upvotes to anyone that shows me how to do this properly!

How to unmerge a Git merge?

You can reset your branch to the state it was in just before the merge if you find the commit it was on then.

One way is to use git reflog, it will list all the HEADs you've had. I find that git reflog --relative-date is very useful as it shows how long ago each change happened.

Once you find that commit just do a git reset --hard <commit id> and your branch will be as it was before.

If you have SourceTree, you can look up the <commit id> there if git reflog is too overwhelming.

How can you use php in a javascript function

I think you're confusing server code with client code.

JavaScript runs on the client after it has received data from the server (like a webpage).

PHP runs on the server before it sends the data.

So there are two ways with interacting with JavaScript with php.

Like above, you can generate javascript with php in the same fashion you generate HTML with php.

Or you can use an AJAX request from javascript to interact with the server. The server can respond with data and the javascript can receive that and do something with it.

I'd recommend going back to the basics and studying how HTTP works in the server-client relationship. Then study the concept of server side languages and client side languages.

Then take a tutorial with ajax, and you will start getting the concept.

Good luck, google is your friend.

How to inherit constructors?

Yes, you will have to implement the constructors that make sense for each derivation and then use the base keyword to direct that constructor to the appropriate base class or the this keyword to direct a constructor to another constructor in the same class.

If the compiler made assumptions about inheriting constructors, we wouldn't be able to properly determine how our objects were instantiated. In the most part, you should consider why you have so many constructors and consider reducing them to only one or two in the base class. The derived classes can then mask out some of them using constant values like null and only expose the necessary ones through their constructors.

Update

In C#4 you could specify default parameter values and use named parameters to make a single constructor support multiple argument configurations rather than having one constructor per configuration.

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

FromBody string parameter is giving null

You are on the right track.

On your header set

Content-Type: application/x-www-form-urlencoded

The body of the POST request should be =test and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.


See also POST string to ASP.NET Web Api application - returns null

Counter inside xsl:for-each loop

position(). E.G.:

<countNo><xsl:value-of select="position()" /></countNo>

Working Soap client example

String send = 
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" +
    "        <soap:Body>\n" +
    "        </soap:Body>\n" +
    "</soap:Envelope>";

private static String getResponse(String send) throws Exception {
    String url = "https://api.comscore.com/KeyMeasures.asmx"; //endpoint
    String result = "";
    String username="user_name";
    String password="pass_word";
    String[] command = {"curl", "-u", username+":"+password ,"-X", "POST", "-H", "Content-Type: text/xml", "-d", send, url};
    ProcessBuilder process = new ProcessBuilder(command); 
    Process p;
    try {
        p = process.start();
        BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ( (line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
        }
        result = builder.toString();
    }
    catch (IOException e)
    {   System.out.print("error");
        e.printStackTrace();
    }

    return result;
}

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.

In other words, List<? extends Serializable> means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).

What is the difference between Forking and Cloning on GitHub?

Basically, yes. A fork is just a request for GitHub to clone the project and registers it under your username; GitHub also keeps track of the relationship between the two repositories, so you can visualize the commits and pulls between the two projects (and other forks).

You can still request that people pull from your cloned repository, even if you don't use fork -- but you'd have to deal with making it publicly available yourself. Or send the developers patches (see git format-patch) that they can apply to their trees.

How to compile the finished C# project and then run outside Visual Studio?

If you cannot find the .exe file, rebuild your solution and in your "Output" from Visual Studio the path to the file will be shown.

Build solution path.

How to directly execute SQL query in C#?

Something like this should suffice, to do what your batch file was doing (dumping the result set as semi-colon delimited text to the console):

// sqlcmd.exe
// -S .\PDATA_SQLEXPRESS
// -U sa
// -P 2BeChanged!
// -d PDATA_SQLEXPRESS
// -s ; -W -w 100
// -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "

DataTable dt            = new DataTable() ;
int       rows_returned ;

const string credentials = @"Server=(localdb)\.\PDATA_SQLEXPRESS;Database=PDATA_SQLEXPRESS;User ID=sa;Password=2BeChanged!;" ;
const string sqlQuery = @"
  select tPatCulIntPatIDPk ,
         tPatSFirstname    ,
         tPatSName         ,
         tPatDBirthday
  from dbo.TPatientRaw
  where tPatSName = @patientSurname
  " ;

using ( SqlConnection connection = new SqlConnection(credentials) )
using ( SqlCommand    cmd        = connection.CreateCommand() )
using ( SqlDataAdapter sda       = new SqlDataAdapter( cmd ) )
{
  cmd.CommandText = sqlQuery ;
  cmd.CommandType = CommandType.Text ;
  connection.Open() ;
  rows_returned = sda.Fill(dt) ;
  connection.Close() ;
}

if ( dt.Rows.Count == 0 )
{
  // query returned no rows
}
else
{

  //write semicolon-delimited header
  string[] columnNames = dt.Columns
                           .Cast<DataColumn>()
                           .Select( c => c.ColumnName )
                           .ToArray()
                           ;
  string   header      = string.Join("," , columnNames) ;
  Console.WriteLine(header) ;

  // write each row
  foreach ( DataRow dr in dt.Rows )
  {

    // get each rows columns as a string (casting null into the nil (empty) string
    string[] values = new string[dt.Columns.Count];
    for ( int i = 0 ; i < dt.Columns.Count ; ++i )
    {
      values[i] = ((string) dr[i]) ?? "" ; // we'll treat nulls as the nil string for the nonce
    }

    // construct the string to be dumped, quoting each value and doubling any embedded quotes.
    string data = string.Join( ";" , values.Select( s => "\""+s.Replace("\"","\"\"")+"\"") ) ;
    Console.WriteLine(values);

  }

}

String contains - ignore case

You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

Pattern.compile(Pattern.quote(strptrn), Pattern.CASE_INSENSITIVE).matcher(str1).find();

Bootstrap modal - close modal when "call to action" button is clicked

Use data-dismiss="modal". In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal" is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function

 <a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>

In some external script file, and in my doc ready there is of course a function for the click of that identifier ID

 $("#divExamListHeader").on('click', '#btnReleaseAll', function () {
               // Do DatabaseMagic Here for a call a MVC ActionResult

Passing command line arguments in Visual Studio 2010?

Under Project->Properties->Debug, you should see a box for Command line arguments (This is in C# 2010, but it should basically be the same place)

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

Some apps are marked as less secure by google, so you just need to give access for those app so google will allow you to access its services to you.

follow this http://www.codematrics.com/your-imap-server-wants-to-alert-you-to-the-following-please-login-via-your-web-browser-gmail/

VB.net: Date without time

Either use one of the standard date and time format strings which only specifies the date (e.g. "D" or "d"), or a custom date and time format string which only uses the date parts (e.g. "yyyy/MM/dd").

compare two list and return not matching items using linq

Try,

  public class Sent
{
    public int MsgID;
    public string Content;
    public int Status;

}

public class Messages
{
    public int MsgID;
    public string Content;
}

  List<Sent> SentList = new List<Sent>() { new Sent() { MsgID = 1, Content = "aaa", Status = 0 }, new Sent() { MsgID = 3, Content = "ccc", Status = 0 } };
            List<Messages> MsgList = new List<Messages>() { new Messages() { MsgID = 1, Content = "aaa" }, new Messages() { MsgID = 2, Content = "bbb" }, new Messages() { MsgID = 3, Content = "ccc" }, new Messages() { MsgID = 4, Content = "ddd" }, new Messages() { MsgID = 5, Content = "eee" }};

            int [] sentMsgIDs = SentList.Select(v => v.MsgID).ToArray();
            List<Messages> result1 = MsgList.Where(o => !sentMsgIDs.Contains(o.MsgID)).ToList<Messages>();

Hope it should help.

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

I ran into this error when I had a .jsx and .scss file in the same directory with the same root name.

So, for example, if you have Component.jsx and Component.scss in the same folder and you try to do this:

import Component from ./Component

Webpack apparently gets confused and, at least in my case, tries to import the scss file when I really want the .jsx file.

I was able to fix it by renaming the .scss file and avoiding the ambiguity. I could have also explicitly imported Component.jsx

Print the contents of a DIV

I think the solutions proposed so far have the following drawbacks:

  1. The CSS media query solutions assume there is only one div to print.
  2. The javascript solutions work only on certain browsers.
  3. Destroying the parent window content and recreating that creates a mess.

I have improved on the solutions above. Here is something that I have tested that works really well with the following benefits.

  1. Works on all the browsers including IE, Chrome, Safari and firefox.
  2. Doesn't destroy and reload the parent window.
  3. Can print any number of DIV's in a page.
  4. Uses html templates to avoid error prone string concatenation.

Key Points to note :

  1. Have to have a onload="window.print()" on the newly created window.
  2. Don't call targetwindow.close() or targetwindow.print() from the parent.
  3. Make sure you do targetwindow.document.close() and target.focus()
  4. I'm using jquery but you can do the same technique using plain javascript as well.
  5. You can see this in action here http://math.tools/table/multiplication. You can print each table separately, by clicking on the print button on the box header.

_x000D_
_x000D_
<script id="print-header" type="text/x-jquery-tmpl">_x000D_
   <html>_x000D_
   <header>_x000D_
       <title>Printing Para {num}</title>_x000D_
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
       <style>_x000D_
          body {_x000D_
            max-width: 300px;_x000D_
          }_x000D_
       </style>_x000D_
   </header>_x000D_
   <body onload="window.print()">_x000D_
   <h2>Printing Para {num} </h2>_x000D_
   <h4>http://math.tools</h4>_x000D_
</script>_x000D_
<script id="print-footer" type="text/x-jquery-tmpl">_x000D_
    </body>_x000D_
    </html>_x000D_
</script>_x000D_
<script>_x000D_
$('.printthis').click(function() {_x000D_
   num = $(this).attr("data-id");_x000D_
   w = window.open();_x000D_
   w.document.write(_x000D_
                   $("#print-header").html().replace("{num}",num)  +_x000D_
                   $("#para-" + num).html() +_x000D_
                   $("#print-footer").html() _x000D_
                   );_x000D_
   w.document.close();_x000D_
   w.focus();_x000D_
   //w.print(); Don't do this otherwise chrome won't work. Look at the onload on the body of the newly created window._x000D_
   ///w.close(); Don't do this otherwise chrome won't work_x000D_
});_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<a class="btn printthis" data-id="1" href="#" title="Print Para 1"><i class="fa fa-print"></i> Print Para 1</a>_x000D_
<a class="btn printthis" data-id="2" href="#" title="Print Para 2"><i class="fa fa-print"></i> Print Para 2</a>_x000D_
  _x000D_
<p class="para" id="para-1">_x000D_
  Para 1 : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
  _x000D_
_x000D_
<p class="para" id="para-2">_x000D_
  Para 2 : Lorem 2 ipsum 2 dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
  
_x000D_
_x000D_
_x000D_

Changing button text onclick

There are lots of ways. And this should work too in all browsers and you don't have to use document.getElementById anymore since you're passing the element itself to the function.

<input type="button" value="Open Curtain" onclick="return change(this);" />

<script type="text/javascript">
function change( el )
{
    if ( el.value === "Open Curtain" )
        el.value = "Close Curtain";
    else
        el.value = "Open Curtain";
}
</script>

CSS scrollbar style cross browser

try this it's very easy to use and tested on IE and Safari and FF and worked fine and beside no need for many div around it just add id and it will work fine, after you link you Js and Css files. FaceScroll Custom scrollbar

hope it help's

Edit Step 1: Add the below script to the section of your page:

<link href="general.css" rel="stylesheet" type="text/css">

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript" src="jquery.ui.touch-punch.min.js"></script>

<script type="text/javascript" src="facescroll.js"></script>
<script type="text/javascript">
    jQuery(function(){ // on page DOM load
        $('#demo1').alternateScroll();
        $('#demo2').alternateScroll({ 'vertical-bar-class': 'styled-v-bar', 'hide-bars': false });  
    })
</script>

Step 2: Then in the BODY of your page, add the below sample HTML block to your page.

<p><b>Scrollbar (default style) shows onMouseover</b></p>

<div id="demo1" style="width:300px; height:250px; padding:8px; background:lightyellow; border:1px solid gray; resize:both; overflow:scroll">

From Wikipedia- Gunpowder, also known since in the late 19th century as black powder, was the first chemical explosive and the only one known until the mid 1800s.[2] It is a mixture of sulfur, charcoal, and potassium nitrate (saltpeter) - with the sulfur and charcoal acting as fuels, while the saltpeter works as an oxidizer.[3] Because of its 
</div>

<br />

<p><b>Scrollbar (alternate style), always shown</b></p>

<div id="demo2" style="width:400px; height:130px; padding:10px; padding-right:8px; background:lightyellow; border:1px solid gray; overflow:scroll; resize:both;">

From Wikipedia- Gunpowder, also known since in the late 19th century as black powder, was the first chemical explosive and the only one known until the mid 1800s.[2] It is a mixture of sulfur, charcoal, and potassium nitrate (saltpeter) - with the sulfur and charcoal acting as fuels, while the saltpeter works as an oxidizer.[3] Because of its 
</div>

How do you create vectors with specific intervals in R?

Usually, we want to divide our vector into a number of intervals. In this case, you can use a function where (a) is a vector and (b) is the number of intervals. (Let's suppose you want 4 intervals)

a <- 1:10
b <- 4

FunctionIntervalM <- function(a,b) {
  seq(from=min(a), to = max(a), by = (max(a)-min(a))/b)
}

FunctionIntervalM(a,b)
# 1.00  3.25  5.50  7.75 10.00

Therefore you have 4 intervals:

1.00 - 3.25 
3.25 - 5.50
5.50 - 7.75
7.75 - 10.00

You can also use a cut function

  cut(a, 4)

# (0.991,3.25] (0.991,3.25] (0.991,3.25] (3.25,5.5]   (3.25,5.5]   (5.5,7.75]  
# (5.5,7.75]   (7.75,10]    (7.75,10]    (7.75,10]   
#Levels: (0.991,3.25] (3.25,5.5] (5.5,7.75] (7.75,10]

Powershell 2 copy-item which creates a folder if doesn't exist

Here's an example that worked for me. I had a list of about 500 specific files in a text file, contained in about 100 different folders, that I was supposed to copy over to a backup location in case those files were needed later. The text file contained full path and file name, one per line. In my case, I wanted to strip off the Drive letter and first sub-folder name from each file name. I wanted to copy all these files to a similar folder structure under another root destination folder I specified. I hope other users find this helpful.

# Copy list of files (full path + file name) in a txt file to a new destination, creating folder structure for each file before copy
$rootDestFolder = "F:\DestinationFolderName"
$sourceFiles = Get-Content C:\temp\filelist.txt
foreach($sourceFile in $sourceFiles){
    $filesplit = $sourceFile.split("\")
    $splitcount = $filesplit.count
    # This example strips the drive letter & first folder ( ex: E:\Subfolder\ ) but appends the rest of the path to the rootDestFolder
    $destFile = $rootDestFolder + "\" + $($($sourceFile.split("\")[2..$splitcount]) -join "\")
    # Output List of source and dest 
    Write-Host ""
    Write-Host "===$sourceFile===" -ForegroundColor Green
    Write-Host "+++$destFile+++"
    # Create path and file, if they do not already exist
    $destPath = Split-Path $destFile
    If(!(Test-Path $destPath)) { New-Item $destPath -Type Directory }
    If(!(Test-Path $destFile)) { Copy-Item $sourceFile $destFile }
}

Git Bash is extremely slow on Windows 7 x64

I solved my slow Git problem on Windows 7 x64 by starting cmd.exe with "Run as administrator".

Install GD library and freetype on Linux

Installing GD :

For CentOS / RedHat / Fedora :

sudo yum install php-gd

For Debian/ubuntu :

sudo apt-get install php5-gd

Installing freetype :

For CentOS / RedHat / Fedora :

sudo yum install freetype*

For Debian/ubuntu :

sudo apt-get install freetype*

Don't forget to restart apache after that (if you are using apache):

CentOS / RedHat / Fedora :

sudo /etc/init.d/httpd restart

Or

sudo service httpd restart

Debian/ubuntu :

sudo /etc/init.d/apache2 restart

Or

sudo service apache2 restart

Setting value of active workbook in Excel VBA

Try this.

Dim Workbk as workbook
Set Workbk = thisworkbook

Now everything you program will apply just for your containing macro workbook.

How to Correctly Use Lists in R?

Just to add one more point to this:

R does have a data structure equivalent to the Python dict in the hash package. You can read about it in this blog post from the Open Data Group. Here's a simple example:

> library(hash)
> h <- hash( keys=c('foo','bar','baz'), values=1:3 )
> h[c('foo','bar')]
<hash> containing 2 key-value pairs.
  bar : 2
  foo : 1

In terms of usability, the hash class is very similar to a list. But the performance is better for large datasets.

Why is __dirname not defined in node REPL?

As @qiao said, you can't use __dirname in the node repl. However, if you need need this value in the console, you can use path.resolve() or path.dirname(). Although, path.dirname() will just give you a "." so, probably not that helpful. Be sure to require('path').

Can I change a column from NOT NULL to NULL without dropping it?

For MYSQL

ALTER TABLE myTable MODIFY myColumn {DataType} NULL

TOMCAT - HTTP Status 404

To get your program to run, please put jsp files under web-content and not under WEB-INF because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:

http://localhost:8080/YourProject/yourfile.jsp

then your problem will be solved.

How can you integrate a custom file browser/uploader with CKEditor?

An article at zerokspot entitled Custom filebrowser callbacks in CKEditor 3.0 handles this. The most relevant section is quoted below:

So all you have to do from the file browser when you have a file selected is to call this code with the right callback number (normally 1) and the URL of the selected file:

window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum,url);

For the quick-uploader the process is quite similar. At first I thought that the editor might be listening for a 200 HTTP return code and perhaps look into some header field or something like that to determine the location of the uploaded file, but then - through some Firebug monitoring - I noticed that all that happens after an upload is the following code:

<script type="text/javascript">
window.parent.CKEDITOR.tools.callFunction(CKEditorFuncNum,url, errorMessage); </script>

If the upload failed, set the errorMessage to some non-zero-length string and empty the url, and vice versa on success.

creating an array of structs in c++

It works perfectly. I have gcc compiler C++11 ready. Try this and you'll see:

#include <iostream>

using namespace std;

int main()
{
    int pause;

    struct Customer
    {
           int uid;
           string name;
    };

    Customer customerRecords[2];
    customerRecords[0] = {25, "Bob Jones"};
    customerRecords[1] = {26, "Jim Smith"};
    cout << customerRecords[0].uid << " " << customerRecords[0].name << endl;
    cout << customerRecords[1].uid << " " << customerRecords[1].name << endl;
    cin >> pause;
return 0;
}

Best way to store passwords in MYSQL database

You should use one way encryption (which is a way to encrypt a value so that is very hard to revers it). I'm not familiar with MySQL, but a quick search shows that it has a password() function that does exactly this kind of encryption. In the DB you will store the encrypted value and when the user wants to authenticate you take the password he provided, you encrypt it using the same algorithm/function and then you check that the value is the same with the password stored in the database for that user. This assumes that the communication between the browser and your server is secure, namely that you use https.

What is the equivalent of "none" in django templates?

{% if profile.user.first_name %} works (assuming you also don't want to accept '').

if in Python in general treats None, False, '', [], {}, ... all as false.

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

Page redirect after certain time PHP

Redirect PHP time programming:

 <?php
 header("Refresh:10;url=***-----índex.php--OR----URL-----");
 ?>

Delete certain lines in a txt file via a batch file

If you have sed:

sed -e '/REFERENCE/d' -e '/ERROR/d' [FILENAME]

Where FILENAME is the name of the text file with the good & bad lines

c# Image resizing to different size while preserving aspect ratio

Just generalizing it down to aspect ratios and sizes, image stuff can be done outside of this function

public static d.RectangleF ScaleRect(d.RectangleF dest, d.RectangleF src, 
  bool keepWidth, bool keepHeight)  
{
    d.RectangleF destRect = new d.RectangleF();

    float sourceAspect = src.Width / src.Height;
    float destAspect = dest.Width / dest.Height;

    if (sourceAspect > destAspect)
    {
        // wider than high keep the width and scale the height
        destRect.Width = dest.Width;
        destRect.Height = dest.Width / sourceAspect;

        if (keepHeight)
        {
            float resizePerc = dest.Height / destRect.Height;
            destRect.Width = dest.Width * resizePerc;
            destRect.Height = dest.Height;
        }
    }
    else
    {
        // higher than wide – keep the height and scale the width
        destRect.Height = dest.Height;
        destRect.Width = dest.Height * sourceAspect;

        if (keepWidth)
        {
            float resizePerc = dest.Width / destRect.Width;
            destRect.Width = dest.Width;
            destRect.Height = dest.Height * resizePerc;
        }

    }

    return destRect;
}

How to use multiple LEFT JOINs in SQL?

The required SQL will be some like:-

SELECT * FROM cd
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cd.sht
....

Hope it helps.

Use python requests to download CSV

The following approach worked well for me. I also did not need to use csv.reader() or csv.writer() functions, which I feel makes the code cleaner. The code is compatible with Python2 and Python 3.

from six.moves import urllib

DOWNLOAD_URL = "https://raw.githubusercontent.com/gjreda/gregreda.com/master/content/notebooks/data/city-of-chicago-salaries.csv"
DOWNLOAD_PATH ="datasets\city-of-chicago-salaries.csv" 
urllib.request.urlretrieve(URL,DOWNLOAD_PATH)

Note - six is a package that helps in writing code that is compatible with both Python 2 and Python 3. For additional details regarding six see - What does from six.moves import urllib do in Python?

Java String declaration

String str = new String("SOME")

always create a new object on the heap

String str="SOME" 

uses the String pool

Try this small example:

        String s1 = new String("hello");
        String s2 = "hello";
        String s3 = "hello";

        System.err.println(s1 == s2);
        System.err.println(s2 == s3);

To avoid creating unnecesary objects on the heap use the second form.

How can I wait for 10 second without locking application UI in android

do this on a new thread (seperate it from main thread)

 new Thread(new Runnable() {
     @Override
     public void run() {
        // TODO Auto-generated method stub
     }
}).run();

multiple where condition codeigniter

Yes, multiple calls to where() is a perfectly valid way to achieve this.

$this->db->where('username',$username);
$this->db->where('status',$status);

http://www.codeigniter.com/user_guide/database/query_builder.html