Programs & Examples On #Gevent

Gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of libevent (libev after 1.0) event loop.

Byte Array in Python

Just use a bytearray (Python 2.6 and later) which represents a mutable sequence of bytes

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')

Indexing get and sets the individual bytes

>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')

and if you need it as a str (or bytes in Python 3), it's as simple as

>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'

Python requests library how to pass Authorization header with single token

Requests natively supports basic auth only with user-pass params, not with tokens.

You could, if you wanted, add the following class to have requests support token based basic authentication:

import requests
from base64 import b64encode

class BasicAuthToken(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        authstr = 'Basic ' + b64encode(('token:' + self.token).encode('utf-8')).decode('utf-8')
        r.headers['Authorization'] = authstr
        return r

Then, to use it run the following request :

r = requests.get(url, auth=BasicAuthToken(api_token))

An alternative would be to formulate a custom header instead, just as was suggested by other users here.

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

setSize() or setBounds() can be used when no layout manager is being used.

However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize() methods like setPreferredSize() and setMinimumSize() etc.

And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout, GridBagLayout, and SpringLayout managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout and GridLayout usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.

What range of values can integer types store in C++

You should look at the specialisations of the numeric_limits<> template for a given type. Its in the header.

Unable to Resolve Module in React Native App

reload the app and the cause of this error is the changes of files location made in react-native dependency which other libraries like native-base point to.

To solve it you need to view the mentioned file and change the file location to the correct location.

How to fix a Div to top of page with CSS only

Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following

#term-defs {
height: 300px;
overflow: scroll; }

This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.

#top {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  width: 100%;
  height: 23px;
}

This will fix it to the top, on top of other content with a height of 23px.

The final implementation will depend on what effect you really want.

HTML table with horizontal scrolling (first column fixed)

I have a similar table styled like so:

<table style="width:100%; table-layout:fixed">
    <tr>
        <td style="width: 150px">Hello, World!</td>
        <td>
            <div>
                <pre style="margin:0; overflow:scroll">My preformatted content</pre>
            </div>
        </td>
    </tr>
</table>

In Jenkins, how to checkout a project into a specific directory (using GIT)

I agree with @Lukasz Rzanek that we can use git plugin

But, I use option: checkout to a sub-direction what is enable as follow:
In Source Code Management, tick Git
click add button, choose checkout to a sub-directory

enter image description here

SonarQube Exclude a directory

what version of sonar are you using? There is one option called "sonar.skippedModules=yourmodulename".

This will skip the whole module. So be aware of it.

Find if variable is divisible by 2

var x = 2;
x % 2 ? oddFunction() : evenFunction();

GROUP BY with MAX(DATE)

SELECT train, dest, time FROM ( 
  SELECT train, dest, time, 
    RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank
    FROM traintable
  ) where dest_rank = 1

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

Deprecated meaning?

Deprecated in general means "don't use it".
A deprecated function may or may not work, but it is not guaranteed to work.

How can I check file size in Python?

Using pathlib (added in Python 3.4 or a backport available on PyPI):

from pathlib import Path
file = Path() / 'doc.txt'  # or Path('./doc.txt')
size = file.stat().st_size

This is really only an interface around os.stat, but using pathlib provides an easy way to access other file related operations.

Change value of input placeholder via model?

Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.

Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.

This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.

Auto-increment on partial primary key with Entity Framework Core

Well those Data Annotations should do the trick, maybe is something related with the PostgreSQL Provider.

From EF Core documentation:

Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during SaveChanges.

You could also try with this Fluent Api configuration:

modelBuilder.Entity<Foo>()
            .Property(f => f.Id)
            .ValueGeneratedOnAdd();

But as I said earlier, I think this is something related with the DB provider. Try to add a new row to your DB and check later if was generated a value to the Id column.

Double quotes within php script echo

You can just forgo the quotes for alphanumeric attributes:

echo "<font color=red> XHTML is not a thing anymore. </font>";
echo "<div class=editorial-note> There, I said it. </div>";

Is perfectly valid in HTML, and though still shunned, absolutely en vogue since HTML5.

CAVEATS

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

Waiting for another flutter command to release the startup lock

This occurs when any other flutter command is running in background. To solve this you can run for mac

killall -9 dart

and for windows open task manager. Then in processes tab, search for dart process and kill all of them. Hope this helps you.

Search input with an icon Bootstrap 4

Here is an input box with a search icon on the right.

  <div class="input-group">
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
      <div class="input-group-append">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
  </div>

Here is an input box with a search icon on the left.

  <div class="input-group">
      <div class="input-group-prepend">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
  </div>

Jaxb, Class has two properties of the same name

You didn't specified what JAXB-IMPL version are you using, but once I had the same problem (with jaxb-impl 2.0.5) and solved it using the annotation at the getter level instead of using it at the member level.

Icons missing in jQuery UI

you have workaround by setting background color instead of this missing icon. Here are the steps to follow:

  • open relevant 'jquery-ui-x.-.x.css' file
  • search for the missing file name in css file(eg: ui-bg_flat_75_ffffff_40x100.png")
  • Remove/comment the line that calls this background image
  • instead add the following line to replace the background color 'background-color: #ffffff'

That will probably work

EditorFor() and html properties

You can define attributes for your properties.

[StringLength(100)]
public string Body { get; set; }

This is known as System.ComponentModel.DataAnnotations. If you can't find the ValidationAttribute that you need you can allways define custom attributes.

Best Regards, Carlos

Converting between datetime and Pandas Timestamp objects

>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')

How to search text using php if ($text contains "World")

  /* https://ideone.com/saBPIe */

  function search($search, $string) {

    $pos = strpos($string, $search);  

    if ($pos === false) {

      return "not found";     

    } else {

      return "found in " . $pos;

    }    

  }

  echo search("world", "hello world");

Embed PHP online:

_x000D_
_x000D_
body, html, iframe { _x000D_
  width: 100% ;_x000D_
  height: 100% ;_x000D_
  overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/saBPIe" ></iframe>
_x000D_
_x000D_
_x000D_

How to remove all elements in String array in java?

list.clear() is documented for clearing the ArrayList.

list.removeAll() has no documentation at all in Eclipse.

Checking if a double (or float) is NaN in C++

First solution: if you are using C++11

Since this was asked there were a bit of new developments: it is important to know that std::isnan() is part of C++11

Synopsis

Defined in header <cmath>

bool isnan( float arg ); (since C++11)
bool isnan( double arg ); (since C++11)
bool isnan( long double arg ); (since C++11)

Determines if the given floating point number arg is not-a-number (NaN).

Parameters

arg: floating point value

Return value

true if arg is NaN, false otherwise

Reference

http://en.cppreference.com/w/cpp/numeric/math/isnan

Please note that this is incompatible with -fast-math if you use g++, see below for other suggestions.


Other solutions: if you using non C++11 compliant tools

For C99, in C, this is implemented as a macro isnan(c)that returns an int value. The type of x shall be float, double or long double.

Various vendors may or may not include or not a function isnan().

The supposedly portable way to check for NaN is to use the IEEE 754 property that NaN is not equal to itself: i.e. x == x will be false for x being NaN.

However the last option may not work with every compiler and some settings (particularly optimisation settings), so in last resort, you can always check the bit pattern ...

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

How can I delete a newline if it is the last character in a file?

The only time I've wanted to do this is for code golf, and then I've just copied my code out of the file and pasted it into an echo -n 'content'>file statement.

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

How to change to an older version of Node.js

Another good library for managing multiple versions of Node is N: https://github.com/visionmedia/n

Android dependency has different version for the compile and runtime

After a lot of time and getting help from a friend who knows a lot more than me about android: app/build.gradle

android {
    compileSdkVersion 27

    // org.gradle.caching = true

    defaultConfig {
        applicationId "com.cryptoviewer"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 196
        versionName "16.83"
        // ndk {
        //     abiFilters "armeabi-v7a", "x86"
        // }
    }

and dependencies

dependencies {
    implementation project(':react-native-camera')
   //...
    implementation "com.android.support:appcompat-v7:26.1.0" // <= YOU CARE ABOUT THIS
    implementation "com.facebook.react:react-native:+"  // From node_modules
}

in build.gradle

allprojects {
   //...
    configurations.all {
        resolutionStrategy.force "com.android.support:support-v4:26.1.0"
    }

in gradle.properties

android.useDeprecatedNdk=true
android.enableAapt2=false
org.gradle.jvmargs=-Xmx4608M

How do you run a js file using npm scripts?

{ "scripts" :
  { "build": "node build.js"}
}

npm run build OR npm run-script build


{
  "name": "build",
  "version": "1.0.0",
  "scripts": {
    "start": "node build.js"
  }
}

npm start


NB: you were missing the { brackets } and the node command

folder structure is fine:

+ build
  - package.json
  - build.js

CASCADE DELETE just once

The delete with the cascade option only applied to tables with foreign keys defined. If you do a delete, and it says you cannot because it would violate the foreign key constraint, the cascade will cause it to delete the offending rows.

If you want to delete associated rows in this way, you will need to define the foreign keys first. Also, remember that unless you explicitly instruct it to begin a transaction, or you change the defaults, it will do an auto-commit, which could be very time consuming to clean up.

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Check Safari developer reference on Touch class.

According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX and not PageX

endforeach in loops?

It's the end statement for the alternative syntax:

foreach ($foo as $bar) :
    ...
endforeach;

Useful to make code more readable if you're breaking out of PHP:

<?php foreach ($foo as $bar) : ?>
    <div ...>
        ...
    </div>
<?php endforeach; ?>

How do I kill all the processes in Mysql "show processlist"?

The following will create a simple stored procedure that uses a cursor to kill all processes one by one except for the process currently being used:

DROP PROCEDURE IF EXISTS kill_other_processes;

DELIMITER $$

CREATE PROCEDURE kill_other_processes()
BEGIN
  DECLARE finished INT DEFAULT 0;
  DECLARE proc_id INT;
  DECLARE proc_id_cursor CURSOR FOR SELECT id FROM information_schema.processlist;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

  OPEN proc_id_cursor;
  proc_id_cursor_loop: LOOP
    FETCH proc_id_cursor INTO proc_id;

    IF finished = 1 THEN 
      LEAVE proc_id_cursor_loop;
    END IF;

    IF proc_id <> CONNECTION_ID() THEN
      KILL proc_id;
    END IF;

  END LOOP proc_id_cursor_loop;
  CLOSE proc_id_cursor;
END$$

DELIMITER ;

It can be run with SELECTs to show the processes before and after as follows:

SELECT * FROM information_schema.processlist;
CALL kill_other_processes();
SELECT * FROM information_schema.processlist;

Where can I find Android source code online?

Everything is mirrored on omapzoom.org. Some of the code is also mirrored on github.

Contacts is here for example.

Since December 2019, you can use the new official public code search tool for AOSP: cs.android.com. There's also the Android official source browser (based on Gitiles) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories.

To get all the code locally, you can use the repo helper program, or you can just clone individual repositories.

And others:

Threads vs Processes in Linux

Once upon a time there was Unix and in this good old Unix there was lots of overhead for processes, so what some clever people did was to create threads, which would share the same address space with the parent process and they only needed a reduced context switch, which would make the context switch more efficient.

In a contemporary Linux (2.6.x) there is not much difference in performance between a context switch of a process compared to a thread (only the MMU stuff is additional for the thread). There is the issue with the shared address space, which means that a faulty pointer in a thread can corrupt memory of the parent process or another thread within the same address space.

A process is protected by the MMU, so a faulty pointer will just cause a signal 11 and no corruption.

I would in general use processes (not much context switch overhead in Linux, but memory protection due to MMU), but pthreads if I would need a real-time scheduler class, which is a different cup of tea all together.

Why do you think threads are have such a big performance gain on Linux? Do you have any data for this, or is it just a myth?

request exceeds the configured maxQueryStringLength when using [Authorize]

i have this error using datatables.net

i fixed changing the default ajax Get to POST in te properties of the DataTable()

"ajax": {
        "url": "../ControllerName/MethodJson",
        "type": "POST"
    },

An object reference is required to access a non-static member

Make your audioSounds and minTime variables as static variables, as you are using them in a static method (playSound).

Marking a method as static prevents the usage of non-static (instance) members in that method.

To understand more , please read this SO QA:

Static keyword in c#

How to export non-exportable private key from store

You might need to uninstall antivirus (in my case I had to get rid of Avast).

This makes sure that crypto::cng command will work. Otherwise it was giving me errors:

mimikatz $ crypto::cng
ERROR kull_m_patch_genericProcessOrServiceFromBuild ; OpenProcess (0x00000005)

After removing Avast:

mimikatz $ crypto::cng
"KeyIso" service patched

Magic. (:

BTW

Windows Defender is another program blocking the program to work, so you will need also to disable it for the time of using program at least.

ImportError: No module named 'MySQL'

The silly mistake I had done was keeping mysql.py in same dir. Try renaming mysql.py to another name so python don't consider that as module.

Hexadecimal string to byte array in C

Here is HexToBin and BinToHex relatively clean and readable. (Note originally there were returned enum error codes through an error logging system not a simple -1 or -2.)

typedef unsigned char ByteData;
ByteData HexChar (char c)
{
    if ('0' <= c && c <= '9') return (ByteData)(c - '0');
    if ('A' <= c && c <= 'F') return (ByteData)(c - 'A' + 10);
    if ('a' <= c && c <= 'f') return (ByteData)(c - 'a' + 10);
    return (ByteData)(-1);
}

ssize_t HexToBin (const char* s, ByteData * buff, ssize_t length)
{
    ssize_t result = 0;
    if (!s || !buff || length <= 0) return -2;

    while (*s)
    {
        ByteData nib1 = HexChar(*s++);
        if ((signed)nib1 < 0) return -3;
        ByteData nib2 = HexChar(*s++);
        if ((signed)nib2 < 0) return -4;

        ByteData bin = (nib1 << 4) + nib2;

        if (length-- <= 0) return -5;
        *buff++ = bin;
        ++result;
    }
    return result;
}

void BinToHex (const ByteData * buff, ssize_t length, char * output, ssize_t outLength)
{
    char binHex[] = "0123456789ABCDEF";

    if (!output || outLength < 4) return (void)(-6);
    *output = '\0';

    if (!buff || length <= 0 || outLength <= 2 * length)
    {
        memcpy(output, "ERR", 4);
        return (void)(-7);
    }

    for (; length > 0; --length, outLength -= 2)
    {
        ByteData byte = *buff++;

        *output++ = binHex[(byte >> 4) & 0x0F];
        *output++ = binHex[byte & 0x0F];
    }
    if (outLength-- <= 0) return (void)(-8);
    *output++ = '\0';
}

Android Studio: Plugin with id 'android-library' not found

In later versions, the plugin has changed name to:

apply plugin: 'com.android.library'

And as already mentioned by some of the other answers, you need the gradle tools in order to use it. Using 3.0.1, you have to use the google repo, not mavenCentral or jcenter:

buildscript {
    repositories {
        ...
        //In IntelliJ or older versions of Android Studio
        //maven {
        //   url 'https://maven.google.com'
        //}
        google()//in newer versions of Android Studio
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

Get installed applications in a system

I agree that enumerating through the registry key is the best way.

Note, however, that the key given, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", will list all applications in a 32-bit Windows installation, and 64-bit applications in a Windows 64-bit installation.

In order to also see 32-bit applications installed on a Windows 64-bit installation, you would also need to enumeration the key @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall".

How to symbolicate crash log Xcode?

For me the .crash file was enough. Without .dSYM file and .app file.

I ran these two commands on the mac where I build the archive and it worked:

export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer" 

/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash  /yourPath/crash1.crash > /yourPath/crash1_symbolicated.crash

CSS3 background image transition

This can be achieved with greater cross-browser support than the accepted answer by using pseudo-elements as exemplified by this answer: https://stackoverflow.com/a/19818268/2602816

Creating a custom JButton in Java

Yes, this is possible. One of the main pros for using Swing is the ease with which the abstract controls can be created and manipulates.

Here is a quick and dirty way to extend the existing JButton class to draw a circle to the right of the text.

package test;

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;

import javax.swing.JButton;
import javax.swing.JFrame;

public class MyButton extends JButton {

    private static final long serialVersionUID = 1L;

    private Color circleColor = Color.BLACK;

    public MyButton(String label) {
        super(label);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        Dimension originalSize = super.getPreferredSize();
        int gap = (int) (originalSize.height * 0.2);
        int x = originalSize.width + gap;
        int y = gap;
        int diameter = originalSize.height - (gap * 2);

        g.setColor(circleColor);
        g.fillOval(x, y, diameter, diameter);
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension size = super.getPreferredSize();
        size.width += size.height;
        return size;
    }

    /*Test the button*/
    public static void main(String[] args) {
        MyButton button = new MyButton("Hello, World!");

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new FlowLayout());
        contentPane.add(button);

        frame.setVisible(true);
    }

}

Note that by overriding paintComponent that the contents of the button can be changed, but that the border is painted by the paintBorder method. The getPreferredSize method also needs to be managed in order to dynamically support changes to the content. Care needs to be taken when measuring font metrics and image dimensions.

For creating a control that you can rely on, the above code is not the correct approach. Dimensions and colours are dynamic in Swing and are dependent on the look and feel being used. Even the default Metal look has changed across JRE versions. It would be better to implement AbstractButton and conform to the guidelines set out by the Swing API. A good starting point is to look at the javax.swing.LookAndFeel and javax.swing.UIManager classes.

http://docs.oracle.com/javase/8/docs/api/javax/swing/LookAndFeel.html

http://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html

Understanding the anatomy of LookAndFeel is useful for writing controls: Creating a Custom Look and Feel

What is the syntax meaning of RAISERROR()

The severity level 16 in your example code is typically used for user-defined (user-detected) errors. The SQL Server DBMS itself emits severity levels (and error messages) for problems it detects, both more severe (higher numbers) and less so (lower numbers).

The state should be an integer between 0 and 255 (negative values will give an error), but the choice is basically the programmer's. It is useful to put different state values if the same error message for user-defined error will be raised in different locations, e.g. if the debugging/troubleshooting of problems will be assisted by having an extra indication of where the error occurred.

Detect whether Office is 32bit or 64bit via the registry

This Wikipedia article states:

On 64-bit versions of Windows, there are two folders for application files; the "Program Files" folder contains 64-bit programs, and the "Program Files (x86)" folder contains 32-bit programs.

So if the program is installed under C:\Program Files it is a 64-bit version. If it is installed under C:\Program Files (x86) it is a 32-bit installation.

How can I increase a scrollbar's width using CSS?

Yes.

If the scrollbar is not the browser scrollbar, then it will be built of regular HTML elements (probably divs and spans) and can thus be styled (or will be Flash, Java, etc and can be customized as per those environments).

The specifics depend on the DOM structure used.

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

Here it goes an example:

$.post("test.php", { 'choices[]': ["Jon", "Susan"] });

Hope it helps.

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

How to remove files that are listed in the .gitignore but still on the repository?

In linux you can use this commande :

for exemple i want to delete "*.py~" so my command should be ==>

find . -name "*.py~" -exec rm -f {} \;

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

mysql $link generally means, the resource object of the established mysqli connection to query the database.

So there are two ways of solving this problem

mysqli_query();

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql"); 
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));

Or, Using mysql_query() (This is now obselete)

$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");        
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());

As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .

Scala list concatenation, ::: vs ++

::: works only with lists, while ++ can be used with any traversable. In the current implementation (2.9.0), ++ falls back on ::: if the argument is also a List.

Keep the order of the JSON keys during JSON conversion to CSV

patchFor(answer @gary) :

$ git diff JSONObject.java                                                         
diff --git a/JSONObject.java b/JSONObject.java
index e28c9cd..e12b7a0 100755
--- a/JSONObject.java
+++ b/JSONObject.java
@@ -32,7 +32,7 @@ import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
 import java.util.Collection;
 import java.util.Enumeration;
-import java.util.HashMap;
+import java.util.LinkedHashMap;
 import java.util.Iterator;
 import java.util.Locale;
 import java.util.Map;
@@ -152,7 +152,9 @@ public class JSONObject {
      * Construct an empty JSONObject.
      */
     public JSONObject() {
-        this.map = new HashMap<String, Object>();
+//      this.map = new HashMap<String, Object>();
+        // I want to keep order of the given data:
+        this.map = new LinkedHashMap<String, Object>();
     }

     /**
@@ -243,7 +245,7 @@ public class JSONObject {
      * @throws JSONException
      */
     public JSONObject(Map<String, Object> map) {
-        this.map = new HashMap<String, Object>();
+        this.map = new LinkedHashMap<String, Object>();
         if (map != null) {
             Iterator<Entry<String, Object>> i = map.entrySet().iterator();
             while (i.hasNext()) {

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

Decode to Unicode, encode the results to UTF8.

apple.decode('latin1').encode('utf8')

Why is char[] preferred over String for passwords?

There is nothing that char array gives you vs String unless you clean it up manually after use, and I haven't seen anyone actually doing that. So to me the preference of char[] vs String is a bit exaggerated.

Take a look at the widely used Spring Security library here and ask yourself - are Spring Security guys incompetent or char[] passwords just don't make much sense. When some nasty hacker grabs memory dumps of your RAM be sure s/he'll get all the passwords even if you use sophisticated ways to hide them.

However, Java changes all the time, and some scary features like String Deduplication feature of Java 8 might intern String objects without your knowledge. But that's a different conversation.

Load image from url

public class MainActivity extends Activity {

    Bitmap b;
    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView)findViewById(R.id.imageView1);
        information info = new information();
        info.execute("");
    }

    public class information extends AsyncTask<String, String, String>
    {
        @Override
        protected String doInBackground(String... arg0) {

            try
            {
                URL url = new URL("http://10.119.120.10:80/img.jpg");
                InputStream is = new BufferedInputStream(url.openStream());
                b = BitmapFactory.decodeStream(is);

            } catch(Exception e){}
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            img.setImageBitmap(b);
        }
    }
}

How to make a form close when pressing the escape key?

The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.

This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

How do you cast a List of supertypes to a List of subtypes?

With Java 8, you actually can

List<TestB> variable = collectionOfListA
    .stream()
    .map(e -> (TestB) e)
    .collect(Collectors.toList());

How an 'if (A && B)' statement is evaluated?

for logical && both the parameters must be true , then it ll be entered in if {} clock otherwise it ll execute else {}. for logical || one of parameter or condition is true is sufficient to execute if {}.

if( (A) && (B) ){
     //if A and B both are true
}else{
}
if( (A) ||(B) ){
     //if A or B is true 
}else{
}

Reverse / invert a dictionary mapping

Fast functional solution for non-bijective maps (values not unique):

from itertools import imap, groupby

def fst(s):
    return s[0]

def snd(s):
    return s[1]

def inverseDict(d):
    """
    input d: a -> b
    output : b -> set(a)
    """
    return {
        v : set(imap(fst, kv_iter))
        for (v, kv_iter) in groupby(
            sorted(d.iteritems(),
                   key=snd),
            key=snd
        )
    }

In theory this should be faster than adding to the set (or appending to the list) one by one like in the imperative solution.

Unfortunately the values have to be sortable, the sorting is required by groupby.

Parsing date string in Go

For those of you out there that are encountering this, use the time.RFC3339 versus the string constant of "2006-01-02T15:04:05.000Z". And here is the reason why:

regDate := "2007-10-09T22:50:01.23Z"

layout1 := "2006-01-02T15:04:05.000Z"
t1, err := time.Parse(layout1, regDate)

if err != nil {
    fmt.Println("Static format doesn't work")
} else {
    fmt.Println(t1)
}

layout2 := time.RFC3339
t2, err := time.Parse(layout2, regDate)

if err != nil {
    fmt.Println("RFC format doesn't work") // You shouldn't see this at all
} else {
    fmt.Println(t2)
}

This will produce the following result:

Static format doesn't work
2007-10-09 22:50:01.23 +0000 UTC

Here is the Playground Link

How to select only the records with the highest date in LINQ

Go a simple way to do this :-

Created one class to hold following information

  • Level (number)
  • Url (Url of the site)

Go the list of sites stored on a ArrayList object. And executed following query to sort it in descending order by Level.

var query = from MyClass object in objCollection 
    orderby object.Level descending 
    select object

Once I got the collection sorted in descending order, I wrote following code to get the Object that comes as top row

MyClass topObject = query.FirstRow<MyClass>()

This worked like charm.

How to select the first element of a set with JSTL?

Work for arrays and lists only, not for set.

How to modify the nodejs request default timeout time?

Linking to express issue #3330

You may set the timeout either globally for entire server:

var server = app.listen();
server.setTimeout(500000);

or just for specific route:

app.post('/xxx', function (req, res) {
   req.setTimeout(500000);
});

Get the time difference between two datetimes

To get the difference between two-moment format dates or javascript Date format indifference of minutes the most optimum solution is

const timeDiff = moment.duration((moment(apptDetails.end_date_time).diff(moment(apptDetails.date_time)))).asMinutes()

you can change the difference format as you need by just replacing the asMinutes() function

How would you make two <div>s overlap?

I might approach it like so (CSS and HTML):

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0px;_x000D_
}_x000D_
#logo {_x000D_
  position: absolute; /* Reposition logo from the natural layout */_x000D_
  left: 75px;_x000D_
  top: 0px;_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  z-index: 2;_x000D_
}_x000D_
#content {_x000D_
  margin-top: 100px; /* Provide buffer for logo */_x000D_
}_x000D_
#links {_x000D_
  height: 75px;_x000D_
  margin-left: 400px; /* Flush links (with a 25px "padding") right of logo */_x000D_
}
_x000D_
<div id="logo">_x000D_
  <img src="https://via.placeholder.com/200x100" />_x000D_
</div>_x000D_
<div id="content">_x000D_
  _x000D_
  <div id="links">dssdfsdfsdfsdf</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c

This solution works nice when using Latin American accents, such as 'ñ'.

I have solved this problem just by adding

df = pd.read_csv(fileName,encoding='latin1')

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

How do you build a Singleton in Dart?

I use this simple pattern on dart and previously on Swift. I like that it's terse and only one way of using it.

class Singleton {
  static Singleton shared = Singleton._init();
  Singleton._init() {
    // init work here
  }

  void doSomething() {
  }
}

Singleton.shared.doSomething();

What are OLTP and OLAP. What is the difference between them?

oltp- mostly used for business transaction.used to collect business data.In sql we use insert,update and delete command for retrieving small source of data.like wise they are highly normalised.... OLTP Mostly used for maintaining the data integrity.

olap- mostly use for reporting,data mining and business analytic purpose. for the large or bulk data.deliberately it is de-normalised. it stores Historical data..

How to pass text in a textbox to JavaScript function?

This is what I have done. (Adapt from all of your answers)

<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />

It works. Thanks to all of you. :)

Best Timer for using in a Windows service

I agree with previous comment that might be best to consider a different approach. My suggest would be write a console application and use the windows scheduler:

This will:

  • Reduce plumbing code that replicates scheduler behaviour
  • Provide greater flexibility in terms of scheduling behaviour (e.g. only run on weekends) with all scheduling logic abstracted from application code
  • Utilise the command line arguments for parameters without having to setup configuration values in config files etc
  • Far easier to debug/test during development
  • Allow a support user to execute by invoking the console application directly (e.g. useful during support situations)

Laravel 5.2 not reading env file

For me the following worked

- php artisan config:cache
- php artisan config:clear
- php artisan cache:clear

Easier way to debug a Windows service

Just paste

Debugger.Break();

any where in you code.

For Example ,

internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            Debugger.Break();
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new Service1()
            };
            ServiceBase.Run(ServicesToRun);
        }
    }

It will hit Debugger.Break(); when you run your program.

How can I get the line number which threw exception?

Check this one

StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);

//Get the file name
string fileName = frame.GetFileName();

//Get the method name
string methodName = frame.GetMethod().Name;

//Get the line number from the stack frame
int line = frame.GetFileLineNumber();

//Get the column number
int col = frame.GetFileColumnNumber();

Peak memory usage of a linux/unix process

Heaptrack is KDE tool that has a GUI and text interface. I find it more suitable than valgrind to understand the memory usage of a process because it provides more details and flamegraphs. It's also faster because it does less checking that valgrind. And it gives you the peak memory usage.

Anyway, tracking rss and vss is misleading because pages could be shared, that's why that memusg. What you should really do is track the sum of Pss in /proc/[pid]/smaps or use pmap. GNOME system-monitor used to do so but it was too expensive.

"Unable to get the VLookup property of the WorksheetFunction Class" error

Try below code

I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.

Private Sub ComboBox1_Change()


    On Error Resume Next
    Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
    On Error GoTo 0

    If Ret <> "" Then MsgBox Ret


End Sub

OR

 On Error Resume Next

    Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)

    If Result = "Error 2042" Then
        'nothing found
    ElseIf cell <> Result Then
        MsgBox cell.Value
    End If

    On Error GoTo 0

How can I create a temp file with a specific extension with .NET?

This is what I am doing:

string tStamp = String.Format("{0:yyyyMMdd.HHmmss}", DateTime.Now);
string ProcID = Process.GetCurrentProcess().Id.ToString();
string tmpFolder = System.IO.Path.GetTempPath();
string outFile = tmpFolder + ProcID + "_" + tStamp + ".txt";

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

make div's height expand with its content

I know this is kind of old thread, however, this can be achieved with min-height CSS property in a clean way, so I'll leave this here for future references:

I made a fiddle based on the OP posted code here: http://jsfiddle.net/U5x4T/1/, as you remove and add divs inside, you'll notice how does the container expands or reduces in size

The only 2 things you need to achieve this, additional to the OP code is:

*Overflow in the main container (required for the floating divs)

*min-height css property, more info available here: http://www.w3schools.com/cssref/pr_dim_min-height.asp

Select Top and Last rows in a table (SQL server)

You must sort your data according your needs (es. in reverse order) and use select top query

Convert char array to a int number in C

It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.

char *buff;
size_t buff_size = 100;
int choice;
do{
    buff = (char *)malloc(buff_size *sizeof(char));
    getline(&buff, &buff_size, stdin);
    choice = atoi(buff);
    free(buff);
                    
}while((choice<1)&&(choice>9));

Split string into individual words Java

you can use Apache commons' StringUtils class

    String[] partsOfString = StringUtils.split("I want to walk my dog",StringUtils.SPACE)

Visual Studio 2015 installer hangs during install?

I had a similar problem. My solution was to switch off the antivirus software (Avast), download the .iso file, mount it (double click in the Windows Explorer on the .iso file), and then run it from the PowerShell with admin rights with the following switches:

.\vs_community.exe /NoWeb /NoRefresh

This way you don't have to go offline or remove your existing installation.

PHP - Check if the page run on Mobile or Desktop browser

There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net

Using that it's quite easy to only display content for a mobile:

include 'Mobile_Detect.php';
$detect = new Mobile_Detect();

// Check for any mobile device.
if ($detect->isMobile()){
   // mobile content
}
else {
   // other content for desktops
}

Oracle Differences between NVL and Coalesce

COALESCE is more modern function that is a part of ANSI-92 standard.

NVL is Oracle specific, it was introduced in 80's before there were any standards.

In case of two values, they are synonyms.

However, they are implemented differently.

NVL always evaluates both arguments, while COALESCE usually stops evaluation whenever it finds the first non-NULL (there are some exceptions, such as sequence NEXTVAL):

SELECT  SUM(val)
FROM    (
        SELECT  NVL(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val
        FROM    dual
        CONNECT BY
                level <= 10000
        )

This runs for almost 0.5 seconds, since it generates SYS_GUID()'s, despite 1 being not a NULL.

SELECT  SUM(val)
FROM    (
        SELECT  COALESCE(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val
        FROM    dual
        CONNECT BY
                level <= 10000
        )

This understands that 1 is not a NULL and does not evaluate the second argument.

SYS_GUID's are not generated and the query is instant.

Loop through each cell in a range of cells when given a Range object

I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until loop.

Do Until Selection.Value = ""
  Rem Do things here...
Loop

How to redirect to Index from another controller?

You can use the overloads method RedirectToAction(string actionName, string controllerName);

Example:

RedirectToAction(nameof(HomeController.Index), "Home");

How to get file_get_contents() to work with HTTPS?

I was stuck with non functional https on IIS. Solved with:

file_get_contents('https.. ) wouldn't load.

  • download https://curl.haxx.se/docs/caextract.html
  • install under ..phpN.N/extras/ssl
  • edit php.ini with:

    curl.cainfo = "C:\Program Files\PHP\v7.3\extras\ssl\cacert.pem" openssl.cafile="C:\Program Files\PHP\v7.3\extras\ssl\cacert.pem"

finally!

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

I'd say the best way is to make an href anchor to an ID you'd never use, like #Do1Not2Use3This4Id5 or a similar ID, that you are 100% sure no one will use and won't offend people.

  1. Javascript:void(0) is a bad idea and violates Content Security Policy on CSP-enabled HTTPS pages https://developer.mozilla.org/en/docs/Security/CSP (thanks to @jakub.g)
  2. Using just # will have the user jump back to the top when pressed
  3. Won't ruin the page if JavaScript isn't enabled (unless you have JavaScript detecting code
  4. If JavaScript is enabled you can disable the default event
  5. You have to use href unless you know how to prevent your browser from selecting some text, (don't know if using 4 will remove the thing that stops the browser from selecting text)

Basically no one mentioned 5 in this article which I think is important as your site comes off as unprofessional if it suddenly starts selecting things around the link.

Is there a way to programmatically minimize a window

<form>.WindowState = FormWindowState.Minimized;

duplicate 'row.names' are not allowed error

The answer here (https://stackoverflow.com/a/22408965/2236315) by @adrianoesch should help (e.g., solves "If you know of a solution that does not require the awkward workaround mentioned in your comment (shift the column names, copy the data), that would be great." and "...requiring that the data be copied" proposed by @Frank).

Note that if you open in some text editor, you should see that the number of header fields less than number of columns below the header row. In my case, the data set had a "," missing at the end of the last header field.

How to navigate to a section of a page

My Solutions:

$("body").scrollspy({ target: ".target", offset: fix_header_height });

$(".target").click(function() {
 $("body").animate(
  {
   scrollTop: $($(this).attr("href")).offset().top - fix_header_height
  },
  500
 );
 return;
});

Making a UITableView scroll when text field is selected

If you use Three20, then use the autoresizesForKeyboard property. Just set in the your view controller's -initWithNibName:bundle method

self.autoresizesForKeyboard = YES

This takes care of:

  1. Listening for keyboard notifications and adjusting the table view's frame
  2. Scrolling to the first responder

Done and done.

git ignore vim temporary files

This is something that should only be done on a per-user basis, not per-repository. If Joe uses emacs, he will want to have emacs backup files ignored, but Betty (who uses vi) will want vi backup files ignored (in many cases, they are similar, but there are about 24,893 common editors in existence and it is pretty ridiculous to try to ignore all of the various backup extensions.)

In other words, do not put anything in .gitignore or in core.excludes in $GIT_DIR/config. Put the info in $HOME/.gitconfig instead (as nunopolonia suggests with --global.) Note that "global" means per-user, not per-system.

If you want configuration across the system for all users (which you don't), you'll need a different mechanism. (Possibly with templates setup prior to initialization of the repository.)

On design patterns: When should I use the singleton?

A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital.

When using Singletons, you should make sure that you're not accidentally concealing dependencies. Ideally, the singletons (like most static variables in an application) be set up during the execution of your initialization code for the application (static void Main() for C# executables, static void main() for java executables) and then passed in to all other classes that are instantiated which require it. This helps you maintain testability.

Facebook login "given URL not allowed by application configuration"

I kept getting this error, when using wildcard subdomains with my app. I had the site url set to: http://myapp.com and app domain also to http://myapp.com, and also the same value for the Valid OAuth redirect URIs in the advanced tab of the settings app. I tried different combinations but only setting the http://subdomain.myapp.com as the redirect value worked, of course only for that subdomain.

The solution was to empty the redirect fields, leave it blank, that worked! ;)

comparing two strings in ruby

Here are some:

"Ali".eql? "Ali"
=> true

The spaceship (<=>) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:

"Apples" <=> "Apples"
=> 0

"Apples" <=> "Pears"
=> -1

"Pears" <=> "Apples"
=> 1

A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:

"Apples".casecmp "apples"
=> 0

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

As Justin Scofield has suggested in his answer, for Angular 5's latest release and for Angular 6, as on 1st June, 2018, just import 'rxjs/add/operator/map'; isn't sufficient to remove the TS error: [ts] Property 'map' does not exist on type 'Observable<Object>'.

Its necessary to run the below command to install the required dependencies: npm install rxjs@6 rxjs-compat@6 --save after which the map import dependency error gets resolved!

How to increase application heap size in Eclipse?

Open eclipse.ini

Search for -Xmx512m or maybe more size it is.

Just change it to a required size such as I changed it to -Xmx1024m

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

When you allow the 9000 port to firewall on your desired operating System the following error "ERROR: Sonar server 'http://localhost:9000' can not be reached" will remove successfully.In ubuntu it is just like as by typing the following command in terminal "sudo ufw allow 9000/tcp" this error will removed from the Jenkins server by clicking on build now in jenkins.

How can I send an HTTP POST request to a server from Excel using VBA?

To complete the response of the other users:

For this I have created an "WinHttp.WinHttpRequest.5.1" object.

Send a post request with some data from Excel using VBA:

Dim LoginRequest As Object
Set LoginRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
LoginRequest.Open "POST", "http://...", False
LoginRequest.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
LoginRequest.send ("key1=value1&key2=value2")

Send a get request with token authentication from Excel using VBA:

Dim TCRequestItem As Object
Set TCRequestItem = CreateObject("WinHttp.WinHttpRequest.5.1")
TCRequestItem.Open "GET", "http://...", False
TCRequestItem.setRequestHeader "Content-Type", "application/xml"
TCRequestItem.setRequestHeader "Accept", "application/xml"
TCRequestItem.setRequestHeader "Authorization", "Bearer " & token
TCRequestItem.send

JavaScript Array Push key value

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

Change Activity's theme programmatically

I know that i am late but i would like to post a solution here:
Check the full source code here.
This is the code i used when changing theme using preferences..

SharedPreferences pref = PreferenceManager
        .getDefaultSharedPreferences(this);
String themeName = pref.getString("prefSyncFrequency3", "Theme1");
if (themeName.equals("Africa")) {
    setTheme(R.style.AppTheme);



} else if (themeName.equals("Colorful Beach")) {
    //Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
    setTheme(R.style.beach);


} else if (themeName.equals("Abstract")) {
    //Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();

    setTheme(R.style.abstract2);

} else if (themeName.equals("Default")) {

    setTheme(R.style.defaulttheme);

}

Please note that you have to put the code before setcontentview..

HAPPY CODING!

How to format a URL to get a file from Amazon S3?

Its actually formulated more like:

https://<bucket-name>.s3.amazonaws.com/<key>

See here

Changing image sizes proportionally using CSS?

if you know the spect ratio you can use padding-bottom with percentage to set the hight depending on with of the diff.

<div>
   <div style="padding-bottom: 33%;">
      i have 33% height of my parents width
   </div>
</div>

How to wait for async method to complete?

Best Solution to wait AsynMethod till complete the task is

var result = Task.Run(async() => await yourAsyncMethod()).Result;

Forcing anti-aliasing using css: Is this a myth?

Here's a nice way to achieve anti-aliasing:

text-shadow: 0 0 1px rgba(0,0,0,0.3);

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

You need to annotate your Customer class with @Named or @Model annotation:

package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
    private String email;
    private String password;
}

or create/modify beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">
</beans>

LINQ syntax where string value is not null or empty

This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.

The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.

Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)

Linux / Bash, using ps -o to get process by specific name?

This will get you the PID of a process by name:

pidof name

Which you can then plug back in to ps for more detail:

ps -p $(pidof name)

JSON formatter in C#?

I updated the old version, now it should support unquoted values such as integers and booleans.

I refactored the previous version and got the final version: The code is shorter and cleaner. Only require one extension method. The most important: fixed some bugs.

class JsonHelper
{
    private const string INDENT_STRING = "    ";
    public static string FormatJson(string str)
    {
        var indent = 0;
        var quoted = false;
        var sb = new StringBuilder();
        for (var i = 0; i < str.Length; i++)
        {
            var ch = str[i];
            switch (ch)
            {
                case '{':
                case '[':
                    sb.Append(ch);
                    if (!quoted)
                    {
                        sb.AppendLine();
                        Enumerable.Range(0, ++indent).ForEach(item => sb.Append(INDENT_STRING));
                    }
                    break;
                case '}':
                case ']':
                    if (!quoted)
                    {
                        sb.AppendLine();
                        Enumerable.Range(0, --indent).ForEach(item => sb.Append(INDENT_STRING));
                    }
                    sb.Append(ch);
                    break;
                case '"':
                    sb.Append(ch);
                    bool escaped = false;
                    var index = i;
                    while (index > 0 && str[--index] == '\\')
                        escaped = !escaped;
                    if (!escaped)
                        quoted = !quoted;
                    break;
                case ',':
                    sb.Append(ch);
                    if (!quoted)
                    {
                        sb.AppendLine();
                        Enumerable.Range(0, indent).ForEach(item => sb.Append(INDENT_STRING));
                    }
                    break;
                case ':':
                    sb.Append(ch);
                    if (!quoted)
                        sb.Append(" ");
                    break;
                default:
                    sb.Append(ch);
                    break;
            }
        }
        return sb.ToString();
    }
}

static class Extensions
{
    public static void ForEach<T>(this IEnumerable<T> ie, Action<T> action)
    {
        foreach (var i in ie)
        {
            action(i);
        }
    }
}

How to break out of a loop from inside a switch?

Premise

The following code should be considered bad form, regardless of language or desired functionality:

while( true ) {
}

Supporting Arguments

The while( true ) loop is poor form because it:

  • Breaks the implied contract of a while loop.
    • The while loop declaration should explicitly state the only exit condition.
  • Implies that it loops forever.
    • Code within the loop must be read to understand the terminating clause.
    • Loops that repeat forever prevent the user from terminating the program from within the program.
  • Is inefficient.
    • There are multiple loop termination conditions, including checking for "true".
  • Is prone to bugs.
    • Cannot easily determine where to put code that will always execute for each iteration.
  • Leads to unnecessarily complex code.
  • Automatic source code analysis.
    • To find bugs, program complexity analysis, security checks, or automatically derive any other source code behaviour without code execution, specifying the initial breaking condition(s) allows algorithms to determine useful invariants, thereby improving automatic source code analysis metrics.
  • Infinite loops.
    • If everyone always uses while(true) for loops that are not infinite, we lose the ability to concisely communicate when loops actually have no terminating condition. (Arguably, this has already happened, so the point is moot.)

Alternative to "Go To"

The following code is better form:

while( isValidState() ) {
  execute();
}

bool isValidState() {
  return msg->state != DONE;
}

Advantages

No flag. No goto. No exception. Easy to change. Easy to read. Easy to fix. Additionally the code:

  1. Isolates the knowledge of the loop's workload from the loop itself.
  2. Allows someone maintaining the code to easily extend the functionality.
  3. Allows multiple terminating conditions to be assigned in one place.
  4. Separates the terminating clause from the code to execute.
  5. Is safer for Nuclear Power plants. ;-)

The second point is important. Without knowing how the code works, if someone asked me to make the main loop let other threads (or processes) have some CPU time, two solutions come to mind:

Option #1

Readily insert the pause:

while( isValidState() ) {
  execute();
  sleep();
}

Option #2

Override execute:

void execute() {
  super->execute();
  sleep();
}

This code is simpler (thus easier to read) than a loop with an embedded switch. The isValidState method should only determine if the loop should continue. The workhorse of the method should be abstracted into the execute method, which allows subclasses to override the default behaviour (a difficult task using an embedded switch and goto).

Python Example

Contrast the following answer (to a Python question) that was posted on StackOverflow:

  1. Loop forever.
  2. Ask the user to input their choice.
  3. If the user's input is 'restart', continue looping forever.
  4. Otherwise, stop looping forever.
  5. End.
Code
while True: 
    choice = raw_input('What do you want? ')

    if choice == 'restart':
        continue
    else:
        break

print 'Break!' 

Versus:

  1. Initialize the user's choice.
  2. Loop while the user's choice is the word 'restart'.
  3. Ask the user to input their choice.
  4. End.
Code
choice = 'restart';

while choice == 'restart': 
    choice = raw_input('What do you want? ')

print 'Break!'

Here, while True results in misleading and overly complex code.

How to create a md5 hash of a string in C?

It would appear that you should

  • Create a struct MD5context and pass it to MD5Init to get it into a proper starting condition
  • Call MD5Update with the context and your data
  • Call MD5Final to get the resulting hash

These three functions and the structure definition make a nice abstract interface to the hash algorithm. I'm not sure why you were shown the core transform function in that header as you probably shouldn't interact with it directly.

The author could have done a little more implementation hiding by making the structure an abstract type, but then you would have been forced to allocate the structure on the heap every time (as opposed to now where you can put it on the stack if you so desire).

What's the difference between using CGFloat and float?

As others have said, CGFloat is a float on 32-bit systems and a double on 64-bit systems. However, the decision to do that was inherited from OS X, where it was made based on the performance characteristics of early PowerPC CPUs. In other words, you should not think that float is for 32-bit CPUs and double is for 64-bit CPUs. (I believe, Apple's ARM processors were able to process doubles long before they went 64-bit.) The main performance hit of using doubles is that they use twice the memory and therefore might be slower if you are doing a lot of floating point operations.

PHP array delete by value (not key)

As per your requirement "each value can only be there for once" if you are just interested in keeping unique values in your array, then the array_unique() might be what you are looking for.

Input:

$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);

Result:

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

Rendering raw html with reactjs

You could leverage the html-to-react npm module.

Note: I'm the author of the module and just published it a few hours ago. Please feel free to report any bugs or usability issues.

Python - Locating the position of a regex match in a string?

You could use .find("is"), it would return position of "is" in the string

or use .start() from re

>>> re.search("is", String).start()
2

Actually its match "is" from "This"

If you need to match per word, you should use \b before and after "is", \b is the word boundary.

>>> re.search(r"\bis\b", String).start()
5
>>>

for more info about python regular expressions, docs here

How to remove text before | character in notepad++

To replace anything that starts with "text" until the last character:

text.+(.*)$

Example

text             hsjh sdjh sd          jhsjhsdjhsdj hsd
                                                      ^
                                                      last character


To replace anything that starts with "text" until "123"

text.+(\ 123)

Example

text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e
^                                   ^
From here                     To here

Responsive Images with CSS

.erb-image-wrapper img{
    max-width:100% !important;
    height:auto;
    display:block;
}

Worked for me.
Thanks for MrMisterMan for his assistance.

alert a variable value

If I'm understanding your question and code correctly, then I want to first mention three things before sharing my code/version of a solution. First, for both name and value you probably shouldn't be using the getAttribute() method because they are, themselves, properties of (the variable named) inputs (at a given index of i). Secondly, the variable that you are trying to alert is one of a select handful of terms in JavaScript that are designated as 'reserved keywords' or simply "reserved words". As you can see in/on this list (on the link), new is clearly a reserved word in JS and should never be used as a variable name. For more information, simply google 'reserved words in JavaScript'. Third and finally, in your alert statement itself, you neglected to include a semicolon. That and that alone can sometimes be enough for your code not to run as expected. [Aside: I'm not saying this as advice but more as observation: JavaScript will almost always forgive and allow having too many and/or unnecessary semicolons, but generally JavaScript is also equally if not moreso merciless if/when missing (any of the) necessary, required semicolons. Therefore, best practice is, of course, to add the semicolons only at all of the required points and exclude them in all other circumstances. But practically speaking, if in doubt, it probably will not hurt things by adding/including an extra one but will hurt by ignoring a mandatory one. General rules are all declarations and assignments end with a semicolon (such as variable assignments, alerts, console.log statements, etc.) but most/all expressions do not (such as for loops, while loops, function expressions Just Saying.] But I digress..

    function whenWindowIsReady() {
        var inputs = document.getElementsByTagName('input');
        var lengthOfInputs = inputs.length; // this is for optimization
        for (var i = 0; i < lengthOfInputs; i++) {
            if (inputs[i].name === "ans") {   
                var ansIsName = inputs[i].value;
                alert(ansIsName);
            }
        }
    }

    window.onReady = whenWindowIsReady();

PS: You used a double assignment operator in your conditional statement, and in this case it doesn't matter since you are comparing Strings, but generally I believe the triple assignment operator is the way to go and is more accurate as that would check if the values are EQUIVALENT WITHOUT TYPE CONVERSION, which can be very important for other instances of comparisons, so it's important to point out. For example, 1=="1" and 0==false are both true (when usually you'd want those to return false since the value on the left was not the same as the value on the right, without type conversion) but 1==="1" and 0===false are both false as you'd expect because the triple operator doesn't rely on type conversion when making comparisons. Keep that in mind for the future.

How to format string to money

try

amtf =  amtf.Insert(amtf.Length - 2, ".");

Function ereg_replace() is deprecated - How to clear this bug?

http://php.net/ereg_replace says:

Note: As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension.

Thus, preg_replace is in every way better choice. Note there are some differences in pattern syntax though.

TCP: can two different sockets share a port?

TCP / HTTP Listening On Ports: How Can Many Users Share the Same Port

So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.

Intuitively (and wrongly), most people assume that it looks something like this:

    Local Computer    | Remote Computer
    --------------------------------
    <local_ip>:80     | <foreign_ip>:80

    ^^ not actually what happens, but this is the conceptual model a lot of people have in mind.

This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.

Three things must be understood:

1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.

2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.

3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.

So, this is really what gets created when a client connects to a server:

    Local Computer   | Remote Computer           | Role
    -----------------------------------------------------------
    0.0.0.0:80       | <none>                    | LISTENING
    127.0.0.1:80     | 10.1.2.3:<random_port>    | ESTABLISHED

Looking at What Actually Happens

First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).

    netstat -atnp | grep -i ":500 "

As expected, the output is blank. Now let's start a web server:

    sudo python3 -m http.server 500

Now, here is the output of running netstat again:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      - 

So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all ip addresses". An easy mistake to make is to only listen on port 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.

So now, let's connect a user to our machine:

    quicknet -m tcp -t localhost:500 -p Test payload.

This is a simple script (https://github.com/grokit/quickweb) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:54240      ESTABLISHED -

If you connect with another client and do netstat again, you will see the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:26813      ESTABLISHED -

... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.

Build Error - missing required architecture i386 in file

I too got the same error am using xcode version 4.0.2 so what i did was selected the xcode project file and from their i selected the Target option their i could see the app of my project so i clicked on it and went to the build settings option.

Their in the search option i typed Framework search path, and deleted all the settings and then clicked the build button and that worked for me just fine,

Thanks and Regards

Using Keras & Tensorflow with AMD GPU

One can use AMD GPU via the PlaidML Keras backend.

Fastest: PlaidML is often 10x faster (or more) than popular platforms (like TensorFlow CPU) because it supports all GPUs, independent of make and model. PlaidML accelerates deep learning on AMD, Intel, NVIDIA, ARM, and embedded GPUs.

Easiest: PlaidML is simple to install and supports multiple frontends (Keras and ONNX currently)

Free: PlaidML is completely open source and doesn't rely on any vendor libraries with proprietary and restrictive licenses.

For most platforms, getting started with accelerated deep learning is as easy as running a few commands (assuming you have Python (v2 or v3) installed):

virtualenv plaidml
source plaidml/bin/activate
pip install plaidml-keras plaidbench

Choose which accelerator you'd like to use (many computers, especially laptops, have multiple):

plaidml-setup

Next, try benchmarking MobileNet inference performance:

plaidbench keras mobilenet

Or, try training MobileNet:

plaidbench --batch-size 16 keras --train mobilenet

To use it with keras set

os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"

For more information

https://github.com/plaidml/plaidml

https://github.com/rstudio/keras/issues/205#issuecomment-348336284

What is the most accurate way to retrieve a user's correct IP address in PHP?

I do wonder if perhaps you should iterate over the exploded HTTP_X_FORWARDED_FOR in reverse order, since my experience has been that the user's IP address ends up at the end of the comma-separated list, so starting at the start of the header, you're more likely to get the ip address of one of the proxies returned, which could potentially still allow session hijacking as many users may come through that proxy.

ORA-28000: the account is locked error getting frequently

Solution 01

Account Unlock by using below query :

SQL> select USERNAME,ACCOUNT_STATUS from dba_users where username='ABCD_DEV';    
USERNAME             ACCOUNT_STATUS
-------------------- --------------------------------
ABCD_DEV       LOCKED

SQL> alter user ABCD_DEV account unlock;    
User altered.

SQL> select USERNAME,ACCOUNT_STATUS from dba_users where username='ABCD_DEV';    
USERNAME             ACCOUNT_STATUS
-------------------- --------------------------------
ABCD_DEV       OPEN

Solution 02

Check PASSWORD_LIFE_TIME parameter by using below query :

SELECT resource_name, limit FROM dba_profiles WHERE profile = 'DEFAULT' AND resource_type = 'PASSWORD';

RESOURCE_NAME                    LIMIT
-------------------------------- ------------------------------
FAILED_LOGIN_ATTEMPTS            10
PASSWORD_LIFE_TIME               10
PASSWORD_REUSE_TIME              10
PASSWORD_REUSE_MAX               UNLIMITED
PASSWORD_VERIFY_FUNCTION         NULL
PASSWORD_LOCK_TIME               1
PASSWORD_GRACE_TIME              7
INACTIVE_ACCOUNT_TIME            UNLIMITED

Change the parameter using below query

ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

Visual Studio - How to change a project's folder name and solution name without breaking the solution

You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.

IF - ELSE IF - ELSE Structure in Excel

When FIND returns #VALUE!, it is an error, not a string, so you can't compare FIND(...) with "#VALUE!", you need to check if FIND returns an error with ISERROR. Also FIND can work on multiple characters.

So a simplified and working version of your formula would be:

=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))

Or, to remove the double negations:

=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")

How can I make a button have a rounded border in Swift?

You can subclass UIButton and add @IBInspectable variables to it so you can configure the custom button parameters via the StoryBoard "Attribute Inspector". Below I write down that code.

@IBDesignable
class BHButton: UIButton {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    @IBInspectable lazy var isRoundRectButton : Bool = false

    @IBInspectable public var cornerRadius : CGFloat = 0.0 {
        didSet{
            setUpView()
        }
    }

    @IBInspectable public var borderColor : UIColor = UIColor.clear {
        didSet {
            self.layer.borderColor = borderColor.cgColor
        }
    }

    @IBInspectable public var borderWidth : CGFloat = 0.0 {
        didSet {
            self.layer.borderWidth = borderWidth
        }
    }

    //  MARK:   Awake From Nib

    override func awakeFromNib() {
        super.awakeFromNib()
        setUpView()
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        setUpView()
    }

    func setUpView() {
        if isRoundRectButton {
            self.layer.cornerRadius = self.bounds.height/2;
            self.clipsToBounds = true
        }
        else{
            self.layer.cornerRadius = self.cornerRadius;
            self.clipsToBounds = true
        }
    }

}

Bigger Glyphicons

_x000D_
_x000D_
<button class="btn btn-default glyphicon glyphicon-plus fa-2x" type="button">_x000D_
</button>_x000D_
_x000D_
<!--fa-2x , fa-3x , fa-4x ... -->_x000D_
<button class="btn btn-default glyphicon glyphicon-plus fa-3x" type="button">_x000D_
</button>
_x000D_
_x000D_
_x000D_

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

You can covert numpy.ndarray to object using astype(object)

This will work:

>>> a = [np.zeros((224,224,3)).astype(object), np.zeros((224,224,3)).astype(object), np.zeros((224,224,13)).astype(object)]

Split string in JavaScript and detect line break

Split string in JavaScript

var array = str.match(/[^\r\n]+/g);

OR

var array = str.split(/\r?\n/);

Performance

How to find locked rows in Oracle

The below PL/SQL block finds all locked rows in a table. The other answers only find the blocking session, finding the actual locked rows requires reading and testing each row.

(However, you probably do not need to run this code. If you're having a locking problem, it's usually easier to find the culprit using GV$SESSION.BLOCKING_SESSION and other related data dictionary views. Please try another approach before you run this abysmally slow code.)

First, let's create a sample table and some data. Run this in session #1.

--Sample schema.
create table test_locking(a number);
insert into test_locking values(1);
insert into test_locking values(2);
commit;
update test_locking set a = a+1 where a = 1;

In session #2, create a table to hold the locked ROWIDs.

--Create table to hold locked ROWIDs.
create table locked_rowids(the_rowid rowid);
--Remove old rows if table is already created:
--delete from locked_rowids;
--commit;

In session #2, run this PL/SQL block to read the entire table, probe each row, and store the locked ROWIDs. Be warned, this may be ridiculously slow. In your real version of this query, change both references to TEST_LOCKING to your own table.

--Save all locked ROWIDs from a table.
--WARNING: This PL/SQL block will be slow and will temporarily lock rows.
--You probably don't need this information - it's usually good enough to know
--what other sessions are locking a statement, which you can find in
--GV$SESSION.BLOCKING_SESSION.
declare
    v_resource_busy exception;
    pragma exception_init(v_resource_busy, -00054);
    v_throwaway number;
    type rowid_nt is table of rowid;
    v_rowids rowid_nt := rowid_nt();
begin
    --Loop through all the rows in the table.
    for all_rows in
    (
        select rowid
        from test_locking
    ) loop
        --Try to look each row.
        begin
            select 1
            into v_throwaway
            from test_locking
            where rowid = all_rows.rowid
            for update nowait;
        --If it doesn't lock, then record the ROWID.
        exception when v_resource_busy then
            v_rowids.extend;
            v_rowids(v_rowids.count) := all_rows.rowid;
        end;

        rollback;
    end loop;

    --Display count:
    dbms_output.put_line('Rows locked: '||v_rowids.count);

    --Save all the ROWIDs.
    --(Row-by-row because ROWID type is weird and doesn't work in types.)
    for i in 1 .. v_rowids.count loop
        insert into locked_rowids values(v_rowids(i));
    end loop;
    commit;
end;
/

Finally, we can view the locked rows by joining to the LOCKED_ROWIDS table.

--Display locked rows.
select *
from test_locking
where rowid in (select the_rowid from locked_rowids);


A
-
1

Play audio file from the assets directory

This function will work properly :)

// MediaPlayer m; /*assume, somewhere in the global scope...*/

public void playBeep() {
    try {
        if (m.isPlaying()) {
            m.stop();
            m.release();
            m = new MediaPlayer();
        }

        AssetFileDescriptor descriptor = getAssets().openFd("beepbeep.mp3");
        m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
        descriptor.close();

        m.prepare();
        m.setVolume(1f, 1f);
        m.setLooping(true);
        m.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

How to measure time in milliseconds using ANSI C?

There is no ANSI C function that provides better than 1 second time resolution but the POSIX function gettimeofday provides microsecond resolution. The clock function only measures the amount of time that a process has spent executing and is not accurate on many systems.

You can use this function like this:

struct timeval tval_before, tval_after, tval_result;

gettimeofday(&tval_before, NULL);

// Some code you want to time, for example:
sleep(1);

gettimeofday(&tval_after, NULL);

timersub(&tval_after, &tval_before, &tval_result);

printf("Time elapsed: %ld.%06ld\n", (long int)tval_result.tv_sec, (long int)tval_result.tv_usec);

This returns Time elapsed: 1.000870 on my machine.

How can I set the opacity or transparency of a Panel in WinForms?

Panel with opacity:

public class GlassyPanel : Panel
{
    const int WS_EX_TRANSPARENT = 0x20;  

    int opacity = 50;

    public int Opacity
    {
        get
        {
            return opacity;
        }
        set
        {
            if (value < 0 || value > 100) throw new ArgumentException("Value must be between 0 and 100");
            opacity = value;
        }
    }

    protected override CreateParams CreateParams
    {
        get
        {
            var cp = base.CreateParams;
            cp.ExStyle = cp.ExStyle | WS_EX_TRANSPARENT;

            return cp;
        }
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        using (var b = new SolidBrush(Color.FromArgb(opacity * 255 / 100, BackColor)))
        {
            e.Graphics.FillRectangle(b, ClientRectangle);
        }

        base.OnPaint(e);
    }
}

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric

geom_segment(data=tmpp, 
   aes(x=start_pos, 
   y=lib.complexity, 
   xend=end_pos, 
   yend=lib.complexity)
)
# to 
geom_segment(data=tmpp, 
   aes(x=as.numeric(start_pos), 
   y=as.numeric(lib.complexity), 
   xend=as.numeric(end_pos), 
   yend=as.numeric(lib.complexity))
)

Format date with Moment.js

Include moment.js and using the below code you can format your date

var formatDate= 1399919400000;

var responseDate = moment(formatDate).format('DD/MM/YYYY');

My output is "13/05/2014"

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

Even though the question is too old, but I would like to share the solution that worked for me because I already checked everything when it comes to this error. It was a pain, I spent two days trying and at the end the solution was:

update the M2e plugin in eclipse

clean and build again

What are naming conventions for MongoDB?

I think it's all personal preference. My preferences come from using NHibernate, in .NET, with SQL Server, so they probably differ from what others use.

  • Databases: The application that's being used.. ex: Stackoverflow
  • Collections: Singular in name, what it's going to be a collection of, ex: Question
  • Document fields, ex: MemberFirstName

Honestly, it doesn't matter too much, as long as it's consistent for the project. Just get to work and don't sweat the details :P

Web.Config Debug/Release

If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<connectionStrings xdt:Transform="Replace">
    <!-- production environment config --->
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>
....

Information for this answer are brought from this answer and this blog post.

notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

MySQL WHERE IN ()

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET. Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

How to get current date & time in MySQL?

If you make change default value to CURRENT_TIMESTAMP it is more effiency,

ALTER TABLE servers MODIFY COLUMN network_shares datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

For most of the people still receiving the error after fixing project properties, you probably installed Java 7 SDK when setting up your environment, but it is not currently supported for Android development.

As the error message sais, you should have installed Java 5.0 or 6.0, but Java 7 was found.

If you fix project properties without first installing Java 5 or 6, you will see the same error again.

  • So first, ensure you have Java SDK 5 or 6 installed, or install it.
  • Check your environment variable (JAVA_HOME) is pointing to SDK 5/6.

And then:

  • Check that Eclipse is using SDK 5/6 by default (Window => Prefs. => Java => Compiler
  • Disable Project Specific Settings (Project Properties => Java Compiler)
  • Fix Project Properties

OR

  • Leave Eclipse using JDK 7 by default.
  • Enable Project Specific Settings (Project Properties => Java Compiler)
  • Select Compiler Compliance 1.5 or 1.6 (Project Properties => Java Compiler)

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

Error importing SQL dump into MySQL: Unknown database / Can't create database

If you create your database in direct admin or cpanel, you must edit your sql with notepad or notepad++ and change CREATE DATABASE command to CREATE DATABASE IF NOT EXISTS in line22

How to use ArgumentCaptor for stubbing?

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

The calling thread must be STA, because many UI components require this

If you make the call from the main thread, you must add the STAThread attribute to the Main method, as stated in the previous answer.

If you use a separate thread, it needs to be in a STA (single-threaded apartment), which is not the case for background worker threads. You have to create the thread yourself, like this:

Thread t = new Thread(ThreadProc);
t.SetApartmentState(ApartmentState.STA);

t.Start();

with ThreadProc being a delegate of type ThreadStart.

App.Config file in console application C#

use this

System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")

How to make an array of arrays in Java

try

String[][] arrays = new String[5][];

Using :focus to style outer div?

Some people, like me, will benefit from using the :focus-within pseudo-class.

Using it will apply the css you want to a div, for instance.

You can read more here https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within

center image in div with overflow hidden

You should make the container relative and give it a height as well and you're done.

http://jsfiddle.net/jaap/wjw83/4/

_x000D_
_x000D_
.main {_x000D_
  width: 300px;_x000D_
  margin: 0 auto;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  height: 200px;_x000D_
}_x000D_
_x000D_
img.absolute {_x000D_
  left: 50%;_x000D_
  margin-left: -200px;_x000D_
  position: absolute;_x000D_
}
_x000D_
<div class="main">_x000D_
  <img class="absolute" src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />_x000D_
</div>_x000D_
<br />_x000D_
<img src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />
_x000D_
_x000D_
_x000D_

If you want to you can also center the image vertically by adding a negative margin and top position: http://jsfiddle.net/jaap/wjw83/5/

How do you parse and process HTML/XML in PHP?

Just use DOMDocument->loadHTML() and be done with it. libxml's HTML parsing algorithm is quite good and fast, and contrary to popular belief, does not choke on malformed HTML.

How to Read from a Text File, Character by Character in C++

To quote Bjarne Stroustrup:"The >> operator is intended for formatted input; that is, reading objects of an expected type and format. Where this is not desirable and we want to read charactes as characters and then examine them, we use the get() functions."

char c;
while (input.get(c))
{
    // do something with c
}

Monad in plain English? (For the OOP programmer with no FP background)

From wikipedia:

In functional programming, a monad is a kind of abstract data type used to represent computations (instead of data in the domain model). Monads allow the programmer to chain actions together to build a pipeline, in which each action is decorated with additional processing rules provided by the monad. Programs written in functional style can make use of monads to structure procedures that include sequenced operations,1[2] or to define arbitrary control flows (like handling concurrency, continuations, or exceptions).

Formally, a monad is constructed by defining two operations (bind and return) and a type constructor M that must fulfill several properties to allow the correct composition of monadic functions (i.e. functions that use values from the monad as their arguments). The return operation takes a value from a plain type and puts it into a monadic container of type M. The bind operation performs the reverse process, extracting the original value from the container and passing it to the associated next function in the pipeline.

A programmer will compose monadic functions to define a data-processing pipeline. The monad acts as a framework, as it's a reusable behavior that decides the order in which the specific monadic functions in the pipeline are called, and manages all the undercover work required by the computation.[3] The bind and return operators interleaved in the pipeline will be executed after each monadic function returns control, and will take care of the particular aspects handled by the monad.

I believe it explains it very well.

React Router Pass Param to Component

If you want to pass props to a component inside a route, the simplest way is by utilizing the render, like this:

<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />

You can access the props inside the DetailPage using:

this.props.match
this.props.globalStore

The {...props} is needed to pass the original Route's props, otherwise you will only get this.props.globalStore inside the DetailPage.

Count the number occurrences of a character in a string

I know the ask is to count a particular letter. I am writing here generic code without using any method.

sentence1 =" Mary had a little lamb"
count = {}
for i in sentence1:
    if i in count:
        count[i.lower()] = count[i.lower()] + 1
    else:
        count[i.lower()] = 1
print(count)

output

{' ': 5, 'm': 2, 'a': 4, 'r': 1, 'y': 1, 'h': 1, 'd': 1, 'l': 3, 'i': 1, 't': 2, 'e': 1, 'b': 1}

Now if you want any particular letter frequency, you can print like below.

print(count['m'])
2

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

Apart of larsmans answer (who is indeed correct), the exception in a call to a get() method, so the code you have posted is not the one that is causing the error.

Where do I call the BatchNormalization function in Keras?

Batch Normalization is used to normalize the input layer as well as hidden layers by adjusting mean and scaling of the activations. Because of this normalizing effect with additional layer in deep neural networks, the network can use higher learning rate without vanishing or exploding gradients. Furthermore, batch normalization regularizes the network such that it is easier to generalize, and it is thus unnecessary to use dropout to mitigate overfitting.

Right after calculating the linear function using say, the Dense() or Conv2D() in Keras, we use BatchNormalization() which calculates the linear function in a layer and then we add the non-linearity to the layer using Activation().

from keras.layers.normalization import BatchNormalization
model = Sequential()
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('softmax'))

sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, 
validation_split=0.2, verbose = 2)

How is Batch Normalization applied?

Suppose we have input a[l-1] to a layer l. Also we have weights W[l] and bias unit b[l] for the layer l. Let a[l] be the activation vector calculated(i.e. after adding the non-linearity) for the layer l and z[l] be the vector before adding non-linearity

  1. Using a[l-1] and W[l] we can calculate z[l] for the layer l
  2. Usually in feed-forward propagation we will add bias unit to the z[l] at this stage like this z[l]+b[l], but in Batch Normalization this step of addition of b[l] is not required and no b[l] parameter is used.
  3. Calculate z[l] means and subtract it from each element
  4. Divide (z[l] - mean) using standard deviation. Call it Z_temp[l]
  5. Now define new parameters ? and ß that will change the scale of the hidden layer as follows:

    z_norm[l] = ?.Z_temp[l] + ß

In this code excerpt, the Dense() takes the a[l-1], uses W[l] and calculates z[l]. Then the immediate BatchNormalization() will perform the above steps to give z_norm[l]. And then the immediate Activation() will calculate tanh(z_norm[l]) to give a[l] i.e.

a[l] = tanh(z_norm[l])

Calculate relative time in C#

jquery.timeago plugin

Jeff, because Stack Overflow uses jQuery extensively, I recommend the jquery.timeago plugin.

Benefits:

  • Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically.
  • You can take full advantage of page and/or fragment caching in your web applications, because the timestamps aren't calculated on the server.
  • You get to use microformats like the cool kids.

Just attach it to your timestamps on DOM ready:

jQuery(document).ready(function() {
    jQuery('abbr.timeago').timeago();
});

This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title:

<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>

into something like this:

<abbr class="timeago" title="July 17, 2008">4 months ago</abbr>

which yields: 4 months ago. As time passes, the timestamps will automatically update.

Disclaimer: I wrote this plugin, so I'm biased.

How to capture a list of specific type with mockito

Based on @tenshi's and @pkalinow's comments (also kudos to @rogerdpack), the following is a simple solution for creating a list argument captor that also disables the "uses unchecked or unsafe operations" warning:

@SuppressWarnings("unchecked")
final ArgumentCaptor<List<SomeType>> someTypeListArgumentCaptor =
    ArgumentCaptor.forClass(List.class);

Full example here and corresponding passing CI build and test run here.

Our team has been using this for some time in our unit tests and this looks like the most straightforward solution for us.

How to copy a file to multiple directories using the gnu cp command

For example if you are in the parent directory of you destination folders you can do:

for i in $(ls); do cp sourcefile $i; done

Handling exceptions from Java ExecutorService tasks

WARNING: It should be noted that this solution will block the calling thread.


If you want to process exceptions thrown by the task, then it is generally better to use Callable rather than Runnable.

Callable.call() is permitted to throw checked exceptions, and these get propagated back to the calling thread:

Callable task = ...
Future future = executor.submit(task);
try {
   future.get();
} catch (ExecutionException ex) {
   ex.getCause().printStackTrace();
}

If Callable.call() throws an exception, this will be wrapped in an ExecutionException and thrown by Future.get().

This is likely to be much preferable to subclassing ThreadPoolExecutor. It also gives you the opportunity to re-submit the task if the exception is a recoverable one.

How to set default value to all keys of a dict object in python?

Use defaultdict

from collections import defaultdict
a = {} 
a = defaultdict(lambda:0,a)
a["anything"] # => 0

This is very useful for case like this,where default values for every key is set as 0:

results ={ 'pre-access' : {'count': 4, 'pass_count': 2},'no-access' : {'count': 55, 'pass_count': 19}
for k,v in results.iteritems():
  a['count'] += v['count']
  a['pass_count'] += v['pass_count']

Send JavaScript variable to PHP variable

PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:

<script type="text/javascript">
  var foo = '<?php echo $foo ?>';
</script>

To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):

var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});

On your server, you would need to receive the variable sent in the post:

$variable = $_POST['variable'];

INSERT ... ON DUPLICATE KEY (do nothing)

HOW TO IMPLEMENT 'insert if not exist'?

1. REPLACE INTO

pros:

  1. simple.

cons:

  1. too slow.

  2. auto-increment key will CHANGE(increase by 1) if there is entry matches unique key or primary key, because it deletes the old entry then insert new one.

2. INSERT IGNORE

pros:

  1. simple.

cons:

  1. auto-increment key will not change if there is entry matches unique key or primary key but auto-increment index will increase by 1

  2. some other errors/warnings will be ignored such as data conversion error.

3. INSERT ... ON DUPLICATE KEY UPDATE

pros:

  1. you can easily implement 'save or update' function with this

cons:

  1. looks relatively complex if you just want to insert not update.

  2. auto-increment key will not change if there is entry matches unique key or primary key but auto-increment index will increase by 1

4. Any way to stop auto-increment key increasing if there is entry matches unique key or primary key?

As mentioned in the comment below by @toien: "auto-increment column will be effected depends on innodb_autoinc_lock_mode config after version 5.1" if you are using innodb as your engine, but this also effects concurrency, so it needs to be well considered before used. So far I'm not seeing any better solution.

Installing a plain plugin jar in Eclipse 3.5

in Eclipse 4.4.1

  1. copy jar in "C:\eclipse\plugins"
  2. edit file "C:\eclipse\configuration\org.eclipse.equinox.simpleconfigurator\bundles.info"
  3. add jar info. example: com.soft4soft.resort.jdt,2.4.4,file:plugins\com.soft4soft.resort.jdt_2.4.4.jar,4,false
  4. restart Eclipse.

How to check if a file exists in a shell script

Internally, the rm command must test for file existence anyway,
so why add another test? Just issue

rm filename

and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.

If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.

How to change Toolbar home icon color

Instead of style changes, just put these two lines of code to your activity.

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.arrowleft);

How to position three divs in html horizontally?

I'd refrain from using floats for this sort of thing; I'd rather use inline-block.

Some more points to consider:

  • Inline styles are bad for maintainability
  • You shouldn't have spaces in selector names
  • You missed some important HTML tags, like <head> and <body>
  • You didn't include a doctype

Here's a better way to format your document:

<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<style type="text/css">
* {margin: 0; padding: 0;}
#container {height: 100%; width:100%; font-size: 0;}
#left, #middle, #right {display: inline-block; *display: inline; zoom: 1; vertical-align: top; font-size: 12px;}
#left {width: 25%; background: blue;}
#middle {width: 50%; background: green;}
#right {width: 25%; background: yellow;}
</style>
</head>
<body>
<div id="container">
    <div id="left">Left Side Menu</div>
    <div id="middle">Random Content</div>
    <div id="right">Right Side Menu</div>
</div>
</body>
</html>

Here's a jsFiddle for good measure.

How do I get an empty array of any size in python?

If you (or other searchers of this question) were actually interested in creating a contiguous array to fill with integers, consider bytearray and memoryivew:

# cast() is available starting Python 3.3
size = 10**6 
ints = memoryview(bytearray(size)).cast('i') 

ints.contiguous, ints.itemsize, ints.shape
# (True, 4, (250000,))

ints[0]
# 0

ints[0] = 16
ints[0]
# 16

Hiding a form and showing another when a button is clicked in a Windows Forms application

The While statement will not execute until after form1 is closed - as it is outside the main message loop.

Remove it and change the first bit of code to:

private void button1_Click_1(object sender, EventArgs e)  
{  
    if (richTextBox1.Text != null)  
    {  
        this.Visible=false;
        Form2 form2 = new Form2();
        form2.show();
    }  
    else MessageBox.Show("Insert Attributes First !");  

}

This is not the best way to achieve what you are looking to do though. Instead consider the Wizard design pattern.

Alternatively you could implement a custom ApplicationContext that handles the lifetime of both forms. An example to implement a splash screen is here, which should set you on the right path.

http://www.codeproject.com/KB/cs/applicationcontextsplash.aspx?display=Print

One line if statement not working

One line if:

<statement> if <condition>

Your case:

"Yes" if @item.rigged

"No" if [email protected] # or: "No" unless @item.rigged

How to force file download with PHP

Read the docs about built-in PHP function readfile

$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($file_url); 

Also make sure to add proper content type based on your file application/zip, application/pdf etc. - but only if you do not want to trigger the save-as dialog.

HQL "is null" And "!= null" on an Oracle column

That is a binary operator in hibernate you should use

is not null

Have a look at 14.10. Expressions

How to fix java.net.SocketException: Broken pipe?

This is caused by:

  • most usually, writing to a connection when the other end has already closed it;
  • less usually, the peer closing the connection without reading all the data that is already pending at his end.

So in both cases you have a poorly defined or implemented application protocol.

There is a third reason which I will not document here but which involves the peer taking deliberate action to reset rather than properly close the connection.

How to change Label Value using javascript

This will work in Chrome

// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'

But after looking, labels doesn't seem to be widely supported..


You can use querySelector

// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'

Bootstrap 4 datapicker.js not included

Maybe you want to try this: https://bootstrap-datepicker.readthedocs.org/en/latest/index.html

It's a flexible datepicker widget in the Bootstrap style.

how to print an exception using logger?

Try to log the stack trace like below:

logger.error("Exception :: " , e);

X11/Xlib.h not found in Ubuntu

A quick search using...

apt search Xlib.h

Turns up the package libx11-dev but you shouldn't need this for pure OpenGL programming. What tutorial are you using?

You can add Xlib.h to your system by running the following...

sudo apt install libx11-dev

Plotting in a non-blocking way with Matplotlib

A lot of these answers are super inflated and from what I can find, the answer isn't all that difficult to understand.

You can use plt.ion() if you want, but I found using plt.draw() just as effective

For my specific project I'm plotting images, but you can use plot() or scatter() or whatever instead of figimage(), it doesn't matter.

plt.figimage(image_to_show)
plt.draw()
plt.pause(0.001)

Or

fig = plt.figure()
...
fig.figimage(image_to_show)
fig.canvas.draw()
plt.pause(0.001)

If you're using an actual figure.
I used @krs013, and @Default Picture's answers to figure this out
Hopefully this saves someone from having launch every single figure on a separate thread, or from having to read these novels just to figure this out

alternative to "!is.null()" in R

If it's just a matter of easy reading, you could always define your own function :

is.not.null <- function(x) !is.null(x)

So you can use it all along your program.

is.not.null(3)
is.not.null(NULL)

CSS property to pad text inside of div

Padding is a way to add kind of a margin inside the Div.
Just Use

div { padding-left: 20px; }

And to mantain the size, you would have to -20px from the original width of the Div.

How to change default install location for pip

You can set the following environment variable:

PIP_TARGET=/path/to/pip/dir

https://pip.pypa.io/en/stable/user_guide/#environment-variables

C# - Simplest way to remove first occurrence of a substring from another string

I definitely agree that this is perfect for an extension method, but I think it can be improved a bit.

public static string Remove(this string source, string remove,  int firstN)
    {
        if(firstN <= 0 || string.IsNullOrEmpty(source) || string.IsNullOrEmpty(remove))
        {
            return source;
        }
        int index = source.IndexOf(remove);
        return index < 0 ? source : source.Remove(index, remove.Length).Remove(remove, --firstN);
    }

This does a bit of recursion which is always fun.

Here is a simple unit test as well:

   [TestMethod()]
    public void RemoveTwiceTest()
    {
        string source = "look up look up look it up";
        string remove = "look";
        int firstN = 2;
        string expected = " up  up look it up";
        string actual;
        actual = source.Remove(remove, firstN);
        Assert.AreEqual(expected, actual);

    }

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

System.Net.Http: missing from namespace? (using .net 4.5)

HttpClient lives in the System.Net.Http namespace.

You'll need to add:

using System.Net.Http;

And make sure you are referencing System.Net.Http.dll in .NET 4.5.


The code posted doesn't appear to do anything with webClient. Is there something wrong with the code that is actually compiling using HttpWebRequest?


Update

To open the Add Reference dialog right-click on your project in Solution Explorer and select Add Reference.... It should look something like:

enter image description here

Remove a folder from git tracking

I came across this question while Googling for "git remove folder from tracking". The OP's question lead me to the answer. I am summarizing it here for future generations.

Question

How do I remove a folder from my git repository without deleting it from my local machine (i.e., development environment)?

Answer

Step 1. Add the folder path to your repo's root .gitignore file.

path_to_your_folder/

Step 2. Remove the folder from your local git tracking, but keep it on your disk.

git rm -r --cached path_to_your_folder/

Step 3. Push your changes to your git repo.

The folder will be considered "deleted" from Git's point of view (i.e. they are in past history, but not in the latest commit, and people pulling from this repo will get the files removed from their trees), but stay on your working directory because you've used --cached.

Running ASP.Net on a Linux based server

dotnet is the official home of .NET on GitHub. It's a great starting point to find many .NET OSS projects from Microsoft and the community, including many that are part of the .NET Foundation.

This may be a great start to support Linux.