Programs & Examples On #Sql mode

How to turn on/off MySQL strict mode in localhost (xampp)?

To Change it permanently in ubuntu do the following

in the ubuntu command line

sudo nano /etc/mysql/my.cnf

Then add the following

[mysqld]
sql_mode=

Error related to only_full_group_by when executing a query in MySql

You can try to disable the only_full_group_by setting by executing the following:

mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
mysql> set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

MySQL 8 does not accept NO_AUTO_CREATE_USER so that needs to be removed.

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

Your server may read a different my.cnf than the one you're editing (unless you specified it when starting mysqld).

From the MySQL Certification Study Guide:

The search order includes two general option files, /etc/my.cnf and $MYSQL_HOME/my.cnf. The second file is used only if the MYSQL_HOME environment variable is set. Typically, you seet it to the MySQL installation directory. (The mysqld_safe script attempts to set MYSQL_HOME if it is not set before starting the server.) The option file search order also includes ~/.my.cnf (that is the home directory). This isn't an especially suitable location for server options. (Normally, you invoke the server as mysql, or as root with a --user=mysql option. The user-specific file read by the server would depend on which login account you invoke it from, possibly leading to inconsistent sets of options being used.)

Another possibility is of course, that your sql-mode option gets overwritten further down in the same file. Multiple options have to be separated by , in the same line.

P.S.: And you need the quotes, IIRC. Now that you've tried it without quotes, I'm pretty sure, you're editing the wrong file, since MySQL doesn't start when there's an error in the option file.

P.P.S.: Had a look at my config files again, there it's

[mysqld]
sql_mode = "NO_ENGINE_SUBSTITUTION"

and it's working.

IntelliJ - show where errors are

For those who even yet have the problem, try enabling "Build project automatically" in the Java compiler settings and see if that makes a difference as it worked for me.

Bootstrap table striped: How do I change the stripe background colour?

You have two options, either you override the styles with a custom stylesheet, or you edit the main bootstrap css file. I prefer the former.

Your custom styles should be linked after bootstrap.

<link rel="stylesheet" src="bootstrap.css">
<link rel="stylesheet" src="custom.css">

In custom.css

.table-striped>tr:nth-child(odd){
   background-color:red;
}

php exec command (or similar) to not wait for result

"exec nohup setsid your_command"

the nohup allows your_command to continue even though the process that launched may terminate first. If it does, the the SIGNUP signal will be sent to your_command causing it to terminate (unless it catches that signal and ignores it).

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

Failed to decode downloaded font

I also had same problem but i have solved by adding 'Content-Type' : 'application/x-font-ttf' in response header for all .ttf files

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

CSS3 transition on click using pure CSS

As jeremyjjbrow said, :active pseudo won't persist. But there's a hack for doing it on pure css. You can wrap it on a <a> tag, and apply the :active on it, like this:

<a class="test">
    <img class="crossRotate" src="images/cross.png" alt="Cross Menu button" />
 </a>

And the css:

.test:active .crossRotate {
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    }

Try it out... It works (at least on Chrome)!

Using union and order by clause in mysql

When you use an ORDER BY clause inside of a sub query used in conjunction with a UNION mysql will optimise away the ORDER BY clause.

This is because by default a UNION returns an unordered list so therefore an ORDER BY would do nothing.

The optimisation is mentioned in the docs and says:

To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION
(SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);

However, use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Therefore, the use of ORDER BY in this context is typically in conjunction with LIMIT, so that it is used to determine the subset of the selected rows to retrieve for the SELECT, even though it does not necessarily affect the order of those rows in the final UNION result. If ORDER BY appears without LIMIT in a SELECT, it is optimized away because it will have no effect anyway.

The last sentence of this is a bit misleading because it should have an effect. This optimisation causes a problem when you are in a situation where you need to order within the subquery.

To force MySQL to not do this optimisation you can add a LIMIT clause like so:

(SELECT 1 AS rank, id, add_date FROM my_table WHERE distance < 5 ORDER BY add_date LIMIT 9999999999)
UNION ALL
(SELECT 2 AS rank, id, add_date FROM my_table WHERE distance BETWEEN 5 AND 15 ORDER BY rank LIMIT 9999999999)
UNION ALL
(SELECT 3 AS rank, id, add_date from my_table WHERE distance BETWEEN 5 and 15 ORDER BY id LIMIT 9999999999)

A high LIMIT means that you could add an OFFSET on the overall query if you want to do something such as pagination.

This also gives you the added benefit of being able to ORDER BY different columns for each union.

What are all the differences between src and data-src attributes?

The first <img /> is invalid - src is a required attribute. data-src is an attribute than can be leveraged by, say, JavaScript, but has no presentational meaning.

How to read a file from jar in Java?

Just for completeness, there has recently been a question on the Jython mailinglist where one of the answers referred to this thread.

The question was how to call a Python script that is contained in a .jar file from within Jython, the suggested answer is as follows (with "InputStream" as explained in one of the answers above:

PythonInterpreter.execfile(InputStream)

Seeding the random number generator in Javascript

No, but here's a simple pseudorandom generator, an implementation of Multiply-with-carry I adapted from Wikipedia (has been removed since):

var m_w = 123456789;
var m_z = 987654321;
var mask = 0xffffffff;

// Takes any integer
function seed(i) {
    m_w = (123456789 + i) & mask;
    m_z = (987654321 - i) & mask;
}

// Returns number between 0 (inclusive) and 1.0 (exclusive),
// just like Math.random().
function random()
{
    m_z = (36969 * (m_z & 65535) + (m_z >> 16)) & mask;
    m_w = (18000 * (m_w & 65535) + (m_w >> 16)) & mask;
    var result = ((m_z << 16) + (m_w & 65535)) >>> 0;
    result /= 4294967296;
    return result;
}

EDIT: fixed seed function by making it reset m_z
EDIT2: Serious implementation flaws have been fixed

use localStorage across subdomains

This is how I solved it for my website. I redirected all the pages without www to www.site.com. This way, it will always take localstorage of www.site.com

Add the following to your .htacess, (create one if you already don't have it) in root directory

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Remove a modified file from pull request

Switch to the branch from which you created the pull request:

$ git checkout pull-request-branch

Overwrite the modified file(s) with the file in another branch, let's consider it's master:

git checkout origin/master -- src/main/java/HelloWorld.java

Commit and push it to the remote:

git commit -m "Removed a modified file from pull request"
git push origin pull-request-branch

How do I get the n-th level parent of an element in jQuery?

you can also use :

$(this).ancestors().eq(n) 

ex: $(this).ancestors().eq(2) -> the parent of the parent of this.

To show a new Form on click of a button in C#

This is the code that I needed. A defined user control's .show() function doesn't actually show anything. It must first be wrapped into a form like so:

CustomControl customControl = new CustomControl();
Form newForm = new Form();
newForm.Controls.Add(customControl);
newForm.ShowDialog();

Setting Column width in Apache POI

Unfortunately there is only the function setColumnWidth(int columnIndex, int width) from class Sheet; in which width is a number of characters in the standard font (first font in the workbook) if your fonts are changing you cannot use it. There is explained how to calculate the width in function of a font size. The formula is:

width = Truncate([{NumOfVisibleChar} * {MaxDigitWidth} + {5PixelPadding}] / {MaxDigitWidth}*256) / 256

You can always use autoSizeColumn(int column, boolean useMergedCells) after inputting the data in your Sheet.

Disable vertical sync for glxgears

The vblank_mode environment variable does the trick. You should then get several hundreds FPS on modern hardware. And you are now able to compare the results with others.

$>   vblank_mode=0 glxgears

Convert Pandas Column to DateTime

Use the pandas to_datetime function to parse the column as DateTime. Also, by using infer_datetime_format=True, it will automatically detect the format and convert the mentioned column to DateTime.

import pandas as pd
raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], infer_datetime_format=True)

How to check if running as root in a bash script

id -u is much better than whoami, since some systems like android may not provide the word root.

Example:

# whoami
whoami
whoami: unknown uid 0

Cannot enqueue Handshake after invoking quit

You can use debug: false,

Example: //mysql connection

var dbcon1 = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "",
      database: "node5",
      debug: false,
    });

From an array of objects, extract value of a property as array

If you want multiple values in ES6+ the following will work

objArray = [ { foo: 1, bar: 2, baz: 9}, { foo: 3, bar: 4, baz: 10}, { foo: 5, bar: 6, baz: 20} ];

let result = objArray.map(({ foo, baz }) => ({ foo, baz }))

This works as {foo, baz} on the left is using object destructoring and on the right side of the arrow is equivalent to {foo: foo, baz: baz} due to ES6's enhanced object literals.

Get list of JSON objects with Spring RestTemplate

After multiple tests, this is the best way I found :)

Set<User> test = httpService.get(url).toResponseSet(User[].class);

All you need there

public <T> Set<T> toResponseSet(Class<T[]> setType) {
    HttpEntity<?> body = new HttpEntity<>(objectBody, headers);
    ResponseEntity<T[]> response = template.exchange(url, method, body, setType);
    return Sets.newHashSet(response.getBody());
}

Excel Define a range based on a cell value

Say you have number 1,2,3,4,5,6, in cell A1,A2,A3,A4,A5,A6 respectively. in cell A7 we calculate the sum of A1:Ax. x is specified in cell B1 (in this case, x can be any number from 1 to 6). in cell A7, you can write the following formular:

=SUM(A1:INDIRECT(CONCATENATE("A",B1)))

CONCATENATE will give you the index of the cell Ax(if you put 3 in B1, CONCATENATE("A",B1)) gives A3).

INDIRECT convert "A3" to a index.

see this link Using the value in a cell as a cell reference in a formula?

span with onclick event inside a tag

When you click on hide me, both a and span clicks are triggering. Since the page is redirecting to another, you cannot see the working of hide()

You can see this for more clarification

http://jsfiddle.net/jzn82/

How to reset sequence in postgres and fill id column with new data?

Both provided solutions did not work for me;

> SELECT setval('seq', 0);
ERROR:  setval: value 0 is out of bounds for sequence "seq" (1..9223372036854775807)

setval('seq', 1) starts the numbering with 2, and ALTER SEQUENCE seq START 1 starts the numbering with 2 as well, because seq.is_called is true (Postgres version 9.0.4)

The solution that worked for me is:

> ALTER SEQUENCE seq RESTART WITH 1;
> UPDATE foo SET id = DEFAULT;

How do I localize the jQuery UI Datepicker?

just in case anyone is STILL stuck on this, despite the other answers, I solved this with:

$.datepicker.setDefaults($.datepicker.regional['en-GB']);

note the extra 'GB'. After that it worked fine.

How do I do base64 encoding on iOS?

I Think This will be helpful

 + (NSString *)toBase64String:(NSString *)string {
    NSData *data = [string dataUsingEncoding: NSUnicodeStringEncoding];

    NSString *ret = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    return ret;
    }

    + (NSString *)fromBase64String:(NSString *)string {
NSData *aData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSData *aDataDecoded = [[NSData alloc]initWithBase64EncodedString:string options:0];
NSString *decryptedStr = [[NSString alloc]initWithData:aDataDecoded encoding:NSUTF8StringEncoding];

return [decryptedStr autorelease];

}

How to extract epoch from LocalDate and LocalDateTime?

This is one way without using time a zone:

LocalDateTime now = LocalDateTime.now();
long epoch = (now.getLong(ChronoField.EPOCH_DAY) * 86400000) + now.getLong(ChronoField.MILLI_OF_DAY);

Capture iOS Simulator video for App Preview

A tip for users who like to use ZSH functions. You can simplify things a little by adding a function that does the same thing as @Tikhonov Alexander's answer.

Start out by typing:

edit ~/.zshrc

into your terminal.

Then add this function someplace in the file.

function recsim() {
    echo -n "Use CTRL+C to stop recording";
    xcrun simctl io booted recordVideo --codec=h264 --mask=black "$1.mp4";
}

To use, type something like:

recsim appPreview

into your terminal window. Note: Terminal must be restarted after adding the function before it will work.

This function is adapted from Antoine Van Der Lee's blog post on how to do this in bash, which can be found here.

How to convert a number to string and vice versa in C++

In C++17, new functions std::to_chars and std::from_chars are introduced in header charconv.

std::to_chars is locale-independent, non-allocating, and non-throwing.

Only a small subset of formatting policies used by other libraries (such as std::sprintf) is provided.

From std::to_chars, same for std::from_chars.

The guarantee that std::from_chars can recover every floating-point value formatted by to_chars exactly is only provided if both functions are from the same implementation

 // See en.cppreference.com for more information, including format control.
#include <cstdio>
#include <cstddef>
#include <cstdlib>
#include <cassert>
#include <charconv>

using Type =  /* Any fundamental type */ ;
std::size_t buffer_size = /* ... */ ;

[[noreturn]] void report_and_exit(int ret, const char *output) noexcept 
{
    std::printf("%s\n", output);
    std::exit(ret);
}
void check(const std::errc &ec) noexcept
{
    if (ec ==  std::errc::value_too_large)
        report_and_exit(1, "Failed");
}
int main() {
    char buffer[buffer_size];        
    Type val_to_be_converted, result_of_converted_back;

    auto result1 = std::to_chars(buffer, buffer + buffer_size,  val_to_be_converted);
    check(result1.ec);
    *result1.ptr = '\0';

    auto result2 = std::from_chars(buffer, result1.ptr, result_of_converted_back);
    check(result2.ec);

    assert(val_to_be_converted == result_of_converted_back);
    report_and_exit(0, buffer);
}

Although it's not fully implemented by compilers, it definitely will be implemented.

c# datagridview doubleclick on row with FullRowSelect

Don't manually edit the .designer files in visual studio that usually leads to headaches. Instead either specify it in the properties section of your DataGridRow which should be contained within a DataGrid element. Or if you just want VS to do it for you find the double click event within the properties page->events (little lightning bolt icon) and double click the text area where you would enter a function name for that event.

This link should help

http://msdn.microsoft.com/en-us/library/6w2tb12s(v=vs.90).aspx

How to create an AVD for Android 4.0

You can also get this problem if you have your Android SDK version controlled. You get a slightly different error:

Unable to find a 'userdata.img' file for ABI .svn to copy into the AVD folder.

For some reason, the Android Virtual Device (AVD) manager believes the .svn folder is specifying an application binary interface (ABI). It looks for userdata.img within the .svn folder and can't find it, so it fails.

I used the shell extension found in the responses for the Stack Overflow question Removing .svn files from all directories to remove all .svn folders recursively from the android-sdk folder. After this, the AVD manager was able to create an AVD successfully. I have yet to figure out how to get the SDK to play nicely with Subversion.

Instagram API to fetch pictures with specific hashtags

Take a look here in order to get started: http://instagram.com/developer/

and then in order to retrieve pictures by tag, look here: http://instagram.com/developer/endpoints/tags/

Getting tags from Instagram doesn't require OAuth, so you can make the calls via these URLs:

GET IMAGES https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={TOKEN}

SEARCH https://api.instagram.com/v1/tags/search?q={tag-query}&access_token={TOKEN}

TAG INFO https://api.instagram.com/v1/tags/{tag-name}?access_token={TOKEN}

How do I get rid of the "cannot empty the clipboard" error?

I have seen various answers which say when I uninstalled this or that it worked. I think that the uninstall is probably just sorting out an issue in the registry, rather it being an issue with the particular application that is being uninstalled.

I have also seen cases of people saying kill the RDP task but I don't have that and I still have the error.

I have seen cases of people saying clear the clipboard in Excel, but that doesn't work for me - nor does changing the settings in the Clipboard.

I believe that the issue is that an application has a lock on the clipboard and that application is not releasing it. The clipboard is a shared resource, so that implies that each application has to get a lock on it before changing it and then release the lock once it has completed the change, however, it looks like sometimes the lock is not released.

I found that the following cured it. Close down all MS applications including IE and Outlook. Check Task Manager processes to make sure that they are all gone.

Then restart the application where you had the Copy and Paste issue and it will probably then work.

Regards

Paul Simon

Get type name without full namespace

make use of (Type Properties)

 Name   Gets the name of the current member. (Inherited from MemberInfo.)
 Example : typeof(T).Name;

Set default option in mat-select

Try this

<mat-form-field>
    <mat-select [(ngModel)]="modeselect" [placeholder]="modeselect">
        <mat-option value="domain">Domain</mat-option>
        <mat-option value="exact">Exact</mat-option>
    </mat-select>
</mat-form-field>

Component:

export class SelectValueBindingExample {
    public modeselect = 'Domain';
}

Live demo

Also, don't forget to import FormsModule in your app.module

How to switch a user per task or set of tasks?

You can specify become_method to override the default method set in ansible.cfg (if any), and which can be set to one of sudo, su, pbrun, pfexec, doas, dzdo, ksu.

- name: I am confused
  command: 'whoami'
  become: true
  become_method: su
  become_user: some_user
  register: myidentity

- name: my secret identity
  debug:
    msg: '{{ myidentity.stdout }}'

Should display

TASK [my-task : my secret identity] ************************************************************
ok: [my_ansible_server] => {
    "msg": "some_user"
}

What's a "static method" in C#?

From another point of view: Consider that you want to make some changes on a single String. for example you want to make the letters Uppercase and so on. you make another class named "Tools" for these actions. there is no meaning of making instance of "Tools" class because there is not any kind of entity available inside that class (compare to "Person" or "Teacher" class). So we use static keyword in order to use "Tools" class without making any instance of that, and when you press dot after class name ("Tools") you can have access to the methods you want.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Tools.ToUpperCase("Behnoud Sherafati"));
        Console.ReadKey();
    }
}

public static class Tools
{
    public static string ToUpperCase(string str)
    {
        return str.ToUpper();

    }
}
}

How to add an UIViewController's view as subview

Change the frame size of viewcontroller.view.frame, and then add to subview. [viewcontrollerparent.view addSubview:viewcontroller.view]

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

In my case ; what solved my issue was.....

You may had json like this, the keys without " double quotations....

{ name: "test", phone: "2324234" }

So try any online Json Validator to make sure you have right syntax...

Json Validator Online

Using FileSystemWatcher to monitor a directory

The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

Call a Class From another class

Simply create an instance of Class2 and call the desired method.

Suggested reading: http://docs.oracle.com/javase/tutorial/java/javaOO/

How to create a windows service from java app

it's simple as you have to put shortcut in

Windows 7 C:\users\All Users\Start Menu\Programs\Startup(Admin) or User home directory(%userProfile%)

Windows 10 : In Run shell:startup

in it's property -> shortcut -> target - > java.exe -jar D:\..\runJar.jar

NOTE: This will run only after you login


With Admin Right

sc create serviceName binpath= "java.exe -jar D:\..\runJar.jar" Will create windows service

if you get timeout use cmd /c D:\JAVA7~1\jdk1.7.0_51\bin\java.exe -jar d:\jenkins\jenkins.war but even with this you'll get timeout but in background java.exe will be started. Check in task manager

NOTE: This will run at windows logon start-up(before sign-in, Based on service 'Startup Type')

Detailed explanation of creating windows service

Kubernetes how to make Deployment to update image

Another option which is more suitable for debugging but worth mentioning is to check in revision history of your rollout:

$ kubectl rollout history deployment my-dep
deployment.apps/my-dep
 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
3         <none>

To see the details of each revision, run:

 kubectl rollout history deployment my-dep --revision=2

And then returning to the previous revision by running:

 $kubectl rollout undo deployment my-dep --to-revision=2

And then returning back to the new one.
Like running ctrl+z -> ctrl+y (:

(*) The CHANGE-CAUSE is <none> because you should run the updates with the --record flag - like mentioned here:

kubectl set image deployment/nginx-deployment nginx=nginx:1.16.1 --record

(**) There is a discussion regarding deprecating this flag.

Selenium WebDriver.get(url) does not open the URL

@Neeraj

I've resolved this problem, but i'm not sure if you are the same reason.

In general, my problem was caused by some permission issues.

I tried to move my whole project into ~/:

mv xxx/ ~/

and then i change give it the 777 permission:

chmod -R 777 xxx/

I'm not familiar with linux permission so i just do this to make sure i have permission to execute the program.

Even you don't have permission, the selenium program will not prompt you.

So, good luck.

What's the difference between ViewData and ViewBag?

One main difference I noticed between ViewData and ViewBag is:

ViewData : it will return object does not matter what you have assigned into this and need to typecast again back to the original type.

ViewBag : it is enough smart to return exact type what you have assigned to it it does not matter weather you have assigned simple type (i.e. int, string etc.) or complex type.

Ex: Controller code.

 namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Products p1 = new Products();
            p1.productId = 101;
            p1.productName = "Phone";
            Products p2 = new Products();
            p2.productId = 102;
            p2.productName = "laptop";

            List<Products> products = new List<Products>();
            products.Add(p1);
            products.Add(p2);
            ViewBag.Countries = products;
            return View();
        }
    }
    public class Products
    {
        public int productId { get; set; }
        public string productName { get; set; }
    }
}

View Code.

<ul>
            @foreach (WebApplication1.Controllers.Products item in ViewBag.Countries)
            {
            <li>@item.productId &nbsp;&nbsp;&nbsp;@item.productName</li>
            }
        </ul>

OutPut Screen.

enter image description here

How to print instances of a class using print()?

There are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.

You just have to make sure you have parentheses at the end of your class, e.g:

print(class())

Here's an example of code from a project I was working on:

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number
    def __str__(self):
        return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number

class Hydrogen(Element):
    def __init__(self):
        super().__init__(name = "Hydrogen", symbol = "H", number = "1")

To print my Hydrogen class, I used the following:

print(Hydrogen())

Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.

Hope this helps, let me know if you have anymore questions.

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try this:

import matplotlib as plt

after importing the file we can use matplotlib library but remember to use it as plt

df.plt(kind='line',figsize=(10,5))

after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.

What characters do I need to escape in XML documents?

New, simplified answer to an old, commonly asked question...

Simplified XML Escaping (prioritized, 100% complete)

  1. Always (90% important to remember)

    • Escape < as &lt; unless < is starting a <tag/>.
    • Escape & as &amp; unless & is starting an &entity;.
  2. Attribute Values (9% important to remember)

    • attr=" 'Single quotes' are ok within double quotes."
    • attr=' "Double quotes" are ok within single quotes.'
    • Escape " as &quot; and ' as &apos; otherwise.
  3. Comments, CDATA, and Processing Instructions (0.9% important to remember)

    • <!-- Within comments --> nothing has to be escaped but no -- strings are allowed.
    • <![CDATA[ Within CDATA ]]> nothing has to be escaped, but no ]]> strings are allowed.
    • <?PITarget Within PIs ?> nothing has to be escaped, but no ?> strings are allowed.
  4. Esoterica (0.1% important to remember)

    • Escape ]]> as ]]&gt; unless ]]> is ending a CDATA section.
      (This rule applies to character data in general – even outside a CDATA section.)

how to implement a long click listener on a listview

    listView.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {
        return false;
    }
});

Definitely does the trick.

How to remove and clear all localStorage data

localStorage.clear();

should work.

High CPU Utilization in java application - why?

In the thread dump you can find the Line Number as below.

for the main thread which is currently running...

"main" #1 prio=5 os_prio=0 tid=0x0000000002120800 nid=0x13f4 runnable [0x0000000001d9f000]
   java.lang.Thread.State: **RUNNABLE**
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:313)
    at com.rana.samples.**HighCPUUtilization.main(HighCPUUtilization.java:17)**

How to use ImageBackground to set background image for screen in react-native

const img = '../../img/splash/splash_bg.png';
<ImageBackground  source={{ uri: img }} style={styles.backgroundImage} >
    </ImageBackground>

This worked for me. Reference to RN docs can be found here.I wrote mine by reading this- https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting

How can I access "static" class variables within class methods in Python?

Define class method:

class Foo(object):
    bar = 1
    @classmethod
    def bah(cls):    
        print cls.bar

Now if bah() has to be instance method (i.e. have access to self), you can still directly access the class variable.

class Foo(object):
    bar = 1
    def bah(self):    
        print self.bar

How do I update the password for Git?

The only way I could modify my git password was to go to Credential Manager in Windows (Windows Key + type 'credential') and edit the git entry under Windows Credentials Generic Credentials. Note: Not listed alphabetically

Error: could not find function "%>%"

the following can be used:

 install.packages("data.table")
 library(data.table)

HTML5 Audio Looping

This works and it is a lot easier to toggle that the methods above:

use inline: onended="if($(this).attr('data-loop')){ this.currentTime = 0; this.play(); }"

Turn the looping on by $(audio_element).attr('data-loop','1'); Turn the looping off by $(audio_element).removeAttr('data-loop');

Match exact string

It depends. You could

string.match(/^abc$/)

But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'

I think you would want to use \b (word boundaries):

_x000D_
_x000D_
var str = 'the first 3 letters of the alphabet are abc. not abc123';_x000D_
var pat = /\b(abc)\b/g;_x000D_
console.log(str.match(pat));
_x000D_
_x000D_
_x000D_

Live example: http://jsfiddle.net/uu5VJ/

If the former solution works for you, I would advise against using it.

That means you may have something like the following:

var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
    if (strs[i] == 'abc') {
        //do something 
    }
    else {
        //do something else
    }
}

While you could use

if (str[i].match(/^abc$/g)) {
    //do something 
}

It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.

More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

Does static constexpr variable inside a function make sense?

The short answer is that not only is static useful, it is pretty well always going to be desired.

First, note that static and constexpr are completely independent of each other. static defines the object's lifetime during execution; constexpr specifies that the object should be available during compilation. Compilation and execution are disjoint and discontiguous, both in time and space. So once the program is compiled, constexpr is no longer relevant.

Every variable declared constexpr is implicitly const but const and static are almost orthogonal (except for the interaction with static const integers.)

The C++ object model (§1.9) requires that all objects other than bit-fields occupy at least one byte of memory and have addresses; furthermore all such objects observable in a program at a given moment must have distinct addresses (paragraph 6). This does not quite require the compiler to create a new array on the stack for every invocation of a function with a local non-static const array, because the compiler could take refuge in the as-if principle provided it can prove that no other such object can be observed.

That's not going to be easy to prove, unfortunately, unless the function is trivial (for example, it does not call any other function whose body is not visible within the translation unit) because arrays, more or less by definition, are addresses. So in most cases, the non-static const(expr) array will have to be recreated on the stack at every invocation, which defeats the point of being able to compute it at compile time.

On the other hand, a local static const object is shared by all observers, and furthermore may be initialized even if the function it is defined in is never called. So none of the above applies, and a compiler is free not only to generate only a single instance of it; it is free to generate a single instance of it in read-only storage.

So you should definitely use static constexpr in your example.

However, there is one case where you wouldn't want to use static constexpr. Unless a constexpr declared object is either ODR-used or declared static, the compiler is free to not include it at all. That's pretty useful, because it allows the use of compile-time temporary constexpr arrays without polluting the compiled program with unnecessary bytes. In that case, you would clearly not want to use static, since static is likely to force the object to exist at runtime.

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I had the same error while copying and pasting a comment from the web

For me it was a single quote (') in the word

I just erased it and re-typed it.

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

Use Conda instead of pip. It works perfectly

conda install PyAudio

How to decode jwt token in javascript without using a library?

If you use Node.JS, You can use the native Buffer module by doing :

const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImp0aSI6ImU3YjQ0Mjc4LTZlZDYtNDJlZC05MTZmLWFjZDQzNzhkM2U0YSIsImlhdCI6MTU5NTg3NzUxOCwiZXhwIjoxNTk1ODgxMTE4fQ.WXyDlDMMSJAjOFF9oAU9JrRHg2wio-WolWAkAaY3kg4';
const base64Url = token.split('.')[1];
const decoded = Buffer.from(base64Url, 'base64').toString();
console.log(decoded)

And you're good to go :-)

Proper way of checking if row exists in table in PL/SQL block

You can do EXISTS in Oracle PL/SQL.

You can do the following:

DECLARE
    n_rowExist NUMBER := 0;
BEGIN
    SELECT CASE WHEN EXISTS (
      SELECT 1
      FROM person
      WHERE ID = 10
    ) THEN 1 ELSE 0 INTO n_rowExist END FROM DUAL;
    
    IF n_rowExist = 1 THEN
       -- do things when it exists
    ELSE
       -- do things when it doesn't exist
    END IF;

END;
/

Explanation:

In the query nested where it starts with SELECT CASE WHEN EXISTS and after the parenthesis (SELECT 1 FROM person WHERE ID = 10) it will return a result if it finds a person of ID of 10. If the there's a result on the query then it will assign the value of 1 otherwise it will assign the value of 0 to n_rowExist variable. Afterwards, the if statement checks if the value returned equals to 1 then is true otherwise it will be 0 = 1 and that is false.

Import multiple csv files into pandas and concatenate into one DataFrame

Based on @Sid's good answer.

Before concatenating, you can load csv files into an intermediate dictionary which gives access to each data set based on the file name (in the form dict_of_df['filename.csv']). Such a dictionary can help you identify issues with heterogeneous data formats, when column names are not aligned for example.

Import modules and locate file paths:

import os
import glob
import pandas
from collections import OrderedDict
path =r'C:\DRO\DCL_rawdata_files'
filenames = glob.glob(path + "/*.csv")

Note: OrderedDict is not necessary, but it'll keep the order of files which might be useful for analysis.

Load csv files into a dictionary. Then concatenate:

dict_of_df = OrderedDict((f, pandas.read_csv(f)) for f in filenames)
pandas.concat(dict_of_df, sort=True)

Keys are file names f and values are the data frame content of csv files. Instead of using f as a dictionary key, you can also use os.path.basename(f) or other os.path methods to reduce the size of the key in the dictionary to only the smaller part that is relevant.

Get file name from a file location in Java

Here are 2 ways(both are OS independent.)

Using Paths : Since 1.7

Path p = Paths.get(<Absolute Path of Linux/Windows system>);
String fileName = p.getFileName().toString();
String directory = p.getParent().toString();

Using FilenameUtils in Apache Commons IO :

String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");

Python threading.timer - repeat function every 'n' seconds

In addition to the above great answers using Threads, in case you have to use your main thread or prefer an async approach - I wrapped a short class around aio_timers Timer class (to enable repeating)

import asyncio
from aio_timers import Timer

class RepeatingAsyncTimer():
    def __init__(self, interval, cb, *args, **kwargs):
        self.interval = interval
        self.cb = cb
        self.args = args
        self.kwargs = kwargs
        self.aio_timer = None
        self.start_timer()
    
    def start_timer(self):
        self.aio_timer = Timer(delay=self.interval, 
                               callback=self.cb_wrapper, 
                               callback_args=self.args, 
                               callback_kwargs=self.kwargs
                              )
    
    def cb_wrapper(self, *args, **kwargs):
        self.cb(*args, **kwargs)
        self.start_timer()


from time import time
def cb(timer_name):
    print(timer_name, time())

print(f'clock starts at: {time()}')
timer_1 = RepeatingAsyncTimer(interval=5, cb=cb, timer_name='timer_1')
timer_2 = RepeatingAsyncTimer(interval=10, cb=cb, timer_name='timer_2')

clock starts at: 1602438840.9690785

timer_1 1602438845.980087

timer_2 1602438850.9806316

timer_1 1602438850.9808934

timer_1 1602438855.9863033

timer_2 1602438860.9868324

timer_1 1602438860.9876585

How can I combine multiple nested Substitute functions in Excel?

Thanks for the idea of breaking down a formula Werner!

Using Alt+Enter allows one to put each bit of a complex substitute formula on separate lines: they become easier to follow and automatically line themselves up when Enter is pressed.

Just make sure you have enough end statements to match the number of substitute( lines either side of the cell reference.

As in this example:

=
substitute(
substitute(
substitute(
substitute(
B11
,"(","")
,")","")
,"[","")
,"]","")

becomes:

=
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(
SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")

which works fine as is, but one can always delete the extra paragraphs manually:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(B12,"(",""),")",""),"[",""),"]","")

Name > substitute()

[American Samoa] > American Samoa

Show popup after page load

  <script type="text/javascript">
  jQuery(document).ready(function(){
         setTimeout(PopUp(),5000); // invoke Popup function after 5 seconds 
  });
   </script>

Compiling problems: cannot find crt1.o

Ran into this on CentOs 5.4. Noticed that lib64 contained the crt*.o files, but lib did not. Installed glibc-devel through yum which installed the i386 bits and this resolved my issue.

How can I generate a tsconfig.json file?

i am using this,

yarn tsc --init

this fixed it for me

Parse JSON file using GSON

Imo, the best way to parse your JSON response with GSON would be creating classes that "match" your response and then use Gson.fromJson() method.
For example:

class Response {
    Map<String, App> descriptor;
    // standard getters & setters...
}

class App {
  String name;
  int age;
  String[] messages;
  // standard getters & setters...
}

Then just use:

Gson gson = new Gson();
Response response = gson.fromJson(yourJson, Response.class);

Where yourJson can be a String, any Reader, a JsonReader or a JsonElement.

Finally, if you want to access any particular field, you just have to do:

String name = response.getDescriptor().get("app3").getName();

You can always parse the JSON manually as suggested in other answers, but personally I think this approach is clearer, more maintainable in long term and it fits better with the whole idea of JSON.

Encode html entities in javascript

HTML Special Characters & its ESCAPE CODES

Reserved Characters must be escaped by HTML: We can use a character escape to represent any Unicode character [Ex: & - U+00026] in HTML, XHTML or XML using only ASCII characters. Numeric character references [Ex: ampersand(&) - &#38;] & Named character references [Ex: &amp;] are types of character escape used in markup.


Predefined Entities

    Original Character     XML entity replacement    XML numeric replacement  
                  <                                    &lt;                                           &#60;                    
                  >                                     &gt;                                         &#62;                    
                  "                                     &quot;                                      &#34;                    
                  &                                   &amp;                                       &#38;                    
                   '                                    &apos;                                      &#39;                    

To display HTML Tags as a normal form in web page we use <pre>, <code> tags or we can escape them. Escaping the string by replacing with any occurrence of the "&" character by the string "&amp;" and any occurrences of the ">" character by the string "&gt;". Ex: stackoverflow post

function escapeCharEntities() {
    var map = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        "\"": "&quot;",
        "'": "&apos;"
    };
    return map;
}

var mapkeys = '', mapvalues = '';
var html = {
    encodeRex : function () {
        return  new RegExp(mapkeys, 'g'); // "[&<>"']"
    }, 
    decodeRex : function () {
        return  new RegExp(mapvalues, 'g'); // "(&amp;|&lt;|&gt;|&quot;|&apos;)"
    },
    encodeMap : JSON.parse( JSON.stringify( escapeCharEntities () ) ), // json = {&: "&amp;", <: "&lt;", >: "&gt;", ": "&quot;", ': "&apos;"}
    decodeMap : JSON.parse( JSON.stringify( swapJsonKeyValues( escapeCharEntities () ) ) ),
    encode : function ( str ) {
        var encodeRexs = html.encodeRex();
        console.log('Encode Rex: ', encodeRexs); // /[&<>"']/gm
        return str.replace(encodeRexs, function(m) { console.log('Encode M: ', m); return html.encodeMap[m]; }); // m = < " > SpecialChars
    },
    decode : function ( str ) {
        var decodeRexs = html.decodeRex();
        console.log('Decode Rex: ', decodeRexs); // /(&amp;|&lt;|&gt;|&quot;|&apos;)/g
        return str.replace(decodeRexs, function(m) { console.log('Decode M: ', m); return html.decodeMap[m]; }); // m = &lt; &quot; &gt;
    }
};

function swapJsonKeyValues ( json ) {
    var count = Object.keys( json ).length;
    var obj = {};
    var keys = '[', val = '(', keysCount = 1;
    for(var key in json) {
        if ( json.hasOwnProperty( key ) ) {
            obj[ json[ key ] ] = key;
            keys += key;
            if( keysCount < count ) {
                val += json[ key ]+'|';
            } else {
                val += json[ key ];
            }
            keysCount++;
        }
    }
    keys += ']';    val  += ')';
    console.log( keys, ' == ', val);
    mapkeys = keys;
    mapvalues = val;
    return obj;
}

console.log('Encode: ', html.encode('<input type="password" name="password" value=""/>') ); 
console.log('Decode: ', html.decode(html.encode('<input type="password" name="password" value=""/>')) );

O/P:
Encode:  &lt;input type=&quot;password&quot; name=&quot;password&quot; value=&quot;&quot;/&gt;
Decode:  <input type="password" name="password" value=""/>

How to order by with union in SQL?

If I want the sort to be applied to only one of the UNION if use Union all:

Select id,name,age
From Student
Where age < 15
Union all
Select id,name,age
From 
(
Select id,name,age
From Student
Where Name like "%a%"
Order by name
)

Call static method with reflection

As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.

foreach (var tempClass in macroClasses)
{
   // using reflection I will be able to run the method as:
   tempClass.GetMethod("Run").Invoke(null, null);
}

As the comment points out, you may want to ensure the method is static when calling GetMethod:

tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

You could put a _ViewStart.cshtml file inside the /Views/Public folder which would override the default one in the /Views folder and specify the desired layout:

@{
    Layout = "~/Views/Shared/_PublicLayout.cshtml";
}

By analogy you could put another _ViewStart.cshtml file inside the /Views/Staff folder with:

@{
    Layout = "~/Views/Shared/_StaffLayout.cshtml";
}

You could also specify which layout should be used when returning a view inside a controller action but that's per action:

return View("Index", "~/Views/Shared/_StaffLayout.cshtml", someViewModel);

Yet another possibility is a custom action filter which would override the layout. As you can see many possibilities to achieve this. Up to you to choose which one fits best in your scenario.


UPDATE:

As requested in the comments section here's an example of an action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

and then decorate a controller or an action with this custom attribute specifying the layout you want:

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

Most common C# bitwise operations on enums

The idiom is to use the bitwise or-equal operator to set bits:

flags |= 0x04;

To clear a bit, the idiom is to use bitwise and with negation:

flags &= ~0x04;

Sometimes you have an offset that identifies your bit, and then the idiom is to use these combined with left-shift:

flags |= 1 << offset;
flags &= ~(1 << offset);

Java null check why use == instead of .equals()

Object.equals is null safe, however be aware that if two objects are null, object.equals will return true so be sure to check that the objects you are comparing aren't null (or hold null values) before using object.equals for comparison.

String firstname = null;
String lastname = null;

if(Objects.equals(firstname, lastname)){
    System.out.println("equal!");
} else {
    System.out.println("not equal!");
}

Example snippet above will return equal!

How to pass data in the ajax DELETE request other than headers

deleteRequest: function (url, Id, bolDeleteReq, callback, errorCallback) {
    $.ajax({
        url: urlCall,
        type: 'DELETE',
        data: {"Id": Id, "bolDeleteReq" : bolDeleteReq},
        success: callback || $.noop,
        error: errorCallback || $.noop
    });
}

Note: the use of headers was introduced in JQuery 1.5.:

A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

Should I use alias or alias_method?

A year after asking the question comes a new article on the subject:

http://erniemiller.org/2014/10/23/in-defense-of-alias/

It seems that "so many men, so many minds." From the former article author encourages to use alias_method, while the latter suggests using alias.

However there's a common overview of these methods in both blogposts and answers above:

  • use alias when you want to limit aliasing to the scope where it's defined
  • use alias_method to allow inherited classes to access it

Download all stock symbol list of a market

This may be old, but... if you change the link in google stock list as below:

https://www.google.com/finance?q=%5B(exchange%20%3D%3D%20%22NASDAQ%22)%5D&restype=company&noIL=1&num=30000

  • note for the noIL=1&num=30000

It means, starting for row 1 to 30000. It shows all results in one page.

You may automate it using any language or just export the table to excel.

Hope it helps.

Using sed and grep/egrep to search and replace

try something using a for loop

 for i in `egrep -lR "YOURSEARCH" .` ; do echo  $i; sed 's/f/k/' <$i >/tmp/`basename $i`; mv /tmp/`basename $i` $i; done

not pretty, but should do.

How to filter WooCommerce products by custom attribute

A plugin is probably your best option. Look in the wordpress plugins directory or google to see if you can find one. I found the one below and that seemed to work perfect.

https://wordpress.org/plugins/woocommerce-products-filter/

This one seems to do exactly what you are after

Android: remove notification from notification bar

Please try this,

public void removeNotification(Context context, int notificationId) {      
    NotificationManager nMgr = (NotificationManager) context.getApplicationContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);
    nMgr.cancel(notificationId);
}

Regular expression to allow spaces between words

tl;dr

Just add a space in your character class.

^[a-zA-Z0-9_ ]*$

 


Now, if you want to be strict...

The above isn't exactly correct. Due to the fact that * means zero or more, it would match all of the following cases that one would not usually mean to match:

  • An empty string, "".
  • A string comprised entirely of spaces, "      ".
  • A string that leads and / or trails with spaces, "   Hello World  ".
  • A string that contains multiple spaces in between words, "Hello   World".

Originally I didn't think such details were worth going into, as OP was asking such a basic question that it seemed strictness wasn't a concern. Now that the question's gained some popularity however, I want to say...

...use @stema's answer.

Which, in my flavor (without using \w) translates to:

^[a-zA-Z0-9_]+( [a-zA-Z0-9_]+)*$

(Please upvote @stema regardless.)

Some things to note about this (and @stema's) answer:

  • If you want to allow multiple spaces between words (say, if you'd like to allow accidental double-spaces, or if you're working with copy-pasted text from a PDF), then add a + after the space:

    ^\w+( +\w+)*$
    
  • If you want to allow tabs and newlines (whitespace characters), then replace the space with a \s+:

    ^\w+(\s+\w+)*$
    

    Here I suggest the + by default because, for example, Windows linebreaks consist of two whitespace characters in sequence, \r\n, so you'll need the + to catch both.

Still not working?

Check what dialect of regular expressions you're using.* In languages like Java you'll have to escape your backslashes, i.e. \\w and \\s. In older or more basic languages and utilities, like sed, \w and \s aren't defined, so write them out with character classes, e.g. [a-zA-Z0-9_] and [\f\n\p\r\t], respectively.

 


* I know this question is tagged , but based on 25,000+ views, I'm guessing it's not only those folks who are coming across this question. Currently it's the first hit on google for the search phrase, regular expression space word.

Difference between PACKETS and FRAMES

Packets and Frames are the names given to Protocol data units (PDUs) at different network layers

  • Segments/Datagrams are units of data in the Transport Layer.

    In the case of the internet, the term Segment typically refers to TCP, while Datagram typically refers to UDP. However Datagram can also be used in a more general sense and refer to other layers (link):

    Datagram

    A self-contained, independent entity of data carrying sufficient information to be routed from the source to the destination computer without reliance on earlier exchanges between this source and destination computer andthe transporting network.

  • Packets are units of data in the Network Layer (IP in case of the Internet)

  • Frames are units of data in the Link Layer (e.g. Wifi, Bluetooth, Ethernet, etc).

enter image description here

Handling errors in Promise.all

Promise.allSettled

Instead of Promise.all use Promise.allSettled which waits for all promises to settle, regardless of the result

_x000D_
_x000D_
let p1 = new Promise(resolve => resolve("result1"));
let p2 = new Promise( (resolve,reject) => reject('some troubles') );
let p3 = new Promise(resolve => resolve("result3"));

// It returns info about each promise status and value
Promise.allSettled([p1,p2,p3]).then(result=> console.log(result));
_x000D_
_x000D_
_x000D_

Polyfill

_x000D_
_x000D_
if (!Promise.allSettled) {
  const rejectHandler = reason => ({ status: 'rejected', reason });
  const resolveHandler = value => ({ status: 'fulfilled', value });

  Promise.allSettled = function (promises) {
    const convertedPromises = promises
      .map(p => Promise.resolve(p).then(resolveHandler, rejectHandler));
    return Promise.all(convertedPromises);
  };
}
_x000D_
_x000D_
_x000D_

%Like% Query in spring JpaRepository

when call funtion, I use: findByPlaceContaining("%" + place);

or: findByPlaceContaining(place + "%");

or: findByPlaceContaining("%" + place + "%");

How to check if a process is in hang state (Linux)

What do you mean by ‘hang state’? Typically, a process that is unresponsive and using 100% of a CPU is stuck in an endless loop. But there's no way to determine whether that has happened or whether the process might not eventually reach a loop exit state and carry on.

Desktop hang detectors just work by sending a message to the application's event loop and seeing if there's any response. If there's not for a certain amount of time they decide the app has ‘hung’... but it's entirely possible it was just doing something complicated and will come back to life in a moment once it's done. Anyhow, that's not something you can use for any arbitrary process.

How to remove folders with a certain name

find path/to/the/folders -maxdepth 1 -name "my_*" -type d -delete

Overriding a JavaScript function while referencing the original

The answer that @Matthew Crumley provides is making use of the immediately invoked function expressions, to close the older 'a' function into the execution context of the returned function. I think this was the best answer, but personally, I would prefer passing the function 'a' as an argument to IIFE. I think it is more understandable.

   var a = (function(original_a) {
        if (condition) {
            return function() {
                new_code();
                original_a();
            }
        } else {
            return function() {
                original_a();
                other_new_code();
            }
        }
    })(a);

Generic htaccess redirect www to non-www

Try this:

RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ %{HTTP_HOST}$1 [C]
RewriteRule ^www\.(.*)$ http://$1 [L,R=301]

If the host starts with www, we stick the whole host onto the start of the URL, then take off the "www."

Select specific row from mysql table

SET @customerID=0;
SELECT @customerID:=@customerID+1 AS customerID
FROM CUSTOMER ;

you can obtain the dataset from SQL like this and populate it into a java data structure (like a List) and then make the necessary sorting over there. (maybe with the help of a comparable interface)

How to add a new row to datagridview programmatically

I have found this useful more than once when the DataGrid is bound to a table.

        DataTable dt = (DataTable)dgvData.DataSource;
        DataRow row = dt.NewRow();
        foreach (var something in something)
        {
           row["ColumnName"] = something ;               
        }
        dt.Rows.Add(row);
        dgvData.DataSource = dt;

What is stdClass in PHP?

Likewise,

$myNewObj->setNewVar = 'newVal'; 

yields a stdClass object - auto casted

I found this out today by misspelling:

$GLOBASLS['myObj']->myPropertyObj->myProperty = 'myVal';

Cool!

TypeError: unsupported operand type(s) for -: 'list' and 'list'

Use Set in Python

>>> a = [2,4]
>>> b = [1,4,3]
>>> set(a) - set(b)
set([2])

What is wrong with my SQL here? #1089 - Incorrect prefix key

according to the latest version of MySQL (phpMyAdmin), add a correct INDEX while choosing primary key. for example: id[int] INDEX 0 ,if id is your primary key and at the first index. Or,


For your problem try this one

CREATE TABLE `table`.`users` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(50) NOT NULL,
    `password` VARCHAR(50) NOT NULL,
    `dir` VARCHAR(100) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE = MyISAM;

(HTML) Download a PDF file instead of opening them in browser when clicked

You can use

Response.AddHeader("Content-disposition", "attachment; filename=" + Name);

Check out this example:

http://www.codeproject.com/KB/aspnet/textfile.aspx

This goes for ASP.NET. I am sure you can find similar solutions in all other server side languages. However there's no javascript solution to the best of my knowledge.

Get Month name from month number

You can also do this to get current Month :

string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month);

How do files get into the External Dependencies in Visual Studio C++?

To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified  all '.lib' files & there names for current project.

So, Developer has to specify external dependencies for Project as below..

1. Select Project in Solution explorer.

2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".

3.  Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".

enter image description here enter image description here

Class Diagrams in VS 2017

Noticed this in the beta and thought I had a bad install. The UI elements to add new Class Diagrams were missing and I was unable to open existing *.cd Class Diagram files in my solutions. Just upgraded to 2017 and found the problem remains. After some investigation it seems the Class Designer component is no longer installed by default.

Re-running the VS Installer and adding the Class Designer component restores both my ability to open and edit Class Diagrams as well as the UI elements needed to create new ones

VS Installer > Individual Components > Class Designer

find files by extension, *.html under a folder in nodejs

Can't add a comment because of reputation, but notice the following:

Using fs.readdir or node-glob to find a wildcard set of files in a folder of 500,000 files took ~2s. Using exec with DIR took ~0.05s (non recursive) or ~0.45s (recursive). (I was looking for ~14 files matching my pattern in a single directory).

So far, I have failed to find any nodejs implementation which uses low level OS wildcard searching for efficiency. But the above DIR/ls based code works wonderfully in windows in terms of efficiency. linux find, however, will likely be very slow for large directories.

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

Usually, best is to see a character in his context.

Here is the full list of Unicode chars, and how your browser currently displays them. I am seeing this list evolving, browser versions after others.

This list is obtained by iteration in decimal of the html entities unicode table, it may take some seconds, but is very useful to me in many cases.

By hovering quickly a given char you will get the dec and hex and the shortcuts to generate it with a keyboard.

_x000D_
_x000D_
var i = 0
    do document.write("<a title='(Linux|Hex): [CTRL+SHIFT]+u"+(i).toString(16)+"\nHtml entity: &# "+i+";\n&#x"+(i).toString(16)+";\n(Win|Dec): [ALT]+"+i+"' onmouseover='this.focus()' onclick='this.href=\"//google.com/?q=\"+this.innerHTML' style='cursor:pointer' target='new'>"+"&#"+i+";</a>"),i++
    while (i<136690)
window.stop() 


//  From https://codepen.io/Nico_KraZhtest/pen/mWzXqy
_x000D_
_x000D_
_x000D_

The same snippet as a bookmarklet:

javascript:void%20!function(){var%20t=0;do{document.write(%22%3Ca%20title='(Linux|Hex):%20[CTRL+SHIFT]+u%22+t.toString(16)+%22\nHtml%20entity:%20%26%23%20%22+t+%22;\n%26%23x%22+t.toString(16)+%22;\n(Win|Dec):%20[ALT]+%22+t+%22'%20onmouseover='this.focus()'%20onclick='this.href=\%22https://google.com/%3Fq=\%22+this.innerHTML'%20style='cursor:pointer'%20target='new'%3E%26%23%22+t+%22;%3C/a%3E%22),t++}while(t%3C136690);window.stop()}();

To generate that list from php:

for ($x = 0; $x < 136690; $x++) {
  echo html_entity_decode('&#'.$x.';',ENT_NOQUOTES,'UTF-8');
}

To generate that list into the console, using php:

php -r 'for ($x = 0; $x < 136690; $x++) { echo html_entity_decode("&#".$x.";",ENT_NOQUOTES,"UTF-8");}'

Here is a plain text extract, of arrows, some are coming with unicode 10.0. http://unicode.org/versions/Unicode10.0.0/

Unicode 10.0 adds 8,518 characters, for a total of 136,690 characters.

???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????


Hey, did you notice the plain html <details> element has a drop down arrow? This is sometimes all what we need.

_x000D_
_x000D_
<details>
  <summary>Morning</summary>
  <p>Hello world!</p>
</details>
<details>
  <summary>Evening</summary>
  <p>How sweat?</p>
</details>
_x000D_
_x000D_
_x000D_

Passing command line arguments to R CMD BATCH

My impression is that R CMD BATCH is a bit of a relict. In any case, the more recent Rscript executable (available on all platforms), together with commandArgs() makes processing command line arguments pretty easy.

As an example, here is a little script -- call it "myScript.R":

## myScript.R
args <- commandArgs(trailingOnly = TRUE)
rnorm(n=as.numeric(args[1]), mean=as.numeric(args[2]))

And here is what invoking it from the command line looks like

> Rscript myScript.R 5 100
[1]  98.46435 100.04626  99.44937  98.52910 100.78853

Edit:

Not that I'd recommend it, but ... using a combination of source() and sink(), you could get Rscript to produce an .Rout file like that produced by R CMD BATCH. One way would be to create a little R script -- call it RscriptEcho.R -- which you call directly with Rscript. It might look like this:

## RscriptEcho.R
args <- commandArgs(TRUE)
srcFile <- args[1]
outFile <- paste0(make.names(date()), ".Rout")
args <- args[-1]

sink(outFile, split = TRUE)
source(srcFile, echo = TRUE)

To execute your actual script, you would then do:

Rscript RscriptEcho.R myScript.R 5 100
[1]  98.46435 100.04626  99.44937  98.52910 100.78853

which will execute myScript.R with the supplied arguments and sink interleaved input, output, and messages to a uniquely named .Rout.

Edit2:
You can run Rscript verbosely and place the verbose output in a file.

Rscript --verbose myScript.R 5 100 > myScript.Rout

delete image from folder PHP

You can delete files in PHP using the unlink() function.

unlink('path/to/file.jpg');

Get and Set a Single Cookie with Node.js HTTP Server

There is no quick function access to getting/setting cookies, so I came up with the following hack:

var http = require('http');

function parseCookies (request) {
    var list = {},
        rc = request.headers.cookie;

    rc && rc.split(';').forEach(function( cookie ) {
        var parts = cookie.split('=');
        list[parts.shift().trim()] = decodeURI(parts.join('='));
    });

    return list;
}


http.createServer(function (request, response) {

  // To Read a Cookie
  var cookies = parseCookies(request);

  // To Write a Cookie
  response.writeHead(200, {
    'Set-Cookie': 'mycookie=test',
    'Content-Type': 'text/plain'
  });
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

This will store all cookies into the cookies object, and you need to set cookies when you write the head.

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

PHP Multiple Checkbox Array

<form method='post' id='userform' action='thisform.php'> <tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
    </td> </tr> </table> <input type='submit' class='buttons'> </form>

<?php 
if (isset($_POST['checkboxvar'])) 
{
    print_r($_POST['checkboxvar']); 
}
?>

You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.

To echo checked options into your email you would then do this:

echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want

Please keep in mind you should always sanitize your input as needed.

For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays

Best JavaScript compressor

I use ShrinkSafe from the Dojo project - it is exceptional because it actually uses a JavaScript interpreter (Rhino) to deal with finding symbols in the code and understanding their scope, etc. which helps to ensure that the code will work when it comes out the other end, as opposed to a lot of compression tools which use regex to do the same (which is not as reliable).

I actually have an MSBuild task in a Web Deployment Project in my current Visual Studio solution that runs a script which in turn runs all of the solution's JS files through ShrinkSafe before we deploy and it works quite well.

EDIT: By the way, "best" is open to debate, since the criteria for "best" will vary depending on the needs of the project. Personally, I think ShrinkSafe is a good balance; for some people that think smallest size == best, it will be insufficient.

EDIT: It is worth noting that the YUI compressor also uses Rhino.

How do you roll back (reset) a Git repository to a particular commit?

When you say the 'GUI Tool', I assume you're using Git For Windows.

IMPORTANT, I would highly recommend creating a new branch to do this on if you haven't already. That way your master can remain the same while you test out your changes.

With the GUI you need to 'roll back this commit' like you have with the history on the right of your view. Then you will notice you have all the unwanted files as changes to commit on the left. Now you need to right click on the grey title above all the uncommited files and select 'disregard changes'. This will set your files back to how they were in this version.

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

There is no best way, it depends on your use case.

  • Use way 1 if you want to create several similar objects. In your example, Person (you should start the name with a capital letter) is called the constructor function. This is similar to classes in other OO languages.
  • Use way 2 if you only need one object of a kind (like a singleton). If you want this object to inherit from another one, then you have to use a constructor function though.
  • Use way 3 if you want to initialize properties of the object depending on other properties of it or if you have dynamic property names.

Update: As requested examples for the third way.

Dependent properties:

The following does not work as this does not refer to book. There is no way to initialize a property with values of other properties in a object literal:

var book = {
    price: somePrice * discount,
    pages: 500,
    pricePerPage: this.price / this.pages
};

instead, you could do:

var book = {
    price: somePrice * discount,
    pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;

Dynamic property names:

If the property name is stored in some variable or created through some expression, then you have to use bracket notation:

var name = 'propertyName';

// the property will be `name`, not `propertyName`
var obj = {
    name: 42
}; 

// same here
obj.name = 42;

// this works, it will set `propertyName`
obj[name] = 42;

Send form data with jquery ajax json

You can use serialize() like this:

$.ajax({
  cache: false,
  url: 'test.php',
  data: $('form').serialize(),
  datatype: 'json',
  success: function(data) {

  }
});

How to install Guest addition in Mac OS as guest and Windows machine as host

You need to update your virtualbox sw. On new version, there is VBoxDarwinAdditions.pkg included in a additions iso image, in older versions is missing.

"Fade" borders in CSS

How to fade borders with CSS:

<div style="border-style:solid;border-image:linear-gradient(red, transparent) 1;border-bottom:0;">Text</div>

Please excuse the inline styles for the sake of demonstration. The 1 property for the border-image is border-image-slice, and in this case defines the border as a single continuous region.

Source: Gradient Borders

Java ArrayList - Check if list is empty

Your original problem was that you were checking if the list was null, which it would never be because you instantiated it with List<Integer> numbers = new ArrayList<Integer>();. However, you have updated your code to use the List.isEmpty() method to properly check if the list is empty.

The problem now is that you are never actually sending an empty list to giveList(). In your do-while loop, you add any input number to the list, even if it is -1. To prevent -1 being added, change the do-while loop to only add numbers if they are not -1. Then, the list will be empty if the user's first input number is -1.

do {
    number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number (-1 to stop)"));
    /* Change this line */
    if (number != -1) numbers.add(number);
} while (number != -1);

Using Java 8 to convert a list of objects into a string obtained from the toString() method

The other answers are fine. However, you can also pass Collectors.toList() as parameter to Stream.collect() to return the elements as an ArrayList.

System.out.println( list.stream().map( e -> e.toString() ).collect( toList() ) );

Java foreach loop: for (Integer i : list) { ... }

The API does not support that directly. You can use the for(int i..) loop and count the elements or use subLists(0, size - 1) and handle the last element explicitly:

  if(x.isEmpty()) return;
  int last = x.size() - 1;
  for(Integer i : x.subList(0, last)) out.println(i);
  out.println("last " + x.get(last));

This is only useful if it does not introduce redundancy. It performs better than the counting version (after the subList overhead is amortized). (Just in case you cared after the boxing anyway).

Where is HttpContent.ReadAsAsync?

If you are already using Newtonsoft.Json and don't want to install Microsoft.AspNet.WebApi.Client:

 var myInstance = JsonConvert.DeserializeObject<MyClass>(
   await response.Content.ReadAsStringAsync());

.NET Excel Library that can read/write .xls files

I'd recommend NPOI. NPOI is FREE and works exclusively with .XLS files. It has helped me a lot.

Detail: you don't need to have Microsoft Office installed on your machine to work with .XLS files if you use NPOI.

Check these blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C#

NPOI with Excel Table and dynamic Chart

[UPDATE]

NPOI 2.0 added support for XLSX and DOCX.

You can read more about it here:

NPOI 2.0 series of posts scheduled

Selecting empty text input using jQuery

$("input[type=text][value=]")

After trying a lots of version I found this the most logical.

Note that text is case-sensitive.

Left align and right align within div in Bootstrap

Bootstrap v4 introduces flexbox support

<div class="d-flex justify-content-end">
  <div class="mr-auto p-2">Flex item</div>
  <div class="p-2">Flex item</div>
  <div class="p-2">Flex item</div>
</div>

Learn more at https://v4-alpha.getbootstrap.com/utilities/flexbox/

Display Images Inline via CSS

The code you have posted here and code on your site both are different. There is a break <br> after second image, so the third image into new line, remove this <br> and it will display correctly.

CSS :not(:last-child):after selector

Your sample does not work in IE for me, you have to specify Doctype header in your document to render your page in standard way in IE to use the content CSS property:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<html>

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

</html>

Second way is to use CSS 3 selectors

li:not(:last-of-type):after
{
    content:           " |";
}

But you still need to specify Doctype

And third way is to use JQuery with some script like following:

<script type="text/javascript" src="jquery-1.4.1.js"></script>
<link href="style2.css" rel="stylesheet" type="text/css">
</head>
<html>

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>

<script type="text/javascript">
  $(document).ready(function () {
      $("li:not(:last)").append(" | ");
    });
</script>

Advantage of third way is that you dont have to specify doctype and jQuery will take care of compatibility.

How to make the HTML link activated by clicking on the <li>?

Use jQuery so you don't have to write inline javascript on <li> element:

$(document).ready(function(){
    $("li > a").each(function(index, value) {
        var link = $(this).attr("href");
        $(this).parent().bind("click", function() {
            location.href = link;
        });
    });
}); 

char *array and char array[]

No. Actually it's the "same" as

char array[] = {'O', 'n', 'e', ..... 'i','c','\0');

Every character is a separate element, with an additional \0 character as a string terminator.

I quoted "same", because there are some differences between char * array and char array[]. If you want to read more, take a look at C: differences between char pointer and array

Convert a string into an int

How about

[@"7" intValue];

Additionally if you want an NSNumber you could do

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter numberFromString:@"7"];

Auto-refreshing div with jQuery - setTimeout or another method?

$(document).ready(function() {
  $.ajaxSetup({ cache: false }); // This part addresses an IE bug.  without it, IE will only load the first number and will never refresh
  setInterval(function() {
    $('#notice_div').load('response.php');
  }, 3000); // the "3000" 
});

How do you create a Swift Date object?

According to @mythz answer, I decide to post updated version of his extension using swift3 syntax.

extension Date {
    static func from(_ year: Int, _ month: Int, _ day: Int) -> Date?
    {
        let gregorianCalendar = Calendar(identifier: .gregorian)
        let dateComponents = DateComponents(calendar: gregorianCalendar, year: year, month: month, day: day)
        return gregorianCalendar.date(from: dateComponents)
    }
}

I don't use parse method, but if someone needs, I will update this post.

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Set in RecyclerView initialization

recyclerView.setLayoutManager(new GridLayoutManager(this, 4));

How to access first element of JSON object array?

the event property seems to be string first you have to parse it to json :

 var req = { mandrill_events: '[{"event":"inbound","ts":1426249238}]' };
 var event = JSON.parse(req.mandrill_events);
 var ts =  event[0].ts

How can I use a JavaScript variable as a PHP variable?

You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data. -don

Mysql where id is in array

$string="1,2,3,4,5";
$array=array_map('intval', explode(',', $string));
$array = implode("','",$array);
$query=mysqli_query($conn, "SELECT name FROM users WHERE id IN ('".$array."')");

NB: the syntax is:

SELECT * FROM table WHERE column IN('value1','value2','value3')

Git - Ignore files during merge

.gitattributes - is a root-level file of your repository that defines the attributes for a subdirectory or subset of files.

You can specify the attribute to tell Git to use different merge strategies for a specific file. Here, we want to preserve the existing config.xml for our branch. We need to set the merge=foo to config.xml in .gitattributes file.

merge=foo tell git to use our(current branch) file, if a merge conflict occurs.

  1. Add a .gitattributes file at the root level of the repository

  2. You can set up an attribute for confix.xml in the .gitattributes file

     <pattern> merge=foo
    

    Let's take an example for config.xml

     config.xml merge=foo
    
  3. And then define a dummy foo merge strategy with:

     $ git config --global merge.foo.driver true
    

If you merge the stag form dev branch, instead of having the merge conflicts with the config.xml file, the stag branch's config.xml preserves at whatever version you originally had.

for more reference: merge_strategies

TypeError: 'float' object is not subscriptable

PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))      
for i,price in enumerate(PriceList):
  PriceList[i] = PizzaChange + 3*int(i>=7)

PHP check if file is an image

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one. Also its possible to get uploaded file content and search it for special character like <?php to find the file is image or not.

How to insert current_timestamp into Postgres via python

from datetime import datetime as dt

then use this in your code:

cur.execute('INSERT INTO my_table (dt_col) VALUES (%s)', (dt.now(),))

String or binary data would be truncated. The statement has been terminated

SQL Server 2016 SP2 CU6 and SQL Server 2017 CU12 introduced trace flag 460 in order to return the details of truncation warnings. You can enable it at the query level or at the server level.

Query level

INSERT INTO dbo.TEST (ColumnTest)
VALUES (‘Test truncation warnings’)
OPTION (QUERYTRACEON 460);
GO

Server Level

DBCC TRACEON(460, -1);
GO

From SQL Server 2019 you can enable it at database level:

ALTER DATABASE SCOPED CONFIGURATION 
SET VERBOSE_TRUNCATION_WARNINGS = ON;

The old output message is:

Msg 8152, Level 16, State 30, Line 13
String or binary data would be truncated.
The statement has been terminated.

The new output message is:

Msg 2628, Level 16, State 1, Line 30
String or binary data would be truncated in table 'DbTest.dbo.TEST', column 'ColumnTest'. Truncated value: ‘Test truncation warnings‘'.

In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.

Insert current date into a date column using T-SQL?

UPDATE Table
SET DateColumn=GETDATE()
WHERE UserID=@UserID

If you're inserting into a table, and will always need to put the current date, I would recommend setting GETDATE() as the default value for that column, and don't allow NULLs

How to pass a function as a parameter in Java?

Thanks to Java 8 you don't need to do the steps below to pass a function to a method, that's what lambdas are for, see Oracle's Lambda Expression tutorial. The rest of this post describes what we used to have to do in the bad old days in order to implement this functionality.

Typically you declare your method as taking some interface with a single method, then you pass in an object that implements that interface. An example is in commons-collections, where you have interfaces for Closure, Transformer, and Predicate, and methods that you pass implementations of those into. Guava is the new improved commons-collections, you can find equivalent interfaces there.

So for instance, commons-collections has org.apache.commons.collections.CollectionUtils, which has lots of static methods that take objects passed in, to pick one at random, there's one called exists with this signature:

static boolean exists(java.util.Collection collection, Predicate predicate) 

It takes an object that implements the interface Predicate, which means it has to have a method on it that takes some Object and returns a boolean.

So I can call it like this:

CollectionUtils.exists(someCollection, new Predicate() {
    public boolean evaluate(Object object) { 
        return ("a".equals(object.toString());
    }
});

and it returns true or false depending on whether someCollection contains an object that the predicate returns true for.

Anyway, this is just an example, and commons-collections is outdated. I just forget the equivalent in Guava.

What can MATLAB do that R cannot do?

R is an environment for statistical data analysis and graphics. MATLAB's origins are in numerical computation. The basic language implementations have many features in common if you use them for for data manipulation (e.g., matrix/vector operations).

R has statistical functionality hard to find elsewhere (>2000 Packages on CRAN), and lots of statisticians use it. On the other hand, MATLAB has lots of (expensive) toolboxes for engineering applications like

  • image processing/image acquisition,
  • filter design,
  • fuzzy logic/fuzzy control,
  • partial differential equations,
  • etc.

How do I put an already-running process under nohup?

Simple and easiest steps

  1. Ctrl + Z ----------> Suspends the process
  2. bg --------------> Resumes and runs background
  3. disown %1 -------------> required only if you need to detach from the terminal

What is the shortcut in IntelliJ IDEA to find method / functions?

CTRL + F12 brings up the File Structure navigation menu, which lets you search for members of the currently open file.

Grep only the first match and stop

A single liner, using find:

find -type f -exec grep -lm1 "PATTERN" {} \; -a -quit

Most efficient way to get table row count

None of these answers seem to be quite right. I tried them all. Here are my results.

Sending query: SELECT count(*) FROM daximation
91
Sending query: SELECT Auto_increment FROM information_schema.tables WHERE table_name='daximation'
96
Sending query: SHOW TABLE STATUS LIKE 'daximation'
98
Sending query: SELECT id FROM daximation ORDER BY id DESC LIMIT 1
97

here's the screenshot: https://www.screencast.com/t/s8c3trYU

Here is my PHP code:

$query = "SELECT count(*) FROM daximation"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);

$query = "SELECT Auto_increment FROM information_schema.tables WHERE table_name='daximation'"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);

$query = "SHOW TABLE STATUS LIKE 'daximation'"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[10]);

$query = "SELECT id FROM daximation ORDER BY id DESC LIMIT 1"; 
$result = sendquery($query);
$row = mysqli_fetch_row($result);
debugprint( $row[0]);

TypeError: Converting circular structure to JSON in nodejs

It's because you don't an async response For example:

app.get(`${api}/users`, async (req, res) => {
    const users = await User.find()
    res.send(users);
   })

Tomcat in Intellij Idea Community Edition

If you use Gradle, you can try my script: https://github.com/Adrninistrator/IDEA-IC-Tomcat .This script will build files for web application, create a Tomcat instance, start Tomcat and load the web application.

Command to get time in milliseconds

The other answers are probably sufficient in most cases but I thought I'd add my two cents as I ran into a problem on a BusyBox system.

The system in question did not support the %N format option and doesn't have no Python or Perl interpreter.

After much head scratching, we (thanks Dave!) came up with this:

adjtimex | awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }'

It extracts the seconds and microseconds from the output of adjtimex (normally used to set options for the system clock) and prints them without new lines (so they get glued together). Note that the microseconds field has to be pre-padded with zeros, but this doesn't affect the seconds field which is longer than six digits anyway. From this it should be trivial to convert microseconds to milliseconds.

If you need a trailing new line (maybe because it looks better) then try

adjtimex | awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }' && printf "\n"

Also note that this requires adjtimex and awk to be available. If not then with BusyBox you can point to them locally with:

ln -s /bin/busybox ./adjtimex
ln -s /bin/busybox ./awk

And then call the above as

./adjtimex | ./awk '/(time.tv_sec|time.tv_usec):/ { printf("%06d", $2) }'

Or of course you could put them in your PATH

EDIT:

The above worked on my BusyBox device. On Ubuntu I tried the same thing and realised that adjtimex has different versions. On Ubuntu this worked to output the time in seconds with decimal places to microseconds (including a trailing new line)

sudo apt-get install adjtimex
adjtimex -p | awk '/raw time:/ { print $6 }'

I wouldn't do this on Ubuntu though. I would use date +%s%N

ReactJS and images in public folder

You don't need any webpack configuration for this..

In your component just give image path. By default react will know its in public directory.

<img src="/image.jpg" alt="image" />

Looping through a Scripting.Dictionary using index/item number

Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.

For i = 0 To d.Count - 1
    s = d.Items()(i)
    Debug.Print s
Next i()

KEYS works the same way

For i = 0 To d.Count - 1
    Debug.Print d.Keys()(i), d.Items()(i)
Next i

This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".

Debug.Print Split("A,B,C,D", ",")(2)

SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.

Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.

How does createOrReplaceTempView work in Spark?

CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.

first we read data in csv format and then convert to data frame and create a temp view

Reading data in csv format

val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")

printing the schema

data.printSchema

SchemaOfTable

data.createOrReplaceTempView("Data")

Now we can run sql queries on top the table view we just created

  %sql select Week as Date,Campaign Type,Engagements,Country from Data order     by Date asc

enter image description here

"Cannot update paths and switch to branch at the same time"

It causes by that your local branch doesn't track remote branch. As ssasi said,you need use these commands:

git remote update
git fetch
git checkout -b branch_nameA origin/branch_nameB

I solved my problem just now....

Set UITableView content inset permanently

automaticallyAdjustsScrollViewInsets is deprecated in iOS11 (and the accepted solution no longer works). use:

if #available(iOS 11.0, *) {
    scrollView.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

How can I pass an Integer class correctly by reference?

You are correct here:

Integer i = 0;
i = i + 1;  // <- I think that this is somehow creating a new object!

First: Integer is immutable.

Second: the Integer class is not overriding the + operator, there is autounboxing and autoboxing involved at that line (In older versions of Java you would get an error on the above line).
When you write i + 1 the compiler first converts the Integer to an (primitive) int for performing the addition: autounboxing. Next, doing i = <some int> the compiler converts from int to an (new) Integer: autoboxing.
So + is actually being applied to primitive ints.

Add key value pair to all objects in array

arrOfObj.map(o => { 
  o.isActive = true; 
  return o; 
});

Redis: Show database size/size for keys

Take a look at this project it outputs some interesting stats about keyspaces based on regexs and prefixes. It uses the DEBUG OBJECT command and scans the db, identifying groups of keys and estimating the percentage of space they're taking up.

https://github.com/snmaynard/redis-audit

Output looks like this:

Summary  

---------------------------------------------------+--------------+-------------------+---------------------------------------------------  
Key                                                | Memory Usage | Expiry Proportion | Last Access Time                                    
---------------------------------------------------+--------------+-------------------+---------------------------------------------------  
notification_3109439                               | 88.14%       | 0.0%              | 2 minutes                               
user_profile_3897016                               | 11.86%       | 99.98%            | 20 seconds  
---------------------------------------------------+--------------+-------------------+---------------------------------------------------  

Or this this one: https://github.com/sripathikrishnan/redis-rdb-tools which does a full analysis on the entire keyspace by analyzing a dump.rdb file offline. This one works well also. It can give you the avg/min/max size for the entries in your db, and will even do it based on a prefix.

JS how to cache a variable

I have written a generic caching func() which will cache any variable easily and very readable format. Caching function:

function calculateSomethingMaybe(args){
  return args;
}

function caching(fn){
  const cache = {};
  return function(){
    const string = arguments[0];
    if(!cache[string]){
      const result = fn.apply(this, arguments);
      cache[string] = result;
      return result;
    }
    return cache[string];
  }
}

const letsCache = caching(calculateSomethingMaybe);

console.log(letsCache('a book'), letsCache('a pen'), letsCache('a book'));

How do I convert a list into a string with spaces in Python?

For Non String list we can do like this as well

" ".join(map(str, my_list))

Linux: command to open URL in default browser

On distributions that come with the open command,

$ open http://www.google.com

Bootstrap modal z-index

I fell into this this with using the JQLayout plugin, especially when using nested layouts and modals with Bootstrap 4.

An overriding css needs to be added to correct the behaviour,

.pane-center{
    z-index:inherit !important;
}

How to uninstall Jenkins?

Keep in mind, that in Terminal you need to add backslash before space, so the proper copy/paste will be

/Library/Application\ Support/Jenkins/Uninstall.command

p.s. sorry for the late answer :)

Java integer to byte array

If you're using apache-commons

public static byte[] toByteArray(int value) {
    byte result[] = new byte[4];
    return Conversion.intToByteArray(value, 0, result, 0, 4);
}

CodeIgniter 500 Internal Server Error

Make sure your root index.php file has the correct permission, its permission must be 0755 or 0644

How to JSON serialize sets?

JSON notation has only a handful of native datatypes (objects, arrays, strings, numbers, booleans, and null), so anything serialized in JSON needs to be expressed as one of these types.

As shown in the json module docs, this conversion can be done automatically by a JSONEncoder and JSONDecoder, but then you would be giving up some other structure you might need (if you convert sets to a list, then you lose the ability to recover regular lists; if you convert sets to a dictionary using dict.fromkeys(s) then you lose the ability to recover dictionaries).

A more sophisticated solution is to build-out a custom type that can coexist with other native JSON types. This lets you store nested structures that include lists, sets, dicts, decimals, datetime objects, etc.:

from json import dumps, loads, JSONEncoder, JSONDecoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))):
            return JSONEncoder.default(self, obj)
        return {'_python_object': pickle.dumps(obj)}

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(str(dct['_python_object']))
    return dct

Here is a sample session showing that it can handle lists, dicts, and sets:

>>> data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]

>>> j = dumps(data, cls=PythonObjectEncoder)

>>> loads(j, object_hook=as_python_object)
[1, 2, 3, set(['knights', 'say', 'who', 'ni']), {u'key': u'value'}, Decimal('3.14')]

Alternatively, it may be useful to use a more general purpose serialization technique such as YAML, Twisted Jelly, or Python's pickle module. These each support a much greater range of datatypes.

Xcode "Build and Archive" from command line

I found how to automate the build and archive process from the comand line, I just wrote a blog article explaining how you can achieve that.

The command you have to use is xcrun:

/usr/bin/xcrun -sdk iphoneos PackageApplication \
-v "${RELEASE_BUILDDIR}/${APPLICATION_NAME}.app" \
-o "${BUILD_HISTORY_DIR}/${APPLICATION_NAME}.ipa" \
--sign "${DEVELOPER_NAME}" \
--embed "${PROVISONING_PROFILE}"

You will find all the details in the article. If you have any questions dont hesitate to ask.

How do I create a pause/wait function using Qt?

Similar to some answers here, but maybe a little more lightweight

void MyClass::sleepFor(qint64 milliseconds){
    qint64 timeToExitFunction = QDateTime::currentMSecsSinceEpoch()+milliseconds;
    while(timeToExitFunction>QDateTime::currentMSecsSinceEpoch()){
        QApplication::processEvents(QEventLoop::AllEvents, 100);
    }
}

Change color when hover a font awesome icon?

use - !important - to override default black

_x000D_
_x000D_
.fa-heart:hover{_x000D_
   color:red !important;_x000D_
}_x000D_
.fa-heart-o:hover{_x000D_
   color:red !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
<i class="fa fa-heart fa-2x"></i>_x000D_
<i class="fa fa-heart-o fa-2x"></i>
_x000D_
_x000D_
_x000D_

svn : how to create a branch from certain revision of trunk

append the revision using an "@" character:

svn copy http://src@REV http://dev

Or, use the -r [--revision] command line argument.

How to open a file for both reading and writing?

Here's how you read a file, and then write to it (overwriting any existing data), without closing and reopening:

with open(filename, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(output)
    f.truncate()

git replace local version with remote version

This is the safest solution:

git stash

Now you can do whatever you want without fear of conflicts.

For instance:

git checkout origin/master

If you want to include the remote changes in the master branch you can do:

git reset --hard origin/master

This will make you branch "master" to point to "origin/master".

TypeError: a bytes-like object is required, not 'str' in python and CSV

just change wb to w

outfile=open('./immates.csv','wb')

to

outfile=open('./immates.csv','w')

How to force reloading php.ini file?

To force a reload of the php.ini you should restart apache.

Try sudo service apache2 restart from the command line. Or sudo /etc/init.d/apache2 restart

Scikit-learn train_test_split with indices

If you are using pandas you can access the index by calling .index of whatever array you wish to mimic. The train_test_split carries over the pandas indices to the new dataframes.

In your code you simply use x1.index and the returned array is the indexes relating to the original positions in x.

click() event is calling twice in jquery

Make sure and check that you have not accidentally included your script twice in your HTML page.

How to pass parameters to a Script tag?

Put the values you need someplace where the other script can retrieve them, like a hidden input, and then pull those values from their container when you initialize your new script. You could even put all your params as a JSON string into one hidden field.

How to display and hide a div with CSS?

Html Code :

    <a id="f">Show First content!</a>
    <br/>
    <a id="s">Show Second content!!</a>
    <div class="a">Default Content</div>
    <div class="ab hideDiv">First content</div>
    <div class="abc hideDiv">Second content</div>

Script code:

$(document).ready(function() {
    $("#f").mouseover(function(){
        $('.a,.abc').addClass('hideDiv');
        $('.ab').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });

    $("#s").mouseover(function(){
        $('.a,.ab').addClass('hideDiv');
        $('.abc').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });
});

css code:

.hideDiv
{
    display:none;
}

Excluding directory when creating a .tar.gz file

The exclude option needs to include the = sign and " are not required.

--exclude=/home/user/public_html/tmp

How to reload the current state?

For angular v1.2.26, none of the above works. An ng-click that calls the above methods will have to be clicked twice in order to make the state reload.

So I ended up emulating 2 clicks using $timeout.

$provide.decorator('$state',
        ["$delegate", "$stateParams", '$timeout', function ($delegate, $stateParams, $timeout) {
            $delegate.forceReload = function () {
                var reload = function () {
                    $delegate.transitionTo($delegate.current, angular.copy($stateParams), {
                        reload: true,
                        inherit: true,
                        notify: true
                    })
                };
                reload();
                $timeout(reload, 100);
            };
            return $delegate;
        }]);

'profile name is not valid' error when executing the sp_send_dbmail command

In my case, I was moving a SProc between servers and the profile name in my TSQL code did not match the profile name on the new server.

Updating TSQL profile name == New server profile name fixed the error for me.

Check if a specific value exists at a specific key in any subarray of a multidimensional array

Here is an updated version of Dan Grossman's answer which will cater for multidimensional arrays (what I was after):

function find_key_value($array, $key, $val)
{
    foreach ($array as $item)
    {
        if (is_array($item) && find_key_value($item, $key, $val)) return true;

        if (isset($item[$key]) && $item[$key] == $val) return true;
    }

    return false;
}

Passing bash variable to jq

Jq now have better way to acces environment variables, you can use env.EMAILI:

projectID=$(cat file.json | jq -r ".resource[] | select(.username==env.EMAILID) | .id")

How to add the JDBC mysql driver to an Eclipse project?

Try to insert this:

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

before getting the JDBC Connection.

Changes in import statement python3

To support both Python 2 and Python 3, use explicit relative imports as below. They are relative to the current module. They have been supported starting from 2.5.

from .sister import foo
from . import brother
from ..aunt import bar
from .. import uncle

Current date and time as string

#include <chrono>
#include <iostream>

int main()
{
    std::time_t ct = std::time(0);
    char* cc = ctime(&ct);

    std::cout << cc << std::endl;
    return 0;
}

What is the difference between printf() and puts() in C?

Right, printf could be thought of as a more powerful version of puts. printf provides the ability to format variables for output using format specifiers such as %s, %d, %lf, etc...

How do I make the text box bigger in HTML/CSS?

there are many options that would change the height of an input box. padding, font-size, height would all do this. different combinations of these produce taller input boxes with different styles. I suggest just changing the font-size (and font-family for looks) and add some padding to make it even taller and also more appealing. I will give you an example of all three style though:

#signin input {
font-size:20px;
}

OR

#signin input {
padding:10px;
}

OR

#signin input {
height:24px;
}

This is the combination of the three that I recommend:

#signin input {
font-size:20px;font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-weight: 300;
padding:10px;
}

System.BadImageFormatException An attempt was made to load a program with an incorrect format

It's possibly a 32 - 64 bits mismatch.

If you're running on a 64-bit OS, the Assembly RevitAPI may be compiled as 32-bit and your process as 64-bit or "Any CPU".

Or, the RevitAPI is compiled as 64-bit and your process is compiled as 32-bit or "Any CPU" and running on a 32-bit OS.

How to add new line into txt file

var Line = textBox1.Text + "," + textBox2.Text;

File.AppendAllText(@"C:\Documents\m2.txt", Line + Environment.NewLine);

How do I space out the child elements of a StackPanel?

The thing you really want to do is wrap all child elements. In this case you should use an items control and not resort to horrible attached properties which you will end up having a million of for every property you wish to style.

<ItemsControl>

    <!-- target the wrapper parent of the child with a style -->
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="Control">
            <Setter Property="Margin" Value="0 0 5 0"></Setter>
        </Style>
    </ItemsControl.ItemContainerStyle>

    <!-- use a stack panel as the main container -->
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <!-- put in your children -->
    <ItemsControl.Items>
        <Label>Auto Zoom Reset?</Label>
        <CheckBox x:Name="AutoResetZoom"/>
        <Button x:Name="ProceedButton" Click="ProceedButton_OnClick">Next</Button>
        <ComboBox SelectedItem="{Binding LogLevel }" ItemsSource="{Binding LogLevels}" />
    </ItemsControl.Items>
</ItemsControl>

enter image description here

How to remove duplicates from Python list and keep order?

If your input is already sorted, then there may be a simpler way to do it:

from operator import itemgetter
from itertools import groupby
unique_list = list(map(itemgetter(0), groupby(yourList)))

How to use PrintWriter and File classes in Java?

You should have a clear idea of exceptions in java. In java there are checked exceptions and unchecked exceptions.

Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.

NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:

CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.

How to resolve: 1.Put your code in try catch block:

2.use throws keyword as shown by other guys above.

Advice:Read more about Exceptions.(I personally love this topic)

How to check if running in Cygwin, Mac or Linux?

Use only this from command line works very fine, thanks to Justin:

#!/bin/bash

################################################## #########
# Bash script to find which OS
################################################## #########

OS=`uname`
echo "$OS"

source

How can I generate a self-signed certificate with SubjectAltName using OpenSSL?

Can someone help me with the exact syntax?

It's a three-step process, and it involves modifying the openssl.cnf file. You might be able to do it with only command line options, but I don't do it that way.

Find your openssl.cnf file. It is likely located in /usr/lib/ssl/openssl.cnf:

$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf

On my Debian system, /usr/lib/ssl/openssl.cnf is used by the built-in openssl program. On recent Debian systems it is located at /etc/ssl/openssl.cnf

You can determine which openssl.cnf is being used by adding a spurious XXX to the file and see if openssl chokes.


First, modify the req parameters. Add an alternate_names section to openssl.cnf with the names you want to use. There are no existing alternate_names sections, so it does not matter where you add it.

[ alternate_names ]

DNS.1        = example.com
DNS.2        = www.example.com
DNS.3        = mail.example.com
DNS.4        = ftp.example.com

Next, add the following to the existing [ v3_ca ] section. Search for the exact string [ v3_ca ]:

subjectAltName      = @alternate_names

You might change keyUsage to the following under [ v3_ca ]:

keyUsage = digitalSignature, keyEncipherment

digitalSignature and keyEncipherment are standard fare for a server certificate. Don't worry about nonRepudiation. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.

In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.


Second, modify the signing parameters. Find this line under the CA_default section:

# Extension copying option: use with caution.
# copy_extensions = copy

And change it to:

# Extension copying option: use with caution.
copy_extensions = copy

This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.


Third, generate your self-signed certificate:

$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...

Finally, examine the certificate:

$ openssl x509 -in certificate.pem -text -noout
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 9647297427330319047 (0x85e215e5869042c7)
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Validity
            Not Before: Feb  1 05:23:05 2014 GMT
            Not After : Feb  1 05:23:05 2016 GMT
        Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (3072 bit)
                Modulus:
                    00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
                    ...
                    d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
                    72:1c:45:92:2c:88:a9:be:0b:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
                34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
            X509v3 Authority Key Identifier:
                keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4

            X509v3 Basic Constraints: critical
                CA:FALSE
            X509v3 Key Usage:
                Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
            X509v3 Subject Alternative Name:
                DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
    Signature Algorithm: sha256WithRSAEncryption
         3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
         ...
         71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
         8b:0a:bd:65:03:d1

What is the best practice for creating a favicon on a web site?

  1. you can work with this website for generate favin.ico
  2. I recommend use .ico format because the png don't work with method 1 and ico could have more detail!
  3. both method work with all browser but when it's automatically work what you want type a code for it? so i think method 1 is better.

Search All Fields In All Tables For A Specific Value (Oracle)

Quote:

I've tried using this statement below to find an appropriate column based on what I think it should be named but it returned no results.*

SELECT * from dba_objects WHERE
object_name like '%DTN%'

A column isn't an object. If you mean that you expect the column name to be like '%DTN%', the query you want is:

SELECT owner, table_name, column_name FROM all_tab_columns WHERE column_name LIKE '%DTN%';

But if the 'DTN' string is just a guess on your part, that probably won't help.

By the way, how certain are you that '1/22/2008P09RR8' is a value selected directly from a single column? If you don't know at all where it is coming from, it could be a concatenation of several columns, or the result of some function, or a value sitting in a nested table object. So you might be on a wild goose chase trying to check every column for that value. Can you not start with whatever client application is displaying this value and try to figure out what query it is using to obtain it?

Anyway, diciu's answer gives one method of generating SQL queries to check every column of every table for the value. You can also do similar stuff entirely in one SQL session using a PL/SQL block and dynamic SQL. Here's some hastily-written code for that:

    SET SERVEROUTPUT ON SIZE 100000

    DECLARE
      match_count INTEGER;
    BEGIN
      FOR t IN (SELECT owner, table_name, column_name
                  FROM all_tab_columns
                  WHERE owner <> 'SYS' and data_type LIKE '%CHAR%') LOOP

        EXECUTE IMMEDIATE
          'SELECT COUNT(*) FROM ' || t.owner || '.' || t.table_name ||
          ' WHERE '||t.column_name||' = :1'
          INTO match_count
          USING '1/22/2008P09RR8';

        IF match_count > 0 THEN
          dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );
        END IF;

      END LOOP;

    END;
    /

There are some ways you could make it more efficient too.

In this case, given the value you are looking for, you can clearly eliminate any column that is of NUMBER or DATE type, which would reduce the number of queries. Maybe even restrict it to columns where type is like '%CHAR%'.

Instead of one query per column, you could build one query per table like this:

SELECT * FROM table1
  WHERE column1 = 'value'
     OR column2 = 'value'
     OR column3 = 'value'
     ...
     ;

Getting the button into the top right corner inside the div box

Just add position:absolute; top:0; right:0; to the CSS for your button.

 #button {
     line-height: 12px;
     width: 18px;
     font-size: 8pt;
     font-family: tahoma;
     margin-top: 1px;
     margin-right: 2px;
     position:absolute;
     top:0;
     right:0;
 }

jsFiddle example