Programs & Examples On #Software update

A new version of a software for any computer program. It can be better in performance and may include several new features.

How do I update Node.js?

You may use Chocolatey on Windows. It's very easy to use and useful for keeping you updated with other applications too.

Also, you can just simply download the latest version from https://nodejs.org and install it.

AngularJS. How to call controller function from outside of controller component

I've found an example on the internet.

Some guy wrote this code and worked perfectly

HTML

<div ng-cloak ng-app="ManagerApp">
    <div id="MainWrap" class="container" ng-controller="ManagerCtrl">
       <span class="label label-info label-ext">Exposing Controller Function outside the module via onClick function call</span>
       <button onClick='ajaxResultPost("Update:Name:With:JOHN","accept",true);'>click me</button>
       <br/> <span class="label label-warning label-ext" ng-bind="customParams.data"></span>
       <br/> <span class="label label-warning label-ext" ng-bind="customParams.type"></span>
       <br/> <span class="label label-warning label-ext" ng-bind="customParams.res"></span>
       <br/>
       <input type="text" ng-model="sampletext" size="60">
       <br/>
    </div>
</div>

JAVASCRIPT

var angularApp = angular.module('ManagerApp', []);
angularApp.controller('ManagerCtrl', ['$scope', function ($scope) {

$scope.customParams = {};

$scope.updateCustomRequest = function (data, type, res) {
    $scope.customParams.data = data;
    $scope.customParams.type = type;
    $scope.customParams.res = res;
    $scope.sampletext = "input text: " + data;
};



}]);

function ajaxResultPost(data, type, res) {
    var scope = angular.element(document.getElementById("MainWrap")).scope();
    scope.$apply(function () {
    scope.updateCustomRequest(data, type, res);
    });
}

Demo

*I did some modifications, see original: font JSfiddle

Java: How to convert String[] to List or Set

Whilst this isn't strictly an answer to this question I think it's useful.

Arrays and Collections can bother be converted to Iterable which can avoid the need for performing a hard conversion.

For instance I wrote this to join lists/arrays of stuff into a string with a seperator

public static <T> String join(Iterable<T> collection, String delimiter) {
    Iterator<T> iterator = collection.iterator();
    if (!iterator.hasNext())
        return "";

    StringBuilder builder = new StringBuilder();

    T thisVal = iterator.next();
    builder.append(thisVal == null? "": thisVal.toString());

    while (iterator.hasNext()) {
        thisVal = iterator.next();
        builder.append(delimiter);
        builder.append(thisVal == null? "": thisVal.toString());
    }

    return builder.toString();
}

Using iterable means you can either feed in an ArrayList or similar aswell as using it with a String... parameter without having to convert either.

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

If you are using version 2.2 and above of Android Studio then in Android Studio use Build ? Analyze APK then select AndroidManifest.xml file.

Spring RequestMapping for controllers that produce and consume JSON

You shouldn't need to configure the consumes or produces attribute at all. Spring will automatically serve JSON based on the following factors.

  • The accepts header of the request is application/json
  • @ResponseBody annotated method
  • Jackson library on classpath

You should also follow Wim's suggestion and define your controller with the @RestController annotation. This will save you from annotating each request method with @ResponseBody

Another benefit of this approach would be if a client wants XML instead of JSON, they would get it. They would just need to specify xml in the accepts header.

Disable the postback on an <ASP:LinkButton>

use html link instead of asp link and you can use label in between html link for server side control

Conditionally hide CommandField or ButtonField in Gridview

To conditionally control view of Template/Command fields, use RowDataBound event of Gridview, like:

    <asp:GridView ID="gv1" OnRowDataBound="gv1_RowDataBound"
              runat="server" AutoGenerateColumns="False" DataKeyNames="Id" >
    <Columns>   
        ...        
           <asp:TemplateField HeaderText="Order Status" 
HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"> 
                 <ItemTemplate> 
                       <asp:Label ID="lblOrderStatus" runat="server"
Text='<%# Bind("OrderStatus") %>'></asp:Label> 
                 </ItemTemplate>
                 <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
                 <ItemStyle HorizontalAlign="Center"></ItemStyle>
           </asp:TemplateField>  
        ...

            <asp:CommandField ShowSelectButton="True" SelectText="Select" />

    </Columns>
                </asp:GridView>

and following:

protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        Label lblOrderStatus=(Label) e.Row.Cells[4].FindControl("lblOrderStatus");

        if (lblOrderStatus.Text== "Ordered")
        {
            lblOrderStatus.ForeColor = System.Drawing.Color.DarkBlue;
            LinkButton bt = (LinkButton)e.Row.Cells[5].Controls[0];
            bt.Visible = false;
            e.Row.BackColor = System.Drawing.Color.LightGray;
        }
    }

Create a sample login page using servlet and JSP?

You aren't really using the doGet() method. When you're opening the page, it issues a GET request, not POST.

Try changing doPost() to service() instead... then you're using the same method to handle GET and POST requests.

...

How to download a file from my server using SSH (using PuTTY on Windows)

There's no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.

Though PuTTY supports connection-sharing.

While you still need to run a compatible file transfer client (pscp or psftp), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.

To enable the sharing see:
Sharing an SSH connection between PuTTY tools.


Even without connection-sharing, you can still use the psftp or pscp from Windows command line.

See How to use PSCP to copy file from Unix machine to Windows machine ...?

Note that the scp is OpenSSH program. It's primarily *nix program, but you can run it via Windows Subsystem for Linux or get a Windows build from Win32-OpenSSH (it is already built-in in the latest versions of Windows 10).


If you really want to download the files to a local desktop, you have to specify a target path as %USERPROFILE%\Desktop (what typically resolves to a path like C:\Users\username\Desktop).


Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY command.
See Opening Session in PuTTY.

With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.
See Opening PuTTY in the same directory.

(I'm the author of WinSCP)

Debugging "Element is not clickable at point" error

You can also use JavaScript click and scrolling would be not required then.

IJavaScriptExecutor ex = (IJavaScriptExecutor)Driver;
ex.ExecuteScript("arguments[0].click();", elementToClick);

select records from postgres where timestamp is in certain range

SELECT * 
FROM reservations 
WHERE arrival >= '2012-01-01'
AND arrival < '2013-01-01'
   ;

BTW if the distribution of values indicates that an index scan will not be the worth (for example if all the values are in 2012), the optimiser could still choose a full table scan. YMMV. Explain is your friend.

rbind error: "names do not match previous names"

The names of the first dataframe do not match the names of the second one. Just as the error message says.

> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE

If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:

> names(xd.small[[1]]) <- names(xd.small[[2]]) 
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE

Then things should proceed happily.

Case insensitive regular expression without re.compile?

Pass re.IGNORECASE to the flags param of search, match, or sub:

re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)

phpmyadmin "Not Found" after install on Apache, Ubuntu

Finally I got the solution

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
sudo a2enconf phpmyadmin
sudo service apache2 reload

More about https://askubuntu.com/questions/55280/phpmyadmin-is-not-working-after-i-installed-it

Access parent DataContext from DataTemplate

RelativeSource vs. ElementName

These two approaches can achieve the same result,

RelativeSource

Binding="{Binding Path=DataContext.MyBindingProperty, 
          RelativeSource={RelativeSource AncestorType={x:Type Window}}}"

This method looks for a control of a type Window (in this example) in the visual tree and when it finds it you basically can access it's DataContext using the Path=DataContext..... The Pros about this method is that you don't need to be tied to a name and it's kind of dynamic, however, changes made to your visual tree can affect this method and possibly break it.

ElementName

Binding="{Binding Path=DataContext.MyBindingProperty, ElementName=MyMainWindow}

This method referes to a solid static Name so as long as your scope can see it, you're fine.You should be sticking to your naming convention not to break this method of course.The approach is qute simple and all you need is to specify a Name="..." for your Window/UserControl.

Although all three types (RelativeSource, Source, ElementName) are capable of doing the same thing, but according to the following MSDN article, each one better be used in their own area of specialty.

How to: Specify the Binding Source

Find the brief description of each plus a link to a more details one in the table on the bottom of the page.

How to send Basic Auth with axios

If you are trying to do basic auth, you can try this:

const username = ''
const password = ''

const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')

const url = 'https://...'
const data = {
...
}

axios.post(url, data, {
  headers: {
 'Authorization': `Basic ${token}`
},
})

This worked for me. Hope that helps

127 Return code from $?

127 - command not found

example: $caat The error message will

bash:

caat: command not found

now you check using echo $?

JavaScript: What are .extend and .prototype used for?

.extend() is added by many third-party libraries to make it easy to create objects from other objects. See http://api.jquery.com/jQuery.extend/ or http://www.prototypejs.org/api/object/extend for some examples.

.prototype refers to the "template" (if you want to call it that) of an object, so by adding methods to an object's prototype (you see this a lot in libraries to add to String, Date, Math, or even Function) those methods are added to every new instance of that object.

Bootstrap 4 Change Hamburger Toggler Color

Easiest way is replace this default bootstrap code:

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
</button>

by this :

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="" role="button" ><i class="fa fa-bars" aria-hidden="true" style="color:#e6e6ff"></i></span>
</button>

And don't forget to add this code also to your file:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> 

Hope it helps!!

Create Map in Java

Map<Integer, Point2D> hm = new HashMap<Integer, Point2D>();

Set ANDROID_HOME environment variable in mac

If some one is still finding difficulties, i have made a video on this

https://www.youtube.com/watch?v=tbLAHKhjjI4

Because the new version of Apple does not support bash shell so i have explained in details how do we set variables in 2020.

Get all table names of a particular database by SQL query?

USE dbName;

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_SCHEMA = 'dbName' OR TABLE_SCHEMA = 'schemaName')
ORDER BY TABLE_NAME

If you are working with multiple schemata on an MS SQL server, then SELECT-ing TABLE_NAME without also simultaneously selecting TABLE_SCHEMA might be of limited benefit, so I have assumed we are interested in the tables belonging to a known schema when using MS SQL Server.

I have tested the query above with SQL Server Management Studio using an SQL Server database of mine and with MySQL Workbench using a MySQL database, and in both cases it gives the table names.

The query bodges Michael Baylon's two different queries into one that can then run on either database type. The first part of the WHERE clause works on MySQL databases and the second part (after the OR) works on MS SQL Server databases. It is ugly and logically a little incorrect as it supposes that there is no undesired schema with the same name as the database. This might help someone who is looking for one single query that can run on either database server.

Path of assets in CSS files in Symfony 2

If it can help someone, we have struggled a lot with Assetic, and we are now doing the following in development mode:

  • Set up like in Dumping Asset Files in the dev Environmen so in config_dev.yml, we have commented:

    #assetic:
    #    use_controller: true
    

    And in routing_dev.yml

    #_assetic:
    #    resource: .
    #    type:     assetic
    
  • Specify the URL as absolute from the web root. For example, background-image: url("/bundles/core/dynatree/skins/skin/vline.gif"); Note: our vhost web root is pointing on web/.

  • No usage of cssrewrite filter

How to quickly and conveniently disable all console.log statements in my code?

You should not!

It is not a good practice to overwrite built-in functions. There is also no guarantee that you will suppress all output, other libraries you use may revert your changes and there are other functions that may write to the console; .dir(), .warning(), .error(), .debug(), .assert() etc.

As some suggested, you could define a DEBUG_MODE variable and log conditionally. Depending on the complexity and nature of your code, it may be a good idea to write your own logger object/function that wraps around the console object and has this capability built-in. That would be the right place to do deal with instrumentation.

That said, for 'testing' purposes you can write tests instead of printing to the console. If you are not doing any testing, and those console.log() lines were just an aid to write your code, simply delete them.

How to read first N lines of a file?

Python 2:

with open("datafile") as myfile:
    head = [next(myfile) for x in xrange(N)]
print head

Python 3:

with open("datafile") as myfile:
    head = [next(myfile) for x in range(N)]
print(head)

Here's another way (both Python 2 & 3):

from itertools import islice

with open("datafile") as myfile:
    head = list(islice(myfile, N))
print(head)

Converting milliseconds to a date (jQuery/JavaScript)

/Date(1383066000000)/

function convertDate(data) {
    var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
    var ConvDate= new Date(getdate);
    return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

Error inflating class fragment

If you use obfuscation with Navigation component you need to exclude android's fragment and your args. Add these lines to your proguard-rules files:

# Exclude the fragments and argType for navigation component.
-keep class * extends androidx.fragment.app.Fragment{}
-keep class com.safetonet.presentation.features.parent.adddevice.model.PresentableAddDeviceData

Limit on the WHERE col IN (...) condition

Depending on your version, use a table valued parameter in 2008, or some approach described here:

Arrays and Lists in SQL Server 2005

How to enable multidexing with the new Android Multidex support library

If you want to enable multi-dex in your project then just go to gradle.builder

and add this in your dependencie

 dependencies {
   compile 'com.android.support:multidex:1.0.0'}

then you have to add

 defaultConfig {
...
minSdkVersion 14
targetSdkVersion 21
...

// Enabling multidex support.
multiDexEnabled true}

Then open a class and extand it to Application If your app uses extends the Application class, you can override the oncrete() method and call

   MultiDex.install(this) 

to enable multidex.

and finally add into your manifest

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
   ...
     android:name="android.support.multidex.MultiDexApplication">
   ...
   </application>
 </manifest> 

Inline <style> tags vs. inline css properties

There can be different reasons for choosing one way over the other.

  • If you need to specify css to elements that are generated programmatically (for example modifying css for images of different sizes), it can be more maintainable to use inline css.
  • If some css is valid only for the current page, you should rather use the script tag than a separate .css file. It is good if the browser doesn't have to do too many http requests.

Otherwise, as stated, it is better to use a separate css file.

Making heatmap from pandas DataFrame

Surprised to see no one mentioned more capable, interactive and easier to use alternatives.

A) You can use plotly:

  1. Just two lines and you get:

  2. interactivity,

  3. smooth scale,

  4. colors based on whole dataframe instead of individual columns,

  5. column names & row indices on axes,

  6. zooming in,

  7. panning,

  8. built-in one-click ability to save it as a PNG format,

  9. auto-scaling,

  10. comparison on hovering,

  11. bubbles showing values so heatmap still looks good and you can see values wherever you want:

import plotly.express as px
fig = px.imshow(df.corr())
fig.show()

enter image description here

B) You can also use Bokeh:

All the same functionality with a tad much hassle. But still worth it if you do not want to opt-in for plotly and still want all these things:

from bokeh.plotting import figure, show, output_notebook
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.transform import transform
output_notebook()
colors = ['#d7191c', '#fdae61', '#ffffbf', '#a6d96a', '#1a9641']
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
data = df.corr().stack().rename("value").reset_index()
p = figure(x_range=list(df.columns), y_range=list(df.index), tools=TOOLS, toolbar_location='below',
           tooltips=[('Row, Column', '@level_0 x @level_1'), ('value', '@value')], height = 500, width = 500)

p.rect(x="level_1", y="level_0", width=1, height=1,
       source=data,
       fill_color={'field': 'value', 'transform': LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max())},
       line_color=None)
color_bar = ColorBar(color_mapper=LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max()), major_label_text_font_size="7px",
                     ticker=BasicTicker(desired_num_ticks=len(colors)),
                     formatter=PrintfTickFormatter(format="%f"),
                     label_standoff=6, border_line_color=None, location=(0, 0))
p.add_layout(color_bar, 'right')

show(p)

enter image description here

Why can't I duplicate a slice with `copy()`?

NOTE: This is an incorrect solution as @benlemasurier proved

Here is a way to copy a slice. I'm a bit late, but there is a simpler, and faster answer than @Dave's. This are the instructions generated from a code like @Dave's. These is the instructions generated by mine. As you can see there are far fewer instructions. What is does is it just does append(slice), which copies the slice. This code:

package main

import "fmt"

func main() {
    var foo = []int{1, 2, 3, 4, 5}
    fmt.Println("foo:", foo)
    var bar = append(foo)
    fmt.Println("bar:", bar)
    bar = append(bar, 6)
    fmt.Println("foo after:", foo)
    fmt.Println("bar after:", bar)
}

Outputs this:

foo: [1 2 3 4 5]
bar: [1 2 3 4 5]
foo after: [1 2 3 4 5]
bar after: [1 2 3 4 5 6]

React prevent event bubbling in nested components on click

This is not 100% ideal, but if it is either too much of a pain to pass down props in children -> children fashion or create a Context.Provider/Context.Consumer just for this purpose), and you are dealing with another library which has it's own handler it runs before yours, you can also try:

   function myHandler(e) { 
        e.persist(); 
        e.nativeEvent.stopImmediatePropagation();
        e.stopPropagation(); 
   }

From what I understand, the event.persist method prevents an object from immediately being thrown back into React's SyntheticEvent pool. So because of that, the event passed in React actually doesn't exist by the time you reach for it! This happens in grandchildren because of the way React handle's things internally by first checking parent on down for SyntheticEvent handlers (especially if the parent had a callback).

As long as you are not calling persist on something which would create significant memory to keep creating events such as onMouseMove (and you are not creating some kind of Cookie Clicker game like Grandma's Cookies), it should be perfectly fine!

Also note: from reading around their GitHub occasionally, we should keep our eyes out for future versions of React as they may eventually resolve some of the pain with this as they seem to be going towards making folding React code in a compiler/transpiler.

How can I set the request header for curl?

Sometimes changing the header is not enough, some sites check the referer as well:

curl -v \
     -H 'Host: restapi.some-site.com' \
     -H 'Connection: keep-alive' \
     -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
     -H 'Accept-Language: en-GB,en-US;q=0.8,en;q=0.6' \
     -e localhost \
     -A 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36' \
     'http://restapi.some-site.com/getsomething?argument=value&argument2=value'

In this example the referer (-e or --referer in curl) is 'localhost'.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Just one line and it solved my issue.

sudo dpkg-reconfigure mysql-server-5.5

Inline for loop

q  = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
vm = [-1, -1, -1, -1,1,2,3,1]

p = []
for v in vm:
    if v in q:
        p.append(q.index(v))
    else:
        p.append(99999)

print p
p = [q.index(v) if v in q else 99999 for v in vm]
print p

Output:

[99999, 99999, 99999, 99999, 0, 1, 2, 0]
[99999, 99999, 99999, 99999, 0, 1, 2, 0]

Instead of using append() in the list comprehension you can reference the p as direct output, and use q.index(v) and 99999 in the LC.

Not sure if this is intentional but note that q.index(v) will find just the first occurrence of v, even tho you have several in q. If you want to get the index of all v in q, consider using a enumerator and a list of already visited indexes

Something in those lines(pseudo-code):

visited = []
for i, v in enumerator(vm):
   if i not in visited:
       p.append(q.index(v))
   else:
       p.append(q.index(v,max(visited))) # this line should only check for v in q after the index of max(visited)
   visited.append(i)

When do I need to use a semicolon vs a slash in Oracle SQL?

I know this is an old thread, but I just stumbled upon it and I feel this has not been explained completely.

There is a huge difference in SQL*Plus between the meaning of a / and a ; because they work differently.

The ; ends a SQL statement, whereas the / executes whatever is in the current "buffer". So when you use a ; and a / the statement is actually executed twice.

You can easily see that using a / after running a statement:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:37:20 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> drop table foo;

Table dropped.

SQL> /
drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

In this case one actually notices the error.


But assuming there is a SQL script like this:

drop table foo;
/

And this is run from within SQL*Plus then this will be very confusing:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Apr 18 12:38:05 2012

Copyright (c) 1982, 2010, Oracle.  All rights reserved.


Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
With the Partitioning and OLAP options

SQL> @drop

Table dropped.

drop table foo
           *
ERROR at line 1:
ORA-00942: table or view does not exist

The / is mainly required in order to run statements that have embedded ; like a CREATE PROCEDURE statement.

How to add elements to a list in R (loop)

The following adds elements to a list in a loop.

l<-c()
i=1

while(i<100) {

    b<-i
    l<-c(l,b)
    i=i+1
}

How do I send a JSON string in a POST request in Go

If you already have a struct.

import (
    "bytes"
    "encoding/json"
    "io"
    "net/http"
    "os"
)

// .....

type Student struct {
    Name    string `json:"name"`
    Address string `json:"address"`
}

// .....

body := &Student{
    Name:    "abc",
    Address: "xyz",
}

payloadBuf := new(bytes.Buffer)
json.NewEncoder(payloadBuf).Encode(body)
req, _ := http.NewRequest("POST", url, payloadBuf)

client := &http.Client{}
res, e := client.Do(req)
if e != nil {
    return e
}

defer res.Body.Close()

fmt.Println("response Status:", res.Status)
// Print the body to the stdout
io.Copy(os.Stdout, res.Body)

Full gist.

How to recursively delete an entire directory with PowerShell 2.0?

del <dir> -Recurse -Force # I prefer this, short & sweet

OR

remove-item <dir> -Recurse -Force

If you have a huge directory then what I usually do is

while (dir | where name -match <dir>) {write-host deleting; sleep -s 3}

Run this on another powershell terminal and it will stop when it is done.

Mockito verify order / sequence of method calls

InOrder helps you to do that.

ServiceClassA firstMock = mock(ServiceClassA.class);
ServiceClassB secondMock = mock(ServiceClassB.class);

Mockito.doNothing().when(firstMock).methodOne();   
Mockito.doNothing().when(secondMock).methodTwo();  

//create inOrder object passing any mocks that need to be verified in order
InOrder inOrder = inOrder(firstMock, secondMock);

//following will make sure that firstMock was called before secondMock
inOrder.verify(firstMock).methodOne();
inOrder.verify(secondMock).methodTwo();

How to move child element from one parent to another using jQuery

$('#parent2').prepend($('#table1_length')).prepend($('#table1_filter'));

doesn't work for you? I think it should...

Python: Continuing to next iteration in outer loop

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            break
    else:
        ...block1...

Break will break the inner loop, and block1 won't be executed (it will run only if the inner loop is exited normally).

How to add a new project to Github using VS Code

Install git on your PC and setup configuration values in either Command Prompt (cmd) or VS Code terminal (Ctrl + `)

git config --global user.name "Your Name"
git config --global user.email [email protected]

Setup editor

Windows eg.:

git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -nosession"

Linux / Mac eg.:

git config --global core.editor vim

Check git settings which displays configuration details

git config --list

Login to github and create a remote repository. Copy the URL of this repository

Navigate to your project directory and execute the below commands

git init                                                           // start tracking current directory
git add -A                                                         // add all files in current directory to staging area, making them available for commit
git commit -m "commit message"                                     // commit your changes
git remote add origin https://github.com/username/repo-name.git    // add remote repository URL which contains the required details
git pull origin master                                             // always pull from remote before pushing
git push -u origin master                                          // publish changes to your remote repository

Generate list of all possible permutations of a string

I'm not sure why you would want to do this in the first place. The resulting set for any moderately large values of x and y will be huge, and will grow exponentially as x and/or y get bigger.

Lets say your set of possible characters is the 26 lowercase letters of the alphabet, and you ask your application to generate all permutations where length = 5. Assuming you don't run out of memory you'll get 11,881,376 (i.e. 26 to the power of 5) strings back. Bump that length up to 6, and you'll get 308,915,776 strings back. These numbers get painfully large, very quickly.

Here's a solution I put together in Java. You'll need to provide two runtime arguments (corresponding to x and y). Have fun.

public class GeneratePermutations {
    public static void main(String[] args) {
        int lower = Integer.parseInt(args[0]);
        int upper = Integer.parseInt(args[1]);

        if (upper < lower || upper == 0 || lower == 0) {
            System.exit(0);
        }

        for (int length = lower; length <= upper; length++) {
            generate(length, "");
        }
    }

    private static void generate(int length, String partial) {
        if (length <= 0) {
            System.out.println(partial);
        } else {
            for (char c = 'a'; c <= 'z'; c++) {
                generate(length - 1, partial + c);
            }
        }
    }
}

Can someone explain mappedBy in JPA and Hibernate?

Table relationship vs. entity relationship

In a relational database system, a one-to-many table relationship looks as follows:

one-to-many table relationship

Note that the relationship is based on the Foreign Key column (e.g., post_id) in the child table.

So, there is a single source of truth when it comes to managing a one-to-many table relationship.

Now, if you take a bidirectional entity relationship that maps on the one-to-many table relationship we saw previously:

Bidirectional One-To-Many entity association

If you take a look at the diagram above, you can see that there are two ways to manage this relationship.

In the Post entity, you have the comments collection:

@OneToMany(
    mappedBy = "post",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();

And, in the PostComment, the post association is mapped as follows:

@ManyToOne(
    fetch = FetchType.LAZY
)
@JoinColumn(name = "post_id")
private Post post;

Because there are two ways to represent the Foreign Key column, you must define which is the source of truth when it comes to translating the association state change into its equivalent Foreign Key column value modification.

MappedBy

The mappedBy attribute tells that the @ManyToOne side is in charge of managing the Foreign Key column, and the collection is used only to fetch the child entities and to cascade parent entity state changes to children (e.g., removing the parent should also remove the child entities).

Synchronize both sides of a bidirectional association

Now, even if you defined the mappedBy attribute and the child-side @ManyToOne association manages the Foreign Key column, you still need to synchronize both sides of the bidirectional association.

The best way to do that is to add these two utility methods:

public void addComment(PostComment comment) {
    comments.add(comment);
    comment.setPost(this);
}

public void removeComment(PostComment comment) {
    comments.remove(comment);
    comment.setPost(null);
}

The addComment and removeComment methods ensure that both sides are synchronized. So, if we add a child entity, the child entity needs to point to the parent and the parent entity should have the child contained in the child collection.

onClick not working on mobile (touch)

you can use instead of click :

$('#whatever').on('touchstart click', function(){ /* do something... */ });

What does it mean to "program to an interface"?

Code to the Interface Not the Implementation has NOTHING to do with Java, nor its Interface construct.

This concept was brought to prominence in the Patterns / Gang of Four books but was most probably around well before that. The concept certainly existed well before Java ever existed.

The Java Interface construct was created to aid in this idea (among other things), and people have become too focused on the construct as the centre of the meaning rather than the original intent. However, it is the reason we have public and private methods and attributes in Java, C++, C#, etc.

It means just interact with an object or system's public interface. Don't worry or even anticipate how it does what it does internally. Don't worry about how it is implemented. In object-oriented code, it is why we have public vs. private methods/attributes. We are intended to use the public methods because the private methods are there only for use internally, within the class. They make up the implementation of the class and can be changed as required without changing the public interface. Assume that regarding functionality, a method on a class will perform the same operation with the same expected result every time you call it with the same parameters. It allows the author to change how the class works, its implementation, without breaking how people interact with it.

And you can program to the interface, not the implementation without ever using an Interface construct. You can program to the interface not the implementation in C++, which does not have an Interface construct. You can integrate two massive enterprise systems much more robustly as long as they interact through public interfaces (contracts) rather than calling methods on objects internal to the systems. The interfaces are expected to always react the same expected way given the same input parameters; if implemented to the interface and not the implementation. The concept works in many places.

Shake the thought that Java Interfaces have anything what-so-ever to do with the concept of 'Program to the Interface, Not the Implementation'. They can help apply the concept, but they are not the concept.

How to record phone calls in android?

The accepted answer is perfect, except it does not record outgoing calls. Note that for outgoing calls it is not possible (as near as I can tell from scouring many posts) to detect when the call is actually answered (if anybody can find a way other than scouring notifications or logs please let me know). The easiest solution is to just start recording straight away when the outgoing call is placed and stop recording when IDLE is detected. Just adding the same class as above with outgoing recording in this manner for completeness:

private void startRecord(String seed) {
        String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
        File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
        if (!sampleDir.exists()) {
            sampleDir.mkdirs();
        }
        String file_name = "Record" + seed;
        try {
            audiofile = File.createTempFile(file_name, ".amr", sampleDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();

        recorder = new MediaRecorder();

        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(audiofile.getAbsolutePath());
        try {
            recorder.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        recorder.start();
        recordstarted = true;
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_IN)) {
            if ((bundle = intent.getExtras()) != null) {
                state = bundle.getString(TelephonyManager.EXTRA_STATE);
                if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                    inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                    wasRinging = true;
                    Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
                } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                    if (wasRinging == true) {

                        Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();

                        startRecord("incoming");
                    }
                } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                    wasRinging = false;
                    Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                    if (recordstarted) {
                        recorder.stop();
                        recordstarted = false;
                    }
                }
            }
        } else if (intent.getAction().equals(ACTION_OUT)) {
            if ((bundle = intent.getExtras()) != null) {
                outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
                startRecord("outgoing");
                if ((bundle = intent.getExtras()) != null) {
                    state = bundle.getString(TelephonyManager.EXTRA_STATE);
                    if (state != null) {
                        if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                            wasRinging = false;
                            Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                            if (recordstarted) {
                                recorder.stop();
                                recordstarted = false;
                            }
                        }
                    }


                }
            }
        }
    }

How do I concatenate a string with a variable?

It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer. The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.

Best practice to return errors in ASP.NET Web API

You can use custom ActionFilter in Web Api to validate model:

public class DRFValidationFilters : ActionFilterAttribute
{

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request
                .CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);

            //BadRequest(actionContext.ModelState);
        }
    }

    public override Task OnActionExecutingAsync(HttpActionContext actionContext,
        CancellationToken cancellationToken)
    {

        return Task.Factory.StartNew(() =>
        {
            if (!actionContext.ModelState.IsValid)
            {
                actionContext.Response = actionContext.Request
                    .CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        });
    }

    public class AspirantModel
    {
        public int AspirantId { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName { get; set; }
        public string AspirantType { get; set; }
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
            ErrorMessage = "Not a valid Phone number")]
        public string MobileNumber { get; set; }
        public int StateId { get; set; }
        public int CityId { get; set; }
        public int CenterId { get; set; }


        [HttpPost]
        [Route("AspirantCreate")]
        [DRFValidationFilters]
        public IHttpActionResult Create(AspirantModel aspirant)
        {
            if (aspirant != null)
            {

            }
            else
            {
                return Conflict();
            }

            return Ok();
        }
    }
}

Register CustomAttribute class in webApiConfig.cs config.Filters.Add(new DRFValidationFilters());

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

it depends on how you actually order your data,if its on a channel first basis then you should reshape your data: x_train=x_train.reshape(x_train.shape[0],channel,width,height)

if its channel last: x_train=s_train.reshape(x_train.shape[0],width,height,channel)

How to install SQL Server Management Studio 2008 component only

SQL Server Management Studio 2008 R2 Express commandline:

The answer by dyslexicanaboko hits the crucial point, but this one is even simpler and suited for command line (unattended scenarios):

(tried out with SQL Server 2008 R2 Express, one instance installed and having downloaded SQLManagementStudio_x64_ENU.exe)

As pointed out in this thread often enough, it is better to use the original SQL server setup (e.g. SQL Express with Tools), if possible, but there are some scenarios, where you want to add SSMS at a SQL derivative without that tools, afterwards:

I´ve already put it in a batch syntax here:

@echo off
"%~dp0SQLManagementStudio_x64_ENU.exe" /Q /ACTION="Install" /FEATURES="SSMS" /IACCEPTSQLSERVERLICENSETERMS

Remarks:

  1. For 2008 without R2 it should be enough to omit the /IACCEPTSQLSERVERLICENSETERMS flag, i guess.

  2. The /INDICATEPROGRESS parameter is useless here, the whole command takes a number of minutes and is 100% silent without any acknowledgement. Just look at the start menu, if the command is ready, if it has succeeded.

  3. This should work for the "ADV_SSMS" Feature (instead of "SSMS") too, which is the management studio extended variant (profiling, reporting, tuning, etc.)

How do I get the localhost name in PowerShell?

Don't forget that all your old console utilities work just fine in PowerShell:

PS> hostname
KEITH1

ERROR 1396 (HY000): Operation CREATE USER failed for 'jack'@'localhost'

Funnily enough the MySQL workbench solved it for me. In the Administration tab -> Users and Privileges, the user was listed with an error. Using the delete option solved the problem.

AngularJS - add HTML element to dom in directive without jQuery

Why not to try simple (but powerful) html() method:

iElement.html('<svg width="600" height="100" class="svg"></svg>');

Or append as an alternative:

iElement.append('<svg width="600" height="100" class="svg"></svg>');

And , of course , more cleaner way:

 var svg = angular.element('<svg width="600" height="100" class="svg"></svg>');
 iElement.append(svg);

Fiddle: http://jsfiddle.net/cherniv/AgGwK/

How to check if there exists a process with a given pid in Python?

Building upon ntrrgc's I've beefed up the windows version so it checks the process exit code and checks for permissions:

def pid_exists(pid):
    """Check whether pid exists in the current process table."""
    if os.name == 'posix':
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
    else:
        import ctypes
        kernel32 = ctypes.windll.kernel32
        HANDLE = ctypes.c_void_p
        DWORD = ctypes.c_ulong
        LPDWORD = ctypes.POINTER(DWORD)
        class ExitCodeProcess(ctypes.Structure):
            _fields_ = [ ('hProcess', HANDLE),
                ('lpExitCode', LPDWORD)]

        SYNCHRONIZE = 0x100000
        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if not process:
            return False

        ec = ExitCodeProcess()
        out = kernel32.GetExitCodeProcess(process, ctypes.byref(ec))
        if not out:
            err = kernel32.GetLastError()
            if kernel32.GetLastError() == 5:
                # Access is denied.
                logging.warning("Access is denied to get pid info.")
            kernel32.CloseHandle(process)
            return False
        elif bool(ec.lpExitCode):
            # print ec.lpExitCode.contents
            # There is an exist code, it quit
            kernel32.CloseHandle(process)
            return False
        # No exit code, it's running.
        kernel32.CloseHandle(process)
        return True

How can I display the current branch and folder path in terminal?

Simple way

Open ~/.bash_profile in your favorite editor and add the following content to the bottom.

Git branch in prompt.

parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "

Add Git Branch To Terminal Prompt (Mac)

How to zero pad a sequence of integers in bash so that all have the same width?

In your specific case though it's probably easiest to use the -f flag to seq to get it to format the numbers as it outputs the list. For example:

for i in $(seq -f "%05g" 10 15)
do
  echo $i
done

will produce the following output:

00010
00011
00012
00013
00014
00015

More generally, bash has printf as a built-in so you can pad output with zeroes as follows:

$ i=99
$ printf "%05d\n" $i
00099

You can use the -v flag to store the output in another variable:

$ i=99
$ printf -v j "%05d" $i
$ echo $j
00099

Notice that printf supports a slightly different format to seq so you need to use %05d instead of %05g.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

If you are using Bootstrap 3.3.x then use this code (you need to add class name carousel-fade to your carousel).

.carousel-fade .carousel-inner .item {
  -webkit-transition-property: opacity;
          transition-property: opacity;
}
.carousel-fade .carousel-inner .item,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  opacity: 0;
}
.carousel-fade .carousel-inner .active,
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}
.carousel-fade .carousel-inner .next,
.carousel-fade .carousel-inner .prev,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-control {
  z-index: 2;
}

How to get a jqGrid cell value when editing

I obtain edit value using javascript:

document.getElementById('idCell').value

I hope this info useful for someone.

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

Select second last element with css

Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.


The :nth-child CSS3 selector is in fact more capable than you ever imagined!

For example, this will select the last 2 elements of #container:

#container :nth-last-child(-n+2) {}

But this is just the beginning of a beautiful friendship.

_x000D_
_x000D_
#container :nth-last-child(-n+2) {
  background-color: cyan;
}
_x000D_
<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div>
 <div>SELECT THIS</div>
</div>
_x000D_
_x000D_
_x000D_

Get the cell value of a GridView row

I was looking for an integer value in named column, so I did the below:

int index = dgv_myDataGridView.CurrentCell.RowIndex;

int id = Convert.ToInt32(dgv_myDataGridView["ID", index].Value)

The good thing about this is that the column can be in any position in the grid view and you will still get the value.

Cheers

Convert Date/Time for given Timezone - java

display date and time for all timezones

import java.util.Calendar;
import java.util.TimeZone;
import java.text.DateFormat;
import java.text.SimpleDateFormat;



static final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ssZ";
DateFormat dateFormat = new SimpleDateFormat(ISO8601);
Calendar c = Calendar.getInstance();
String formattedTime;
for (String availableID : TimeZone.getAvailableIDs()) {
    dateFormat.setTimeZone(TimeZone.getTimeZone(availableID));
    formattedTime = dateFormat.format(c.getTime());
    System.out.println(formattedTime + " " + availableID);
}

AngularJS Multiple ng-app within a page

Only one app is automatically initialized. Others have to manually initialized as follows:

Syntax:

angular.bootstrap(element, [modules]);

Example:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8" data-require="[email protected]"></script>_x000D_
  <script data-require="[email protected]" data-semver="0.2.18" src="//cdn.rawgit.com/angular-ui/ui-router/0.2.18/release/angular-ui-router.js"></script>_x000D_
  <link rel="stylesheet" href="style.css" />_x000D_
  <script>_x000D_
    var parentApp = angular.module('parentApp', [])_x000D_
  .controller('MainParentCtrl', function($scope) {_x000D_
    $scope.name = 'universe';_x000D_
  });_x000D_
_x000D_
_x000D_
_x000D_
var childApp = angular.module('childApp', ['parentApp'])_x000D_
  .controller('MainChildCtrl', function($scope) {_x000D_
    $scope.name = 'world';_x000D_
  });_x000D_
_x000D_
_x000D_
angular.element(document).ready(function() {_x000D_
  angular.bootstrap(document.getElementById('childApp'), ['childApp']);_x000D_
});_x000D_
    _x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="childApp">_x000D_
    <div ng-controller="MainParentCtrl">_x000D_
      Hello {{name}} !_x000D_
      <div>_x000D_
        <div ng-controller="MainChildCtrl">_x000D_
          Hello {{name}} !_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

AngularJS API

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

It might be old but in my case, it was because of docker. Hope it will help others.

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Jquery onclick on div

js

<script
  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>


<script type="text/javascript">

$(document).ready(function(){
    $("#div1").on('click', function(){
            console.log("click!!!");
        });
});

</script>

html

<div id="div1">div!</div>

CodeIgniter Active Record not equal

It worked fine with me,

$this->db->where("your_id !=",$your_id);

Or try this one,

$this->db->where("your_id <>",$your_id);

Or try this one,

$this->db->where("your_id IS NOT NULL");

all will work.

Correct Way to Load Assembly, Find Class and Call Run() Method

Use an AppDomain

It is safer and more flexible to load the assembly into its own AppDomain first.

So instead of the answer given previously:

var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

I would suggest the following (adapted from this answer to a related question):

var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

Now you can unload the assembly and have different security settings.

If you want even more flexibility and power for dynamic loading and unloading of assemblies, you should look at the Managed Add-ins Framework (i.e. the System.AddIn namespace). For more information, see this article on Add-ins and Extensibility on MSDN.

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

Another solution could be:

var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference).AsEnumerable()
   .Where(x => x.DateTimeStart.Date == currentDate.Date).AsQueryable();

How do I move to end of line in Vim?

The easiest option would be to key in $. If you are working with blocks of text, you might appreciate the command { and } in order to move a paragraph back and forward, respectively.

seek() function?

Regarding seek() there's not too much to worry about.

First of all, it is useful when operating over an open file.

It's important to note that its syntax is as follows:

fp.seek(offset, from_what)

where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference:

  • 0: means your reference point is the beginning of the file
  • 1: means your reference point is the current file position
  • 2: means your reference point is the end of the file

if omitted, from_what defaults to 0.

Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek will be useful to you when you need to walk along that open file, just as a path you are traveling into.

What is exactly the base pointer and stack pointer? To what do they point?

First of all, the stack pointer points to the bottom of the stack since x86 stacks build from high address values to lower address values. The stack pointer is the point where the next call to push (or call) will place the next value. It's operation is equivalent to the C/C++ statement:

 // push eax
 --*esp = eax
 // pop eax
 eax = *esp++;

 // a function call, in this case, the caller must clean up the function parameters
 move eax,some value
 push eax
 call some address  // this pushes the next value of the instruction pointer onto the
                    // stack and changes the instruction pointer to "some address"
 add esp,4 // remove eax from the stack

 // a function
 push ebp // save the old stack frame
 move ebp, esp
 ... // do stuff
 pop ebp  // restore the old stack frame
 ret

The base pointer is top of the current frame. ebp generally points to your return address. ebp+4 points to the first parameter of your function (or the this value of a class method). ebp-4 points to the first local variable of your function, usually the old value of ebp so you can restore the prior frame pointer.

Inheritance and init method in Python

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

Repository Pattern Step by Step Explanation

This is a nice example: The Repository Pattern Example in C#

Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:

  • for reading, it creates the query satisfying the supplied criteria and returns the result set
  • for writing, it issues the commands necessary to make the underlying persistence engine (e.g. an SQL database) save the data

Associating existing Eclipse project with existing SVN repository

I came across the same issue. I checked out using Tortoise client and then tried to import the projects in Eclipse using import wizard. Eclipse did not recognize the svn location. I tried share option as mentioned in the above posts and it tried to commit these projects into SVN. But my issue was a version mismatch. I selected svn 1.8 version in eclipse (I was using 1.7 in eclipse and 1.8.8 in tortoise) and then re imported the projects. It resolved with no issues.

How to concatenate strings in django templates?

I have changed the folder hierarchy

/shop/shop_name/base.html To /shop_name/shop/base.html

and then below would work.

{% extends shop_name|add:"/shop/base.html"%} 

Now its able to extend the base.html page.

Warning: comparison with string literals results in unspecified behaviour

You want to use strcmp() == 0 to compare strings instead of a simple ==, which will just compare if the pointers are the same (which they won't be in this case).

args[i] is a pointer to a string (a pointer to an array of chars null terminated), as is "&" or "<".

The expression argc[i] == "&" checks if the two pointers are the same (point to the same memory location).

The expression strcmp( argc[i], "&") == 0 will check if the contents of the two strings are the same.

Notice: Array to string conversion in

One of reasons why you will get this Notice: Array to string conversion in… is that you are combining group of arrays. Example, sorting out several first and last names.

To echo elements of array properly, you can use the function, implode(separator, array) Example:

implode(' ', $var)

result:

first name[1], last name[1]
first name[2], last name[2]

More examples from W3C.

How can I create a unique constraint on my column (SQL Server 2008 R2)?

Here's another way through the GUI that does exactly what your script does even though it goes through Indexes (not Constraints) in the object explorer.

  1. Right click on "Indexes" and click "New Index..." (note: this is disabled if you have the table open in design view)

enter image description here

  1. Give new index a name ("U_Name"), check "Unique", and click "Add..."

enter image description here

  1. Select "Name" column in the next windown

enter image description here

  1. Click OK in both windows

PHP case-insensitive in_array function

  • in_array accepts these parameters : in_array(search,array,type)
  • if the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.
  • so in order to make the search ignore the case, it would be enough to use it like this :

$a = array( 'one', 'two', 'three', 'four' );

$b = in_array( 'ONE', $a, false );

How to round up a number to nearest 10?

For people who want to do it with raw SQL, without using php, java, python etc. SET SQL_SAFE_UPDATES = 0; UPDATE db.table SET value=ceil(value/10)*10 where value not like '%0';

How to make blinking/flashing text with CSS 3

Use the alternate value for animation-direction (and you don't need to add any keframes this way).

alternate

The animation should reverse direction each cycle. When playing in reverse, the animation steps are performed backward. In addition, timing functions are also reversed; for example, an ease-in animation is replaced with an ease-out animation when played in reverse. The count to determinate if it is an even or an odd iteration starts at one.

CSS:

.waitingForConnection {
  animation: blinker 1.7s cubic-bezier(.5, 0, 1, 1) infinite alternate;  
}
@keyframes blinker { to { opacity: 0; } }

I've removed the from keyframe. If it's missing, it gets generated from the value you've set for the animated property (opacity in this case) on the element, or if you haven't set it (and you haven't in this case), from the default value (which is 1 for opacity).

And please don't use just the WebKit version. Add the unprefixed one after it as well. If you just want to write less code, use the shorthand.

_x000D_
_x000D_
.waitingForConnection {
  animation: blinker 1.7s cubic-bezier(.5, 0, 1, 1) infinite alternate;  
}
@keyframes blinker { to { opacity: 0; } }

.waitingForConnection2 {
  animation: blinker2 0.6s cubic-bezier(1, 0, 0, 1) infinite alternate;  
}
@keyframes blinker2 { to { opacity: 0; } }

.waitingForConnection3 {
  animation: blinker3 1s ease-in-out infinite alternate;  
}
@keyframes blinker3 { to { opacity: 0; } }
_x000D_
<div class="waitingForConnection">X</div>
<div class="waitingForConnection2">Y</div>
<div class="waitingForConnection3">Z</div>
_x000D_
_x000D_
_x000D_

Mockito matcher and array of primitives

I agree with Mutanos and Alecio. Further, one can check as many identical method calls as possible (verifying the subsequent calls in the production code, the order of the verify's does not matter). Here is the code:

import static org.mockito.AdditionalMatchers.*;

    verify(mockObject).myMethod(aryEq(new byte[] { 0 }));
    verify(mockObject).myMethod(aryEq(new byte[] { 1, 2 }));

Query to select data between two dates with the format m/d/yyyy

use this

select * from xxx where dates between '10/oct/2012' and '10/dec/2012'

you are entering string, So give the name of month as according to format...

Refresh Page and Keep Scroll Position

UPDATE

You can use document.location.reload(true) as mentioned below instead of the forced trick below.

Replace your HTML with this:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            body { 
                background-image: url('../Images/Black-BackGround.gif');
                background-repeat: repeat;
            }
            body td {
               font-Family: Arial; 
               font-size: 12px; 
            }
            #Nav a { 
                position:relative; 
                display:block; 
                text-decoration: none; 
                color:black; 
            }
        </style>
        <script type="text/javascript">
            function refreshPage () {
                var page_y = document.getElementsByTagName("body")[0].scrollTop;
                window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
            }
            window.onload = function () {
                setTimeout(refreshPage, 35000);
                if ( window.location.href.indexOf('page_y') != -1 ) {
                    var match = window.location.href.split('?')[1].split("&")[0].split("=");
                    document.getElementsByTagName("body")[0].scrollTop = match[1];
                }
            }
        </script>
    </head>
    <body><!-- BODY CONTENT HERE --></body>
</html>

how do I insert a column at a specific column index in pandas?

df.insert(loc, column_name, value)

This will work if there is no other column with the same name. If a column, with your provided name already exists in the dataframe, it will raise a ValueError.

You can pass an optional parameter allow_duplicates with True value to create a new column with already existing column name.

Here is an example:



    >>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]})
    >>> df
       b  c
    0  1  3
    1  2  4
    >>> df.insert(0, 'a', -1)
    >>> df
       a  b  c
    0 -1  1  3
    1 -1  2  4
    >>> df.insert(0, 'a', -2)
    Traceback (most recent call last):
      File "", line 1, in 
      File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 3760, in insert
        self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
      File "C:\Python39\lib\site-packages\pandas\core\internals\managers.py", line 1191, in insert
        raise ValueError(f"cannot insert {item}, already exists")
    ValueError: cannot insert a, already exists
    >>> df.insert(0, 'a', -2,  allow_duplicates = True)
    >>> df
       a  a  b  c
    0 -2 -1  1  3
    1 -2 -1  2  4

Undefined reference to pthread_create in Linux

In Visual Studio 2019 specify -pthread in the property pages for the project under:

Linker -> Command Line -> Additional Options

Type in -pthread in the textbox.

How can I strip all punctuation from a string in JavaScript using regex?

If you want to remove specific punctuation from a string, it will probably be best to explicitly remove exactly what you want like

replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"")

Doing the above still doesn't return the string as you have specified it. If you want to remove any extra spaces that were left over from removing crazy punctuation, then you are going to want to do something like

replace(/\s{2,}/g," ");

My full example:

var s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var punctuationless = s.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");

Results of running code in firebug console:

alt text

How to download fetch response in react as file

I have faced the same problem once too. I have solved it by creating on empty link with a ref to it like so:

linkRef = React.createRef();
render() {
    return (
        <a ref={this.linkRef}/>
    );
}

and in my fetch function i have done something like this:

fetch(/*your params*/)
    }).then(res => {
        return res.blob();
    }).then(blob => {
        const href = window.URL.createObjectURL(blob);
        const a = this.linkRef.current;
        a.download = 'Lebenslauf.pdf';
        a.href = href;
        a.click();
        a.href = '';
    }).catch(err => console.error(err));

basically i have assigned the blobs url(href) to the link, set the download attribute and enforce one click on the link. As far as i understand this is the "basic" idea of the answer provided by @Nate. I dont know if this is a good idea to do it this way... I did.

MySQL Data Source not appearing in Visual Studio

I was having the same problem just now. I solved it by uninstalling the latest Connector/NET drivers (6.7.4) and then installed the older drivers (6.6.5) and it works.

I am using Visual Studio 2010. I uninstalled the latest ones because I figured they were somehow related to .NET4.5, which I'm not able to use.


Update #1:

Supposedly another way is to register the MySql Connector with various Visual Studio versions (2010/2012/2013/2015...) during installation: Go to Modify Product Features and select all the relevant Visual Studio versions.

see Image


Update #2 - Visual Studio 2019 Update:

When I installed MySQL Community with the ConnectorNET and VisualStudio Plugin options included - MySQL didn't show up as a data provider in Visual Studio.

The installer I used included the VS Plugin version 1.2.9, which had supposedly fixed installation issues from 1.2.8, but still didn't work for me...

The solution for me was to uninstall the Connector and the Visual Studio Plugin, download them as individual components, and then install them separately (not as part of the MySQLServer Installer). Install the Connector first, then VS plugin after.

I found the solution here, Thanks to @LambertHeenan.


NOTE about Visual Studio Express

The OP asks whether MySQL is supported with Visual Studio Express (which as far as I can tell has been renamed to Visual Studio Community). In the past MySQL officially didn't support Visual Studio Express, as per @Paul's answer below, but they do officially support Visual Studio Community 2017 and 2019, according to this page.

Bootstrap: wider input field

Use the bootstrap built in classes input-large, input-medium, ... : <input type="text" class="input-large search-query">

Or use your own css:

  1. Give the element a unique classname class="search-query input-mysize"
  2. Add this in your css file (not the bootstrap.less or css files):
    .input-mysize { width: 150px }

Click toggle with jQuery

Easiest solution

$('.offer').click(function(){
    var cc = $(this).attr('checked') == undefined  ? false : true;
    $(this).find(':checkbox').attr('checked',cc);
});

Using ng-click vs bind within link function of Angular Directive

You may use a controller in directive:

angular.module('app', [])
  .directive('appClick', function(){
     return {
       restrict: 'A',
       scope: true,
       template: '<button ng-click="click()">Click me</button> Clicked {{clicked}} times',
       controller: function($scope, $element){
         $scope.clicked = 0;
         $scope.click = function(){
           $scope.clicked++
         }
       }
     }
   });

Demo on plunkr

More about directives in Angular guide. And very helpfull for me was videos from official Angular blog post About those directives.

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

THIS IS JUST A NOTE FOR ANYONE DEALING WITH THIS PROBLEM USING THE RUBY DRIVER

I had this same problem when using the Ruby Gem.

To set slaveOk in Ruby, you just pass it as an argument when you create the client like this:

mongo_client = MongoClient.new("localhost", 27017, { slave_ok: true })

https://github.com/mongodb/mongo-ruby-driver/wiki/Tutorial#making-a-connection

mongo_client = MongoClient.new # (optional host/port args)

Notice that 'args' is the third optional argument.

Convert row to column header for Pandas DataFrame,

To rename the header without reassign df:

df.rename(columns=df.iloc[0], inplace = True)

To drop the row without reassign df:

df.drop(df.index[0], inplace = True)

How to create a template function within a class? (C++)

See here: Templates, template methods,Member Templates, Member Function Templates

class   Vector
{
  int     array[3];

  template <class TVECTOR2> 
  void  eqAdd(TVECTOR2 v2);
};

template <class TVECTOR2>
void    Vector::eqAdd(TVECTOR2 a2)
{
  for (int i(0); i < 3; ++i) array[i] += a2[i];
}

How to remove html special chars?

If you are working in WordPress and are like me and simply need to check for an empty field (and there are a copious amount of random html entities in what seems like a blank string) then take a look at:

sanitize_title_with_dashes( string $title, string $raw_title = '', string $context = 'display' )

Link to wordpress function page

For people not working on WordPress, I found this function REALLY useful to create my own sanitizer, take a look at the full code and it's really in depth!

How can I display a modal dialog in Redux that performs asynchronous actions?

Wrap the modal into a connected container and perform the async operation in here. This way you can reach both the dispatch to trigger actions and the onClose prop too. To reach dispatch from props, do not pass mapDispatchToProps function to connect.

class ModalContainer extends React.Component {
  handleDelete = () => {
    const { dispatch, onClose } = this.props;
    dispatch({type: 'DELETE_POST'});

    someAsyncOperation().then(() => {
      dispatch({type: 'DELETE_POST_SUCCESS'});
      onClose();
    })
  }

  render() {
    const { onClose } = this.props;
    return <Modal onClose={onClose} onSubmit={this.handleDelete} />
  }
}

export default connect(/* no map dispatch to props here! */)(ModalContainer);

The App where the modal is rendered and its visibility state is set:

class App extends React.Component {
  state = {
    isModalOpen: false
  }

  handleModalClose = () => this.setState({ isModalOpen: false });

  ...

  render(){
    return (
      ...
      <ModalContainer onClose={this.handleModalClose} />  
      ...
    )
  }

}

Create 3D array using Python

numpy.arrays are designed just for this case:

 numpy.zeros((i,j,k))

will give you an array of dimensions ijk, filled with zeroes.

depending what you need it for, numpy may be the right library for your needs.

How can I find out the current route in Rails?

If you are trying to special case something in a view, you can use current_page? as in:

<% if current_page?(:controller => 'users', :action => 'index') %>

...or an action and id...

<% if current_page?(:controller => 'users', :action => 'show', :id => 1) %>

...or a named route...

<% if current_page?(users_path) %>

...and

<% if current_page?(user_path(1)) %>

Because current_page? requires both a controller and action, when I care about just the controller I make a current_controller? method in ApplicationController:

  def current_controller?(names)
    names.include?(current_controller)
  end

And use it like this:

<% if current_controller?('users') %>

...which also works with multiple controller names...

<% if current_controller?(['users', 'comments']) %>

How to return a struct from a function in C++?

You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:

auto f()
{
    struct S
    {
      int a;
      double b;
    } s;
    s.a = 42;
    s.b = 42.0;
    return s;
}

auto x = f();
a = x.a;
b = x.b;

How to clear/remove observable bindings in Knockout.js?

Instead of using KO's internal functions and dealing with JQuery's blanket event handler removal, a much better idea is using with or template bindings. When you do this, ko re-creates that part of DOM and so it automatically gets cleaned. This is also recommended way, see here: https://stackoverflow.com/a/15069509/207661.

How do you round to 1 decimal place in Javascript?

If your source code is typescript you could use a function like this:

public static ToFixedRounded(decimalNumber: number, fractionDigits: number): number {
    var rounded = Math.pow(10, fractionDigits);
    return (Math.round(decimalNumber * rounded) / rounded).toFixed(fractionDigits) as unknown as number;
}

SQL Server default character encoding

The default character encoding for a SQL Server database is iso_1, which is ISO 8859-1. Note that the character encoding depends on the data type of a column. You can get an idea of what character encodings are used for the columns in a database as well as the collations using this SQL:

select data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name, count(*) count
from information_schema.columns
group by data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name;

If it's using the default, the character_set_name should be iso_1 for the char and varchar data types. Since nchar and nvarchar store Unicode data in UCS-2 format, the character_set_name for those data types is UNICODE.

LINQ syntax where string value is not null or empty

This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.

The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.

Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)

How could I convert data from string to long in c#

long is internally represented as System.Int64 which is a 64-bit signed integer. The value you have taken "1100.25" is actually decimal and not integer hence it can not be converted to long.

You can use:

String strValue = "1100.25";
decimal lValue = Convert.ToDecimal(strValue);

to convert it to decimal value

How do I pass multiple parameter in URL?

You can pass multiple parameters as "?param1=value1&param2=value2"

But it's not secure. It's vulnerable to Cross Site Scripting (XSS) Attack.

Your parameter can be simply replaced with a script.

Have a look at this article and article

You can make it secure by using API of StringEscapeUtils

static String   escapeHtml(String str) 
          Escapes the characters in a String using HTML entities.

Even using https url for security without above precautions is not a good practice.

Have a look at related SE question:

Is URLEncoder.encode(string, "UTF-8") a poor validation?

How to Enable ActiveX in Chrome?

I downloaded this "IE Tab Multi" from Chrome. It works good! http://iblogbox.com/chrome/ietab/alert.php

How to import the class within the same directory or sub directory?

Python 3


Same directory.

import file:log.py

import class: SampleApp().

import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()

or

directory is basic.

import in file: log.py.

import class: SampleApp().

from basic import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()

Two color borders

Another way is to use box-shadow:

#mybox {
box-shadow:
  0 0 0 1px #CCC,
  0 0 0 2px #888,
  0 0 0 3px #444,
  0 0 0 4px #000;
-moz-box-shadow:
  0 0 0 1px #CCC,
  0 0 0 2px #888,
  0 0 0 3px #444,
  0 0 0 4px #000;
-webkit-shadow:
  0 0 0 1px #CCC,
  0 0 0 2px #888,
  0 0 0 3px #444,
  0 0 0 4px #000;
}

<div id="mybox">ABC</div>

See example here.

CSS Font Border?

There seems to be a 'text-stroke' property, but (at least for me) it only works in Safari.

http://webkit.org/blog/85/introducing-text-stroke/

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

Note that if you use SELECT FOR UPDATE to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE, then to check the affected row count.

add below line to my.cnf file

innodb_locks_unsafe_for_binlog = 1

#

1 - ON
0 - OFF

#

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

java.net.SocketException: Software caused connection abort: recv failed

The only time I've seen something like this happen is when I have a bad connection, or when somebody is closing the socket that I am using from a different thread context.

Select2() is not a function

Had the same issue. Sorted it by defer loading select2

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js" defer></script>

In C, how should I read a text file and print all strings

You can use fgets and limit the size of the read string.

char *fgets(char *str, int num, FILE *stream);

You can change the while in your code to:

while (fgets(str, 100, file)) /* printf("%s", str) */;

Git push existing repo to a new and different remote repo server?

To push your existing repo into different, you need to:

  1. Clone the original repo first.

    git clone https://git.fedorahosted.org/cgit/rhq/rhq.git
    
  2. Push the cloned sources to your new repository:

    cd rhq
    git push https://github.com/user/example master:master
    

You may change master:master into source:destination branch.


If you want to push specific commit (branch), then do:

  1. On the original repo, create and checkout a new branch:

    git checkout -b new_branch
    
  2. Choose and reset to the point which you want to start with:

    git log # Find the interesting hash
    git reset 4b62bdc9087bf33cc01d0462bf16bbf396369c81 --hard
    

    Alternatively select the commit by git cherry-pick to append into existing HEAD.

  3. Then push to your new repo:

    git push https://github.com/user/example new_branch:master
    

    If you're rebasing, use -f for force push (not recommended). Run git reflog to see history of changes.

How to change Tkinter Button state from disabled to normal?

You simply have to set the state of the your button self.x to normal:

self.x['state'] = 'normal'

or

self.x.config(state="normal")

This code would go in the callback for the event that will cause the Button to be enabled.


Also, the right code should be:

self.x = Button(self.dialog, text="Download", state=DISABLED, command=self.download)
self.x.pack(side=LEFT)

The method pack in Button(...).pack() returns None, and you are assigning it to self.x. You actually want to assign the return value of Button(...) to self.x, and then, in the following line, use self.x.pack().

How to send a GET request from PHP?

I like using fsockopen open for this.

How to concatenate int values in java?

People were fretting over what happens when a == 0. Easy fix for that...have a digit before it. :)

int sum = 100000 + a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.valueOf(sum).substring(1));

Biggest drawback: it creates two strings. If that's a big deal, String.format could help.

int sum = a*10000 + b*1000 + c*100 + d*10 + e;
System.out.println(String.format("%05d", sum));

Eclipse does not highlight matching variables

I had this issue with Eclipse Mars for PHP developers, 64 bit edition for Windows. I now discovered that highlighting works out-of-the-box with the 32 bit version. Even with a fresh download of the equivalent 64 bit build, highlighting does not work. So I will switch back to 32 bit (this is actually not the first problem I observe with Eclipse 64 bit).

Edit:

I thought this was the solution, so I installed the 32 bit version in C:\Program Files (x86) and set a shortcut in the "Start" menu. When I started Eclipse from there, highlighting again ceased to work. I now got it working again by deleting the .metadata directory in the workspace (i.e. resetting the workspace settings) and re-importing the projects.

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

This ORA error is occurred because of violation of unique constraint.

ORA-00001: unique constraint (constraint_name) violated

This is caused because of trying to execute an INSERT or UPDATE statement that has created a duplicate value in a field restricted by a unique index.

You can resolve this either by

  • changing the constraint to allow duplicates, or
  • drop the unique constraint or you can change your SQL to avoid duplicate inserts

How do I write a bash script to restart a process if it dies?

I use this for my npm Process

#!/bin/bash
for (( ; ; ))
do
date +"%T"
echo Start Process
cd /toFolder
sudo process
date +"%T"
echo Crash
sleep 1
done

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

[UPDATED privacy keys list to iOS 13 - see below]

There is a list of all Cocoa Keys that you can specify in your Info.plist file:

https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html

(Xcode: Target -> Info -> Custom iOS Target Properties)

iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).

Privacy keys with example description: cheatsheet

Source

Alternatively, you can open Info.plist as source code: source code

Source

And add privacy keys like this:

<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>

List of all privacy keys: [UPDATED to iOS 13]

NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription

Update 2019:

In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.

I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo to ${PRODUCT_NAME} need access to the camera to update your avatar even though the app context was obvious (user tapped on the avatar).

It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.

Installing Python 2.7 on Windows 8

I think that the essence of this question is how to install Python and be able to use it from the command line. The steps below show how to get all that working. Check that you didn't miss anything:

  1. From https://www.python.org/download/releases/2.7.6 download appropriate Python 2.7.6 Windows Installer. (If that link doesn't work, check https://www.python.org/downloads/)
  2. Run the file
  3. Select install for all users or install just for me, click Next
  4. You'll see it installs under the C:\Python27 folder, click Next
  5. Click Next again for the 'Customize Python' step
  6. Click Finish
  7. Open Control Panel, then System
  8. Click 'Advanced system settings' on the left
  9. Click the 'Environment Variables' button
  10. Under 'System variables' click the variable called 'Path' then the 'Edit...' button. (This will set it for all users, you could instead choose to edit the User variables to just set python as a command prompt command for the current user)
  11. Without deleting any other text, add C:\Python27; (include the semi-colon) to the beginning of the 'Variable value' and click OK.
  12. Click OK on the 'Environment Variables' window.

Open a new command prompt window type python, you will have python running in the command prompt. Note: command prompt windows open prior to setting the Environment Variable will not have the python command available.

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

Unable to add window -- token is not valid; is your activity running?

This crash is usually caused by your app trying to display a dialog using a previously-finished Activity as a context. For example, this can happen if an Activity triggers an AsyncTask that tries to display a dialog when it is finished, but the user navigates back from the Activity before the task is completed.

External resources

Android – Displaying Dialogs From Background Threads

Error : BinderProxy@45d459c0 is not valid; is your activity running?

What are libtool's .la file for?

According to http://blog.flameeyes.eu/2008/04/14/what-about-those-la-files, they're needed to handle dependencies. But using pkg-config may be a better option:

In a perfect world, every static library needing dependencies would have its own .pc file for pkg-config, and every package trying to statically link to that library would be using pkg-config --static to get the libraries to link to.

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

What you have is a parse error. Those are thrown before any code is executed. A PHP file needs to be parsed in its entirety before any code in it can be executed. If there's a parse error in the file where you're setting your error levels, they won't have taken effect by the time the error is thrown.

Either break your files up into smaller parts, like setting the error levels in one file and then includeing another file which contains the actual code (and errors), or set the error levels outside PHP using php.ini or .htaccess directives.

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

All you need is a check on the post side of things.

if(empty($_REQUEST['type_id']) && $_REQUEST['type_id'] != 0)
    $_REQUEST['type_id'] = null;

How do you add a scroll bar to a div?

to add scroll u need to define max-height of your div and then add overflow-y

so do something like this

.my_scroll_div{
    overflow-y: auto;
    max-height: 100px;
}

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

With Hooks and useState

Use defaultValue to select the default value.

    const statusOptions = [
        { value: 1, label: 'Publish' },
        { value: 0, label: 'Unpublish' }
    ];
    const [statusValue, setStatusValue] = useState('');
    const handleStatusChange = e => {
        setStatusValue(e.value);
    }

return(
<>
<Select options={statusOptions} 
    defaultValue={[{ value: published, label: published == 1 ? 'Publish' : 'Unpublish' }]} 
    onChange={handleStatusChange} 
    value={statusOptions.find(obj => obj.value === statusValue)} required />
</>
)

Error: Cannot find module 'ejs'

Add dependency in package.json and then run npm install

    {
  ...
  ... 
  "dependencies": {
    "express": "*",
    "ejs": "*",
  }
}

Function stoi not declared

I managed to fix this problem by adding the following lines to my CMakeLists.txt:

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS}  -Wall  -O3 -march=native ")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall   -O3 -march=native")

# Check C++11 or C++0x support
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
   add_definitions(-DCOMPILEDWITHC11)
   message(STATUS "Using flag -std=c++11.")
elseif(COMPILER_SUPPORTS_CXX0X)
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
   add_definitions(-DCOMPILEDWITHC0X)
   message(STATUS "Using flag -std=c++0x.")
else()
   message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

As mentioned by the other fellows, that is the -std=c++11 issue.

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

You can just put:

header("HTTP/1.0 500 Internal Server Error");

inside your conditions like:

if (that happened) {
    header("HTTP/1.0 500 Internal Server Error");
}

As for the database query, you can just do that like this:

$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");

You should remember that you have to put this code before any html tag (or output).

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

I was facing this issue too, I was receiving a 404 when accessing a URL pattern that I knew was linked to a Servlet. The reason is because I had 2 Servlets with their @WebServlet name parameter set as the same string.

@WebServlet(name = "ServletName", urlPatterns = {"/path"})
public class ServletName extends HttpServlet {}
@WebServlet(name = "ServletName", urlPatterns = {"/other-path"})
public class OtherServletName extends HttpServlet {}

Both of the name parameters are the same. If you're using the name parameter, make sure they are unique compared to all other Servlets on your application.

How to view AndroidManifest.xml from APK file?

Google has just released a cross-platform open source tool for inspecting APKs (among many other binary Android formats):

ClassyShark is a standalone binary inspection tool for Android developers. It can reliably browse any Android executable and show important info such as class interfaces and members, dex counts and dependencies. ClassyShark supports multiple formats including libraries (.dex, .aar, .so), executables (.apk, .jar, .class) and all Android binary XMLs: AndroidManifest, resources, layouts etc.

ClassyShark screenshot

HttpClient - A task was cancelled?

In my situation, the controller method was not made as async and the method called inside the controller method was async.

So I guess its important to use async/await all the way to top level to avoid issues like these.

How can I make an EXE file from a Python program?

py2exe:

py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.

Capturing multiple line output into a Bash variable

Another pitfall with this is that command substitution$() — strips trailing newlines. Probably not always important, but if you really want to preserve exactly what was output, you'll have to use another line and some quoting:

RESULTX="$(./myscript; echo x)"
RESULT="${RESULTX%x}"

This is especially important if you want to handle all possible filenames (to avoid undefined behavior like operating on the wrong file).

Using an array from Observable Object with ngFor and Async Pipe Angular 2

Who ever also stumbles over this post.

I belive is the correct way:

  <div *ngFor="let appointment of (_nextFourAppointments | async).availabilities;"> 
    <div>{{ appointment }}</div>
  </div>

Regular expression to match numbers with or without commas and decimals in text

(,*[\d]+,*[\d]*)+

This would match any small or large number as following with or without comma

1
100
1,262
1,56,262
10,78,999
12,34,56,789

or

1
100
1262
156262
1078999
123456789

add scroll bar to table body

These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.

jQuery.scrollTableBody (GitHub)

As long as you have a table with proper <thead>, <tbody>, and (optional) <tfoot>, all you need to do is this:

$('table').scrollTableBody();

How do I convert this list of dictionaries to a csv file?

Here is another, more general solution assuming you don't have a list of rows (maybe they don't fit in memory) or a copy of the headers (maybe the write_csv function is generic):

def gen_rows():
    yield OrderedDict(name='bob', age=25, weight=200)
    yield OrderedDict(name='jim', age=31, weight=180)

def write_csv():
    it = genrows()
    first_row = it.next()  # __next__ in py3
    with open("people.csv", "w") as outfile:
        wr = csv.DictWriter(outfile, fieldnames=list(first_row))
        wr.writeheader()
        wr.writerow(first_row)
        wr.writerows(it)

Note: the OrderedDict constructor used here only preserves order in python >3.4. If order is important, use the OrderedDict([('name', 'bob'),('age',25)]) form.

pull out p-values and r-squared from a linear regression

You can see the structure of the object returned by summary() by calling str(summary(fit)). Each piece can be accessed using $. The p-value for the F statistic is more easily had from the object returned by anova.

Concisely, you can do this:

rSquared <- summary(fit)$r.squared
pVal <- anova(fit)$'Pr(>F)'[1]

Capitalize only first character of string and leave others alone? (Rails)

Note that if you need to deal with multi-byte characters, i.e. if you have to internationalize your site, the s[0] = ... solution won't be adequate. This Stack Overflow question suggests using the unicode-util gem

Ruby 1.9: how can I properly upcase & downcase multibyte strings?

EDIT

Actually an easier way to at least avoid strange string encodings is to just use String#mb_chars:

s = s.mb_chars
s[0] = s.first.upcase
s.to_s

How to remove specific elements in a numpy array

In case you don't have the indices of the elements you want to remove, you can use the function in1d provided by numpy.

The function returns True if the element of a 1-D array is also present in a second array. To delete the elements, you just have to negate the values returned by this function.

Notice that this method keeps the order from the original array.

In [1]: import numpy as np

        a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
        rm = np.array([3, 4, 7])
        # np.in1d return true if the element of `a` is in `rm`
        idx = np.in1d(a, rm)
        idx

Out[1]: array([False, False,  True,  True, False, False,  True, False, False])

In [2]: # Since we want the opposite of what `in1d` gives us, 
        # you just have to negate the returned value
        a[~idx]

Out[2]: array([1, 2, 5, 6, 8, 9])

Creating and Update Laravel Eloquent

Actually firstOrCreate would not update in case that the register already exists in the DB. I improved a bit Erik's solution as I actually needed to update a table that has unique values not only for the column "id"

/**
 * If the register exists in the table, it updates it. 
 * Otherwise it creates it
 * @param array $data Data to Insert/Update
 * @param array $keys Keys to check for in the table
 * @return Object
 */
static function createOrUpdate($data, $keys) {
    $record = self::where($keys)->first();
    if (is_null($record)) {
        return self::create($data);
    } else {
        return self::where($keys)->update($data);
    }
}

Then you'd use it like this:

Model::createOrUpdate(
        array(
    'id_a' => 1,
    'foo' => 'bar'
        ), array(
    'id_a' => 1
        )
);

Good way of getting the user's location in Android

To select the right location provider for your app, you can use Criteria objects:

Criteria myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_HIGH);
myCriteria.setPowerRequirement(Criteria.POWER_LOW);
// let Android select the right location provider for you
String myProvider = locationManager.getBestProvider(myCriteria, true); 

// finally require updates at -at least- the desired rate
long minTimeMillis = 600000; // 600,000 milliseconds make 10 minutes
locationManager.requestLocationUpdates(myProvider,minTimeMillis,0,locationListener); 

Read the documentation for requestLocationUpdates for more details on how the arguments are taken into account:

The frequency of notification may be controlled using the minTime and minDistance parameters. If minTime is greater than 0, the LocationManager could potentially rest for minTime milliseconds between location updates to conserve power. If minDistance is greater than 0, a location will only be broadcasted if the device moves by minDistance meters. To obtain notifications as frequently as possible, set both parameters to 0.

More thoughts

  • You can monitor the accuracy of the Location objects with Location.getAccuracy(), which returns the estimated accuracy of the position in meters.
  • the Criteria.ACCURACY_HIGH criterion should give you errors below 100m, which is not as good as GPS can be, but matches your needs.
  • You also need to monitor the status of your location provider, and switch to another provider if it gets unavailable or disabled by the user.
  • The passive provider may also be a good match for this kind of application: the idea is to use location updates whenever they are requested by another app and broadcast systemwide.

Java: Calling a super method which calls an overridden method

Further more extended the output of the raised question, this will give more insight on the access specifier and override behavior.

            package overridefunction;
            public class SuperClass 
                {
                public void method1()
                {
                    System.out.println("superclass method1");
                    this.method2();
                    this.method3();
                    this.method4();
                    this.method5();
                }
                public void method2()
                {
                    System.out.println("superclass method2");
                }
                private void method3()
                {
                    System.out.println("superclass method3");
                }
                protected void method4()
                {
                    System.out.println("superclass method4");
                }
                void method5()
                {
                    System.out.println("superclass method5");
                }
            }

            package overridefunction;
            public class SubClass extends SuperClass
            {
                @Override
                public void method1()
                {
                    System.out.println("subclass method1");
                    super.method1();
                }
                @Override
                public void method2()
                {
                    System.out.println("subclass method2");
                }
                // @Override
                private void method3()
                {
                    System.out.println("subclass method3");
                }
                @Override
                protected void method4()
                {
                    System.out.println("subclass method4");
                }
                @Override
                void method5()
                {
                    System.out.println("subclass method5");
                }
            }

            package overridefunction;
            public class Demo 
            {
                public static void main(String[] args) 
                {
                    SubClass mSubClass = new SubClass();
                    mSubClass.method1();
                }
            }

            subclass method1
            superclass method1
            subclass method2
            superclass method3
            subclass method4
            subclass method5

ImageView in circular through xml

The following is one of the simplest ways to do it, use the following code:

Dependencies

dependencies {
    ...
    compile 'de.hdodenhof:circleimageview:2.1.0'      // use this or use the latest compile version. In case u get bug.
}

XML Code

<de.hdodenhof.circleimageview.CircleImageView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/profile_image"
    android:layout_width="96dp"             //  here u can adjust the width 
    android:layout_height="96dp"            //  here u can adjust the height 
    android:src="@drawable/profile"         //  here u can change the image 
    app:civ_border_width="2dp"              //  here u can adjust the border of the circle.  
    app:civ_border_color="#FF000000"/>      //  here u can adjust the border color

Screenshot:

Screenshot

Source: Circular ImageView GitHub Repository

enter image description here

How do I disable right click on my web page?

If you are a jquery fan,use this

    $(function() {
        $(this).bind("contextmenu", function(e) {
            e.preventDefault();
        });
    }); 

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I found the solution : it's the 9th byte of this key :

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections] "DefaultConnectionSettings"=hex:3c,00,00,00,1f,00,00,00,05,00,00,00,00,00,00, 00,00,00,00,00,00,00,00,00,01,00,00,00,1f,00,00,00,68,74,74,70,3a,2f,2f,31, 34,34,2e,31,33,31,2e,32,32,32,2e,31,36,37,2f,77,70,61,64,2e,64,61,74,90,0e, 1e,66,d3,88,c5,01,01,00,00,00,8d,a8,4e,9e,00,00,00,00,00,00,00,00

It's a bitfield:

  • 0x1: (Always 1)
  • 0x2: Proxy enabled
  • 0x4: "Use automatic configuration script" checked
  • 0x8: "Automatically detect settings" checked

Mask 0x8 to turn it off, i.e., subtract 8 if it's higher than 8.

Thanks to Jamie on google groups.

Update

Based on the VBScript by WhoIsRich combined with details in this answer, here's a PowerShell script to amend these & related settings:

function Set-ProxySettings {
    [CmdletBinding()]
    param ( #could improve with parameter sets 
        [Parameter(Mandatory = $false)]
        [bool]$AutomaticDetect = $true
        ,
        [Parameter(Mandatory = $false)]
        [bool]$UseProxyForLAN = $false
        ,
        [Parameter(Mandatory = $false)]
        [AllowNull()][AllowEmptyString()]
        [string]$ProxyAddress = $null
        ,
        [Parameter(Mandatory = $false)]
        [int]$ProxyPort = 8080 #closest we have to a default port for proxies
        ,
        [AllowNull()][AllowEmptyString()]
        [bool]$UseAutomaticConfigurationScript = $false
    )
    begin {
        [string]$ProxyRegRoot = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
        [string]$DefaultConnectionSettingsPath = (Join-Path $ProxyRegRoot 'Connections')
        [byte]$MaskProxyEnabled = 2
        [byte]$MaskUseAutomaticConfigurationScript = 4
        [byte]$MaskAutomaticDetect = 8
        [int]$ProxyConnectionSettingIndex = 8
    }
    process {
    #this setting is affected by multiple options, so fetch once here 
    [byte[]]$DefaultConnectionSettings = Get-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' | Select-Object -ExpandProperty 'DefaultConnectionSettings'

    #region auto detect
    if($AutomaticDetect) { 
        Set-ItemProperty -Path $ProxyRegRoot -Name AutoDetect -Value 1
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskAutomaticDetect
    } else {
        Set-ItemProperty -Path $ProxyRegRoot -Name AutoDetect -Value 0
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskAutomaticDetect)
    }
    #endregion

    #region defined proxy
    if($UseProxyForLAN) {
        if(-not ([string]::IsNullOrWhiteSpace($ProxyAddress))) {
            Set-ItemProperty -Path $ProxyRegRoot -Name ProxyServer -Value ("{0}:{1}" -f $ProxyAddress,$ProxyPort)
        }
        Set-ItemProperty -Path $ProxyRegRoot -Name ProxyEnable -Value 1
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskProxyEnabled
    } else {
        Set-ItemProperty -Path $ProxyRegRoot -Name ProxyEnable -Value 0        
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskProxyEnabled)
    }
    #endregion

    #region config script
    if($UseAutomaticConfigurationScript){
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskUseAutomaticConfigurationScript
    }else{
        $DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskUseAutomaticConfigurationScript) 
    }
    #endregion

    #persist the updates made above
    Set-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' -Value $DefaultConnectionSettings
    }
}

Hidden Features of C#?

@David in Dakota:

Console.WriteLine( "-".PadRight( 21, '-' ) );

I used to do this, until I discovered that the String class has a constructor that allows you to do the same thing in a cleaner way:

new String('-',22);

How to count lines in a document?

there are many ways. using wc is one.

wc -l file

others include

awk 'END{print NR}' file

sed -n '$=' file (GNU sed)

grep -c ".*" file

Create a view with ORDER BY clause

Error is: FROM (SELECT empno,name FROM table1 where location = 'A' ORDER BY emp_no)

And solution is : FROM (SELECT empno,name FROM table1 where location = 'A') ORDER BY emp_no

Data binding in React

With the new feature called Hooks from the React team which makes functional components to handle state changes.. your question can be solved easily

import React, { useState, useEffect } from 'react'
import ReactDOM from 'react-dom';

const Demo = props =>{
    const [text, setText] = useState("there");
    return props.logic(text, setText);
};

const App = () => {
    const [text, setText] = useState("hello");

    const componentDidMount = () =>{
        setText("hey");
    };
    useEffect(componentDidMount, []);

    const logic = (word, setWord) => (
        <div>
            <h1>{word}</h1>
            <input type="text" value={word} onChange={e => setWord(e.target.value)}></input>
            <h1>{text}</h1>
            <input type="text" value={text} onChange={e => setText(e.target.value)}></input>
        </div>
    );
    return <Demo logic={logic} />;
};

ReactDOM.render(<App />,document.getElementById("root"));

Getting SyntaxError for print with keyword argument end=' '

Are you sure you are using Python 3.x? The syntax isn't available in Python 2.x because print is still a statement.

print("foo" % bar, end=" ")

in Python 2.x is identical to

print ("foo" % bar, end=" ")

or

print "foo" % bar, end=" "

i.e. as a call to print with a tuple as argument.

That's obviously bad syntax (literals don't take keyword arguments). In Python 3.x print is an actual function, so it takes keyword arguments, too.

The correct idiom in Python 2.x for end=" " is:

print "foo" % bar,

(note the final comma, this makes it end the line with a space rather than a linebreak)

If you want more control over the output, consider using sys.stdout directly. This won't do any special magic with the output.

Of course in somewhat recent versions of Python 2.x (2.5 should have it, not sure about 2.4), you can use the __future__ module to enable it in your script file:

from __future__ import print_function

The same goes with unicode_literals and some other nice things (with_statement, for example). This won't work in really old versions (i.e. created before the feature was introduced) of Python 2.x, though.

How to symbolicate crash log Xcode?

Follow these steps in Xcode 10 to symbolicate a crash log from an app build on the same machine:

  1. Inside Organizer, locate the archive where the app is based on.
  2. Click on the Download Debug Symbols button. Nothing will appear in your Downloads folder, but that's OK.
  3. Connect the build machine to an iOS device.
  4. Select the device in Devices and Simulators.
  5. Click on the View Devices Logs button.
  6. Drag-and-drop the crash file to the left panel. The file must end with a .crash extension, otherwise the drag fails.
  7. Switch to the All Logs tab.
  8. Select the added crash file.
  9. The file should automatically symbolicate, otherwise use the right-click context menu item Re-Symbolicate Log.

SQL Logic Operator Precedence: And and Or

Query to show a 3-variable boolean expression truth table :

;WITH cteData AS
(SELECT 0 AS A, 0 AS B, 0 AS C
UNION ALL SELECT 0,0,1
UNION ALL SELECT 0,1,0
UNION ALL SELECT 0,1,1
UNION ALL SELECT 1,0,0
UNION ALL SELECT 1,0,1
UNION ALL SELECT 1,1,0
UNION ALL SELECT 1,1,1
)
SELECT cteData.*,
    CASE WHEN

(A=1) OR (B=1) AND (C=1)

    THEN 'True' ELSE 'False' END AS Result
FROM cteData

Results for (A=1) OR (B=1) AND (C=1) :

A   B   C   Result
0   0   0   False
0   0   1   False
0   1   0   False
0   1   1   True
1   0   0   True
1   0   1   True
1   1   0   True
1   1   1   True

Results for (A=1) OR ( (B=1) AND (C=1) ) are the same.

Results for ( (A=1) OR (B=1) ) AND (C=1) :

A   B   C   Result
0   0   0   False
0   0   1   False
0   1   0   False
0   1   1   True
1   0   0   False
1   0   1   True
1   1   0   False
1   1   1   True

What does "make oldconfig" do exactly in the Linux kernel makefile?

Summary

As mentioned by Ignacio, it updates your .config for you after you update the kernel source, e.g. with git pull.

It tries to keep your existing options.

Having a script for that is helpful because:

  • new options may have been added, or old ones removed

  • the kernel's Kconfig configuration format has options that:

    • imply one another via select
    • depend on another via depends

    Those option relationships make manual config resolution even harder.

Let's modify .config manually to understand how it resolves configurations

First generate a default configuration with:

make defconfig

Now edit the generated .config file manually to emulate a kernel update and run:

make oldconfig

to see what happens. Some conclusions:

  1. Lines of type:

    # CONFIG_XXX is not set
    

    are not mere comments, but actually indicate that the parameter is not set.

    For example, if we remove the line:

    # CONFIG_DEBUG_INFO is not set
    

    and run make oldconfig, it will ask us:

    Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
    

    When it is over, the .config file will be updated.

    If you change any character of the line, e.g. to # CONFIG_DEBUG_INFO, it does not count.

  2. Lines of type:

    # CONFIG_XXX is not set
    

    are always used for the negation of a property, although:

    CONFIG_XXX=n
    

    is also understood as the negation.

    For example, if you remove # CONFIG_DEBUG_INFO is not set and answer:

    Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
    

    with N, then the output file contains:

    # CONFIG_DEBUG_INFO is not set
    

    and not:

    CONFIG_DEBUG_INFO=n
    

    Also, if we manually modify the line to:

    CONFIG_DEBUG_INFO=n
    

    and run make oldconfig, then the line gets modified to:

    # CONFIG_DEBUG_INFO is not set
    

    without oldconfig asking us.

  3. Configs whose dependencies are not met, do not appear on the .config. All others do.

    For example, set:

    CONFIG_DEBUG_INFO=y
    

    and run make oldconfig. It will now ask us for: DEBUG_INFO_REDUCED, DEBUG_INFO_SPLIT, etc. configs.

    Those properties did not appear on the defconfig before.

    If we look under lib/Kconfig.debug where they are defined, we see that they depend on DEBUG_INFO:

    config DEBUG_INFO_REDUCED
        bool "Reduce debugging information"
        depends on DEBUG_INFO
    

    So when DEBUG_INFO was off, they did not show up at all.

  4. Configs which are selected by turned on configs are automatically set without asking the user.

    For example, if CONFIG_X86=y and we remove the line:

    CONFIG_ARCH_MIGHT_HAVE_PC_PARPORT=y
    

    and run make oldconfig, the line gets recreated without asking us, unlike DEBUG_INFO.

    This happens because arch/x86/Kconfig contains:

    config X86
        def_bool y
        [...]
        select ARCH_MIGHT_HAVE_PC_PARPORT
    

    and select forces that option to be true. See also: https://unix.stackexchange.com/questions/117521/select-vs-depends-in-kernel-kconfig

  5. Configs whose constraints are not met are asked for.

    For example, defconfig had set:

    CONFIG_64BIT=y
    CONFIG_RCU_FANOUT=64
    

    If we edit:

    CONFIG_64BIT=n
    

    and run make oldconfig, it will ask us:

    Tree-based hierarchical RCU fanout value (RCU_FANOUT) [32] (NEW)
    

    This is because RCU_FANOUT is defined at init/Kconfig as:

    config RCU_FANOUT
        int "Tree-based hierarchical RCU fanout value"
        range 2 64 if 64BIT
        range 2 32 if !64BIT
    

    Therefore, without 64BIT, the maximum value is 32, but we had 64 set on the .config, which would make it inconsistent.

Bonuses

make olddefconfig sets every option to their default value without asking interactively. It gets run automatically on make to ensure that the .config is consistent in case you've modified it manually like we did. See also: https://serverfault.com/questions/116299/automatically-answer-defaults-when-doing-make-oldconfig-on-a-kernel-tree

make alldefconfig is like make olddefconfig, but it also accepts a config fragment to merge. This target is used by the merge_config.sh script: https://stackoverflow.com/a/39440863/895245

And if you want to automate the .config modification, that is not too simple: How do you non-interactively turn on features in a Linux kernel .config file?

How to return a string from a C++ function?

You never give any value to your strings in main so they are empty, and thus obviously the function returns an empty string.

Replace:

string str1, str2, str3;

with:

string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";

Also, you have several problems in your replaceSubstring function:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::find returns a std::string::size_type (aka. size_t) not an int. Two differences: size_t is unsigned, and it's not necessarily the same size as an int depending on your platform (eg. on 64 bits Linux or Windows size_t is unsigned 64 bits while int is signed 32 bits).
  • What happens if s2 is not part of s1? I'll leave it up to you to find how to fix that. Hint: std::string::npos ;)

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

it's well documented here:

https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6

How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:

http://tomcat.apache.org/tomcat-7.0-doc/config/http.html

Standard Implementation -> address

"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."

How to create string with multiple spaces in JavaScript

In 2021 - use ES6 Template Literals for this task. If you need IE11 Support - use a transpiler.

let a = `something       something`;

Template Literals are fast, powerful and produce cleaner code.


If you need IE11 support and you don't have transpiler, stay strong and use \xa0 - it is a NO-BREAK SPACE char.

Reference from UTF-8 encoding table and Unicode characters, you can write as below:

var a = 'something' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + 'something';

Constant pointer vs Pointer to constant

Please refer the following link for better understanding about the difference between Const pointer and Pointer on a constant value.

constant pointer vs pointer on a constant value

Parsing JSON using Json.net

I don't know about JSON.NET, but it works fine with JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1):

using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
    public string OBJECT_NAME { get; set; }
    public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
    public int id { get; set; }
}
public class SubObject
{
    public NameTypePair attributes { get; set; }
    public Position position { get; set; }
}
public class Position
{
    public int x { get; set; }
    public int y { get; set; }
}
public class Foo
{
    public Foo() { objects = new List<SubObject>(); }
    public string displayFieldName { get; set; }
    public NameTypePair fieldAliases { get; set; }
    public PositionType positionType { get; set; }
    public Ref reference { get; set; }
    public List<SubObject> objects { get; set; }
}
static class Program
{

    const string json = @"{
  ""displayFieldName"" : ""OBJECT_NAME"", 
  ""fieldAliases"" : {
    ""OBJECT_NAME"" : ""OBJECT_NAME"", 
    ""OBJECT_TYPE"" : ""OBJECT_TYPE""
  }, 
  ""positionType"" : ""point"", 
  ""reference"" : {
    ""id"" : 1111
  }, 
  ""objects"" : [
    {
      ""attributes"" : {
        ""OBJECT_NAME"" : ""test name"", 
        ""OBJECT_TYPE"" : ""test type""
      }, 
      ""position"" : 
      {
        ""x"" : 5, 
        ""y"" : 7
      }
    }
  ]
}";


    static void Main()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Foo foo = ser.Deserialize<Foo>(json);
    }


}

Edit:

Json.NET works using the same JSON and classes.

Foo foo = JsonConvert.DeserializeObject<Foo>(json);

Link: Serializing and Deserializing JSON with Json.NET

Bootstrap Align Image with text

Try using .pull-left to left align image along with text.

Ex:

<p>At the time all text elements goes here.At the time all text elements goes here. At the time all text elements goes here.<img src="images/hello-missing.jpg" class="pull-left img-responsive" style="padding:15px;" /> to uncovering the truth .</p>

What can be the reasons of connection refused errors?

The error means the OS of the listening socket recognized the inbound connection request but chose to intentionally reject it.

Assuming an intermediate firewall is not getting in the way, there are only two reasons (that I know of) for the OS to reject an inbound connection request. One reason has already been mentioned several times - the listening port being connected to is not open.

There is another reason that has not been mentioned yet - the listening port is actually open and actively being used, but its backlog of queued inbound connection requests has reached its maximum so there is no room available for the inbound connection request to be queued at that moment. The server code has not called accept() enough times yet to finish clearing out available slots for new queue items.

Wait a moment or so and try the connection again. Unfortunately, there is no way to differentiate between "the port is not open at all" and "the port is open but too busy right now". They both use the same generic error code.

How can I remove a button or make it invisible in Android?

In order to access elements from another class you can simply use

findViewById(R.id.**nameOfYourelementID**).setVisibility(View.GONE); 

Is it possible to auto-format your code in Dreamweaver?

And for JavaScript source format you can use Dreamweaver JavaScript source formatting extension.(available on adobe)

Code to loop through all records in MS Access

Found a good code with comments explaining each statement. Code found at - accessallinone

Sub DAOLooping()
On Error GoTo ErrorHandler

Dim strSQL As String
Dim rs As DAO.Recordset

strSQL = "tblTeachers"
'For the purposes of this post, we are simply going to make 
'strSQL equal to tblTeachers.
'You could use a full SELECT statement such as:
'SELECT * FROM tblTeachers (this would produce the same result in fact).
'You could also add a Where clause to filter which records are returned:
'SELECT * FROM tblTeachers Where ZIPPostal = '98052'
' (this would return 5 records)

Set rs = CurrentDb.OpenRecordset(strSQL)
'This line of code instantiates the recordset object!!! 
'In English, this means that we have opened up a recordset 
'and can access its values using the rs variable.

With rs


    If Not .BOF And Not .EOF Then
    'We don’t know if the recordset has any records, 
    'so we use this line of code to check. If there are no records 
    'we won’t execute any code in the if..end if statement.    

        .MoveLast
        .MoveFirst
        'It is not necessary to move to the last record and then back 
        'to the first one but it is good practice to do so.

        While (Not .EOF)
        'With this code, we are using a while loop to loop 
        'through the records. If we reach the end of the recordset, .EOF 
        'will return true and we will exit the while loop.

            Debug.Print rs.Fields("teacherID") & " " & rs.Fields("FirstName")
            'prints info from fields to the immediate window

            .MoveNext
            'We need to ensure that we use .MoveNext, 
            'otherwise we will be stuck in a loop forever… 
            '(or at least until you press CTRL+Break)
        Wend

    End If

    .close
    'Make sure you close the recordset...
End With

ExitSub:
    Set rs = Nothing
    '..and set it to nothing
    Exit Sub
ErrorHandler:
    Resume ExitSub
End Sub

Recordsets have two important properties when looping through data, EOF (End-Of-File) and BOF (Beginning-Of-File). Recordsets are like tables and when you loop through one, you are literally moving from record to record in sequence. As you move through the records the EOF property is set to false but after you try and go past the last record, the EOF property becomes true. This works the same in reverse for the BOF property.

These properties let us know when we have reached the limits of a recordset.

What is the difference between varchar and varchar2 in Oracle?

As for now, they are synonyms.

VARCHAR is reserved by Oracle to support distinction between NULL and empty string in future, as ANSI standard prescribes.

VARCHAR2 does not distinguish between a NULL and empty string, and never will.

If you rely on empty string and NULL being the same thing, you should use VARCHAR2.

How to get first and last element in an array in java?

This is the given array.

    int myIntegerNumbers[] = {1,2,3,4,5,6,7,8,9,10};

// If you want print the last element in the array.

    int lastNumerOfArray= myIntegerNumbers[9];
    Log.i("MyTag", lastNumerOfArray + "");

// If you want to print the number of element in the array.

    Log.i("MyTag", "The number of elements inside" +
            "the array " +myIntegerNumbers.length);

// Second method to print the last element inside the array.

    Log.i("MyTag", "The last elements inside " +
            "the array " + myIntegerNumbers[myIntegerNumbers.length-1]);

Dynamically creating keys in a JavaScript associative array

JavaScript does not have associative arrays. It has objects.

The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

It looks like you have an associative array because an Array is also an Object - however you're not actually adding things into the array at all; you're setting fields on the object.

Now that that is cleared up, here is a working solution to your example:

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// Split into key and value
var kvp = cleaned.split('=');

// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.

How to unzip a list of tuples into individual lists?

Use zip(*list):

>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]

The zip() function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l you apply all tuples in l as separate arguments to the zip() function, so zip() pairs up 1 with 3 with 8 first, then 2 with 4 and 9. Those happen to correspond nicely with the columns, or the transposition of l.

zip() produces tuples; if you must have mutable list objects, just map() the tuples to lists or use a list comprehension to produce a list of lists:

map(list, zip(*l))          # keep it a generator
[list(t) for t in zip(*l)]  # consume the zip generator into a list of lists

Could not obtain information about Windows NT group user

I had to connect to VPN for the publish script to successfully deploy to the DB.

jQuery: find element by text

Yes, use the jQuery contains selector.

Changing the URL in react-router v4 without using Redirect or Link

React Router v4

There's a couple of things that I needed to get this working smoothly.

The doc page on auth workflow has quite a lot of what is required.

However I had three issues

  1. Where does the props.history come from?
  2. How do I pass it through to my component which isn't directly inside the Route component
  3. What if I want other props?

I ended up using:

  1. option 2 from an answer on 'Programmatically navigate using react router' - i.e. to use <Route render> which gets you props.history which can then be passed down to the children.
  2. Use the render={routeProps => <MyComponent {...props} {routeProps} />} to combine other props from this answer on 'react-router - pass props to handler component'

N.B. With the render method you have to pass through the props from the Route component explicitly. You also want to use render and not component for performance reasons (component forces a reload every time).

const App = (props) => (
    <Route 
        path="/home" 
        render={routeProps => <MyComponent {...props} {...routeProps}>}
    />
)

const MyComponent = (props) => (
    /**
     * @link https://reacttraining.com/react-router/web/example/auth-workflow
     * N.B. I use `props.history` instead of `history`
     */
    <button onClick={() => {
        fakeAuth.signout(() => props.history.push('/foo'))
    }}>Sign out</button>
)

One of the confusing things I found is that in quite a few of the React Router v4 docs they use MyComponent = ({ match }) i.e. Object destructuring, which meant initially I didn't realise that Route passes down three props, match, location and history

I think some of the other answers here are assuming that everything is done via JavaScript classes.

Here's an example, plus if you don't need to pass any props through you can just use component

class App extends React.Component {
    render () {
        <Route 
            path="/home" 
            component={MyComponent}
        />
    }
}

class MyComponent extends React.Component {
    render () {
        /**
         * @link https://reacttraining.com/react-router/web/example/auth-workflow
         * N.B. I use `props.history` instead of `history`
         */
        <button onClick={() => {
            this.fakeAuth.signout(() => this.props.history.push('/foo'))
        }}>Sign out</button>
    }
}

What is the @Html.DisplayFor syntax for?

I think the main benefit would be when you define your own Display Templates, or use Data annotations.

So for example if your title was a date, you could define

[DisplayFormat(DataFormatString = "{0:d}")]

and then on every page it would display the value in a consistent manner. Otherwise you may have to customise the display on multiple pages. So it does not help much for plain strings, but it does help for currencies, dates, emails, urls, etc.

For example instead of an email address being a plain string it could show up as a link:

<a href="mailto:@ViewData.Model">@ViewData.TemplateInfo.FormattedModelValue</a>

How do I use JDK 7 on Mac OSX?

An easy way to install Java 7 on a Mac is by using Homebrew, thanks to the Homebrew Cask plugin (which is now installed by default).

Run this command to install Java 7:

brew cask install caskroom/versions/java7

How to make a transparent border using CSS?

Well if you want fully transparent than you can use

border: 5px solid transparent;

If you mean opaque/transparent, than you can use

border: 5px solid rgba(255, 255, 255, .5);

Here, a means alpha, which you can scale, 0-1.

Also some might suggest you to use opacity which does the same job as well, the only difference is it will result in child elements getting opaque too, yes, there are some work arounds but rgba seems better than using opacity.

For older browsers, always declare the background color using #(hex) just as a fall back, so that if old browsers doesn't recognize the rgba, they will apply the hex color to your element.

Demo

Demo 2 (With a background image for nested div)

Demo 3 (With an img tag instead of a background-image)

body {
    background: url(http://www.desktopas.com/files/2013/06/Images-1920x1200.jpg);   
}

div.wrap {
    border: 5px solid #fff; /* Fall back, not used in fiddle */
    border: 5px solid rgba(255, 255, 255, .5);
    height: 400px;
    width: 400px;
    margin: 50px;
    border-radius: 50%;
}

div.inner {
    background: #fff; /* Fall back, not used in fiddle */
    background: rgba(255, 255, 255, .5);
    height: 380px;
    width: 380px;
    border-radius: 50%; 
    margin: auto; /* Horizontal Center */
    margin-top: 10px; /* Vertical Center ... Yea I know, that's 
                         manually calculated*/
}

Note (For Demo 3): Image will be scaled according to the height and width provided so make sure it doesn't break the scaling ratio.

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

I just got this error and i came to know that it is about the local variable alias

at the end of the stored procedure i had like

select @localvariable1,@localvariable2

it was working fine in sql but when i ran this in ssrs it was always throwing error but after I gave alias it is fixed

select @localvariable1 as A,@localvariable2 as B

How to generate .NET 4.0 classes from xsd?

If you want to generate the class with auto properties, convert the XSD to XML using this then convert the XML to JSON using this and copy to clipboard the result. Then in VS, inside the file where your class will be created, go to Edit>Paste Special>Paste JSON as classes.

Why is document.body null in my javascript?

The body hasn't been defined at this point yet. In general, you want to create all elements before you execute javascript that uses these elements. In this case you have some javascript in the head section that uses body. Not cool.

You want to wrap this code in a window.onload handler or place it after the <body> tag (as mentioned by e-bacho 2.0).

<head>
    <title>Javascript Tests</title>

    <script type="text/javascript">
      window.onload = function() {
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);

        alert("Why does the span change after this alert? Not before?");
      }

    </script>
</head>

See demo.

How to programmatically move, copy and delete files and directories on SD?

Use standard Java I/O. Use Environment.getExternalStorageDirectory() to get to the root of external storage (which, on some devices, is an SD card).

Constructor of an abstract class in C#

You are absolutely correct. We cannot instantiate an abstract class because abstract methods don't have any body i.e. implementation is not possible for abstract methods. But there may be some scenarios where you want to initialize some variables of base class. You can do that by using base keyword as suggested by @Rodrick. In such cases, we need to use constructors in our abstract class.

Write a file in external storage in Android

You can do this with this code also.

 public class WriteSDCard extends Activity {

 private static final String TAG = "MEDIA";
 private TextView tv;

  /** Called when the activity is first created. */
@Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);     
    tv = (TextView) findViewById(R.id.TextView01);
    checkExternalMedia();
    writeToSDFile();
    readRaw();
 }

/** Method to check whether external media available and writable. This is adapted from
   http://developer.android.com/guide/topics/data/data-storage.html#filesExternal */

 private void checkExternalMedia(){
      boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;
    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // Can read and write the media
        mExternalStorageAvailable = mExternalStorageWriteable = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // Can only read the media
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
    } else {
        // Can't read or write
        mExternalStorageAvailable = mExternalStorageWriteable = false;
    }   
    tv.append("\n\nExternal Media: readable="
            +mExternalStorageAvailable+" writable="+mExternalStorageWriteable);
}

/** Method to write ascii text characters to file on SD card. Note that you must add a 
   WRITE_EXTERNAL_STORAGE permission to the manifest file or this method will throw
   a FileNotFound Exception because you won't have write permission. */

private void writeToSDFile(){

    // Find the root of the external storage.
    // See http://developer.android.com/guide/topics/data/data-  storage.html#filesExternal

    File root = android.os.Environment.getExternalStorageDirectory(); 
    tv.append("\nExternal file system root: "+root);

    // See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder

    File dir = new File (root.getAbsolutePath() + "/download");
    dir.mkdirs();
    File file = new File(dir, "myData.txt");

    try {
        FileOutputStream f = new FileOutputStream(file);
        PrintWriter pw = new PrintWriter(f);
        pw.println("Hi , How are you");
        pw.println("Hello");
        pw.flush();
        pw.close();
        f.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        Log.i(TAG, "******* File not found. Did you" +
                " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
    } catch (IOException e) {
        e.printStackTrace();
    }   
    tv.append("\n\nFile written to "+file);
}

/** Method to read in a text file placed in the res/raw directory of the application. The
  method reads in all lines of the file sequentially. */

private void readRaw(){
    tv.append("\nData read from res/raw/textfile.txt:");
    InputStream is = this.getResources().openRawResource(R.raw.textfile);
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr, 8192);    // 2nd arg is buffer size

    // More efficient (less readable) implementation of above is the composite expression
    /*BufferedReader br = new BufferedReader(new InputStreamReader(
            this.getResources().openRawResource(R.raw.textfile)), 8192);*/

    try {
        String test;    
        while (true){               
            test = br.readLine();   
            // readLine() returns null if no more lines in the file
            if(test == null) break;
            tv.append("\n"+"    "+test);
        }
        isr.close();
        is.close();
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    tv.append("\n\nThat is all");
}
}

keytool error Keystore was tampered with, or password was incorrect

I have solve this issue by using default password "changeit".

mysqld: Can't change dir to data. Server doesn't start

Check your real my.ini file location and set --defaults-file="location" with this command

mysql --defaults-file="C:\MYSQL\my.ini" -u root -p

This solution is permanently for your cmd Screen.

Disable scrolling in all mobile devices

Setting position to relative does not work for me. It only works if I set the position of body to fixed:

document.body.style.position = "fixed";
document.body.style.overflowY = "hidden";
document.body.addEventListener('touchstart', function(e){ e.preventDefault()});

How different is Scrum practice from Agile Practice?

Agile is not a methodology, embracing the agile manifesto means adopting a particular philosophy about software development. Within that philosophical perspective, there are many processes and practices. Scrum is a set of practices that follow agile principles. Many people grab onto the practices and processes without embracing (or even understanding) the underlying philosophy and they often end up with gorillarinas.

How to initialize an array of custom objects

I had to create an array of a predefined type, and I successfully did as follows:

[System.Data.DataColumn[]]$myitems = ([System.Data.DataColumn]("col1"), 
                [System.Data.DataColumn]("col2"),  [System.Data.DataColumn]("col3"))

Use PHP to convert PNG to JPG with compression?

<?php
function createThumbnail($imageDirectory, $imageName, $thumbDirectory, $thumbWidth) {
    $explode = explode(".", $imageName);
    $filetype = $explode[1];

    if ($filetype == 'jpg') {
        $srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
    } else
    if ($filetype == 'jpeg') {
        $srcImg = imagecreatefromjpeg("$imageDirectory/$imageName");
    } else
    if ($filetype == 'png') {
        $srcImg = imagecreatefrompng("$imageDirectory/$imageName");
    } else
    if ($filetype == 'gif') {
        $srcImg = imagecreatefromgif("$imageDirectory/$imageName");
    }

    $origWidth = imagesx($srcImg);
    $origHeight = imagesy($srcImg);

    $ratio = $origWidth / $thumbWidth;
    $thumbHeight = $origHeight / $ratio;

    $thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight);
    imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $origWidth, $origHeight);

    if ($filetype == 'jpg') {
        imagejpeg($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'jpeg') {
        imagejpeg($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'png') {
        imagepng($thumbImg, "$thumbDirectory/$imageName");
    } else
    if ($filetype == 'gif') {
        imagegif($thumbImg, "$thumbDirectory/$imageName");
    }
}
    ?>

This is a very good thumbnail script =) Here's an example:

$path = The path to the folder where the original picture is. $name = The filename of the file you want to make a thumbnail of. $thumbpath = The path to the directory where you want the thumbnail to be saved into. $maxwidth = the maximum width of the thumbnail in PX eg. 100 (wich will be 100px).

createThumbnail($path, $name, $thumbpath, $maxwidth);

What are Java command line options to set to allow JVM to be remotely debugged?

Here is the easiest solution.

There are a lot of environment special configurations needed if you are using Maven. So, if you start your program from maven, just run the mvnDebug command instead of mvn, it will take care of starting your app with remote debugging configurated. Now you can just attach a debugger on port 8000.

It'll take care of all the environment problems for you.

Reading text files using read.table

From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

So, perhaps your data file isn't clean. Being more specific will help the data import:

d = read.table("foobar.txt", 
               sep="\t", 
               col.names=c("id", "name"), 
               fill=FALSE, 
               strip.white=TRUE)

will specify exact columns and fill=FALSE will force a two column data frame.

"Register" an .exe so you can run it from any command line in Windows

Rather than putting the executable into a directory on the path, you should create a batch file in a directory on the path that launches the program. This way you don't separate the executable from its supporting files, and you don't add other stuff in the same directory to the path unintentionally.

Such batch file can look like this:

@echo off
start "" "C:\Program Files (x86)\Software\software.exe" %*