Programs & Examples On #Wm syscommand

How do I paste multi-line bash codes into terminal and run it all at once?

To prevent a long line of commands in a text file, I keep my copy-pase snippets like this:

echo a;\
echo b;\
echo c

What is the difference between window, screen, and document in Javascript?

The window is the actual global object.

The screen is the screen, it contains properties about the user's display.

The document is where the DOM is.

How do you do Impersonation in .NET?

Here is some good overview of .NET impersonation concepts.

Basically you will be leveraging these classes that are out of the box in the .NET framework:

The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.

SQL GROUP BY CASE statement with aggregate function

I think the answer is pretty simple (unless I'm missing something?)

SELECT    
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END AS some_product
FROM some_table
GROUP BY
CASE
    WHEN col1 > col2 THEN SUM(col3*col4)
    ELSE 0
END

You can put the CASE STATEMENT in the GROUP BY verbatim (minus the alias column name)

How to read a string one letter at a time in python

Why not just iterate through the string?

a_string="abcd"
for letter in a_string:
    print letter

returns

a
b
c
d

So, in pseudo-ish code, I would do this:

user_string = raw_input()
list_of_output = []
for letter in user_string:
   list_of_output.append(morse_code_ify(letter))

output_string = "".join(list_of_output)

Note: the morse_code_ify function is pseudo-code.

You definitely want to make a list of the characters you want to output rather than just concatenating on them on the end of some string. As stated above, it's O(n^2): bad. Just append them onto a list, and then use "".join(the_list).

As a side note: why are you removing the spaces? Why not just have morse_code_ify(" ") return a "\n"?

How to embed a YouTube channel into a webpage

In order to embed your channel, all you need to do is copy then paste the following code in another web-page.

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=YourChannelName&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Make sure to replace the YourChannelName with your actual channel name.

For example: if your channel name were CaliChick94066 your channel embed code would be:

<script src="http://www.gmodules.com/ig/ifr?url=http://www.google.com/ig/modules/youtube.xml&up_channel=CaliChick94066&synd=open&w=320&h=390&title=&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>

Please look at the following links:

YouTube on your site

Embed YouTube Channel

You just have to name the URL to your channel name. Also you can play with the height and the border color and size. Hope it helps

How can I render Partial views in asp.net mvc 3?

<%= Html.Partial("PartialName", Model) %>

Create new user in MySQL and give it full access to one database

To create a user and grant all privileges on a database.

Log in to MySQL:

mysql -u root

Now create and grant

GRANT ALL PRIVILEGES ON dbTest.* To 'user'@'hostname' IDENTIFIED BY 'password';

Anonymous user (for local testing only)

Alternately, if you just want to grant full unrestricted access to a database (e.g. on your local machine for a test instance, you can grant access to the anonymous user, like so:

GRANT ALL PRIVILEGES ON dbTest.* To ''@'hostname'

Be aware

This is fine for junk data in development. Don't do this with anything you care about.

How to use source: function()... and AJAX in JQuery UI autocomplete

$("#id").autocomplete(
{
    search: function () {},
    source: function (request, response)
    {
        $.ajax(
        {
            url: ,
            dataType: "json",
            data:
            {
                term: request.term,
            },
            success: function (data)
            {
                response(data);
            }
        });
    },
    minLength: 2,
    select: function (event, ui)
    {
        var test = ui.item ? ui.item.id : 0;
        if (test > 0)
        {
           alert(test);
        }
    }
});

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

How can I view an object with an alert()

If you want to easily view the contents of objects while debugging, install a tool like Firebug and use console.log:

console.log(product);

If you want to view the properties of the object itself, don't alert the object, but its properties:

alert(product.ProductName);
alert(product.UnitPrice);
// etc... (or combine them)

As said, if you really want to boost your JavaScript debugging, use Firefox with the Firebug addon. You will wonder how you ever debugged your code before.

Running java with JAVA_OPTS env variable has no effect

You can setup _JAVA_OPTIONS instead of JAVA_OPTS. This should work without $_JAVA_OPTIONS.

Java: Retrieving an element from a HashSet

The idea that you need to get the reference to the object that is contained inside a Set object is common. It can be archived by 2 ways:

  1. Use HashSet as you wanted, then:

    public Object getObjectReference(HashSet<Xobject> set, Xobject obj) {
        if (set.contains(obj)) {
            for (Xobject o : set) {
                if (obj.equals(o))
                    return o;
            }
        }
        return null;
    }
    

For this approach to work, you need to override both hashCode() and equals(Object o) methods In the worst scenario we have O(n)

  1. Second approach is to use TreeSet

    public Object getObjectReference(TreeSet<Xobject> set, Xobject obj) {
        if (set.contains(obj)) {
            return set.floor(obj);
        }
        return null;
    }
    

This approach gives O(log(n)), more efficient. You don't need to override hashCode for this approach but you have to implement Comparable interface. ( define function compareTo(Object o)).

What does the star operator mean, in a function call?

The single star * unpacks the sequence/collection into positional arguments, so you can do this:

def sum(a, b):
    return a + b

values = (1, 2)

s = sum(*values)

This will unpack the tuple so that it actually executes as:

s = sum(1, 2)

The double star ** does the same, only using a dictionary and thus named arguments:

values = { 'a': 1, 'b': 2 }
s = sum(**values)

You can also combine:

def sum(a, b, c, d):
    return a + b + c + d

values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
s = sum(*values1, **values2)

will execute as:

s = sum(1, 2, c=10, d=15)

Also see section 4.7.4 - Unpacking Argument Lists of the Python documentation.


Additionally you can define functions to take *x and **y arguments, this allows a function to accept any number of positional and/or named arguments that aren't specifically named in the declaration.

Example:

def sum(*values):
    s = 0
    for v in values:
        s = s + v
    return s

s = sum(1, 2, 3, 4, 5)

or with **:

def get_a(**values):
    return values['a']

s = get_a(a=1, b=2)      # returns 1

this can allow you to specify a large number of optional parameters without having to declare them.

And again, you can combine:

def sum(*values, **options):
    s = 0
    for i in values:
        s = s + i
    if "neg" in options:
        if options["neg"]:
            s = -s
    return s

s = sum(1, 2, 3, 4, 5)            # returns 15
s = sum(1, 2, 3, 4, 5, neg=True)  # returns -15
s = sum(1, 2, 3, 4, 5, neg=False) # returns 15

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

create_table :you_table_name do |t| t.references :studant, index: { name: 'name_for_studant_index' } t.references :teacher, index: { name: 'name_for_teacher_index' } end

Mockito: Mock private field initialization

Following code can be used to initialize mapper in REST client mock. The mapper field is private and needs to be set during unit test setup.

import org.mockito.internal.util.reflection.FieldSetter;

new FieldSetter(client, Client.class.getDeclaredField("mapper")).set(new Mapper());

Case insensitive regular expression without re.compile?

You can also perform case insensitive searches using search/match without the IGNORECASE flag (tested in Python 2.7.3):

re.search(r'(?i)test', 'TeSt').group()    ## returns 'TeSt'
re.match(r'(?i)test', 'TeSt').group()     ## returns 'TeSt'

Change Twitter Bootstrap Tooltip content on click

You can set content on tooltip call with a function

        $("#myelement").tooltip({
            "title": function() {
                return "<h2>"+$("#tooltipcontainer").html()+"</h2>";
            }
        });

You don't have to use only the title of the called element.

Extract first and last row of a dataframe in pandas

I think the most simple way is .iloc[[0, -1]].

df = pd.DataFrame({'a':range(1,5), 'b':['a','b','c','d']})
df2 = df.iloc[[0, -1]]

print df2

   a  b
0  1  a
3  4  d

How to use C++ in Go

This can be achieved using command cgo.

In essence 'If the import of "C" is immediately preceded by a comment, that comment, called the preamble, is used as a header when compiling the C parts of the package. For example:'
source:https://golang.org/cmd/cgo/

// #include <stdio.h>
// #include <errno.h>
import "C"

Android RelativeLayout programmatically Set "centerInParent"

I have done for

1. centerInParent

2. centerHorizontal

3. centerVertical

with true and false.

private void addOrRemoveProperty(View view, int property, boolean flag){
    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
    if(flag){
        layoutParams.addRule(property);
    }else {
        layoutParams.removeRule(property);
    }
    view.setLayoutParams(layoutParams);
}

How to call method:

centerInParent - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);

centerInParent - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);

centerHorizontal - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);

centerHorizontal - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);

centerVertical - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);

centerVertical - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);

Hope this would help you.

Docker compose, running containers in net:host

Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.

Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none

version: '3.7'
services:
  app:
    image: ramansharma/einwohnertomcat:v0.0.1
    deploy:
      replicas: 1
      ports:
       - '8080:8080'
    volumes:
     - type: bind
       source: /proc
       target: /hostfs/proc
       read_only: true
     - type: bind
       source: /sys/fs/cgroup
       target: /hostfs/sys/fs/cgroup
       read_only: true
     - type: bind
       source: /
       target: /hostfs
       read_only: true
    networks:
     hostnet: {}
    networks:
     - einwohner_net
     - elk_elk_net
networks:
 einwohner_net:
 elk_elk_net:
   external: true
 hostnet:
   external: true
   name: host

PHP, Get tomorrows date from date

$date = '2013-01-22';
$time = strtotime($date) + 86400;
echo date('Y-m-d', $time);

Where 86400 is the # of seconds in a day.

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Winand, Quality was also an issue for me so I did this:

For Each ws In ActiveWorkbook.Worksheets
    If ws.PageSetup.PrintArea <> "" Then
        'Reverse the effects of page zoom on the exported image
        zoom_coef = 100 / ws.Parent.Windows(1).Zoom
        areas = Split(ws.PageSetup.PrintArea, ",")
        areaNo = 0
        For Each a In areas
            Set area = ws.Range(a)
            ' Change xlPrinter to xlScreen to see zooming white space
            area.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
            Set chartobj = ws.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
            chartobj.Chart.Paste
            'scale the image before export
            ws.Shapes(chartobj.Index).ScaleHeight 3, msoFalse, msoScaleFromTopLeft
            ws.Shapes(chartobj.Index).ScaleWidth 3, msoFalse, msoScaleFromTopLeft
            chartobj.Chart.Export ws.Name & "-" & areaNo & ".png", "png"
            chartobj.delete
            areaNo = areaNo + 1
        Next
    End If
Next

See here:https://robp30.wordpress.com/2012/01/11/improving-the-quality-of-excel-image-export/

Jasmine.js comparing arrays

just for the record you can always compare using JSON.stringify

const arr = [1,2,3]; expect(JSON.stringify(arr)).toBe(JSON.stringify([1,2,3])); expect(JSON.stringify(arr)).toEqual(JSON.stringify([1,2,3]));

It's all meter of taste, this will also work for complex literal objects

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

How to Use TempTable in Stored Procedure?

Here are the steps:

CREATE TEMP TABLE

-- CREATE TEMP TABLE 
Create Table #MyTempTable (
    EmployeeID int
);

INSERT TEMP SELECT DATA INTO TEMP TABLE

-- INSERT COMMON DATA
Insert Into #MyTempTable
Select EmployeeID from [EmployeeMaster] Where EmployeeID between 1 and 100

SELECT TEMP TABLE (You can now use this select query)

Select EmployeeID from #MyTempTable

FINAL STEP DROP THE TABLE

Drop Table #MyTempTable

I hope this will help. Simple and Clear :)

Subdomain on different host

UPDATE - I do not have Total DNS enabled at GoDaddy because the domain is hosted at DiscountASP. As such, I could not add an A Record and that is why GoDaddy was only offering to forward my subdomain to a different site. I finally realized that I had to go to DiscountASP to add the A Record to point to DreamHost. Now waiting to see if it all works!

Of course, use the stinkin' IP! I'm not sure why that wasn't registering for me. I guess their helper text example of pointing to another url was throwing me off.

Thanks for both of the replies. I 'got it' as soon as I read Bryant's response which was first but Saif kicked it up a notch and added a little more detail.

Thanks!

How to get the directory of the currently running file?

os.Executable: https://tip.golang.org/pkg/os/#Executable

filepath.EvalSymlinks: https://golang.org/pkg/path/filepath/#EvalSymlinks

Full Demo:

package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func main() {
    var dirAbsPath string
    ex, err := os.Executable()
    if err == nil {
        dirAbsPath = filepath.Dir(ex)
        fmt.Println(dirAbsPath)
        return
    }

    exReal, err := filepath.EvalSymlinks(ex)
    if err != nil {
        panic(err)
    }
    dirAbsPath = filepath.Dir(exReal)
    fmt.Println(dirAbsPath)
}

How do I remove a CLOSE_WAIT socket connection

It should be mentioned that the Socket instance in both client and the server end needs to explicitly invoke close(). If only one of the ends invokes close() then too, the socket will remain in CLOSE_WAIT state.

Spring MVC - How to return simple String as JSON in Rest Controller

Make simple:

    @GetMapping("/health")
    public ResponseEntity<String> healthCheck() {
        LOG.info("REST request health check");
        return new ResponseEntity<>("{\"status\" : \"UP\"}", HttpStatus.OK);
    }

Matplotlib (pyplot) savefig outputs blank image

Calling savefig before show() worked for me.

fig ,ax = plt.subplots(figsize = (4,4))
sns.barplot(x='sex', y='tip', color='g', ax=ax,data=tips)
sns.barplot(x='sex', y='tip', color='b', ax=ax,data=tips)
ax.legend(['Male','Female'], facecolor='w')

plt.savefig('figure.png')
plt.show()

Show image using file_get_contents

$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo '<img src="' . $src . '">';

REST API error code 500 handling

80 % of the times, this would due to wrong input by in soapRequest.xml file

Set min-width in HTML table's <td>

min-width and max-width properties do not work the way you expect for table cells. From spec:

In CSS 2.1, the effect of 'min-width' and 'max-width' on tables, inline tables, table cells, table columns, and column groups is undefined.

This hasn't changed in CSS3.

What is the garbage collector in Java?

garbage collector implies that objects that are no longer needed by the program are "garbage" and can be thrown away.

How do I tell Maven to use the latest version of a dependency?

Unlike others I think there are many reasons why you might always want the latest version. Particularly if you are doing continuous deployment (we sometimes have like 5 releases in a day) and don't want to do a multi-module project.

What I do is make Hudson/Jenkins do the following for every build:

mvn clean versions:use-latest-versions scm:checkin deploy -Dmessage="update versions" -DperformRelease=true

That is I use the versions plugin and scm plugin to update the dependencies and then check it in to source control. Yes I let my CI do SCM checkins (which you have to do anyway for the maven release plugin).

You'll want to setup the versions plugin to only update what you want:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>versions-maven-plugin</artifactId>
    <version>1.2</version>
    <configuration>
        <includesList>com.snaphop</includesList>
        <generateBackupPoms>false</generateBackupPoms>
        <allowSnapshots>true</allowSnapshots>
    </configuration>
</plugin>

I use the release plugin to do the release which takes care of -SNAPSHOT and validates that there is a release version of -SNAPSHOT (which is important).

If you do what I do you will get the latest version for all snapshot builds and the latest release version for release builds. Your builds will also be reproducible.

Update

I noticed some comments asking some specifics of this workflow. I will say we don't use this method anymore and the big reason why is the maven versions plugin is buggy and in general is inherently flawed.

It is flawed because to run the versions plugin to adjust versions all the existing versions need to exist for the pom to run correctly. That is the versions plugin cannot update to the latest version of anything if it can't find the version referenced in the pom. This is actually rather annoying as we often cleanup old versions for disk space reasons.

Really you need a separate tool from maven to adjust the versions (so you don't depend on the pom file to run correctly). I have written such a tool in the the lowly language that is Bash. The script will update the versions like the version plugin and check the pom back into source control. It also runs like 100x faster than the mvn versions plugin. Unfortunately it isn't written in a manner for public usage but if people are interested I could make it so and put it in a gist or github.

Going back to workflow as some comments asked about that this is what we do:

  1. We have 20 or so projects in their own repositories with their own jenkins jobs
  2. When we release the maven release plugin is used. The workflow of that is covered in the plugin's documentation. The maven release plugin sort of sucks (and I'm being kind) but it does work. One day we plan on replacing this method with something more optimal.
  3. When one of the projects gets released jenkins then runs a special job we will call the update all versions job (how jenkins knows its a release is a complicated manner in part because the maven jenkins release plugin is pretty crappy as well).
  4. The update all versions job knows about all the 20 projects. It is actually an aggregator pom to be specific with all the projects in the modules section in dependency order. Jenkins runs our magic groovy/bash foo that will pull all the projects update the versions to the latest and then checkin the poms (again done in dependency order based on the modules section).
  5. For each project if the pom has changed (because of a version change in some dependency) it is checked in and then we immediately ping jenkins to run the corresponding job for that project (this is to preserve build dependency order otherwise you are at the mercy of the SCM Poll scheduler).

At this point I'm of the opinion it is a good thing to have the release and auto version a separate tool from your general build anyway.

Now you might think maven sort of sucks because of the problems listed above but this actually would be fairly difficult with a build tool that does not have a declarative easy to parse extendable syntax (aka XML).

In fact we add custom XML attributes through namespaces to help hint bash/groovy scripts (e.g. don't update this version).

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

You can also use like this:

for(Iterator iterator = arrayList.iterator(); iterator.hasNext();) {
x = iterator.next();
//do some stuff
}

Its a good practice to cast and use the object. For example, if the 'arrayList' contains a list of 'Object1' objects. Then, we can re-write the code as:

for(Iterator iterator = arrayList.iterator(); iterator.hasNext();) {
x = (Object1) iterator.next();
//do some stuff
}

Can you style an html radio button to look like a checkbox?

I don't think you can make a control look like anything other than a control with CSS.

Your best bet it to make a PRINT button goes to a new page with a graphic in place of the selected radio button, then do a window.print() from there.

Fixing the order of facets in ggplot

Make your size a factor in your dataframe by:

temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))

Then change the facet_grid(.~size) to facet_grid(.~size_f)

Then plot: enter image description here

The graphs are now in the correct order.

How to get Latitude and Longitude of the mobile device in android?

Above solutions is also correct, but some time if location is null then it crash the app or not working properly. The best way to get Latitude and Longitude of android is:

 Geocoder geocoder;
     String bestProvider;
     List<Address> user = null;
     double lat;
     double lng;

    LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

     Criteria criteria = new Criteria();
     bestProvider = lm.getBestProvider(criteria, false);
     Location location = lm.getLastKnownLocation(bestProvider);

     if (location == null){
         Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
      }else{
        geocoder = new Geocoder(activity);
        try {
            user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
        lat=(double)user.get(0).getLatitude();
        lng=(double)user.get(0).getLongitude();
        System.out.println(" DDD lat: " +lat+",  longitude: "+lng);

        }catch (Exception e) {
                e.printStackTrace();
        }
    }

ViewDidAppear is not called when opening app from background

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

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

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

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

Tower of Hanoi: Recursive Algorithm

The answer for the question, how does the program know, that even is "src" to "aux", and odd is "src" to "dst" for the opening move lies in the program. If you break down fist move with 4 discs, then this looks like this:

hanoi(4, "src", "aux", "dst");
if (disc > 0) {
    hanoi(3, 'src', 'dst', 'aux');
        if (disc > 0) {
            hanoi(2, 'src', 'aux', 'dst');
                if (disc > 0) {
                    hanoi(1, 'src', 'dst', 'aux');
                        if (disc > 0) {
                            hanoi(0, 'src', 'aux', 'dst');
                                END
                        document.writeln("Move disc" + 1 + "from" + Src + "to" + Aux);
                        hanoi(0, 'aux', 'src', 'dst');
                                END
                        }

also the first move with 4 disc(even) goes from Src to Aux.

Login to remote site with PHP cURL

This is how I solved this in ImpressPages:

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

How to create unique keys for React elements?

Keys helps React identify which items have changed/added/removed and should be given to the elements inside the array to give the elements a stable identity.

With that in mind, there are basically three different strategies as described bellow:

  1. Static Elements (when you don't need to keep html state (focus, cursor position, etc)
  2. Editable and sortable elements
  3. Editable but not sortable elements

As React Documentation explains, we need to give stable identity to the elements and because of that, carefully choose the strategy that best suits your needs:

STATIC ELEMENTS

As we can see also in React Documentation, is not recommended the use of index for keys "if the order of items may change. This can negatively impact performance and may cause issues with component state".

In case of static elements like tables, lists, etc, I recommend using a tool called shortid.

1) Install the package using NPM/YARN:

npm install shortid --save

2) Import in the class file you want to use it:

import shortid from 'shortid';

2) The command to generate a new id is shortid.generate().

3) Example:

  renderDropdownItems = (): React.ReactNode => {
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach(item => {
        dropdownItems.push(
          <option value={item.value} key={shortid.generate()}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

IMPORTANT: As React Virtual DOM relies on the key, with shortid every time the element is re-rendered a new key will be created and the element will loose it's html state like focus or cursor position. Consider this when deciding how the key will be generated as the strategy above can be useful only when you are building elements that won't have their values changed like lists or read only fields.

EDITABLE (sortable) FIELDS

If the element is sortable and you have a unique ID of the item, combine it with some extra string (in case you need to have the same information twice in a page). This is the most recommended scenario.

Example:

  renderDropdownItems = (): React.ReactNode => {
    const elementKey:string = 'ddownitem_'; 
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach(item => {
        dropdownItems.push(
          <option value={item.value} key={${elementKey}${item.id}}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

EDITABLE (non sortable) FIELDS (e.g. INPUT ELEMENTS)

As a last resort, for editable (but non sortable) fields like input, you can use some the index with some starting text as element key cannot be duplicated.

Example:

  renderDropdownItems = (): React.ReactNode => {
    const elementKey:string = 'ddownitem_'; 
    const { data, isDisabled } = this.props;
    const { selectedValue } = this.state;
    const dropdownItems: Array<React.ReactNode> = [];

    if (data) {
      data.forEach((item:any index:number) => {
        dropdownItems.push(
          <option value={item.value} key={${elementKey}${index}}>
            {item.text}
          </option>
        );
      });
    }

    return (
      <select
        value={selectedValue}
        onChange={this.onSelectedItemChanged}
        disabled={isDisabled}
      >
        {dropdownItems}
      </select>
    );
  };

Hope this helps.

Simple way to query connected USB devices info in Python?

If you are working on windows, you can use pywin32 (old link: see update below).

I found an example here:

import win32com.client

wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
    print usb.DeviceID

Update Apr 2020:

'pywin32' release versions from 218 and up can be found here at github. Current version 227.

How can I run Tensorboard on a remote server?

  1. Find your local external IP by googling "whats my ip" or entering this command: wget http://ipinfo.io/ip -qO -
  2. Determine your remote external IP. This is probably what comes after your username when ssh-ing into the remote server. You can also wget http://ipinfo.io/ip -qO - again from there too.
  3. Secure your remote server traffic to just accept your local external IP address
  4. Run Tensorboard. Note the port it defaults to: 6006
  5. Enter your remote external IP address into your browser, followed by the port: 123.123.12.32:6006

If your remote server is open to traffic from your local IP address, you should be able to see your remote Tensorboard.

Warning: if all internet traffic can access your system (if you haven't specified a single IP address that can access it), anyone may be able to view your TensorBoard results and runaway with creating SkyNet themselves.

exclude @Component from @ComponentScan

In case of excluding test component or test configuration, Spring Boot 1.4 introduced new testing annotations @TestComponent and @TestConfiguration.

Sleep function in C++

The simplest way I found for C++ 11 was this:

Your includes:

#include <chrono>
#include <thread>

Your code (this is an example for sleep 1000 millisecond):

std::chrono::duration<int, std::milli> timespan(1000);
std::this_thread::sleep_for(timespan);

The duration could be configured to any of the following:

std::chrono::nanoseconds   duration</*signed integer type of at least 64 bits*/, std::nano>
std::chrono::microseconds  duration</*signed integer type of at least 55 bits*/, std::micro>
std::chrono::milliseconds  duration</*signed integer type of at least 45 bits*/, std::milli>
std::chrono::seconds       duration</*signed integer type of at least 35 bits*/, std::ratio<1>>  
std::chrono::minutes       duration</*signed integer type of at least 29 bits*/, std::ratio<60>>
std::chrono::hours         duration</*signed integer type of at least 23 bits*/, std::ratio<3600>>

Why should we include ttf, eot, woff, svg,... in a font-face

WOFF 2.0, based on the Brotli compression algorithm and other improvements over WOFF 1.0 giving more than 30 % reduction in file size, is supported in Chrome, Opera, and Firefox.

http://en.wikipedia.org/wiki/Web_Open_Font_Format http://en.wikipedia.org/wiki/Brotli

http://sth.name/2014/09/03/Speed-up-webfonts/ has an example on how to use it.

Basically you add a src url to the woff2 file and specify the woff2 format. It is important to have this before the woff-format: the browser will use the first format that it supports.

What's the difference between TRUNCATE and DELETE in SQL

DROP

The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.

TRUNCATE

TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE. Table level lock will be added when Truncating.

DELETE

The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire. Row level lock will be added when deleting.

From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

You can't save things to Hibernate until you've also told Hibernate about all the other objects referenced by this newly saved object. So in this case, you're telling Hibernate about a User, but haven't told it about the Country.

You can solve problems like this in two ways.

Manually

Call session.save(country) before you save the User.

CascadeType

You can specify to Hibernate that this relationship should propagate some operations using CascadeType. In this case CascadeType.PERSIST would do the job, as would CascadeType.ALL.

Referencing existing countries

Based on your response to @zerocool though, you have a second problem, which is that when you have two User objects with the same Country, you are not making sure it's the same Country. To do this, you have to get the appropriate Country from the database, set it on the new user, and then save the User. Then, both of your User objects will refer to the same Country, not just two Country instances that happen to have the same name. Review the Criteria API as one way of fetching existing instances.

Pyspark: display a spark data frame in a table format

As mentioned by @Brent in the comment of @maxymoo's answer, you can try

df.limit(10).toPandas()

to get a prettier table in Jupyter. But this can take some time to run if you are not caching the spark dataframe. Also, .limit() will not keep the order of original spark dataframe.

How to generate Javadoc from command line

its simple go to the folder where your all java code is saved say E:/javaFolder and then javadoc *.java

example

E:\javaFolder> javadoc *.java

System.IO.IOException: file used by another process

Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :

 using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
 { 
   fs.close();
 }
 using (StreamWriter sw = new StreamWriter(@"File.txt")) 
 { 
   sw.WriteLine("bla bla bla"); 
   sw.Close(); 
 } 

python-dev installation error: ImportError: No module named apt_pkg

For some reason my install was missing apt_pkg.so in the python3 dist-packages dir. (apt_pkg.cpython-33m-x86_64-linux-gnu.so was there?!) but and I had to make a symlink apt_pkg.so -> apt_pkg.cpython-33m-x86_64-linux-gnu.so in /usr/lib/python3/dist-packages

I'm not sure whether my upgrade was broken or why this was the case. It occured after trying to upgrade (precise->raring->quantal upgrade)

Creating a triangle with for loops

private static void printStar(int x) {
    int i, j;
    for (int y = 0; y < x; y++) { // number of row of '*'

        for (i = y; i < x - 1; i++)
            // number of space each row
            System.out.print(' ');

        for (j = 0; j < y * 2 + 1; j++)
            // number of '*' each row
            System.out.print('*');

        System.out.println();
    }
}

Cache busting via params

It very much depends on quite how robust you want your caching to be. For example, the squid proxy server (and possibly others) defaults to not caching URLs served with a querystring - at least, it did when that article was written. If you don't mind certain use cases causing unnecessary cache misses, then go ahead with query params. But it's very easy to set up a filename-based cache-busting scheme which avoids this problem.

What are the proper permissions for an upload folder with PHP/Apache?

Based on the answer from @Ryan Ahearn, following is what I did on Ubuntu 16.04 to create a user front that only has permission for nginx's web dir /var/www/html.

Steps:

* pre-steps:
    * basic prepare of server,
    * create user 'dev'
        which will be the owner of "/var/www/html",
    * 
    * install nginx,
    * 
* 
* create user 'front'
    sudo useradd -d /home/front -s /bin/bash front
    sudo passwd front

    # create home folder, if not exists yet,
    sudo mkdir /home/front
    # set owner of new home folder,
    sudo chown -R front:front /home/front

    # switch to user,
    su - front

    # copy .bashrc, if not exists yet,
    cp /etc/skel/.bashrc ~front/
    cp /etc/skel/.profile ~front/

    # enable color,
    vi ~front/.bashrc
    # uncomment the line start with "force_color_prompt",

    # exit user
    exit
* 
* add to group 'dev',
    sudo usermod -a -G dev front
* change owner of web dir,
    sudo chown -R dev:dev /var/www
* change permission of web dir,
    chmod 775 $(find /var/www/html -type d)
    chmod 664 $(find /var/www/html -type f)
* 
* re-login as 'front'
    to make group take effect,
* 
* test
* 
* ok
* 

rebase in progress. Cannot commit. How to proceed or stop (abort)?

I got into this state recently. After resolving conflicts during a rebase, I committed my changes, rather than running git rebase --continue. This yields the same messages you saw when you ran your git status and git rebase --continue commands. I resolved the issue by running git rebase --abort, and then re-running the rebase. One could likely also skip the rebase, but I wasn't sure what state that would leave me in.

$ git rebase --continue
Applying: <commit message>
No changes - did you forget to use 'git add'?
If there is nothing left to stage, chances are that something else
already introduced the same changes; you might want to skip this patch.

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".

$ git status
rebase in progress; onto 4df0775
You are currently rebasing branch '<local-branch-name>' on '4df0775'.
  (all conflicts fixed: run "git rebase --continue")

nothing to commit, working directory clean

'Invalid update: invalid number of rows in section 0

Swift Version --> Remove the object from your data array before you call

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        print("Deleted")

        currentCart.remove(at: indexPath.row) //Remove element from your array 
        self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

Remove substring from the string

If you are using rails or at less activesupport you got String#remove and String#remove! method

def remove!(*patterns)
  patterns.each do |pattern|
    gsub! pattern, ""
  end

  self
end

source: http://api.rubyonrails.org/classes/String.html#method-i-remove

How to iterate using ngFor loop Map containing key as string and values as map iteration

The below code useful to display in the map insertion order.

<ul>
    <li *ngFor="let recipient of map | keyvalue: asIsOrder">
        {{recipient.key}} --> {{recipient.value}}
    </li>
</ul>

.ts file add the below code.

asIsOrder(a, b) {
    return 1;
}

Python: Total sum of a list of numbers with the for loop

l = [1,2,3,4,5]
sum = 0
for x in l:
    sum = sum + x

And you can change l for any list you want.

Sort Java Collection

You can also use:

Collections.sort(list, new Comparator<CustomObject>() {
    public int compare(CustomObject obj1, CustomObject obj2) {
        return obj1.id - obj2.id;
    }
});
System.out.println(list);

Cloning specific branch

you can use this command for particular branch clone :

git clone <url of repo> -b <branch name to be cloned>

Eg: git clone https://www.github.com/Repo/FirstRepo -b master

Delete data with foreign key in SQL Server table

You can disable and re-enable the foreign key constraints before and after deleting:

alter table MyOtherTable nocheck constraint all
delete from MyTable
alter table MyOtherTable check constraint all

Load HTML page dynamically into div with jQuery

You can use jQuery's getJSON() or Load(); with the latter, you can reference an existing html file. For more details, see http://www.codeproject.com/Articles/661782/Three-Ways-to-Dynamically-Load-HTML-Content-into-a

How to get a value inside an ArrayList java

main class

public class Test {
    public static void main (String [] args){
        Car thisCar= new Car ("Toyota", "$10000", "2003");  
        ArrayList<Car> car= new ArrayList<Car> ();
        car.add(thisCar); 
        processCar(car);
    } 

    public static void processCar(ArrayList<Car> car){
        for(Car c : car){
            System.out.println (c.getPrice());
        }
    }
}

car class

public class Car {
    private String vehicle;
    private String price;
    private String model;

    public Car(String vehicle, String price, String model){
        this.vehicle = vehicle;
        this.model = model;
        this.price = price;
    }

    public String getVehicle() {
        return vehicle;
    }

    public String getPrice() {
        return price;
    }

    public String getModel() {
        return model;
    }  
}

IE 8: background-size fix

As posted by 'Dan' in a similar thread, there is a possible fix if you're not using a sprite:

How do I make background-size work in IE?

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";

However, this scales the entire image to fit in the allocated area. So if your using a sprite, this may cause issues.

Caution
The filter has a flaw, any links inside the allocated area are no longer clickable.

What does "export default" do in JSX?

Simplest Understanding for default export is

Export is ES6's feature which is used to Export a module(file) and use it in some other module(file).

Default Export:

  1. default export is the convention if you want to export only one object(variable, function, class) from the file(module).
  2. There could be only one default export per file, but not restricted to only one export.
  3. When importing default exported object we can rename it as well.

Export or Named Export:

  1. It is used to export the object(variable, function, calss) with the same name.

  2. It is used to export multiple objects from one file.

  3. It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as operator.

In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

Here is some SQL that actually make sense:

SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL

Simple is always better.

sqlite3.OperationalError: unable to open database file

Django NewbieMistakes

PROBLEM You're using SQLite3, your DATABASE_NAME is set to the database file's full path, the database file is writeable by Apache, but you still get the above error.

SOLUTION Make sure Apache can also write to the parent directory of the database. SQLite needs to be able to write to this directory.

Make sure each folder of your database file's full path does not start with number, eg. /www/4myweb/db (observed on Windows 2000).

If DATABASE_NAME is set to something like '/Users/yourname/Sites/mydjangoproject/db/db', make sure you've created the 'db' directory first.

Make sure your /tmp directory is world-writable (an unlikely cause as other thing on your system will also not work). ls /tmp -ald should produce drwxrwxrwt ....

Make sure the path to the database specified in settings.py is a full path.

Also make sure the file is present where you expect it to be.

How to convert R Markdown to PDF?

For an option that looks more like what you get when you print from a browser, wkhtmltopdf provides one option.

On Ubuntu

sudo apt-get install wkhtmltopdf

And then the same command as for the pandoc example to get to the HTML:

RMDFILE=example-r-markdown  
Rscript -e "require(knitr); require(markdown); knit('$RMDFILE.rmd', '$RMDFILE.md'); markdownToHTML('$RMDFILE.md', '$RMDFILE.html', options=c('use_xhml'))"

and then

wkhtmltopdf example-r-markdown.html example-r-markdown.pdf

The resulting file looked like this. It did not seem to handle the MathJax (this issue is discussed here), and the page breaks are ugly. However, in some cases, such a style might be preferred over a more LaTeX style presentation.

MySQL show status - active or total connections?

To see a more complete list you can run:

show session status;

or

show global status;

See this link to better understand the usage.

If you want to know details about the database you can run:

status;

Set default option in mat-select

I was able to set the default value or whatever value using the following:

Template:
          <mat-form-field>
              <mat-label>Holiday Destination</mat-label>
              <mat-select [(ngModel)]="selectedCity" formControlName="cityHoliday">
                <mat-option [value]="nyc">New York</mat-option>
                <mat-option [value]="london">London</mat-option>
                <mat-option [value]="india">Delhi</mat-option>
                <mat-option [value]="Oslo">Oslo</mat-option>
              </mat-select>
          </mat-form-field>

Component:

export class WhateverComponent implements OnInit{

selectedCity: string;    

}

ngOnInit() {
    this.selectedCity = 'london';
} 

}

How to use onClick() or onSelect() on option tag in a JSP page?

Neither the onSelect() nor onClick() events are supported by the <option> tag. The former refers to selecting text (i.e. by clicking + dragging across a text field) so can only be used with the <text> and <textarea> tags. The onClick() event can be used with <select> tags - however, you probably are looking for functionality where it would be best to use the onChange() event, not onClick().

Furthermore, by the look of your <c:...> tags, you are also trying to use JSP syntax in a plain HTML document. That's just... incorrect.

In response to your comment to this answer - I can barely understand it. However, it sounds like what you want to do is get the value of the <option> tag that the user has just selected whenever they select one. In that case, you want to have something like:

<html>
 <head>
  <script type="text/javascript">

   function changeFunc() {
    var selectBox = document.getElementById("selectBox");
    var selectedValue = selectBox.options[selectBox.selectedIndex].value;
    alert(selectedValue);
   }

  </script>
 </head>
 <body>
  <select id="selectBox" onchange="changeFunc();">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
  </select>
 </body>
</html>

converting numbers in to words C#

public static string NumberToWords(int number)
{
    if (number == 0)
        return "zero";

    if (number < 0)
        return "minus " + NumberToWords(Math.Abs(number));

    string words = "";

    if ((number / 1000000) > 0)
    {
        words += NumberToWords(number / 1000000) + " million ";
        number %= 1000000;
    }

    if ((number / 1000) > 0)
    {
        words += NumberToWords(number / 1000) + " thousand ";
        number %= 1000;
    }

    if ((number / 100) > 0)
    {
        words += NumberToWords(number / 100) + " hundred ";
        number %= 100;
    }

    if (number > 0)
    {
        if (words != "")
            words += "and ";

        var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
        var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

        if (number < 20)
            words += unitsMap[number];
        else
        {
            words += tensMap[number / 10];
            if ((number % 10) > 0)
                words += "-" + unitsMap[number % 10];
        }
    }

    return words;
}

Get the value of input text when enter key pressed

You should not place Javascript code in your HTML, since you're giving those input a class ("search"), there is no reason to do this. A better solution would be to do something like this :

$( '.search' ).on( 'keydown', function ( evt ) {
    if( evt.keyCode == 13 )
        search( $( this ).val() ); 
} ); 

sqlite copy data from one table to another

If you have data already present in both the tables and you want to update a table column values based on some condition then use this

UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id)

How to store printStackTrace into a string

StackTraceElement[] stack = new Exception().getStackTrace();
String theTrace = "";
for(StackTraceElement line : stack)
{
   theTrace += line.toString();
}

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Negative margins are valid in css and understanding their (compliant) behaviour is mainly based on the box model and margin collapsing. While certain scenarios are more complex, a lot of common mistakes can be avoided after studying the spec.

For instance, rendering of your sample code is guided by the css spec as described in calculating heights and margins for absolutely positioned non-replaced elements.

If I were to make a graphical representation, I'd probably go with something like this (not to scale):

negative top margin

The margin box lost 8px on the top, however this does not affect the content & padding boxes. Because your element is absolutely positioned, moving the element 8px up does not cause any further disturbance to the layout; with static in-flow content that's not always the case.

Bonus:

Still need convincing that reading specs is the way to go (as opposed to articles like this)? I see you're trying to vertically center the element, so why do you have to set margin-top:-8px; and not margin-top:-50%;?

Well, vertical centering in CSS is harder than it should be. When setting even top or bottom margins in %, the value is calculated as a percentage always relative to the width of the containing block. This is rather a common pitfall and the quirk is rarely described outside of w3 docos

How to change the buttons text using javascript

You can toggle filterstatus value like this

filterstatus ^= 1;

So your function looks like

function showFilterItem(objButton) {
if (filterstatus == 0) {
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().showFilterItem();
    objButton.value = "Hide Filter";
}
else {
    $find('<%=FileAdminRadGrid.ClientID %>').get_masterTableView().hideFilterItem();
    objButton.value = "Show filter";
}
  filterstatus ^= 1;    
}

How do I overload the square-bracket operator in C#?

you can find how to do it here. In short it is:

public object this[int i]
{
    get { return InnerList[i]; }
    set { InnerList[i] = value; }
}

If you only need a getter the syntax in answer below can be used as well (starting from C# 6).

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

In Kotlin, you can do:

ContextCompat.getColor(requireContext(), R.color.stage_hls_fallback_snackbar)

if requireContext() is accessible from where you are calling the function. I was getting an error when trying

ContextCompat.getColor(context, R.color.stage_hls_fallback_snackbar)

What's the Use of '\r' escape sequence?

To answer the part of your question,

what is the use of \r?

Many Internet protocols, such as FTP, HTTP and SMTP, are specified in terms of lines delimited by carriage return and newline. So, for example, when sending an email, you might have code such as:

fprintf(socket, "RCPT TO: %s\r\n", recipients);

Or, when a FTP server replies with a permission-denied error:

fprintf(client, "550 Permission denied\r\n");

MVC: How to Return a String as JSON

Yeah that's it without no further issues, to avoid raw string json this is it.

    public ActionResult GetJson()
    {
        var json = System.IO.File.ReadAllText(
            Server.MapPath(@"~/App_Data/content.json"));

        return new ContentResult
        {
            Content = json,
            ContentType = "application/json",
            ContentEncoding = Encoding.UTF8
        };
    } 

NOTE: please note that method return type of JsonResult is not working for me, since JsonResult and ContentResult both inherit ActionResult but there is no relationship between them.

How to execute UNION without sorting? (SQL)

The sort is used to eliminate the duplicates, and is implicit for DISTINCT and UNION queries (but not UNION ALL) - you could still specify the columns you'd prefer to order by if you need them sorted by specific columns.

For example, if you wanted to sort by the result sets, you could introduce an additional column, and sort by that first:

SELECT foo, bar, 1 as ResultSet
FROM Foo
WHERE bar = 1
UNION
SELECT foo, bar, 2 as ResultSet
FROM Foo
WHERE bar = 3
UNION
SELECT foo, bar, 3 as ResultSet
FROM Foo
WHERE bar = 2
ORDER BY ResultSet

How to restore a SQL Server 2012 database to SQL Server 2008 R2?

Merge replication. You can create the subscriber (2008) from the distributor (2008). After the database has fully synchronized, drop the subscription and the publication.

PHP and MySQL Select a Single Value

try this

session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
      $_SESSION['myid'] = $row['id'];
}

Embedding Windows Media Player for all browsers

I found a good article about using the WMP with Firefox on MSDN.

Based on MSDN's article and after doing some trials and errors, I found using JavaScript is better than using conditional comments or nested "EMBED/OBJECT" tags.

I made a JS function that generate WMP object based on given arguments:

<script type="text/javascript">
    function generateWindowsMediaPlayer(
        holderId,   // String
        height,     // Number
        width,      // Number
        videoUrl    // String
        // you can declare more arguments for more flexibility
        ) {
        var holder = document.getElementById(holderId);

        var player = '<object ';
        player += 'height="' + height.toString() + '" ';
        player += 'width="' + width.toString() + '" ';

        videoUrl = encodeURI(videoUrl); // Encode for special characters

        if (navigator.userAgent.indexOf("MSIE") < 0) {
            // Chrome, Firefox, Opera, Safari
            //player += 'type="application/x-ms-wmp" '; //Old Edition
            player += 'type="video/x-ms-wmp" '; //New Edition, suggested by MNRSullivan (Read Comments)
            player += 'data="' + videoUrl + '" >';
        }
        else {
            // Internet Explorer
            player += 'classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" >';
            player += '<param name="url" value="' + videoUrl + '" />';
        }

        player += '<param name="autoStart" value="false" />';
        player += '<param name="playCount" value="1" />';
        player += '</object>';

        holder.innerHTML = player;
    }
</script>

Then I used that function by writing some markups and inline JS like these:

<div id='wmpHolder'></div>

<script type="text/javascript">        
    window.addEventListener('load', generateWindowsMediaPlayer('wmpHolder', 240, 320, 'http://mysite.com/path/video.ext'));
</script>

You can use jQuery.ready instead of window load event to making the codes more backward-compatible and cross-browser.

I tested the codes over IE 9-10, Chrome 27, Firefox 21, Opera 12 and Safari 5, on Windows 7/8.

How do I add 1 day to an NSDate?

Use the below function and use days paramater to get the date daysAhead/daysBehind just pass parameter as positive for future date or negative for previous dates:

+ (NSDate *) getDate:(NSDate *)fromDate daysAhead:(NSUInteger)days
{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = days;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *previousDate = [calendar dateByAddingComponents:dateComponents
                                                     toDate:fromDate
                                                    options:0];
    [dateComponents release];
    return previousDate;
}

Unexpected token ILLEGAL in webkit

I got the same error when the script file I was including container some special characters and when I was running in local moode (directly from local disk). I my case the solution was to explicitly tell the encoding:

<script src="my.js" charset="UTF-8"></script>

Should I initialize variable within constructor or outside constructor

I have the practice (habit) of almost always initializing in the contructor for two reasons, one in my opinion it adds to readablitiy (cleaner), and two there is more logic control in the constructor than in one line. Even if initially the instance variable doesn't require logic, having it in the constructor gives more flexibility to add logic in the future if needed.

As to the concern mentioned above about multiple constructors, that's easily solved by having one no-arg constructor that initializes all the instance variables that are initilized the same for all constructors and then each constructor calls this() at the first line. That solves your reduncancy issues.

get launchable activity name of package from adb

#!/bin/bash
#file getActivity.sh
package_name=$1
#launch app by package name
adb shell monkey -p ${package_name} -c android.intent.category.LAUNCHER 1;
sleep 1;
#get Activity name
adb shell logcat -d | grep 'START u0' | tail -n 1 | sed 's/.*cmp=\(.*\)} .*/\1/g'

sample:

getActivity.sh com.tencent.mm
com.tencent.mm/.ui.LauncherUI

Express.js: how to get remote client address

var ip = req.connection.remoteAddress;

ip = ip.split(':')[3];

Is it possible to use raw SQL within a Spring Repository

YES, You can do this on bellow ways:

1. By CrudRepository (Projection)

Spring Data Repositories usually return the domain model when using query methods. However, sometimes, you may need to alter the view of that model for various reasons.

Suppose your entity is like this :

    import javax.persistence.*;
    import java.math.BigDecimal;

    @Entity
    @Table(name = "USER_INFO_TEST")
    public class UserInfoTest {
        private int id;
        private String name;
        private String rollNo;

        public UserInfoTest() {
        }

        public UserInfoTest(int id, String name) {
        this.id = id;
        this.name = name;
        }

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "ID", nullable = false, precision = 0)
        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        @Basic
        @Column(name = "name", nullable = true)
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Basic
        @Column(name = "roll_no", nullable = true)
        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

Now your Projection class is like bellow. It can those fields that you needed.

public interface IUserProjection {
     int getId();
     String getName();
     String getRollNo();
}

And Your Data Access Object(Dao) is like bellow :

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.ArrayList;

public interface UserInfoTestDao extends CrudRepository<UserInfoTest,Integer> {
    @Query(value = "select id,name,roll_no from USER_INFO_TEST where rollNo = ?1", nativeQuery = true)
    ArrayList<IUserProjection> findUserUsingRollNo(String rollNo);
}

Now ArrayList<IUserProjection> findUserUsingRollNo(String rollNo) will give you the list of user.

2. Using EntityManager

Suppose your query is "select id,name from users where roll_no = 1001".

Here query will return a object with id and name column. Your Response class is like bellow:

Your Response class is like:

public class UserObject{
        int id;
        String name;
        String rollNo;

        public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

here UserObject constructor will get a Object Array and set data with object.

public UserObject(Object[] columns) {
            this.id = (columns[0] != null)?((BigDecimal)columns[0]).intValue():0;
            this.name = (String) columns[1];
        }

Your query executing function is like bellow :

public UserObject getUserByRoll(EntityManager entityManager,String rollNo) {

        String queryStr = "select id,name from users where roll_no = ?1";
        try {
            Query query = entityManager.createNativeQuery(queryStr);
            query.setParameter(1, rollNo);

            return new UserObject((Object[]) query.getSingleResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

Here you have to import bellow packages:

import javax.persistence.Query;
import javax.persistence.EntityManager;

Now your main class, you have to call this function. First get EntityManager and call this getUserByRoll(EntityManager entityManager,String rollNo) function. Calling procedure is given bellow:

Here is the Imports

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

get EntityManager from this way:

@PersistenceContext
private EntityManager entityManager;

UserObject userObject = getUserByRoll(entityManager,"1001");

Now you have data in this userObject.

Note:

query.getSingleResult() return a object array. You have to maintain the column position and data type with query column position.

select id,name from users where roll_no = 1001 

query return a array and it's [0] --> id and [1] -> name.

More info visit this thread and this Thread

Thanks :)

how to rename an index in a cluster?

As such there is no direct method to copy or rename index in ES (I did search extensively for my own project)

However a very easy option is to use a popular migration tool [Elastic-Exporter].

http://www.retailmenot.com/corp/eng/posts/2014/12/02/elasticsearch-cluster-migration/

[PS: this is not my blog, just stumbled upon and found it good]

Thereby you can copy index/type and then delete the old one.

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

I used the concept from the answer posted by @marcg and it works great with JPA 2.1. His code wasn't quite right, so I'm posted my working implementation. This will convert Boolean entity fields to a Y/N character column in the database.

From my entity class:

@Convert(converter=BooleanToYNStringConverter.class)
@Column(name="LOADED", length=1)
private Boolean isLoadedSuccessfully;

My converter class:

/**
 * Converts a Boolean entity attribute to a single-character
 * Y/N string that will be stored in the database, and vice-versa
 * 
 * @author jtough
 */
public class BooleanToYNStringConverter 
        implements AttributeConverter<Boolean, String> {

    /**
     * This implementation will return "Y" if the parameter is Boolean.TRUE,
     * otherwise it will return "N" when the parameter is Boolean.FALSE. 
     * A null input value will yield a null return value.
     * @param b Boolean
     */
    @Override
    public String convertToDatabaseColumn(Boolean b) {
        if (b == null) {
            return null;
        }
        if (b.booleanValue()) {
            return "Y";
        }
        return "N";
    }

    /**
     * This implementation will return Boolean.TRUE if the string
     * is "Y" or "y", otherwise it will ignore the value and return
     * Boolean.FALSE (it does not actually look for "N") for any
     * other non-null string. A null input value will yield a null
     * return value.
     * @param s String
     */
    @Override
    public Boolean convertToEntityAttribute(String s) {
        if (s == null) {
            return null;
        }
        if (s.equals("Y") || s.equals("y")) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}

This variant is also fun if you love emoticons and are just sick and tired of Y/N or T/F in your database. In this case, your database column must be two characters instead of one. Probably not a big deal.

/**
 * Converts a Boolean entity attribute to a happy face or sad face
 * that will be stored in the database, and vice-versa
 * 
 * @author jtough
 */
public class BooleanToHappySadConverter 
        implements AttributeConverter<Boolean, String> {

    public static final String HAPPY = ":)";
    public static final String SAD = ":(";

    /**
     * This implementation will return ":)" if the parameter is Boolean.TRUE,
     * otherwise it will return ":(" when the parameter is Boolean.FALSE. 
     * A null input value will yield a null return value.
     * @param b Boolean
     * @return String or null
     */
    @Override
    public String convertToDatabaseColumn(Boolean b) {
        if (b == null) {
            return null;
        }
        if (b) {
            return HAPPY;
        }
        return SAD;
    }

    /**
     * This implementation will return Boolean.TRUE if the string
     * is ":)", otherwise it will ignore the value and return
     * Boolean.FALSE (it does not actually look for ":(") for any
     * other non-null string. A null input value will yield a null
     * return value.
     * @param s String
     * @return Boolean or null
     */
    @Override
    public Boolean convertToEntityAttribute(String s) {
        if (s == null) {
            return null;
        }
        if (HAPPY.equals(s)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}

ArrayList of int array in java

Integer is wrapper class and int is primitive data type.Always prefer using Integer in ArrayList.

What is 'Currying'?

Currying is a transformation that can be applied to functions to allow them to take one less argument than previously.

For example, in F# you can define a function thus:-

let f x y z = x + y + z

Here function f takes parameters x, y and z and sums them together so:-

f 1 2 3

Returns 6.

From our definition we can can therefore define the curry function for f:-

let curry f = fun x -> f x

Where 'fun x -> f x' is a lambda function equivilent to x => f(x) in C#. This function inputs the function you wish to curry and returns a function which takes a single argument and returns the specified function with the first argument set to the input argument.

Using our previous example we can obtain a curry of f thus:-

let curryf = curry f

We can then do the following:-

let f1 = curryf 1

Which provides us with a function f1 which is equivilent to f1 y z = 1 + y + z. This means we can do the following:-

f1 2 3

Which returns 6.

This process is often confused with 'partial function application' which can be defined thus:-

let papply f x = f x

Though we can extend it to more than one parameter, i.e.:-

let papply2 f x y = f x y
let papply3 f x y z = f x y z
etc.

A partial application will take the function and parameter(s) and return a function that requires one or more less parameters, and as the previous two examples show is implemented directly in the standard F# function definition so we could achieve the previous result thus:-

let f1 = f 1
f1 2 3

Which will return a result of 6.

In conclusion:-

The difference between currying and partial function application is that:-

Currying takes a function and provides a new function accepting a single argument, and returning the specified function with its first argument set to that argument. This allows us to represent functions with multiple parameters as a series of single argument functions. Example:-

let f x y z = x + y + z
let curryf = curry f
let f1 = curryf 1
let f2 = curryf 2
f1 2 3
6
f2 1 3
6

Partial function application is more direct - it takes a function and one or more arguments and returns a function with the first n arguments set to the n arguments specified. Example:-

let f x y z = x + y + z
let f1 = f 1
let f2 = f 2
f1 2 3
6
f2 1 3
6

SSL Connection / Connection Reset with IISExpress

I was having this problem, I had configured my site for global require https in FilterConfig.cs.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new RequireHttpsAttribute());
    }

I had forgotten to change the project url to https: from this tutorial http://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-app-membership-oauth-sql-database/ under ENABLE SSL part 4. This caused the errors you were getting.

Jenkins: Failed to connect to repository

I had the exact same problem. The way I solved it on Mac is this:

  1. Switch to jenkins user (sudo -iu jenkins)
  2. Run: ssh-keygen (Note - You are creating ssh key pairs for jenkins user now. You should see something like this : Enter file in which to save the key (/Users/Shared/Jenkins/.ssh/id_rsa):
  3. Keep pressing Enter for default value till end
  4. Run the command showing in the Jenkins error message, on your teminal (eg : "git ls-remote -h [email protected]:adolfosrs/jenkins-test.git HEAD")
  5. You will be asked if you want to continue. Say yes
  6. The Github repo will be added to your known_hosts file in : /Users/Shared/Jenkins/.ssh/
  7. Go back to Jenkins portal and try your Github SSH url
  8. It should work. Good Luck

Casting objects in Java

Have a look at this sample:

public class A {
  //statements
}

public class B extends A {
  public void foo() { }
}

A a=new B();

//To execute **foo()** method.

((B)a).foo();

How to get only numeric column values?

The other answers indicating using IsNumeric in the where clause are correct, as far as they go, but it's important to remember that it returns 1 if the value can be converted to any numeric type. As such, oddities such as "1d3" will make it through the filter.

If you need only values composed of digits, search for that explicitly:

SELECT column1 FROM table WHERE column1 not like '%[^0-9]%'

The above is filtering to reject any column which contains a non-digit character

Note that in any case, you're going to incur a table scan, indexes are useless for this sort of query.

How to generate the JPA entity Metamodel?

Ok, based on what I have read here, I did it with EclipseLink this way and I did not need to put the processor dependency to the project, only as an annotationProcessorPath element of the compiler plugin.

    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <annotationProcessorPaths>
                <annotationProcessorPath>
                    <groupId>org.eclipse.persistence</groupId>
                    <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
                    <version>2.7.7</version>
                </annotationProcessorPath>
            </annotationProcessorPaths>
            <compilerArgs>
                <arg>-Aeclipselink.persistencexml=src/main/resources/META-INF/persistence.xml</arg>
            </compilerArgs>
        </configuration>
    </plugin>

Replacing Spaces with Underscores

As of others have explained how to do it using str_replace, you can also use regex to achieve this.

$name = preg_replace('/\s+/', '_', $name);

How to find if element with specific id exists or not

You can simply use if(yourElement)

_x000D_
_x000D_
var a = document.getElementById("elemA");_x000D_
var b = document.getElementById("elemB");_x000D_
_x000D_
if(a)_x000D_
  console.log("elemA exists");_x000D_
else_x000D_
  console.log("elemA does not exist");_x000D_
  _x000D_
if(b)_x000D_
  console.log("elemB exists");_x000D_
else_x000D_
  console.log("elemB does not exist");
_x000D_
<div id="elemA"></div>
_x000D_
_x000D_
_x000D_

JWT (JSON Web Token) library for Java

JJWT aims to be the easiest to use and understand JWT library for the JVM and Android:

https://github.com/jwtk/jjwt

How to convert a string of numbers to an array of numbers?

There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.

Reasons:

  1. It's working:

    var src = "1,2,5,4,3";
    var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
    
    var obj = {1: ..., 3: ..., 4: ..., 7: ...};
    var keys= Object.keys(obj); // ["1", "3", "4", "7"]
    var ids = keys.map(parseFloat); // [1, 3, 4, 7]
    
    var arr = ["1", 5, "7", 11];
    var ints= arr.map(parseFloat); // [1, 5, 7, 11]
    ints[1] === "5" // false
    ints[1] === 5   // true
    ints[2] === "7" // false
    ints[2] === 7   // true
    
  2. It's shorter.

  3. It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:

      // execution time measure function
      // keep it simple, yeah?
    > var f = (function (arr, c, n, m) {
          var i,t,m,s=n();
          for(i=0;i++<c;)t=arr.map(m);
          return n()-s
      }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
    
    > f(Number) // first launch, just warming-up cache
    > 3971 // nice =)
    
    > f(Number)
    > 3964 // still the same
    
    > f(function(e){return+e})
    > 5132 // yup, just little bit slower
    
    > f(function(e){return+e})
    > 5112 // second run... and ok.
    
    > f(parseFloat)
    > 3727 // little bit quicker than .map(Number)
    
    > f(parseFloat)
    > 3737 // all ok
    
    > f(function(e){return parseInt(e,10)})
    > 21852 // awww, how adorable...
    
    > f(function(e){return parseInt(e)})
    > 22928 // maybe, without '10'?.. nope.
    
    > f(function(e){return parseInt(e)})
    > 22769 // second run... and nothing changes.
    
    > f(Number)
    > 3873 // and again
    > f(parseFloat)
    > 3583 // and again
    > f(function(e){return+e})
    > 4967 // and again
    
    > f(function(e){return parseInt(e,10)})
    > 21649 // dammit 'parseInt'! >_<
    

Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt

matplotlib savefig in jpeg format

To clarify and update @neo useful answer and the original question. A clean solution consists of installing Pillow, which is an updated version of the Python Imaging Library (PIL). This is done using

pip install pillow

Once Pillow is installed, the standard Matplotlib commands

import matplotlib.pyplot as plt

plt.plot([1, 2])
plt.savefig('image.jpg')

will save the figure into a JPEG file and will not generate a ValueError any more.

Contrary to @amillerrhodes answer, as of Matplotlib 3.1, JPEG files are still not supported. If I remove the Pillow package I still receive a ValueError about an unsupported file type.

pypi UserWarning: Unknown distribution option: 'install_requires'

I'm on a Mac with python 2.7.11. I have been toying with creating extremely simple and straightforward projects, where my only requirement is that I can run python setup.py install, and have setup.py use the setup command, ideally from distutils. There are literally no other imports or code aside from the kwargs to setup() other than what I note here.

I get the error when the imports for my setup.py file are:

from distutils.core import setup

When I use this, I get warnings such as

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'entry_points' warnings.warn(msg)

If I change the imports (and nothing else) to the following:

from distutils.core import setup
import setuptools  # noqa

The warnings go away.

Note that I am not using setuptools, just importing it changes the behavior such that it no longer emits the warnings. For me, this is the cause of a truly baffling difference where some projects I'm using give those warnings, and some others do not.

Clearly, some form of monkey-patching is going on, and it is affected by whether or not that import is done. This probably isn't the situation for everyone researching this problem, but for the narrow environment in which I'm working, this is the answer I was looking for.


This is consistent with the other (community) comment, which says that distutils should monkeypatch setuptools, and that they had the problem when installing Ansible. Ansible appears to have tried to allow installs without having setuptools in the past, and then went back on that.

https://github.com/ansible/ansible/blob/devel/setup.py

A lot of stuff is up in the air... but if you're looking for a simple answer for a simple project, you should probably just import setuptools.

Immutable array in Java

My recommendation is to not use an array or an unmodifiableList but to use Guava's ImmutableList, which exists for this purpose.

ImmutableList<Integer> values = ImmutableList.of(0, 1, 2, 3);

C# code to validate email address

I succinctified Poyson 1's answer like so:

public static bool IsValidEmailAddress(string candidateEmailAddr)
{
    string regexExpresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
    return (Regex.IsMatch(candidateEmailAddr, regexExpresion)) && 
           (Regex.Replace(candidateEmailAddr, regexExpresion, string.Empty).Length == 0);
}

Converting dd/mm/yyyy formatted string to Datetime

You need to use DateTime.ParseExact with format "dd/MM/yyyy"

DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Its safer if you use d/M/yyyy for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.


Your date format day/Month/Year might be an acceptable date format for some cultures. For example for Canadian Culture en-CA DateTime.Parse would work like:

DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));

Or

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture

Both the above lines would work because the the string's format is acceptable for en-CA culture. Since you are not supplying any culture to your DateTime.Parse call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.


Another method for parsing is using DateTime.TryParseExact

DateTime dt;
if (DateTime.TryParseExact("24/01/2013", 
                            "d/M/yyyy", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None,
    out dt))
{
    //valid date
}
else
{
    //invalid date
}

The TryParse group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool value indicating success or failure in parsing.

Notice that I have used single d and M for day and month respectively. Single d and M works for both single/double digits day and month. So for the format d/M/yyyy valid values could be:

  • "24/01/2013"
  • "24/1/2013"
  • "4/12/2013" //4 December 2013
  • "04/12/2013"

For further reading you should see: Custom Date and Time Format Strings

Comparing two arrays & get the values which are not common

This should help, uses simple hash table.

$a1=@(1,2,3,4,5) $b1=@(1,2,3,4,5,6)


$hash= @{}

#storing elements of $a1 in hash
foreach ($i in $a1)
{$hash.Add($i, "present")}

#define blank array $c
$c = @()

#adding uncommon ones in second array to $c and removing common ones from hash
foreach($j in $b1)
{
if(!$hash.ContainsKey($j)){$c = $c+$j}
else {hash.Remove($j)}
}

#now hash is left with uncommon ones in first array, so add them to $c
foreach($k in $hash.keys)
{
$c = $c + $k
}

Simple (non-secure) hash function for JavaScript?

There are many realizations of hash functions written in JS. For example:

If you don't need security, you can also use base64 which is not hash-function, has not fixed output and could be simply decoded by user, but looks more lightweight and could be used for hide values: http://www.webtoolkit.info/javascript-base64.html

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

check properties->java build path -> libraries. there should be no errors, in my case there was errors in the maven. once I put the required jar in the maven repo, it worked fine

A regular expression to exclude a word/string

Here's yet another way (using a negative look-ahead):

^/(?!ignoreme|ignoreme2|ignoremeN)([a-z0-9]+)$ 

Note: There's only one capturing expression: ([a-z0-9]+).

Difference between except: and except Exception as e: in Python

Another way to look at this. Check out the details of the exception:

In [49]: try: 
    ...:     open('file.DNE.txt') 
    ...: except Exception as  e: 
    ...:     print(dir(e)) 
    ...:                                                                                                                                    
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'with_traceback']

There are lots of "things" to access using the 'as e' syntax.

This code was solely meant to show the details of this instance.

How can I return NULL from a generic method in C#?

For completeness sake, it's good to know you could also do this:

return default;

It returns the same as return default(T);

What is the best way to find the users home directory in Java?

As I was searching for Scala version, all I could find was McDowell's JNA code above. I include my Scala port here, as there currently isn't anywhere more appropriate.

import com.sun.jna.platform.win32._
object jna {
    def getHome: java.io.File = {
        if (!com.sun.jna.Platform.isWindows()) {
            new java.io.File(System.getProperty("user.home"))
        }
        else {
            val pszPath: Array[Char] = new Array[Char](WinDef.MAX_PATH)
            new java.io.File(Shell32.INSTANCE.SHGetSpecialFolderPath(null, pszPath, ShlObj.CSIDL_MYDOCUMENTS, false) match {
                case true => new String(pszPath.takeWhile(c => c != '\0'))
                case _    => System.getProperty("user.home")
            })
        }
    }
}

As with the Java version, you will need to add Java Native Access, including both jar files, to your referenced libraries.

It's nice to see that JNA now makes this much easier than when the original code was posted.

Serving favicon.ico in ASP.NET MVC

1) You can put your favicon where you want and add this tag to your page head

<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />

although some browsers will try to get the favicon from /favicon.ico by default, so you should use the IgnoreRoute.

2) If a browser makes a request for the favicon in another directory it will get a 404 error wich is fine and if you have the link tag in answer 1 in your master page the browser will get the favicon you want.

Pass Array Parameter in SqlCommand

try it like this

StringBuilder sb = new StringBuilder(); 
foreach (ListItem item in ddlAge.Items) 
{ 
     if (item.Selected) 
     { 
          string sqlCommand = "SELECT * from TableA WHERE Age IN (@Age)"; 
          SqlConnection sqlCon = new SqlConnection(connectString); 
          SqlCommand sqlComm = new SqlCommand(); 
          sqlComm.Connection = sqlCon; 
          sqlComm.CommandType = System.Data.CommandType.Text; 
          sqlComm.CommandText = sqlCommand; 
          sqlComm.CommandTimeout = 300; 
          sqlComm.Parameters.Add("@Age", SqlDbType.NVarChar);
          sb.Append(item.Text + ","); 
          sqlComm.Parameters["@Age"].Value = sb.ToString().TrimEnd(',');
     } 
} 

Include jQuery in the JavaScript Console

The top answer, by jondavidjohn is good but I'd like to tweak it to address a couple of points:

  • Various browsers issue a warning when loading a script from http to a page on https.
  • Just changing jquery.com's protocol to https results in a warning if you try it straight from the browser's URL bar: This is probably not the site you are looking for!
  • I like to use Google's CDN when I'm using the console to experiment with Google sites such as Gmail.

My only issue is that I have to include a version number where in the console I really always want the latest.

var jq = document.createElement('script');
jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
jQuery.noConflict();

New line character in VB.Net?

In asp.net for giving new line character in string you should use <br> .

For window base application Environment.NewLine will work fine.

How to suppress scientific notation when printing float values?

In addition to SG's answer, you can also use the Decimal module:

from decimal import Decimal
x = str(Decimal(1) / Decimal(10000))

# x is a string '0.0001'

PHP code to remove everything but numbers

This is for future developers, you can also try this. Simple too

echo preg_replace('/\D/', '', '604-619-5135');

How to Upload Image file in Retrofit 2

It is quite easy. Here is the API Interface

public interface Api {

    @Multipart
    @POST("upload")
    Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);

}

And you can use the following code to make a call.

private void uploadFile(File file, String desc) {

        //creating request body for file
        RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
        RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);

        //The gson builder
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();


        //creating retrofit object
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        //creating our api 
        Api api = retrofit.create(Api.class);

        //creating a call and calling the upload image method 
        Call<MyResponse> call = api.uploadImage(requestFile, descBody);

        //finally performing the call 
        call.enqueue(new Callback<MyResponse>() {
            @Override
            public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
                if (!response.body().error) {
                    Toast.makeText(getApplicationContext(), "File Uploaded Successfully...", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<MyResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

Source: Retrofit Upload File Tutorial.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

I wrote a function for my own project to do this (it doesn't use numpy, though):

def partition(seq, chunks):
    """Splits the sequence into equal sized chunks and them as a list"""
    result = []
    for i in range(chunks):
        chunk = []
        for element in seq[i:len(seq):chunks]:
            chunk.append(element)
        result.append(chunk)
    return result

If you want the chunks to be randomized, just shuffle the list before passing it in.

Java: is there a map function?

Be very careful with Collections2.transform() from guava. That method's greatest advantage is also its greatest danger: its laziness.

Look at the documentation of Lists.transform(), which I believe applies also to Collections2.transform():

The function is applied lazily, invoked when needed. This is necessary for the returned list to be a view, but it means that the function will be applied many times for bulk operations like List.contains(java.lang.Object) and List.hashCode(). For this to perform well, function should be fast. To avoid lazy evaluation when the returned list doesn't need to be a view, copy the returned list into a new list of your choosing.

Also in the documentation of Collections2.transform() they mention you get a live view, that change in the source list affect the transformed list. This sort of behaviour can lead to difficult-to-track problems if the developer doesn't realize the way it works.

If you want a more classical "map", that will run once and once only, then you're better off with FluentIterable, also from Guava, which has an operation which is much more simple. Here is the google example for it:

FluentIterable
       .from(database.getClientList())
       .filter(activeInLastMonth())
       .transform(Functions.toStringFunction())
       .limit(10)
       .toList();

transform() here is the map method. It uses the same Function<> "callbacks" as Collections.transform(). The list you get back is read-only though, use copyInto() to get a read-write list.

Otherwise of course when java8 comes out with lambdas, this will be obsolete.

How to make a query with group_concat in sql server

This can also be achieved using the Scalar-Valued Function in MSSQL 2008
Declare your function as following,

CREATE FUNCTION [dbo].[FunctionName]
(@MaskId INT)
RETURNS Varchar(500) 
AS
BEGIN

    DECLARE @SchoolName varchar(500)                        

    SELECT @SchoolName =ISNULL(@SchoolName ,'')+ MD.maskdetail +', ' 
    FROM maskdetails MD WITH (NOLOCK)       
    AND MD.MaskId=@MaskId

    RETURN @SchoolName

END

And then your final query will be like

SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid 
ORDER BY m.maskname ;

Note: You may have to change the function, as I don't know the complete table structure.

What is a smart pointer and when should I use one?

A smart pointer is a pointer-like type with some additional functionality, e.g. automatic memory deallocation, reference counting etc.

A small intro is available on the page Smart Pointers - What, Why, Which?.

One of the simple smart-pointer types is std::auto_ptr (chapter 20.4.5 of C++ standard), which allows one to deallocate memory automatically when it out of scope and which is more robust than simple pointer usage when exceptions are thrown, although less flexible.

Another convenient type is boost::shared_ptr which implements reference counting and automatically deallocates memory when no references to the object remains. This helps avoiding memory leaks and is easy to use to implement RAII.

The subject is covered in depth in book "C++ Templates: The Complete Guide" by David Vandevoorde, Nicolai M. Josuttis, chapter Chapter 20. Smart Pointers. Some topics covered:

How to fix warning from date() in PHP"

Try to set date.timezone in php.ini file. Or you can manually set it using ini_set() or date_default_timezone_set().

Exclude Blank and NA in R

A good idea is to set all of the "" (blank cells) to NA before any further analysis.

If you are reading your input from a file, it is a good choice to cast all "" to NAs:

foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited

If you have already your table loaded, you can act as follows:

foo[foo==""] <- NA

Then to keep only rows with no NA you may just use na.omit():

foo <- na.omit(foo)

Or to keep columns with no NA:

foo <- foo[, colSums(is.na(foo)) == 0] 

C# if/then directives for debug vs release

Since the purpose of these COMPILER directives are to tell the compiler NOT to include code, debug code,beta code, or perhaps code that is needed by all of your end users, except say those the advertising department, i.e. #Define AdDept you want to be able include or remove them based on your needs. Without having to change your source code if for example a non AdDept merges into the AdDept. Then all that needs to be done is to include the #AdDept directive in the compiler options properties page of an existing version of the program and do a compile and wa la! the merged program's code springs alive!.

You might also want to use a declarative for a new process that is not ready for prime time or that can not be active in the code until it's time to release it.

Anyhow, that's the way I do it.

Mongoose: Get full list of users

To make function to wait for list to be fetched.

getArrayOfData() {
    return DataModel.find({}).then(function (storedDataArray) {
        return storedDataArray;
    }).catch(function(err){
        if (err) {
            throw new Error(err.message);
        }
    });
}

Generate random number between two numbers in JavaScript

ES6 / Arrow functions version based on Francis' code (i.e. the top answer):

const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

how to console.log result of this ajax call?

You could try something like this (copied from the jQuery Ajax examples)

var request = $.ajax({
  url: "script.php",
  type: "POST",
  data: {id : menuId},
  dataType: "html"
});

request.done(function(msg) {
  console.log( msg );
});

request.fail(function(jqXHR, textStatus) {
  console.log( "Request failed: " + textStatus );
});

The problem with your original code is that the error argument you pass into your on function isn't actually coming from anywhere. JQuery on doesn't return a second argument, and even if it did, it would relate to the click event not the Ajax call.

Use CSS to automatically add 'required field' asterisk to form inputs

input[required], select[required] {
    background-image: url('/img/star.png');
    background-repeat: no-repeat;
    background-position-x: right;
}

Image has some 20px space on the right not to overlap with select dropdown arrow

enter image description here

And it looks like this: enter image description here

Formatting PowerShell Get-Date inside string

Instead of using string interpolation you could simply format the DateTime using the ToString("u") method and concatenate that with the rest of the string:

$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u") 

How do I share a global variable between c files?

If you want to use global variable i of file1.c in file2.c, then below are the points to remember:

  1. main function shouldn't be there in file2.c
  2. now global variable i can be shared with file2.c by two ways:
    a) by declaring with extern keyword in file2.c i.e extern int i;
    b) by defining the variable i in a header file and including that header file in file2.c.

Define static method in source-file with declaration in header-file in C++

Keywords static and virtual should not be repeated in the definition. They should only be used in the class declaration.

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

This can also happen if you have a function with the same name as an object type in your signature. For example:

class func Player(playerObj: Player)

will cause the compiler to get confused (and rightfully so) since the compiler will first look locally within the file before looking at other files. So it looks at "Player" in the signature and thinks, that's not an object in this scope, but a function, so something is wrong.

Perhaps this is a good reason why I shouldn't capitalize class functions. :)

Assert a function/method was not called using Mock

You can check the called attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest, you can check the contents of call_args_list instead:

self.assertItemsEqual(my_var.call_args_list, [])

When it fails, it gives a message like this:

AssertionError: Element counts were not equal:
First has 0, Second has 1:  call('first argument', 4)

PL/SQL, how to escape single quote in a string?

You can use literal quoting:

stmt := q'[insert into MY_TBL (Col) values('ER0002')]';

Documentation for literals can be found here.

Alternatively, you can use two quotes to denote a single quote:

stmt := 'insert into MY_TBL (Col) values(''ER0002'')';

The literal quoting mechanism with the Q syntax is more flexible and readable, IMO.

How do I run a node.js app as a background service?

Since I'm missing this option in the list of provided answers I'd like to add an eligible option as of 2020: docker or any equivalent container platform. In addition to ensuring your application is working in a stable environment there are additional security benefits as well as improved portability.

There is docker support for Windows, macOS and most/major Linux distributions. Installing docker on a supported platform is rather straight-forward and well-documented. Setting up a Node.js application is as simple as putting it in a container and running that container while making sure its being restarted after shutdown.

Create Container Image

Assuming your application is available in /home/me/my-app on that server, create a text file Dockerfile in folder /home/me/my-app with content similar to this one:

FROM node:lts-alpine
COPY /my-app /app
CMD ["/app/server.js"]

Create the image using command like this:

docker build -t myapp-as-a-service /home/me

Note: Last parameter is selecting folder containing that Dockerfile instead of the Dockerfile itself. You may pick a different one using option -f.

Start Container

Use this command for starting the container:

docker run -d --restart always -p 80:3000 myapp-as-a-service

This command is assuming your app is listening on port 3000 and you want it to be exposed on port 80 of your host.

This is a very limited example for sure, but it's a good starting point.

URL string format for connecting to Oracle database with JDBC

Look here.

Your URL is quite incorrect. Should look like this:

url="jdbc:oracle:thin:@localhost:1521:orcl"

You don't register a driver class, either. You want to download the thin driver JAR, put it in your CLASSPATH, and make your code look more like this.

UPDATE: The "14" in "ojdbc14.jar" stands for JDK 1.4. You should match your driver version with the JDK you're running. I'm betting that means JDK 5 or 6.

How can I uninstall Ruby on ubuntu?

Why you are removing old version of the ruby?

rvm install 2.4.2 // version of ruby u need to insatll rvm use 2.4.2 --default // set ruby version you want use by default

Using rvm you can install multiple ruby version in the system

Please follow below steps install ruby using rvm

sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 
curl -sSL https://get.rvm.io | bash -s stable 
source ~/.rvm/scripts/rvm
rvm install 2.4.2 
rvm use 2.4.2 --default 
ruby -v

The installation step will change for different Ubuntu version

For more info,

https://gorails.com/setup/ubuntu/14.04

How to negate specific word in regex?

Unless performance is of utmost concern, it's often easier just to run your results through a second pass, skipping those that match the words you want to negate.

Regular expressions usually mean you're doing scripting or some sort of low-performance task anyway, so find a solution that is easy to read, easy to understand and easy to maintain.

Spark - SELECT WHERE or filtering?

According to spark documentation "where() is an alias for filter()"

filter(condition) Filters rows using the given condition. where() is an alias for filter().

Parameters: condition – a Column of types.BooleanType or a string of SQL expression.

>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]

>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]

FirebaseInstanceIdService is deprecated

Simply call this method to get the Firebase Messaging Token

public void getFirebaseMessagingToken ( ) {
        FirebaseMessaging.getInstance ().getToken ()
                .addOnCompleteListener ( task -> {
                    if (!task.isSuccessful ()) {
                        //Could not get FirebaseMessagingToken
                        return;
                    }
                    if (null != task.getResult ()) {
                        //Got FirebaseMessagingToken
                        String firebaseMessagingToken = Objects.requireNonNull ( task.getResult () );
                        //Use firebaseMessagingToken further
                    }
                } );
    }

The above code works well after adding this dependency in build.gradle file

implementation 'com.google.firebase:firebase-messaging:21.0.0'

Note: This is the code modification done for the above dependency to resolve deprecation. (Working code as of 1st November 2020)

How are booleans formatted in Strings in Python?

To update this for Python-3 you can do this

"{} {}".format(True, False)

However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.

>>> "{:<8} {}".format(True, False)
'1        False'

To get around this you can cast True as a string, e.g.

>>> "{:<8} {}".format(str(True), False)
'True     False'

How to declare a Fixed length Array in TypeScript

Actually, You can achieve this with current typescript:

type Grow<T, A extends Array<T>> = ((x: T, ...xs: A) => void) extends ((...a: infer X) => void) ? X : never;
type GrowToSize<T, A extends Array<T>, N extends number> = { 0: A, 1: GrowToSize<T, Grow<T, A>, N> }[A['length'] extends N ? 0 : 1];

export type FixedArray<T, N extends number> = GrowToSize<T, [], N>;

Examples:

// OK
const fixedArr3: FixedArray<string, 3> = ['a', 'b', 'c'];

// Error:
// Type '[string, string, string]' is not assignable to type '[string, string]'.
//   Types of property 'length' are incompatible.
//     Type '3' is not assignable to type '2'.ts(2322)
const fixedArr2: FixedArray<string, 2> = ['a', 'b', 'c'];

// Error:
// Property '3' is missing in type '[string, string, string]' but required in type 
// '[string, string, string, string]'.ts(2741)
const fixedArr4: FixedArray<string, 4> = ['a', 'b', 'c'];

EDIT (after a long time)

This should handle bigger sizes (as basically it grows array exponentially until we get to closest power of two):

type Shift<A extends Array<any>> = ((...args: A) => void) extends ((...args: [A[0], ...infer R]) => void) ? R : never;

type GrowExpRev<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : {
  0: GrowExpRev<[...A, ...P[0]], N, P>,
  1: GrowExpRev<A, N, Shift<P>>
}[[...A, ...P[0]][N] extends undefined ? 0 : 1];

type GrowExp<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : {
  0: GrowExp<[...A, ...A], N, [A, ...P]>,
  1: GrowExpRev<A, N, P>
}[[...A, ...A][N] extends undefined ? 0 : 1];

export type FixedSizeArray<T, N extends number> = N extends 0 ? [] : N extends 1 ? [T] : GrowExp<[T, T], N, [[T]]>;

How To: Best way to draw table in console app (C#)

It's easier in VisualBasic.net!

If you want the user to be able to manually enter data into a table:

Console.Write("Enter Data For Column 1: ")
    Dim Data1 As String = Console.ReadLine
    Console.Write("Enter Data For Column 2: ")
    Dim Data2 As String = Console.ReadLine

    Console.WriteLine("{0,-20} {1,-10} {2,-10}", "{Data Type}", "{Column 1}", "{Column 2}")
    Console.WriteLine("{0,-20} {1,-10} {2,-10}", "Data Entered:", Data1, Data2)

    Console.WriteLine("ENTER To Exit: ")
    Console.ReadLine()

It should look like this:

It should look like this (Click Me).

.NET unique object identifier

You can develop your own thing in a second. For instance:

   class Program
    {
        static void Main(string[] args)
        {
            var a = new object();
            var b = new object();
            Console.WriteLine("", a.GetId(), b.GetId());
        }
    }

    public static class MyExtensions
    {
        //this dictionary should use weak key references
        static Dictionary<object, int> d = new Dictionary<object,int>();
        static int gid = 0;

        public static int GetId(this object o)
        {
            if (d.ContainsKey(o)) return d[o];
            return d[o] = gid++;
        }
    }   

You can choose what you will like to have as unique ID on your own, for instance, System.Guid.NewGuid() or simply integer for fastest access.

Laravel 5: Retrieve JSON array from $request

As of Laravel 5.2+, you can fetch it directly with $request->input('item') as well.

Retrieving JSON Input Values

When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig deeper into JSON arrays:

$name = $request->input('user.name');

https://laravel.com/docs/5.2/requests

As noted above, the content-type header must be set to application/json so the jQuery ajax call would need to include contentType: "application/json",

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    dataType: "json",
    contentType: "application/json",
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

By fixing the AJAX call, $request->all() should work.

Select rows with same id but different value in another column

Select A.ARIDNR,A.LIEFNR
from Table A
join Table B
on A.ARIDNR = B.ARIDNR
and A.LIEFNR<> B.LIEFNR
group by A.ARIDNR,A.LIEFNR

SpringMVC RequestMapping for GET parameters

You can add @RequestMapping like so:

@RequestMapping("/userGrid")
public @ResponseBody GridModel getUsersForGrid(
   @RequestParam("_search") String search,
   @RequestParam String nd,
   @RequestParam int rows,
   @RequestParam int page,
   @RequestParam String sidx) 
   @RequestParam String sord) {

jQuery Select first and second td

jquery provides one more function: eq

Select first tr

$(".bootgrid-table tr").eq(0).addClass("black");

Select second tr

$(".bootgrid-table tr").eq(1).addClass("black");

WebAPI Multiple Put/Post parameters

If attribute routing is being used, you can use the [FromUri] and [FromBody] attributes.

Example:

[HttpPost()]
[Route("api/products/{id:int}")]
public HttpResponseMessage AddProduct([FromUri()] int id,  [FromBody()] Product product)
{
  // Add product
}

How to create an HTTPS server in Node.js?

You can use also archive this with the Fastify framework:

const { readFileSync } = require('fs')
const Fastify = require('fastify')

const fastify = Fastify({
  https: {
    key: readFileSync('./test/asset/server.key'),
    cert: readFileSync('./test/asset/server.cert')
  },
  logger: { level: 'debug' }
})

fastify.listen(8080)

(and run openssl req -nodes -new -x509 -keyout server.key -out server.cert to create the files if you need to write tests)

Difference between npx and npm?

NPM is a package manager, you can install node.js packages using NPM

NPX is a tool to execute node.js packages.

It doesn't matter whether you installed that package globally or locally. NPX will temporarily install it and run it. NPM also can run packages if you configure a package.json file and include it in the script section.

So remember this, if you want to check/run a node package quickly without installing locally or globally use NPX.

npM - Manager

npX - Execute - easy to remember

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

A feature rich Angular grid is this one:

trNgGrid

Some of its features:

  • Was built with simplicity in mind.
  • Is using plain HTML tables, allowing the browsers to optimize the rendering.
  • Fully declarative, preserving the separation of concerns, thus allowing you to fully describe it in HTML, without messing up your controllers.
  • Is fully customizable via templates and two-way data bound attributes.
  • Easy to maintain, having the code written in TypeScript.
  • Has a very short list of dependencies: AngularJs and Bootstrap CSS, with optional Bootswatch themes.

trNgGrid

Enjoy. Yes, I'm the author. I got fed up with all the Angular grids out there.

VSCode regex find & replace submatch math?

To augment Benjamin's answer with an example:

Find        Carrots(With)Dip(Are)Yummy
Replace     Bananas$1Mustard$2Gross
Result      BananasWithMustardAreGross

Anything in the parentheses can be a regular expression.

C# string reference type?

Actually it would have been the same for any object for that matter i.e. being a reference type and passing by reference are 2 different things in c#.

This would work, but that applies regardless of the type:

public static void TestI(ref string test)

Also about string being a reference type, its also a special one. Its designed to be immutable, so all of its methods won't modify the instance (they return a new one). It also has some extra things in it for performance.

Can't find AVD or SDK manager in Eclipse

I had similar problem after updating SDK from r20 to r21, but all I missed was the SDK/AVD Manager and running into this post while searching for the answer.

I managed to solve it by going to Window -> Customize Perspective, and under Command Groups Availability tab check the Android SDK and AVD Manager (not sure why it became unchecked because it was there before). I'm using Mac by the way, in case the menu option looks different.

Server Error in '/' Application. ASP.NET

Looks like this is a very generic message from iis. in my case we enabled integrated security on web config but forgot to change IIS app pool identity. Things to check -

  • go to event viewer on your server and check exact message.
  • -make sure your app pool and web config using same security(E.g Windows,integrated)

Note: this may not help every time but this might be one of the reason for above error message.

What is the default scope of a method in Java?

The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.

More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html

How to find which version of Oracle is installed on a Linux server (In terminal)

Login as sys user in sql*plus. Then do this query:

select * from v$version; 

or

select * from product_component_version;

How can I check for Python version in a program that uses new language features?

For standalone python scripts, the following module docstring trick to enforce a python version (here v2.7.x) works (tested on *nix).

#!/bin/sh
''''python -V 2>&1 | grep -q 2.7 && exec python -u -- "$0" ${1+"$@"}; echo "python 2.7.x missing"; exit 1 # '''

import sys
[...]

This should handle missing python executable as well but has a dependency on grep. See here for background.

Using CSS to affect div style inside iframe

The quick answer is: No, sorry.

It's not possible using just CSS. You basically need to have control over the iframe content in order to style it. There are methods using javascript or your web language of choice (which I've read a little about, but am not to familiar with myself) to insert some needed styles dynamically, but you would need direct control over the iframe content, which it sounds like you do not have.

How do I remove a single breakpoint with GDB?

Use:

clear fileName:lineNum   // Removes all breakpoints at the specified line.
delete breakpoint number // Delete one breakpoint whose number is 'number'

CodeIgniter Select Query

When use codeIgniter Framework then refer this active records link. how the data interact with structure and more.

The following functions allow you to build SQL SELECT statements.

Selecting Data

$this->db->get();

Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:

$query = $this->db->get('mytable');

With access to each row

$query = $this->db->get('mytable');

foreach ($query->result() as $row)
{
    echo $row->title;
}

Where clues

$this->db->get_where();

EG:

 $query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

Select field

$this->db->select('title, content, date');

$query = $this->db->get('mytable');

// Produces: SELECT title, content, date FROM mytable

E.G

$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE); 
$query = $this->db->get('mytable');

disable Bootstrap's Collapse open/close animation

For Bootstrap 3 and 4 it's

.collapsing {
    -webkit-transition: none;
    transition: none;
    display: none;
}

Circular dependency in Spring

In the codebase I'm working with (1 million + lines of code) we had a problem with long startup times, around 60 seconds. We were getting 12000+ FactoryBeanNotInitializedException.

What I did was set a conditional breakpoint in AbstractBeanFactory#doGetBean

catch (BeansException ex) {
   // Explicitly remove instance from singleton cache: It might have been put there
   // eagerly by the creation process, to allow for circular reference resolution.
   // Also remove any beans that received a temporary reference to the bean.
   destroySingleton(beanName);
   throw ex;
}

where it does destroySingleton(beanName) I printed the exception with conditional breakpoint code:

   System.out.println(ex);
   return false;

Apparently this happens when FactoryBeans are involved in a cyclic dependency graph. We solved it by implementing ApplicationContextAware and InitializingBean and manually injecting the beans.

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class A implements ApplicationContextAware, InitializingBean{

    private B cyclicDepenency;
    private ApplicationContext ctx;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        ctx = applicationContext;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        cyclicDepenency = ctx.getBean(B.class);
    }

    public void useCyclicDependency()
    {
        cyclicDepenency.doSomething();
    }
}

This cut down the startup time to around 15 secs.

So don't always assume that spring can be good at solving these references for you.

For this reason I'd recommend disabling cyclic dependency resolution with AbstractRefreshableApplicationContext#setAllowCircularReferences(false) to prevent many future problems.

How to properly make a http web GET request

Another way is using 'HttpClient' like this:

using System;
using System.Net;
using System.Net.Http;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Making API Call...");
            using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
            {
                client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
                HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
                response.EnsureSuccessStatusCode();
                string result = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Result: " + result);
            }
            Console.ReadLine();
        }
    }
}

Check HttpClient vs HttpWebRequest from stackoverflow and this from other.

Update June 22, 2020: It's not recommended to use httpclient in a 'using' block as it might cause port exhaustion.

private static HttpClient client = null;
    
ContructorMethod()
{
   if(client == null)
   {
        HttpClientHandler handler = new HttpClientHandler()
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        };        
        client = new HttpClient(handler);
   }
   client.BaseAddress = new Uri("https://api.stackexchange.com/2.2/");
   HttpResponseMessage response = client.GetAsync("answers?order=desc&sort=activity&site=stackoverflow").Result;
   response.EnsureSuccessStatusCode();
   string result = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine("Result: " + result);           
 }

If using .Net Core 2.1+, consider using IHttpClientFactory and injecting like this in your startup code.

 var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
            TimeSpan.FromSeconds(60));

 services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        }).AddPolicyHandler(request => timeout);

How to update fields in a model without creating a new record in django?

If you get a model instance from the database, then calling the save method will always update that instance. For example:

t = TemperatureData.objects.get(id=1)
t.value = 999  # change field
t.save() # this will update only

If your goal is prevent any INSERTs, then you can override the save method, test if the primary key exists and raise an exception. See the following for more detail:

Detect key input in Python

Key input is a predefined event. You can catch events by attaching event_sequence(s) to event_handle(s) by using one or multiple of the existing binding methods(bind, bind_class, tag_bind, bind_all). In order to do that:

  1. define an event_handle method
  2. pick an event(event_sequence) that fits your case from an events list

When an event happens, all of those binding methods implicitly calls the event_handle method while passing an Event object, which includes information about specifics of the event that happened, as the argument.

In order to detect the key input, one could first catch all the '<KeyPress>' or '<KeyRelease>' events and then find out the particular key used by making use of event.keysym attribute.

Below is an example using bind to catch both '<KeyPress>' and '<KeyRelease>' events on a particular widget(root):

try:                        # In order to be able to import tkinter for
    import tkinter as tk    # either in python 2 or in python 3
except ImportError:
    import Tkinter as tk


def event_handle(event):
    # Replace the window's title with event.type: input key
    root.title("{}: {}".format(str(event.type), event.keysym))


if __name__ == '__main__':
    root = tk.Tk()
    event_sequence = '<KeyPress>'
    root.bind(event_sequence, event_handle)
    root.bind('<KeyRelease>', event_handle)
    root.mainloop()

Read .csv file in C

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

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

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

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

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

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

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

    if(pFile == NULL)
        return RET_FAIL;

    while (!feof(pFile)) {

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

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

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


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

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

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

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

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

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

Converting Dictionary to List?

Converting from dict to list is made easy in Python. Three examples:

>> d = {'a': 'Arthur', 'b': 'Belling'}

>> d.items()
[('a', 'Arthur'), ('b', 'Belling')]

>> d.keys()
['a', 'b']

>> d.values()
['Arthur', 'Belling']

How to fix Python Numpy/Pandas installation?

I had this exact problem.

The issue is that there is an old version of numpy in the default mac install, and that pip install pandas sees that one first and fails -- not going on to see that there is a newer version that pip herself has installed.

If you're on a default mac install, and you've done pip install numpy --upgrade to be sure you're up to date, but pip install pandas still fails due to an old numpy, try the following:

$ cd /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/
$ sudo rm -r numpy
$ pip install pandas

This should now install / build pandas.

To check it out what we've done, do the following: start python, and import numpy and import pandas. With any luck, numpy.__version__ will be 1.6.2 (or greater), and pandas.__version__ will be 0.9.1 (or greater).

If you'd like to see where pip has put (found!) them, just print(numpy) and print(pandas).

Subtract two dates in SQL and get days of the result

How about

Select I.Fee
From Item I
WHERE  (days(GETDATE()) - days(I.DateCreated) < 365)

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

Execute SQL script from command line

You can do like this

sqlcmd -S <server Name> -U sa -P sapassword -i inputquery_file_name -o outputfile_name

From your command prompt run sqlcmd /? to get all the options you can use with sqlcmd utility

Sorting HashMap by values

You don't, basically. A HashMap is fundamentally unordered. Any patterns you might see in the ordering should not be relied on.

There are sorted maps such as TreeMap, but they traditionally sort by key rather than value. It's relatively unusual to sort by value - especially as multiple keys can have the same value.

Can you give more context for what you're trying to do? If you're really only storing numbers (as strings) for the keys, perhaps a SortedSet such as TreeSet would work for you?

Alternatively, you could store two separate collections encapsulated in a single class to update both at the same time?

Get value from hashmap based on key to JSTL

if all you're trying to do is get the value of a single entry in a map, there's no need to loop over any collection at all. simplifying gautum's response slightly, you can get the value of a named map entry as follows:

<c:out value="${map['key']}"/>

where 'map' is the collection and 'key' is the string key for which you're trying to extract the value.

Code signing is required for product type 'Application' in SDK 'iOS5.1'

TN2250 Tech document was retired,To resolve this add IOs5.1 or 8.1 sdk field under Anyios SDK field

in code sign problem will solved

how to loop through rows columns in excel VBA Macro

This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.

Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.

Sub Loop3()

Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String

Application.ScreenUpdating = False

'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row              'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column         'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead))  'assigns range for automation

ReDim frmlas(1)      'array assigned to formula strings
    'VOL column formula
frmlas(0) = "VOL FORMULA"
    'CAPACITY column formula
frmlas(1) = "CAP FORMULA"

For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then         'checks for volume formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula= frmlas(0)    'inserts volume formula
    Next j
ElseIf rng(0, i).Value = "Cap" Then     'checks for capacity formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula = frmlas(1)   'inserts capacity formula
    Next j
End If
Next i

Application.ScreenUpdating = True

End Sub

Best practice to look up Java Enum

The error message in IllegalArgumentException is already descriptive enough.

Your method makes a generic exception out of a specific one with the same message simply reworded. A developer would prefer the specific exception type and can handle the case appropriately instead of trying to handle RuntimeException.

If the intent is to make the message more user friendly, then references to values of enums is irrelevant to them anyway. Let the UI code determine what should be displayed to the user, and the UI developer would be better off with the IllegalArgumentException.

How to Deep clone in javascript

The Underscore.js contrib library library has a function called snapshot that deep clones an object

snippet from the source:

snapshot: function(obj) {
  if(obj == null || typeof(obj) != 'object') {
    return obj;
  }

  var temp = new obj.constructor();

  for(var key in obj) {
    if (obj.hasOwnProperty(key)) {
      temp[key] = _.snapshot(obj[key]);
    }
  }

  return temp;
}

once the library is linked to your project, invoke the function simply using

_.snapshot(object);

Laravel - Pass more than one variable to view

Just pass it as an array:

$data = [
    'name'  => 'Raphael',
    'age'   => 22,
    'email' => '[email protected]'
];

return View::make('user')->with($data);

Or chain them, like @Antonio mentioned.

What is the use of the @Temporal annotation in Hibernate?

If you're looking for short answer:

In the case of using java.util.Date, Java doesn't really know how to directly relate to SQL types. This is when @Temporal comes into play. It's used to specify the desired SQL type.

Source: Baeldung

Cannot create PoolableConnectionFactory

Go to my.ini file at the below path in windows C:\ProgramData\MySQL\MySQL Server 8.0\my.ini

and comment the below line

#bind-address=127.0.0.1

Then restart the MySQL server and connect.

Then you would be able to connect to MySQL from other IP address/machine.

Is it possible to serialize and deserialize a class in C++?

C++14 (C++17 recommended) boost prf

  • no macros
  • no code to be explicitly written

demo

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

Change position:absolute to position:fixed;.

Example can be found in this jsFiddle.

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

I'm using a similar code as those that use the while loop but I call the entry count in every loop... so I suppose it's somewhat slower

FragmentManager manager = getFragmentManager();
while (manager.getBackStackEntryCount() > 0){
        manager.popBackStackImmediate();
    }