Programs & Examples On #Wsdl.exe

The Web Services Description Language tool generates code for XML Web services and XML Web service clients from WSDL contract files, XSD schemas, and .discomap discovery documents.

how to generate web service out of wsdl

step-1

open -> Visual Studio 2017 Developer Command Prompt

step-2

WSDL.exe  /OUT:myFile.cs WSDLURL  /Language:CS /serverInterface
  • /serverInterface (this to create interface from wsdl file)
  • WSDL.exe (this use to create class from wsdl. this comes with .net
  • /OUT: (output file name)

step-2

create new "Web service Project"

step-3

add -> web service

step-4

copy all code from myFile.cs (generated above) except "using classes" eg:

 /// <remarks/>
    [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "4.6.1055.0")]
    [System.Web.Services.WebServiceBindingAttribute(Name="calculoterServiceSoap",Namespace="http://tempuri.org/")]

public interface ICalculoterServiceSoap {

    /// <remarks/>
    [System.Web.Services.WebMethodAttribute()]
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/addition", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    string addition(int firtNo, int secNo);
}

step-4

past it into your webService.asmx.cs (inside of namespace) created above in step-2

step-5

inherit the interface class with your web service class eg:

public class WebService2 : ICalculoterServiceSoap

Location of WSDL.exe

You can find what you want in windows by looking with the windows dir command, use the administrator account to make it easy:

c:>dir wsdl.exe /s

How to show validation message below each textbox using jquery?

You could put static elements after the fields and show them, or you could inject the validation message dynamically. See the below example for how to inject dynamically.

This example also follows the best practice of setting focus to the blank field so user can easily correct the issue.

Note that you could easily genericize this to work with any label & field (for required fields anyway), instead of my example which specifically codes each validation.

Your fiddle is updated, see here: jsfiddle

The code:

$('form').on('submit', function (e) {
    var focusSet = false;
    if (!$('#email').val()) {
        if ($("#email").parent().next(".validation").length == 0) // only add if not added
        {
            $("#email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter email address</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        $('#email').focus();
        focusSet = true;
    } else {
        $("#email").parent().next(".validation").remove(); // remove it
    }
    if (!$('#password').val()) {
        if ($("#password").parent().next(".validation").length == 0) // only add if not added
        {
            $("#password").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Please enter password</div>");
        }
        e.preventDefault(); // prevent form from POST to server
        if (!focusSet) {
            $("#password").focus();
        }
    } else {
        $("#password").parent().next(".validation").remove(); // remove it
    }
});  

The CSS:

    .validation
    {
      color: red;
      margin-bottom: 20px;
    }

What are file descriptors, explained in simple terms?

As an addition to other answers, unix considers everything as a file system. Your keyboard is a file that is read only from the perspective of the kernel. The screen is a write only file. Similarly, folders, input-output devices etc are also considered to be files. Whenever a file is opened, say when the device drivers[for device files] requests an open(), or a process opens an user file the kernel allocates a file descriptor, an integer that specifies the access to that file such it being read only, write only etc. [for reference : https://en.wikipedia.org/wiki/Everything_is_a_file ]

docker-compose up for only certain containers

You usually don't want to do this. With Docker Compose you define services that compose your app. npm and manage.py are just management commands. You don't need a container for them. If you need to, say create your database tables with manage.py, all you have to do is:

docker-compose run client python manage.py create_db

Think of it as the one-off dynos Heroku uses.

If you really need to treat these management commands as separate containers (and also use Docker Compose for these), you could create a separate .yml file and start Docker Compose with the following command:

docker-compose up -f my_custom_docker_compose.yml

How to change the default background color white to something else in twitter bootstrap

I would not recommend changing the actual bootstrap CSS files. If you do not want to use Jako's first solution you can create a custom bootstrap style sheet with one of the available Bootstrap theme generator (Bootstrap theme generators). That way you can use 1 style sheet with all of the default Bootstrap CSS with just the one change to it that you want. With a Bootstrap theme generator you do not need to write any CSS. You only need to set the hex values for the color you want for the body (Scaffolding; bodyBackground).

Appending to 2D lists in Python

You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:

listy = [[] for i in range(3)]

Running your example code now gives the result you probably expected:

>>> listy = [[] for i in range(3)]
>>> listy[1] = [1,2]
>>> listy
[[], [1, 2], []]
>>> listy[1].append(3)
>>> listy
[[], [1, 2, 3], []]
>>> listy[2].append(1)
>>> listy
[[], [1, 2, 3], [1]]

Take nth column in a text file

For the sake of completeness:

while read _ _ one _ two _; do
    echo "$one $two"
done < file.txt

Instead of _ an arbitrary variable (such as junk) can be used as well. The point is just to extract the columns.

Demo:

$ while read _ _ one _ two _; do echo "$one $two"; done < /tmp/file.txt
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

I fixed this error on Ubuntu by carefully following the instructions for installing R. This included:

  1. adding deb http://cran.utstat.utoronto.ca/bin/linux/ubuntu trusty/ to my /etc/apt/sources.list file
  2. Running sudo apt-get update
  3. Running sudo apt-get install r-base-dev

For step 1 you can chose any CRAN download mirror in place of my University of Toronto one if you would like.

Spring Boot @autowired does not work, classes in different package

When you use @SpringBootApplication annotation in for example package

com.company.config

it will automatically make component scan like this:

@ComponentScan("com.company.config") 

So it will NOT scan packages like com.company.controller etc.. Thats why you have to declare your @SpringBootApplication in package one level prior to your normal packages like this: com.company OR use scanBasePackages property, like this:

@SpringBootApplication(scanBasePackages = { "com.company" })

OR componentScan:

@SpringBootApplication
@ComponentScan("com.company")


Select SQL results grouped by weeks

I think this should do it..

Select 
ProductName,
WeekNumber,
sum(sale)
from
(
    SELECT 
    ProductName,
    DATEDIFF(week, '2011-05-30', date) AS WeekNumber,
    sale
    FROM table
)
GROUP BY
ProductName,
WeekNumber

Using C# to check if string contains a string in string array

You can also do the same thing as Anton Gogolev suggests to check if any item in stringArray1 matches any item in stringArray2:

if(stringArray1.Any(stringArray2.Contains))

And likewise all items in stringArray1 match all items in stringArray2:

if(stringArray1.All(stringArray2.Contains))

Find and replace specific text characters across a document with JS

Vanilla JavaScript solution:

document.body.innerHTML = document.body.innerHTML.replace(/Original/g, "New")

How to send objects through bundle

You can also use Gson to convert an object to a JSONObject and pass it on bundle. For me was the most elegant way I found to do this. I haven't tested how it affects performance.

In Initial Activity

Intent activity = new Intent(MyActivity.this,NextActivity.class);
activity.putExtra("myObject", new Gson().toJson(myobject));
startActivity(activity);

In Next Activity

String jsonMyObject;
Bundle extras = getIntent().getExtras();
if (extras != null) {
   jsonMyObject = extras.getString("myObject");
}
MyObject myObject = new Gson().fromJson(jsonMyObject, MyObject.class);

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

On top of what @wisekiddo said, you can also modify your build settings in the project.pbxproj file by setting the Swift 3 @obj Inference to default like SWIFT_SWIFT3_OBJC_INFERENCE = Default; for your build flavors (i.e. debug and release), especially if you're coming from some other environment besides Xcode

bash script read all the files in directory

You can go without the loop:

find /path/to/dir -type f -exec /your/first/command \{\} \; -exec /your/second/command \{\} \; 

HTH

Rails - Could not find a JavaScript runtime?

On CentOS 6.5, the following worked for me:

sudo yum install -y nodejs

Convert object to JSON string in C#

I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.

public class ReturnData 
{
    public int totalCount { get; set; }
    public List<ExceptionReport> reports { get; set; }  
}

public class ExceptionReport
{
    public int reportId { get; set; }
    public string message { get; set; }  
}


string json = JsonConvert.SerializeObject(myReturnData);

Trying to check if username already exists in MySQL database using PHP

PHP 7 improved query.........

$sql = mysqli_query($conn, "SELECT * from users WHERE user_uid = '$uid'"); if (mysqli_num_rows($sql) > 0) { echo 'Username taken.'; }

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

All that was necessary for me, a Ubuntu user, was to change the owner of the ~/.android directory. In a terminal type the following command:

sudo chown -R username:username ~/.android

Obviously, you must replace "username" (twice) with your username.

I wasn't sure if I should post this as an answer because the original poster's question was concerning Windows Vista, not Ubuntu. However I found this post whilst searching for the answer on Ubuntu so I believe it is pertinent. I don't have sufficient reputation to comment on +Maher Gamal's answer, though, which is what lead me to this answer. Hopefully someone else finds it useful!

Getting only response header from HTTP POST using curl

-D, --dump-header <file>
       Write the protocol headers to the specified file.

       This  option  is handy to use when you want to store the headers
       that a HTTP site sends to you. Cookies from  the  headers  could
       then  be  read  in  a  second  curl  invocation by using the -b,
       --cookie option! The -c, --cookie-jar option is however a better
       way to store cookies.

and

-S, --show-error
       When used with -s, --silent, it makes curl show an error message if it fails.

and

-L/--location
      (HTTP/HTTPS) If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response
      code), this option will make curl redo the request on the new place. If used together with -i/--include or -I/--head, headers from  all  requested
      pages  will  be  shown.  When authentication is used, curl only sends its credentials to the initial host. If a redirect takes curl to a different
      host, it won’t be able to intercept the user+password. See also --location-trusted on how to change this. You can limit the amount of redirects to
      follow by using the --max-redirs option.

      When curl follows a redirect and the request is not a plain GET (for example POST or PUT), it will do the following request with a GET if the HTTP
      response was 301, 302, or 303. If the response code was any other 3xx code, curl will re-send the following  request  using  the  same  unmodified
      method.

from the man page. so

curl -sSL -D - www.acooke.org -o /dev/null

follows redirects, dumps the headers to stdout and sends the data to /dev/null (that's a GET, not a POST, but you can do the same thing with a POST - just add whatever option you're already using for POSTing data)

note the - after the -D which indicates that the output "file" is stdout.

How do I delete virtual interface in Linux?

Have you tried:

ifconfig 10:35978f0 down

As the physical interface is 10 and the virtual aspect is after the colon :.

See also https://www.cyberciti.biz/faq/linux-command-to-remove-virtual-interfaces-or-network-aliases/

Easy way to build Android UI?

Droiddraw is good. I have been using it since long and haven't faced any issues yet (though it crashes sometimes, but thats ok)

scp from Linux to Windows

I had to use pscp like above Hesham's post once I downloaded and installed putty. I did it to Windows from Linux on Windows so I entered the following:

c:\ssl>pscp username@linuxserver:keenan/ssl/* .

This will copy everything in the keenan/ssl folder to the local folder (.) you performed this command from (c:\ssl). The keenan/ssl will specify the home folder of the username user, for example the full path would be /home/username/keenan/ssl. You can specify a different folder using a forward slash (/), such as

c:\ssl>pscp username@linuxserver:/home/username/keenan/ssl/* .

So you can specify any folder at the root of Linux using :/.

Media Queries: How to target desktop, tablet, and mobile?

If you want to target a device then just write min-device-width. For example:

For iPhone

@media only screen and (min-device-width: 480px){}

For tablets

@media only screen and (min-device-width: 768px){}

Here are some good articles:

Bootstrap 3 Gutter Size

If you use sass in your own project, you can override the default bootstrap gutter size by copy pasting the sass variables from bootstrap's _variables.scss file into your own projects sass file somewhere, like:

// Grid columns
//
// Set the number of columns and specify the width of the gutters.
$grid-gutter-width-base:     50px !default;
$grid-gutter-widths: (
        xs: $grid-gutter-width-base,
        sm: $grid-gutter-width-base,
        md: $grid-gutter-width-base,
        lg: $grid-gutter-width-base,
        xl: $grid-gutter-width-base
) !default;

Now your gutters will be 50px instead of 30px. I find this to be the cleanest method to adjust the gutter size.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Short answer:

There is no difference in semantic.

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Further reading:

RequestMapping can be used at class level:

This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.

while GetMapping only applies to method:

Annotation for mapping HTTP GET requests onto specific handler methods.


https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

how to remove empty strings from list, then remove duplicate values from a list

Amiram Korach solution is indeed tidy. Here's an alternative for the sake of versatility.

var count = dtList.Count;
// Perform a reverse tracking.
for (var i = count - 1; i > -1; i--)
{
    if (dtList[i]==string.Empty) dtList.RemoveAt(i);
}
// Keep only the unique list items.
dtList = dtList.Distinct().ToList();

ImportError: No module named BeautifulSoup

you can import bs4 instead of BeautifulSoup. Since bs4 is a built-in module, no additional installation is required.

from bs4 import BeautifulSoup
import re

doc = ['<html><head><title>Page title</title></head>',
       '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.',
       '<p id="secondpara" align="blah">This is paragraph <b>two</b>.',
       '</html>']
soup = BeautifulSoup(''.join(doc))

print soup.prettify()

If you want to request, using requests module. request is using urllib, requests modules. but I personally recommendation using requests module instead of urllib

module install for using:

$ pip install requests

Here's how to use the requests module:

import requests as rq
res = rq.get('http://www.example.com')

print(res.content)
print(res.status_code)

How to convert a structure to a byte array in C#?

This is fairly easy, using marshalling.

Top of file

using System.Runtime.InteropServices

Function

byte[] getBytes(CIFSPacket str) {
    int size = Marshal.SizeOf(str);
    byte[] arr = new byte[size];

    IntPtr ptr = Marshal.AllocHGlobal(size);
    Marshal.StructureToPtr(str, ptr, true);
    Marshal.Copy(ptr, arr, 0, size);
    Marshal.FreeHGlobal(ptr);
    return arr;
}

And to convert it back:

CIFSPacket fromBytes(byte[] arr) {
    CIFSPacket str = new CIFSPacket();

    int size = Marshal.SizeOf(str);
    IntPtr ptr = Marshal.AllocHGlobal(size);

    Marshal.Copy(arr, 0, ptr, size);

    str = (CIFSPacket)Marshal.PtrToStructure(ptr, str.GetType());
    Marshal.FreeHGlobal(ptr);

    return str;
}

In your structure, you will need to put this before a string

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)]
public string Buffer;

And make sure SizeConst is as big as your biggest possible string.

And you should probably read this: http://msdn.microsoft.com/en-us/library/4ca6d5z7.aspx

Add row to query result using select

is it possible to extend query results with literals like this?

Yes.

Select Name
From Customers
UNION ALL
Select 'Jason'
  • Use UNION to add Jason if it isn't already in the result set.
  • Use UNION ALL to add Jason whether or not he's already in the result set.

MS-DOS Batch file pause with enter key

There's a pause command that does just that, though it's not specifically the enter key.

If you really want to wait for only the enter key, you can use the set command to ask for user input with a dummy variable, something like:

set /p DUMMY=Hit ENTER to continue...

System.Collections.Generic.List does not contain a definition for 'Select'

You need to have the System.Linq namespace included in your view since Select is an extension method. You have a couple of options on how to do this:

Add @using System.Linq to the top of your cshtml file.

If you find that you will be using this namespace often in many of your views, you can do this for all views by modifying the web.config inside of your Views folder (not the one at the root). You should see a pages/namespace XML element, create a new add child that adds System.Linq. Here is an example:

<configuration>
    <system.web.webPages.razor>
        <pages>
            <namespaces>
                <add namespace="System.Linq" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>
</configuration>

How do you display a Toast from a background thread on Android?

Like this or this, with a Runnable that shows the Toast. Namely,

Activity activity = // reference to an Activity
// or
View view = // reference to a View

activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        showToast(activity);
    }
});
// or
view.post(new Runnable() {
    @Override
    public void run() {
        showToast(view.getContext());
    }
});

private void showToast(Context ctx) {
    Toast.makeText(ctx, "Hi!", Toast.LENGTH_SHORT).show();
}

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.

Run Android studio emulator on AMD processor

Since Android Studio 3.2 and Android Emulator 27.3.8 - the android emulator is supported by Windows Hypervisor Platform and as stated in the official android developer blog - there is mac support (since OS X v10.10 Yosemite) and windows support (since April 2018 Update). You may find further instructions on the developer blog.

In my opinion, the performance is significantly better than all previous workarounds.

Good MapReduce examples

Map reduce is a framework that was developed to process massive amounts of data efficiently. For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.

For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases. Map Reduce provides a cluster based implementation where data is processed in a distributed manner

Here is a wikipedia article explaining what map-reduce is all about

Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and a well used use-case.

Personally, found this link quite useful to understand the concept

Copying the explanation provided in the blog (In case the link goes stale)

Finding Friends

MapReduce is a framework originally developed at Google that allows for easy large scale distributed computing across a number of domains. Apache Hadoop is an open source implementation.

I'll gloss over the details, but it comes down to defining two functions: a map function and a reduce function. The map function takes a value and outputs key:value pairs. For instance, if we define a map function that takes a string and outputs the length of the word as the key and the word itself as the value then map(steve) would return 5:steve and map(savannah) would return 8:savannah. You may have noticed that the map function is stateless and only requires the input value to compute it's output value. This allows us to run the map function against values in parallel and provides a huge advantage. Before we get to the reduce function, the mapreduce framework groups all of the values together by key, so if the map functions output the following key:value pairs:

3 : the
3 : and
3 : you
4 : then
4 : what
4 : when
5 : steve
5 : where
8 : savannah
8 : research

They get grouped as:

3 : [the, and, you]
4 : [then, what, when]
5 : [steve, where]
8 : [savannah, research]

Each of these lines would then be passed as an argument to the reduce function, which accepts a key and a list of values. In this instance, we might be trying to figure out how many words of certain lengths exist, so our reduce function will just count the number of items in the list and output the key with the size of the list, like:

3 : 3
4 : 3
5 : 2
8 : 2

The reductions can also be done in parallel, again providing a huge advantage. We can then look at these final results and see that there were only two words of length 5 in our corpus, etc...

The most common example of mapreduce is for counting the number of times words occur in a corpus. Suppose you had a copy of the internet (I've been fortunate enough to have worked in such a situation), and you wanted a list of every word on the internet as well as how many times it occurred.

The way you would approach this would be to tokenize the documents you have (break it into words), and pass each word to a mapper. The mapper would then spit the word back out along with a value of 1. The grouping phase will take all the keys (in this case words), and make a list of 1's. The reduce phase then takes a key (the word) and a list (a list of 1's for every time the key appeared on the internet), and sums the list. The reducer then outputs the word, along with it's count. When all is said and done you'll have a list of every word on the internet, along with how many times it appeared.

Easy, right? If you've ever read about mapreduce, the above scenario isn't anything new... it's the "Hello, World" of mapreduce. So here is a real world use case (Facebook may or may not actually do the following, it's just an example):

Facebook has a list of friends (note that friends are a bi-directional thing on Facebook. If I'm your friend, you're mine). They also have lots of disk space and they serve hundreds of millions of requests everyday. They've decided to pre-compute calculations when they can to reduce the processing time of requests. One common processing request is the "You and Joe have 230 friends in common" feature. When you visit someone's profile, you see a list of friends that you have in common. This list doesn't change frequently so it'd be wasteful to recalculate it every time you visited the profile (sure you could use a decent caching strategy, but then I wouldn't be able to continue writing about mapreduce for this problem). We're going to use mapreduce so that we can calculate everyone's common friends once a day and store those results. Later on it's just a quick lookup. We've got lots of disk, it's cheap.

Assume the friends are stored as Person->[List of Friends], our friends list is then:

A -> B C D
B -> A C D E
C -> A B D E
D -> A B C E
E -> B C D

Each line will be an argument to a mapper. For every friend in the list of friends, the mapper will output a key-value pair. The key will be a friend along with the person. The value will be the list of friends. The key will be sorted so that the friends are in order, causing all pairs of friends to go to the same reducer. This is hard to explain with text, so let's just do it and see if you can see the pattern. After all the mappers are done running, you'll have a list like this:

For map(A -> B C D) :

(A B) -> B C D
(A C) -> B C D
(A D) -> B C D

For map(B -> A C D E) : (Note that A comes before B in the key)

(A B) -> A C D E
(B C) -> A C D E
(B D) -> A C D E
(B E) -> A C D E
For map(C -> A B D E) :

(A C) -> A B D E
(B C) -> A B D E
(C D) -> A B D E
(C E) -> A B D E
For map(D -> A B C E) :

(A D) -> A B C E
(B D) -> A B C E
(C D) -> A B C E
(D E) -> A B C E
And finally for map(E -> B C D):

(B E) -> B C D
(C E) -> B C D
(D E) -> B C D
Before we send these key-value pairs to the reducers, we group them by their keys and get:

(A B) -> (A C D E) (B C D)
(A C) -> (A B D E) (B C D)
(A D) -> (A B C E) (B C D)
(B C) -> (A B D E) (A C D E)
(B D) -> (A B C E) (A C D E)
(B E) -> (A C D E) (B C D)
(C D) -> (A B C E) (A B D E)
(C E) -> (A B D E) (B C D)
(D E) -> (A B C E) (B C D)

Each line will be passed as an argument to a reducer. The reduce function will simply intersect the lists of values and output the same key with the result of the intersection. For example, reduce((A B) -> (A C D E) (B C D)) will output (A B) : (C D) and means that friends A and B have C and D as common friends.

The result after reduction is:

(A B) -> (C D)
(A C) -> (B D)
(A D) -> (B C)
(B C) -> (A D E)
(B D) -> (A C E)
(B E) -> (C D)
(C D) -> (A B E)
(C E) -> (B D)
(D E) -> (B C)

Now when D visits B's profile, we can quickly look up (B D) and see that they have three friends in common, (A C E).

What is a handle in C++?

This appears in the context of the Handle-Body-Idiom, also called Pimpl idiom. It allows one to keep the ABI (binary interface) of a library the same, by keeping actual data into another class object, which is merely referenced by a pointer held in an "handle" object, consisting of functions that delegate to that class "Body".

It's also useful to enable constant time and exception safe swap of two objects. For this, merely the pointer pointing to the body object has to be swapped.

JPanel setBackground(Color.BLACK) does nothing

You have to call the super.paintComponent(); as well, to allow the Java API draw the original background. The super refers to the original JPanel code.

public void paintComponent(Graphics g){
    super.paintComponent(g);

    g.setColor(Color.red);
    g.fillOval(player.getxCenter(), player.getyCenter(), player.getRadius(), player.getRadius());
}

Pandas Merge - How to avoid duplicating columns

You can work out the columns that are only in one DataFrame and use this to select a subset of columns in the merge.

cols_to_use = df2.columns.difference(df.columns)

Then perform the merge (note this is an index object but it has a handy tolist() method).

dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer')

This will avoid any columns clashing in the merge.

Angular 2 / 4 / 5 not working in IE11

I was having the same issue, if you have enabled Display intranet sites in Compatibility View the polyfills.ts won't work, you still need to add the following line as has been told.

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

How to use clock() in C++

clock() returns the number of clock ticks since your program started. There is a related constant, CLOCKS_PER_SEC, which tells you how many clock ticks occur in one second. Thus, you can test any operation like this:

clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;

Access denied for user 'test'@'localhost' (using password: YES) except root user

In my case the same error happen because I was trying to use mysql by just typing "mysql" instead of "mysql -u root -p"

Javascript to set hidden form value on drop down change

Here you can set hidden's value at onchange event of dropdown list :

$('#myDropDown').bind('change', function () {
  $('#myHidden').val('setted value');
});

your hidden and drop down list :

<input type="hidden" id="myHidden" />

<select id="myDropDown">
   <option value="opt 1">Option 1</option>
   <option value="opt 2">Option 2</option>
   <option value="opt 3">Option 3</option>
</ select>

Task vs Thread differences

Usually you hear Task is a higher level concept than thread... and that's what this phrase means:

  1. You can't use Abort/ThreadAbortedException, you should support cancel event in your "business code" periodically testing token.IsCancellationRequested flag (also avoid long or timeoutless connections e.g. to db, otherwise you will never get a chance to test this flag). By the similar reason Thread.Sleep(delay) call should be replaced with Task.Delay(delay, token) call (passing token inside to have possibility to interrupt delay).

  2. There are no thread's Suspend and Resume methods functionality with tasks. Instance of task can't be reused either.

  3. But you get two new tools:

    a) continuations

    // continuation with ContinueWhenAll - execute the delegate, when ALL
    // tasks[] had been finished; other option is ContinueWhenAny
    
    Task.Factory.ContinueWhenAll( 
       tasks,
       () => {
           int answer = tasks[0].Result + tasks[1].Result;
           Console.WriteLine("The answer is {0}", answer);
       }
    );
    

    b) nested/child tasks

    //StartNew - starts task immediately, parent ends whith child
    var parent = Task.Factory.StartNew
    (() => {
              var child = Task.Factory.StartNew(() =>
             {
             //...
             });
          },  
          TaskCreationOptions.AttachedToParent
    );
    
  4. So system thread is completely hidden from task, but still task's code is executed in the concrete system thread. System threads are resources for tasks and ofcourse there is still thread pool under the hood of task's parallel execution. There can be different strategies how thread get new tasks to execute. Another shared resource TaskScheduler cares about it. Some problems that TaskScheduler solves 1) prefer to execute task and its conitnuation in the same thread minimizing switching cost - aka inline execution) 2) prefer execute tasks in an order they were started - aka PreferFairness 3) more effective distribution of tasks between inactive threads depending on "prior knowledge of tasks activity" - aka Work Stealing. Important: in general "async" is not same as "parallel". Playing with TaskScheduler options you can setup async tasks be executed in one thread synchronously. To express parallel code execution higher abstractions (than Tasks) could be used: Parallel.ForEach, PLINQ, Dataflow.

  5. Tasks are integrated with C# async/await features aka Promise Model, e.g there requestButton.Clicked += async (o, e) => ProcessResponce(await client.RequestAsync(e.ResourceName)); the execution of client.RequestAsync will not block UI thread. Important: under the hood Clicked delegate call is absolutely regular (all threading is done by compiler).

That is enough to make a choice. If you need to support Cancel functionality of calling legacy API that tends to hang (e.g. timeoutless connection) and for this case supports Thread.Abort(), or if you are creating multithread background calculations and want to optimize switching between threads using Suspend/Resume, that means to manage parallel execution manually - stay with Thread. Otherwise go to Tasks because of they will give you easy manipulate on groups of them, are integrated into the language and make developers more productive - Task Parallel Library (TPL) .

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

I had this error when I tried to use retrolambda inside my unit tests. I didn't find a solution how to make retrolambda work with unit tests. So, I use old fashioned anonymous classes instead of lambdas with my unit tests, and it works for me.

Call of overloaded function is ambiguous

Cast the value so the compiler knows which function to call:

p.setval(static_cast<const char *>( 0 ));

Note, that you have a segmentation fault in your code after you get it to compile (depending on which function you really wanted to call).

Angular 2 - NgFor using numbers instead collections

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill().map((x,i)=>i); // [0,1,2,3,4]
    this.numbers = Array(5).fill(4); // [4,4,4,4,4]
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@Component({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@Component({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Setting table row height

You can remove some extra spacing as well if you place a border-collapse: collapse; CSS statement on your table.

C# windows application Event: CLR20r3 on application start

To solve CLR20r3 problem set - Local User Policy \ Computer Configuration \ Windows Settings \ Security Settings \ Local Policies \ Security Options - System cryptography: Use FIPS 140 compliant cryptographic algorithms, including encryption, hashing and signing - Disable

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

  1. Open Command line (Start -> Run -> type "cmd")
  2. type PATH
  3. Verify that you can see here written C:\Program Files\Mozilla Firefox15\Firefox.exe

It will be probably not here - because thats what the error says. How to fix it?

  1. Click Start
  2. Right click on "Computer" and click "Properties"
  3. In left menu Choose "Advanced system settings"
  4. Go to tab "Advanced" and click "Environment Variables..."
  5. In the window below select "Path" and click "Edit..." (Admin rights needed)
  6. Add at the end the desired path, semicolon separated
  7. Possible restart of computer needed

It his does not help then change the constructor like this:

File pathToBinary = new File("C:\\Program Files\\Mozilla Firefox15\\Firefox.exe");
FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
FirefoxDriver _driver = new FirefoxDriver(ffBinary,firefoxProfile);

Generic Property in C#

You cannot 'alter' the property syntax this way. What you can do is this:

class Foo
{
    string MyProperty { get; set; }  // auto-property with inaccessible backing field
}

and a generic version would look like this:

class Foo<T>
{
    T MyProperty { get; set; }
}

How to convert Nonetype to int or string?

That TypeError only appears when you try to pass int() None (which is the only NoneType value, as far as I know). I would say that your real goal should not be to convert NoneType to int or str, but to figure out where/why you're getting None instead of a number as expected, and either fix it or handle the None properly.

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

Might not be relevant for everyone but this little detail was causing mine not to work:

Change div from this:

<div class="map">

To this:

<div id="map">

link with target="_blank" does not open in new tab in Chrome

Learn from another guy:

<a onclick="window.open(this.href,'_blank');return false;" href="http://www.foracure.org.au">Some Other Site</a>

It makes sense to me.

How to read specific lines from a file (by line number)?

The quick answer:

f=open('filename')
lines=f.readlines()
print lines[25]
print lines[29]

or:

lines=[25, 29]
i=0
f=open('filename')
for line in f:
    if i in lines:
        print i
    i+=1

There is a more elegant solution for extracting many lines: linecache (courtesy of "python: how to jump to a particular line in a huge text file?", a previous stackoverflow.com question).

Quoting the python documentation linked above:

>>> import linecache
>>> linecache.getline('/etc/passwd', 4)
'sys:x:3:3:sys:/dev:/bin/sh\n'

Change the 4 to your desired line number, and you're on. Note that 4 would bring the fifth line as the count is zero-based.

If the file might be very large, and cause problems when read into memory, it might be a good idea to take @Alok's advice and use enumerate().

To Conclude:

  • Use fileobject.readlines() or for line in fileobject as a quick solution for small files.
  • Use linecache for a more elegant solution, which will be quite fast for reading many files, possible repeatedly.
  • Take @Alok's advice and use enumerate() for files which could be very large, and won't fit into memory. Note that using this method might slow because the file is read sequentially.

How to pause for specific amount of time? (Excel/VBA)

this works flawlessly for me. insert any code before or after the "do until" loop. In your case, put the 5 lines (time1= & time2= & "do until" loop) at the end inside your do loop

sub whatever()
Dim time1, time2

time1 = Now
time2 = Now + TimeValue("0:00:01")
    Do Until time1 >= time2
        DoEvents
        time1 = Now()
    Loop

End sub

PowerShell try/catch/finally

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

printf with std::string?

Please don't use printf("%s", your_string.c_str());

Use cout << your_string; instead. Short, simple and typesafe. In fact, when you're writing C++, you generally want to avoid printf entirely -- it's a leftover from C that's rarely needed or useful in C++.

As to why you should use cout instead of printf, the reasons are numerous. Here's a sampling of a few of the most obvious:

  1. As the question shows, printf isn't type-safe. If the type you pass differs from that given in the conversion specifier, printf will try to use whatever it finds on the stack as if it were the specified type, giving undefined behavior. Some compilers can warn about this under some circumstances, but some compilers can't/won't at all, and none can under all circumstances.
  2. printf isn't extensible. You can only pass primitive types to it. The set of conversion specifiers it understands is hard-coded in its implementation, and there's no way for you to add more/others. Most well-written C++ should use these types primarily to implement types oriented toward the problem being solved.
  3. It makes decent formatting much more difficult. For an obvious example, when you're printing numbers for people to read, you typically want to insert thousands separators every few digits. The exact number of digits and the characters used as separators varies, but cout has that covered as well. For example:

    std::locale loc("");
    std::cout.imbue(loc);
    
    std::cout << 123456.78;
    

    The nameless locale (the "") picks a locale based on the user's configuration. Therefore, on my machine (configured for US English) this prints out as 123,456.78. For somebody who has their computer configured for (say) Germany, it would print out something like 123.456,78. For somebody with it configured for India, it would print out as 1,23,456.78 (and of course there are many others). With printf I get exactly one result: 123456.78. It is consistent, but it's consistently wrong for everybody everywhere. Essentially the only way to work around it is to do the formatting separately, then pass the result as a string to printf, because printf itself simply will not do the job correctly.

  4. Although they're quite compact, printf format strings can be quite unreadable. Even among C programmers who use printf virtually every day, I'd guess at least 99% would need to look things up to be sure what the # in %#x means, and how that differs from what the # in %#f means (and yes, they mean entirely different things).

What are the file limits in Git (number and size)?

As of 2018-04-20 Git for Windows has a bug which effectively limits the file size to 4GB max using that particular implementation (this bug propagates to lfs as well).

Reflection - get attribute name and value on property

To get all attributes of a property in a dictionary use this:

typeof(Book)
  .GetProperty("Name")
  .GetCustomAttributes(false) 
  .ToDictionary(a => a.GetType().Name, a => a);

remember to change from false to true if you want to include inheritted attributes as well.

how to make label visible/invisible?

You can set display attribute as none to hide a label.

<label id="excel-data-div" style="display: none;"></label>

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Example query: SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;

Nexus 5 USB driver

You should install Google Drivers from: http://developer.android.com/sdk/win-usb.html#top That works for me every time

Displaying Windows command prompt output and redirecting it to a file

mtee is a small utility which works very well for this purpose. It's free, source is open, and it Just Works.

You can find it at http://www.commandline.co.uk.

Used in a batch file to display output AND create a log file simultaneously, the syntax looks like this:

    someprocess | mtee /+ mylogfile.txt

Where /+ means to append output.

This assumes that you have copied mtee into a folder which is in the PATH, of course.

How to clone git repository with specific revision/changeset?

Its simple. You just have to set the upstream for the current branch

$ git clone repo
$ git checkout -b newbranch
$ git branch --set-upstream-to=origin/branch newbranch
$ git pull

That's all

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Reasons I've encountered this error:

  1. Did not use .AsNoTracking() when querying for existing entities. Especially when calling a helper function to check permissions.
  2. Calling .Include() on a query and then trying to edit the parent. Example: var ent = repo.Query<Ent>().Include(e=>e.Ent2).First(); ...repo.Edit(e.Ent2); repo.Edit(e); If I'm going to edit a nested object, I try to separate these into separate query calls now. If you can't do that, set the child object to null and iterate through lists, detaching objects like this
  3. Editing an old entity in a Put web call. The new item is already added to the repo, so modify that one and have it be saved in super.Put(). Example of what will throw an error: public void Put(key, newItem){ var old = repo.Query<Entity>().Where(e=>Id==key).First(); ... repo.Edit(old); super.Put(key,newItem); ... }
  4. Multiple helper functions edit the same entity. Instead of passing the ID as a parameter into each function, pass a reference to the entity. Error solved!

How to change symbol for decimal point in double.ToString()?

Create an extension method?

Console.WriteLine(value.ToGBString());

// ...

public static class DoubleExtensions
{
    public static string ToGBString(this double value)
    {
        return value.ToString(CultureInfo.GetCultureInfo("en-GB"));
    }
}

Python subprocess/Popen with a modified environment

you might use my_env.get("PATH", '') instead of my_env["PATH"] in case PATH somehow not defined in the original environment, but other than that it looks fine.

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

How to insert default values in SQL table?

To insert the default values you should omit them something like this :

Insert into Table (Field2) values(5)

All other fields will have null or their default values if it has defined.

How to wrap text in textview in Android

You need to add your TextView in a ScrollView with something like this :

<ScrollView android:id="@+id/SCROLL_VIEW"  
android:layout_height="150px"   
android:layout_width="fill_parent">  

<TextView   
   android:id="@+id/TEXT_VIEW"   
   android:layout_height="wrap_content"   
   android:layout_width="wrap_content"   
   android:text="This text view should act as header This text view should act as header This text view should act as header This text view should act as header This text view should act as header This text view should act as header This text view should act as header" />  
 </ScrollView>

Java - Convert String to valid URI object

You can use the multi-argument constructors of the URI class. From the URI javadoc:

The multi-argument constructors quote illegal characters as required by the components in which they appear. The percent character ('%') is always quoted by these constructors. Any other characters are preserved.

So if you use

URI uri = new URI("http", "www.google.com?q=a b");

Then you get http:www.google.com?q=a%20b which isn't quite right, but it's a little closer.

If you know that your string will not have URL fragments (e.g. http://example.com/page#anchor), then you can use the following code to get what you want:

String s = "http://www.google.com?q=a b";
String[] parts = s.split(":",2);
URI uri = new URI(parts[0], parts[1], null);

To be safe, you should scan the string for # characters, but this should get you started.

concatenate char array in C

Have a look at the strcat function.

In particular, you could try this:

const char* name = "hello";
const char* extension = ".txt";

char* name_with_extension;
name_with_extension = malloc(strlen(name)+1+4); /* make space for the new string (should check the return value ...) */
strcpy(name_with_extension, name); /* copy name into the new var */
strcat(name_with_extension, extension); /* add the extension */

How do I get the value of text input field using JavaScript?

simple js

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}

Nested lists python

You can do this. Adapt it to your situation:

  for l in Nlist:
      for item in l:
        print item

Passing variable number of arguments around

You can use inline assembly for the function call. (in this code I assume the arguments are characters).

void format_string(char *fmt, ...);
void debug_print(int dbg_level, int numOfArgs, char *fmt, ...)
    {
        va_list argumentsToPass;
        va_start(argumentsToPass, fmt);
        char *list = new char[numOfArgs];
        for(int n = 0; n < numOfArgs; n++)
            list[n] = va_arg(argumentsToPass, char);
        va_end(argumentsToPass);
        for(int n = numOfArgs - 1; n >= 0; n--)
        {
            char next;
            next = list[n];
            __asm push next;
        }
        __asm push fmt;
        __asm call format_string;
        fprintf(stdout, fmt);
    }

How to draw circle in html page?

You can use the border-radius attribute to give it a border-radius equivalent to the element's border-radius. For example:

<div style="border-radius 10px; -moz-border-radius 10px; -webkit-border-radius 10px; width: 20px; height: 20px; background: red; border: solid black 1px;">&nbsp;</div>

(The reason for using the -moz and -webkit extensions is to support pre-CSS3-final versions of Gecko and Webkit.)

There are more examples on this page. As far as inserting text, you can do it but you have to be mindful of the positioning, as most browsers' box padding model still uses the outer square.

Adding padding to a tkinter widget only on one side

The padding options padx and pady of the grid and pack methods can take a 2-tuple that represent the left/right and top/bottom padding.

Here's an example:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

Binding Listbox to List<object> in WinForms

There are two main routes here:

1: listBox1.DataSource = yourList;

Do any manipulation (Add/Delete) to yourList and Rebind.
Set DisplayMember and ValueMember to control what is shown.

2: listBox1.Items.AddRange(yourList.ToArray());

(or use a for-loop to do Items.Add(...))

You can control Display by overloading ToString() of the list objects or by implementing the listBox1.Format event.

VBA vlookup reference in different sheet

Your code work fine, provided the value in Sheet2!D2 exists in Sheet1!A:A. If it does not then error 1004 is raised.

To handle this case, try

Sub Demo()
    Dim MyStringVar1 As Variant
    On Error Resume Next
    MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
      Worksheets("Sheet1").Range("A:C"), 1, False)
    On Error GoTo 0
    If IsEmpty(MyStringVar1) Then
        MsgBox "Value not found!"
    End If

    Range("E2") = MyStringVar1

End Sub

What is dynamic programming?

It's an optimization of your algorithm that cuts running time.

While a Greedy Algorithm is usually called naive, because it may run multiple times over the same set of data, Dynamic Programming avoids this pitfall through a deeper understanding of the partial results that must be stored to help build the final solution.

A simple example is traversing a tree or a graph only through the nodes that would contribute with the solution, or putting into a table the solutions that you've found so far so you can avoid traversing the same nodes over and over.

Here's an example of a problem that's suited for dynamic programming, from UVA's online judge: Edit Steps Ladder.

I'm going to make quick briefing of the important part of this problem's analysis, taken from the book Programming Challenges, I suggest you check it out.

Take a good look at that problem, if we define a cost function telling us how far appart two strings are, we have two consider the three natural types of changes:

Substitution - change a single character from pattern "s" to a different character in text "t", such as changing "shot" to "spot".

Insertion - insert a single character into pattern "s" to help it match text "t", such as changing "ago" to "agog".

Deletion - delete a single character from pattern "s" to help it match text "t", such as changing "hour" to "our".

When we set each of this operations to cost one step we define the edit distance between two strings. So how do we compute it?

We can define a recursive algorithm using the observation that the last character in the string must be either matched, substituted, inserted or deleted. Chopping off the characters in the last edit operation leaves a pair operation leaves a pair of smaller strings. Let i and j be the last character of the relevant prefix of and t, respectively. there are three pairs of shorter strings after the last operation, corresponding to the string after a match/substitution, insertion or deletion. If we knew the cost of editing the three pairs of smaller strings, we could decide which option leads to the best solution and choose that option accordingly. We can learn this cost, through the awesome thing that's recursion:

#define MATCH 0 /* enumerated type symbol for match */
#define INSERT 1 /* enumerated type symbol for insert */
#define DELETE 2 /* enumerated type symbol for delete */


int string_compare(char *s, char *t, int i, int j)

{

    int k; /* counter */
    int opt[3]; /* cost of the three options */
    int lowest_cost; /* lowest cost */
    if (i == 0) return(j * indel(’ ’));
    if (j == 0) return(i * indel(’ ’));
    opt[MATCH] = string_compare(s,t,i-1,j-1) +
      match(s[i],t[j]);
    opt[INSERT] = string_compare(s,t,i,j-1) +
      indel(t[j]);
    opt[DELETE] = string_compare(s,t,i-1,j) +
      indel(s[i]);
    lowest_cost = opt[MATCH];
    for (k=INSERT; k<=DELETE; k++)
    if (opt[k] < lowest_cost) lowest_cost = opt[k];
    return( lowest_cost );

}

This algorithm is correct, but is also impossibly slow.

Running on our computer, it takes several seconds to compare two 11-character strings, and the computation disappears into never-never land on anything longer.

Why is the algorithm so slow? It takes exponential time because it recomputes values again and again and again. At every position in the string, the recursion branches three ways, meaning it grows at a rate of at least 3^n – indeed, even faster since most of the calls reduce only one of the two indices, not both of them.

So how can we make the algorithm practical? The important observation is that most of these recursive calls are computing things that have already been computed before. How do we know? Well, there can only be |s| · |t| possible unique recursive calls, since there are only that many distinct (i, j) pairs to serve as the parameters of recursive calls.

By storing the values for each of these (i, j) pairs in a table, we can avoid recomputing them and just look them up as needed.

The table is a two-dimensional matrix m where each of the |s|·|t| cells contains the cost of the optimal solution of this subproblem, as well as a parent pointer explaining how we got to this location:

typedef struct {
int cost; /* cost of reaching this cell */
int parent; /* parent cell */
} cell;

cell m[MAXLEN+1][MAXLEN+1]; /* dynamic programming table */

The dynamic programming version has three differences from the recursive version.

First, it gets its intermediate values using table lookup instead of recursive calls.

**Second,**it updates the parent field of each cell, which will enable us to reconstruct the edit sequence later.

**Third,**Third, it is instrumented using a more general goal cell() function instead of just returning m[|s|][|t|].cost. This will enable us to apply this routine to a wider class of problems.

Here, a very particular analysis of what it takes to gather the most optimal partial results, is what makes the solution a "dynamic" one.

Here's an alternate, full solution to the same problem. It's also a "dynamic" one even though its execution is different. I suggest you check out how efficient the solution is by submitting it to UVA's online judge. I find amazing how such a heavy problem was tackled so efficiently.

How do I create and access the global variables in Groovy?

Like all OO languages, Groovy has no concept of "global" by itself (unlike, say, BASIC, Python or Perl).

If you have several methods that need to share the same variable, use a field:

class Foo {
    def a;

    def foo() {
        a = 1;
    }
    def bar() {
        print a;
    }
}

How can I have linebreaks in my long LaTeX equations?

multline is best to use. Instead, you can use dmath, split as well.

Here is an example:

\begin{multline}
  {\text {\bf \emph {T(u)}}} ={  \alpha *}{\frac{\sum_{i=1}^{\text{\bf \emph {I(u)}}}{{\text{\bf \emph {S(u,i)}}}* {\text {\bf \emph {Cr(P(u,i))}}} * {\text {\bf \emph {TF(u,i)}}}}}{\text {\bf \emph {I(u)}}}}  \\
   +{  \beta *}{\frac{\sum_{i=1}^{\text{\bf \emph {$I_h$(u)}}}{{\text{\bf \emph {S(u,i)}}}* {\text {\bf \emph {Cr(P(u,i))}}} * {\text {\bf \emph {TF(u,i)}}}}}{\text {\bf \emph {$I_h$(u)}}}}
\end{multline}

Structuring online documentation for a REST API

That's a very complex question for a simple answer.

You may want to take a look at existing API frameworks, like Swagger Specification (OpenAPI), and services like apiary.io and apiblueprint.org.

Also, here's an example of the same REST API described, organized and even styled in three different ways. It may be a good start for you to learn from existing common ways.

At the very top level I think quality REST API docs require at least the following:

  • a list of all your API endpoints (base/relative URLs)
  • corresponding HTTP GET/POST/... method type for each endpoint
  • request/response MIME-type (how to encode params and parse replies)
  • a sample request/response, including HTTP headers
  • type and format specified for all params, including those in the URL, body and headers
  • a brief text description and important notes
  • a short code snippet showing the use of the endpoint in popular web programming languages

Also there are a lot of JSON/XML-based doc frameworks which can parse your API definition or schema and generate a convenient set of docs for you. But the choice for a doc generation system depends on your project, language, development environment and many other things.

Remove element by id

you can just use element.remove()

How do I do a Date comparison in Javascript?

I would rather use the Date valueOf method instead of === or !==

Seems like === is comparing internal Object's references and nothing concerning date.

Are SSL certificates bound to the servers ip address?

Most SSL certificates are bound to the hostname of the machine and not the ip address.

You might get a better answer if you ask this question on serverfault.com

How can I update my ADT in Eclipse?

I had the same problem where there's no files under Generated Java files, BuildConfig and R.java were missing. The automatic build option is not generating.
In Eclipse under Project, uncheck Build Automatically. Then under Project select Build Project. You may need to fix the projec

How do I repair an InnoDB table?

The following solution was inspired by Sandro's tip above.

Warning: while it worked for me, but I cannot tell if it will work for you.

My problem was the following: reading some specific rows from a table (let's call this table broken) would crash MySQL. Even SELECT COUNT(*) FROM broken would kill it. I hope you have a PRIMARY KEY on this table (in the following sample, it's id).

  1. Make sure you have a backup or snapshot of the broken MySQL server (just in case you want to go back to step 1 and try something else!)
  2. CREATE TABLE broken_repair LIKE broken;
  3. INSERT broken_repair SELECT * FROM broken WHERE id NOT IN (SELECT id FROM broken_repair) LIMIT 1;
  4. Repeat step 3 until it crashes the DB (you can use LIMIT 100000 and then use lower values, until using LIMIT 1 crashes the DB).
  5. See if you have everything (you can compare SELECT MAX(id) FROM broken with the number of rows in broken_repair).
  6. At this point, I apparently had all my rows (except those which were probably savagely truncated by InnoDB). If you miss some rows, you could try adding an OFFSET to the LIMIT.

Good luck!

Add a new element to an array without specifying the index in Bash

As Dumb Guy points out, it's important to note whether the array starts at zero and is sequential. Since you can make assignments to and unset non-contiguous indices ${#array[@]} is not always the next item at the end of the array.

$ array=(a b c d e f g h)
$ array[42]="i"
$ unset array[2]
$ unset array[3]
$ declare -p array     # dump the array so we can see what it contains
declare -a array='([0]="a" [1]="b" [4]="e" [5]="f" [6]="g" [7]="h" [42]="i")'
$ echo ${#array[@]}
7
$ echo ${array[${#array[@]}]}
h

Here's how to get the last index:

$ end=(${!array[@]})   # put all the indices in an array
$ end=${end[@]: -1}    # get the last one
$ echo $end
42

That illustrates how to get the last element of an array. You'll often see this:

$ echo ${array[${#array[@]} - 1]}
g

As you can see, because we're dealing with a sparse array, this isn't the last element. This works on both sparse and contiguous arrays, though:

$ echo ${array[@]: -1}
i

WPF popup window

You need to create a new Window class. You can design that then any way you want. You can create and show a window modally like this:

MyWindow popup = new MyWindow();
popup.ShowDialog();

You can add a custom property for your result value, or if you only have two possible results ( + possibly undeterminate, which would be null), you can set the window's DialogResult property before closing it and then check for it (it is the value returned by ShowDialog()).

How do I add a bullet symbol in TextView?

Another best way to add bullet in any text view is stated below two steps:

First, create a drawable

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <!--set color of the bullet-->
   <solid 
       android:color="#666666"/> //set color of bullet

    <!--set size of the bullet-->
   <size 
       android:width="120dp"
        android:height="120dp"/>
</shape>

Then add this drawable in textview and set its pedding by using below properties

android:drawableStart="@drawable/bullet"
android:drawablePadding="10dp"

Working copy XXX locked and cleanup failed in SVN

In-place unversioning of the files, and a fresh checkout into the same location, has solved this problem for me.

In TortoiseSVN, to do an in-place unversioning, right-drag the root folder of the working copy from the file list onto itself in the directory tree, and choose "SVN Export versioned items here" from the pop-up menu. TortoiseSVN notices that the destination is the same as the source, and suggests unversioning the working copy.

After unversioning, do a fresh checkout into the same folder (which now contains an unversioned copy of all the files you had). TortoiseSVN will warn you that you are checking out into an existing folder, but you can go ahead.

After this, cleanups, updates and other operations worked without a hitch. Since both of the above steps preserve local modifications, there should not be any loss of information (but backing the working copy up before this may nevertheless be a good idea).

One warning: If the working copy contains mixed versions or uncommitted property changes, that information WILL be lost. For me, this is not a common occurrence, and given the choice of a corrupt working copy or losing uncommitted property changes, I tend to opt for the latter.

How to set a default entity property value with Hibernate

Suppose we have an entity which contains a sub-entity.

Using insertable = false, updatable = false on the entity prevents the entity from creating new sub-entities and preceding the default DBMS value. But the problem with this is that we are obliged to always use the default value or if we need the entity to contain another sub-entity that is not the default, we must try to change these annotations at runtime to insertable = true, updatable = true, so it doesn't seem like a good path.

Inside the sub-entity if it makes more sense to use in all the columns insertable = false, updatable = false so that no more sub-entities are created regardless of the method we use (with @DynamicInsert it would not be necessary)

Inserting a default value can be done in various ways such as Default entity property value using constructor or setter. Other ways like using JPA with columnDefinition have the drawback that they insert a null by default and the default value of the DBMS does not precede.


Insert default value using DBMS and optional using Hibernate

But using @DynamicInsert we avoid sending a null to the db when we want to insert a sub-entity with its default value, and in turn we allow sub-entities with values other than the default to be inserted.

For inserting, should this entity use dynamic sql generation where only non-null columns get referenced in the prepared sql statement?

Given the following needs:

  • The entity does not have the responsibility of creating new sub-entities.
  • When inserting an entity, the sub-entity is the one that was defined as default in the DBMS.
  • Possibility of creating an entity with a sub-entity which has a UUID other than the default.

DBMS: PostgreSQL | Language: Kotlin

@Entity
@Table(name = "entity")
@DynamicInsert
data class EntityTest(
        @Id @GeneratedValue @Column(name = "entity_uuid") val entityUUID: UUID? = null,

        @OneToOne(cascade = [CascadeType.ALL])
        @JoinColumn(name = "subentity_uuid", referencedColumnName = "subentity_uuid")
        var subentityTest: SubentityTest? = null
) {}

@Entity
@Table(name = "subentity")
data class SubentityTest(
        @Id @GeneratedValue @Column(name = "subentity_uuid", insertable = false, updatable = false) var subentityUUID: UUID? = null,
        @Column(insertable = false, updatable = false) var name: String,
) {
        constructor() : this(name = "")
}

And the value is set by default in the database:

alter table entity alter column subentity_uuid set default 'd87ee95b-06f1-52ab-83ed-5d882ae400e6'::uuid;

GL

How to define an enum with string value?

Well first you try to assign strings not chars, even if they are just one character. use ',' instead of ",". Next thing is, enums only take integral types without char you could use the unicode value, but i would strongly advice you not to do so. If you are certain that these values stay the same, in differnt cultures and languages, i would use a static class with const strings.

SQL Server - find nth occurrence in a string

Try this

CREATE FUNCTION [dbo].[CHARINDEX2] (
    @expressionToFind VARCHAR(MAX),
    @expressionToSearch VARCHAR(MAX),
    @occurrenceIndex INT,
    @startLocation INT = 0
)
RETURNS INT
AS BEGIN

IF @occurrenceIndex < 1 BEGIN
    RETURN CAST('The argument @occurrenceIndex must be a positive integer.' AS INT)
END

IF @startLocation < 0 BEGIN
    RETURN CAST('The argument @startLocation must be a non negative integer.' AS INT)
END

DECLARE @returnIndex INT

SET @returnIndex = CHARINDEX(@expressionToFind, @expressionToSearch, @startLocation)

IF (@occurrenceIndex = 1) BEGIN
    RETURN @returnIndex
END

DECLARE @target_length INT
SET @target_length = LEN(@expressionToFind)
SET @occurrenceIndex += -1

WHILE (@occurrenceIndex > 0 AND @returnIndex > 0) BEGIN
    SET @returnIndex = CHARINDEX(@expressionToFind, @expressionToSearch, @returnIndex + @target_length);
    SET @occurrenceIndex += -1
END

RETURN @returnIndex

END
GO

Do something if screen width is less than 960 px

// Adds and removes body class depending on screen width.
function screenClass() {
    if($(window).innerWidth() > 960) {
        $('body').addClass('big-screen').removeClass('small-screen');
    } else {
        $('body').addClass('small-screen').removeClass('big-screen');
    }
}

// Fire.
screenClass();

// And recheck when window gets resized.
$(window).bind('resize',function(){
    screenClass();
});

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Try:

cl /v

Actually, any time I give cl an argument, it prints out the version number on the first line.

You could just feed it a garbage argument and then parse the first line of the output, which contains the verison number.

Delete all but the most recent X files in bash

The problems with the existing answers:

  • inability to handle filenames with embedded spaces or newlines.
    • in the case of solutions that invoke rm directly on an unquoted command substitution (rm `...`), there's an added risk of unintended globbing.
  • inability to distinguish between files and directories (i.e., if directories happened to be among the 5 most recently modified filesystem items, you'd effectively retain fewer than 5 files, and applying rm to directories will fail).

wnoise's answer addresses these issues, but the solution is GNU-specific (and quite complex).

Here's a pragmatic, POSIX-compliant solution that comes with only one caveat: it cannot handle filenames with embedded newlines - but I don't consider that a real-world concern for most people.

For the record, here's the explanation for why it's generally not a good idea to parse ls output: http://mywiki.wooledge.org/ParsingLs

ls -tp | grep -v '/$' | tail -n +6 | xargs -I {} rm -- {}

Note: This command operates in the current directory; to target a directory explicitly, use a subshell ((...)):
(cd /path/to && ls -tp | grep -v '/$' | tail -n +6 | xargs -I {} rm -- {})
The same applies analogously to the commands below.

The above is inefficient, because xargs has to invoke rm once for each filename.
Your platform's xargs may allow you to solve this problem:

If you have GNU xargs, use -d '\n', which makes xargs consider each input line a separate argument, yet passes as many arguments as will fit on a command line at once:

ls -tp | grep -v '/$' | tail -n +6 | xargs -d '\n' -r rm --

-r (--no-run-if-empty) ensures that rm is not invoked if there's no input.

If you have BSD xargs (including on macOS), you can use -0 to handle NUL-separated input, after first translating newlines to NUL (0x0) chars., which also passes (typically) all filenames at once (will also work with GNU xargs):

ls -tp | grep -v '/$' | tail -n +6 | tr '\n' '\0' | xargs -0 rm --

Explanation:

  • ls -tp prints the names of filesystem items sorted by how recently they were modified , in descending order (most recently modified items first) (-t), with directories printed with a trailing / to mark them as such (-p).

    • Note: It is the fact that ls -tp always outputs file / directory names only, not full paths, that necessitates the subshell approach mentioned above for targeting a directory other than the current one ((cd /path/to && ls -tp ...)).
  • grep -v '/$' then weeds out directories from the resulting listing, by omitting (-v) lines that have a trailing / (/$).

    • Caveat: Since a symlink that points to a directory is technically not itself a directory, such symlinks will not be excluded.
  • tail -n +6 skips the first 5 entries in the listing, in effect returning all but the 5 most recently modified files, if any.
    Note that in order to exclude N files, N+1 must be passed to tail -n +.

  • xargs -I {} rm -- {} (and its variations) then invokes on rm on all these files; if there are no matches at all, xargs won't do anything.

    • xargs -I {} rm -- {} defines placeholder {} that represents each input line as a whole, so rm is then invoked once for each input line, but with filenames with embedded spaces handled correctly.
    • -- in all cases ensures that any filenames that happen to start with - aren't mistaken for options by rm.

A variation on the original problem, in case the matching files need to be processed individually or collected in a shell array:

# One by one, in a shell loop (POSIX-compliant):
ls -tp | grep -v '/$' | tail -n +6 | while IFS= read -r f; do echo "$f"; done

# One by one, but using a Bash process substitution (<(...), 
# so that the variables inside the `while` loop remain in scope:
while IFS= read -r f; do echo "$f"; done < <(ls -tp | grep -v '/$' | tail -n +6)

# Collecting the matches in a Bash *array*:
IFS=$'\n' read -d '' -ra files  < <(ls -tp | grep -v '/$' | tail -n +6)
printf '%s\n' "${files[@]}" # print array elements

How to convert Varchar to Double in sql?

This might be more desirable, that is use float instead

SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC

Using sessions & session variables in a PHP Login Script

$session_start();

extract($_POST);         
//extract data from submit post 

if(isset($submit))  
  {    
    if($user=="user" && $pass=="pass")    
      {     
        $_SESSION['user']= $user;       
        //if correct password and name store in session 
    } else {
        echo "Invalid user and password";
        header("Locatin:form.php")
    }
if(isset($_SESSION['user']))     
  {
  }

Is there a link to the "latest" jQuery library on Google APIs?

What about this one?

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

I think this is always the latest version - Correct me, if I'm wrong.

Use IntelliJ to generate class diagram

Try Ctrl+Alt+U

Also check if the UML plugin is activated (settings -> plugin, settings can be opened by Ctrl+Alt+S

How do I find out what version of WordPress is running?

Open the blog, Check source once the blog is open. It should have a meta tag like:

<meta name="generator" content="WordPress 2.8.4" />

Uninstall Django completely

If installed Django using python setup.py install

python -c "import sys; sys.path = sys.path[1:]; import django; print(django.__path__)"

find the directory you need to remove, delete it

What is LDAP used for?

LDAP is the Lightweight Directory Access Protocol. Basically, it's a protocol used to access data from a database (or other source) and it's mostly suited for large numbers of queries and minimal updates (the sort of thing you would use for login information for example).

LDAP doesn't itself provide a database, just a means to query data in the database.

How often should Oracle database statistics be run?

When I was managing a large multi-user planning system backed by Oracle, our DBA had a weekly job that gathered statistics. Also, when we rolled out a significant change that could affect or be affected by statistics, we would force the job to run out of cycle to get things caught up.

What's a simple way to get a text input popup dialog box on an iPhone

Try this Swift code in a UIViewController -

func doAlertControllerDemo() {

    var inputTextField: UITextField?;

    let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your passwod.", preferredStyle: UIAlertControllerStyle.Alert);

    passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        // Now do whatever you want with inputTextField (remember to unwrap the optional)

        let entryStr : String = (inputTextField?.text)! ;

        print("BOOM! I received '\(entryStr)'");

        self.doAlertViewDemo(); //do again!
    }));


    passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        print("done");
    }));


    passwordPrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Password"
        textField.secureTextEntry = false       /* true here for pswd entry */
        inputTextField = textField
    });


    self.presentViewController(passwordPrompt, animated: true, completion: nil);


    return;
}

What does "Table does not support optimize, doing recreate + analyze instead" mean?

The better option is create a new table copy the rows to the destination table, drop the actual table and rename the newly created table . This method is good for small tables,

ORA-00932: inconsistent datatypes: expected - got CLOB

I found that selecting a clob column in CTE caused this explosion. ie

with cte as (
    select
        mytable1.myIntCol,
        mytable2.myClobCol
    from mytable1
    join mytable2 on ...
)
select myIntCol, myClobCol
from cte
where ...

presumably because oracle can't handle a clob in a temporary table.

Because my values were longer than 4K, I couldn't use to_char().
My work around was to select it from the final select, ie

with cte as (
    select
        mytable1.myIntCol
    from mytable1
)
select myIntCol, myClobCol
from cte
join mytable2 on ...
where ...

Too bad if this causes a performance problem.

How do I make a simple crawler in PHP?

Hobodave you were very close. The only thing I have changed is within the if statement that checks to see if the href attribute of the found anchor tag begins with 'http'. Instead of simply adding the $url variable which would contain the page that was passed in you must first strip it down to the host which can be done using the parse_url php function.

<?php
function crawl_page($url, $depth = 5)
{
  static $seen = array();
  if (isset($seen[$url]) || $depth === 0) {
    return;
  }

  $seen[$url] = true;

  $dom = new DOMDocument('1.0');
  @$dom->loadHTMLFile($url);

  $anchors = $dom->getElementsByTagName('a');
  foreach ($anchors as $element) {
    $href = $element->getAttribute('href');
    if (0 !== strpos($href, 'http')) {
       /* this is where I changed hobodave's code */
        $host = "http://".parse_url($url,PHP_URL_HOST);
        $href = $host. '/' . ltrim($href, '/');
    }
    crawl_page($href, $depth - 1);
  }

  echo "New Page:<br /> ";
  echo "URL:",$url,PHP_EOL,"<br />","CONTENT:",PHP_EOL,$dom->saveHTML(),PHP_EOL,PHP_EOL,"  <br /><br />";
}

crawl_page("http://hobodave.com/", 5);
?>

Difference between /res and /assets directories

Ted Hopp answered this quite nicely. I have been using res/raw for my opengl texture and shader files. I was thinking about moving them to an assets directory to provide a hierarchical organization.

This thread convinced me not to. First, because I like the use of a unique resource id. Second because it's very simple to use InputStream/openRawResource or BitmapFactory to read in the file. Third because it's very useful to be able to use in a portable library.

How do I calculate power-of in C#?

You are looking for the static method Math.Pow().

How to make the window full screen with Javascript (stretching all over the screen)

This function work like a charm

function toggle_full_screen()
{
    if ((document.fullScreenElement && document.fullScreenElement !== null) || (!document.mozFullScreen && !document.webkitIsFullScreen))
    {
        if (document.documentElement.requestFullScreen){
            document.documentElement.requestFullScreen();
        }
        else if (document.documentElement.mozRequestFullScreen){ /* Firefox */
            document.documentElement.mozRequestFullScreen();
        }
        else if (document.documentElement.webkitRequestFullScreen){   /* Chrome, Safari & Opera */
            document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
        }
        else if (document.msRequestFullscreen){ /* IE/Edge */
            document.documentElement.msRequestFullscreen();
        }
    }
    else
    {
        if (document.cancelFullScreen){
            document.cancelFullScreen();
        }
        else if (document.mozCancelFullScreen){ /* Firefox */
            document.mozCancelFullScreen();
        }
        else if (document.webkitCancelFullScreen){   /* Chrome, Safari and Opera */
            document.webkitCancelFullScreen();
        }
        else if (document.msExitFullscreen){ /* IE/Edge */
            document.msExitFullscreen();
        }
    }
}

To use it just call:

toggle_full_screen();

How to build and run Maven projects after importing into Eclipse IDE

Dependencies can be updated by using "Maven --> Update Project.." in Eclipse using m2e plugin, after pom.xml file modification. Maven Project Update based on changes on pom.xml

Apply CSS styles to an element depending on its child elements

Basically, no. The following would be what you were after in theory:

div.a < div { border: solid 3px red; }

Unfortunately it doesn't exist.

There are a few write-ups along the lines of "why the hell not". A well fleshed out one by Shaun Inman is pretty good:

http://www.shauninman.com/archive/2008/05/05/css_qualified_selectors

install / uninstall APKs programmatically (PackageManager vs Intents)

If you are passing package name as parameter to any of your user defined function then use the below code :

    Intent intent=new Intent(Intent.ACTION_DELETE);
    intent.setData(Uri.parse("package:"+packageName));
    startActivity(intent);

Trying Gradle build - "Task 'build' not found in root project"

Check your file: settings.gradle for presence lines with included subprojects (for example: include chapter1-bookstore )

Avoid web.config inheritance in child web application using inheritInChildApplications

It needs to go directly under the root <configuration> node and you need to set a path like this:

<?xml version="1.0"?>
<configuration>
    <location path="." inheritInChildApplications="false"> 
        <!-- Stuff that shouldn't be inherited goes in here -->
    </location>
</configuration>

A better way to handle configuration inheritance is to use a <clear/> in the child config wherever you don't want to inherit. So if you didn't want to inherit the parent config's connection strings you would do something like this:

<?xml version="1.0"?>
<configuration>
    <connectionStrings>
        <clear/>
        <!-- Child config's connection strings -->
    </connectionStrings>
</configuration>

How do I get the command-line for an Eclipse run configuration?

I found a solution on Stack Overflow for Java program run configurations which also works for JUnit run configurations.

You can get the full command executed by your configuration on the Debug tab, or more specifically the Debug view.

  1. Run your application
  2. Go to your Debug perspective
  3. There should be an entry in there (in the Debug View) for the app you've just executed
  4. Right-click the node which references java.exe or javaw.exe and select Properties In the dialog that pops up you'll see the Command Line which includes all jars, parameters, etc

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

Another possible solution depending on your situation.

If you know that libpthread_rt.so.1 is the same as libpthread_rt.so then you can create a symlink by:

ln -s /lib/libpthread_rt.so /lib/libpthread_rt.so.1

Then ls -l /lib should now show the symlink and what it points to.

JavaScript dictionary with names

Another approach would be to have an array of objects, with each individual object holding the properties of a column. This slightly changes the structure of "myMappings", but makes it easy to work with:

var myMappings = [
    { title: "Name", width: "10%" },
    { title: "Phone", width: "10%" },
    { title: "Address", width: "50%" },
    { title: "Zip", width: "10%" },
    { title: "Comments", width: "20%" }
];

Then you could easily iterate through all your "columns" with a for loop:

for (var i = 0; i < myMappings.length; i += 1) {
    // myMappings[i].title ...
    // myMappings[i].width ...
}

Making a cURL call in C#

Or in restSharp:

var client = new RestClient("https://example.com/?urlparam=true");
var request = new RestRequest(Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("header1", "headerval");
request.AddParameter("application/x-www-form-urlencoded", "bodykey=bodyval", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

How do I make a branch point at a specific commit?

If you are currently not on branch master, that's super easy:

git branch -f master 1258f0d0aae

This does exactly what you want: It points master at the given commit, and does nothing else.

If you are currently on master, you need to get into detached head state first. I'd recommend the following two command sequence:

git checkout 1258f0d0aae    #detach from master
git branch -f master HEAD   #exactly as above

#optionally reattach to master
git checkout master

Be aware, though, that any explicit manipulation of where a branch points has the potential to leave behind commits that are no longer reachable by any branches, and thus become object to garbage collection. So, think before you type git branch -f!


This method is better than the git reset --hard approach, as it does not destroy anything in the index or working directory.

What is declarative programming?

As far as I can tell, it started being used to describe programming systems like Prolog, because prolog is (supposedly) about declaring things in an abstract way.

It increasingly means very little, as it has the definition given by the users above. It should be clear that there is a gulf between the declarative programming of Haskell, as against the declarative programming of HTML.

How do I generate a stream from a string?

Modernized and slightly modified version of the extension methods for ToStream:

public static Stream ToStream(this string value) => ToStream(value, Encoding.UTF8);

public static Stream ToStream(this string value, Encoding encoding) 
                          => new MemoryStream(encoding.GetBytes(value ?? string.Empty));

Modification as suggested in @Palec's comment of @Shaun Bowe answer.

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

Abstract methods in Java

The error message tells the exact reason: "abstract methods cannot have a body".

They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.

Example:

 public abstract class AbstractGreeter {
   public abstract String getHelloMessage();

   public void sayHello() {
     System.out.println(getHelloMessage());
   }
 }

 public class FrenchGreeter extends AbstractGreeter{

   // we must implement the abstract method
   @Override
   public String getHelloMessage() {
     return "bonjour";
   }
 }

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

Its already answered above. I will summarise the steps to check above.

run git remote -v in project dir. If the output shows remote url starting with https://abc then you may need username password everytime.

So to change the remote url run git remote set-url origin {ssh remote url address starts with mostly [email protected]:}.

Now run git remote -v to verify the changed remote url.

Refer : https://help.github.com/articles/changing-a-remote-s-url/

Fragment transaction animation: slide in and slide out

I have same issue, i used simple solution

1)create sliding_out_right.xml in anim folder

  <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android">
        <translate android:fromXDelta="0" android:toXDelta="-50%p"
            android:duration="@android:integer/config_mediumAnimTime"/>
        <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
            android:duration="@android:integer/config_mediumAnimTime" />
    </set>

2) create sliding_in_left.xml in anim folder

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="50%p" android:toXDelta="0"
        android:duration="@android:integer/config_mediumAnimTime"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>

3) simply using fragment transaction setCustomeAnimations() with two custom xml and two default xml for animation as follows :-

 fragmentTransaction.setCustomAnimations(R.anim.sliding_in_left, R.anim.sliding_out_right, android.R.anim.slide_in_left, android.R.anim.slide_out_right );

jQuery: selecting each td in a tr

You can simply do the following inside your TR loop:

$(this).find('td').each (function() {
  // do your cool stuff
});                          

PHP PDO: charset, set names?

I think you need an additionally query because the charset option in the DSN is actually ignored. see link posted in the comment of the other answer.

Looking at how Drupal 7 is doing it in http://api.drupal.org/api/drupal/includes--database--mysql--database.inc/function/DatabaseConnection_mysql%3A%3A__construct/7:

// Force MySQL to use the UTF-8 character set. Also set the collation, if a
// certain one has been set; otherwise, MySQL defaults to 'utf8_general_ci'
// for UTF-8.
if (!empty($connection_options['collation'])) {
  $this->exec('SET NAMES utf8 COLLATE ' . $connection_options['collation']);
}
else {
  $this->exec('SET NAMES utf8');
}

How to check if a string array contains one string in JavaScript?

var stringArray = ["String1", "String2", "String3"];

return (stringArray.indexOf(searchStr) > -1)

Change image source in code behind - Wpf

The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.

You simply want to pass the actual path to the UriSource:

logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");

CodeIgniter htaccess and URL rewrite issues

<IfModule mod_rewrite.c>
   RewriteEngine On
   RewriteBase /dmizone_bkp
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond $1 !^(index\.php|images|robots\.txt|css|docs|js|system)
   RewriteRule ^(.*)$ /dmizone_bkp/index.php?/$1 [L]
</IfModule> 

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Set value of textbox using JQuery

1) you are calling it wrong way try:

$(input[name="searchBar"]).val('hi')

2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event

$(document).ready(function() {
  $(input[name="searchBar"]).val('hi');
});

How to run JUnit tests with Gradle?

testCompile is deprecated. Gradle 7 compatible:

dependencies {
...
   testImplementation 'junit:junit:4.13'
}

and if you use the default folder structure (src/test/java/...) the test section is simply:

test {
    useJUnit()
}

Finally:

gradlew clean test

Alos see: https://docs.gradle.org/current/userguide/java_testing.html

jQuery select element in parent window

I looked for a solution to this problem, and came across the present page. I implemented the above solution:

$("#testdiv",opener.document) //doesn't work

But it doesn't work. Maybe it did work in previous jQuery versions, but it doesn't seem to work now.

I found this working solution on another stackoverflow page: how to access parent window object using jquery?

From which I got this working solution:

window.opener.$("#testdiv") //This works.

Embed Youtube video inside an Android app

Pretty simple: Just put it inside a static method.

startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(linkYouTube)));

Eclipse CDT: no rule to make target all

Project -> Clean -> Clean all Projects and then Project -> Build Project worked for me (I did the un-checking generate make-file automatically and then rechecking it before doing this). This was for an AVR (micro-processor programming) project through the AVR CDT plugin in eclipse Juno though.

Android: upgrading DB version and adding new table

Handling database versions is very important part of application development. I assume that you already have class AppDbHelper extending SQLiteOpenHelper. When you extend it you will need to implement onCreate and onUpgrade method.

  1. When onCreate and onUpgrade methods called

    • onCreate called when app newly installed.
    • onUpgrade called when app updated.
  2. Organizing Database versions I manage versions in a class methods. Create implementation of interface Migration. E.g. For first version create MigrationV1 class, second version create MigrationV1ToV2 (these are my naming convention)


    public interface Migration {
        void run(SQLiteDatabase db);//create tables, alter tables
    }

Example migration:

public class MigrationV1ToV2 implements Migration{
      public void run(SQLiteDatabase db){
        //create new tables
        //alter existing tables(add column, add/remove constraint)
        //etc.
     }
   }
  1. Using Migration classes

onCreate: Since onCreate will be called when application freshly installed, we also need to execute all migrations(database version updates). So onCreate will looks like this:

public void onCreate(SQLiteDatabase db){
        Migration mV1=new MigrationV1();
       //put your first database schema in this class
        mV1.run(db);
        Migration mV1ToV2=new MigrationV1ToV2();
        mV1ToV2.run(db);
        //other migration if any
  }

onUpgrade: This method will be called when application is already installed and it is updated to new application version. If application contains any database changes then put all database changes in new Migration class and increment database version.

For example, lets say user has installed application which has database version 1, and now database version is updated to 2(all schema updates kept in MigrationV1ToV2). Now when application upgraded, we need to upgrade database by applying database schema changes in MigrationV1ToV2 like this:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < 2) {
        //means old version is 1
        Migration migration = new MigrationV1ToV2();
        migration.run(db);
    }
    if (oldVersion < 3) {
        //means old version is 2
    }
}

Note: All upgrades (mentioned in onUpgrade) in to database schema should be executed in onCreate

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:

select Detail.ReceiptDate AS 'DATE',
       SUM(TotalMailed),
       SUM(TotalReturnMail),
       SUM(TraceReturnedMail)

from
(

select SentDate AS 'ReceiptDate', 
       count('TotalMailed') AS TotalMailed, 
       0 as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate

UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       count(TotalReturnMail) as TotalReturnMail, 
       0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY  MDE.ReturnMailDate

UNION ALL

select MDE.ReturnMailDate AS 'ReceiptDate', 
       0 AS TotalMailed, 
       0 as TotalReturnMail, 
       count(TraceReturnedMail) as TraceReturnedMail

from MailDataExtract MDE
    inner join DTSharedData.dbo.ScanData SD 
        ON SD.ScanDataID = MDE.ReturnScanDataID
   where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate

) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1

I'm getting an error "invalid use of incomplete type 'class map'

Your first usage of Map is inside a function in the combat class. That happens before Map is defined, hence the error.

A forward declaration only says that a particular class will be defined later, so it's ok to reference it or have pointers to objects, etc. However a forward declaration does not say what members a class has, so as far as the compiler is concerned you can't use any of them until Map is fully declared.

The solution is to follow the C++ pattern of the class declaration in a .h file and the function bodies in a .cpp. That way all the declarations appear before the first definitions, and the compiler knows what it's working with.

What are best practices that you use when writing Objective-C and Cocoa?

Some of these have already been mentioned, but here's what I can think of off the top of my head:

  • Follow KVO naming rules. Even if you don't use KVO now, in my experience often times it's still beneficial in the future. And if you are using KVO or bindings, you need to know things are going work the way they are supposed to. This covers not just accessor methods and instance variables, but to-many relationships, validation, auto-notifying dependent keys, and so on.
  • Put private methods in a category. Not just the interface, but the implementation as well. It's good to have some distance conceptually between private and non-private methods. I include everything in my .m file.
  • Put background thread methods in a category. Same as above. I've found it's good to keep a clear conceptual barrier when you're thinking about what's on the main thread and what's not.
  • Use #pragma mark [section]. Usually I group by my own methods, each subclass's overrides, and any information or formal protocols. This makes it a lot easier to jump to exactly what I'm looking for. On the same topic, group similar methods (like a table view's delegate methods) together, don't just stick them anywhere.
  • Prefix private methods & ivars with _. I like the way it looks, and I'm less likely to use an ivar when I mean a property by accident.
  • Don't use mutator methods / properties in init & dealloc. I've never had anything bad happen because of it, but I can see the logic if you change the method to do something that depends on the state of your object.
  • Put IBOutlets in properties. I actually just read this one here, but I'm going to start doing it. Regardless of any memory benefits, it seems better stylistically (at least to me).
  • Avoid writing code you don't absolutely need. This really covers a lot of things, like making ivars when a #define will do, or caching an array instead of sorting it each time the data is needed. There's a lot I could say about this, but the bottom line is don't write code until you need it, or the profiler tells you to. It makes things a lot easier to maintain in the long run.
  • Finish what you start. Having a lot of half-finished, buggy code is the fastest way to kill a project dead. If you need a stub method that's fine, just indicate it by putting NSLog( @"stub" ) inside, or however you want to keep track of things.

git pull error "The requested URL returned error: 503 while accessing"

Every one please avoid modifying post buffer and advising it to others. It may help in some cases but it breaks others. If you have modified your post buffer for pushing your large project. Undo it using following command. git config --global --unset http.postBuffer git config --local --unset http.postBuffer

I modified my post buffer to fix one of the issues I had with git but it was the reason for my future problems with git.

Why powershell does not run Angular commands?

Remove ng.ps1 from the directory C:\Users\%username%\AppData\Roaming\npm\ then try clearing the npm cache at C:\Users\%username%\AppData\Roaming\npm-cache\

How to get the indices list of all NaN value in numpy array?

You can use np.where to match the boolean conditions corresponding to Nan values of the array and map each outcome to generate a list of tuples.

>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]

jQuery DataTable overflow and text-wrapping issues

The same problem and I solved putting the table between the code

<div class = "table-responsive"> </ div>

TensorFlow, "'module' object has no attribute 'placeholder'"

Solution: Do not use "tensorflow" as your filename.

Notice that you use tensorflow.py as your filename. And I guess you write code like:

import tensorflow as tf

Then you are actually importing the script file "tensorflow.py" that is under your current working directory, rather than the "real" tensorflow module from Google.

Here is the order in which a module will be searched when importing:

  1. The directory containing the input script (or the current directory when no file is specified).

  2. PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

  3. The installation-dependent default.

Deleting Elements in an Array if Element is a Certain value VBA

When creating the array, why not just skip over the 0s and save yourself the time of having to worry about them later? As mentioned above, arrays are not well-suited for deletion.

How to use Tomcat 8 in Eclipse?

I follow Jason's step, but not works.

And then I find the WTP Update site http://download.eclipse.org/webtools/updates/.

Help -> Install new software -> Add > WTP:http://download.eclipse.org/webtools/updates/ -> OK

Then Help -> Check for update, just works, I don't know whether Jason's affect this .

json and empty array

"location" : null // this is not really an array it's a null object
"location" : []   // this is an empty array

It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

"psql: could not connect to server: Connection refused" Error when connecting to remote database

See the port and make a port change in postgresql.conf. My installation of postgres 9.4 uses port 5431 or 5434 instead of 5432. If it say the port is in use so change the port. And check if you give password in psql installation so give the password in file and save it.

How to get CSS to select ID that begins with a string (not in Javascript)?

I noticed that there is another CSS selector that does the same thing . The syntax is as follows :

[id|="name_id"]

This will select all elements ID which begins with the word enclosed in double quotes.

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

How to open standard Google Map application from my application?

I have a sample app where I prepare the intent and just pass the CITY_NAME in the intent to the maps marker activity which eventually calculates longitude and latitude by Geocoder using CITY_NAME.

Below is the code snippet of starting the maps marker activity and the complete MapsMarkerActivity.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    } else if (id == R.id.action_refresh) {
        Log.d(APP_TAG, "onOptionsItemSelected Refresh selected");
        new MainActivityFragment.FetchWeatherTask().execute(CITY, FORECAS_DAYS);
        return true;
    } else if (id == R.id.action_map) {
        Log.d(APP_TAG, "onOptionsItemSelected Map selected");
        Intent intent = new Intent(this, MapsMarkerActivity.class);
        intent.putExtra("CITY_NAME", CITY);
        startActivity(intent);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public class MapsMarkerActivity extends AppCompatActivity
        implements OnMapReadyCallback {

    private String cityName = "";

    private double longitude;

    private double latitude;

    static final int numberOptions = 10;

    String [] optionArray = new String[numberOptions];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Retrieve the content view that renders the map.
        setContentView(R.layout.activity_map);
        // Get the SupportMapFragment and request notification
        // when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        // Test whether geocoder is present on platform
        if(Geocoder.isPresent()){
            cityName = getIntent().getStringExtra("CITY_NAME");
            geocodeLocation(cityName);
        } else {
            String noGoGeo = "FAILURE: No Geocoder on this platform.";
            Toast.makeText(this, noGoGeo, Toast.LENGTH_LONG).show();
            return;
        }
    }

    /**
     * Manipulates the map when it's available.
     * The API invokes this callback when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user receives a prompt to install
     * Play services inside the SupportMapFragment. The API invokes this method after the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        // Add a marker in Sydney, Australia,
        // and move the map's camera to the same location.
        LatLng sydney = new LatLng(latitude, longitude);
        // If cityName is not available then use
        // Default Location.
        String markerDisplay = "Default Location";
        if (cityName != null
                && cityName.length() > 0) {
            markerDisplay = "Marker in " + cityName;
        }
        googleMap.addMarker(new MarkerOptions().position(sydney)
                .title(markerDisplay));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    /**
     * Method to geocode location passed as string (e.g., "Pentagon"), which
     * places the corresponding latitude and longitude in the variables lat and lon.
     *
     * @param placeName
     */
    private void geocodeLocation(String placeName){

        // Following adapted from Conder and Darcey, pp.321 ff.
        Geocoder gcoder = new Geocoder(this);

        // Note that the Geocoder uses synchronous network access, so in a serious application
        // it would be best to put it on a background thread to prevent blocking the main UI if network
        // access is slow. Here we are just giving an example of how to use it so, for simplicity, we
        // don't put it on a separate thread.  See the class RouteMapper in this package for an example
        // of making a network access on a background thread. Geocoding is implemented by a backend
        // that is not part of the core Android framework, so we use the static method
        // Geocoder.isPresent() to test for presence of the required backend on the given platform.

        try{
            List<Address> results = null;
            if(Geocoder.isPresent()){
                results = gcoder.getFromLocationName(placeName, numberOptions);
            } else {
                Log.i(MainActivity.APP_TAG, "No Geocoder found");
                return;
            }
            Iterator<Address> locations = results.iterator();
            String raw = "\nRaw String:\n";
            String country;
            int opCount = 0;
            while(locations.hasNext()){
                Address location = locations.next();
                if(opCount == 0 && location != null){
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
                country = location.getCountryName();
                if(country == null) {
                    country = "";
                } else {
                    country =  ", " + country;
                }
                raw += location+"\n";
                optionArray[opCount] = location.getAddressLine(0)+", "
                        +location.getAddressLine(1)+country+"\n";
                opCount ++;
            }
            // Log the returned data
            Log.d(MainActivity.APP_TAG, raw);
            Log.d(MainActivity.APP_TAG, "\nOptions:\n");
            for(int i=0; i<opCount; i++){
                Log.i(MainActivity.APP_TAG, "("+(i+1)+") "+optionArray[i]);
            }
            Log.d(MainActivity.APP_TAG, "latitude=" + latitude + ";longitude=" + longitude);
        } catch (Exception e){
            Log.d(MainActivity.APP_TAG, "I/O Failure; do you have a network connection?",e);
        }
    }
}

Links expire so i have pasted complete code above but just in case if you would like to see complete code then its available at : https://github.com/gosaliajigar/CSC519/tree/master/CSC519_HW4_89753

Enable binary mode while restoring a Database from an SQL dump

Under linux Ungzip your file using gunzip Edit your unzip sql file using

vi unzipsqlfile.sql

Remove the first binary line with esc dd go to the bottom of the file with esc shift g remove the last binary line with dd save the file esc x: Then reimport to mysql with :

mysql -u username -p new_database < unzipsqlfile.sql

I performed that with a 20go sql file from a jetbackup cpanel mysql backup. Be patient to wait vi doing the job for big files

Dependency injection with Jersey 2.0

For me it works without the AbstractBinder if I include the following dependencies in my web application (running on Tomcat 8.5, Jersey 2.27):

<dependency>
    <groupId>javax.ws.rs</groupId>
    <artifactId>javax.ws.rs-api</artifactId>
    <version>2.1</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>${jersey-version}</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.ext.cdi</groupId>
    <artifactId>jersey-cdi1x</artifactId>
    <version>${jersey-version}</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.inject</groupId>
    <artifactId>jersey-hk2</artifactId>
    <version>${jersey-version}</version>
</dependency>

It works with CDI 1.2 / CDI 2.0 for me (using Weld 2 / 3 respectively).

PHP combine two associative arrays into one array

Check out array_merge().

$array3 = array_merge($array1, $array2);

Pick a random value from an enum?

Letter lettre = Letter.values()[(int)(Math.random()*Letter.values().length)];

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

Project -> ManageNugetPackages -> Browse -> Search "Microsoft.EntityFrameworkCore.SqlServer" and install or update.

How to use Python's pip to download and keep the zipped files for a package?

installing python packages offline

For windows users:

To download into a file open your cmd and folow this:

cd <*the file-path where you want to save it*>

pip download <*package name*>

the package and the dependencies will be downloaded in the current working directory.

To install from the current working directory:

set your folder where you downloaded as the cwd then follow these:

pip install <*the package name which is downloded as .whl*> --no-index --find-links <*the file locaation where the files are downloaded*>

this will search for dependencies in that location.

How to push files to an emulator instance using Android Studio

One easy way is to drag and drop. It will copy files to /sdcard/Download. You can copy whole folders or multiple files. Make sure that "Enable Clipboard Sharing" is enabled. (under ...->Settings)

enter image description here

nano error: Error opening terminal: xterm-256color

I, too, have this problem on an older Mac that I upgraded to Lion.

Before reading the terminfo tip, I was able to get vi and less working by doing "export TERM=xterm".

After reading the tip, I grabbed /usr/share/terminfo from a newer Mac that has fresh install of Lion and does not exhibit this problem.

Now, even though echo $TERM still yields xterm-256color, vi and less now work fine.

How to correctly get image from 'Resources' folder in NetBeans

I have a slightly different approach that might be useful/more beneficial to some.

Under your main project folder, create a resource folder. Your folder structure should look something like this.

  • Project Folder
    • build
    • dist
    • lib
    • nbproject
    • resources
    • src

Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.

Under categories on the left side, select Sources.

In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.

enter image description here

You should now be able to pull resources using this line or similar approach:

MyClass.class.getResource("/main.jpg");

If you were to create a package called Images under the resources folder, you can retrieve the resource like this:

MyClass.class.getResource("/Images/main.jpg");

Swift Open Link in Safari

In Swift 2.0:

UIApplication.sharedApplication().openURL(NSURL(string: "http://stackoverflow.com")!)

Laravel 5 How to switch from Production mode

Laravel 5 gets its enviroment related variables from the .env file located in the root of your project. You just need to set APP_ENV to whatever you want, for example:

APP_ENV=development

This is used to identify the current enviroment. If you want to display errors, you'll need to enable debug mode in the same file:

APP_DEBUG=true

The role of the .env file is to allow you to have different settings depending on which machine you are running your application. So on your production server, the .env file settings would be different from your local development enviroment.

Storing sex (gender) in database

I'd call the column "gender".

Data Type   Bytes Taken          Number/Range of Values
------------------------------------------------
TinyINT     1                    255 (zero to 255)
INT         4            -       2,147,483,648 to 2,147,483,647
BIT         1 (2 if 9+ columns)  2 (0 and 1)
CHAR(1)     1                    26 if case insensitive, 52 otherwise

The BIT data type can be ruled out because it only supports two possible genders which is inadequate. While INT supports more than two options, it takes 4 bytes -- performance will be better with a smaller/more narrow data type.

CHAR(1) has the edge over TinyINT - both take the same number of bytes, but CHAR provides a more narrow number of values. Using CHAR(1) would make using "m", "f",etc natural keys, vs the use of numeric data which are referred to as surrogate/artificial keys. CHAR(1) is also supported on any database, should there be a need to port.

Conclusion

I would use Option 2: CHAR(1).

Addendum

An index on the gender column likely would not help because there's no value in an index on a low cardinality column. Meaning, there's not enough variety in the values for the index to provide any value.

Newline in string attribute

<TextBlock>
    Stuff on line1 <LineBreak/>
    Stuff on line2
</TextBlock>

not that it's important to know but what you specify between the TextBlock tags is called inline content and goes into the TextBlock.Inlines property which is a InlineCollection and contains items of type Inline. Subclasses of Inline are Run and LineBreak, among others. see TextBlock.Inlines

Reading a key from the Web.Config using ConfigurationManager

  var url = ConfigurationManager.AppSettings["ServiceProviderUrl"];

Detect click event inside iframe

I know this is old but the ID's don't match in your code one is choose_pic and one is choose_pics:

<input type=button id=choose_pics value='Choose'>

$("#filecontainer").contents().find("#choose_pic").click(function(){
    //do something      
}); 

Authenticating against Active Directory with Java on Linux

I recommend you to look at the adbroker package of the oVirt project. It uses Spring-Ldap and the Krb5 JAAS Login module (with GSSAPI) in order to authenticate using Kerberos against Ldap servers (Active-Directory, ipa, rhds, Tivoli-DS). Look for the code at engine\backend\manager\modules\bll\src\main\java\org\ovirt\engine\core\bll\adbroker

You can use git to clone the repository or browse using the gerrit link

iterating through json object javascript

Here is my recursive approach:

function visit(object) {
    if (isIterable(object)) {
        forEachIn(object, function (accessor, child) {
            visit(child);
        });
    }
    else {
        var value = object;
        console.log(value);
    }
}

function forEachIn(iterable, functionRef) {
    for (var accessor in iterable) {
        functionRef(accessor, iterable[accessor]);
    }
}

function isIterable(element) {
    return isArray(element) || isObject(element);
}

function isArray(element) {
    return element.constructor == Array;
}

function isObject(element) {
    return element.constructor == Object;
}

Virtualbox shared folder permissions

Add yourself to the vboxsf group within the guest VM.

Solution 1

Run sudo adduser $USER vboxsf from terminal.
(On Suse it's sudo usermod --append --groups vboxsf $USER)

To take effect you should log out and then log in, or you may need to reboot.

Solution 2

Edit the file /etc/group (you will need root privileges). Look for the line vboxsf:x:999 and add at the end :yourusername -- use this solution if you don't have sudo.

To take effect you should log out and then log in, or you may need to reboot.

popup form using html/javascript/css

There are plenty available. Try using Modal windows of Jquery or DHTML would do good. Put the content in your div or Change your content in div dynamically and show it to the user. It won't be a popup but a modal window.
Jquery's Thickbox would clear your problem.

How can I use a for each loop on an array?

what about this simple inArray function:

Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
    If element = stringToBeFound Then
        isInArray = True
        Exit Function
    End If
Next element
End Function

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The error tells you that there is an error but you don´t catch it. This is how you can catch it:

getAllPosts().then(response => {
    console.log(response);
}).catch(e => {
    console.log(e);
});

You can also just put a console.log(reponse) at the beginning of your API callback function, there is definitely an error message from the Graph API in it.

More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

Or with async/await:

//some async function
try {
    let response = await getAllPosts();
} catch(e) {
    console.log(e);
}

Get only specific attributes with from Laravel Collection

this is a follow up on the patricus [answer][1] above but for nested arrays:

$topLevelFields =  ['id','status'];
$userFields = ['first_name','last_name','email','phone_number','op_city_id'];

return $onlineShoppers->map(function ($user) { 
    return collect($user)->only($topLevelFields)
                             ->merge(collect($user['user'])->only($userFields))->all();  
    })->all();

Open button in new window?

You can acheive this using window.open() method, passing _blank as one of the parameter. You can refer the below links which has more information on this.

http://www.w3schools.com/jsref/met_win_open.asp

http://msdn.microsoft.com/en-us/library/ms536651(v=vs.85).aspx

Hope this will help you.

How can I declare and use Boolean variables in a shell script?

You can use shFlags.

It gives you the option to define: DEFINE_bool

Example:

DEFINE_bool(big_menu, true, "Include 'advanced' options in the menu listing");

From the command line you can define:

sh script.sh --bigmenu
sh script.sh --nobigmenu # False

Superscript in markdown (Github flavored)?

Comments about previous answers

The universal solution is using the HTML tag <sup>, as suggested in the main answer.
However, the idea behind Markdown is precisely to avoid the use of such tags:
The document should look nice as plain text, not only when rendered.

Another answer proposes using Unicode characters, which makes the document look nice as a plain text document but could reduce compatibility.

Finally, I would like to remember the simplest solution for some documents: the character ^.
Some Markdown implementation (e.g. MacDown in macOS) interprets the caret as an instruction for superscript.

Ex.
Sin^2 + Cos^2 = 1
Clearly, Stack Overflow does not interpret the caret as a superscript instruction. However, the text is comprehensible, and this is what really matters when using Markdown.

Javascript .querySelector find <div> by innerTEXT

If you don't want to use jquery or something like that then you can try this:

function findByText(rootElement, text){
    var filter = {
        acceptNode: function(node){
            // look for nodes that are text_nodes and include the following string.
            if(node.nodeType === document.TEXT_NODE && node.nodeValue.includes(text)){
                 return NodeFilter.FILTER_ACCEPT;
            }
            return NodeFilter.FILTER_REJECT;
        }
    }
    var nodes = [];
    var walker = document.createTreeWalker(rootElement, NodeFilter.SHOW_TEXT, filter, false);
    while(walker.nextNode()){
       //give me the element containing the node
       nodes.push(walker.currentNode.parentNode);
    }
    return nodes;
}

//call it like
var nodes = findByText(document.body,'SomeText');
//then do what you will with nodes[];
for(var i = 0; i < nodes.length; i++){ 
    //do something with nodes[i]
} 

Once you have the nodes in an array that contain the text you can do something with them. Like alert each one or print to console. One caveat is that this may not necessarily grab divs per se, this will grab the parent of the textnode that has the text you are looking for.

How can I drop a table if there is a foreign key constraint in SQL Server?

    --Find and drop the constraints

    DECLARE @dynamicSQL VARCHAR(MAX)
    DECLARE MY_CURSOR CURSOR 

    LOCAL STATIC READ_ONLY FORWARD_ONLY 
    FOR
        SELECT dynamicSQL = 'ALTER TABLE [' +  OBJECT_SCHEMA_NAME(parent_object_id) + '].[' + OBJECT_NAME(parent_object_id) + '] DROP CONSTRAINT [' + name + ']'
        FROM sys.foreign_keys
        WHERE object_name(referenced_object_id)  in ('table1', 'table2', 'table3')
    OPEN MY_CURSOR
    FETCH NEXT FROM MY_CURSOR INTO @dynamicSQL
    WHILE @@FETCH_STATUS = 0
    BEGIN

        PRINT @dynamicSQL
        EXEC (@dynamicSQL)

        FETCH NEXT FROM MY_CURSOR INTO @dynamicSQL
    END
    CLOSE MY_CURSOR
    DEALLOCATE MY_CURSOR


    -- Drop tables
    DROP 'table1'
    DROP 'table2'
    DROP 'table3'

Get counts of all tables in a schema

Get counts of all tables in a schema and order by desc

select 'with tmp(table_name, row_number) as (' from dual 
union all 
select 'select '''||table_name||''',count(*) from '||table_name||' union  ' from USER_TABLES 
union all
select 'select '''',0 from dual) select table_name,row_number from tmp order by row_number desc ;' from dual;

Copy the entire result and execute

How can I list (ls) the 5 last modified files in a directory?

ls -t list files by creation time not last modified time. Use ls -ltc if you want to list files by last modified time from last to first(top to bottom). Thus to list the last n: ls -ltc | head ${n}

How do I resolve a HTTP 414 "Request URI too long" error?

An excerpt from the RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1:

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

  • Annotation of existing resources;
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
  • Providing a block of data, such as the result of submitting a form, to a data-handling process;
  • Extending a database through an append operation.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

I tried many solutions but didn't work for me. The below solution works for me.

locate the sdkmanager file in android SDK.

In my case : ~/Android/Sdk/tools/bin

go to that path : cd ~/Android/Sdk/tools/bin

Accept licenses manually : ./sdkmanager --licenses Enter Yes or y

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

It says "POST not supported", so the request is not calling your servlet. If I were you, I will issue a GET (e.g. access using a browser) to the exact URL you are issuing your POST request, and see what you get. I bet you'll see something unexpected.

How to call javascript from a href?

The proper way to invoke javascript code when clicking a link would be to add an onclick handler:

<a href="#" onclick="myFunction()">LinkText</a>

Although an even "more proper" way would be to get it out of the html all together and add the handler with another javascript when the dom is loaded.

How to get a single value from FormGroup

You can get value like this

this.form.controls['your form control name'].value

How to make button look like a link?

The code of the accepted answer works for most cases, but to get a button that really behaves like a link you need a bit more code. It is especially tricky to get the styling of focused buttons right on Firefox (Mozilla).

The following CSS ensures that anchors and buttons have the same CSS properties and behave the same on all common browsers:

button {
  align-items: normal;
  background-color: rgba(0,0,0,0);
  border-color: rgb(0, 0, 238);
  border-style: none;
  box-sizing: content-box;
  color: rgb(0, 0, 238); 
  cursor: pointer;
  display: inline;
  font: inherit;
  height: auto;
  padding: 0;
  perspective-origin: 0 0;
  text-align: start;
  text-decoration: underline;
  transform-origin: 0 0;
  width: auto;
  -moz-appearance: none;
  -webkit-logical-height: 1em; /* Chrome ignores auto, so we have to use this hack to set the correct height  */
  -webkit-logical-width: auto; /* Chrome ignores auto, but here for completeness */
}

/* Mozilla uses a pseudo-element to show focus on buttons, */
/* but anchors are highlighted via the focus pseudo-class. */

@supports (-moz-appearance:none) { /* Mozilla-only */
  button::-moz-focus-inner { /* reset any predefined properties */ 
    border: none;
    padding: 0;
  }
  button:focus { /* add outline to focus pseudo-class */
    outline-style: dotted;
    outline-width: 1px;
  }
}

The example above only modifies button elements to improve readability, but it can easily be extended to modify input[type="button"], input[type="submit"] and input[type="reset"] elements as well. You could also use a class, if you want to make only certain buttons look like anchors.

See this JSFiddle for a live-demo.

Please also note that this applies the default anchor-styling to buttons (e.g. blue text-color). So if you want to change the text-color or anything else of anchors & buttons, you should do this after the CSS above.


The original code (see snippet) in this answer was completely different and incomplete.

_x000D_
_x000D_
/* Obsolete code! Please use the code of the updated answer. */_x000D_
_x000D_
input[type="button"], input[type="button"]:focus, input[type="button"]:active,  _x000D_
button, button:focus, button:active {_x000D_
 /* Remove all decorations to look like normal text */_x000D_
 background: none;_x000D_
 border: none;_x000D_
 display: inline;_x000D_
 font: inherit;_x000D_
 margin: 0;_x000D_
 padding: 0;_x000D_
 outline: none;_x000D_
 outline-offset: 0;_x000D_
 /* Additional styles to look like a link */_x000D_
 color: blue;_x000D_
 cursor: pointer;_x000D_
 text-decoration: underline;_x000D_
}_x000D_
/* Remove extra space inside buttons in Firefox */_x000D_
input[type="button"]::-moz-focus-inner,_x000D_
button::-moz-focus-inner {_x000D_
    border: none;_x000D_
    padding: 0;_x000D_
}
_x000D_
_x000D_
_x000D_

Procedure expects parameter which was not supplied

I had a problem where I would get the error when I supplied 0 to an integer param. And found that:

cmd.Parameters.AddWithValue("@Status", 0);

works, but this does not:

cmd.Parameters.Add(new SqlParameter("@Status", 0));

Finding first and last index of some value in a list in Python

This method can be more optimized than above

def rindex(iterable, value):
    try:
        return len(iterable) - next(i for i, val in enumerate(reversed(iterable)) if val == value) - 1
    except StopIteration:
        raise ValueError