Programs & Examples On #Lobo cobra

Cobra is a pure Java HTML renderer and DOM parser that is being developed to support HTML 4, Javascript and CSS 2.

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

Up to Android 7.1 (SDK 25)

Until Android 7.1 you will get it with:

Build.SERIAL

From Android 8 (SDK 26)

On Android 8 (SDK 26) and above, this field will return UNKNOWN and must be accessed with:

Build.getSerial()

which requires the dangerous permission android.permission.READ_PHONE_STATE.

From Android Q (SDK 29)

Since Android Q using Build.getSerial() gets a bit more complicated by requiring:

android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE (which can only be acquired by system apps), or for the calling package to be the device or profile owner and have the READ_PHONE_STATE permission. This means most apps won't be able to uses this feature. See the Android Q announcement from Google.

See Android SDK reference


Best Practice for Unique Device Identifier

If you just require a unique identifier, it's best to avoid using hardware identifiers as Google continuously tries to make it harder to access them for privacy reasons. You could just generate a UUID.randomUUID().toString(); and save it the first time it needs to be accessed in e.g. shared preferences. Alternatively you could use ANDROID_ID which is a 8 byte long hex string unique to the device, user and (only Android 8+) app installation. For more info on that topic, see Best practices for unique identifiers.

How to compile without warnings being treated as errors?

Sure, find where -Werror is set and remove that flag. Then warnings will be only warnings.

UICollectionView Set number of columns

the perfect solution is to Using UICollectionViewDelegateFlowLayout but you can easily so calculate the cell width and divided on the wanted number of columns you want

the tricky is to make the width with no fraction

(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{
 CGFloat screenWidth = self.view.frame.size.width;
   CGFloat marginWidth = (screenWidth - collectionView.frame.size.width);


   CGFloat cellWith = (collectionView.frame.size.width - marginWidth )/3;
   cellWith= floorf(cellWith);




  CGSize retval = CGSizeMake(cellWith,cellWith);


  return retval;}

How to provide animation when calling another activity in Android?

Wrote a tutorial so that you can animate your activity's in and out,

Enjoy:

http://blog.blundellapps.com/animate-an-activity/

Display a jpg image on a JPanel

ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );

How can I disable a button on a jQuery UI dialog?

A button is identified by the class ui-button. To disable a button:

$("#myButton").addClass("ui-state-disabled").attr("disabled", true);

Unless you are dynamically creating the dialog (which is possible), you will know the position of the button. So, to disable the first button:

$("#myButton:eq(0)").addClass("ui-state-disabled").attr("disabled", true);

The ui-state-disabled class is what gives a button that nice dimmed style.

What do I use on linux to make a python program executable

Another way to do it could be by creating an alias. For example in terminal write:

alias printhello='python /home/hello_world.py'

Writing printhello will run hello_world.py, but this is only temporary. To make aliases permanent, you have to add them to bashrc, you can edit it by writing this in the terminal:

gedit ~/.bashrc

find -exec with multiple commands

Thanks to Camilo Martin, I was able to answer a related question:

What I wanted to do was

find ... -exec zcat {} | wc -l \;

which didn't work. However,

find ... | while read -r file; do echo "$file: `zcat $file | wc -l`"; done

does work, so thank you!

A simple algorithm for polygon intersection

If you use C++, and don't want to create the algorithm yourself, you can use Boost.Geometry. It uses an adapted version of the Weiler-Atherton algorithm mentioned above.

Scala: write string to file in one statement

If you like Groovy syntax, you can use the Pimp-My-Library design pattern to bring it to Scala:

import java.io._
import scala.io._

class RichFile( file: File ) {

  def text = Source.fromFile( file )(Codec.UTF8).mkString

  def text_=( s: String ) {
    val out = new PrintWriter( file , "UTF-8")
    try{ out.print( s ) }
    finally{ out.close }
  }
}

object RichFile {

  implicit def enrichFile( file: File ) = new RichFile( file )

}

It will work as expected:

scala> import RichFile.enrichFile
import RichFile.enrichFile

scala> val f = new File("/tmp/example.txt")
f: java.io.File = /tmp/example.txt

scala> f.text = "hello world"

scala> f.text
res1: String = 
"hello world

Is it possible to print a variable's type in standard C++?

Note that the names generated by the RTTI feature of C++ is not portable. For example, the class

MyNamespace::CMyContainer<int, test_MyNamespace::CMyObject>

will have the following names:

// MSVC 2003:
class MyNamespace::CMyContainer[int,class test_MyNamespace::CMyObject]
// G++ 4.2:
N8MyNamespace8CMyContainerIiN13test_MyNamespace9CMyObjectEEE

So you can't use this information for serialization. But still, the typeid(a).name() property can still be used for log/debug purposes

Changing SQL Server collation to case insensitive from case sensitive?

You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.

Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.

You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.

You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

pip cannot install anything

This has happened to my because of proxy-authntication, so I did this to resolve it

export http_proxy=http://uname:[email protected]:8080
export https_proxy=http://uname:[email protected]:8080
export ftp_proxy=http://uname:[email protected]:8080

"This project is incompatible with the current version of Visual Studio"

In case you came here looking for the issue with ".smproj" file, it is because you are missing SQL Server Analysis Services(SSAS). To over come this, install SQL Server Data Tools(SSDT) in your system, restart your Visual Studio and it will work.

Thanks.

increase font size of hyperlink text html

Your font tag is not correct, so it won't work in some browsers. The px unit is used with CSS, not HTML attributes. The font tag should look like this:

<font size="100">

Well, actually it shouldn't be there at all. The font tag is deprecated, you should use CSS to style the content, like you do already with the text-decoration:

<a href="selectTopic?html" style="font-size: 100px; text-decoration: none">HTML 5</a>

To separate the content from the styling, you should of course work towards putting the CSS in a style sheet rather than as inline style attributes. That way you can apply one style to several elements without having to put the same style attribute in all of them.

Example:

<a href="selectTopic?html" class="topic">HTML 5</a>

CSS:

.topic { font-size: 100px; text-decoration: none; }

Select multiple elements from a list

mylist[c(5,7,9)] should do it.

You want the sublists returned as sublists of the result list; you don't use [[]] (or rather, the function is [[) for that -- as Dason mentions in comments, [[ grabs the element.

How to create a function in SQL Server

This will work for most of the website names :

SELECT ID, REVERSE(PARSENAME(REVERSE(WebsiteName), 2)) FROM dbo.YourTable .....

JavaScript "cannot read property "bar" of undefined

If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:

if (thing && thing.foo)
   alert(thing.foo.bar);

I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:

function someFunc(parameterName) {
   if (parameterName && parameterName.foo)
       alert(parameterName.foo.bar);
}

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

For me this error occurred because i didn't have UIWindow declared in the upper level of my class when setting a root view controller

            rootViewController?.showTimeoutAlert = showTimeOut
            let navigationController = SwipeNavigationController(rootViewController: rootViewController!)
            self.window = UIWindow(frame: UIScreen.main.bounds)
            self.window?.rootViewController = navigationController
            self.window?.makeKeyAndVisible()

Ex if I tried declaring window in that block of code instead of referencing self then I would receive the error

The type arguments for method cannot be inferred from the usage

As I mentioned in my comment, I think the reason why this doesn't work is because the compiler can't infer types based on generic constraints.

Below is an alternative implementation that will compile. I've revised the IAccess interface to only have the T generic type parameter.

interface ISignatur<T>
{
    Type Type { get; }
}

interface IAccess<T>
{
    ISignatur<T> Signature { get; }
    T Value { get; set; }
}

class Signatur : ISignatur<bool>
{
    public Type Type
    {
        get { return typeof(bool); }
    }
}

class ServiceGate
{
    public IAccess<T> Get<T>(ISignatur<T> sig)
    {
        throw new NotImplementedException();
    }
}

static class Test
{
    static void Main()
    {
        ServiceGate service = new ServiceGate();
        var access = service.Get(new Signatur());
    }
}

Access iframe elements in JavaScript

If your iframe is in the same domain as your parent page you can access the elements using document.frames collection.

// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on document.frames['myIFrame'].document like you are working on
// normal document object in JS
window.frames['myIFrame'].document.getElementById('myIFrameElemId')

If your iframe is not in the same domain the browser should prevent such access for security reasons.

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

My fix was suprisingly simple and another one of those obvious when you realise what you've done. I was manually building the configuration using .NET Core/Standard in the following fashion:

var configurationBuilder = new ConfigurationBuilder();
var root = configurationBuilder.Build(); 

and had forgotten to include the appsettings.json file that had my configuration settings in it

configurationBuilder.AddJsonFile("appsettings.json", false);

Once added, all started working once more.

Boolean operators ( &&, -a, ||, -o ) in Bash

Rule of thumb: Use -a and -o inside square brackets, && and || outside.

It's important to understand the difference between shell syntax and the syntax of the [ command.

  • && and || are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.

  • [ is not special syntax. It's actually a command with the name [, also known as test. Since [ is just a regular command, it uses -a and -o for its and and or operators. It can't use && and || because those are shell syntax that commands don't get to see.

But wait! Bash has a fancier test syntax in the form of [[ ]]. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&, ||, <, and > freely inside the brackets because, unlike [, the double bracketed form is special shell syntax. Bash parses [[ itself so you can write things like [[ $foo == 5 && $bar == 6 ]].

What is the best way to merge mp3 files?

As Thomas Owens pointed out, simply concatenating the files will leave multiple ID3 headers scattered throughout the resulting concatenated file - so the time/bitrate info will be wildly wrong.

You're going to need to use a tool which can combine the audio data for you.

mp3wrap would be ideal for this - it's designed to join together MP3 files, without needing to decode + re-encode the data (which would result in a loss of audio quality) and will also deal with the ID3 tags intelligently.

The resulting file can also be split back into its component parts using the mp3splt tool - mp3wrap adds information to the IDv3 comment to allow this.

HTML: how to make 2 tables with different CSS

Of course, just assign seperate css classes to both tables.

<table class="style1"></table>
<table class="style2"></table>

.css

table.style1 { //your css here}
table.style2 { //your css here}

string to string array conversion in java

String data = "abc";
String[] arr = explode(data);

public String[] explode(String s) {
    String[] arr = new String[s.length];
    for(int i = 0; i < s.length; i++)
    {
        arr[i] = String.valueOf(s.charAt(i));
    }
    return arr;
}

How to len(generator())

The conversion to list that's been suggested in the other answers is the best way if you still want to process the generator elements afterwards, but has one flaw: It uses O(n) memory. You can count the elements in a generator without using that much memory with:

sum(1 for x in generator)

Of course, be aware that this might be slower than len(list(generator)) in common Python implementations, and if the generators are long enough for the memory complexity to matter, the operation would take quite some time. Still, I personally prefer this solution as it describes what I want to get, and it doesn't give me anything extra that's not required (such as a list of all the elements).

Also listen to delnan's advice: If you're discarding the output of the generator it is very likely that there is a way to calculate the number of elements without running it, or by counting them in another manner.

Passing data to components in vue.js

The best way to send data from a parent component to a child is using props.

Passing data from parent to child via props

  • Declare props (array or object) in the child
  • Pass it to the child via <child :name="variableOnParent">

See demo below:

_x000D_
_x000D_
Vue.component('child-comp', {
  props: ['message'], // declare the props
  template: '<p>At child-comp, using props in the template: {{ message }}</p>',
  mounted: function () {
    console.log('The props are also available in JS:', this.message);
  }
})

new Vue({
  el: '#app',
  data: {
    variableAtParent: 'DATA FROM PARENT!'
  }
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<div id="app">
  <p>At Parent: {{ variableAtParent }}<br>And is reactive (edit it) <input v-model="variableAtParent"></p>
  <child-comp :message="variableAtParent"></child-comp>
</div>
_x000D_
_x000D_
_x000D_

Brackets.io: Is there a way to auto indent / format <html>

You can install an indentator package.

Click on File > Extension Manager....

Look for the search field and type: Indentator > Install

Once Indentator is installed, you can use Ctrl + Alt + I

x86 Assembly on a Mac

After installing any version of Xcode targeting Intel-based Macs, you should be able to write assembly code. Xcode is a suite of tools, only one of which is the IDE, so you don't have to use it if you don't want to. (That said, if there are specific things you find clunky, please file a bug at Apple's bug reporter - every bug goes to engineering.) Furthermore, installing Xcode will install both the Netwide Assembler (NASM) and the GNU Assembler (GAS); that will let you use whatever assembly syntax you're most comfortable with.

You'll also want to take a look at the Compiler & Debugging Guides, because those document the calling conventions used for the various architectures that Mac OS X runs on, as well as how the binary format and the loader work. The IA-32 (x86-32) calling conventions in particular may be slightly different from what you're used to.

Another thing to keep in mind is that the system call interface on Mac OS X is different from what you might be used to on DOS/Windows, Linux, or the other BSD flavors. System calls aren't considered a stable API on Mac OS X; instead, you always go through libSystem. That will ensure you're writing code that's portable from one release of the OS to the next.

Finally, keep in mind that Mac OS X runs across a pretty wide array of hardware - everything from the 32-bit Core Single through the high-end quad-core Xeon. By coding in assembly you might not be optimizing as much as you think; what's optimal on one machine may be pessimal on another. Apple regularly measures its compilers and tunes their output with the "-Os" optimization flag to be decent across its line, and there are extensive vector/matrix-processing libraries that you can use to get high performance with hand-tuned CPU-specific implementations.

Going to assembly for fun is great. Going to assembly for speed is not for the faint of heart these days.

Change keystore password from no password to a non blank password

this way worked better for me:

echo y | keytool -storepasswd -storepass 123456 -keystore /tmp/IT-Root-CA.keystore -import -alias IT-Root-CA -file /etc/pki/ca-trust/source/anchors/IT-Root-CA.crt

machine running:

[root@rhel80-68]# cat /etc/redhat-release 
Red Hat Enterprise Linux release 8.1 (Ootpa)

Can I change the Android startActivity() transition animation?

I wanted to use the styles.xml solution, but it did not work for me with activities. Turns out that instead of using android:windowEnterAnimation and android:windowExitAnimation, I need to use the activity animations like this:

<style name="ActivityAnimation.Vertical" parent="">
    <item name="android:activityOpenEnterAnimation">@anim/enter_from_bottom</item>
    <item name="android:activityOpenExitAnimation">@anim/exit_to_bottom</item>
    <item name="android:activityCloseEnterAnimation">@anim/enter_from_bottom</item>
    <item name="android:activityCloseExitAnimation">@anim/exit_to_bottom</item>
    <item name="android:windowEnterAnimation">@anim/enter_from_bottom</item>
    <item name="android:windowExitAnimation">@anim/exit_to_bottom</item>
</style>

Also, for some reason this only worked from Android 8 and above. I added the following code to my BaseActivity, to fix it for the API levels below:

override fun finish() {
    super.finish()
    setAnimationsFix()
}

/**
 * The activityCloseExitAnimation and activityCloseEnterAnimation properties do not work correctly when applied from the theme.
 * So in this fix, we retrieve them from the theme, and apply them.
 * @suppress Incorrect warning: https://stackoverflow.com/a/36263900/1395437
 */
@SuppressLint("ResourceType")
private fun setAnimationsFix() {
    // Retrieve the animations set in the theme applied to this activity in the manifest..
    var activityStyle = theme.obtainStyledAttributes(intArrayOf(attr.windowAnimationStyle))
    val windowAnimationStyleResId = activityStyle.getResourceId(0, 0)
    activityStyle.recycle()
    // Now retrieve the resource ids of the actual animations used in the animation style pointed to by
    // the window animation resource id.
    activityStyle = theme.obtainStyledAttributes(windowAnimationStyleResId, intArrayOf(activityCloseEnterAnimation, activityCloseExitAnimation))
    val activityCloseEnterAnimation = activityStyle.getResourceId(0, 0)
    val activityCloseExitAnimation = activityStyle.getResourceId(1, 0)
    activityStyle.recycle()
    overridePendingTransition(activityCloseEnterAnimation, activityCloseExitAnimation);
}

How to get span tag inside a div in jQuery and assign a text?

function Errormessage(txt) {
    $("#message").fadeIn("slow");
    $("#message span:first").text(txt);
    // find the span inside the div and assign a text
    $("#message a.close-notify").click(function() {
        $("#message").fadeOut("slow");
    });
}

How can I set the value of a DropDownList using jQuery?

There are many ways to do it. here are some of them:

$("._statusDDL").val('2');

OR

$('select').prop('selectedIndex', 3);

How can I directly view blobs in MySQL Workbench

Doesn't seem to be possible I'm afraid, its listed as a bug in workbench: http://bugs.mysql.com/bug.php?id=50692 It would be very useful though!

Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

This can be done just using Copy-Item. No need to use Get-Childitem. I think you are just overthinking it.

Copy-Item -Path C:\MyFolder -Destination \\Server\MyFolder -recurse -Force

I just tested it and it worked for me.

edit: included suggestion from the comments

# Add wildcard to source folder to ensure consistent behavior
Copy-Item -Path $sourceFolder\* -Destination $targetFolder -Recurse

Mysql - delete from multiple tables with one query

A join statement is unnecessarily complicated in this situation. The original question only deals with deleting records for a given user from multiple tables at the same time. Intuitively, you might expect something like this to work:

DELETE FROM table1,table2,table3,table4 WHERE user_id='$user_id'

Of course, it doesn't. But rather than writing multiple statements (redundant and inefficient), using joins (difficult for novices), or foreign keys (even more difficult for novices and not available in all engines or existing datasets) you could simplify your code with a LOOP!

As a basic example using PHP (where $db is your connection handle):

$tables = array("table1","table2","table3","table4");
foreach($tables as $table) {
  $query = "DELETE FROM $table WHERE user_id='$user_id'";
  mysqli_query($db,$query);
}

Hope this helps someone!

Find an element in DOM based on an attribute value

Use query selectors, examples:

document.querySelectorAll(' input[name], [id|=view], [class~=button] ')

input[name] Inputs elements with name property.

[id|=view] Elements with id that start with view-.

[class~=button] Elements with the button class.

NSString with \n or line break

I just ran into the same issue when overloading -description for a subclass of NSObject. In this situation I was able to use carriage return (\r) instead of newline (\n) to create a line break.

[NSString stringWithFormat:@"%@\r%@", mystring1,mystring2];

How can I start an Activity from a non-Activity class?

Your onTap override receives the MapView from which you can obtain the Context:

@Override
public boolean onTap(GeoPoint p, MapView mapView)
{
    // ...

    Intent intent = new Intent();
    intent.setClass(mapView.getContext(), FullscreenView.class);
    startActivity(intent);

    // ...
}

HintPath vs ReferencePath in Visual Studio

Although this is an old document, but it helped me resolve the problem of 'HintPath' being ignored on another machine. It was because the referenced DLL needed to be in source control as well:

https://msdn.microsoft.com/en-us/library/ee817675.aspx#tdlg_ch4_includeoutersystemassemblieswithprojects

Excerpt:

To include and then reference an outer-system assembly
1. In Solution Explorer, right-click the project that needs to reference the assembly,,and then click Add Existing Item.
2. Browse to the assembly, and then click OK. The assembly is then copied into the project folder and automatically added to VSS (assuming the project is already under source control).
3. Use the Browse button in the Add Reference dialog box to set a file reference to assembly in the project folder.

How much should a function trust another function

My 2 cents.

This is a loaded question imho. A rule of thumb I use to is see how this function will be called. If the caller is something I have control over then , its ok to assume that it will be called with the right parameters and with proper initialization.

On the other hand if its some client I don't control then it is a good idea to do thorough error checking.

How to check if a function exists on a SQL database

Why not just:

IF object_id('YourFunctionName', 'FN') IS NOT NULL
BEGIN
    DROP FUNCTION [dbo].[YourFunctionName]
END
GO

The second argument of object_id is optional, but can help to identify the correct object. There are numerous possible values for this type argument, particularly:

  • FN : Scalar function
  • IF : Inline table-valued function
  • TF : Table-valued-function
  • FS : Assembly (CLR) scalar-function
  • FT : Assembly (CLR) table-valued function

Algorithm for solving Sudoku

Not gonna write full code, but I did a sudoku solver a long time ago. I found that it didn't always solve it (the thing people do when they have a newspaper is incomplete!), but now think I know how to do it.

  • Setup: for each square, have a set of flags for each number showing the allowed numbers.
  • Crossing out: just like when people on the train are solving it on paper, you can iteratively cross out known numbers. Any square left with just one number will trigger another crossing out. This will either result in solving the whole puzzle, or it will run out of triggers. This is where I stalled last time.
  • Permutations: there's only 9! = 362880 ways to arrange 9 numbers, easily precomputed on a modern system. All of the rows, columns, and 3x3 squares must be one of these permutations. Once you have a bunch of numbers in there, you can do what you did with the crossing out. For each row/column/3x3, you can cross out 1/9 of the 9! permutations if you have one number, 1/(8*9) if you have 2, and so forth.
  • Cross permutations: Now you have a bunch of rows and columns with sets of potential permutations. But there's another constraint: once you set a row, the columns and 3x3s are vastly reduced in what they might be. You can do a tree search from here to find a solution.

Linux : Search for a Particular word in a List of files under a directory

You can use this command:

grep -rn "string" *

n for showing line number with the filename r for recursive

How to read/process command line arguments?

The docopt library is really slick. It builds an argument dict from the usage string for your app.

Eg from the docopt readme:

"""Naval Fate.

Usage:
  naval_fate.py ship new <name>...
  naval_fate.py ship <name> move <x> <y> [--speed=<kn>]
  naval_fate.py ship shoot <x> <y>
  naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]
  naval_fate.py (-h | --help)
  naval_fate.py --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.

"""
from docopt import docopt


if __name__ == '__main__':
    arguments = docopt(__doc__, version='Naval Fate 2.0')
    print(arguments)

400 vs 422 response to POST of data

Your case: HTTP 400 is the right status code for your case from REST perspective as its syntactically incorrect to send sales_tax instead of tax, though its a valid JSON. This is normally enforced by most of the server side frameworks when mapping the JSON to objects. However, there are some REST implementations that ignore new key in JSON object. In that case, a custom content-type specification to accept only valid fields can be enforced by server-side.

Ideal Scenario for 422:

In an ideal world, 422 is preferred and generally acceptable to send as response if the server understands the content type of the request entity and the syntax of the request entity is correct but was unable to process the data because its semantically erroneous.

Situations of 400 over 422:

Remember, the response code 422 is an extended HTTP (WebDAV) status code. There are still some HTTP clients / front-end libraries that aren't prepared to handle 422. For them, its as simple as "HTTP 422 is wrong, because it's not HTTP". From the service perspective, 400 isn't quite specific.

In enterprise architecture, the services are deployed mostly on service layers like SOA, IDM, etc. They typically serve multiple clients ranging from a very old native client to a latest HTTP clients. If one of the clients doesn't handle HTTP 422, the options are that asking the client to upgrade or change your response code to HTTP 400 for everyone. In my experience, this is very rare these days but still a possibility. So, a careful study of your architecture is always required before deciding on the HTTP response codes.

To handle situation like these, the service layers normally use versioning or setup configuration flag for strict HTTP conformance clients to send 400, and send 422 for the rest of them. That way they provide backwards compatibility support for existing consumers but at the same time provide the ability for the new clients to consume HTTP 422.


The latest update to RFC7321 says:

The 400 (Bad Request) status code indicates that the server cannot or
   will not process the request due to something that is perceived to be
   a client error (e.g., malformed request syntax, invalid request
   message framing, or deceptive request routing).

This confirms that servers can send HTTP 400 for invalid request. 400 doesn't refer only to syntax error anymore, however, 422 is still a genuine response provided the clients can handle it.

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Use subquery

SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]

No @XmlRootElement generated by JAXB

JAXBElement wrappers works for cases where no @XmlRootElement is generated by JAXB. These wrappers are available in ObjectFactory class generated by maven-jaxb2-plugin. For eg:

     public class HelloWorldEndpoint {
        @PayloadRoot(namespace = NAMESPACE_URI, localPart = "person")
        @ResponsePayload
        public JAXBElement<Greeting> sayHello(@RequestPayload JAXBElement<Person> request) {

        Person person = request.getValue();

        String greeting = "Hello " + person.getFirstName() + " " + person.getLastName() + "!";

        Greeting greet = new Greeting();
        greet.setGreeting(greeting);

        ObjectFactory factory = new ObjectFactory();
        JAXBElement<Greeting> response = factory.createGreeting(greet);
        return response;
      }
 }

How to get streaming url from online streaming radio station

not that hard,

if you take a look at the page source, you'll see that it uses to stream the audio via shoutcast.

this is the stream url

"StreamUrl": "http://stream.radiotime.com/listen.stream?streamIds=3244651&rti=c051HQVbfRc4FEMbKg5RRVMzRU9KUBw%2fVBZHS0dPF1VIExNzJz0CGQtRcX8OS0o0CUkYRFJDDW8LEVRxGAEOEAcQXko%2bGgwSBBZrV1pQZgQZZxkWCA4L%7e%7e%7e",

which returns a JSON like that:

{
    "Streams": [
        {
            "StreamId": 3244651,
            "Reliability": 92,
            "Bandwidth": 64,
            "HasPlaylist": false,
            "MediaType": "MP3",
            "Url": "http://mp3hdfm32.hala.jo:8132",
            "Type": "Live"
        }
    ]
}

i believe that's the url you need: http://mp3hdfm32.hala.jo:8132

this is the station WebSite

Logging POST data from $request_body

Ok. So finally I was able to log the post data and return a 200. It's kind of a hacky solution that I'm not too proud of which basically overrides the natural behavior for error_page, but my inexperience of nginx plus timelines lead me to this solution:

location /bk {
  if ($request_method != POST) {
    return 405;
  }
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_redirect off;
  proxy_pass $scheme://127.0.0.1:$server_port/success;
  log_format my_tracking $request_body;
  access_log  /mnt/logs/nginx/my_tracking.access.log my_tracking;
}
location /success {
  return 200;
}
error_page   500 502 503 504  /50x.html;
location = /50x.html {
  root   /var/www/nginx-default;
  log_format my_tracking $request_body;
  access_log  /mnt/logs/nginx/my_tracking.access.log my_tracking_2;
}

Now according to that config, it would seem that the proxy pass would return a 200 all the time. Occasionally I would get 500 but when I threw in an error_log to see what was going on, all of my request_body data was in there and I couldn't see a problem. So I caught that and wrote to the same log. Since nginx doesn't like the same name for the tracking variable, I just used my_tracking_2 and wrote to the same log as when it returns a 200. Definitely not the most elegant solution and I welcome any better solution. I've seen the post module, but in my scenario, I couldn't recompile from source.

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

How to Use TempTable in Stored Procedure?

Here are the steps:

CREATE TEMP TABLE

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

INSERT TEMP SELECT DATA INTO TEMP TABLE

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

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

Select EmployeeID from #MyTempTable

FINAL STEP DROP THE TABLE

Drop Table #MyTempTable

I hope this will help. Simple and Clear :)

How do you add CSS with Javascript?

Here's a slightly updated version of Chris Herring's solution, taking into account that you can use innerHTML as well instead of a creating a new text node:

function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';

    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }

    document.getElementsByTagName("head")[0].appendChild( style );
}

set up device for development (???????????? no permissions)

For those using debian, the guide for setting up a device under Ubuntu to create the file "/etc/udev/rules.d/51-android.rules" does not work. I followed instructions from here. Putting down the same here for reference.

Edit this file as superuser

sudo nano /lib/udev/rules.d/91-permissions.rules

Find the text similar to this

# usbfs-like devices 
SUBSYSTEM==”usb”, ENV{DEVTYPE}==”usb_device”, \ MODE=”0664"

Then change the mode to 0666 like below

# usbfs-like devices 
SUBSYSTEM==”usb”, ENV{DEVTYPE}==”usb_device”, \ MODE=”0666"

This allows adb to work, however we still need to set up the device so it can be recognized. We need to create this file as superuser,

sudo nano /lib/udev/rules.d/99-android.rules

and enter

SUBSYSTEM==”usb”, ENV{DEVTYPE}==”usb_device”, ATTRS{idVendor}==”0bb4", MODE=”0666"

the above line is for HTC, follow @grebulon's post for complete list.

Save the file and then restart udev as super user

sudo /etc/init.d/udev restart

Connect the phone via USB and it should be detected when you compile and run a project.

add an onclick event to a div

Assign the onclick like this:

divTag.onclick = printWorking;

The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>, but this is generally not recommended.

Good Linux (Ubuntu) SVN client

As a developer, I use eclipse + sub-eclipse client (Assuming that you are using svn to checkout some development project and you will compile them).

most people don't spend much time with svn operation, and command line is the fastest way to do so.

there is also some nice GUI tools :

http://rabbitvcs.org/

or

http://www.harecoded.com/nautilus-subversion-integration-tool-execute-svn-commands-with-gnome-scripts-96355

Compare two objects in Java with possible null values

Since version 3.5 Apache Commons StringUtils has the following methods:

static int  compare(String str1, String str2)
static int  compare(String str1, String str2, boolean nullIsLess)
static int  compareIgnoreCase(String str1, String str2)
static int  compareIgnoreCase(String str1, String str2, boolean nullIsLess)

These provide null safe String comparison.

Difference between return and exit in Bash functions

return will cause the current function to go out of scope, while exit will cause the script to end at the point where it is called. Here is a sample program to help explain this:

#!/bin/bash

retfunc()
{
    echo "this is retfunc()"
    return 1
}

exitfunc()
{
    echo "this is exitfunc()"
    exit 1
}

retfunc
echo "We are still here"
exitfunc
echo "We will never see this"

Output

$ ./test.sh
this is retfunc()
We are still here
this is exitfunc()

How to change current working directory using a batch file

A simpler syntax might be

pushd %root%

Compiling problems: cannot find crt1.o

I solved it as follows:

1) try to locate ctr1.o and ctri.o files by using find -name ctr1.o

I got the following in my computer: $/usr/lib/i386-linux/gnu

2) Add that path to PATH (also LIBRARY_PATH) environment variable (in order to see which is the name: type env command in the Terminal):

$PATH=/usr/lib/i386-linux/gnu:$PATH
$export PATH

HTTP Error 500.19 and error code : 0x80070021

Your web.config describes that you're using forms authentication - make sure you enable forms authentication and disable anonymous authentication in IIS under the Authentication menu, for the website that is running in IIS.

Simple JavaScript login form validation

You can do two things here either move the onSubmit attribute to the form tag, or change the onSubmit event to an onCLick event.

Option 1

<form name="loginform" onSubmit="return validateForm();">

Option 2

<input type="submit" value="Login" onClick="return validateForm();" />

Adding placeholder text to textbox

I came up with a method that worked for me, but only because I was willing to use the textbox name as my placeholder. See below.

public TextBox employee = new TextBox();

private void InitializeHomeComponent()
{
    //
    //employee
    //
    this.employee.Name = "Caller Name";
    this.employee.Text = "Caller Name";
    this.employee.BackColor = System.Drawing.SystemColors.InactiveBorder;
    this.employee.Location = new System.Drawing.Point(5, 160);
    this.employee.Size = new System.Drawing.Size(190, 30);
    this.employee.TabStop = false;
    this.Controls.Add(employee);
    // I loop through all of my textboxes giving them the same function
    foreach (Control C in this.Controls)
    {
        if (C.GetType() == typeof(System.Windows.Forms.TextBox))
        {
            C.GotFocus += g_GotFocus;
            C.LostFocus += g_LostFocus;
        }
     }
 }

    private void g_GotFocus(object sender, EventArgs e)
    {
        var tbox = sender as TextBox;
        tbox.Text = "";
    }

    private void g_LostFocus(object sender, EventArgs e)
    {
        var tbox = sender as TextBox;
        if (tbox.Text == "")
        {
            tbox.Text = tbox.Name;
        }
    }

Change the borderColor of the TextBox

Isn't it Simple as this,

txtbox1.BorderColor = System.Drawing.Color.Red;

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

Programmatically add new column to DataGridView

Add new column to DataTable and use column Expression property to set your Status expression.

Here you can find good example: DataColumn.Expression Property

DataTable and DataColumn Expressions in ADO.NET - Calculated Columns

UPDATE

Code sample:

DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));

dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));

demoGridView.DataSource = dt;

UPDATE #2

dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

convert array into DataFrame in Python

You can add parameter columns or use dict with key which is converted to column name:

np.random.seed(123)
e = np.random.normal(size=10)  
dataframe=pd.DataFrame(e, columns=['a']) 
print (dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

e_dataframe=pd.DataFrame({'a':e}) 
print (e_dataframe)
          a
0 -1.085631
1  0.997345
2  0.282978
3 -1.506295
4 -0.578600
5  1.651437
6 -2.426679
7 -0.428913
8  1.265936
9 -0.866740

Remove the complete styling of an HTML button/submit

I'm assuming that when you say 'click the button, it moves to the top a little' you're talking about the mouse down click state for the button, and that when you release the mouse click, it returns to its normal state? And that you're disabling the default rendering of the button by using:

input, button, submit { border:none; } 

If so..

Personally, I've found that you can't actually stop/override/disable this IE native action, which led me to change my markup a little to allow for this movement and not affect the overall look of the button for the various states.

This is my final mark-up:

_x000D_
_x000D_
<span class="your-button-class">_x000D_
    <span>_x000D_
        <input type="Submit" value="View Person">_x000D_
    </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How To Execute SSH Commands Via PHP

Do you have the SSH2 extension available?

Docs: http://www.php.net/manual/en/function.ssh2-exec.php

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/usr/local/bin/php -i');

Get page title with Selenium WebDriver using Java

If you're using Selenium 2.0 / Webdriver you can call driver.getTitle() or driver.getPageSource() if you want to search through the actual page source.

CSS way to horizontally align table

Steven is right, in theory:

the “correct” way to center a table using CSS. Conforming browsers ought to center tables if the left and right margins are equal. The simplest way to accomplish this is to set the left and right margins to “auto.” Thus, one might write in a style sheet:

table
{ 
    margin-left: auto;
    margin-right: auto;
}

But the article mentioned in the beginning of this answer gives you all the other way to center a table.

An elegant css cross-browser solution: This works in both MSIE 6 (Quirks and Standards), Mozilla, Opera and even Netscape 4.x without setting any explicit widths:

div.centered 
{
    text-align: center;
}

div.centered table 
{
    margin: 0 auto; 
    text-align: left;
}


<div class="centered">
    <table>
    …
    </table>
</div>

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

How to add Active Directory user group as login in SQL Server

In SQL Server Management Studio, go to Object Explorer > (your server) > Security > Logins and right-click New Login:

enter image description here

Then in the dialog box that pops up, pick the types of objects you want to see (Groups is disabled by default - check it!) and pick the location where you want to look for your objects (e.g. use Entire Directory) and then find your AD group.

enter image description here

You now have a regular SQL Server Login - just like when you create one for a single AD user. Give that new login the permissions on the databases it needs, and off you go!

Any member of that AD group can now login to SQL Server and use your database.

Determine if a String is an Integer in Java

You can use Integer.parseInt(str) and catch the NumberFormatException if the string is not a valid integer, in the following fashion (as pointed out by all answers):

static boolean isInt(String s)
{
 try
  { int i = Integer.parseInt(s); return true; }

 catch(NumberFormatException er)
  { return false; }
}

However, note here that if the evaluated integer overflows, the same exception will be thrown. Your purpose was to find out whether or not, it was a valid integer. So its safer to make your own method to check for validity:

static boolean isInt(String s)  // assuming integer is in decimal number system
{
 for(int a=0;a<s.length();a++)
 {
    if(a==0 && s.charAt(a) == '-') continue;
    if( !Character.isDigit(s.charAt(a)) ) return false;
 }
 return true;
}

How to use jquery $.post() method to submit form values

Yor $.post has no data. You need to pass the form data. You can use serialize() to post the form data. Try this

$("#post-btn").click(function(){
    $.post("process.php", $('#reg-form').serialize() ,function(data){
        alert(data);
    });
});

Reload nginx configuration

If your system has systemctl

sudo systemctl reload nginx

If your system supports service (using debian/ubuntu) try this

sudo service nginx reload

If not (using centos/fedora/etc) you can try the init script

sudo /etc/init.d/nginx reload

Is there a way to break a list into columns?

If you want a preset number of columns, you can use column-count and column-gap, as mentioned above.

However, if you want a single column with limited height that would break into more columns if needed, this can be achieved quite simply by changing display to flex.

This will not work on IE9 and some other old browsers. You can check support on Can I use

_x000D_
_x000D_
<style>_x000D_
  ul {_x000D_
    display: -ms-flexbox;           /* IE 10 */_x000D_
    display: -webkit-flex;          /* Safari 6.1+. iOS 7.1+ */_x000D_
    display: flex;_x000D_
    -webkit-flex-flow: wrap column; /* Safari 6.1+ */_x000D_
    flex-flow: wrap column;_x000D_
    max-height: 150px;              /* Limit height to whatever you need */_x000D_
  }_x000D_
</style>_x000D_
_x000D_
<ul>_x000D_
    <li>Item</li>_x000D_
    <li>Item</li>_x000D_
    <li>Item</li>_x000D_
    <li>Item</li>_x000D_
    <li>Item</li>_x000D_
    <li>Item</li>_x000D_
    <li>Item</li>_x000D_
    <li>Item</li>_x000D_
    <li>Item</li>_x000D_
    <li>Item</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

In my case, I am Returning JSON Object as

{"data":"","message":"Attendance Saved Successfully..!!!","status":"success"}

Resolved by changing it as

{"data":{},"message":"Attendance Saved Successfully..!!!","status":"success"}

Here data is a sub JsonObject and it should starts from { not ""

How do I import modules or install extensions in PostgreSQL 9.1+?

For the postgrersql10

I have solved it with

yum install postgresql10-contrib

Don't forget to activate extensions in postgresql.conf

shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.track = all

then of course restart

systemctl restart postgresql-10.service 

all of the needed extensions you can find here

/usr/pgsql-10/share/extension/

How to create standard Borderless buttons (like in the design guideline mentioned)?

For anybody who's still searching:

inherit your own style for Holo buttonbars:

<style name="yourStyle" parent="@android:style/Holo.ButtonBar">
  ...
</style>

or Holo Light:

<style name="yourStyle" parent="@android:style/Holo.Light.ButtonBar">
  ...
</style>

and for borderless Holo buttons:

<style name="yourStyle" parent="@android:style/Widget.Holo.Button.Borderless.Small">
  ...
</style>

or Holo Light:

<style name="yourStyle" parent="@android:style/Widget.Holo.Light.Button.Borderless.Small">
  ...
</style>

How to make a deep copy of Java ArrayList

Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

Assuming clone is correctly overriden inPerson.

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

A .pl is a single script.

In .pm (Perl Module) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.

How to add a touch event to a UIView?

Objective-C:

UIControl *headerView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, nextY)];
[headerView addTarget:self action:@selector(myEvent:) forControlEvents:UIControlEventTouchDown];

Swift:

let headerView = UIControl(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: nextY))
headerView.addTarget(self, action: #selector(myEvent(_:)), for: .touchDown)

The question asks:

How do I add a touch event to a UIView?

It isn't asking for a tap event.

Specifically OP wants to implement UIControlEventTouchDown

Switching the UIView to UIControl is the right answer here because Gesture Recognisers don't know anything about .touchDown, .touchUpInside, .touchUpOutside etc.

Additionally, UIControl inherits from UIView so you're not losing any functionality.

If all you want is a tap, then you can use the Gesture Recogniser. But if you want finer control, like this question asks for, you'll need UIControl.

https://developer.apple.com/documentation/uikit/uicontrol?language=objc https://developer.apple.com/documentation/uikit/uigesturerecognizer?language=objc

Copying one structure to another

Since C90, you can simply use:

dest_struct = source_struct;

as long as the string is memorized inside an array:

struct xxx {
    char theString[100];
};

Otherwise, if it's a pointer, you'll need to copy it by hand.

struct xxx {
    char* theString;
};

dest_struct = source_struct;
dest_struct.theString = malloc(strlen(source_struct.theString) + 1);
strcpy(dest_struct.theString, source_struct.theString);

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

This thing worked for me pretty well:

<div id="{{ 'object-' + $index }}"></div>

Append text with .bat

I am not proficient at batch scripting but I can tell you that REM stands for Remark. The append won't occur as it is essentially commented out.

http://technet.microsoft.com/en-us/library/bb490986.aspx

Also, the append operator redirects the output of a command to a file. In the snippet you posted it is not clear what output should be redirected.

Moving uncommitted changes to a new branch

Just move to the new branch. The uncommited changes get carried over.

git checkout -b ABC_1

git commit -m <message>

How to delete all records from table in sqlite with Android?

There's no need to use "execute" function.The following code worked for me:::

    db.delete(TABLE_NAME,null,null);
    db.close();

Java Scanner String input

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you to use scan.next() instead of scan.nextLine().

Position buttons next to each other in the center of page

your code will look something like this ...

<!doctype html>
<html lang="en">

<head>
<style>
#button1{
width: 300px;
height: 40px;

}
#button2{
width: 300px;
height: 40px;
}
display:inline-block;
</style>

<meta charset="utf-8">
<meta name="Homepage" content="Starting page for the survey website ">

 <title> Survey HomePage</title>
</head>
<body>
<center>
<img src="kingstonunilogo.jpg" alt="uni logo" style="width:180px;height:160px">
 <button type="button home-button" id="button1" >Home</button>
 <button type="button contact-button" id="button2">Contact Us</button>
</center>
</body>
 </html>

How to draw a line with matplotlib?

As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2)).

Can I embed a custom font in an iPhone application?

For iOS 3.2 and above: Use the methods provided by several above, which are:

  1. Add your font file (for example, Chalkduster.ttf) to Resources folder of the project in XCode.
  2. Open info.plist and add a new key called UIAppFonts. The type of this key should be array.
  3. Add your custom font name to this array including extension ("Chalkduster.ttf").
  4. Use [UIFont fontWithName:@"Real Font Name" size:16] in your application.

BUT The "Real Font Name" is not always the one you see in Fontbook. The best way is to ask your device which fonts it sees and what the exact names are.

I use the uifont-name-grabber posted at: uifont-name-grabber

Just drop the fonts you want into the xcode project, add the file name to its plist, and run it on the device you are building for, it will email you a complete font list using the names that UIFont fontWithName: expects.

Change default icon

If you are using Forms you can use the icon setting in the properties pane. To do this select the form and scroll down in the properties pane till you see the icon setting. When you open the application it will have the icon wherever you have it in your application and in the task bar

Icon settings

Angularjs - display current date

A solution similar to the one of @Nick G. by using filter, but make the parameter meaningful:

Implement an filter called relativedate which calculate the date relative to current date by the given parameter as diff. As a result, (0 | relativedate) means today and (1 | relativedate) means tomorrow.

.filter('relativedate', ['$filter', function ($filter) {
  return function (rel, format) {
    let date = new Date();
    date.setDate(date.getDate() + rel);
    return $filter('date')(date, format || 'yyyy-MM-dd')
  };
}]);

and your html:

<div ng-app="myApp">
    <div>Yesterday: {{-1 | relativedate}}</div>
    <div>Today: {{0 | relativedate}}</div>
    <div>Tomorrow: {{1 | relativedate}}</div>
</div>

Excel formula to get cell color

Color is not data.

The Get.cell technique has flaws.

  1. It does not update as soon as the cell color changes, but only when the cell (or the sheet) is recalculated.
  2. It does not have sufficient numbers for the millions of colors that are available in modern Excel. See the screenshot and notice how the different intensities of yellow or purple all have the same number.

enter image description here

That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.

Again: Color is not data.

If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.

force line break in html table cell

Try using

<table  border="1" cellspacing="0" cellpadding="0" class="template-table" 
style="table-layout: fixed; width: 100%"> 

as table style along with

<td style="word-break:break-word">long text</td>

for td it works for normal/real scenario text with words, not for random typed letters without gaps

TypeError: Converting circular structure to JSON in nodejs

Try using this npm package. This helped me decoding the res structure from my node while using passport-azure-ad for integrating login using Microsoft account

https://www.npmjs.com/package/circular-json

You can stringify your circular structure by doing:

const str = CircularJSON.stringify(obj);

then you can convert it onto JSON using JSON parser

JSON.parse(str)

What are the safe characters for making URLs?

I found it very useful to encode my URL to a safe one when I was returning a value through Ajax/PHP to a URL which was then read by the page again.

PHP output with URL encoder for the special character &:

// PHP returning the success information of an Ajax request
echo "".str_replace('&', '%26', $_POST['name']) . " category was changed";

// JavaScript sending the value to the URL
window.location.href = 'time.php?return=updated&val=' + msg;

// JavaScript/PHP executing the function printing the value of the URL,
// now with the text normally lost in space because of the reserved & character.

setTimeout("infoApp('updated','<?php echo $_GET['val'];?>');", 360);

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

error: package com.android.annotations does not exist

if error from butterknife auto generated file then update butterknife dependency version

implementation 'com.jakewharton:butterknife:10.0.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.0.0'

Mockito match any class argument

There is another way to do that without cast:

when(a.method(Matchers.<Class<A>>any())).thenReturn(b);

This solution forces the method any() to return Class<A> type and not its default value (Object).

Why do I have to run "composer dump-autoload" command to make migrations work in laravel?

You should run:

composer dump-autoload

and if does not work you should:

re-install composer

How to use curl in a shell script?

#!/bin/bash                                                                                                                                                                                     
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"

# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"

# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer

or:

Execute bash script from URL

Unit Testing: DateTime.Now

I'm surprised no one has suggested one of the most obvious ways to go:

public class TimeDependentClass
{
    public void TimeDependentMethod(DateTime someTime)
    {
        if (GetCurrentTime() > someTime) DoSomething();
    }

    protected virtual DateTime GetCurrentTime()
    {
        return DateTime.Now; // or UtcNow
    }
}

Then you can simply override this method in your test double.

I also kind of like injecting a TimeProvider class in some cases, but for others, this is more than enough. I'd probably favor the TimeProvider version if you need to reuse this in several classes though.

EDIT: For anyone interested, this is called adding a "seam" to your class, a point where you can hook in to it's behavior to modify it (for testing purposes or otherwise) without actually having to change the code in the class.

How to upload file to server with HTTP POST multipart/form-data?

I was also wanted to upload stuff to a Server and it was a Spring application i finally discovered that I needed to acctually set an content type for it to interpret it as a file. Just like this:

...
MultipartFormDataContent form = new MultipartFormDataContent();
var fileStream = new FileStream(uniqueTempPathInProject, FileMode.Open);
var streamContent = new StreamContent(fileStream);
streamContent.Headers.ContentType=new MediaTypeHeaderValue("application/zip");
form.Add(streamContent, "file",fileName);
...

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

This happens because your upstream takes too much to answer the request and NGINX thinks the upstream already failed in processing the request, so it responds with an error. Just include and increase proxy_read_timeout in location config block. Same thing happened to me and I used 1 hour timeout for an internal app at work:

proxy_read_timeout 3600;

With this, NGINX will wait for an hour (3600s) for its upstream to return something.

How can I have a newline in a string in sh?

This isn't ideal, but I had written a lot of code and defined strings in a way similar to the method used in the question. The accepted solution required me to refactor a lot of the code so instead, I replaced every \n with "$'\n'" and this worked for me.

Can Mysql Split a column?

It's working..

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(
SUBSTRING_INDEX(SUBSTRING_INDEX(SUBSTRING_INDEX(col,'1', 1), '2', 1), '3', 1), '4', 1), '5', 1), '6', 1)
, '7', 1), '8', 1), '9', 1), '0', 1) as new_col  
FROM table_name group by new_col; 

Set space between divs

For folks searching for solution to set spacing between N divs, here is another approach using pseudo selectors:

div:not(:last-child) {
  margin-right: 40px;
}

You can also combine child pseudo selectors:

div:not(:first-child):not(:last-child) {
  margin-left: 20px;
  margin-right: 20px;
}

TSQL: How to convert local time to UTC? (SQL Server 2008)

While a few of these answers will get you in the ballpark, you cannot do what you're trying to do with arbitrary dates for SqlServer 2005 and earlier because of daylight savings time. Using the difference between the current local and current UTC will give me the offset as it exists today. I have not found a way to determine what the offset would have been for the date in question.

That said, I know that SqlServer 2008 provides some new date functions that may address that issue, but folks using an earlier version need to be aware of the limitations.

Our approach is to persist UTC and perform the conversion on the client side where we have more control over the conversion's accuracy.

How to clear all input fields in bootstrap modal when clicking data-dismiss button?

The following worked for me:

$(':input').val('');

However, it is submitting the form, so it might not be what you are looking for.

C#: HttpClient with POST parameters

As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

The querystring (get) parameters included in your url probably will not do anything.

Try this:

string url = "http://myserver/method";    
string content = "param1=1&param2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);

HTH,

bovako

How to remove a file from the index in git?

According to my humble opinion and my work experience with git, staging area is not the same as index. I may be wrong of course, but as I said, my experience in using git and my logic tell me, that index is a structure that follows your changes to your working area(local repository) that are not excluded by ignoring settings and staging area is to keep files that are already confirmed to be committed, aka files in index on which add command was run on. You don't notice and realize that "slight" difference, because you use git commit -a -m "comment" adding indexed and cached files to stage area and committing in one command or using IDEs like IDEA for that too often. And cache is that what keeps changes in indexed files. If you want to remove file from index that has not been added to staging area before, options proposed before match for you, but... If you have done that already, you will need to use

Git restore --staged <file>

And, please, don't ask me where I was 10 years ago... I missed you, this answer is for further generations)

What is the difference between . (dot) and $ (dollar sign)?

The $ operator is for avoiding parentheses. Anything appearing after it will take precedence over anything that comes before.

For example, let's say you've got a line that reads:

putStrLn (show (1 + 1))

If you want to get rid of those parentheses, any of the following lines would also do the same thing:

putStrLn (show $ 1 + 1)
putStrLn $ show (1 + 1)
putStrLn $ show $ 1 + 1

The primary purpose of the . operator is not to avoid parentheses, but to chain functions. It lets you tie the output of whatever appears on the right to the input of whatever appears on the left. This usually also results in fewer parentheses, but works differently.

Going back to the same example:

putStrLn (show (1 + 1))
  1. (1 + 1) doesn't have an input, and therefore cannot be used with the . operator.
  2. show can take an Int and return a String.
  3. putStrLn can take a String and return an IO ().

You can chain show to putStrLn like this:

(putStrLn . show) (1 + 1)

If that's too many parentheses for your liking, get rid of them with the $ operator:

putStrLn . show $ 1 + 1

How to view changes made to files on a certain revision in Subversion

The equivalent command in svn is:

svn log --diff -r revision

How to do a GitHub pull request

I wrote a bash program that does all the work of setting up a PR branch for you. It performs forking if needed, syncing with the upstream, setting up upstream remote, etc. and you just need to commit your modifications, push and submit a PR.

Here is how you run it:

github-make-pr-branch ssh your-github-username orig_repo_user orig_repo_name new-feature

You will find the program here and its repository also includes a step-by-step guide to performing the same process manually if you'd like to understand how it works, and also extra information on how to keep your feature branch up-to-date with the upstream master and other useful tidbits.

How can I hide a checkbox in html?

Elements that are not being rendered (be it through visibility: hidden, display: none, opacity: 0.0, whatever) will not indicate focus. The browser will not draw a focus border around nothing.

If you want the text to be focusable, that's completely doable. You can wrap the whole thing in an element that can receive focus (for example, a hyperlink), or allow another tag to have focus using the tabindex property:

<label tabindex="0" class="checkbox">
  <input type="checkbox" value="valueofcheckbox" style="display:none" checked="checked" />Option Text
</label>

Fiddle

In this case, the <label> tag above is actually receiving focus and everything within it will have a focus border when it's in focus.

I do question what your goal is. If you're using a hidden checkbox to internally track some sort of state, you might be better off using a <input type="hidden" /> tag instead.

Notepad++ Multi editing

You can use Edit > Column Editor... to insert text at the current and following lines. The shortcut is Alt + C.

How do I assert my exception message with JUnit Test annotation?

Do you have to use @Test(expected=SomeException.class)? When we have to assert the actual message of the exception, this is what we do.

@Test
public void myTestMethod()
{
  try
  {
    final Integer employeeId = null;
    new Employee(employeeId);
    fail("Should have thrown SomeException but did not!");
  }
  catch( final SomeException e )
  {
    final String msg = "Employee ID is null";
    assertEquals(msg, e.getMessage());
  }
}

How to get UTC+0 date in Java 8?

1 line solution in Java 8:

public Date getCurrentUtcTime() {
    return Date.from(Instant.now());
}

What is the coolest thing you can do in <10 lines of simple code? Help me inspire beginners!

The Mandelbrot Set can be presented in a way that isn't terribly complex, for example in Java below:

public class MiniMandelbrot {
    public static void main(String[] args) {
        int[] rgbArray = new int[256 * 256];
        for (int y=0; y<256; y++) {
            for (int x=0; x<256; x++) {
                double cReal=x/64.0-2.0, cImaginary=y/64.0-2.0;
                double zReal=0.0, zImaginary=0.0, zRealSquared=0.0, zImaginarySquared=0.0;
                int i;
                for (i = 0; (i < 63) && (zRealSquared + zImaginarySquared < 4.0); i++) {
                    zImaginary = (zReal * zImaginary) + (zReal * zImaginary) + cImaginary;
                    zReal = zRealSquared - zImaginarySquared - cReal;
                    zImaginarySquared = zImaginary * zImaginary;
                    zRealSquared = zReal * zReal;
                }
                rgbArray[x+y*256] = i * 0x040404;
            }
        }
        java.awt.image.BufferedImage bufferedImage = new java.awt.image.BufferedImage(256, 256, 1);
        bufferedImage.setRGB(0, 0, 256, 256, rgbArray, 0, 256);
        javax.swing.JOptionPane.showMessageDialog(null, new javax.swing.ImageIcon(bufferedImage), "The Mandelbrot Set", -1);
    }
}

ModuleNotFoundError: No module named 'sklearn'

You can just use pip for installing packages, even when you are using anaconda:

pip install -U scikit-learn scipy matplotlib

This should work for installing the package.

And for Python 3.x just use pip3:

pip3 install -U scikit-learn scipy matplotlib

Check which element has been clicked with jQuery

The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:

http://api.jquery.com/category/selectors/

However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.

Meaning of Open hashing and Closed hashing

You have an array that is the "hash table".

In Open Hashing each cell in the array points to a list containg the collisions. The hashing has produced the same index for all items in the linked list.

In Closed Hashing you use only one array for everything. You store the collisions in the same array. The trick is to use some smart way to jump from collision to collision unitl you find what you want. And do this in a reproducible / deterministic way.

How to append text to an existing file in Java?

/**********************************************************************
 * it will write content to a specified  file
 * 
 * @param keyString
 * @throws IOException
 *********************************************************************/
public static void writeToFile(String keyString,String textFilePAth) throws IOException {
    // For output to file
    File a = new File(textFilePAth);

    if (!a.exists()) {
        a.createNewFile();
    }
    FileWriter fw = new FileWriter(a.getAbsoluteFile(), true);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(keyString);
    bw.newLine();
    bw.close();
}// end of writeToFile()

How can I initialize a String array with length 0 in Java?

Ok I actually found the answer but thought I would 'import' the question into SO anyway

String[] files = new String[0];
or
int[] files = new int[0];

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

Find the IP address of the client in an SSH session

 who | cut -d"(" -f2 |cut -d")" -f1

possibly undefined macro: AC_MSG_ERROR

On Mac OS X el captain with brew, try:
brew install pkgconfig

This worked for me.

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

For python2 you can also do this

'%(author)s in %(publication)s'%{'author':unicode(self.author),
                                  'publication':unicode(self.publication)}

which is handy if you have a lot of arguments to substitute (particularly if you are doing internationalisation)

Python2.6 onwards supports .format()

'{author} in {publication}'.format(author=self.author,
                                   publication=self.publication)

CSS Box Shadow - Top and Bottom Only

So this is my first answer here, and because I needed something similar I did with pseudo elements for 2 inner shadows, and an extra DIV for an upper outer shadow. Don't know if this is the best solutions but maybe it will help someone.

HTML

<div class="shadow-block">
    <div class="shadow"></div>
    <div class="overlay">
        <div class="overlay-inner">
            content here
        </div>
    </div>
</div>

CSS

.overlay {
    background: #f7f7f4;
    height: 185px;
    overflow: hidden;
    position: relative;
    width: 100%; 
}

.overlay:before {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 50px 2px rgba(1, 1, 1, 0.6);
    content: " ";
    display: block;
    margin: 0 auto;
    width: 80%;
}

.overlay:after {
    border-radius: 50% 50% 50% 50%;
    box-shadow: 0 0 70px 5px rgba(1, 1, 1, 0.5);
    content: "-";
    display: block;
    margin: 0 auto;
    position: absolute;
    bottom: -65px;
    left: -50%;
    right: -50%;
    width: 80%;
}

.shadow {
    position: relative;
    width:100%;
    height:8px;
    margin: 0 0 -22px 0;
    -webkit-box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    box-shadow: 0px 0px 50px 3px rgba(1, 1, 1, 0.6);
    border-radius: 50%;
}

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

Make sure you're calling super() as the first thing in your constructor.

You should set this for setAuthorState method

class ManageAuthorPage extends Component {

  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  constructor(props) {
    super(props);
    this.handleAuthorChange = this.handleAuthorChange.bind(this);
  } 

  handleAuthorChange(event) {
    let {name: fieldName, value} = event.target;

    this.setState({
      [fieldName]: value
    });
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.handleAuthorChange}
      />
    );
  }
}

Another alternative based on arrow function:

class ManageAuthorPage extends Component {

  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  handleAuthorChange = (event) => {
    const {name: fieldName, value} = event.target;

    this.setState({
      [fieldName]: value
    });
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.handleAuthorChange}
      />
    );
  }
}

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

You don't need to uninstall WebDAV, just add these lines to the web.config:

<system.webServer>
  <modules>
    <remove name="WebDAVModule" />
  </modules>
  <handlers>
    <remove name="WebDAV" />
  </handlers>
</system.webServer>

How to hide image broken Icon using only CSS/HTML?

I liked the answer by Nick and was playing around with this solution. Found a cleaner method. Since ::before/::after pseudos don't work on replaced elements like img and object they will only work if the object data (src) is not loaded. It keeps the HTML more clean and will only add the pseudo if the object fails to load.

_x000D_
_x000D_
object {_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  display: block;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  margin-right: 20px;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
object::after {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  content: '';_x000D_
  background: red url("http://placehold.it/200x200");_x000D_
}
_x000D_
<object data="http://lorempixel.com/200/200/people/1" type="image/png"></object>_x000D_
_x000D_
<object data="http://broken.img/url" type="image/png"></object>
_x000D_
_x000D_
_x000D_

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

How to set username and password for SmtpClient object in .NET?

Use NetworkCredential

Yep, just add these two lines to your code.

var credentials = new System.Net.NetworkCredential("username", "password");

client.Credentials = credentials;

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

Image comparison - fast algorithm

As cartman pointed out, you can use any kind of hash value for finding exact duplicates.

One starting point for finding close images could be here. This is a tool used by CG companies to check if revamped images are still showing essentially the same scene.

jQuery UI autocomplete with JSON

You need to transform the object you are getting back into an array in the format that jQueryUI expects.

You can use $.map to transform the dealers object into that array.

$('#dealerName').autocomplete({
    source: function (request, response) {
        $.getJSON("/example/location/example.json?term=" + request.term, function (data) {
            response($.map(data.dealers, function (value, key) {
                return {
                    label: value,
                    value: key
                };
            }));
        });
    },
    minLength: 2,
    delay: 100
});

Note that when you select an item, the "key" will be placed in the text box. You can change this by tweaking the label and value properties that $.map's callback function return.

Alternatively, if you have access to the server-side code that is generating the JSON, you could change the way the data is returned. As long as the data:

  • Is an array of objects that have a label property, a value property, or both, or
  • Is a simple array of strings

In other words, if you can format the data like this:

[{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]

or this:

["dealer 5", "dealer 6"]

Then your JavaScript becomes much simpler:

$('#dealerName').autocomplete({
    source: "/example/location/example.json"
});

Why is my method undefined for the type object?

It should be like that

public static void main(String[] args) {
        EchoServer0 e = new EchoServer0();
        // TODO Auto-generated method stub
        e.listen();
}

Your variable of type Object truly doesn't have such a method, but the type EchoServer0 you define above certainly has.

Appending pandas dataframes generated in a for loop

you can try this.

data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    data_you_need=data_you_need.append(data,ignore_index=True)

I hope it can help.

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

To fetch only one distinct record from duplicate column of two rows you can use "rowid" column which is maintained by oracle itself as Primary key,so first try

"select rowid,RequestID,CreatedDate,HistoryStatus  from temptable;"

and then you can fetch second row only by it's value of 'rowid' column by using in SELECT statement.

How to split long commands over multiple lines in PowerShell

Another way to break a string across multiple lines is to put an empty expression in the middle of the string, and break it across lines:

sample string:

"stackoverflow stackoverflow stackoverflow stackoverflow stackoverflow"

broken across lines:

"stackoverflow stackoverflow $(
)stackoverflow stack$(
)overflow stackoverflow"

Favicon not showing up in Google Chrome

I read a bunch of different entries till I finally found a solution that worked for my scenario (ASP.NET MVC4 project).

Instead of using the filename favicon.ico for my icon, I renamed it to something else, ie myIcon.ico. Then I just used exactly what Domi posted:

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

And this worked!

It's not a caching issue because I tested this with Fiddler - a request for favicon never occurred, even if I cleared my cache "From the beginning of time". I believe it's just some odd bug with chrome?

For homebrew mysql installs, where's my.cnf?

run

sudo find / -name my.cnf

Usually the first result is the correct one. Should be in

/usr/local/etc/

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

Just type git init into your command line and press enter. Then run your command again, you probably were running git remote add origin [your-repository].

That should work, if it doesn't, just let me know.

python : list index out of range error while iteratively popping elements

List comprehension will lead you to a solution.

But the right way to copy a object in python is using python module copy - Shallow and deep copy operations.

l=[1,2,3,0,0,1]
for i in range(0,len(l)):
   if l[i]==0:
       l.pop(i)

If instead of this,

import copy
l=[1,2,3,0,0,1]
duplicate_l = copy.copy(l)
for i in range(0,len(l)):
   if l[i]==0:
       m.remove(i)
l = m

Then, your own code would have worked. But for optimization, list comprehension is a good solution.

react native get TextInput value

If you set the text state, why not use that directly?

_handlePress(event) {
  var username=this.state.text;

Of course the variable naming could be more descriptive than 'text' but your call.

SignalR Console app example

The Self-Host now uses Owin. Checkout http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host to setup the server. It's compatible with the client code above.

How to generate .json file with PHP?

If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.

my_json.php

$array = array(
    'title' => $title,
    'url' => $url
);

echo stripslashes(json_encode($array)); 

Then in your script set the path to the file my_json.php

NGINX - No input file specified. - php Fast/CGI

server {
    server_name www.test.com test.com;
    access_log /sites/test/logs/access.log;
    error_log /sites/test/logs/error.log;
    root /sites/test;

 location ~ / {

index index.php
    include /etc/nginx/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME `$document_root/service/public$fastcgi_script_name`;
}

How to round up integer division and have int result in Java?

(message.length() + 152) / 153

This will give a "rounded up" integer.

BAT file to map to network drive without running as admin

This .vbs code creates a .bat file with the current mapped network drives. Then, just put the created file into the machine which you want to re-create the mappings and double-click it. It will try to create all mappings using the same drive letters (errors can occur if any letter is in use). This method also can be used as a backup of the current mappings. Save the code bellow as a .vbs file (e.g. Mappings.vbs) and double-click it.

' ********** My Code **********
Set wshShell = CreateObject( "WScript.Shell" )

' ********** Get ComputerName
strComputer = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )

' ********** Get Domain 
sUserDomain = createobject("wscript.network").UserDomain

Set Connect = GetObject("winmgmts://"&strComputer)
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections

' ********** Current Path
sCurrentPath = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)

' ********** Blank the report message
strMsg = ""

' ********** Set objects 
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objWbem = GetObject("winmgmts:")
Set objRegistry = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")

' ********** Get UserName
sUser = CreateObject("WScript.Network").UserName

' ********** Print user and computer
'strMsg = strMsg & "    User: " & sUser & VbCrLf
'strMsg = strMsg & "Computer: " & strComputer & VbCrLf & VbCrLf

strMsg = strMsg & "###  COPIED FROM " & strComputer & " ###" & VbCrLf& VbCrLf
strMsg = strMsg & "@echo off" & vbCrLf

For i = 0 to oDrives.Count - 1 Step 2
    strMsg = strMsg & "net use " & oDrives.Item(i) & " " & oDrives.Item(i+1) & " /user:" & sUserDomain & "\" & sUser & " /persistent:yes" & VbCrLf
Next
strMsg = strMsg & ":exit" & VbCrLf
strMsg = strMsg & "@pause" & VbCrLf

' ********** write the file to disk.
strDirectory = sCurrentPath 
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
    ' Procede
Else
    Set objFolder = objFSO.CreateFolder(strDirectory)
End if

' ********** Calculate date serial for filename **********
intMonth = month(now)
if intMonth < 10 then
    strThisMonth = "0" & intMonth
else
    strThisMonth = intMOnth
end if
intDay = Day(now)
if intDay < 10 then
    strThisDay = "0" & intDay
else
    strThisDay = intDay
end if
strFilenameDateSerial = year(now) & strThisMonth & strThisDay
    sFileName = strDirectory & "\" & strComputer & "_" & sUser & "_MappedDrives" & "_" & strFilenameDateSerial & ".bat"
    Set objFile = objFSO.CreateTextFile(sFileName,True) 
objFile.Write strMsg & vbCrLf

' ********** Ask to view file
strFinish = "End: A .bat was generated. " & VbCrLf & "Copy the generated file  (" & sFileName & ")  into the machine where you want to recreate the mappings and double-click it." & VbCrLf & VbCrLf 
MsgBox(strFinish)

laravel 5.4 upload image

i think better to do this

    if ( $request->hasFile('file')){
        if ($request->file('file')->isValid()){
            $file = $request->file('file');
            $name = $file->getClientOriginalName();
            $file->move('images' , $name);
            $inputs = $request->all();
            $inputs['path'] = $name;
        }
    }
    Post::create($inputs);

actually images is folder that laravel make it automatic and file is name of the input and here we store name of the image in our path column in the table and store image in public/images directory

How to properly upgrade node using nvm

? TWO Simple Solutions:

To install the latest version of node and reinstall the old version packages just run the following command.

nvm install node --reinstall-packages-from=node

To install the latest lts (long term support) version of node and reinstall the old version packages just run the following command.

nvm install --lts /* --reinstall-packages-from=node

Here's a GIF to support this answer.

nvm

add string to String array

You cannot resize an array in java.

Once the size of array is declared, it remains fixed.

Instead you can use ArrayList that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.

ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);

String s4 ="Test4";
ar.add(s4);

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

Postgresql: error "must be owner of relation" when changing a owner object

Thanks to Mike's comment, I've re-read the doc and I've realised that my current user (i.e. userA that already has the create privilege) wasn't a direct/indirect member of the new owning role...

So the solution was quite simple - I've just done this grant:

grant userB to userA;

That's all folks ;-)


Update:

Another requirement is that the object has to be owned by user userA before altering it...

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

How to use paths in tsconfig.json?

Checkout the compiler operation using this

I have added baseUrl in the file for a project like below :

"baseUrl": "src"

It is working fine. So add your base directory for your project.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

I know this is an old post and that it wants an answer for .NET 1.1 but there's already a very good answer for that. I thought it would be good to have an answer for those people who land on this post that may have a more recent version of the .Net framework, such as myself when I went looking for an answer to the same question.

In those cases there is an even simpler way to write the contents of a StringBuilder to a text file. It can be done with one line of code. It may not be the most efficient but that wasn't really the question now was it.

System.IO.File.WriteAllText(@"C:\MyDir\MyNewTextFile.txt",sbMyStringBuilder.ToString());

Setting focus to a textbox control

Quite simple :

For the tab control, you need to handle the _SelectedIndexChanged event:

Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) _
  Handles TabControl1.SelectedIndexChanged

If TabControl1.SelectedTab.Name = "TabPage1" Then
    TextBox2.Focus()
End If
If TabControl1.SelectedTab.Name = "TabPage2" Then
    TextBox4.Focus()
End If

Factorial using Recursion in Java

What happens is that the recursive call itself results in further recursive behaviour. If you were to write it out you get:

 fact(4)
 fact(3) * 4;
 (fact(2) * 3) * 4;
 ((fact(1) * 2) * 3) * 4;
 ((1 * 2) * 3) * 4;

How to add icons to React Native app

If you're using expo just place an 1024 x 1024 png file in your project and add an icon property to your app.json i.e. "icon": "./src/assets/icon.png"

https://docs.expo.io/versions/latest/guides/app-icons

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Formatting your data that may be the problem. Try either of these:

data: '{ "things":' + JSON.stringify(things) + '}',

Or (from How can I post an array of string to ASP.NET MVC Controller without a form?)

var postData = { things: things };
...
data = postData

Class method differences in Python: bound, unbound and static

Unbound Methods

Unbound methods are methods that are not bound to any particular class instance yet.

Bound Methods

Bound methods are the ones which are bound to a specific instance of a class.

As its documented here, self can refer to different things depending on the function is bound, unbound or static.

Take a look at the following example:

class MyClass:    
    def some_method(self):
        return self  # For the sake of the example

>>> MyClass().some_method()
<__main__.MyClass object at 0x10e8e43a0># This can also be written as:>>> obj = MyClass()

>>> obj.some_method()
<__main__.MyClass object at 0x10ea12bb0>

# Bound method call:
>>> obj.some_method(10)
TypeError: some_method() takes 1 positional argument but 2 were given

# WHY IT DIDN'T WORK?
# obj.some_method(10) bound call translated as
# MyClass.some_method(obj, 10) unbound method and it takes 2 
# arguments now instead of 1 

# ----- USING THE UNBOUND METHOD ------
>>> MyClass.some_method(10)
10

Since we did not use the class instance — obj — on the last call, we can kinda say it looks like a static method.

If so, what is the difference between MyClass.some_method(10) call and a call to a static function decorated with a @staticmethod decorator?

By using the decorator, we explicitly make it clear that the method will be used without creating an instance for it first. Normally one would not expect the class member methods to be used without the instance and accesing them can cause possible errors depending on the structure of the method.

Also, by adding the @staticmethod decorator, we are making it possible to be reached through an object as well.

class MyClass:    
    def some_method(self):
        return self    

    @staticmethod
    def some_static_method(number):
        return number

>>> MyClass.some_static_method(10)   # without an instance
10
>>> MyClass().some_static_method(10)   # Calling through an instance
10

You can’t do the above example with the instance methods. You may survive the first one (as we did before) but the second one will be translated into an unbound call MyClass.some_method(obj, 10) which will raise a TypeError since the instance method takes one argument and you unintentionally tried to pass two.

Then, you might say, “if I can call static methods through both an instance and a class, MyClass.some_static_method and MyClass().some_static_method should be the same methods.” Yes!

Simple way to convert datarow array to datatable

Another way is to use a DataView

// Create a DataTable
DataTable table = new DataTable()
...

// Filter and Sort expressions
string expression = "[Birth Year] >= 1983"; 
string sortOrder = "[Birth Year] ASC";

// Create a DataView using the table as its source and the filter and sort expressions
DataView dv = new DataView(table, expression, sortOrder, DataViewRowState.CurrentRows);

// Convert the DataView to a DataTable
DataTable new_table = dv.ToTable("NewTableName");

Get the last item in an array

This can be done with lodash _.last or _.nth:

_x000D_
_x000D_
var data = [1, 2, 3, 4]_x000D_
var last = _.nth(data, -1)_x000D_
console.log(last)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
_x000D_
_x000D_
_x000D_

How to find most common elements of a list?

In Python 2.7 and above there is a class called Counter which can help you:

from collections import Counter
words_to_count = (word for word in word_list if word[:1].isupper())
c = Counter(words_to_count)
print c.most_common(3)

Result:

[('Jellicle', 6), ('Cats', 5), ('And', 2)]

I am quite new to programming so please try and do it in the most barebones fashion.

You could instead do this using a dictionary with the key being a word and the value being the count for that word. First iterate over the words adding them to the dictionary if they are not present, or else increasing the count for the word if it is present. Then to find the top three you can either use a simple O(n*log(n)) sorting algorithm and take the first three elements from the result, or you can use a O(n) algorithm that scans the list once remembering only the top three elements.

An important observation for beginners is that by using builtin classes that are designed for the purpose you can save yourself a lot of work and/or get better performance. It is good to be familiar with the standard library and the features it offers.

Create a .csv file with values from a Python list

For those looking for less complicated solution. I actually find this one more simplisitic solution that will do similar job:

import pandas as pd
a = ['a','b','c'] 
df = pd.DataFrame({'a': a})
df= df.set_index('a').T
df.to_csv('list_a.csv', index=False)

Hope this helps as well.

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

Setting a div's height in HTML with CSS

A 2 column layout is a little bit tough to get working in CSS (at least until CSS3 is practical.)

Floating left and right will work to a point, but it won't allow you to extend the background. To make backgrounds stay solid, you'll have to implement a technique known as "faux columns," which basically means your columns themselves won't have a background image. Your 2 columns will be contained inside of a parent tag. This parent tag is given a background image that contains the 2 column colors you want. Make this background only as big as you need it to (if it is a solid color, only make it 1 pixel high) and have it repeat-y. AListApart has a great walkthrough on what is needed to make it work.

http://www.alistapart.com/articles/fauxcolumns/

How do you save/store objects in SharedPreferences on Android?

Try this best way :

PreferenceConnector.java

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class PreferenceConnector {
    public static final String PREF_NAME = "ENUMERATOR_PREFERENCES";
    public static final String PREF_NAME_REMEMBER = "ENUMERATOR_REMEMBER";
    public static final int MODE = Context.MODE_PRIVATE;


    public static final String name = "name";


    public static void writeBoolean(Context context, String key, boolean value) {
        getEditor(context).putBoolean(key, value).commit();
    }

    public static boolean readBoolean(Context context, String key,
            boolean defValue) {
        return getPreferences(context).getBoolean(key, defValue);
    }

    public static void writeInteger(Context context, String key, int value) {
        getEditor(context).putInt(key, value).commit();

    }

    public static int readInteger(Context context, String key, int defValue) {
        return getPreferences(context).getInt(key, defValue);
    }

    public static void writeString(Context context, String key, String value) {
        getEditor(context).putString(key, value).commit();

    }

    public static String readString(Context context, String key, String defValue) {
        return getPreferences(context).getString(key, defValue);
    }

    public static void writeLong(Context context, String key, long value) {
        getEditor(context).putLong(key, value).commit();
    }

    public static long readLong(Context context, String key, long defValue) {
        return getPreferences(context).getLong(key, defValue);
    }

    public static SharedPreferences getPreferences(Context context) {
        return context.getSharedPreferences(PREF_NAME, MODE);
    }

    public static Editor getEditor(Context context) {
        return getPreferences(context).edit();
    }

}

Write the Value :

PreferenceConnector.writeString(this, PreferenceConnector.name,"Girish");

And Get value using :

String name= PreferenceConnector.readString(this, PreferenceConnector.name, "");

ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.

load json into variable

<input  class="pull-right" id="currSpecID" name="currSpecID" value="">

   $.get("http://localhost:8080/HIS_API/rest/MriSpecimen/getMaxSpecimenID", function(data, status){
       alert("Data: " + data + "\nStatus: " + status);
    $("#currSpecID").val(data);
    });

enter image description here enter image description here

grep using a character vector with multiple patterns

Using the sapply

 patterns <- c("A1", "A9", "A6")
         df <- data.frame(name=c("A","Ale","Al","lex","x"),Letters=c("A1","A2","A9","A1","A9"))



   name Letters
1    A      A1
2  Ale      A2
3   Al      A9
4  lex      A1
5    x      A9


 df[unlist(sapply(patterns, grep, df$Letters, USE.NAMES = F)), ]
  name Letters
1    A      A1
4  lex      A1
3   Al      A9
5    x      A9

What is the difference between Cloud, Grid and Cluster?

Cloud: is simply an aggregate of computing power. You can think of the entire "cloud" as single server, for your purposes. It's conceptually much like an old school mainframe where you could submit your jobs to and have it return the result, except that nowadays the concept is applied more widely. (I.e. not just raw computing, also entire services, or storage ...)

Grid: a grid is simply many computers which together might solve a given problem/crunch data. The fundamental difference between a grid and a cluster is that in a grid each node is relatively independent of others; problems are solved in a divide and conquer fashion.

Cluster: conceptually it is essentially smashing up many machines to make a really big & powerful one. This is a much more difficult architecture than cloud or grid to get right because you have to orchestrate all nodes to work together, and provide consistency of things such as cache, memory, and not to mention clocks. Of course clouds have much the same problem, but unlike clusters clouds are not conceptually one big machine, so the entire architecture doesn't have to treat it as such. You can for instance not allocate the full capacity of your data center to a single request, whereas that is kind of the point of a cluster: to be able to throw 100% of the oomph at a single problem.

Xcode 7.2 no matching provisioning profiles found

You can also simply go to xcode preferences then accounts and then it may ask you to simply re sign in with your developer profile and then the issues should go away.

Hope this Helps!

Modify property value of the objects in list using Java 8 streams

just for modifying certain property from object collection you could directly use forEach with a collection as follows

collection.forEach(c -> c.setXyz(c.getXyz + "a"))

Updates were rejected because the tip of your current branch is behind its remote counterpart

Set current branch name like master

git pull --rebase origin master git push origin master

Or branch name develop

git pull --rebase origin develop git push origin develop

Cannot ignore .idea/workspace.xml - keeps popping up

If you have multiple projects in your git repo, .idea/workspace.xml will not match to any files.

Instead, do the following:

$ git rm -f **/.idea/workspace.xml

And make your .gitignore look something like this:

# User-specific stuff:
**/.idea/workspace.xml
**/.idea/tasks.xml
**/.idea/dictionaries
**/.idea/vcs.xml
**/.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
**/.idea/dataSources.ids
**/.idea/dataSources.xml
**/.idea/dataSources.local.xml
**/.idea/sqlDataSources.xml
**/.idea/dynamic.xml
**/.idea/uiDesigner.xml

## File-based project format:
*.iws

# IntelliJ
/out/

How can I increase the JVM memory?

When starting the JVM, two parameters can be adjusted to suit your memory needs :

-Xms<size>

specifies the initial Java heap size and

-Xmx<size>

the maximum Java heap size.

http://www.rgagnon.com/javadetails/java-0131.html

Python __call__ special method practical example

Django forms module uses __call__ method nicely to implement a consistent API for form validation. You can write your own validator for a form in Django as a function.

def custom_validator(value):
    #your validation logic

Django has some default built-in validators such as email validators, url validators etc., which broadly fall under the umbrella of RegEx validators. To implement these cleanly, Django resorts to callable classes (instead of functions). It implements default Regex Validation logic in a RegexValidator and then extends these classes for other validations.

class RegexValidator(object):
    def __call__(self, value):
        # validation logic

class URLValidator(RegexValidator):
    def __call__(self, value):
        super(URLValidator, self).__call__(value)
        #additional logic

class EmailValidator(RegexValidator):
    # some logic

Now both your custom function and built-in EmailValidator can be called with the same syntax.

for v in [custom_validator, EmailValidator()]:
    v(value) # <-----

As you can see, this implementation in Django is similar to what others have explained in their answers below. Can this be implemented in any other way? You could, but IMHO it will not be as readable or as easily extensible for a big framework like Django.

How to have css3 animation to loop forever

add this styles

animation-iteration-count:infinite;

Is there a way to get a list of column names in sqlite?

Assuming that you know the table name, and want the names of the data columns you can use the listed code will do it in a simple and elegant way to my taste:

import sqlite3

def get_col_names():
#this works beautifully given that you know the table name
    conn = sqlite3.connect("t.db")
    c = conn.cursor()
    c.execute("select * from tablename")
    return [member[0] for member in c.description]

Append a tuple to a list - what's the difference between two ways?

It has nothing to do with append. tuple(3, 4) all by itself raises that error.

The reason is that, as the error message says, tuple expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.

Just do (3, 4) to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.

PDOException SQLSTATE[HY000] [2002] No such file or directory

I got the same problem and I'm running Mac OS X 10.10 Yosemite. I have enabled the Apache Server and PHP that already comes with the OS. Then I just configured the mCrypt library to get started. After that when I was working with models and DB I got the error:

[PDOException]
SQLSTATE[HY000] [2002] No such file or directory

The reason I found is just because PHP and MySQL can't get connected themselves. To get this problem fixed, I follow the next steps:

  1. Open a terminal and connect to the mysql with:

    mysql -u root -p
    
  2. It will ask you for the related password. Then once you get the mysql promt type the next command:

    mysql> show variables like '%sock%'
    
  3. You will get something like this:

    +-----------------------------------------+-----------------+
    | Variable_name                           | Value           |
    +-----------------------------------------+-----------------+
    | performance_schema_max_socket_classes   | 10              |
    | performance_schema_max_socket_instances | 322             |
    | socket                                  | /tmp/mysql.sock |
    +-----------------------------------------+-----------------+
    
  4. Keep the value of the last row:

    /tmp/mysql.sock
    
  5. In your laravel project folder, look for the database.php file there is where you configure the DB connection parameters. In the mysql section add the next line at the end:

    'unix_socket' => '/tmp/mysql.sock'
    
  6. You must have something like this:

    'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'SchoolBoard',
            'username'  => 'root',
            'password'  => 'venturaa',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'unix_socket' => '/tmp/mysql.sock',
        ),
    

Now just save changes, and reload the page and it must work!

How do I access (read, write) Google Sheets spreadsheets with Python?

Have a look at GitHub - gspread.

I found it to be very easy to use and since you can retrieve a whole column by

first_col = worksheet.col_values(1)

and a whole row by

second_row = worksheet.row_values(2)

you can more or less build some basic select ... where ... = ... easily.

How to encrypt a large file in openssl using public key

To safely encrypt large files (>600MB) with openssl smime you'll have to split each file into small chunks:

# Splits large file into 500MB pieces
split -b 500M -d -a 4 INPUT_FILE_NAME input.part.

# Encrypts each piece
find -maxdepth 1 -type f -name 'input.part.*' | sort | xargs -I % openssl smime -encrypt -binary -aes-256-cbc -in % -out %.enc -outform DER PUBLIC_PEM_FILE

For the sake of information, here is how to decrypt and put all pieces together:

# Decrypts each piece
find -maxdepth 1 -type f -name 'input.part.*.enc' | sort | xargs -I % openssl smime -decrypt -in % -binary -inform DEM -inkey PRIVATE_PEM_FILE -out %.dec

# Puts all together again
find -maxdepth 1 -type f -name 'input.part.*.dec' | sort | xargs cat > RESTORED_FILE_NAME

HTML code for an apostrophe

Depends on which apostrophe you are talking about: there’s &apos;, &lsquo;, &rsquo; and probably numerous other ones, depending on the context and the language you’re intending to write. And with a declared character encoding of e.g. UTF-8 you can also write them directly into your HTML: ', , .

Object array initialization without default constructor

I don't think there's type-safe method that can do what you want.

What are MVP and MVC and what is the difference?

They each addresses different problems and can even be combined together to have something like below

The Combined Pattern

There is also a complete comparison of MVC, MVP and MVVM here

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

I test all answers for this question not work for me, I use this below method:

I exclude that file(s) has breakpoints from project where that visual studio can't hits them and then I includes them into my project and worked breakpoints.

How do I remove time part from JavaScript date?

Split it by space and take first part like below. Hope this will help you.

var d = '12/12/1955 12:00:00 AM';
d = d.split(' ')[0];
console.log(d);

Find Process Name by its Process ID

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET /a pid=1600
FOR /f "skip=3delims=" %%a IN ('tasklist') DO (
 SET "found=%%a"
 SET /a foundpid=!found:~26,8!
 IF %pid%==!foundpid! echo found %pid%=!found:~0,24%!
)

GOTO :EOF

...set PID to suit your circumstance.