Programs & Examples On #Magic function

How to remove "onclick" with JQuery?

I know this is quite old, but when a lost stranger finds this question looking for an answer (like I did) then this is the best way to do it, instead of using removeAttr():

$element.prop("onclick", null);

Citing jQuerys official doku:

"Removing an inline onclick event handler using .removeAttr() doesn't achieve the desired effect in Internet Explorer 6, 7, or 8. To avoid potential problems, use .prop() instead"

Clone() vs Copy constructor- which is recommended in java

Great sadness: neither Cloneable/clone nor a constructor are great solutions: I DON'T WANT TO KNOW THE IMPLEMENTING CLASS!!! (e.g. - I have a Map, which I want copied, using the same hidden MumbleMap implementation) I just want to make a copy, if doing so is supported. But, alas, Cloneable doesn't have the clone method on it, so there is nothing to which you can safely type-cast on which to invoke clone().

Whatever the best "copy object" library out there is, Oracle should make it a standard component of the next Java release (unless it already is, hidden somewhere).

Of course, if more of the library (e.g. - Collections) were immutable, this "copy" task would just go away. But then we would start designing Java programs with things like "class invariants" rather than the verdammt "bean" pattern (make a broken object and mutate until good [enough]).

Python logging: use milliseconds in time format

This should work too:

logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')

How to implement infinity in Java?

For the numeric wrapper types.

e.g Double.POSITVE_INFINITY

Hope this might help you.

Link to "pin it" on pinterest without generating a button

If you want to create a simple hyperlink instead of the pin it button,

Change this:

http://pinterest.com/pin/create/button/?url=

To this:

http://pinterest.com/pin/create/link/?url=

So, a complete URL might simply look like this:

<a href="//pinterest.com/pin/create/link/?url=http%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F&media=http%3A%2F%2Ffarm8.staticflickr.com%2F7027%2F6851755809_df5b2051c9_z.jpg&description=Next%20stop%3A%20Pinterest">Pin it</a>

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

Check if element exists in jQuery

Try to check the length of the selector, if it returns you something then the element must exists else not.

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}


 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

How to ignore whitespace in a regular expression subject string?

You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

/cats/ -> /c\s*a\s*t\s*s/

Javascript to display the current date and time

_x000D_
_x000D_
var today = new Date();
var day = today.getDay();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
console.log("Today is : " + daylist[day] + ".");
var hour = today.getHours();
var minute = today.getMinutes();
var second = today.getSeconds();
var prepand = (hour >= 12) ? " PM " : " AM ";
hour = (hour >= 12) ? hour - 12 : hour;
if (hour === 0 && prepand === ' PM ') {
  if (minute === 0 && second === 0) {
    hour = 12;
    prepand = ' Noon';
  } else {
    hour = 12;
    prepand = ' PM';
  }
}
if (hour === 0 && prepand === ' AM ') {
  if (minute === 0 && second === 0) {
    hour = 12;
    prepand = ' Midnight';
  } else {
    hour = 12;
    prepand = ' AM';
  }
}
console.log("Current Time : " + hour + prepand + " : " + minute + " : " + second);
_x000D_
_x000D_
_x000D_

Eloquent get only one column as an array

You can use the pluck method:

Word_relation::where('word_one', $word_id)->pluck('word_two')->toArray();

For more info on what methods are available for using with collection, you can you can check out the Laravel Documentation.

Can't use System.Windows.Forms

go to the side project panel, right click on references -> add reference and find System.Windows.Forms

Any time some error like this occurs (some namespace you added is missing that is obviously there) the solution is probably this - adding a reference.

This is needed because your default project does not include everything because you probably wont need it so it saves space. A good practice is to exclude things you're not using.

Convert Difference between 2 times into Milliseconds?

Try:

DateTime first;
DateTime second;

int milliSeconds = (int)((TimeSpan)(second - first)).TotalMilliseconds;

How do I pre-populate a jQuery Datepicker textbox with today's date?

var myDate = new Date();
var prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +
        myDate.getFullYear();
$("#date_pretty").val(prettyDate);

seemed to work, but there might be a better way out there..

Unable to launch the IIS Express Web server

I had the same problem after installing Visual Studio 2013 Update 3.
VS 2013 can not load Microsoft.VisualStudio.TraceLogPackage.dll
Unable to launch the IIS Express Web server

My problem solved by doing the following steps :

1. Repair Visual Studio 2013 Update 3
2. Start the Developer Command Prompt as administrator.
3. Type devenv.exe /setup then press enter

Best way to deploy Visual Studio application that can run without installing

First you need to publish the file by:

  1. BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go. Representation

  2. Save your file to a particular folder. Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj). In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files. (You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)

NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

How can I insert binary file data into a binary SQL field using a simple insert statement?

If you mean using a literal, you simply have to create a binary string:

insert into Files (FileId, FileData) values (1, 0x010203040506)

And you will have a record with a six byte value for the FileData field.


You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).

You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).


In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.

GitHub relative link in Markdown file

This question is pretty old, but it still seems important, as it isn't easy to put relative references from readme.md to wiki pages on Github.

I played around a little bit and this relative link seems to work pretty well:

[Your wiki page](../../wiki/your-wiki-page)

The two ../ will remove /blob/master/ and use your base as a starting point. I haven't tried this on other repositories than Github, though (there may be compatibility issues).

'tuple' object does not support item assignment

Tuples, in python can't have their values changed. If you'd like to change the contained values though I suggest using a list:

[1,2,3] not (1,2,3)

Is there a way to detach matplotlib plots so that the computation can continue?

My answer is a little off topic, but I just decided to get away from matplotlib in my application because of the problem that is stated in this question.

Alternatively, you can use plotly. It does not block the process.

Casting an int to a string in Python

Either:

"ME" + str(i)

Or:

"ME%d" % i

The second one is usually preferred, especially if you want to build a string from several tokens.

Sorting int array in descending order

For primitive array types, you would have to write a reverse sort algorithm:

Alternatively, you can convert your int[] to Integer[] and write a comparator:

public class IntegerComparator implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
}

or use Collections.reverseOrder() since it only works on non-primitive array types.

and finally,

Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1);
Arrays.sort(a2, new IntegerComparator()); // OR
// Arrays.sort(a2, Collections.reverseOrder());

//Unbox the array to primitive type
a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2);

Eclipse java debugging: source not found

I had similar problem with my eclipse maven project. I fought with this issue quite a long time then I tried to rebuild project with

mvn clean eclipse:eclipse

and it helped.

Note: Using this approach will confuse the m2e plugin since the two approaches are very different. m2e adds a virtual node to your project called "Maven Dependencies" and asks Maven to add all dependencies there.

mvn eclipse:eclipse, on the other hand, will create a lot of individual entries in the file .classpath. Eclipse will handle them as if you manually added JARs to your project.

Unless you know how the classpath in Eclipse works, this approach is not recommended.

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

Update in July 2020:

During the last 16 months, maybe the most notable change in the React community is React hooks.

According to what I observe, in order to gain better compatibility with functional components and hooks, projects (even those large ones) would tend to use:

  1. hook + async thunk (hook makes everything very flexible so you could actually place async thunk in where you want and use it as normal functions, for example, still write thunk in action.ts and then useDispatch() to trigger the thunk: https://stackoverflow.com/a/59991104/5256695),
  2. useRequest,
  3. GraphQL/Apollo useQuery useMutation
  4. react-fetching-library
  5. other popular choices of data fetching/API call libraries, tools, design patterns, etc

In comparison, redux-saga doesn't really provide significant benefit in most normal cases of API calls comparing to the above approaches for now, while increasing project complexity by introducing many saga files/generators (also because the last release v1.1.1 of redux-saga was on 18 Sep 2019, which was a long time ago).

But still, redux-saga provides some unique features such as racing effect and parallel requests. Therefore, if you need these special functionalities, redux-saga is still a good choice.


Original post in March 2019:

Just some personal experience:

  1. For coding style and readability, one of the most significant advantages of using redux-saga in the past is to avoid callback hell in redux-thunk — one does not need to use many nesting then/catch anymore. But now with the popularity of async/await thunk, one could also write async code in sync style when using redux-thunk, which may be regarded as an improvement in redux-thunk.

  2. One may need to write much more boilerplate codes when using redux-saga, especially in Typescript. For example, if one wants to implement a fetch async function, the data and error handling could be directly performed in one thunk unit in action.js with one single FETCH action. But in redux-saga, one may need to define FETCH_START, FETCH_SUCCESS and FETCH_FAILURE actions and all their related type-checks, because one of the features in redux-saga is to use this kind of rich “token” mechanism to create effects and instruct redux store for easy testing. Of course one could write a saga without using these actions, but that would make it similar to a thunk.

  3. In terms of the file structure, redux-saga seems to be more explicit in many cases. One could easily find an async related code in every sagas.ts, but in redux-thunk, one would need to see it in actions.

  4. Easy testing may be another weighted feature in redux-saga. This is truly convenient. But one thing that needs to be clarified is that redux-saga “call” test would not perform actual API call in testing, thus one would need to specify the sample result for the steps which may be used after the API call. Therefore before writing in redux-saga, it would be better to plan a saga and its corresponding sagas.spec.ts in detail.

  5. Redux-saga also provides many advanced features such as running tasks in parallel, concurrency helpers like takeLatest/takeEvery, fork/spawn, which are far more powerful than thunks.

In conclusion, personally, I would like to say: in many normal cases and small to medium size apps, go with async/await style redux-thunk. It would save you many boilerplate codes/actions/typedefs, and you would not need to switch around many different sagas.ts and maintain a specific sagas tree. But if you are developing a large app with much complex async logic and the need for features like concurrency/parallel pattern, or have a high demand for testing and maintenance (especially in test-driven development), redux-sagas would possibly save your life.

Anyway, redux-saga is not more difficult and complex than redux itself, and it does not have a so-called steep learning curve because it has well-limited core concepts and APIs. Spending a small amount of time learning redux-saga may benefit yourself one day in the future.

JavaScript variable number of arguments to function

Use the arguments object when inside the function to have access to all arguments passed in.

Does "\d" in regex mean a digit?

Info regarding .NET / C#:

Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets.

If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options.

Info: https://docs.microsoft.com/en-us/dotnet/standard/base-types/character-classes-in-regular-expressions#decimal-digit-character-d

Docker-Compose can't connect to Docker Daemon

Is there slight possibility you deleted default machine? But, first check if all files are there (OSX, similar on other systems)

brew install docker docker-compose docker-machine xhyve docker-machine-driver-xhyve
brew link docker docker-compose docker-machine xhyve docker-machine-driver-xhyve

sudo chown root:wheel /usr/local/opt/docker-machine-driver-xhyve/bin/docker-machine-driver-xhyve
sudo chmod u+s /usr/local/opt/docker-machine-driver-xhyve/bin/docker-machine-driver-xhyve

Also, install Docker App, as it much easier to maintain containers:

brew cask reinstall docker

ans start Docker app from finder (wait until service is fully started)

Then, check instalation with:

docker-machine ls

if no machines are present in list, create one and start it:

docker-machine create default
docker-machine start default

After this, build, compose and all other commands should work properly.

.Net picking wrong referenced assembly version

  1. Go to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG
  2. Find machine.config file
  3. open in notepad
  4. find conflict dll
  5. Remove this and save.

compilation assemblies

addassembly=dllName,Version=1.0.0000.0000 Culture=neutral,PublicKeyToken="QWEWQERWETERY"

assemblies compilation

works for me.

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

Usage depends on whether the component's parent has a layout manager or not.

  • setSize() -- use when a parent layout manager does not exist;
  • setPreferredSize() (also its related setMinimumSize and setMaximumSize) -- use when a parent layout manager exists.

The setSize() method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrames and JWindows) and things that are inside of scrolled panes. You also must call setSize() if you've got components inside a parent without a layout manager.

Generally, setPreferredSize() will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize() and setLocation() to position those components according to the layout's rules.

For example, a BorderLayout tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame, the size of the other components in the layout, and so on.

How to plot vectors in python using matplotlib

In order to match the vector lenght and angle with the x,y coordinates of the plot, you can use to following options to plt.quiver:

plt.figure(figsize=(5,2), dpi=100)
plt.quiver(0,0,250,100, angles='xy', scale_units='xy', scale=1)
plt.xlim(0,250)
plt.ylim(0,100)

Test iOS app on device without apple developer program or jailbreak

There's a way you can do this.

You will need ROOT access to edit the following file.

Navigate to /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk and open the file SDKSettings.plist.

In that file, expand DefaultProperties and change CODE_SIGNING_REQUIRED to NO, while you are there, you can also change ENTITLEMENTS_REQUIRED to NO also.

You will have to restart Xcode for the changes to take effect. Also, you must do this for every .sdk you want to be able to run on device.

Now, in your project settings, you can change Code Signing Identity to Don't Code Sign.

Your app should now build and install on your device successfully.

UPDATE:

There are some issues with iOS 5.1 SDK that this method may not work exactly the same. Any other updates will be listed here when they become available.

UPDATE:

You can find the correct path to SDKSettings.plist with xcrun.

xcrun --sdk iphoneos --show-sdk-path

New SDKSettings.plist location for the iOS 5.1 SDK:

/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/SDKSettings.plist

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

Following @Michelle Tilley solution, apparently it didn't work for me at first. Not sure why, maybe I am using chrome and different version of node. After did some minor tweaks, it is working for me now.

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

In case someone facing similar issue as mine, this might be helpful.

How can I get the image url in a Wordpress theme?

get_template_directory_uri();

This function will help you retrieve theme directory URI, and can be used with your images, your example below:

<img src="<?php echo get_template_directory_uri(); ?>/images/mindset.jpg" />

How to create JSON object Node.js

The other answers are helpful, but the JSON in your question isn't valid. I have formatted it to make it clearer below, note the missing single quote on line 24.

  1 {
  2     'Orientation Sensor':
  3     [
  4         {
  5             sampleTime: '1450632410296',
  6             data: '76.36731:3.4651554:0.5665419'
  7         },
  8         {
  9             sampleTime: '1450632410296',
 10             data: '78.15431:0.5247617:-0.20050584'
 11         }
 12     ],
 13     'Screen Orientation Sensor':
 14     [
 15         {
 16             sampleTime: '1450632410296',
 17             data: '255.0:-1.0:0.0'
 18         }
 19     ],
 20     'MPU6500 Gyroscope sensor UnCalibrated':
 21     [
 22         {
 23             sampleTime: '1450632410296',
 24             data: '-0.05006743:-0.013848438:-0.0063915867
 25         },
 26         {
 27             sampleTime: '1450632410296',
 28             data: '-0.051132694:-0.0127831735:-0.003325345'
 29         }
 30     ]
 31 }

There are a lot of great articles on how to manipulate objects in Javascript (whether using Node JS or a browser). I suggest here is a good place to start: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

test if event handler is bound to an element in jQuery

You can get this information from the data cache.

For example, log them to the console (firebug, ie8):

console.dir( $('#someElementId').data('events') );

or iterate them:

jQuery.each($('#someElementId').data('events'), function(i, event){

    jQuery.each(event, function(i, handler){

        console.log( handler.toString() );

    });

});

Another way is you can use the following bookmarklet but obviously this does not help at runtime.

Local package.json exists, but node_modules missing

This issue can also raise when you change your system password but not the same updated on your .npmrc file that exist on path C:\Users\user_name, so update your password there too.

please check on it and run npm install first and then npm start.

How to clear https proxy setting of NPM?

I had the same problem once.
Follow these steps to delete proxy values:

1.To delete proxy in npm:
(-g is Important)
npm config delete proxy -g
npm config delete http-proxy -g
npm config delete https-proxy -g

Check the npm config file using:
npm config list

2.To delete system proxy: set HTTP_PROXY=null set HTTPS_PROXY=null

Now close the command line and open it to refresh the variables(proxy).

Maven plugin not using Eclipse's proxy settings

Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Python method for reading keypress?

Figured it out by testing all the stuff by myself. Couldn't find any topics about it tho, so I'll just leave the solution here. This might not be the only or even the best solution, but it works for my purposes (within getch's limits) and is better than nothing.

Note: proper keyDown() which would recognize all the keys and actual key presses, is still valued.

Solution: using ord()-function to first turn the getch() into an integer (I guess they're virtual key codes, but not too sure) works fine, and then comparing the result to the actual number representing the wanted key. Also, if I needed to, I could add an extra chr() around the number returned so that it would convert it to a character. However, I'm using mostly down arrow, esc, etc. so converting those to a character would be stupid. Here's the final code:

from msvcrt import getch
while True:
    key = ord(getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        select()
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            moveDown()
        elif key == 72: #Up arrow
            moveUp()

Also if someone else needs to, you can easily find out the keycodes from google, or by using python and just pressing the key:

from msvcrt import getch
while True:
    print(ord(getch()))

How to use an output parameter in Java?

Thank you. I use passing in an object as a parameter. My Android code is below

    String oPerson= null;
    if (CheckAddress("5556", oPerson))
    {
        Toast.makeText(this, 
                "It's Match! " + oPerson,                   
                Toast.LENGTH_LONG).show();
    }

    private boolean CheckAddress(String iAddress, String oPerson)
{
    Cursor cAddress = mDbHelper.getAllContacts();
    String address = "";        
    if (cAddress.getCount() > 0) {
        cAddress.moveToFirst();
        while (cAddress.isAfterLast() == false) {
            address = cAddress.getString(2).toString();
            oPerson = cAddress.getString(1).toString(); 
            if(iAddress.indexOf(address) != -1)
            {
                Toast.makeText(this, 
                        "Person : " + oPerson,                  
                        Toast.LENGTH_LONG).show();
                System.out.println(oPerson);
                cAddress.close();
                return true;                    
            }
            else cAddress.moveToNext();
        }
    }
    cAddress.close();
    return false;
}

The result is

Person : John

It's Match! null

Actually, "It's Match! John"

Please check my mistake.

Using Spring MVC Test to unit test multipart POST request

Here's what worked for me, here I'm attaching a file to my EmailController under test. Also take a look at the postman screenshot on how I'm posting the data.

    @WebAppConfiguration
    @RunWith(SpringRunner.class)
    @SpringBootTest(
            classes = EmailControllerBootApplication.class
        )
    public class SendEmailTest {

        @Autowired
        private WebApplicationContext webApplicationContext;

        @Test
        public void testSend() throws Exception{
            String jsonStr = "{\"to\": [\"[email protected]\"],\"subject\": "
                    + "\"CDM - Spring Boot email service with attachment\","
                    + "\"body\": \"Email body will contain  test results, with screenshot\"}";

            Resource fileResource = new ClassPathResource(
                    "screen-shots/HomePage-attachment.png");

            assertNotNull(fileResource);

            MockMultipartFile firstFile = new MockMultipartFile( 
                       "attachments",fileResource.getFilename(),
                        MediaType.MULTIPART_FORM_DATA_VALUE,
                        fileResource.getInputStream());  
                        assertNotNull(firstFile);


            MockMvc mockMvc = MockMvcBuilders.
                  webAppContextSetup(webApplicationContext).build();

            mockMvc.perform(MockMvcRequestBuilders
                   .multipart("/api/v1/email/send")
                    .file(firstFile)
                    .param("data", jsonStr))
                    .andExpect(status().is(200));
            }
        }

Postman Request

get list of packages installed in Anaconda

For more conda list usage details:

usage: conda-script.py list [-h][-n ENVIRONMENT | -p PATH][--json] [-v] [-q]
[--show-channel-urls] [-c] [-f] [--explicit][--md5] [-e] [-r] [--no-pip][regex]

Composer update memory limit

If there's enough memory composer would internally consume it and run without any problem. No need to specifically tell the composer to do it.

Have you tried to increase your swap memory, coz it worked for me. I increased the swap memory to 4096Mb (4GB) and now it all looks great to me.

first use "sudo free" to see available memory and swap memory. and configure swap as,

For Debian:

sudo fallocate -l 4G /swapfile
sudo dd if=/dev/zero of=/swapfile bs=4096k count=1048
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

to make it permenant add this to /etc/fstab file, /swapfile swap swap defaults 0 0

For CentOS :

[root@myserver]:/# cd /var
[root@myserver]:/var# touch swap.img
[root@myserver]:/var# chmod 600 swap.img
[root@myserver]:/var# mkswap /var/swap.img

[root@myserver]:/var# dd if=/dev/zero of=/var/swap.img bs=4096k count=1000
[root@myserver]:/var# mkswap /var/swap.img 
[root@myserver]:/var# swapon /var/swap.img

you can increase your swap memory by changin bs= 1024k or 2048k or 8096k depending on your physical volume size. use 'swapon' and swapoff commands to see the difference.

check 'swappiness' (60 should do good,)

cat /proc/sys/vm/swappiness

Create folder with batch but only if it doesn't already exist

mkdir C:\VTS 2> NUL

create a folder called VTS and output A subdirectory or file TEST already exists to NUL.

or

(C:&(mkdir "C:\VTS" 2> NUL))&

change the drive letter to C:, mkdir, output error to NUL and run the next command.

Combine Multiple child rows into one row MYSQL

I appreciate the help, I do think I have found a solution if someone would comment on the effectiveness I would appreciate it. Essentially what I did is. I realize it is somewhat static in its implementation but I does what I need it to do (forgive incorrect syntax)

SELECT
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  Options1.Value
  Options2.Value
FROM ORDERED_ITEMS
LEFT JOIN (Ordered_Options as Options1)
    ON (Options1.Ordered_Item.ID = Ordered_Options.Ordered_Item_ID 
        AND Options1.Option_Number = 43)
LEFT JOIN (Ordered_Options as Options2)
    ON (Options2.Ordered_Item.ID = Ordered_Options.Ordered_Item_ID
        AND Options2.Option_Number = 44);

process.env.NODE_ENV is undefined

It is due to OS

In your package.json, make sure to have your scripts(Where app.js is your main js file to be executed & NODE_ENV is declared in a .env file).Eg:

"scripts": {
    "start": "node app.js",
    "dev": "nodemon server.js",
    "prod": "NODE_ENV=production & nodemon app.js"
  }

For windows

Also set up your .env file variable having NODE_ENV=development

If your .env file is in a folder for eg.config folder make sure to specify in app.js(your main js file)

const dotenv = require('dotenv'); dotenv.config({ path: './config/config.env' });

How to auto import the necessary classes in Android Studio with shortcut?

File -> Settings -> Keymap Change keymaps settings to your previous IDE to which you are familiar with

enter image description here

Show/Hide the console window of a C# console application

See my post here:

Show Console in Windows Application

You can make a Windows application (with or without the window) and show the console as desired. Using this method the console window never appears unless you explicitly show it. I use it for dual-mode applications that I want to run in either console or gui mode depending on how they are opened.

Angular routerLink does not navigate to the corresponding component

The links are wrong, you have to do this:

<ul class="nav navbar-nav item">
    <li>
        <a [routerLink]="['/home']" routerLinkActive="active">Home</a>
    </li>
    <li>
        <a [routerLink]="['/about']" routerLinkActive="active">About this
        </a>
    </li>
</ul>

You can read this tutorial

What does the "+" (plus sign) CSS selector mean?

It selects the next paragraph and indents the beginning of the paragraph from the left just as you might in Microsoft Word.

Could not obtain information about Windows NT group user

For me, the jobs were running under DOMAIN\Administrator and failing with the error message "The job failed. Unable to determine if the owner (DOMAIN\administrator) of job Agent history clean up: distribution has server access (reason: Could not obtain information about Windows NT group/user 'DOMAIN\administrator', error code 0x5. [SQLSTATE 42000] (Error 15404)). To fix this, I changed the owner of each failing job to sa. Worked flawlessly after that. The jobs were related to replication cleanup, but I'm unsure if they were manually added or were added as a part of the replication set-up - I wasn't involved with it, so I am not sure.

Is the NOLOCK (Sql Server hint) bad practice?

With NOLOCK hint, the transaction isolation level for the SELECT statement is READ UNCOMMITTED. This means that the query may see dirty and inconsistent data.

This is not a good idea to apply as a rule. Even if this dirty read behavior is OK for your mission critical web based application, a NOLOCK scan can cause 601 error which will terminate the query due to data movement as a result of lack of locking protection.

I suggest reading When Snapshot Isolation Helps and When It Hurts - the MSDN recommends using READ COMMITTED SNAPSHOT rather than SNAPSHOT under most circumstances.

How to copy file from HDFS to the local file system

1.- Remember the name you gave to the file and instead of using hdfs dfs -put. Use 'get' instead. See below.

$hdfs dfs -get /output-fileFolderName-In-hdfs

Python data structure sort list alphabetically

ListName.sort() will sort it alphabetically. You can add reverse=False/True in the brackets to reverse the order of items: ListName.sort(reverse=False)

PHP float with 2 decimal places: .00

You can use this simple function. number_format ()

    $num = 2214.56;

    // default english notation
    $english_format = number_format($num);
    // 2,215

    // French notation
    $format_francais = number_format($num, 2, ',', ' ');
    // 2 214,56

    $num1 = 2234.5688;

   // English notation with thousands separator
    $english_format_number = number_format($num1,2);
    // 2,234.57

    // english notation without thousands separator
    $english_format_number2 = number_format($num1, 2, '.', '');
    // 2234.57

How to configure a HTTP proxy for svn

There are two common approaches for this:

If you are on Windows, you can also write http-proxy- options to Windows Registry. It's pretty handy if you need to apply proxy settings in Active Directory environment via Group Policy Objects.

Getting raw SQL query string from PDO prepared statements

I need to log full query string after bind param so this is a piece in my code. Hope, it is useful for everyone hat has the same issue.

/**
 * 
 * @param string $str
 * @return string
 */
public function quote($str) {
    if (!is_array($str)) {
        return $this->pdo->quote($str);
    } else {
        $str = implode(',', array_map(function($v) {
                    return $this->quote($v);
                }, $str));

        if (empty($str)) {
            return 'NULL';
        }

        return $str;
    }
}

/**
 * 
 * @param string $query
 * @param array $params
 * @return string
 * @throws Exception
 */
public function interpolateQuery($query, $params) {
    $ps = preg_split("/'/is", $query);
    $pieces = [];
    $prev = null;
    foreach ($ps as $p) {
        $lastChar = substr($p, strlen($p) - 1);

        if ($lastChar != "\\") {
            if ($prev === null) {
                $pieces[] = $p;
            } else {
                $pieces[] = $prev . "'" . $p;
                $prev = null;
            }
        } else {
            $prev .= ($prev === null ? '' : "'") . $p;
        }
    }

    $arr = [];
    $indexQuestionMark = -1;
    $matches = [];

    for ($i = 0; $i < count($pieces); $i++) {
        if ($i % 2 !== 0) {
            $arr[] = "'" . $pieces[$i] . "'";
        } else {
            $st = '';
            $s = $pieces[$i];
            while (!empty($s)) {
                if (preg_match("/(\?|:[A-Z0-9_\-]+)/is", $s, $matches, PREG_OFFSET_CAPTURE)) {
                    $index = $matches[0][1];
                    $st .= substr($s, 0, $index);
                    $key = $matches[0][0];
                    $s = substr($s, $index + strlen($key));

                    if ($key == '?') {
                        $indexQuestionMark++;
                        if (array_key_exists($indexQuestionMark, $params)) {
                            $st .= $this->quote($params[$indexQuestionMark]);
                        } else {
                            throw new Exception('Wrong params in query at ' . $index);
                        }
                    } else {
                        if (array_key_exists($key, $params)) {
                            $st .= $this->quote($params[$key]);
                        } else {
                            throw new Exception('Wrong params in query with key ' . $key);
                        }
                    }
                } else {
                    $st .= $s;
                    $s = null;
                }
            }
            $arr[] = $st;
        }
    }

    return implode('', $arr);
}

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I recently ran into the same problem. I had to change my virtual hosts from:

<VirtualHost *:80>
  ServerName local.example.com

  DocumentRoot /home/example/public

  <Directory />
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

To:

<VirtualHost *:80>
  ServerName local.example.com

  DocumentRoot /home/example/public

  <Directory />
    Options All
    AllowOverride All
    Require all granted
  </Directory>
</VirtualHost>

Programmatically check Play Store for app updates

@Tarun answer was working perfectly.but now isnt ,due to the recent changes from Google on google play website.

Just change these from @Tarun answer..

class GetVersionCode extends AsyncTask<Void, String, String> {

    @Override

    protected String doInBackground(Void... voids) {

        String newVersion = null;

        try {
            Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName()  + "&hl=en")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get();
            if (document != null) {
                Elements element = document.getElementsContainingOwnText("Current Version");
                for (Element ele : element) {
                    if (ele.siblingElements() != null) {
                        Elements sibElemets = ele.siblingElements();
                        for (Element sibElemet : sibElemets) {
                            newVersion = sibElemet.text();
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newVersion;

    }


    @Override

    protected void onPostExecute(String onlineVersion) {

        super.onPostExecute(onlineVersion);

        if (onlineVersion != null && !onlineVersion.isEmpty()) {

            if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
                //show anything
            }

        }

        Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);

    }
}

and don't forget to add JSoup library

dependencies {
compile 'org.jsoup:jsoup:1.8.3'}

and on Oncreate()

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


    String currentVersion;
    try {
        currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    new GetVersionCode().execute();

}

that's it.. Thanks to this link

How to set the first option on a select box using jQuery?

Something like this should do the trick: https://jsfiddle.net/TmJCE/898/

$('#name2').change(function(){
    $('#name').prop('selectedIndex',0);
});


$('#name').change(function(){
    $('#name2').prop('selectedIndex',0);
});

Get the (last part of) current directory name in C#

You can also use the Uri class.

new Uri("file:///Users/smcho/filegen_from_directory/AIRPassthrough").Segments.Last()

You may prefer to use this class if you want to get some other segment, or if you want to do the same thing with a web address.

SystemError: Parent module '' not loaded, cannot perform relative import

I usually use this workaround:

try:
    from .mymodule import myclass
except Exception: #ImportError
    from mymodule import myclass

Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.

Using ADB to capture the screen

To start recording your device’s screen, run the following command:

adb shell screenrecord /sdcard/example.mp4

This command will start recording your device’s screen using the default settings and save the resulting video to a file at /sdcard/example.mp4 file on your device.

When you’re done recording, press Ctrl+C in the Command Prompt window to stop the screen recording. You can then find the screen recording file at the location you specified. Note that the screen recording is saved to your device’s internal storage, not to your computer.

The default settings are to use your device’s standard screen resolution, encode the video at a bitrate of 4Mbps, and set the maximum screen recording time to 180 seconds. For more information about the command-line options you can use, run the following command:

adb shell screenrecord --help

This works without rooting the device. Hope this helps.

Maximum call stack size exceeded on npm install

For those having this issue when building a Docker image with Jenkins (or any CI), make sure the package-lock.json is also copied to the container.

COPY ./src/package*.json /home/node/
RUN npm install

For us, the install actually went fine, the error only occurred when running npm prune production for the production image.

Spring MVC: How to return image in @ResponseBody?

You should specify the media type in the response. I'm using a @GetMapping annotation with produces = MediaType.IMAGE_JPEG_VALUE. @RequestMapping will work the same.

@GetMapping(value="/current/chart",produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public byte[] getChart() {
    return ...;
}

Without a media type, it is hard to guess what is actually returned (includes anybody who reads the code, browser and of course Spring itself). A byte[] is just not specific. The only way to determine the media type from a byte[] is sniffing and guessing around.

Providing a media type is just best practice

Displaying Windows command prompt output and redirecting it to a file

To expand on davor's answer, you can use PowerShell like this:

powershell "dir | tee test.txt"

If you're trying to redirect the output of an exe in the current directory, you need to use .\ on the filename, eg:

powershell ".\something.exe | tee test.txt"

Java abstract interface

Be aware that in Spring it has non academic meaning. The abstract interface is a warning to the developer not to use it for @Autowired. I hope that spring/eclipse @Autowired will look at this attribute and warn/fail about usages of such.

A real example: @Service proxy under @Transnational to a @Repository need to use same basic methods however they should use different interfaces that extends this abstract interface due to @Autowired. (I call this XXXSpec interface)

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

What is the LD_PRELOAD trick?

when LD_PRELOAD is used that file will be loaded before any other $export LD_PRELOAD=/path/lib lib to be pre loaded, even this can be used in programs too

Reset push notification settings for app

Doing it programmatically seems to work for me everytime. I have a build with the following line uncommented:

 [[UIApplication sharedApplication] unregisterForRemoteNotifications];

I run it every time I want to unregister from PN. You might have to end the app explicitly from the recents list and play around with the Notification Center in Settings app to get it right.

Also, the UI prompt asking the user to register for PN may not show up. Not sure if has been disabled in any of the recent iOS versions.

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

Read a text file in R line by line

Just use readLines on your file:

R> res <- readLines(system.file("DESCRIPTION", package="MASS"))
R> length(res)
[1] 27
R> res
 [1] "Package: MASS"                                                                  
 [2] "Priority: recommended"                                                          
 [3] "Version: 7.3-18"                                                                
 [4] "Date: 2012-05-28"                                                               
 [5] "Revision: $Rev: 3167 $"                                                         
 [6] "Depends: R (>= 2.14.0), grDevices, graphics, stats, utils"                      
 [7] "Suggests: lattice, nlme, nnet, survival"                                        
 [8] "Authors@R: c(person(\"Brian\", \"Ripley\", role = c(\"aut\", \"cre\", \"cph\"),"
 [9] "        email = \"[email protected]\"), person(\"Kurt\", \"Hornik\", role"  
[10] "        = \"trl\", comment = \"partial port ca 1998\"), person(\"Albrecht\","   
[11] "        \"Gebhardt\", role = \"trl\", comment = \"partial port ca 1998\"),"     
[12] "        person(\"David\", \"Firth\", role = \"ctb\"))"                          
[13] "Description: Functions and datasets to support Venables and Ripley,"            
[14] "        'Modern Applied Statistics with S' (4th edition, 2002)."                
[15] "Title: Support Functions and Datasets for Venables and Ripley's MASS"           
[16] "License: GPL-2 | GPL-3"                                                         
[17] "URL: http://www.stats.ox.ac.uk/pub/MASS4/"                                      
[18] "LazyData: yes"                                                                  
[19] "Packaged: 2012-05-28 08:47:38 UTC; ripley"                                      
[20] "Author: Brian Ripley [aut, cre, cph], Kurt Hornik [trl] (partial port"          
[21] "        ca 1998), Albrecht Gebhardt [trl] (partial port ca 1998), David"        
[22] "        Firth [ctb]"                                                            
[23] "Maintainer: Brian Ripley <[email protected]>"                               
[24] "Repository: CRAN"                                                               
[25] "Date/Publication: 2012-05-28 08:53:03"                                          
[26] "Built: R 2.15.1; x86_64-pc-mingw32; 2012-06-22 14:16:09 UTC; windows"           
[27] "Archs: i386, x64"                                                               
R> 

There is an entire manual devoted to this...

How to run Selenium WebDriver test cases in Chrome

All the previous answers are correct. Following is the little deep dive into the problem and solution.

The driver constructor in Selenium for example

WebDriver driver = new ChromeDriver();

searches for the driver executable, in this case the Google Chrome driver searches for a Chrome driver executable. In case the service is unable to find the executable, the exception is thrown.

This is where the exception comes from (note the check state method)

 /**
   *
   * @param exeName Name of the executable file to look for in PATH
   * @param exeProperty Name of a system property that specifies the path to the executable file
   * @param exeDocs The link to the driver documentation page
   * @param exeDownload The link to the driver download page
   *
   * @return The driver executable as a {@link File} object
   * @throws IllegalStateException If the executable not found or cannot be executed
   */
  protected static File findExecutable(
      String exeName,
      String exeProperty,
      String exeDocs,
      String exeDownload) {
    String defaultPath = new ExecutableFinder().find(exeName);
    String exePath = System.getProperty(exeProperty, defaultPath);
    checkState(exePath != null,
        "The path to the driver executable must be set by the %s system property;"
            + " for more information, see %s. "
            + "The latest version can be downloaded from %s",
            exeProperty, exeDocs, exeDownload);

    File exe = new File(exePath);
    checkExecutable(exe);
    return exe;
  }

The following is the check state method which throws the exception:

  /**
   * Ensures the truth of an expression involving the state of the calling instance, but not
   * involving any parameters to the calling method.
   *
   * <p>See {@link #checkState(boolean, String, Object...)} for details.
   */
  public static void checkState(
      boolean b,
      @Nullable String errorMessageTemplate,
      @Nullable Object p1,
      @Nullable Object p2,
      @Nullable Object p3) {
    if (!b) {
      throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3));
    }
  }

SOLUTION: set the system property before creating driver object as follows.

System.setProperty("webdriver.gecko.driver", "path/to/chromedriver.exe");
WebDriver driver = new ChromeDriver();

The following is the code snippet (for Chrome and Firefox) where the driver service searches for the driver executable:

Chrome:

   @Override
    protected File findDefaultExecutable() {
      return findExecutable("chromedriver", CHROME_DRIVER_EXE_PROPERTY,
          "https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver",
          "http://chromedriver.storage.googleapis.com/index.html");
    }

Firefox:

@Override
 protected File findDefaultExecutable() {
      return findExecutable(
        "geckodriver", GECKO_DRIVER_EXE_PROPERTY,
        "https://github.com/mozilla/geckodriver",
        "https://github.com/mozilla/geckodriver/releases");
    }

where CHROME_DRIVER_EXE_PROPERTY = "webdriver.chrome.driver" and GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver"

Similar is the case for other browsers, and the following is the snapshot of the list of the available browser implementation:

Enter image description here

Is it possible to set UIView border properties from interface builder?

You can make a category of UIView and add this in .h file of category

@property (nonatomic) IBInspectable UIColor *borderColor;
@property (nonatomic) IBInspectable CGFloat borderWidth;
@property (nonatomic) IBInspectable CGFloat cornerRadius;

Now add this in .m file

@dynamic borderColor,borderWidth,cornerRadius;

and this as well in . m file

-(void)setBorderColor:(UIColor *)borderColor{
    [self.layer setBorderColor:borderColor.CGColor];
}

-(void)setBorderWidth:(CGFloat)borderWidth{
    [self.layer setBorderWidth:borderWidth];
}

-(void)setCornerRadius:(CGFloat)cornerRadius{
    [self.layer setCornerRadius:cornerRadius];
}

now you will see this in your storyboard for all UIView subclasses (UILabel, UITextField, UIImageView etc)

enter image description here

Thats it.. No Need to import category anywhere, just add the category's files in the project and see these properties in the storyboard.

What is InputStream & Output Stream? Why and when do we use them?

From the Java Tutorial:

A stream is a sequence of data.

A program uses an input stream to read data from a source, one item at a time:

enter image description here

A program uses an output stream to write data to a destination, one item at time:

enter image description here

The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a network socket, or an array.

Sample code from oracle tutorial:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytes {
    public static void main(String[] args) throws IOException {

        FileInputStream in = null;
        FileOutputStream out = null;

        try {
            in = new FileInputStream("xanadu.txt");
            out = new FileOutputStream("outagain.txt");
            int c;

            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}

This program uses byte streams to copy xanadu.txt file to outagain.txt , by writing one byte at a time

Have a look at this SE question to know more details about advanced Character streams, which are wrappers on top of Byte Streams :

byte stream and character stream

Why do you need to invoke an anonymous function on the same line?

Anonymous functions are meant to be one-shot deal where you define a function on the fly so that it generates an output from you from an input that you are providing. Except that you did not provide the input. Instead, you wrote something on the second line ('SO'); - an independent statement that has nothing to do with the function. What did you expect? :)

How to concat string + i?

Let me add another solution:

>> N = 5;
>> f = cellstr(num2str((1:N)', 'f%d'))
f = 
    'f1'
    'f2'
    'f3'
    'f4'
    'f5'

If N is more than two digits long (>= 10), you will start getting extra spaces. Add a call to strtrim(f) to get rid of them.


As a bonus, there is an undocumented built-in function sprintfc which nicely returns a cell arrays of strings:

>> N = 10;
>> f = sprintfc('f%d', 1:N)
f = 
    'f1'    'f2'    'f3'    'f4'    'f5'    'f6'    'f7'    'f8'    'f9'    'f10'

When do you use POST and when do you use GET?

In PHP, POST data limit is usually set by your php.ini. GET is limited by server/browser settings I believe - usually around 255 bytes.

PLS-00201 - identifier must be declared

The procedure name should be in caps while creating procedure in database. You may use small letters for your procedure name while calling from Java class like:

String getDBUSERByUserIdSql = "{call getDBUSERByUserId(?,?,?,?)}";

In database the name of procedure should be:

GETDBUSERBYUSERID    -- (all letters in caps only)

This serves as one of the solutions for this problem.

og:type and valid values : constantly being parsed as og:type=website

I have moved into the world of namespace specific open graph data and therefore dont rely on the FB types. See "edit open graph" in the apps dev tool dashboard.

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

How to convert a list into data table

private DataTable CreateDataTable(IList<T> item)
{
    Type type = typeof(T);
    var properties = type.GetProperties();

    DataTable dataTable = new DataTable();
    foreach (PropertyInfo info in properties)
    {
        dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
    }

    foreach (T entity in item)
    {
        object[] values = new object[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            values[i] = properties[i].GetValue(entity);
        }

        dataTable.Rows.Add(values);
    }
    return dataTable;
}

How to change an image on click using CSS alone?

You could use an <a> tag with different styles:

a:link    { }
a:visited { }
a:hover   { }
a:active  { }

I'd recommend using that in conjunction with CSS sprites: https://css-tricks.com/css-sprites/

Mapping over values in a python dictionary

To avoid doing indexing from inside lambda, like:

rval = dict(map(lambda kv : (kv[0], ' '.join(kv[1])), rval.iteritems()))

You can also do:

rval = dict(map(lambda(k,v) : (k, ' '.join(v)), rval.iteritems()))

Set line spacing

If you want condensed lines, you can set same value for font-size and line-height

In your CSS file

.condensedlines {              
    font-size:   10pt;
    line-height: 10pt;  /* try also a bit smaller line-height */
}

In your HTML file

<p class="condensedlines">
bla bla bla bla bla bla <br>
bla bla bla bla bla bla <br>
bla bla bla bla bla bla <br>
</p>

--> Play with this snippet on jsfiddle.net

You can also increase line-height for fine line spacing control:

.mylinespacing {
    font-size:   10pt;
    line-height: 14pt; /* 14 = 10 + 2 above + 2 below */
}

How to get the current user in ASP.NET MVC

Try HttpContext.Current.User.

Public Shared Property Current() As System.Web.HttpContext
Member of System.Web.HttpContext

Summary:
Gets or sets the System.Web.HttpContext object for the current HTTP request.

Return Values:
The System.Web.HttpContext for the current HTTP request

jQuery "blinking highlight" effect on div?

You may want to look into jQuery UI. Specifically, the highlight effect:

http://jqueryui.com/demos/effect/

What's the regular expression that matches a square bracket?

does it work with an antislash before the [ ?

\[ or \\[ ?

How do I mock an autowired @Value field in Spring with Mockito?

Also note that I have no explicit "setter" methods (e.g. setDefaultUrl) in my class and I don't want to create any just for the purposes of testing.

One way to resolve this is change your class to use Constructor Injection, that is used for testing and Spring injection. No more reflection :)

So, you can pass any String using the constructor:

class MySpringClass {

    private final String defaultUrl;
    private final String defaultrPassword;

    public MySpringClass (
         @Value("#{myProps['default.url']}") String defaultUrl, 
         @Value("#{myProps['default.password']}") String defaultrPassword) {
        this.defaultUrl = defaultUrl;
        this.defaultrPassword= defaultrPassword;
    }

}

And in your test, just use it:

MySpringClass MySpringClass  = new MySpringClass("anyUrl", "anyPassword");

How to convert signed to unsigned integer in python

Assuming:

  1. You have 2's-complement representations in mind; and,
  2. By (unsigned long) you mean unsigned 32-bit integer,

then you just need to add 2**32 (or 1 << 32) to the negative value.

For example, apply this to -1:

>>> -1
-1
>>> _ + 2**32
4294967295L
>>> bin(_)
'0b11111111111111111111111111111111'

Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.

Nobody but you can say what your hidden assumptions are, though. If, for example, you have 1's-complement representations in mind, then you need to apply the ~ prefix operator instead. Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of "sign bits").

And to duplicate what the platform C compiler does, you can use the ctypes module:

>>> import ctypes
>>> ctypes.c_ulong(-1)  # stuff Python's -1 into a C unsigned long
c_ulong(4294967295L)
>>> _.value
4294967295L

C's unsigned long happens to be 4 bytes on the box that ran this sample.

Hexadecimal To Decimal in Shell Script

In dash and other shells, you can use

printf "%d\n" (your hexadecimal number)

to convert a hexadecimal number to decimal. This is not bash, or ksh, specific.

adb connection over tcp not working now

Try to do port forwarding,

adb forward tcp:<PC port> tcp:<device port>.

like:

adb forward tcp:5555 tcp:5555.

sounds like 5555 port is captured so use other one. As I know 7612 is empty

[Edit]

C:\Users\m>adb forward tcp:7612 tcp:7612

C:\Users\m>adb tcpip 7612
restarting in TCP mode port: 7612

C:\Users\m>adb connect 192.168.1.12
connected to 192.168.1.12:7612

Be sure that you connect to the right IP address. (You can download Network Info 2 to check your IP)

Java Replace Character At Specific Position Of String?

Kay!

First of all, when dealing with strings you have to refer to their positions in 0 base convention. This means that if you have a string like this:

String str = "hi";
//str length is equal 2 but the character
//'h' is in the position 0 and character 'i' is in the postion 1


With that in mind, the best way to tackle this problem is creating a method to replace a character at a given position in a string like this:

Method:

public String changeCharInPosition(int position, char ch, String str){
    char[] charArray = str.toCharArray();
    charArray[position] = ch;
    return new String(charArray);
}

Then you should call the method 'changeCharInPosition' in this way:

String str = "hi";
str = changeCharInPosition(1, 'k', str);
System.out.print(str); //this will return "hk"

If you have any questions, don't hesitate, post something!

MongoDB/Mongoose querying at a specific date?

That should work if the dates you saved in the DB are without time (just year, month, day).

Chances are that the dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day.

db.posts.find({ //query today up to tonight
    created_on: {
        $gte: new Date(2012, 7, 14), 
        $lt: new Date(2012, 7, 15)
    }
})

Calculate rolling / moving average in C++

One way can be to circularly store the values in the buffer array. and calculate average this way.

int j = (int) (counter % size);
buffer[j] = mostrecentvalue;
avg = (avg * size - buffer[j - 1 == -1 ? size - 1 : j - 1] + buffer[j]) / size;

counter++;

// buffer[j - 1 == -1 ? size - 1 : j - 1] is the oldest value stored

The whole thing runs in a loop where most recent value is dynamic.

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

Print a file, skipping the first X lines, in Bash

You can do this using the head and tail commands:

head -n <num> | tail -n <lines to print>

where num is 1e6 + the number of lines you want to print.

How to write a file or data to an S3 object using boto3

boto3 also has a method for uploading a file directly:

s3 = boto3.resource('s3')    
s3.Bucket('bucketname').upload_file('/local/file/here.txt','folder/sub/path/to/s3key')

http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.upload_file

C# 4.0 optional out/ref arguments

No.

A workaround is to overload with another method that doesn't have out / ref parameters, and which just calls your current method.

public bool SomeMethod(out string input)
{
    ...
}

// new overload
public bool SomeMethod()
{
    string temp;
    return SomeMethod(out temp);
}

If you have C# 7.0, you can simplify:

// new overload
public bool SomeMethod()
{
    return SomeMethod(out _);    // declare out as an inline discard variable
}

(Thanks @Oskar / @Reiner for pointing this out.)

How to compare character ignoring case in primitive types

You can't actually do the job quite right with toLowerCase, either on a string or in a character. The problem is that there are variant glyphs in either upper or lower case, and depending on whether you uppercase or lowercase your glyphs may or may not be preserved. It's not even clear what you mean when you say that two variants of a lower-case glyph are compared ignoring case: are they or are they not the same? (Note that there are also mixed-case glyphs: \u01c5, \u01c8, \u01cb, \u01f2 or ?, ?, ?, ?, but any method suggested here will work on those as long as they should count as the same as their fully upper or full lower case variants.)

There is an additional problem with using Char: there are some 80 code points not representable with a single Char that are upper/lower case variants (40 of each), at least as detected by Java's code point upper/lower casing. You therefore need to get the code points and change the case on these.

But code points don't help with the variant glyphs.

Anyway, here's a complete list of the glyphs that are problematic due to variants, showing how they fare against 6 variant methods:

  1. Character toLowerCase
  2. Character toUpperCase
  3. String toLowerCase
  4. String toUpperCase
  5. String equalsIgnoreCase
  6. Character toLowerCase(toUpperCase) (or vice versa)

For these methods, S means that the variants are treated the same as each other, D means the variants are treated as different from each other.

Behavior     Unicode                             Glyphs
===========  ==================================  =========
1 2 3 4 5 6  Upper  Lower  Var Up Var Lo Vr Lo2  U L u l l2
- - - - - -  ------ ------ ------ ------ ------  - - - - -
D D D D S S  \u0049 \u0069 \u0130 \u0131         I i I i   
S D S D S S  \u004b \u006b \u212a                K k K     
D S D S S S  \u0053 \u0073        \u017f         S s   ?   
D S D S S S  \u039c \u03bc        \u00b5         ? µ   µ   
S D S D S S  \u00c5 \u00e5 \u212b                Å å Å     
D S D S S S  \u0399 \u03b9        \u0345 \u1fbe  ? ?   ? ? 
D S D S S S  \u0392 \u03b2        \u03d0         ? ß   ?   
D S D S S S  \u0395 \u03b5        \u03f5         ? e   ?   
D D D D S S  \u0398 \u03b8 \u03f4 \u03d1         T ? ? ?   
D S D S S S  \u039a \u03ba        \u03f0         ? ?   ?   
D S D S S S  \u03a0 \u03c0        \u03d6         ? p   ?   
D S D S S S  \u03a1 \u03c1        \u03f1         ? ?   ?   
D S D S S S  \u03a3 \u03c3        \u03c2         S s   ?   
D S D S S S  \u03a6 \u03c6        \u03d5         F f   ?   
S D S D S S  \u03a9 \u03c9 \u2126                O ? ?     
D S D S S S  \u1e60 \u1e61        \u1e9b         ? ?   ?   

Complicating this still further is that there is no way to get the Turkish I's right (i.e. the dotted versions are different than the undotted versions) unless you know you're in Turkish; none of these methods give correct behavior and cannot unless you know the locale (i.e. non-Turkish: i and I are the same ignoring case; Turkish, not).

Overall, using toUpperCase gives you the closest approximation, since you have only five uppercase variants (or four, not counting Turkish).

You can also try to specifically intercept those five troublesome cases and call toUpperCase(toLowerCase(c)) on them alone. If you choose your guards carefully (just toUpperCase if c < 0x130 || c > 0x212B, then work through the other alternatives) you can get only a ~20% speed penalty for characters in the low range (as compared to ~4x if you convert single characters to strings and equalsIgnoreCase them) and only about a 2x penalty if you have a lot in the danger zone. You still have the locale problem with dotted I, but otherwise you're in decent shape. Of course if you can use equalsIgnoreCase on a larger string, you're better off doing that.

Here is sample Scala code that does the job:

def elevateCase(c: Char): Char = {
  if (c < 0x130 || c > 0x212B) Character.toUpperCase(c)
  else if (c == 0x130 || c == 0x3F4 || c == 0x2126 || c >= 0x212A)
    Character.toUpperCase(Character.toLowerCase(c))
  else Character.toUpperCase(c)
}

Count characters in textarea

$(document).ready(function() {
    var count = $("h1").text().length;
    alert(count);
});

Also, you can put your own element id or class instead of "h1" and length event count your characters of text area string ?

How to bundle an Angular app for production

As of today I still find the Ahead-of-Time Compilation cookbook as the best recipe for production bundling. You can find it here: https://angular.io/docs/ts/latest/cookbook/aot-compiler.html

My experience with Angular 2 so far is that AoT creates the smallest builds with almost no loading time. And most important as the question here is about - you only need to ship a few files to production.

This seems to be because the Angular compiler will not be shipped with the production builds as the templates are compiled "Ahead of Time". It's also very cool to see your HTML template markup transformed to javascript instructions that would be very hard to reverse engineer into the original HTML.

I've made a simple video where I demonstrate download size, number of files etc. for an Angular 2 app in dev vs AoT build - which you can see here:

https://youtu.be/ZoZDCgQwnmQ

You'll find the source code used in the video here:

https://github.com/fintechneo/angular2-templates

Jquery $.ajax fails in IE on cross domain calls

@Furqan Could you please let me know whether you tested this with HTTP POST method,

Since I am also working on the same kind of situation, but I am not able to POST the data to different domain.

But after reading this it was quite simple...only thing is you have to forget about OLD browsers. I am giving code to send with POST method from same above URL for quick reference

function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
    xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
    xhr = new XDomainRequest();
    xhr.open(method, url);
} else {
    xhr = null;
}
return xhr;
}

var request = createCORSRequest("POST", "http://www.sanshark.com/");
var content = "name=sandesh&lastname=daddi";
if (request){
    request.onload = function(){
    //do something with request.responseText
   alert(request.responseText);
};

 request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.setRequestHeader("Content-length", content.length);
            request.send(content);
}

Windows recursive grep command-line

Recursive search for import word inside src folder:

> findstr /s import .\src\*

what is Ljava.lang.String;@

I also met this problem when I've made ListView for android app:

Map<String, Object> m;

for(int i=0; i < dates.length; i++){
    m = new HashMap<String, Object>();
    m.put(ATTR_DATES, dates[i]);
    m.put(ATTR_SQUATS, squats[i]);
    m.put(ATTR_BP, benchpress[i]);
    m.put(ATTR_ROW, row[i]);
    data.add(m);
}

The problem was that I've forgotten to use the [i] index inside the loop

Keep only date part when using pandas.to_datetime

This worked for me on UTC Timestamp (2020-08-19T09:12:57.945888)

for di, i in enumerate(df['YourColumnName']):
    df['YourColumnName'][di] = pd.Timestamp(i)

How do I convert an Array to a List<object> in C#?

The List<> constructor can accept anything which implements IEnumerable, therefore...

        object[] testArray = new object[] { "blah", "blah2" };
        List<object> testList = new List<object>(testArray);

Jquery If radio button is checked

This will listen to the changed event. I have tried the answers from others but those did not work for me and finally, this one worked.

$('input:radio[name="postage"]').change(function(){
    if($(this).is(":checked")){
        alert("lksdahflk");
    }
});

How to resolve git's "not something we can merge" error

It's a silly suggestion, but make sure there is no typo in the branch name!

Display a view from another controller in ASP.NET MVC

With this code you can obtain any controller:

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, 
controller);

Reading file using fscanf() in C

First of all, you're testing fp twice. so printf("Error Reading File\n"); never gets executed.

Then, the output of fscanf should be equal to 2 since you're reading two values.

Using Environment Variables with Vue.js

For those using Vue CLI 3 and the webpack-simple install, Aaron's answer did work for me however I wasn't keen on adding my environment variables to my webpack.config.js as I wanted to commit it to GitHub. Instead I installed the dotenv-webpack plugin and this appears to load environment variables fine from a .env file at the root of the project without the need to prepend VUE_APP_ to the environment variables.

C# difference between == and Equals()

When comparing an object reference to a string (even if the object reference refers to a string), the special behavior of the == operator specific to the string class is ignored.

Normally (when not dealing with strings, that is), Equals compares values, while == compares object references. If two objects you are comparing are referring to the same exact instance of an object, then both will return true, but if one has the same content and came from a different source (is a separate instance with the same data), only Equals will return true. However, as noted in the comments, string is a special case because it overrides the == operator so that when dealing purely with string references (and not object references), only the values are compared even if they are separate instances. The following code illustrates the subtle differences in behaviors:

string s1 = "test";
string s2 = "test";
string s3 = "test1".Substring(0, 4);
object s4 = s3;

Console.WriteLine($"{object.ReferenceEquals(s1, s2)} {s1 == s2} {s1.Equals(s2)}");
Console.WriteLine($"{object.ReferenceEquals(s1, s3)} {s1 == s3} {s1.Equals(s3)}");
Console.WriteLine($"{object.ReferenceEquals(s1, s4)} {s1 == s4} {s1.Equals(s4)}");

The output is:

True True True
False True True
False False True

How to position the div popup dialog to the center of browser screen?

You can use CSS3 'transform':

CSS:

.popup-bck{
  background-color: rgba(102, 102, 102, .5);
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 10;
}
.popup-content-box{
  background-color: white;
  position: fixed;
  top: 50%;
  left: 50%;
  z-index: 11;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

HTML:

<div class="popup-bck"></div>
<div class="popup-content-box">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. 
</div>

*so you don't have to use margin-left: -width/2 px;

jQuery Find and List all LI elements within a UL within a specific DIV

$('li[rel=7]').siblings().andSelf();

// or:

$('li[rel=7]').parent().children();

Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:

var rels = [];

$('ul').each(function() {
    var localRels = [];

    $(this).find('li').each(function(){
        localRels.push( $(this).attr('rel') );
    });

    rels.push(localRels);
});

PHP how to get value from array if key is in a variable

As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.

    protected function _getArrayValue($array, $key, $default = null)
    {
        if (isset($array[$key])) return $array[$key];
        return $default;
    }

hope it helps.

Read text file into string. C++ ifstream

It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

What's the difference between process.cwd() vs __dirname?

process.cwd() returns the current working directory,

i.e. the directory from which you invoked the node command.

__dirname returns the directory name of the directory containing the JavaScript source code file

Catch an exception thrown by an async void method

The exception can be caught in the async function.

public async void Foo()
{
    try
    {
        var x = await DoSomethingAsync();
        /* Handle the result, but sometimes an exception might be thrown
           For example, DoSomethingAsync get's data from the network
           and the data is invalid... a ProtocolException might be thrown */
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught here */
    }
}

public void DoFoo()
{
    Foo();
}

How to change lowercase chars to uppercase using the 'keyup' event?

The only issue with changing user input on the fly like this is how disconcerting it can look to the end user (they'll briefly see the lowercase chars jump to uppercase).

What you may want to consider instead is applying the following CSS style to the input field:

text-transform: uppercase;

That way, any text entered always appears in uppercase. The only drawback is that this is a purely visual change - the value of the input control (when viewed in the code behind) will retain the case as it was originally entered.

Simple to get around this though, force the input val() .toUpperCase(); then you've got the best of both worlds.

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

dtList  = dtList.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList()

I assumed empty string and whitespace are like null. If not you can use IsNullOrEmpty (allow whitespace), or s != null

Array formula on Excel for Mac


Select the range, press CONTROL+U and then press ?+RETURN.


How to find the sum of an array of numbers

A simple method example:

function add(array){
    var arraylength = array.length;
    var sum = 0;
    for(var timesToMultiply = 0; timesToMultiply<arraylength; timesToMultiply++){
        sum += array[timesToMultiply];
    }

    return sum;
}

console.log(add([1, 2, 3, 4]));

How to get an object's methods?

Remember that technically javascript objects don't have methods. They have properties, some of which may be function objects. That means that you can enumerate the methods in an object just like you can enumerate the properties. This (or something close to this) should work:

var bar
for (bar in foo)
{
    console.log("Foo has property " + bar);
}

There are complications to this because some properties of objects aren't enumerable so you won't be able to find every function on the object.

How do I install soap extension?

In ubuntu to install php_soap on PHP7 use below commands. Reference

sudo apt-get install php7.0-soap
sudo systemctl restart apache2.service

For older version of php use below command and restart apache.

apt-get install php-soap

Colorized grep -- viewing the entire file with highlighted matches

Alternatively you can use The Silver Searcher and do

ag <search> --passthrough

Code for a simple JavaScript countdown timer?

_x000D_
_x000D_
// Javascript Countdown_x000D_
// Version 1.01 6/7/07 (1/20/2000)_x000D_
// by TDavid at http://www.tdscripts.com/_x000D_
var now = new Date();_x000D_
var theevent = new Date("Sep 29 2007 00:00:01");_x000D_
var seconds = (theevent - now) / 1000;_x000D_
var minutes = seconds / 60;_x000D_
var hours = minutes / 60;_x000D_
var days = hours / 24;_x000D_
ID = window.setTimeout("update();", 1000);_x000D_
_x000D_
function update() {_x000D_
  now = new Date();_x000D_
  seconds = (theevent - now) / 1000;_x000D_
  seconds = Math.round(seconds);_x000D_
  minutes = seconds / 60;_x000D_
  minutes = Math.round(minutes);_x000D_
  hours = minutes / 60;_x000D_
  hours = Math.round(hours);_x000D_
  days = hours / 24;_x000D_
  days = Math.round(days);_x000D_
  document.form1.days.value = days;_x000D_
  document.form1.hours.value = hours;_x000D_
  document.form1.minutes.value = minutes;_x000D_
  document.form1.seconds.value = seconds;_x000D_
  ID = window.setTimeout("update();", 1000);_x000D_
}
_x000D_
<p><font face="Arial" size="3">Countdown To January 31, 2000, at 12:00: </font>_x000D_
</p>_x000D_
<form name="form1">_x000D_
  <p>Days_x000D_
    <input type="text" name="days" value="0" size="3">Hours_x000D_
    <input type="text" name="hours" value="0" size="4">Minutes_x000D_
    <input type="text" name="minutes" value="0" size="7">Seconds_x000D_
    <input type="text" name="seconds" value="0" size="7">_x000D_
  </p>_x000D_
</form>
_x000D_
_x000D_
_x000D_

PHP regular expression - filter number only

You can try that one:

$string = preg_replace('/[^0-9]/', '', $string);

Cheers.

Issue with background color in JavaFX 8

Both these work for me. Maybe post a complete example?

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class PaneBackgroundTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane root = new BorderPane();
        VBox vbox = new VBox();
        root.setCenter(vbox);

        ToggleButton toggle = new ToggleButton("Toggle color");
        HBox controls = new HBox(5, toggle);
        controls.setAlignment(Pos.CENTER);
        root.setBottom(controls);

//        vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
//                .then("-fx-background-color: cornflowerblue;")
//                .otherwise("-fx-background-color: white;"));

        vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
                .then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
                .otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

Just a note for anyone who stumbles upon this:

If you are trying to SSH with a key that has been shared with you, for example:

ssh -i /path/to/keyfile.pem user@some-host

Where keyfile.pem is the private/public key shared with you and you're using it to connect, make sure you save it into ~/.ssh/ and chmod 777.

Trying to use the file when it was saved elsewhere on my machine was giving the OP's error. Not sure if it is directly related.

What is the maximum number of characters that nvarchar(MAX) will hold?

2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).

nchar and nvarchar

Fetch frame count with ffmpeg

Sorry for the necro answer, but maybe will need this (as I didn't found a solution for recent ffmpeg releases.

With ffmpeg 3.3.4 I found one can find with the following:

ffprobe -i video.mp4 -show_streams -hide_banner | grep "nb_frames"

At the end it will output frame count. It worked for me on videos with audio. It gives twice a "nb_frames" line, though, but the first line was the actual frame count on the videos I tested.

Using Gradle to build a jar with dependencies

Update: In newer Gradle versions (4+) the compile qualifier is deprecated in favour of the new api and implementation configurations. If you use these, the following should work for you:

// Include dependent libraries in archive.
mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

  from {
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

For older gradle versions, or if you still use the "compile" qualifier for your dependencies, this should work:

// Include dependent libraries in archive.
mainClassName = "com.company.application.Main"

jar {
  manifest { 
    attributes "Main-Class": "$mainClassName"
  }  

  from {
    configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
  }
}

Note that mainClassName must appear BEFORE jar {.

How to make EditText not editable through XML in Android?

if you want to click it, but not want to edit it, try:

        android:focusable="false"

How to read a file without newlines?

def getText():
    file=open("ex1.txt","r");

    names=file.read().split("\n");
    for x,word in enumerate(names):
        if(len(word)>=20):
            return 0;
            print "length of ",word,"is over 20"
            break;
        if(x==20):
            return 0;
            break;
    else:
        return names;


def show(names):
    for word in names:
        len_set=len(set(word))
        print word," ",len_set


for i in range(1):

    names=getText();
    if(names!=0):
        show(names);
    else:
        break;

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

How to recover MySQL database from .myd, .myi, .frm files

Simple! Create a dummy database (say abc)

Copy all these .myd, .myi, .frm files to mysql\data\abc wherein mysql\data\ is the place where .myd, .myi, .frm for all databases are stored.

Then go to phpMyadmin, go to db abc and you find your database.

Asynchronously load images with jQuery

IF YOU REALLY NEED TO USE AJAX...

I came accross usecases where the onload handlers were not the right choice. In my case when printing via javascript. So there are actually two options to use AJAX style for this:

Solution 1

Use Base64 image data and a REST image service. If you have your own webservice, you can add a JSP/PHP REST script that offers images in Base64 encoding. Now how is that useful? I came across a cool new syntax for image encoding:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE..."/>

So you can load the Image Base64 data using Ajax and then on completion you build the Base64 data string to the image! Great fun :). I recommend to use this site http://www.freeformatter.com/base64-encoder.html for image encoding.

$.ajax({ 
    url : 'BASE64_IMAGE_REST_URL', 
    processData : false,
}).always(function(b64data){
    $("#IMAGE_ID").attr("src", "data:image/png;base64,"+b64data);
});

Solution2:

Trick the browser to use its cache. This gives you a nice fadeIn() when the resource is in the browsers cache:

var url = 'IMAGE_URL';
$.ajax({ 
    url : url, 
    cache: true,
    processData : false,
}).always(function(){
    $("#IMAGE_ID").attr("src", url).fadeIn();
});   

However, both methods have its drawbacks: The first one only works on modern browsers. The second one has performance glitches and relies on assumption how the cache will be used.

cheers, will

SSIS expression: convert date to string

If, like me, you are trying to use GETDATE() within an expression and have the seemingly unreasonable requirement (SSIS/SSDT seems very much a work in progress to me, and not a polished offering) of wanting that date to get inserted into SQL Server as a valid date (type = datetime), then I found this expression to work:

@[User::someVar] = (DT_WSTR,4)YEAR(GETDATE()) + "-"  + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-"  + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " " + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)

I found this code snippet HERE

How do I query between two dates using MySQL?

Just Cast date_field as date

SELECT * FROM `objects` 
WHERE (cast(date_field as date) BETWEEN '2010-09-29' AND 
'2010-01-30' )

How SID is different from Service name in Oracle tnsnames.ora

what is a SID and Service name

please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm

In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)"

When I have to use one or another? Why do I need two of them?

Consider below mapping in a RAC Environment,

SID      SERVICE_NAME
bob1    bob
bob2    bob
bob3    bob
bob4    bob

if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME.

Please refer, https://community.oracle.com/thread/4049517

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

If you are editing HTML in Notepad you should use "Save As" and alter the default "Encoding:" selection at the botom of the dialog to UTF-8. you should also include-

_x000D_
_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
_x000D_
_x000D_
_x000D_

This un-ambiguously sets the correct character set and informs the browser.

How to duplicate a git repository? (without forking)

Open Terminal.

Create a bare clone of the repository.

git clone --bare https://github.com/exampleuser/old-repository.git

Mirror-push to the new repository.

cd old-repository.git

git push --mirror https://github.com/exampleuser/new-repository.git

Use of "instanceof" in Java

Basically, you check if an object is an instance of a specific class. You normally use it, when you have a reference or parameter to an object that is of a super class or interface type and need to know whether the actual object has some other type (normally more concrete).

Example:

public void doSomething(Number param) {
  if( param instanceof Double) {
    System.out.println("param is a Double");
  }
  else if( param instanceof Integer) {
    System.out.println("param is an Integer");
  }

  if( param instanceof Comparable) {
    //subclasses of Number like Double etc. implement Comparable
    //other subclasses might not -> you could pass Number instances that don't implement that interface
    System.out.println("param is comparable"); 
  }
}

Note that if you have to use that operator very often it is generally a hint that your design has some flaws. So in a well designed application you should have to use that operator as little as possible (of course there are exceptions to that general rule).

Drop rows containing empty cells from a pandas DataFrame

There's a situation where the cell has white space, you can't see it, use

df['col'].replace('  ', np.nan, inplace=True)

to replace white space as NaN, then

df= df.dropna(subset=['col'])

Drag and drop elements from list into separate blocks

Dragging an object and placing in a different location is part of the standard of HTML5. All the objects can be draggable. But the Specifications of below web browser should be followed. API Chrome Internet Explorer Firefox Safari Opera Version 4.0 9.0 3.5 6.0 12.0

You can find example from below: https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop2

How do I rename a column in a SQLite database table?

Say you have a table and need to rename "colb" to "col_b":

First you rename the old table:

ALTER TABLE orig_table_name RENAME TO tmp_table_name;

Then create the new table, based on the old table but with the updated column name:

CREATE TABLE orig_table_name (
  col_a INT
, col_b INT
);

Then copy the contents across from the original table.

INSERT INTO orig_table_name(col_a, col_b)
SELECT col_a, colb
FROM tmp_table_name;

Lastly, drop the old table.

DROP TABLE tmp_table_name;

Wrapping all this in a BEGIN TRANSACTION; and COMMIT; is also probably a good idea.

How to create an integer-for-loop in Ruby?

x.times do |i|
    something(i+1)
end

Is there a splice method for strings?

There seem to be a lot of confusion which was addressed only in comments by elclanrs and raina77ow, so let me post a clarifying answer.

Clarification

From "string.splice" one may expect that it, like the one for arrays:

  • accepts up to 3 arguments: start position, length and (optionally) insertion (string)
  • returns the cut out part
  • modifies the original string

The problem is, the 3d requirement can not be fulfilled because strings are immutable (related: 1, 2), I've found the most dedicated comment here:

In JavaScript strings are primitive value types and not objects (spec). In fact, as of ES5, they're one of the only 5 value types alongside null, undefined, number and boolean. Strings are assigned by value and not by reference and are passed as such. Thus, strings are not just immutable, they are a value. Changing the string "hello" to be "world" is like deciding that from now on the number 3 is the number 4... it makes no sense.

So, with that in account, one may expect the "string.splice" thing to only:

  • accepts up to 2 arguments: start position, length (insertion makes no sense since the string is not changed)
  • returns the cut out part

which is what substr does; or, alternatively,

  • accepts up to 3 arguments: start position, length and (optionally) insertion (string)
  • returns the modified string (without the cut part and with insertion)

which is the subject of the next section.

Solutions

If you care about optimizing, you should probably use the Mike's implementation:

String.prototype.splice = function(index, count, add) {
    if (index < 0) {
        index += this.length;
        if (index < 0)
            index = 0;
    }
    return this.slice(0, index) + (add || "") + this.slice(index + count);
}

Treating the out-of-boundaries index may vary, though. Depending on your needs, you may want:

    if (index < 0) {
        index += this.length;
        if (index < 0)
            index = 0;
    }
    if (index >= this.length) {
        index -= this.length;
        if (index >= this.length)
            index = this.length - 1;
    }

or even

    index = index % this.length;
    if (index < 0)
        index = this.length + index;

If you don't care about performance, you may want to adapt Kumar's suggestion which is more straight-forward:

String.prototype.splice = function(index, count, add) {
    var chars = this.split('');
    chars.splice(index, count, add);
    return chars.join('');
}

Performance

The difference in performances increases drastically with the length of the string. jsperf shows, that for strings with the length of 10 the latter solution (splitting & joining) is twice slower than the former solution (using slice), for 100-letter strings it's x5 and for 1000-letter strings it's x50, in Ops/sec it's:

                      10 letters   100 letters   1000 letters
slice implementation    1.25 M       2.00 M         1.91 M
split implementation    0.63 M       0.22 M         0.04 M

note that I've changed the 1st and 2d arguments when moving from 10 letters to 100 letters (still I'm surprised that the test for 100 letters runs faster than that for 10 letters).

add column to mysql table if it does not exist

Most of the answers address how to add a column safely in a stored procedure, I had the need to add a column to a table safely without using a stored proc and discovered that MySQL does not allow the use of IF Exists() outside a SP. I'll post my solution that it might help someone in the same situation.

SELECT count(*)
INTO @exist
FROM information_schema.columns 
WHERE table_schema = database()
and COLUMN_NAME = 'original_data'
AND table_name = 'mytable';

set @query = IF(@exist <= 0, 'alter table intent add column mycolumn4 varchar(2048) NULL after mycolumn3', 
'select \'Column Exists\' status');

prepare stmt from @query;

EXECUTE stmt;

c++ array - expression must have a constant value

C++ doesn't allow non-constant values for the size of an array. That's just the way it was designed.

C99 allows the size of an array to be a variable, but I'm not sure it is allowed for two dimensions. Some C++ compilers (gcc) will allow this as an extension, but you may need to turn on a compiler option to allow it.

And I almost missed it - you need to declare a variable name, not just the array dimensions.

Writelines writes lines without newline, Just fills the file

As others have noted, writelines is a misnomer (it ridiculously does not add newlines to the end of each line).

To do that, explicitly add it to each line:

with open(dst_filename, 'w') as f:
    f.writelines(s + '\n' for s in lines)

Can the Unix list command 'ls' output numerical chmod permissions?

@The MYYN

wow, nice awk! But what about suid, sgid and sticky bit?

You have to extend your filter with s and t, otherwise they will not count and you get the wrong result. To calculate the octal number for this special flags, the procedure is the same but the index is at 4 7 and 10. the possible flags for files with execute bit set are ---s--s--t amd for files with no execute bit set are ---S--S--T

ls -l | awk '{
    k = 0
    s = 0
    for( i = 0; i <= 8; i++ )
    {
        k += ( ( substr( $1, i+2, 1 ) ~ /[rwxst]/ ) * 2 ^( 8 - i ) )
    }
    j = 4 
    for( i = 4; i <= 10; i += 3 )
    {
        s += ( ( substr( $1, i, 1 ) ~ /[stST]/ ) * j )
        j/=2
    }
    if ( k )
    {
        printf( "%0o%0o ", s, k )
    }
    print
}'  

For test:

touch blah
chmod 7444 blah

will result in:

7444 -r-Sr-Sr-T 1 cheko cheko   0 2009-12-05 01:03 blah

and

touch blah
chmod 7555 blah

will give:

7555 -r-sr-sr-t 1 cheko cheko   0 2009-12-05 01:03 blah

How can I create a UIColor from a hex string?

Create elegant extension for UIColor:

extension UIColor {

convenience init(string: String) {

        var uppercasedString = string.uppercased()
        uppercasedString.remove(at: string.startIndex)

        var rgbValue: UInt32 = 0
        Scanner(string: uppercasedString).scanHexInt32(&rgbValue)

        let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
        let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
        let blue = CGFloat(rgbValue & 0x0000FF) / 255.0

        self.init(red: red, green: green, blue: blue, alpha: 1)
    }
}

Create red color:

let red = UIColor(string: "#ff0000") 

Using python PIL to turn a RGB image into a pure black and white image

from PIL import Image 
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')

yields

enter image description here

How to install XNA game studio on Visual Studio 2012?

I found another issue, for some reason if the extensions are cached in the local AppData folder, the XNA extensions never get loaded.

You need to remove the files extensionSdks.en-US.cache and extensions.en-US.cache from the %LocalAppData%\Microsoft\VisualStudio\11.0\Extensions folder. These files are rebuilt the next time you launch

If you need access to the Visual Studio startup log to debug what's happening, run devenv.exe /log command from the C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE directory (assuming you are on a 64 bit machine). The log file generated is located here:

%AppData%\Microsoft\VisualStudio\11.0\ActivityLog.xml

Can I use jQuery to check whether at least one checkbox is checked?

$('#frmTest').submit(function(){
    if(!$('#frmTest input[type="checkbox"]').is(':checked')){
      alert("Please check at least one.");
      return false;
    }
});

is(':checked') will return true if at least one or more of the checkboxes are checked.

Using Keras & Tensorflow with AMD GPU

Theano does have support for OpenCL but it is still in its early stages. Theano itself is not interested in OpenCL and relies on community support.

Most of the operations are already implemented and it is mostly a matter of tuning and optimizing the given operations.

To use the OpenCL backend you have to build libgpuarray yourself.

From personal experience I can tell you that you will get CPU performance if you are lucky. The memory allocation seems to be very naively implemented (therefore computation will be slow) and will crash when it runs out of memory. But I encourage you to try and maybe even optimize the code or help reporting bugs.

Extract csv file specific columns to list in Python

A standard-lib version (no pandas)

This assumes that the first row of the csv is the headers

import csv

# open the file in universal line ending mode 
with open('test.csv', 'rU') as infile:
  # read the file as a dictionary for each row ({header : value})
  reader = csv.DictReader(infile)
  data = {}
  for row in reader:
    for header, value in row.items():
      try:
        data[header].append(value)
      except KeyError:
        data[header] = [value]

# extract the variables you want
names = data['name']
latitude = data['latitude']
longitude = data['longitude']

How can I change a file's encoding with vim?

Notice that there is a difference between

set encoding

and

set fileencoding

In the first case, you'll change the output encoding that is shown in the terminal. In the second case, you'll change the output encoding of the file that is written.

How to convert Map keys to array?

Not exactly best answer to question but this trick new Array(...someMap) saved me couple of times when I need both key and value to generate needed array. For example when there is need to create react components from Map object based on both key and value values.

  let map = new Map();
  map.set("1", 1);
  map.set("2", 2);
  console.log(new Array(...map).map(pairs => pairs[0])); -> ["1", "2"]

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

Servlet for serving static content

I ended up rolling my own StaticServlet. It supports If-Modified-Since, gzip encoding and it should be able to serve static files from war-files as well. It is not very difficult code, but it is not entirely trivial either.

The code is available: StaticServlet.java. Feel free to comment.

Update: Khurram asks about the ServletUtils class which is referenced in StaticServlet. It is simply a class with auxiliary methods that I used for my project. The only method you need is coalesce (which is identical to the SQL function COALESCE). This is the code:

public static <T> T coalesce(T...ts) {
    for(T t: ts)
        if(t != null)
            return t;
    return null;
}

External VS2013 build error "error MSB4019: The imported project <path> was not found"

I had similar issue. All proposed solutions are just work around for this issue but are not solving source of error. @giammin solution should not be applied if you are using tfs build server as it is just crashed publish functionality. @cat5dev solution - solves issue but do not solve source of it.

I`m almost sure that you are using build process template for VS2012 like ReleaseDefaultTemplate.11.1.xaml or DefaultTemplate.11.1.xaml these build templates have been made for VS2012 and $(VisualStudioVersion) set to 11.0

You should use build process template for VS2013 ReleaseTfvcTemplate.12.xaml or TfvcTemplate.12.xaml which has $(VisualStudioVersion) set to 12.0

This works without any changes in project file.

printing all contents of array in C#

Starting from C# 6.0, when $ - string interpolation has been introduced, there is one more way:

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{string.Join(", ", array}");

//output
A, B, C

Concatenation could be archived using the System.Linq, convert the string[] to char[] and print as a string

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{new String(array.SelectMany(_ => _).ToArray())}");

//output
ABC

How do you determine the size of a file in C?

**Don't do this (why?):

Quoting the C99 standard doc that i found online: "Setting the file position indicator to end-of-file, as with fseek(file, 0, SEEK_END), has undefined behavior for a binary stream (because of possible trailing null characters) or for any stream with state-dependent encoding that does not assuredly end in the initial shift state.**

Change the definition to int so that error messages can be transmitted, and then use fseek() and ftell() to determine the file size.

int fsize(char* file) {
  int size;
  FILE* fh;

  fh = fopen(file, "rb"); //binary mode
  if(fh != NULL){
    if( fseek(fh, 0, SEEK_END) ){
      fclose(fh);
      return -1;
    }

    size = ftell(fh);
    fclose(fh);
    return size;
  }

  return -1; //error
}

How to scroll to top of the page in AngularJS?

Ideally we should do it from either controller or directive as per applicable. Use $anchorScroll, $location as dependency injection.

Then call this two method as

$location.hash('scrollToDivID');
$anchorScroll();

Here scrollToDivID is the id where you want to scroll.

Assumed you want to navigate to a error message div as

<div id='scrollToDivID'>Your Error Message</div>

For more information please see this documentation

Nested routes with react router v4 / v5

You can try something like Routes.js

import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import FrontPage from './FrontPage';
import Dashboard from './Dashboard';
import AboutPage from './AboutPage';
import Backend from './Backend';
import Homepage from './Homepage';
import UserPage from './UserPage';
class Routes extends Component {
    render() {
        return (
            <div>
                <Route exact path="/" component={FrontPage} />
                <Route exact path="/home" component={Homepage} />
                <Route exact path="/about" component={AboutPage} />
                <Route exact path="/admin" component={Backend} />
                <Route exact path="/admin/home" component={Dashboard} />
                <Route exact path="/users" component={UserPage} />    
            </div>
        )
    }
}

export default Routes

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Routes from './Routes';

class App extends Component {
  render() {
    return (
      <div className="App">
      <Router>
        <Routes/>
      </Router>
      </div>
    );
  }
}

export default App;

I think you can achieve the same from here also.

Converting a string to a date in DB2

I know its old post but still I want to contribute
Above will not work if you have data format like this
'YYYMMDD'

For example:

Dt
20151104

So I tried following in order to get the desired result.

select cast(Left('20151104', 4)||'-'||substring('20151104',5,2)||'-'||substring('20151104', 7,2) as date) from SYSIBM.SYSDUMMY1;

Additionally, If you want to run the query from MS SQL linked server to DB2(To display only 100 rows).

    SELECT top 100 * from OPENQUERY([Linked_Server_Name],
    'select cast(Left(''20151104'', 4)||''-''||substring(''20151104'',5,2)||''-''||substring(''20151104'', 7,2) as date) AS Dt 
    FROM SYSIBM.SYSDUMMY1')

Result after above query:

Dt
2015-11-04

Hope this helps for others.

Iterating through directories with Python

From python >= 3.5 onward, you can use **, glob.iglob(path/**, recursive=True) and it seems the most pythonic solution, i.e.:

import glob, os

for filename in glob.iglob('/pardadox-music/**', recursive=True):
    if os.path.isfile(filename): # filter dirs
        print(filename)

Output:

/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...

Notes:
1 - glob.iglob

glob.iglob(pathname, recursive=False)

Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

2 - If recursive is True, the pattern '**' will match any files and zero or more directories and subdirectories.

3 - If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:

>>> import glob
>>> glob.glob('*.gif') ['card.gif'] 
>>> glob.glob('.c*')['.card.gif']

4 - You can also use rglob(pattern), which is the same as calling glob() with **/ added in front of the given relative pattern.

How can I increment a date by one day in Java?

Apache Commons already has this DateUtils.addDays(Date date, int amount) http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html#addDays%28java.util.Date,%20int%29 which you use or you could go with the JodaTime to make it more cleaner.

Perfect 100% width of parent container for a Bootstrap input?

If you're using C# ASP.NET MVC's default template you may find that site.css overrides some of Bootstraps styles. If you want to use Bootstrap, as I did, having M$ override this (without your knowledge) can be a source of great frustration! Feel free to remove any of the unwanted styles...

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

How to remove not null constraint in sql server using query

Remove column constraint: not null to null

ALTER TABLE test ALTER COLUMN column_01 DROP NOT NULL;

Java constructor/method with optional parameters?

You can simulate it with using varargs, however then you should check it for too many arguments.

public void foo(int param1, int ... param2)
{
   int param2_
   if(param2.length == 0)
      param2_ = 2
   else if(para2.length == 1)
      param2_ = param2[0]
   else
      throw new TooManyArgumentsException(); // user provided too many arguments,

   // rest of the code
}

However this approach is not a good way of doing this, therefore it is better to use overloading.

Converting 'ArrayList<String> to 'String[]' in Java

List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
  array[i++] = s;
}

For loop in Objective-C

The traditional for loop in Objective-C is inherited from standard C and takes the following form:

for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
    // Do something.
}

For example, to print the numbers from 1 to 10, you could use the for loop:

for (int i = 1; i <= 10; i++)
{
    NSLog(@"%d", i);
}

On the other hand, the for in loop was introduced in Objective-C 2.0, and is used to loop through objects in a collection, such as an NSArray instance. For example, to loop through a collection of NSString objects in an NSArray and print them all out, you could use the following format.

for (NSString* currentString in myArrayOfStrings)
{
    NSLog(@"%@", currentString);
}

This is logically equivilant to the following traditional for loop:

for (int i = 0; i < [myArrayOfStrings count]; i++)
{
    NSLog(@"%@", [myArrayOfStrings objectAtIndex:i]);
}

The advantage of using the for in loop is firstly that it's a lot cleaner code to look at. Secondly, the Objective-C compiler can optimize the for in loop so as the code runs faster than doing the same thing with a traditional for loop.

Hope this helps.

How do I get milliseconds from epoch (1970-01-01) in Java?

java.time

Using the java.time framework built into Java 8 and later.

import java.time.Instant;

Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900

This works in UTC because Instant.now() is really call to Clock.systemUTC().instant()

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html

How to save a base64 image to user's disk using JavaScript?

HTML5 download attribute

Just to allow user to download the image or other file you may use the HTML5 download attribute.

Static file download

<a href="/images/image-name.jpg" download>
<!-- OR -->
<a href="/images/image-name.jpg" download="new-image-name.jpg"> 

Dynamic file download

In cases requesting image dynamically it is possible to emulate such download.

If your image is already loaded and you have the base64 source then:

function saveBase64AsFile(base64, fileName) {
    var link = document.createElement("a");

    document.body.appendChild(link); // for Firefox

    link.setAttribute("href", base64);
    link.setAttribute("download", fileName);
    link.click();
}

Otherwise if image file is downloaded as Blob you can use FileReader to convert it to Base64:

function saveBlobAsFile(blob, fileName) {
    var reader = new FileReader();

    reader.onloadend = function () {    
        var base64 = reader.result ;
        var link = document.createElement("a");

        document.body.appendChild(link); // for Firefox

        link.setAttribute("href", base64);
        link.setAttribute("download", fileName);
        link.click();
    };

    reader.readAsDataURL(blob);
}

Firefox

The anchor tag you are creating also needs to be added to the DOM in Firefox, in order to be recognized for click events (Link).

IE is not supported: Caniuse link

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Access the css ":after" selector with jQuery

You can add style for :after a like html code.
For example:

var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');

NSCameraUsageDescription in iOS 10.0 runtime crash?

If you're using Ionic, you can solve it directly from config.xml by adding inside platform ios tag:

<platform name="ios">
.
.
.
    <config-file target="*-Info.plist" parent="NSPhotoLibraryUsageDescription">
        <string>photo library usage description</string>
    </config-file>
    <config-file target="*-Info.plist" parent="NSCameraUsageDescription">
        <string>camera usage description</string>
    </config-file>
.
.
.
</platform>

I'd like to thank @BHUPI answer too.

Blade if(isset) is not working Laravel

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.

EXEC sp_addrolemember 'db_ddladmin', 'username_here';

did the trick

How to add a tooltip to an svg graphic?

I always go with the generic css title with my setup. I'm just building analytics for my blog admin page. I don't need anything fancy. Here's some code...

let comps = g.selectAll('.myClass')
   .data(data)
   .enter()
   .append('rect')
   ...styling...
   ...transitions...
   ...whatever...

g.selectAll('.myClass')
   .append('svg:title')
   .text((d, i) => d.name + '-' + i);

And a screenshot of chrome...

enter image description here

How could I create a list in c++?

We are already in 21st century!! Don't try to implement the already existing data structures. Try to use the existing data structures.

Use STL or Boost library

Subtract a value from every number in a list in Python?

To clarify an already posted solution due to questions in the comments

import numpy

array = numpy.array([49, 51, 53, 56])
array = array - 13

will output:

array([36, 38, 40, 43])

Difference between java.lang.RuntimeException and java.lang.Exception

Exceptions are a good way to handle unexpected events in your application flow. RuntimeException are unchecked by the Compiler but you may prefer to use Exceptions that extend Exception Class to control the behaviour of your api clients as they are required to catch errors for them to compile. Also forms good documentation.

If want to achieve clean interface use inheritance to subclass the different types of exception your application has and then expose the parent exception.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

From API level 17 and above, you can call: View.generateViewId()

Then use View.setId(int).

If your app is targeted lower than API level 17, use ViewCompat.generateViewId()

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

I can't leave this question in this state with that final code in the question hanging over me...

dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:

  • There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.

  • The with statement (recommended in another answer) removes the bother of closing the file through the context handler.

  • Use a dictionary instead of two lists.

  • A generator comprehension ((x for y in z)) is used to do the translation in one line.

  • Wrap as little code as you can in a try/except block to reduce the probability of catching an exception you didn't mean to.

  • Use the input() argument rather than print()ing first - Use '\n' to get the new line you want.

  • Don't write code across multiple lines or with intermediate variables like this just for the sake of it:

    a = a.b()
    a = a.c()
    b = a.x()
    c = b.y()
    

    Instead, write these constructs like this, chaining the calls as is perfectly valid:

    a = a.b().c()
    c = a.x().y()
    

code = {}
with open('morseCode.txt', 'r') as morse_code_file:
    # line format is <letter>:<morse code translation>
    for line in morse_code_file:
        line = line.rstrip()  # Remove NL
        code[line[0]] = line[2:]

user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
    try:
        print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
    except KeyError:
        print("Error in input. Only alphanumeric characters, a comma, and period allowed")

    user_input = input("Try again or press <enter> to quit\n")

How to check if a number is between two values?

this is a generic method, you can use everywhere

const isBetween = (num1,num2,value) => value > num1 && value < num2 

Returning an empty array

There is no difference except the fact that foo performs 3 visible method calls to return empty array that is anyway created while bar() just creates this array and returns it.

Undefined symbols for architecture arm64

Set Architectures to armv7 armv7s, Build Active Architecture Only to NO, for every target in the project, including every one in Pods

Run Jquery function on window events: load, resize, and scroll?

You can bind listeners to one common functions -

$(window).bind("load resize scroll",function(e){
  // do stuff
});

Or another way -

$(window).bind({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Alternatively, instead of using .bind() you can use .on() as bind directly maps to on(). And maybe .bind() won't be there in future jquery versions.

$(window).on({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Adding/removing items from a JavaScript object with jQuery

That's not JSON at all, it's just Javascript objects. JSON is a text representation of data, that uses a subset of the Javascript syntax.

The reason that you can't find any information about manipulating JSON using jQuery is because jQuery has nothing that can do that, and it's generally not done at all. You manipulate the data in the form of Javascript objects, and then turn it into a JSON string if that is what you need. (jQuery does have methods for the conversion, though.)

What you have is simply an object that contains an array, so you can use all the knowledge that you already have. Just use data.items to access the array.

For example, to add another item to the array using dynamic values:

// The values to put in the item
var id = 7;
var name = "The usual suspects";
var type = "crime";
// Create the item using the values
var item = { id: id, name: name, type: type };
// Add the item to the array
data.items.push(item);

Why can't overriding methods throw exceptions broader than the overridden method?

What explanation do we attribute to the below

class BaseClass {

    public  void print() {
        System.out.println("In Parent Class , Print Method");
    }

    public static void display() {
        System.out.println("In Parent Class, Display Method");
    }

}


class DerivedClass extends BaseClass {

    public  void print() throws Exception {
        System.out.println("In Derived Class, Print Method");
    }

    public static void display() {
        System.out.println("In Derived Class, Display Method");
    }
}

Class DerivedClass.java throws a compile time exception when the print method throws a Exception , print () method of baseclass does not throw any exception

I am able to attribute this to the fact that Exception is narrower than RuntimeException , it can be either No Exception (Runtime error ), RuntimeException and their child exceptions

Validation for 10 digit mobile number and focus input field on invalid

for email validation, <input type="email"> is enough..

for mobile no use pattern attribute for input as follows:

<input type="number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" required>

you can check for more patterns on http://html5pattern.com.

for focusing on field, you can use onkeyup() event as:

function check()
{

    var mobile = document.getElementById('mobile');
   
    
    var message = document.getElementById('message');

   var goodColor = "#0C6";
    var badColor = "#FF9B37";
  
    if(mobile.value.length!=10){
       
        mobile.style.backgroundColor = badColor;
        message.style.color = badColor;
        message.innerHTML = "required 10 digits, match requested format!"
    }}

and your HTML code should be:

<input name="mobile"  id="mobile" type="number" required onkeyup="check(); return false;" ><span id="message"></span>

SELECT where row value contains string MySQL

This should work:

SELECT * FROM Accounts WHERE Username LIKE '%$query%'