Programs & Examples On #Xnamespace

HTML: How to make a submit button with text + image in it?

I have found a very easy solution! If you have a form and you want to have a custom submit button you can use some code like this:

<button type="submit">
    <img src="login.png" onmouseover="this.src='login2.png';" onmouseout="this.src='login.png';" />
</button>

Or just direct it to a link of a page.

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

I know this answer is too late considering the question is dated 2010 but I came across this question as I was facing a similar problem myself. As already stated in the answer, normed=True means that the total area under the histogram is equal to 1 but the sum of heights is not equal to 1. However, I wanted to, for convenience of physical interpretation of a histogram, make one with sum of heights equal to 1.

I found a hint in the following question - Python: Histogram with area normalized to something other than 1

But I was not able to find a way of making bars mimic the histtype="step" feature hist(). This diverted me to : Matplotlib - Stepped histogram with already binned data

If the community finds it acceptable I should like to put forth a solution which synthesises ideas from both the above posts.

import matplotlib.pyplot as plt

# Let X be the array whose histogram needs to be plotted.
nx, xbins, ptchs = plt.hist(X, bins=20)
plt.clf() # Get rid of this histogram since not the one we want.

nx_frac = nx/float(len(nx)) # Each bin divided by total number of objects.
width = xbins[1] - xbins[0] # Width of each bin.
x = np.ravel(zip(xbins[:-1], xbins[:-1]+width))
y = np.ravel(zip(nx_frac,nx_frac))

plt.plot(x,y,linestyle="dashed",label="MyLabel")
#... Further formatting.

This has worked wonderfully for me though in some cases I have noticed that the left most "bar" or the right most "bar" of the histogram does not close down by touching the lowest point of the Y-axis. In such a case adding an element 0 at the begging or the end of y achieved the necessary result.

Just thought I'd share my experience. Thank you.

ruby 1.9: invalid byte sequence in UTF-8

My current solution is to run:

my_string.unpack("C*").pack("U*")

This will at least get rid of the exceptions which was my main problem

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

I had this error when trying to use the dreadful Business Objects 4 for .Net SDK.

They ship five BusinessObjects*.dll files, but all of them are 64-bit.

To get my webpage to load, I needed to click on Tools\Options, then change this setting in VS2013:

enter image description here

javascript multiple OR conditions in IF statement

You want to execute code where the id is not (1 or 2 or 3), but the OR operator does not distribute over id. The only way to say what you want is to say

the id is not 1, and the id is not 2, and the id is not 3.

which translates to

if (id !== 1 && id !== 2 && id !== 3)

or alternatively for something more pythonesque:

if (!(id in [,1,2,3]))

performSelector may cause a leak because its selector is unknown

Do not suppress warnings!

There are no less than 12 alternative solutions to tinkering with the compiler.
While you are being clever at the time the first implementation, few engineer on Earth can follow your footsteps, and this code will eventually break.

Safe Routes:

All these solutions will work, with some degree of of variation from your original intent. Assume that param can be nil if you so desire:

Safe route, same conceptual behavior:

// GREAT
[_controller performSelectorOnMainThread:selector withObject:anArgument waitUntilDone:YES];
[_controller performSelectorOnMainThread:selector withObject:anArgument waitUntilDone:YES modes:@[(__bridge NSString *)kCFRunLoopDefaultMode]];

[_controller performSelector:selector onThread:[NSThread mainThread] withObject:anArgument waitUntilDone:YES];
[_controller performSelector:selector onThread:[NSThread mainThread] withObject:anArgument waitUntilDone:YES modes:@[(__bridge NSString *)kCFRunLoopDefaultMode]];

Safe route, slightly different behavior:

(See this response)
Use any thread in lieu of [NSThread mainThread].

// GOOD
[_controller performSelector:selector withObject:anArgument afterDelay:0];
[_controller performSelector:selector withObject:anArgument afterDelay:0 inModes:@[(__bridge NSString *)kCFRunLoopDefaultMode]];

[_controller performSelectorOnMainThread:selector withObject:anArgument waitUntilDone:NO];
[_controller performSelectorOnMainThread:selector withObject:anArgument waitUntilDone:NO];
[_controller performSelectorOnMainThread:selector withObject:anArgument waitUntilDone:NO modes:@[(__bridge NSString *)kCFRunLoopDefaultMode]];

[_controller performSelectorInBackground:selector withObject:anArgument];

[_controller performSelector:selector onThread:[NSThread mainThread] withObject:anArgument waitUntilDone:NO];
[_controller performSelector:selector onThread:[NSThread mainThread] withObject:anArgument waitUntilDone:NO modes:@[(__bridge NSString *)kCFRunLoopDefaultMode]];

Dangerous Routes

Requires some kind of compiler silencing, which is bound to break. Note that at present time, it did break in Swift.

// AT YOUR OWN RISK
[_controller performSelector:selector];
[_controller performSelector:selector withObject:anArgument];
[_controller performSelector:selector withObject:anArgument withObject:nil];

Which @NotNull Java annotation should I use?

Unfortunately, JSR 308 will not add more values than this project local Not Null suggestion here

Java 8 will not come with a single default annotation or its own Checker framework. Similar to Find-bugs or JSR 305, this JSR is poorly maintained by a small bunch of mostly academic teams.

No commercial power behind it, thus JSR 308 launches EDR 3 (Early Draft Review at JCP) NOW, while Java 8 is supposed to ship in less than 6 months:-O Similar to 310 btw. but unlike 308 Oracle has taken charge of that now away from its founders to minimize harm it'll do to the Java Platform.

Every project, vendor and academic class like the ones behind the Checker Framework and JSR 308 will create its own proprietary checker annotation.

Making source code incompatible for years to come, until a few popular compromises could be found and maybe added to Java 9 or 10, or via frameworks like Apache Commons or Google Guava;-)

Generic type conversion FROM string

public class TypedProperty<T> : Property
{
    public T TypedValue
    {
        get { return (T)(object)base.Value; }
        set { base.Value = value.ToString();}
    }
}

I using converting via an object. It is a little bit simpler.

Setting cursor at the end of any text of a textbox

Try like below... it will help you...

Some time in Window Form Focus() doesn't work correctly. So better you can use Select() to focus the textbox.

txtbox.Select(); // to Set Focus
txtbox.Select(txtbox.Text.Length, 0); //to set cursor at the end of textbox

Fastest way to remove first char in a String

The second option really isn't the same as the others - if the string is "///foo" it will become "foo" instead of "//foo".

The first option needs a bit more work to understand than the third - I would view the Substring option as the most common and readable.

(Obviously each of them as an individual statement won't do anything useful - you'll need to assign the result to a variable, possibly data itself.)

I wouldn't take performance into consideration here unless it was actually becoming a problem for you - in which case the only way you'd know would be to have test cases, and then it's easy to just run those test cases for each option and compare the results. I'd expect Substring to probably be the fastest here, simply because Substring always ends up creating a string from a single chunk of the original input, whereas Remove has to at least potentially glue together a start chunk and an end chunk.

Creating a new empty branch for a new project

Make an empty new branch like this:

true | git mktree | xargs git commit-tree | xargs git branch proj-doc

If your proj-doc files are already in a commit under a single subdir you can make the new branch this way:

git commit-tree thatcommit:path/to/dir | xargs git branch proj-doc

which might be more convenient than git branch --orphan if that would leave you with a lot of git rm and git mving to do.

Try

git branch --set-upstream proj-doc origin/proj-doc

and see if that helps with your fetching-too-much problem. Also if you really only want to fetch a single branch it's safest to just specify it on the commandline.

HashMap with multiple values under the same key

If you use Spring Framework. There is: org.springframework.util.MultiValueMap.

To create unmodifiable multi value map:

Map<String,List<String>> map = ...
MultiValueMap<String, String> multiValueMap = CollectionUtils.toMultiValueMap(map);

Or use org.springframework.util.LinkedMultiValueMap

Good font for code presentations?

If you are doing a presentation, and you don't care about anything lining up, Verdana is a good choice.

If you are going to distribute your presentation, use a font that you know is on everyone's machine, since using something else is going to cause the machine to fall back to one of the common fonts (like Arial or Times) anyway.

If you do care about things lining up, and are not distributing the presentation, consider Consolas:

alt text

It is highly legible, reminiscent of Verdana, and is monospaced. The color choices are, of course, a matter of taste.

How to extract table as text from the PDF using Python?

  • I would suggest you to extract the table using tabula.
  • Pass your pdf as an argument to the tabula api and it will return you the table in the form of dataframe.
  • Each table in your pdf is returned as one dataframe.
  • The table will be returned in a list of dataframea, for working with dataframe you need pandas.

This is my code for extracting pdf.

import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here'  + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)

Please refer to this repo of mine for more details.

How to remove a TFS Workspace Mapping?

None of the answers here removed my workspaces. But here is one solution that may work for you.

  1. Open up a Visual Studio command prompt
  2. Close Visual Studio first or the delete command may not delete the workspace
  3. List the workspace commands -> tf /? to find the commands available to you from the version of TFS.
  4. List the workspaces -> tf workspaces
  5. Delete the workspace -> tf workspace YourWorkspace /delete

Generate ER Diagram from existing MySQL database, created for CakePHP

Use MySQL Workbench. create SQL dump file of your database

Follow below steps:

  1. Click File->Import->Reverse Engineer MySQL Create Script
  2. Click Browse and select your SQL create script.
  3. Make Sure "Place Imported Objects on a diagram" is checked.
  4. Click Execute Button.
  5. You are done.

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

As everyone else has said, there isn't one in html; however, you could use PUG/Jade. In fact I do this often.

It would look something like this:

select
  - var i = 1
  while i <= 100
    option=i++

This would produce: screenshot of htmltojade.org

How to activate JMX on my JVM for access with jconsole?

First you need to check if your java process is already running with JMX parameters. Do this:

ps -ef | grep java

Check your java process you need to monitor. If you can see jmx rmi parameter Djmx.rmi.registry.port=xxxx then use the port mentioned here in your java visualvm to connect it remotely under jmx connection.

If it's not running through jmx rmi port then you need to run your java process with below mentioned parameters :

-Djmx.rmi.registry.port=1234 -Djmx.rmi.port=1235 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false

Note: port numbers are based on your choice.

Now you can use this port for jmx coneection. Here it is port 1234.

What's the default password of mariadb on fedora?

For me, password = admin, worked. I installed it using pacman, Arch (Manjaro KDE).

NB: MariaDB was already installed, as a dependency of Amarok.

How to add a href link in PHP?

Looks like you missed a few closing tags and you nshould have "http://" on the front of an external URL. Also, you should move your styles to external style sheets instead of using inline styles.

.box{
  float:right;
}
.box a img{
  vertical-align: middle;
  border: 0px;
}

<div class="box">
    <a href="<?php echo "http://www.someotherwebsite.com"; ?>">
        <img src="<?php echo url::file_loc('img'); ?>media/img/twitter.png" alt="Image Decription">
    </a>
</div>

As noted in other comments, it may be easier to use straight HTML, depending on your exact setup.

<div class="box">
    <a href="http://www.someotherwebsite.com">
        <img src="file_location/media/img/twitter.png" alt="Image Decription">
    </a>
</div>

How to convert a negative number to positive?

>>> n = -42
>>> -n       # if you know n is negative
42
>>> abs(n)   # for any n
42

Don't forget to check the docs.

Hadoop "Unable to load native-hadoop library for your platform" warning

Basically, it is not an error, it's a warning in the Hadoop cluster. Here just we update the environment variables.

export HADOOP_OPTS = "$HADOOP_OPTS"-Djava.library.path = /usr/local/hadoop/lib
 export HADOOP_COMMON_LIB_NATIVE_DIR = "/usr/local/hadoop/lib/native"

Returning http status code from Web Api controller

For ASP.NET Web Api 2, this post from MS suggests to change the method's return type to IHttpActionResult. You can then return a built in IHttpActionResult implementation like Ok, BadRequest, etc (see here) or return your own implementation.

For your code, it could be done like:

public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
{
    var user = new DataEntities().Users.First(p => p.Id == userId);
    if (user.LastModified <= lastModifiedAtClient)
    {
        return StatusCode(HttpStatusCode.NotModified);
    }
    return Ok(user);
}

Re-assign host access permission to MySQL user

The more general answer is

UPDATE mysql.user SET host = {newhost} WHERE user = {youruser}

How to Position a table HTML?

You would want to use CSS to achieve that.

say you have a table with the attribute id="my_table"

You would want to write the following in your css file

#my_table{
    margin-top:10px //moves your table 10pixels down
    margin-left:10px //moves your table 10pixels right
}

if you do not have a CSS file then you may just add margin-top:10px, margin-left:10px to the style attribute in your table element like so

<table style="margin-top:10px; margin-left:10px;">
    ....
</table>

There are a lot of resources on the net describing CSS and HTML in detail

Vue-router redirect on page not found (404)

@mani's Original answer is all you want, but if you'd also like to read it in official way, here's

Reference to Vue's official page:

https://router.vuejs.org/guide/essentials/history-mode.html#caveat

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined

I got the same error, I'm using laravel 5.4 with webpack, here package.json before:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    ...
    ...
  },
  "dependencies": {
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I had to move jquery and datatables.net npm packages under one of these "dependencies": {} or "devDependencies": {} in package.json and the error disappeared, after:

{
  ...
  ...
  "devDependencies": {
    "jquery": "^1.12.4",
    "datatables.net": "^2.1.1",
    ...
    ...
  }
}

I hope that helps!

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I just ran into this problem with WAMP and the phpMyAdmin that comes with it. To remove the database and make the error go away. I went into C:\wamp\bin\mysql\mysql5.5.24\data\ and deleted the folder for the database in question.

Then I refreshed the page at phpMyAdmin, and the database was gone.

Embed a PowerPoint presentation into HTML

Well, I think you get to convert the powerpoint to flash first. PowerPoint is not a sharable format on Internet. Some tool like PowerPoint to Flash could be helpful for you.

How to add default signature in Outlook

Dim OutApp As Object, OutMail As Object, LogFile As String
Dim cell As Range, S As String, WMBody As String, lFile As Long

S = Environ("appdata") & "\Microsoft\Signatures\"
If Dir(S, vbDirectory) <> vbNullString Then S = S & Dir$(S & "*.htm") Else S = ""
S = CreateObject("Scripting.FileSystemObject").GetFile(S).OpenAsTextStream(1,  -2).ReadAll

WMBody = "<br>Hi All,<br><br>" & _
         "Last line,<br><br>" & S 'Add the Signature to end of HTML Body

Just thought I'd share how I achieve this. Not too sure if it's correct in the defining variables sense but it's small and easy to read which is what I like.

I attach WMBody to .HTMLBody within the object Outlook.Application OLE.

Hope it helps someone.

Thanks, Wes.

How to extract string following a pattern with grep, regex or perl

If you're using Perl, download a module to parse the XML: XML::Simple, XML::Twig, or XML::LibXML. Don't re-invent the wheel.

Bootstrap dropdown not working

I had setup with Angular 7, jQuery 3.4.1, Popper 1.12.9 and Bootstrap 4.3.1, nothing was working for me unitll I did this little hack in styles:

.dropdown.show .dropdown-menu {
    opacity: 1 !important;
}

Html looks like this:

<nav class="navbar navbar-expand-lg navbar-dark fixed-top py-1">
 <div class="container-fluid">
    <ul class="navbar-nav">
        <li class="nav-item dropdown">
            <button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" id="dropdown-id"
                aria-expanded="false">Menu</button>
            <div class="dropdown-menu" aria-labelledby="dropdown-id">
                <a class="dropdown-item" [routerLink]='["/"]'>Main page</a>
                <a class="dropdown-item" [routerLink]='["/about"]'>About</a>
                <div class="dropdown-divider"></div>
                <a class="dropdown-item" [routerLink]='["/about/terms"]'>Terms</a>
                <a class="dropdown-item" [routerLink]='["/about/privacy"]'>Privacy</a>
            </div>
        </li>
     </ul>
  </div>
</nav>

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

The pointer-events could be useful for this problem as you would be able to put a div over the arrow button, but still be able to click the arrow button.

The pointer-events css makes it possible to click through a div.

This approach will not work for IE versions older than IE11, however. You could something working in IE8 and IE9 if the element you put on top of the arrow button is an SVG element, but it will be more complicated to style the button the way you want proceeding like this.

Here a Js fiddle example: http://jsfiddle.net/e7qnqzx6/2/

How can I get the active screen dimensions?

I wanted to have the screen resolution before opening the first of my windows, so here a quick solution to open an invisible window before actually measuring screen dimensions (you need to adapt the window parameters to your window in order to ensure that both are openend on the same screen - mainly the WindowStartupLocation is important)

Window w = new Window();
w.ResizeMode = ResizeMode.NoResize;
w.WindowState = WindowState.Normal;
w.WindowStyle = WindowStyle.None;
w.Background = Brushes.Transparent;
w.Width = 0;
w.Height = 0;
w.AllowsTransparency = true;
w.IsHitTestVisible = false;
w.WindowStartupLocation = WindowStartupLocation.Manual;
w.Show();
Screen scr = Screen.FromHandle(new WindowInteropHelper(w).Handle);
w.Close();

illegal use of break statement; javascript

You need to make sure requestAnimFrame stops being called once game == 1. A break statement only exits a traditional loop (e.g. while()).

function loop() {
    if (isPlaying) {
        jet1.draw();
        drawAllEnemies();
        if (game != 1) {
            requestAnimFrame(loop);
        }
    }
}

Or alternatively you could simply skip the second if condition and change the first condition to if (isPlaying && game !== 1). You would have to make a variable called game and give it a value of 0. Add 1 to it every game.

Core dump file analysis

Steps to debug coredump using GDB:

Some generic help:

gdb start GDB, with no debugging les

gdb program begin debugging program

gdb program core debug coredump core produced by program

gdb --help describe command line options

  1. First of all, find the directory where the corefile is generated.

  2. Then use ls -ltr command in the directory to find the latest generated corefile.

  3. To load the corefile use

    gdb binary path of corefile
    

    This will load the corefile.

  4. Then you can get the information using the bt command.

    For a detailed backtrace use bt full.

  5. To print the variables, use print variable-name or p variable-name

  6. To get any help on GDB, use the help option or use apropos search-topic

  7. Use frame frame-number to go to the desired frame number.

  8. Use up n and down n commands to select frame n frames up and select frame n frames down respectively.

  9. To stop GDB, use quit or q.

Text vertical alignment in WPF TextBlock

While Orion Edwards Answer works for any situation, it may be a pain to add the border and set the properties of the border every time you want to do this. Another quick way is to set the padding of the text block:

<TextBlock Height="22" Padding="3" />

how to make negative numbers into positive

You have to use:

abs() for int
fabs() for double
fabsf() for float

Above function will also work but you can also try something like this.

    if(a<0)
    {
         a=-a;
    }

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

How do I run a spring boot executable jar in a Production environment?

My Spring boot application has two initializers. One for development and another for production. For development, I use the main method like this:

@SpringBootApplication
public class MyAppInitializer {

    public static void main(String[] args) {
        SpringApplication.run(MyAppInitializer .class, args);
    }

}

My Initializer for production environment extends the SpringBootServletInitializer and looks like this:

@SpringBootApplication
public class MyAppInitializerServlet extends SpringBootServletInitializer{
    private static final Logger log = Logger
            .getLogger(SpringBootServletInitializer.class);
    @Override
    protected SpringApplicationBuilder configure(
            SpringApplicationBuilder builder) {
        log.trace("Initializing the application");
        return builder.sources(MyAppInitializerServlet .class);
    }

}

I use gradle and my build.gradle file applies 'WAR' plugin. When I run it in the development environment, I use bootrun task. Where as when I want to deploy it to production, I use assemble task to generate the WAR and deploy.

I can run like a normal spring application in production without discounting the advantages provided by the inbuilt tomcat while developing. Hope this helps.

Assets file project.assets.json not found. Run a NuGet package restore

In my case I had a problem with the Available Package Sources. I had move the local nuget repository folder to a new path but I did not update it in the Nuget Available Package Sources. When I've correct the path issue, update it in the Available Package Sources and after that everything (nuget restor, etc) was working fine.

Can't import Numpy in Python

I was trying to import numpy in python 3.2.1 on windows 7.

Followed suggestions in above answer for numpy-1.6.1.zip as below after unzipping it

cd numpy-1.6
python setup.py install

but got an error with a statement as below

unable to find vcvarsall.bat

For this error I found a related question here which suggested installing mingW. MingW was taking some time to install.

In the meanwhile tried to install numpy 1.6 again using the direct windows installer available at this link the file name is "numpy-1.6.1-win32-superpack-python3.2.exe"

Installation went smoothly and now I am able to import numpy without using mingW.

Long story short try using windows installer for numpy, if one is available.

Can RDP clients launch remote applications and not desktops

This is quite easily achievable.

  1. We need to allow any unlisted programs to start from RDP.
    1.1 Save the script below on your desktop, the extension must end with .reg.
Windows Registry Editor Version 5.00

    [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\TSAppAllowList]
    "fDisabledAllowList"=dword:00000001


       1.2 Right click on the file and click Merge, Yes, Ok.

  1. Modifying our .rdp file.
    2.1 At the end of our file, add the following code:
remoteapplicationmode:i:1
remoteapplicationname:s:This will be the optional description of the app
remoteapplicationprogram:s:Relative or absolute path to the app
                           (Example: taskmgr or C:\Windows\system32\taskmgr.exe)
remoteapplicationcmdline:s:Here you'd put any optional application parameters


Or just use this one to make sure that it works:

remoteapplicationmode:i:1
remoteapplicationname:s:
remoteapplicationprogram:s:mspaint
remoteapplicationcmdline:s:

        2.2 Enter your username and password and connect.


    3. Now you can use your RemoteApp without any issues as if it was running on your local machine

Dynamically create checkbox with JQuery from text input

One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?

Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...

<div id="checkboxes">
    <input type="checkbox" /> Some label<br />
    <input type="checkbox" /> Some other label<br />
</div>

<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>

Based on this markup your jquery could bind to the click event of the button and manipulate the DOM.

$('#addCheckbox').click(function() {
    var text = $('#newCheckText').val();
    $('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});

Accessing all items in the JToken

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

Then you can call its something like this...

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info

Are string.Equals() and == operator really same?

It is clear that tvi.header is not a String. The == is an operator that is overloaded by String class, which means it will be working only if compiler knows that both side of the operator are String.

Batch: Remove file extension

Using cygwin bash to do the chopping

  :: e.g. FILE=basename.mp4 => FILE_NO_EXT=basename
  set FILE=%1
  for /f "delims=" %%a in ('bash -c "FILE=%FILE%; echo ${FILE/.*/}" ') do set FILE_NO_EXT=%%a

Python equivalent of a given wget command

easy as py:

class Downloder():
    def download_manager(self, url, destination='Files/DownloderApp/', try_number="10", time_out="60"):
        #threading.Thread(target=self._wget_dl, args=(url, destination, try_number, time_out, log_file)).start()
        if self._wget_dl(url, destination, try_number, time_out, log_file) == 0:
            return True
        else:
            return False


    def _wget_dl(self,url, destination, try_number, time_out):
        import subprocess
        command=["wget", "-c", "-P", destination, "-t", try_number, "-T", time_out , url]
        try:
            download_state=subprocess.call(command)
        except Exception as e:
            print(e)
        #if download_state==0 => successfull download
        return download_state

Git: How to update/checkout a single file from remote origin master?

I think I have found an easy hack out.

Delete the file that you have on the local repository (the file that you want updated from the latest commit in the remote server)

And then do a git pull

Because the file is deleted, there will be no conflict

How can I parse a YAML file in Python

First install pyyaml using pip3.

Then import yaml module and load the file into a dictionary called 'my_dict':

import yaml
with open('filename.yaml') as f:
    my_dict = yaml.safe_load(f)

That's all you need. Now the entire yaml file is in 'my_dict' dictionary.

How to get annotations of a member variable?

package be.fery.annotation;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;

@Entity
public class User {
    @Id
    private Long id;

    @Column(name = "ADDRESS_ID")
    private Address address;

    @PrePersist
    public void doStuff(){

    }
}

And a testing class:

    package be.fery.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AnnotationIntrospector {

    public AnnotationIntrospector() {
        super();
    }

    public Annotation[] findClassAnnotation(Class<?> clazz) {
        return clazz.getAnnotations();
    }

    public Annotation[] findMethodAnnotation(Class<?> clazz, String methodName) {

        Annotation[] annotations = null;
        try {
            Class<?>[] params = null;
            Method method = clazz.getDeclaredMethod(methodName, params);
            if (method != null) {
                annotations = method.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    public Annotation[] findFieldAnnotation(Class<?> clazz, String fieldName) {
        Annotation[] annotations = null;
        try {
            Field field = clazz.getDeclaredField(fieldName);
            if (field != null) {
                annotations = field.getAnnotations();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return annotations;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        AnnotationIntrospector ai = new AnnotationIntrospector();
        Annotation[] annotations;
        Class<User> userClass = User.class;
        String methodDoStuff = "doStuff";
        String fieldId = "id";
        String fieldAddress = "address";

        // Find class annotations
        annotations = ai.findClassAnnotation(be.fery.annotation.User.class);
        System.out.println("Annotation on class '" + userClass.getName()
                + "' are:");
        showAnnotations(annotations);

        // Find method annotations
        annotations = ai.findMethodAnnotation(User.class, methodDoStuff);
        System.out.println("Annotation on method '" + methodDoStuff + "' are:");
        showAnnotations(annotations);

        // Find field annotations
        annotations = ai.findFieldAnnotation(User.class, fieldId);
        System.out.println("Annotation on field '" + fieldId + "' are:");
        showAnnotations(annotations);

        annotations = ai.findFieldAnnotation(User.class, fieldAddress);
        System.out.println("Annotation on field '" + fieldAddress + "' are:");
        showAnnotations(annotations);

    }

    public static void showAnnotations(Annotation[] ann) {
        if (ann == null)
            return;
        for (Annotation a : ann) {
            System.out.println(a.toString());
        }
    }

}

Hope it helps...

;-)

Python socket receive - incoming packets always have a different size

The answer by Larry Hastings has some great general advice about sockets, but there are a couple of mistakes as it pertains to how the recv(bufsize) method works in the Python socket module.

So, to clarify, since this may be confusing to others looking to this for help:

  1. The bufsize param for the recv(bufsize) method is not optional. You'll get an error if you call recv() (without the param).
  2. The bufferlen in recv(bufsize) is a maximum size. The recv will happily return fewer bytes if there are fewer available.

See the documentation for details.

Now, if you're receiving data from a client and want to know when you've received all of the data, you're probably going to have to add it to your protocol -- as Larry suggests. See this recipe for strategies for determining end of message.

As that recipe points out, for some protocols, the client will simply disconnect when it's done sending data. In those cases, your while True loop should work fine. If the client does not disconnect, you'll need to figure out some way to signal your content length, delimit your messages, or implement a timeout.

I'd be happy to try to help further if you could post your exact client code and a description of your test protocol.

ValueError: max() arg is an empty sequence

try parsing a default value which can be returned by max if length of v none

max(v, default=0)

jquery function setInterval

Don't pass the result of swapImages to setInterval by invoking it. Just pass the function, like this:

setInterval(swapImages, 1000);

How to save a new sheet in an existing excel file, using Pandas?

A simple example for writing multiple data to excel at a time. And also when you want to append data to a sheet on a written excel file (closed excel file).

When it is your first time writing to an excel. (Writing "df1" and "df2" to "1st_sheet" and "2nd_sheet")

import pandas as pd 
from openpyxl import load_workbook

df1 = pd.DataFrame([[1],[1]], columns=['a'])
df2 = pd.DataFrame([[2],[2]], columns=['b'])
df3 = pd.DataFrame([[3],[3]], columns=['c'])

excel_dir = "my/excel/dir"

with pd.ExcelWriter(excel_dir, engine='xlsxwriter') as writer:    
    df1.to_excel(writer, '1st_sheet')   
    df2.to_excel(writer, '2nd_sheet')   
    writer.save()    

After you close your excel, but you wish to "append" data on the same excel file but another sheet, let's say "df3" to sheet name "3rd_sheet".

book = load_workbook(excel_dir)
with pd.ExcelWriter(excel_dir, engine='openpyxl') as writer:
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)    

    ## Your dataframe to append. 
    df3.to_excel(writer, '3rd_sheet')  

    writer.save()     

Be noted that excel format must not be xls, you may use xlsx one.

String formatting in Python 3

Here are the docs about the "new" format syntax. An example would be:

"({:d} goals, ${:d})".format(self.goals, self.penalties)

If both goals and penalties are integers (i.e. their default format is ok), it could be shortened to:

"({} goals, ${})".format(self.goals, self.penalties)

And since the parameters are fields of self, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):

"({0.goals} goals, ${0.penalties})".format(self)

Explaining:

  • {} means just the next positional argument, with default format;
  • {0} means the argument with index 0, with default format;
  • {:d} is the next positional argument, with decimal integer format;
  • {0:d} is the argument with index 0, with decimal integer format.

There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:

"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)

"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)

"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'

"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'

"games: {:>3}".format(player1.games)  # 'games: 123'
"games: {:>3}".format(player2.games)  # 'games:   4'
"games: {:0>3}".format(player2.games) # 'games: 004'

Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).

exceeds the list view threshold 5000 items in Sharepoint 2010

SharePoint lists V: Techniques for managing large lists :

Tutorial By Microsoft

Level: Advanced

Length: 40 - 50 minutes

When a SharePoint list gets large, you might see warnings such as, “This list exceeds the list view threshold,” or “Displaying the newest results below.” Find out why these warnings occur, and learn ways to configure your large list so that it still provides useful information.

After completing this course you will be able to:

  • Learn what the List View Threshold is, and understand its benefits.
  • Create an index so that you can see more information in a view.
  • Create folders to better organize your large list.
  • Use Datasheet view for fast filtering and sorting of a large list.
  • Learn what the Daily Time Window for Large Queries is.
  • Use Key Filters for fast filtering within Standard view.
  • Sync a large list to SharePoint Workspace.
  • Export a large list to Excel. Link a large list in Access.

CSS: Set a background color which is 50% of the width of the window

In a past project that had to support IE8+ and I achieved this using a image encoded in data-url format.

The image was 2800x1px, half of the image white, and half transparent. Worked pretty well.

body {
    /* 50% right white */
    background: red url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACvAAAAABAQAAAAAqT0YHAAAAAnRSTlMAAHaTzTgAAAAOSURBVHgBYxhi4P/QAgDwrK5SDPAOUwAAAABJRU5ErkJggg==) center top repeat-y;

   /* 50% left white */
   background: red url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAACvAAAAABAQAAAAAqT0YHAAAAAnRSTlMAAHaTzTgAAAAPSURBVHgBY/g/tADD0AIAIROuUgYu7kEAAAAASUVORK5CYII=) center top repeat-y;
}

You can see it working here JsFiddle. Hope it can help someone ;)

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I want to add my solution to above, maybe it helps someone. When i create a field on a model via Room and do not generate getter/setter for the field. As a result project is not compiling and no clear errors.

How do I use tools:overrideLibrary in a build.gradle file?

I just changed minSdkVersion="7" in C:\MyApp\platforms\android\CordovaLib\AndroidManifest.xml and it worked.

Steps:

  1. Path: C:\MyApp\platforms\android\CordovaLib\AndroidManifest.xml
  2. Value: <uses-sdk android:minSdkVersion="7"/>
  3. Ran command in new cmd prompt:

    C:\MyApp>phonegap build android --debug [phonegap] executing 'cordova build android --debug'... [phonegap] completed 'cordova build android --debug'

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.

I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.

C# Enum - How to Compare Value

You can use extension methods to do the same thing with less code.

public enum AccountType
{
    Retailer = 1,
    Customer = 2,
    Manager = 3,
    Employee = 4
}

static class AccountTypeMethods
{
    public static bool IsRetailer(this AccountType ac)
    {
        return ac == AccountType.Retailer;
    }
}

And to use:

if (userProfile.AccountType.isRetailer())
{
    //your code
}

I would recommend to rename the AccountType to Account. It's not a name convention.

How to get a value from a Pandas DataFrame and not the index and object type

Nobody mentioned it, but you can also simply use loc with the index and column labels.

df.loc[2, 'Letters']
# 'C'

Or, if you prefer to use "Numbers" column as reference, you can also set is as an index.

df.set_index('Numbers').loc[3, 'Letters']

How to generate a random number between 0 and 1?

Set the seed using srand(). Also, you're not specifying the max value in rand(), so it's using RAND_MAX. I'm not sure if it's actually 10000... why not just specify it. Although, we don't know what your "expected results" are. It's a random number generator. What are you expecting, and what are you seeing?

As noted in another comment, SA() isn't returning anything explicitly.

http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html http://www.thinkage.ca/english/gcos/expl/c/lib/rand.html

Edit: From Generating random number between [-1, 1] in C? ((float)rand())/RAND_MAX returns a floating-point number in [0,1]

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

toISOString() will return current UTC time only not the current local time. If you want to get the current local time in yyyy-MM-ddTHH:mm:ss.SSSZ format then you should get the current time using following two methods

Method 1:

_x000D_
_x000D_
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString());
_x000D_
_x000D_
_x000D_

Method 2:

_x000D_
_x000D_
document.write(new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString());
_x000D_
_x000D_
_x000D_

Select rows of a matrix that meet a condition

Subset is a very slow function , and I personally find it useless.

I assume you have a data.frame, array, matrix called Mat with A, B, C as column names; then all you need to do is:

  • In the case of one condition on one column, lets say column A

    Mat[which(Mat[,'A'] == 10), ]
    

In the case of multiple conditions on different column, you can create a dummy variable. Suppose the conditions are A = 10, B = 5, and C > 2, then we have:

    aux = which(Mat[,'A'] == 10)
    aux = aux[which(Mat[aux,'B'] == 5)]
    aux = aux[which(Mat[aux,'C'] > 2)]
    Mat[aux, ]

By testing the speed advantage with system.time, the which method is 10x faster than the subset method.

Import existing Gradle Git project into Eclipse

Add the following to your build.gradle

apply plugin: 'eclipse'

and browse to the project directory

gradle eclipse

How to get a list of all files that changed between two Git commits?

  • To list all unstaged tracked changed files:

    git diff --name-only
    
  • To list all staged tracked changed files:

    git diff --name-only --staged
    
  • To list all staged and unstaged tracked changed files:

    { git diff --name-only ; git diff --name-only --staged ; } | sort | uniq
    
  • To list all untracked files (the ones listed by git status, so not including any ignored files):

    git ls-files --other --exclude-standard
    

If you're using this in a shell script, and you want to programmatically check if these commands returned anything, you'll be interested in git diff's --exit-code option.

How to focus on a form input text field on page load using jQuery?

You can use HTML5 autofocus for this. You don't need jQuery or other JavaScript.

<input type="text" name="some_field" autofocus>

Note this will not work on IE9 and lower.

Groovy / grails how to determine a data type?

somObject instanceof Date

should be

somObject instanceOf Date

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

jQuery - Click event on <tr> elements with in a table and getting <td> element values

$("body").on("click", "#tableid tr", function () {
    debugger
    alert($(this).text());
});

$("body").on("click", "#tableid td", function () {
    debugger
    alert($(this).text());
});

Using an HTTP PROXY - Python

I encountered this on jython client. The server was only talking TLS and the client using SSL context.

javax.net.ssl.SSLContext.getInstance("SSL")

Once the client was to TLS, things started working.

Deserialize a JSON array in C#

This should work...

JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);

public class Person
{
    public string Name;
    public int Age;
    public string Location;
}
public class Record
{
    public Person record;
}

Set custom attribute using JavaScript

For people coming from Google, this question is not about data attributes - OP added a non-standard attribute to their HTML object, and wondered how to set it.

However, you should not add custom attributes to your properties - you should use data attributes - e.g. OP should have used data-icon, data-url, data-target, etc.

In any event, it turns out that the way you set these attributes via JavaScript is the same for both cases. Use:

ele.setAttribute(attributeName, value);

to change the given attribute attributeName to value for the DOM element ele.

For example:

document.getElementById("someElement").setAttribute("data-id", 2);

Note that you can also use .dataset to set the values of data attributes, but as @racemic points out, it is 62% slower (at least in Chrome on macOS at the time of writing). So I would recommend using the setAttribute method instead.

Java to Jackson JSON serialization: Money fields

I'm one of the maintainers of jackson-datatype-money, so take this answer with a grain of salt since I'm certainly biased. The module should cover your needs and it's pretty light-weight (no additional runtime dependencies). In addition it's mentioned in the Jackson docs, Spring docs and there were even some discussions already about how to integrate it into the official ecosystem of Jackson.

SQL Server IIF vs CASE

IIF is a non-standard T-SQL function. It was added to SQL SERVER 2012, so that Access could migrate to SQL Server without refactoring the IIF's to CASE before hand. Once the Access db is fully migrated into SQL Server, you can refactor.

How to check if a file exists from a url

You don't need CURL for that... Too much overhead for just wanting to check if a file exists or not...

Use PHP's get_header.

$headers=get_headers($url);

Then check if $result[0] contains 200 OK (which means the file is there)

A function to check if a URL works could be this:

function UR_exists($url){
   $headers=get_headers($url);
   return stripos($headers[0],"200 OK")?true:false;
}

/* You can test a URL like this (sample) */
if(UR_exists("http://www.amazingjokes.com/"))
   echo "This page exists";
else
   echo "This page does not exist";

SQLAlchemy: print the actual query

I would like to point out that the solutions given above do not "just work" with non-trivial queries. One issue I came across were more complicated types, such as pgsql ARRAYs causing issues. I did find a solution that for me, did just work even with pgsql ARRAYs:

borrowed from: https://gist.github.com/gsakkis/4572159

The linked code seems to be based on an older version of SQLAlchemy. You'll get an error saying that the attribute _mapper_zero_or_none doesn't exist. Here's an updated version that will work with a newer version, you simply replace _mapper_zero_or_none with bind. Additionally, this has support for pgsql arrays:

# adapted from:
# https://gist.github.com/gsakkis/4572159
from datetime import date, timedelta
from datetime import datetime

from sqlalchemy.orm import Query


try:
    basestring
except NameError:
    basestring = str


def render_query(statement, dialect=None):
    """
    Generate an SQL expression string with bound parameters rendered inline
    for the given SQLAlchemy statement.
    WARNING: This method of escaping is insecure, incomplete, and for debugging
    purposes only. Executing SQL statements with inline-rendered user values is
    extremely insecure.
    Based on http://stackoverflow.com/questions/5631078/sqlalchemy-print-the-actual-query
    """
    if isinstance(statement, Query):
        if dialect is None:
            dialect = statement.session.bind.dialect
        statement = statement.statement
    elif dialect is None:
        dialect = statement.bind.dialect

    class LiteralCompiler(dialect.statement_compiler):

        def visit_bindparam(self, bindparam, within_columns_clause=False,
                            literal_binds=False, **kwargs):
            return self.render_literal_value(bindparam.value, bindparam.type)

        def render_array_value(self, val, item_type):
            if isinstance(val, list):
                return "{%s}" % ",".join([self.render_array_value(x, item_type) for x in val])
            return self.render_literal_value(val, item_type)

        def render_literal_value(self, value, type_):
            if isinstance(value, long):
                return str(value)
            elif isinstance(value, (basestring, date, datetime, timedelta)):
                return "'%s'" % str(value).replace("'", "''")
            elif isinstance(value, list):
                return "'{%s}'" % (",".join([self.render_array_value(x, type_.item_type) for x in value]))
            return super(LiteralCompiler, self).render_literal_value(value, type_)

    return LiteralCompiler(dialect, statement).process(statement)

Tested to two levels of nested arrays.

Core Data: Quickest way to delete all instances of an entity

Extending Dave Delong's answer.

Swift Version that takes care of iOS 9 and previous versions as well. I have also covered Error handling in this:

let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let fetchRequest = NSFetchRequest(entityName: "Car")
    if #available(iOS 9.0, *) {
        let delete = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            try appDelegate.persistentStoreCoordinator.executeRequest(delete, withContext: appDelegate.managedObjectContext)
        } catch let error as NSError {
            print("Error occured while deleting: \(error)")
        }
    } else {
        // Fallback on earlier versions
        let carRequest = NSFetchRequest()
        carRequest.entity = NSEntityDescription.entityForName("Cars", inManagedObjectContext: appDelegate.managedObjectContext)
        carRequest.includesPropertyValues = false

        do {
            let cars: NSArray = try appDelegate.managedObjectContext.executeFetchRequest(carRequest)

            for car in cars {
                appDelegate.managedObjectContext.delete(car)
            }

            try appDelegate.managedObjectContext.save()

        } catch let error as NSError {
            print("Error occured while fetching or saving: \(error)")
        }
    }

best way to get folder and file list in Javascript

Why to invent the wheel?

There is a very popular NPM package, that let you do things like that easy.

var recursive = require("recursive-readdir");

recursive("some/path", function (err, files) {
  // `files` is an array of file paths
  console.log(files);
});

Lear more:

C++ array initialization

Yes, I believe it should work and it can also be applied to other data types.

For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.

How to disable action bar permanently

Use this in styles.xml file:


<style name="MyTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowActionBar">false</item>
        <item name="android:windowNoTitle">true</item>

find: missing argument to -exec

You need to do some escaping I think.

find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i {} \-sameq {}.mp3 \&\& rm {}\;

How to get the url parameters using AngularJS

If the answers already posted didn't help, one can try with $location.search().myParam; with URLs http://example.domain#?myParam=paramValue

Finding longest string in array

Modern browsers support a for...of loop. The fastest and shortest way to solve this problem in Chrome, Safari, Edge, and Firefox is also the clearest:

let largest = '';
for (let item of arr) {
  if (item.length > largest.length) largest = item
}

In IE, you can use Array.forEach; that's still faster and clearer than sorting or reducing the array.

var largest = '';
arr.forEach(function(item) {
  if (item.length > largest.length) largest = item
});

How to check if a table exists in a given schema

For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

In-place edits with sed on OS X

You can use the -i flag correctly by providing it with a suffix to add to the backed-up file. Extending your example:

sed -i.bu 's/oldword/newword/' file1.txt

Will give you two files: one with the name file1.txt that contains the substitution, and one with the name file1.txt.bu that has the original content.

Mildly dangerous

If you want to destructively overwrite the original file, use something like:

sed -i '' 's/oldword/newword/' file1.txt
      ^ note the space

Because of the way the line gets parsed, a space is required between the option flag and its argument because the argument is zero-length.

Other than possibly trashing your original, I’m not aware of any further dangers of tricking sed this way. It should be noted, however, that if this invocation of sed is part of a script, The Unix Way™ would (IMHO) be to use sed non-destructively, test that it exited cleanly, and only then remove the extraneous file.

iOS9 Untrusted Enterprise Developer with no option to trust

Device: iPad Mini

OS: iOS 9 Beta 3

App downloaded from: Hockey App

Provisioning profile with Trust issues: Enterprise

In my case, when I navigate to Settings > General > Profiles, I could not see on any Apple provisioning profile. All I could see is a Configuration Profile which is HockeyApp Config.

Settings>General>Profile

Here are the steps that I followed:

  1. Connect the Device
  2. Open Xcode
  3. Navigate to Window > Devices
  4. Right click on the Device and select Show Provisioning Profiles...
  5. Delete your Enterprise provisioning profile. Hit Done. Window>Device>Provisioning Profile
  6. Open HockeyApp. Install your app.
  7. Once the app finished installing, go back to Settings>General>Profiles. You should now be able to see your Enterprise provisioning profile. enter image description here
  8. Click Trust enter image description here

That's it! You're done! You can now go back to your app and open it successfully. Hope this helped. :)

How do you manually execute SQL commands in Ruby On Rails using NuoDB

res = ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query( "SELECT 1;" ) }

The above code is an example for

  1. executing arbitrary SQL on your database-connection
  2. returning the connection back to the connection pool afterwards

xml.LoadData - Data at the root level is invalid. Line 1, position 1

I Think that the problem is about encoding. That's why removing first line(with encoding byte) might solve the problem.

My solution for Data at the root level is invalid. Line 1, position 1. in XDocument.Parse(xmlString) was replacing it with XDocument.Load( new MemoryStream( xmlContentInBytes ) );

I've noticed that my xml string looked ok:

<?xml version="1.0" encoding="utf-8"?>

but in different text editor encoding it looked like this:

?<?xml version="1.0" encoding="utf-8"?>

At the end i did not need the xml string but xml byte[]. If you need to use the string you should look for "invisible" bytes in your string and play with encodings to adjust the xml content for parsing or loading.

Hope it will help

Android SDK folder taking a lot of disk space. Do we need to keep all of the System Images?

There is the way to safely removed system-image

Go in SDK Manager in toolbar :

enter image description here

enter image description here

Go in Android SDK :

enter image description here

In tab SDK Platforms, uncheck which platform you want unistall :

enter image description here

Click ok and confirm deletion :

enter image description here

how to get right offset of an element? - jQuery

Getting the anchor point of a div/table (left) = $("#whatever").offset().left; - ok!

Getting the anchor point of a div/table (right) you can use the code below.

 $("#whatever").width();

XML string to XML document

Try this code:

var myXmlDocument = new XmlDocument();
myXmlDocument.LoadXml(theString);

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

You can do something like this, very simple and efficient solution: What i did was actually use a parameter instead of basic placeholder, created a SqlParameter object and used another existing execution method. For e.g in your scenario:

string sql = "INSERT INTO mssqltable (varbinarycolumn) VALUES (@img)";
SqlParameter param = new SqlParameter("img", arraytoinsert); //where img is your parameter name in the query
ExecuteStoreCommand(sql, param);

This should work like a charm, provided you have an open sql connection established.

PostgreSQL psql terminal command

psql --pset=format=FORMAT

Great for executing queries from command line, e.g.

psql --pset=format=unaligned -c "select bandanavalue from bandana where bandanakey = 'atlassian.confluence.settings';"

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

PostgreSQL doesn't support storing NULL (\0x00) characters in text fields (this is obviously different from the database NULL value, which is fully supported).

Source: http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS-UESCAPE

If you need to store the NULL character, you must use a bytea field - which should store anything you want, but won't support text operations on it.

Given that PostgreSQL doesn't support it in text values, there's no good way to get it to remove it. You could import your data into bytea and later convert it to text using a special function (in perl or something, maybe?), but it's likely going to be easier to do that in preprocessing before you load it.

EOFError: EOF when reading a line

**The best is to use try except block to get rid of EOF **

try:
    width = input()
    height = input()
    def rectanglePerimeter(width, height):
       return ((width + height)*2)
    print(rectanglePerimeter(width, height))
except EOFError as e:
    print(end="")

What is the best way to uninstall gems from a rails3 project?

With newer versions of bundler you can use the clean task:

$ bundle help clean
Usage:
    bundle clean

Options:
    [--dry-run=only print out changes, do not actually clean gems]
    [--force=forces clean even if --path is not set]
    [--no-color=Disable colorization in output]
    -V, [--verbose=Enable verbose output mode]

Cleans up unused gems in your bundler directory
$ bundle clean --dry-run --force
Would have removed actionmailer (3.1.12)
Would have removed actionmailer (3.2.0.rc2)
Would have removed actionpack (3.1.12)
Would have removed actionpack (3.2.0.rc2)
Would have removed activemodel (3.1.12)
...

edit:

This is not recommended if you're using a global gemset (i.e. - all of your projects keep their gems in the same place). There're few ways to keep each project's gems separate, though:

  1. rvm gemsets (http://rvm.io/gemsets/basics)
  2. bundle install with any of the following options: --deployment or --path=<path> (http://bundler.io/v1.3/man/bundle-install.1.html)

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

Faced the same problem, I was not able to run wordpress docker container with mysql version 8 as its default authentication mechanism is caching_sha2_password instead of mysql_native_password.

In order to fix this problem we must reset default authentication mechanism to mysql_native_password.

Find my.cnf file in your mysql installation, usually on a linux machine it is at the following location - /etc/mysql

Edit my.cnf file and add following line just under heading [mysqld]

default_authentication_plugin= mysql_native_password

Save the file then log into mysql command line using root user

run command FLUSH PRIVILEGES;

To compare two elements(string type) in XSLT?

First of all, the provided long code:

    <xsl:choose>
        <xsl:when test="OU_NAME='OU_ADDR1'">   --comparing two elements coming from XML             
            <!--remove if  adrees already contain  operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="OU_NAME"/>
            <fo:block/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:otherwise>
    </xsl:choose>

is equivalent to this, much shorter code:

<xsl:if test="not(OU_NAME='OU_ADDR1)'">
              <xsl:value-of select="OU_NAME"/>
        </xsl:if>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>

Now, to your question:

how to compare two elements coming from xml as string

In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator = and the function not() together with the operator =.

$str1 = $str2

evaluates to true() exactly when the string $str1 is equal to the string $str2.

not($str1 = $str2)

evaluates to true() exactly when the string $str1 is not equal to the string $str2.

There is also the != operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.

Now, the rules for comparing two element nodes are similar:

$el1 = $el2

evaluates to true() exactly when the string value of $el1 is equal to the string value of $el2.

not($el1 = $el2)

evaluates to true() exactly when the string value of $el1 is not equal to the string value of $el2.

However, if one of the operands of = is a node-set, then

 $ns = $str

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string $str

$ns1 = $ns2

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string value of some node from $ns2

Therefore, the expression:

OU_NAME='OU_ADDR1'

evaluates to true() only when there is at least one element child of the current node that is named OU_NAME and whose string value is the string 'OU_ADDR1'.

This is obviously not what you want!

Most probably you want:

OU_NAME=OU_ADDR1

This expression evaluates to true exactly there is at least one OU_NAME child of the current node and one OU_ADDR1 child of the current node with the same string value.

Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt, le, eq, gt, ge and the inherited from XPath 1.0 general comparison operator =.

Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.

Send POST data using XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
    // do something to response
    console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');

Or if you can count on browser support you could use FormData:

var data = new FormData();
data.append('user', 'person');
data.append('pwd', 'password');
data.append('organization', 'place');
data.append('requiredkey', 'key');

var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.onload = function () {
    // do something to response
    console.log(this.responseText);
};
xhr.send(data);

Singleton design pattern vs Singleton beans in Spring container

A singleton bean in Spring and the singleton pattern are quite different. Singleton pattern says that one and only one instance of a particular class will ever be created per classloader.

The scope of a Spring singleton is described as "per container per bean". It is the scope of bean definition to a single object instance per Spring IoC container. The default scope in Spring is Singleton.

Even though the default scope is singleton, you can change the scope of bean by specifying the scope attribute of <bean ../> element.

<bean id=".." class=".." scope="prototype" />

PHP Fatal error: Using $this when not in object context

It seems to me to be a bug in PHP. The error

'Fatal error: Uncaught Error: Using $this when not in object context in'

appears in the function using $this, but the error is that the calling function is using non-static function as a static. I.e:

Class_Name
{
    function foo()
    {
        $this->do_something(); // The error appears there.
    }
    function do_something()
    {
        ///
    }
}

While the error is here:

Class_Name::foo();

Java :Add scroll into text area

Try adding these two lines to your code. I hope it will work. It worked for me :)

display.setLineWrap(true);
display.setWrapStyleWord(true);

Picture of output is shown below

enter image description here

How to make an alert dialog fill 90% of screen size?

    final AlertDialog alertDialog;

    LayoutInflater li = LayoutInflater.from(mActivity);
    final View promptsView = li.inflate(R.layout.layout_dialog_select_time, null);

    RecyclerView recyclerViewTime;
    RippleButton buttonDone;

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mActivity);
    alertDialogBuilder.setView(promptsView);

    // create alert dialog
    alertDialog = alertDialogBuilder.create();

    /**
     * setting up window design
     */
    alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);


    alertDialog.show();

    DisplayMetrics metrics = new DisplayMetrics(); //get metrics of screen
    mActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int height = (int) (metrics.heightPixels * 0.9); //set height to 90% of total
    int width = (int) (metrics.widthPixels * 0.9); //set width to 90% of total

    alertDialog.getWindow().setLayout(width, height); //set layout
    recyclerViewTime = promptsView.findViewById(R.id.recyclerViewTime);


    DialogSelectTimeAdapter dialogSelectTimeAdapter = new DialogSelectTimeAdapter(this);
    RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(this);
    recyclerViewTime.setLayoutManager(linearLayoutManager);
    recyclerViewTime.setAdapter(dialogSelectTimeAdapter);

    buttonDone = promptsView.findViewById(R.id.buttonDone);
    buttonDone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            alertDialog.dismiss();

        }
    });

Installation of SQL Server Business Intelligence Development Studio

It sounds like you have installed SQL Server 2005 Express Edition, which does not include SSIS or the Business Intelligence Development Studio.

BIDS is only provided with the (not free) Standard, Enterprise and Developer Editions.

EDIT

This information was correct for SQL Server 2005. Since SQL Server 2014, Developer Edition has been free. BIDS has been replaced by SQL Server Data Tools, a free plugin for Visual Studio (including the free Visual Studio Community Edition).

How to get terminal's Character Encoding

locale command with no arguments will print the values of all of the relevant environment variables except for LANGUAGE.

For current encoding:

locale charmap

For available locales:

locale -a

For available encodings:

locale -m

How do I check if a given string is a legal/valid file name under Windows?

From MSDN's "Naming a File or Directory," here are the general conventions for what a legal file name is under Windows:

You may use any character in the current code page (Unicode/ANSI above 127), except:

  • < > : " / \ | ? *
  • Characters whose integer representations are 0-31 (less than ASCII space)
  • Any other character that the target file system does not allow (say, trailing periods or spaces)
  • Any of the DOS names: CON, PRN, AUX, NUL, COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9 (and avoid AUX.txt, etc)
  • The file name is all periods

Some optional things to check:

  • File paths (including the file name) may not have more than 260 characters (that don't use the \?\ prefix)
  • Unicode file paths (including the file name) with more than 32,000 characters when using \?\ (note that prefix may expand directory components and cause it to overflow the 32,000 limit)

Delete default value of an input text on click

Just use a placeholder tag in your input instead of value

How do I use hexadecimal color strings in Flutter?

Unfortunately, the Color class constructor in Flutter does not accept a simple hexadecimal string (like #bfeb91 in CSS).

Instead, it requires an integer like 0xFFBFEB91.

So here is we convert a hex string to an integer

A simple function

Give this function a hex string and it will return you a Color!

Color _getColorFromHex(String hexColor) {
  hexColor = hexColor.replaceAll("#", "");
  if (hexColor.length == 6) {
    hexColor = "FF" + hexColor;
  }
  if (hexColor.length == 8) {
    return Color(int.parse("0x$hexColor"));
  }
}

Use it like this

Text(
  'Hello World',
  style: TextStyle(backgroundColor: _getColorFromHex('ff00aa')), // or 'bfeb91', or 'ffbfeb91'
),

As a String extension

Leveraging the power of Dart extensions we can augment String with a function that returns a Color:

extension ColorExtension on String {
  toColor() {
    var hexColor = this.replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    }
    if (hexColor.length == 8) {
      return Color(int.parse("0x$hexColor"));
    }
  }
}

Use it like this

Text(
  'Hello World',
  style: TextStyle(backgroundColor: '#bfeb91'.toColor()), // or 'bfeb91', or 'ffbfeb91'
),

Python 3 Building an array of bytes

Here is a solution to getting an array (list) of bytes:

I found that you needed to convert the Int to a byte first, before passing it to the bytes():

bytes(int('0xA2', 16).to_bytes(1, "big"))

Then create a list from the bytes:

list(frame)

So your code should look like:

frame = b""
frame += bytes(int('0xA2', 16).to_bytes(1, "big"))
frame += bytes(int('0x01', 16).to_bytes(1, "big"))
frame += bytes(int('0x02', 16).to_bytes(1, "big"))
frame += bytes(int('0x03', 16).to_bytes(1, "big"))
frame += bytes(int('0x04', 16).to_bytes(1, "big"))
bytesList = list(frame)

The question was for an array (list) of bytes. You accepted an answer that doesn't tell how to get a list so I'm not sure if this is actually what you needed.

Filtering a data frame by values in a column

Try this:

subset(studentdata, Drink=='water')

that should do it.

Python: Converting from ISO-8859-1/latin1 to UTF-8

Try decoding it first, then encoding:

apple.decode('iso-8859-1').encode('utf8')

XmlWriter to Write to a String Instead of to a File

Guys don't forget to call xmlWriter.Close() and xmlWriter.Dispose() or else your string won't finish creating. It will just be an empty string

Hibernate, @SequenceGenerator and allocationSize

To be absolutely clear... what you describe does not conflict with the spec in any way. The spec talks about the values Hibernate assigns to your entities, not the values actually stored in the database sequence.

However, there is the option to get the behavior you are looking for. First see my reply on Is there a way to dynamically choose a @GeneratedValue strategy using JPA annotations and Hibernate? That will give you the basics. As long as you are set up to use that SequenceStyleGenerator, Hibernate will interpret allocationSize using the "pooled optimizer" in the SequenceStyleGenerator. The "pooled optimizer" is for use with databases that allow an "increment" option on the creation of sequences (not all databases that support sequences support an increment). Anyway, read up about the various optimizer strategies there.

how to set default culture info for entire c# application

With 4.0, you will need to manage this yourself by setting the culture for each thread as Alexei describes. But with 4.5, you can define a culture for the appdomain and that is the preferred way to handle this. The relevant apis are CultureInfo.DefaultThreadCurrentCulture and CultureInfo.DefaultThreadCurrentUICulture.

Import and Export Excel - What is the best library?

How about the apache POI java library. I havent used it for Excel , but did use it for Word 2007.

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>

Here's something else I found interesting. If your source is a DataTable, you can use dynamic sorting without using Dynamic Linq

DataTable orders = dataSet.Tables["SalesOrderHeader"];
EnumerableRowCollection<DataRow> query = from order in orders.AsEnumerable()
                                         orderby order.Field<DateTime>("OrderDate")
                                         select order;
DataView view = query.AsDataView();
bindingSource1.DataSource = view;

reference: http://msdn.microsoft.com/en-us/library/bb669083.aspx (Using DataSetExtensions)

Here is one more way to do it by converting it to a DataView:

DataTable contacts = dataSet.Tables["Contact"];    
DataView view = contacts.AsDataView();    
view.Sort = "LastName desc, FirstName asc";    
bindingSource1.DataSource = view;
dataGridView1.AutoResizeColumns();

How to make a GridLayout fit screen size

Grid Layout

       <GridLayout
        android:layout_width="match_parent"
        android:layout_weight="3"
        android:columnCount="2"
        android:padding="10dp"
        android:rowCount="3"
        android:background="@drawable/background_down"
        android:layout_height="0dp">


        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="15dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/user" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Users"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>

        </androidx.cardview.widget.CardView>
        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="15dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/addusers" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Add Users"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>


        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="15dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/newspaper" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Report"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>



        </androidx.cardview.widget.CardView>
        <androidx.cardview.widget.CardView
            android:layout_height="0dp"
            android:layout_width="0dp"
            android:layout_columnWeight="1"
            android:layout_rowWeight="1"
            android:layout_margin="10dp"
            android:elevation="10dp"
            app:cardCornerRadius="5dp"
            >
            <LinearLayout
                android:weightSum="3"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                >

                <ImageView
                    android:layout_weight="2"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:layout_margin="15dp"
                    android:src="@drawable/settings" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Settings"
                    android:textSize="16sp"
                    android:layout_marginStart="15dp"
                    android:layout_marginLeft="15dp" />
            </LinearLayout>


        </androidx.cardview.widget.CardView>

    </GridLayout>

Full tutorials can be found here .

[Android Grid Layout With CardView and OnItemClickListener][2]

How do I address unchecked cast warnings?

This stuff is hard, but here are my current thoughts:

If your API returns Object, then there's nothing you can do -- no matter what, you will be blindly casting the object. You let Java throw ClassCastExceptions, or you can check each element yourself and throw Assertions or IllegalArgumentExceptions or some such, but these runtime checks are all equivalent. You have to suppress the compile time unchecked cast no matter what you do at runtime.

I'd just prefer to blind cast and let the JVM perform its runtime check for me since we "know" what the API should return, and are usually willing to assume that the API works. Use generics everywhere above the cast, if you need them. You aren't really buying anything there since you still have the single blind cast, but at least you can use generics from there on up so the JVM can help you avoid blind casts in other pieces of your code.

In this particular case, presumably you can see the call to SetAttribute and see the type is going in, so just blind-casting the type to same on the way out is not immoral. Add a comment referencing the SetAttribute and be done with it.

tell pip to install the dependencies of packages listed in a requirement file

Extending Piotr's answer, if you also need a way to figure what to put in requirements.in, you can first use pip-chill to find the minimal set of required packages you have. By combining these tools, you can show the dependency reason why each package is installed. The full cycle looks like this:

  1. Create virtual environment:
    $ python3 -m venv venv
  2. Activate it:
    $ . venv/bin/activate
  3. Install newest version of pip, pip-tools and pip-chill:
    (venv)$ pip install --upgrade pip
    (venv)$ pip install pip-tools pip-chill
  4. Build your project, install more pip packages, etc, until you want to save...
  5. Extract minimal set of packages (ie, top-level without dependencies):
    (venv)$ pip-chill --no-version > requirements.in
  6. Compile list of all required packages (showing dependency reasons):
    (venv)$ pip-compile requirements.in
  7. Make sure the current installation is synchronized with the list:
    (venv)$ pip-sync

ERROR: Sonar server 'http://localhost:9000' can not be reached

For me the issue was that the maven sonar plugin was using proxy servers defined in the maven settings.xml. I was trying to access the sonarque on another (not localhost alias) and so it was trying to use the proxy server to access it. Just added my alias to nonProxyHosts in settings.xml and it is working now. I did not face this issue in maven sonar plugin 3.2, only after i upgraded it.

<proxy>
  <id>proxy_id</id>
  <active>true</active>
  <protocol>http</protocol>
  <host>your-proxy-host/host>
  <port>your-proxy-host</port>
  <nonProxyHosts>localhost|127.0.*|other-non-proxy-hosts</nonProxyHosts>
</proxy>enter code here

How to stop PHP code execution?

or try

trigger_error('Die', E_ERROR);

CSS: Change image src on img:hover

There is another simple way using HTML and CSS only!

Just wrap your <img> tag with div like so:

<div class="image-wrapper">
    <img src="http://dummyimage.com/100x100/000/fff">
</div>

Then, in your CSS file hide the img and set the background image for the wrapping div element:

.image-wrapper:hover {
    background-image: url(http://dummyimage.com/100x100/eb00eb/fff);
    background-size: contain;
    background-repeat: no-repeat;
}

.image-wrapper:hover img {
    display: none;
}


Et voilà!

Is there a <meta> tag to turn off caching in all browsers?

Try using

    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Expires" CONTENT="-1">

Class is not abstract and does not override abstract method

If you're trying to take advantage of polymorphic behavior, you need to ensure that the methods visible to outside classes (that need polymorphism) have the same signature. That means they need to have the same name, number and order of parameters, as well as the parameter types.

In your case, you might do better to have a generic draw() method, and rely on the subclasses (Rectangle, Ellipse) to implement the draw() method as what you had been thinking of as "drawEllipse" and "drawRectangle".

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

How can I explicitly free memory in Python?

As other answers already say, Python can keep from releasing memory to the OS even if it's no longer in use by Python code (so gc.collect() doesn't free anything) especially in a long-running program. Anyway if you're on Linux you can try to release memory by invoking directly the libc function malloc_trim (man page). Something like:

import ctypes
libc = ctypes.CDLL("libc.so.6")
libc.malloc_trim(0)

How do I install Python 3 on an AWS EC2 instance?

Here is the one command to install python3 on Amazon linux ec2 instance:

$sudo yum install python3 -y

$python3 --version

Python 3.7.6

Key Shortcut for Eclipse Imports

Some other useful shortcuts:

  1. Alt + Shift + R : Rename
  2. Alt + Shift + Y : Word wrap
  3. Alt + Shift + V : Move the selected elements
  4. Alt + Shift + I : Inline refactoring
  5. Alt + Shift + M : Extract Method refactoring.
  6. Alt + Shift + L : Extract Local Variable
  7. Alt + Shift + A : Block selection mode
  8. Alt + Shift + Arrow Keys: selects enclosing elements
  9. Alt + Shift + F1: Focus on eclipse element to know plugin implementation details.
  10. Alt + Shift + F2: Plugin implementation details.
  11. F4 : Type Hierarchy
  12. Ctrl + Shift + T : Open Type
  13. Ctrl + Shift + H: Open Type in Hierarchy
  14. Ctrl + Alt + H: Call Hierarchy
  15. Ctrl + Shift + G: Reference in workspace
  16. Ctrl + Alt + G: Quick Search for selected text
  17. Ctrl + Shift + O: Organize imports
  18. Ctrl + Shift + M: Add import for currently selected.
  19. Ctrl + Shift + L: Shows you a List of your currently defined shortcut keys
  20. Ctrl + Shift + U: Occurrence in current file
  21. Ctrl + Shift + A: Open plug-in Artifact
  22. Ctrl + Shift + {: Two side by side editors with current file
  23. Ctrl + Shift + Space : Parameter Hints
  24. Ctrl + Shift + Mouse hover : To view javadoc
  25. Shift + Mouse hover : To view source code
  26. Ctrl + Space : Content Assist
  27. Ctrl + F3/O : Outline
  28. Ctrl + T: Type Hierarchy
  29. Ctrl + H : Open Search Dialog
  30. Ctrl + 1 : Quick Fix
  31. Ctrl+Shift+NUM_KEYPAD_DIVIDE : Collapse All code blocks
  32. Ctrl+Shift+NUM_KEYPAD_MULTIPLY : To open all code blocks
  33. Alt + left arrow : Open recently closed file

Ctrl+Shift+ any key :Direct actions (on text mostly)

Alt+Shift+ any key : Indirect actions


Ctrl It was originally used to send Control character to terminals. Ctrl commands are commonly used shortcuts. (In Mac Command)

Alt It enables alternate uses for other keys.


The above shortcuts are default, if we want to change shortcuts we can do. In eclipse -> Windows -> preferences -> keys. Where we can find all shortcuts with full details:
enter image description here

and
https://shortcutworld.com/IntelliJ-IDEA/win/IntelliJ_Shortcuts https://shortcutworld.com/Eclipse/win/Eclipse-Helios_Shortcuts https://www.jetbrains.com/help/idea/migrating-from-eclipse-to-intellij-idea.html#Shortcuts

How do you handle a "cannot instantiate abstract class" error in C++?

If anyone is getting this error from a function, try using a reference to the abstract class in the parameters instead.

void something(Abstract bruh){
}

to

void something(Abstract& bruh){
}

LaTeX: remove blank page after a \part or \chapter

Although I guess you do not need an answer any longer, I am giving the solution for those who will come to see this post.

Derived from book.cls

\def\@endpart{\vfil\newpage
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}

It is "\newpage" at the first line of this fragment that adds a redundant blank page after the part header page. So you must redefine the command \@endpart. Add the following snippet to the beggining of your tex file.

\makeatletter
\renewcommand\@endpart{\vfil
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}
\makeatother

Disable double-tap "zoom" option in browser on touch devices

Note (as of 2020-08-04): this solution does not appear to work in iOS Safari v12+. I will update this answer and delete this note once I find a clear solution that covers iOS Safari.

CSS-only solution

Add touch-action: manipulation to any element on which you want to disable double tap zoom, like with the following disable-dbl-tap-zoom class:

.disable-dbl-tap-zoom {
  touch-action: manipulation;
}

From the touch-action docs (emphasis mine):

manipulation

Enable panning and pinch zoom gestures, but disable additional non-standard gestures such as double-tap to zoom.

This value works on Android and on iOS.

How do I conditionally apply CSS styles in AngularJS?

One more (in the future) way to conditionally apply style is by conditionally creating scoped style

<style scoped type="text/css" ng-if="...">

</style>

But nowadays only FireFox supports scoped styles.

jQuery or JavaScript auto click

First i tried with this sample code:

$(document).ready(function(){ 
     $('#upload-file').click(); 
});

It didn't work for me. Then after, tried with this

$(document).ready(function(){ 
     $('#upload-file')[0].click(); 
});

No change. At last, tried with this

$(document).ready(function(){ 
     $('#upload-file')[0].click(function(){
     }); 
});

Solved my problem. Helpful for anyone.

Set System.Drawing.Color values

using System;
using System.Drawing;
public struct MyColor
    {
        private byte a, r, g, b;        
        public byte A
        {
            get
            {
                return this.a;
            }
        }
        public byte R
        {
            get
            {
                return this.r;
            }
        }
        public byte G
        {
            get
            {
                return this.g;
            }
        }
        public byte B
        {
            get
            {
                return this.b;
            }
        }       
        public MyColor SetAlpha(byte value)
        {
            this.a = value;
            return this;
        }
        public MyColor SetRed(byte value)
        {
            this.r = value;
            return this;
        }
        public MyColor SetGreen(byte value)
        {
            this.g = value;
            return this;
        }
        public MyColor SetBlue(byte value)
        {
            this.b = value;
            return this;
        }
        public int ToArgb()
        {
            return (int)(A << 24) || (int)(R << 16) || (int)(G << 8) || (int)(B);
        }
        public override string ToString ()
        {
            return string.Format ("[MyColor: A={0}, R={1}, G={2}, B={3}]", A, R, G, B);
        }

        public static MyColor FromArgb(byte alpha, byte red, byte green, byte blue)
        {
            return new MyColor().SetAlpha(alpha).SetRed(red).SetGreen(green).SetBlue(blue);
        }
        public static MyColor FromArgb(byte red, byte green, byte blue)
        {
            return MyColor.FromArgb(255, red, green, blue);
        }
        public static MyColor FromArgb(byte alpha, MyColor baseColor)
        {
            return MyColor.FromArgb(alpha, baseColor.R, baseColor.G, baseColor.B);
        }
        public static MyColor FromArgb(int argb)
        {
            return MyColor.FromArgb(argb & 255, (argb >> 8) & 255, (argb >> 16) & 255, (argb >> 24) & 255);
        }   
        public static implicit operator Color(MyColor myColor)
        {           
            return Color.FromArgb(myColor.ToArgb());
        }
        public static implicit operator MyColor(Color color)
        {
            return MyColor.FromArgb(color.ToArgb());
        }
    }

libclntsh.so.11.1: cannot open shared object file.

Just pass your Oracle path variables before you run any scripts:
Like for perl you can do add below in beginning of your script:

BEGIN {
   my $ORACLE_HOME     = "/usr/lib/oracle/11.2/client64";
   my $LD_LIBRARY_PATH = "$ORACLE_HOME/lib";
   if ($ENV{ORACLE_HOME} ne $ORACLE_HOME
   || $ENV{LD_LIBRARY_PATH} ne $LD_LIBRARY_PATH
   ) {
      $ENV{ORACLE_HOME}     = "/usr/lib/oracle/11.2/client64";
      $ENV{LD_LIBRARY_PATH} = "$ORACLE_HOME/lib";
      exec { $^X } $^X, $0, @ARGV;
   }
}

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

increase javaMaxHeapsize in your build.gradle(Module:app) file

dexOptions {
    javaMaxHeapSize "1g"
}

to (Add this line in gradle)

 dexOptions {
        javaMaxHeapSize "4g"
    }

Integrating CSS star rating into an HTML form

CSS:

.rate-container > i {
    float: right;
}

.rate-container > i:HOVER,
.rate-container > i:HOVER ~ i {
    color: gold;
}

HTML:

<div class="rate-container">
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
    <i class="fa fa-star "></i>
</div>

"Non-static method cannot be referenced from a static context" error

setLoanItem() isn't a static method, it's an instance method, which means it belongs to a particular instance of that class rather than that class itself.

Essentially, you haven't specified what media object you want to call the method on, you've only specified the class name. There could be thousands of media objects and the compiler has no way of knowing what one you meant, so it generates an error accordingly.

You probably want to pass in a media object on which to call the method:

public void loanItem(Media m) {
    m.setLoanItem("Yes");
}

How to get numeric value from a prompt box?

var xInt = parseInt(x)

This will return either the integer value, or NaN.

Read more about parseInt here.

Linking to an external URL in Javadoc?

Javadocs don't offer any special tools for external links, so you should just use standard html:

See <a href="http://groversmill.com/">Grover's Mill</a> for a history of the
Martian invasion.

or

@see <a href="http://groversmill.com/">Grover's Mill</a> for a history of 
the Martian invasion.

Don't use {@link ...} or {@linkplain ...} because these are for links to the javadocs of other classes and methods.

Difference between <context:annotation-config> and <context:component-scan>

<context:component-scan base-package="package name" />:

This is used to tell the container that there are bean classes in my package scan those bean classes. In order to scan bean classes by container on top of the bean we have to write one of the stereo type annotation like following.

@Component, @Service, @Repository, @Controller

<context:annotation-config />:

If we don't want to write bean tag explicitly in XML then how the container knows if there is a auto wiring in the bean. This is possible by using @Autowired annotation. we have to inform to the container that there is auto wiring in my bean by context:annotation-config.

Set focus on <input> element

You should use html autofocus for this:

<input *ngIf="show" #search type="text" autofocus /> 

Note: if your component is persisted and reused it will only autofocus the first time the fragment is attached. This can be overcome by having a global dom listener that checks for autofocus attribute inside a dom fragment when it is attached and then reapplying it or focus via javascript.

Using both Python 2.x and Python 3.x in IPython Notebook

With a current version of the Notebook/Jupyter, you can create a Python3 kernel. After starting a new notebook application from the command line with Python 2 you should see an entry „Python 3“ in the dropdown menu „New“. This gives you a notebook that uses Python 3. So you can have two notebooks side-by-side with different Python versions.

The Details

  1. Create this directory: mkdir -p ~/.ipython/kernels/python3
  2. Create this file ~/.ipython/kernels/python3/kernel.json with this content:

    {
        "display_name": "IPython (Python 3)", 
        "language": "python", 
        "argv": [
            "python3", 
            "-c", "from IPython.kernel.zmq.kernelapp import main; main()", 
            "-f", "{connection_file}"
        ], 
        "codemirror_mode": {
            "version": 2, 
            "name": "ipython"
        }
    }
    
  3. Restart the notebook server.

  4. Select „Python 3“ from the dropdown menu „New“
  5. Work with a Python 3 Notebook
  6. Select „Python 2“ from the dropdown menu „New“
  7. Work with a Python 2 Notebook

How can I limit possible inputs in a HTML5 "number" element?

it's very simple, with some javascript you can simulate a maxlength, check it out:

//maxlength="2"
<input type="number" onKeyDown="if(this.value.length==2) return false;" />

Dynamically generating a QR code with PHP

The phpqrcode library is really fast to configure and the API documentation is easy to understand.

In addition to abaumg's answer I have attached 2 examples in PHP from http://phpqrcode.sourceforge.net/examples/index.php

1. QR code encoder

first include the library from your local path

include('../qrlib.php');

then to output the image directly as PNG stream do for example:

QRcode::png('your texte here...');

to save the result locally as a PNG image:

$tempDir = EXAMPLE_TMP_SERVERPATH;

$codeContents = 'your message here...';

$fileName = 'qrcode_name.png';

$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = EXAMPLE_TMP_URLRELPATH.$fileName;

QRcode::png($codeContents, $pngAbsoluteFilePath); 

2. QR code decoder

See also the zxing decoder:

http://zxing.org/w/decode.jspx

Pretty useful to check the output.

3. List of Data format

A list of data format you can use in your QR code according to the data type :

  • Website URL: http://stackoverflow.com (including the protocole http://)
  • email address: mailto:[email protected]
  • Telephone Number: +16365553344 (including country code)
  • SMS Message: smsto:number:message
  • MMS Message: mms:number:subject
  • YouTube Video: youtube://ID (may work on iPhone, not standardized)

How can I create a simple index.html file which lists all files/directories?

There are enough valid reasons to explicitly disable automatic directory indexes in apache or other web servers. Or, for example, you might only want to include certain file types in the index. In such cases you might still want to have a statically generated index.html file for specific folders.

tree

tree is a minimalistic utility that is available on most unix-like systems (ubuntu/debian: sudo apt install tree, mac: brew install tree, windows: zip) and which can generate plain text, XML, JSON or HTML output.

Generate an HTML directory index one level deep:

tree -H '.' -L 1 --noreport --charset utf-8 > index.html

Only include specific file types that match a glob pattern, e.g. *.zip files:

tree -H '.' -L 1 --noreport --charset utf-8 -P "*.zip" > index.html

The argument to -H is what will be used as a base href, so you can pass either a relative path such as . or an absolute path from the web root, such as /files. -L 1 limits the listing to the current directory only.

Generator script with recursive traversal

I needed an index generator which I could style the way I want, and which would also include the file sizes, so ended up using this script — in addition to having customizable styling, the script can also recursively generate an index.html file in all the nested subdirectories.

Update: an updated version (python 3) of the index generation script that uses cleaner styling (inspired by caddyserver's file-server module), includes last modified times and is more responsive in mobile viewports.

Git pull - Please move or remove them before you can merge

If there are too many files to delete, which is actually a case for me. You can also try the following solution:

1) fetch

2) merge with a strategy. For instance this one works for me:

git.exe merge --strategy=ours master

How to open existing project in Eclipse

Try File > New > Project... > Android Project From Existing Code. Don't copy your project from pc into workspace, copy it elsewhere and let the eclipse copy it into workspace by menu commands above and checking copy in existing workspace.

Setting background color for a JFrame

You can use this code block for JFrame background color.

    JFrame frame = new JFrame("Frame BG color");
    frame.setLayout(null);
    
    frame.setSize(1000, 650);
    frame.getContentPane().setBackground(new Color(5, 65, 90));
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setVisible(true);

Are there .NET implementation of TLS 1.2?

as mentioned here you can just add this line

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

How can I parse a String to BigDecimal?

BigDecimal offers a string constructor. You'll need to strip all commas from the number, via via an regex or String filteredString=inString.replaceAll(",","").

You then simply call BigDecimal myBigD=new BigDecimal(filteredString);

You can also create a NumberFormat and call setParseBigDecimal(true). Then parse( will give you a BigDecimal without worrying about manually formatting.

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

In Windows, you need to set node.js folder path into system variables or user variables.

1) open Control Panel -> System and Security -> System -> Advanced System Settings -> Environment Variables

2) in "User variables" or "System variables" find variable PATH and add node.js folder path as value. Usually it is C:\Program Files\nodejs;. If variable doesn't exists, create it.

3) Restart your IDE or computer.

It is useful add also "npm" and "Git" paths as variable, separated by semicolon.

LDAP Authentication using Java

You will have to provide the entire user dn in SECURITY_PRINCIPAL

like this

env.put(Context.SECURITY_PRINCIPAL, "cn=username,ou=testOu,o=test"); 

How to keep a git branch in sync with master

concept47's approach is the right way to do it, but I'd advise to merge with the --no-ff option in order to keep your commit history clear.

git checkout develop
git pull --rebase
git checkout NewFeatureBranch
git merge --no-ff master

Convert integer to hexadecimal and back again

string HexFromID(int ID)
{
    return ID.ToString("X");
}

int IDFromHex(string HexID)
{
    return int.Parse(HexID, System.Globalization.NumberStyles.HexNumber);
}

I really question the value of this, though. You're stated goal is to make the value shorter, which it will, but that isn't a goal in itself. You really mean either make it easier to remember or easier to type.

If you mean easier to remember, then you're taking a step backwards. We know it's still the same size, just encoded differently. But your users won't know that the letters are restricted to 'A-F', and so the ID will occupy the same conceptual space for them as if the letter 'A-Z' were allowed. So instead of being like memorizing a telephone number, it's more like memorizing a GUID (of equivalent length).

If you mean typing, instead of being able to use the keypad the user now must use the main part of the keyboard. It's likely to be more difficult to type, because it won't be a word their fingers recognize.

A much better option is to actually let them pick a real username.

What's the key difference between HTML 4 and HTML 5?

You might be interested in this list of HTML5 elements and attributes.

Also, please note that it's "HTML 4", not "HTML4". Indeed, for HTML 5, both variants are used, but there is an important difference in meaning. HTML 5 refers to the name of the W3C specification, whereas "HTML5" is the document type of those HTML files with a text/html MIME type that follow this spec. The same goes for XHTML 5 vs. XHTML5.

Nested JSON objects - do I have to use arrays for everything?

Every object has to be named inside the parent object:

{ "data": {
    "stuff": {
        "onetype": [
            { "id": 1, "name": "" },
            { "id": 2, "name": "" }
        ],
        "othertype": [
            { "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
        ]
    },
    "otherstuff": {
        "thing":
            [[1, 42], [2, 2]]
    }
}
}

So you cant declare an object like this:

var obj = {property1, property2};

It has to be

var obj = {property1: 'value', property2: 'value'};

Best Practice for Forcing Garbage Collection in C#

The best practise is to not force a garbage collection in most cases. (Every system I have worked on that had forced garbage collections, had underlining problems that if solved would have removed the need to forced the garbage collection, and sped the system up greatly.)

There are a few cases when you know more about memory usage then the garbage collector does. This is unlikely to be true in a multi user application, or a service that is responding to more then one request at a time.

However in some batch type processing you do know more then the GC. E.g. consider an application that.

  • Is given a list of file names on the command line
  • Processes a single file then write the result out to a results file.
  • While processing the file, creates a lot of interlinked objects that can not be collected until the processing of the file have complete (e.g. a parse tree)
  • Does not keep much state between the files it has processed.

You may be able to make a case (after careful) testing that you should force a full garbage collection after you have process each file.

Another cases is a service that wakes up every few minutes to process some items, and does not keep any state while it’s asleep. Then forcing a full collection just before going to sleep may be worthwhile.

The only time I would consider forcing a collection is when I know that a lot of object had been created recently and very few objects are currently referenced.

I would rather have a garbage collection API when I could give it hints about this type of thing without having to force a GC my self.

See also "Rico Mariani's Performance Tidbits"

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

Upload the file Microsoft.ReportViewer.WebForms.dll to your bin directory of your web applicaion.

You can find this dll file in the bin directory of your local web application.

How to remove MySQL root password

I have also been through this problem,

First i tried setting my password of root to blank using command :

SET PASSWORD FOR root@localhost=PASSWORD('');

But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.

SET PASSWORD FOR [email protected]=PASSWORD('');

Just replace localhost with 127.0.0.1 and you are done .

DECODE( ) function in SQL Server

If I understand the question correctly, you want the equivalent of decode but in T-SQL

Select YourFieldAliasName =
CASE PC_SL_LDGR_CODE
    WHEN '02' THEN 'DR'
    ELSE 'CR'
END

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

You need to ensure that you specify the library path during linking when you compile your .c file:

gcc -I/usr/local/include xxx.c -o xxx -L/usr/local/lib -Wl,-R/usr/local/lib

The -Wl,-R part tells the resulting binary to also look for the library in /usr/local/lib at runtime before trying to use the one in /usr/lib/.

How to set the environmental variable LD_LIBRARY_PATH in linux

You should add more details about your distribution, for example under Ubuntu the right way to do this is to add a custom .conf file to /etc/ld.so.conf.d, for example

sudo gedit /etc/ld.so.conf.d/randomLibs.conf

inside the file you are supposed to write the complete path to the directory that contains all the libraries that you wish to add to the system, for example

/home/linux/myLocalLibs

remember to add only the path to the dir, not the full path for the file, all the libs inside that path will be automatically indexed.

Save and run sudo ldconfig to update the system with this libs.

Regular expression to return text between parenthesis

Building on tkerwin's answer, if you happen to have nested parentheses like in

st = "sum((a+b)/(c+d))"

his answer will not work if you need to take everything between the first opening parenthesis and the last closing parenthesis to get (a+b)/(c+d), because find searches from the left of the string, and would stop at the first closing parenthesis.

To fix that, you need to use rfind for the second part of the operation, so it would become

st[st.find("(")+1:st.rfind(")")]

"Content is not allowed in prolog" when parsing perfectly valid XML on GAE

In the spirit of "just delete all those weird characters before the <?xml", here's my Java code, which works well with input via a BufferedReader:

    BufferedReader test = new BufferedReader(new InputStreamReader(fisTest));
    test.mark(4);
    while (true) {
        int earlyChar = test.read();
        System.out.println(earlyChar);
        if (earlyChar == 60) {
            test.reset();
            break;
        } else {
            test.mark(4);
        }
    }

FWIW, the bytes I was seeing are (in decimal): 239, 187, 191.

pass post data with window.location.href

As it was said in other answers there is no way to make a POST request using window.location.href, to do it you can create a form and submit it immediately.

You can use this function:

function postForm(path, params, method) {
    method = method || 'post';

    var form = document.createElement('form');
    form.setAttribute('method', method);
    form.setAttribute('action', path);

    for (var key in params) {
        if (params.hasOwnProperty(key)) {
            var hiddenField = document.createElement('input');
            hiddenField.setAttribute('type', 'hidden');
            hiddenField.setAttribute('name', key);
            hiddenField.setAttribute('value', params[key]);

            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
}

postForm('mysite.com/form', {arg1: 'value1', arg2: 'value2'});

https://stackoverflow.com/a/133997/2965158

Bootstrap css hides portion of container below navbar navbar-fixed-top

It happens because with navbar-fixed-top class the navbar gets the position:fixed. This in turns take the navbar out of the document flow leaving the body to take up the space behind the navbar.

You need to apply padding-top or margin-top to your container, based on your requirements with values >= 50px. (or play around with different values)

The basic bootstrap navbar takes height around 40px. So if you give a padding-top or margin-top of 50px or more, you will always have that breathing space between your container and the navbar.

maven error: package org.junit does not exist

Ok, you've declared junit dependency for test classes only (those that are in src/test/java but you're trying to use it in main classes (those that are in src/main/java).

Either do not use it in main classes, or remove <scope>test</scope>.

How to calculate UILabel height dynamically?

This is the extension I use for calculating multiline UILabel heights, it's an adjusted snippet from a previous stack overflow post:

extension UILabel {
    func estimatedHeight(forWidth: CGFloat, text: String, ofSize: CGFloat) -> CGFloat {

        let size = CGSize(width: forWidth, height: CGFloat(MAXFLOAT))

        let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)

        let attributes = [NSFontAttributeName: UIFont.systemFont(ofSize: ofSize)]

        let rectangleHeight = String(text).boundingRect(with: size, options: options, attributes: attributes, context: nil).height

        return ceil(rectangleHeight)
    }
}

When should the xlsm or xlsb formats be used?

Just for posterity, here's the text from several external sources regarding the Excel file formats. Some of these have been mentioned in other answers to this question but without reproducing the essential content.

1. From Doug Mahugh, August 22, 2006:

...the new XLSB binary format. Like Open XML, it’s a full-fidelity file format that can store anything you can create in Excel, but the XLSB format is optimized for performance in ways that aren’t possible with a pure XML format.

The XLSB format (also sometimes referred to as BIFF12, as in “binary file format for Office 12”) uses the same Open Packaging Convention used by the Open XML formats and XPS. So it’s basically a ZIP container, and you can open it with any ZIP tool to see what’s inside. But instead of .XML parts within the package, you’ll find .BIN parts...

This article also refers to documentation about the BIN format, too lengthy to reproduce here.

2. From MSDN Archive, August 29, 2006 which in turn cites an already-missing blog post regarding the XLSB format:

Even though we’ve done a lot of work to make sure that our XML formats open quickly and efficiently, this binary format is still more efficient for Excel to open and save, and can lead to some performance improvements for workbooks that contain a lot of data, or that would require a lot of XML parsing during the Open process. (In fact, we’ve found that the new binary format is faster than the old XLS format in many cases.) Also, there is no macro-free version of this file format – all XLSB files can contain macros (VBA and XLM). In all other respects, it is functionally equivalent to the XML file format above:

File size – file size of both formats is approximately the same, since both formats are saved to disk using zip compression Architecture – both formats use the same packaging structure, and both have the same part-level structures. Feature support – both formats support exactly the same feature set Runtime performance – once loaded into memory, the file format has no effect on application/calculation speed Converters – both formats will have identical converter support

How can I reverse a NSArray in Objective-C?

I don't know of any built in method. But, coding by hand is not too difficult. Assuming the elements of the array you are dealing with are NSNumber objects of integer type, and 'arr' is the NSMutableArray that you want to reverse.

int n = [arr count];
for (int i=0; i<n/2; ++i) {
  id c  = [[arr objectAtIndex:i] retain];
  [arr replaceObjectAtIndex:i withObject:[arr objectAtIndex:n-i-1]];
  [arr replaceObjectAtIndex:n-i-1 withObject:c];
}

Since you start with a NSArray then you have to create the mutable array first with the contents of the original NSArray ('origArray').

NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr setArray:origArray];

Edit: Fixed n -> n/2 in the loop count and changed NSNumber to the more generic id due to the suggestions in Brent's answer.

What is the best way to conditionally apply attributes in AngularJS?

I got this working by hard setting the attribute. And controlling the attribute applicability using the boolean value for the attribute.

Here is the code snippet:

<div contenteditable="{{ condition ? 'true' : 'false'}}"></div>

I hope this helps.

Best approach to remove time part of datetime in SQL Server

CAST(round(cast(getdate()as real),0,1) AS datetime)

This method does not use string function. Date is basically a real datatype with digits before decimal are fraction of a day.

this I guess will be faster than a lot.

Remove multiple items from a Python list in just one statement

I don't know why everyone forgot to mention the amazing capability of sets in python. You can simply cast your list into a set and then remove whatever you want to remove in a simple expression like so:

>>> item_list = ['item', 5, 'foo', 3.14, True]
>>> item_list = set(item_list) - {'item', 5}
>>> item_list
{True, 3.14, 'foo'}
>>> # you can cast it again in a list-from like so
>>> item_list = list(item_list)
>>> item_list
[True, 3.14, 'foo']

Angular - ui-router get previous state

I keep track of previous states in $rootScope, so whenever in need I will just call the below line of code.

$state.go($rootScope.previousState);

In App.js:

$rootScope.$on('$stateChangeSuccess', function(event, to, toParams, from, fromParams) {
  $rootScope.previousState = from.name;
});

Table column sizing

I hacked this out for release Bootstrap 4.1.1 per my needs before I saw @florian_korner's post. Looks very similar.

If you use sass you can paste this snippet at the end of your bootstrap includes. It seems to fix the issue for chrome, IE, and edge. Does not seem to break anything in firefox.

@mixin make-td-col($size, $columns: $grid-columns) {
    width: percentage($size / $columns);
}

@each $breakpoint in map-keys($grid-breakpoints) {
    $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

    @for $i from 1 through $grid-columns {
        td.col#{$infix}-#{$i}, th.col#{$infix}-#{$i} {
            @include make-td-col($i, $grid-columns);
        }
    }
}

or if you just want the compiled css utility:

td.col-1, th.col-1 {
  width: 8.33333%; }

td.col-2, th.col-2 {
  width: 16.66667%; }

td.col-3, th.col-3 {
  width: 25%; }

td.col-4, th.col-4 {
  width: 33.33333%; }

td.col-5, th.col-5 {
  width: 41.66667%; }

td.col-6, th.col-6 {
  width: 50%; }

td.col-7, th.col-7 {
  width: 58.33333%; }

td.col-8, th.col-8 {
  width: 66.66667%; }

td.col-9, th.col-9 {
  width: 75%; }

td.col-10, th.col-10 {
  width: 83.33333%; }

td.col-11, th.col-11 {
  width: 91.66667%; }

td.col-12, th.col-12 {
  width: 100%; }

td.col-sm-1, th.col-sm-1 {
  width: 8.33333%; }

td.col-sm-2, th.col-sm-2 {
  width: 16.66667%; }

td.col-sm-3, th.col-sm-3 {
  width: 25%; }

td.col-sm-4, th.col-sm-4 {
  width: 33.33333%; }

td.col-sm-5, th.col-sm-5 {
  width: 41.66667%; }

td.col-sm-6, th.col-sm-6 {
  width: 50%; }

td.col-sm-7, th.col-sm-7 {
  width: 58.33333%; }

td.col-sm-8, th.col-sm-8 {
  width: 66.66667%; }

td.col-sm-9, th.col-sm-9 {
  width: 75%; }

td.col-sm-10, th.col-sm-10 {
  width: 83.33333%; }

td.col-sm-11, th.col-sm-11 {
  width: 91.66667%; }

td.col-sm-12, th.col-sm-12 {
  width: 100%; }

td.col-md-1, th.col-md-1 {
  width: 8.33333%; }

td.col-md-2, th.col-md-2 {
  width: 16.66667%; }

td.col-md-3, th.col-md-3 {
  width: 25%; }

td.col-md-4, th.col-md-4 {
  width: 33.33333%; }

td.col-md-5, th.col-md-5 {
  width: 41.66667%; }

td.col-md-6, th.col-md-6 {
  width: 50%; }

td.col-md-7, th.col-md-7 {
  width: 58.33333%; }

td.col-md-8, th.col-md-8 {
  width: 66.66667%; }

td.col-md-9, th.col-md-9 {
  width: 75%; }

td.col-md-10, th.col-md-10 {
  width: 83.33333%; }

td.col-md-11, th.col-md-11 {
  width: 91.66667%; }

td.col-md-12, th.col-md-12 {
  width: 100%; }

td.col-lg-1, th.col-lg-1 {
  width: 8.33333%; }

td.col-lg-2, th.col-lg-2 {
  width: 16.66667%; }

td.col-lg-3, th.col-lg-3 {
  width: 25%; }

td.col-lg-4, th.col-lg-4 {
  width: 33.33333%; }

td.col-lg-5, th.col-lg-5 {
  width: 41.66667%; }

td.col-lg-6, th.col-lg-6 {
  width: 50%; }

td.col-lg-7, th.col-lg-7 {
  width: 58.33333%; }

td.col-lg-8, th.col-lg-8 {
  width: 66.66667%; }

td.col-lg-9, th.col-lg-9 {
  width: 75%; }

td.col-lg-10, th.col-lg-10 {
  width: 83.33333%; }

td.col-lg-11, th.col-lg-11 {
  width: 91.66667%; }

td.col-lg-12, th.col-lg-12 {
  width: 100%; }

td.col-xl-1, th.col-xl-1 {
  width: 8.33333%; }

td.col-xl-2, th.col-xl-2 {
  width: 16.66667%; }

td.col-xl-3, th.col-xl-3 {
  width: 25%; }

td.col-xl-4, th.col-xl-4 {
  width: 33.33333%; }

td.col-xl-5, th.col-xl-5 {
  width: 41.66667%; }

td.col-xl-6, th.col-xl-6 {
  width: 50%; }

td.col-xl-7, th.col-xl-7 {
  width: 58.33333%; }

td.col-xl-8, th.col-xl-8 {
  width: 66.66667%; }

td.col-xl-9, th.col-xl-9 {
  width: 75%; }

td.col-xl-10, th.col-xl-10 {
  width: 83.33333%; }

td.col-xl-11, th.col-xl-11 {
  width: 91.66667%; }

td.col-xl-12, th.col-xl-12 {
  width: 100%; }

Classes residing in App_Code is not accessible

Put this at the top of the other files where you want to access the class:

using CLIck10.App_Code;

OR access the class from other files like this:

CLIck10.App_Code.Glob

Not sure if that's your issue or not but if you were new to C# then this is an easy one to get tripped up on.

Update: I recently found that if I add an App_Code folder to a project, then I must close/reopen Visual Studio for it to properly recognize this "special" folder.

How to "pretty" format JSON output in Ruby on Rails

If you're looking to quickly implement this in a Rails controller action to send a JSON response:

def index
  my_json = '{ "key": "value" }'
  render json: JSON.pretty_generate( JSON.parse my_json )
end

How to directly initialize a HashMap (in a literal way)?

This is one way.

Map<String, String> h = new HashMap<String, String>() {{
    put("a","b");
}};

However, you should be careful and make sure that you understand the above code (it creates a new class that inherits from HashMap). Therefore, you should read more here: http://www.c2.com/cgi/wiki?DoubleBraceInitialization , or simply use Guava:

Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);

ImmutableMap.of works for up to 5 entries. Otherwise, use the builder: source.

How to count the number of true elements in a NumPy bool array

boolarr.sum(axis=1 or axis=0)

axis = 1 will output number of trues in a row and axis = 0 will count number of trues in columns so

boolarr[[true,true,true],[false,false,true]]
print(boolarr.sum(axis=1))

will be (3,1)

Error Code: 1406. Data too long for column - MySQL

This is a step I use with ubuntu. It will allow you to insert more than 45 characters from your input but MySQL will cut your text to 45 characters to insert into the database.

  1. Run command

    sudo nano /etc/mysql/my.cnf

  2. Then paste this code

    [mysqld] sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

  3. restart MySQL

    sudo service mysql restart;

How to delete columns that contain ONLY NAs?

It seeems like you want to remove ONLY columns with ALL NAs, leaving columns with some rows that do have NAs. I would do this (but I am sure there is an efficient vectorised soution:

#set seed for reproducibility
set.seed <- 103
df <- data.frame( id = 1:10 , nas = rep( NA , 10 ) , vals = sample( c( 1:3 , NA ) , 10 , repl = TRUE ) )
df
#      id nas vals
#   1   1  NA   NA
#   2   2  NA    2
#   3   3  NA    1
#   4   4  NA    2
#   5   5  NA    2
#   6   6  NA    3
#   7   7  NA    2
#   8   8  NA    3
#   9   9  NA    3
#   10 10  NA    2

#Use this command to remove columns that are entirely NA values, it will elave columns where only some vlaues are NA
df[ , ! apply( df , 2 , function(x) all(is.na(x)) ) ]
#      id vals
#   1   1   NA
#   2   2    2
#   3   3    1
#   4   4    2
#   5   5    2
#   6   6    3
#   7   7    2
#   8   8    3
#   9   9    3
#   10 10    2

If you find yourself in the situation where you want to remove columns that have any NA values you can simply change the all command above to any.

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

It is not related with Firewall. I had the same issue accessing from office and from mobile. I cleaned the cookies and worked fine. You can read more at https://support.google.com/chromebook/answer/1085581?hl=en

How does OkHttp get Json string?

I am also faced the same issue

use this code:

// notice string() call
String resStr = response.body().string();    
JSONObject json = new JSONObject(resStr);

it definitely works

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

Overwriting my local branch with remote branch

git reset --hard

This is to revert all your local changes to the origin head

Remove white space above and below large text in an inline-block element

The browser is not adding any padding. Instead, letters (even uppercase letters) are generally considerably smaller in the vertical direction than the height of the font, not to mention the line height, which is typically by default about 1.2 times the font height (font size).

There is no general solution to this because fonts are different. Even for fixed font size, the height of a letter varies by font. And uppercase letters need not have the same height in a font.

Practical solutions can be found by experimentation, but they are unavoidably font-dependent. You will need to set the line height essentially smaller than the font size. The following seems to yield the desired result in different browsers on Windows, for the Arial font:

_x000D_
_x000D_
span.foo_x000D_
{_x000D_
  display: inline-block;_x000D_
  font-size: 50px;_x000D_
  background-color: green;_x000D_
  line-height: 0.75em;_x000D_
  font-family: Arial;_x000D_
}_x000D_
_x000D_
span.bar_x000D_
{_x000D_
  position: relative;_x000D_
  bottom: -0.02em;_x000D_
}
_x000D_
<span class=foo><span class=bar>BIG TEXT</span></span>
_x000D_
_x000D_
_x000D_

The nested span elements are used to displace the text vertically. Otherwise, the text sits on the baseline, and under the baseline, there is room reserved for descenders (as in letters j and y).

If you look closely (with zooming), you will notice that there is very small space above and below most letters here. I have set things so that the letter “G” fits in. It extends vertically a bit farther than other uppercase letters because that way the letters look similar in height. There are similar issues with other letters, like “O”. And you need to tune the settings if you’ll need the letter “Q” since it has a descender that extends a bit below the baseline (in Arial). And of course, if you’ll ever need “É”, or almost any diacritic mark, you’re in trouble.

How to get the width and height of an android.widget.ImageView?

If you have created multiple images dynamically than try this one:

// initialize your images array

private ImageView myImages[] = new ImageView[your_array_length];

// create programatically and add to parent view

 for (int i = 0; i < your_array_length; i++) {
                myImages[i] = new ImageView(this);
                myImages[i].setId(i + 1);
                myImages[i].setBackgroundResource(your_array[i]);
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                        frontWidth[i], frontHeight[i]);
                ((MarginLayoutParams) params).setMargins(frontX_axis[i],
                        frontY_axis[i], 0, 0);
                myImages[i].setAdjustViewBounds(true);
                myImages[i].setLayoutParams(params);

                if (getIntent() != null && i != your_array,length) {
                    final int j = i;
                    myImages[j].getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                        public boolean onPreDraw() {
                            myImages[j].getViewTreeObserver().removeOnPreDrawListener(this);
                    finalHeight = myImages[j].getMeasuredHeight();
                        finalWidth = myImages[j].getMeasuredWidth();
                    your_textview.setText("Height: " + finalHeight + " Width: " + finalWidth);
                            return true;
                        }
                    });
                }
                your_parent_layout.addView(myImages[i], params);
            }

// That's it. Happy Coding.

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

Since people will be coming from Google, make sure you're in the right database.

Running SQL in the 'master' database will often return this error.

How to read a file from jar in Java?

A JAR is basically a ZIP file so treat it as such. Below contains an example on how to extract one file from a WAR file (also treat it as a ZIP file) and outputs the string contents. For binary you'll need to modify the extraction process, but there are plenty of examples out there for that.

public static void main(String args[]) {
    String relativeFilePath = "style/someCSSFile.css";
    String zipFilePath = "/someDirectory/someWarFile.war";
    String contents = readZipFile(zipFilePath,relativeFilePath);
    System.out.println(contents);
}

public static String readZipFile(String zipFilePath, String relativeFilePath) {
    try {
        ZipFile zipFile = new ZipFile(zipFilePath);
        Enumeration<? extends ZipEntry> e = zipFile.entries();

        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            // if the entry is not directory and matches relative file then extract it
            if (!entry.isDirectory() && entry.getName().equals(relativeFilePath)) {
                BufferedInputStream bis = new BufferedInputStream(
                        zipFile.getInputStream(entry));
                // Read the file
                    // With Apache Commons I/O
                 String fileContentsStr = IOUtils.toString(bis, "UTF-8");

                    // With Guava
                //String fileContentsStr = new String(ByteStreams.toByteArray(bis),Charsets.UTF_8);
                // close the input stream.
                bis.close();
                return fileContentsStr;
            } else {
                continue;
            }
        }
    } catch (IOException e) {
        logger.error("IOError :" + e);
        e.printStackTrace();
    }
    return null;
}

In this example I'm using Apache Commons I/O and if you are using Maven here is the dependency:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>