Programs & Examples On #Restlet 2.0

Uploading Laravel Project onto Web Server

Had this problem too and found out that the easiest way is to point your domain to the public folder and leave everything else the way they are.

PLEASE ENSURE TO USE THE RIGHT VERSION OF PHP. Save yourself some stress :)

How to call a .NET Webservice from Android using KSOAP2?

Typecast the envelope to SoapPrimitive:

SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
String strRes = result.toString();

and it will work.

python 2.7: cannot pip on windows "bash: pip: command not found"

The problem is that your Python version and the library you want to use are not same versionally (Python). Even if you install Python's latest version, your PATH might not change properly and automatically. Thus, you should change it manually.After matching their version, it will work.

Ex: When I tried to install Django3, I got same error. I noticed that my PATH still seems C:\python27\Scripts though I already install Python3.8, so that I manually edited my PATH C:\python38\Scripts and reinstalled pip install Django and everything worked well.

Retrieve the maximum length of a VARCHAR column in SQL Server

For Oracle, it is also LENGTH instead of LEN

SELECT MAX(LENGTH(Desc)) FROM table_name

Also, DESC is a reserved word. Although many reserved words will still work for column names in many circumstances it is bad practice to do so, and can cause issues in some circumstances. They are reserved for a reason.

If the word Desc was just being used as an example, it should be noted that not everyone will realize that, but many will realize that it is a reserved word for Descending. Personally, I started off by using this, and then trying to figure out where the column name went because all I had were reserved words. It didn't take long to figure it out, but keep that in mind when deciding on what to substitute for your actual column name.

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

This worked for me

class _SplashScreenState extends State<SplashScreen> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: FittedBox(
        child: Image.asset("images/my_image.png"),
        fit: BoxFit.fill,
      ),);
  }
}

! [rejected] master -> master (fetch first)

Try this git command

git push origin master --force

or short of force -f

git push origin master -f

Flattening a shallow list in Python

Performance Results. Revised.

import itertools
def itertools_flatten( aList ):
    return list( itertools.chain(*aList) )

from operator import add
def reduce_flatten1( aList ):
    return reduce(add, map(lambda x: list(x), [mi for mi in aList]))

def reduce_flatten2( aList ):
    return reduce(list.__add__, map(list, aList))

def comprehension_flatten( aList ):
    return list(y for x in aList for y in x)

I flattened a 2-level list of 30 items 1000 times

itertools_flatten     0.00554
comprehension_flatten 0.00815
reduce_flatten2       0.01103
reduce_flatten1       0.01404

Reduce is always a poor choice.

Can there exist two main methods in a Java program?

There can be more than one main method in a single program. Others are Overloaded method. This overloaded method works fine under a single main method

public class MainMultiple{

   public static void main(String args[]){
       main(122);
       main('f');
       main("hello java");
   }

   public static void main(int i){
       System.out.println("Overloaded main()"+i);
   }

   public static void main(char i){
       System.out.println("Overloaded main()"+i);
   }

   public static void main(String str){
       System.out.println("Overloaded main()"+str);
   }
}

Checking if form has been submitted - PHP

Actually, the submit button already performs this function.

Try in the FORM:

<form method="post">
<input type="submit" name="treasure" value="go!">
</form>

Then in the PHP handler:

if (isset($_POST['treasure'])){
echo "treasure will be set if the form has been submitted (to TRUE, I believe)";
}

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

First the mysqldump command is executed and the output generated is redirected using the pipe. The pipe is sending the standard output into the gzip command as standard input. Following the filename.gz, is the output redirection operator (>) which is going to continue redirecting the data until the last filename, which is where the data will be saved.

For example, this command will dump the database and run it through gzip and the data will finally land in three.gz

mysqldump -u user -pupasswd my-database | gzip > one.gz > two.gz > three.gz

$> ls -l
-rw-r--r--  1 uname  grp     0 Mar  9 00:37 one.gz
-rw-r--r--  1 uname  grp  1246 Mar  9 00:37 three.gz
-rw-r--r--  1 uname  grp     0 Mar  9 00:37 two.gz

My original answer is an example of redirecting the database dump to many compressed files (without double compressing). (Since I scanned the question and seriously missed - sorry about that)

This is an example of recompressing files:

mysqldump -u user -pupasswd my-database | gzip -c > one.gz; gzip -c one.gz > two.gz; gzip -c two.gz > three.gz

$> ls -l
-rw-r--r--  1 uname  grp  1246 Mar  9 00:44 one.gz
-rw-r--r--  1 uname  grp  1306 Mar  9 00:44 three.gz
-rw-r--r--  1 uname  grp  1276 Mar  9 00:44 two.gz

This is a good resource explaining I/O redirection: http://www.codecoffee.com/tipsforlinux/articles2/042.html

jquery change class name

I better use the .prop to change the className and it worked perfectly:

$(#td_id).prop('className','newClass');

for this line of code you just have to change the name of newClass, and of course the id of the element, in the next exemple : idelementinyourpage

$(#idelementinyourpage).prop('className','newClass');

By the way, when you want to search which style is applied to any element, you just click F12 on your browser when your page is shown, and then select in the tab of DOM Explorer, the element you want to see. In Styles you now can see what styles are applied to your element and from which class its reading.

Switch statement fall-through...should it be allowed?

Fall-through is really a handy thing, depending on what you're doing. Consider this neat and understandable way to arrange options:

switch ($someoption) {
  case 'a':
  case 'b':
  case 'c':
    // Do something
    break;

  case 'd':
  case 'e':
    // Do something else
    break;
}

Imagine doing this with if/else. It would be a mess.

Replace a value in a data frame based on a conditional (`if`) statement

Short answer is:

junk$nm[junk$nm %in% "B"] <- "b"

Take a look at Index vectors in R Introduction (if you don't read it yet).


EDIT. As noticed in comments this solution works for character vectors so fail on your data.

For factor best way is to change level:

levels(junk$nm)[levels(junk$nm)=="B"] <- "b"

The operation cannot be completed because the DbContext has been disposed error

Here you are trying to execute IQueryable object on inactive DBContext. your DBcontext is already disposed of. you can only execute IQueryable object before DBContext is disposed of. Means you need to write users.Select(x => x.ToInfo()).ToList() statement inside using scope

Find the server name for an Oracle database

SELECT  host_name
FROM    v$instance

Building a fat jar using maven

You can use the onejar-maven-plugin for packaging. Basically, it assembles your project and its dependencies in as one jar, including not just your project jar file, but also all external dependencies as a "jar of jars", e.g.

<build>
    <plugins>
        <plugin>
            <groupId>com.jolira</groupId>
            <artifactId>onejar-maven-plugin</artifactId>
                <version>1.4.4</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>one-jar</goal>
                        </goals>
                    </execution>
                </executions>
        </plugin>
    </plugins>
</build>

Note 1: Configuration options is available at the project home page.

Note 2: For one reason or the other, the onejar-maven-plugin project is not published at Maven Central. However jolira.com tracks the original project and publishes it to with the groupId com.jolira.

How may I reference the script tag that loaded the currently-executing script?

I've got this, which is working in FF3, IE6 & 7. The methods in the on-demand loaded scripts aren't available until page load is complete, but this is still very useful.

//handle on-demand loading of javascripts
makescript = function(url){
    var v = document.createElement('script');
    v.src=url;
    v.type='text/javascript';

    //insertAfter. Get last <script> tag in DOM
    d=document.getElementsByTagName('script')[(document.getElementsByTagName('script').length-1)];
    d.parentNode.insertBefore( v, d.nextSibling );
}

How to convert an image to base64 encoding?

Here is the code for upload to encode and save it to the MySQL

if (!isset($_GET["getfile"])) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Error: " . $_FILES["file"]["error"] . "<br>";
    } else {
        move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);

        $bin_string = file_get_contents($_FILES["file"]["name"]);
        $hex_string = base64_encode($bin_string);
        $mysqli = mysqli_init();

        if (!$mysqli->real_connect('localhost', 'root', '', 'arihant')) {
            die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
        }

        $mysqli->query("INSERT INTO upload(image) VALUES ('" . $hex_string . "')");
    }
}

For showing the image use this

echo "<img src='data:image/jpeg;base64, $image' width=300>";

How to parse JSON in Scala using standard Scala classes?

val jsonString =
  """
    |{
    | "languages": [{
    |     "name": "English",
    |     "is_active": true,
    |     "completeness": 2.5
    | }, {
    |     "name": "Latin",
    |     "is_active": false,
    |     "completeness": 0.9
    | }]
    |}
  """.stripMargin

val result = JSON.parseFull(jsonString).map {
  case json: Map[String, List[Map[String, Any]]] =>
    json("languages").map(l => (l("name"), l("is_active"), l("completeness")))
}.get

println(result)

assert( result == List(("English", true, 2.5), ("Latin", false, 0.9)) )

How to properly ignore exceptions

I usually just do:

try:
    doSomething()
except:
    _ = ""

Regular expression to match a dot

A . in regex is a metacharacter, it is used to match any character. To match a literal dot, you need to escape it, so \.

Largest and smallest number in an array

Int[] number ={1,2,3,4,5,6,7,8,9,10};
Int? Result = null;
 foreach(Int i in number)

    {
       If(!Result.HasValue || i< Result)

        { 

            Result =i;
         }
     }

     Console.WriteLine(Result);
   }

Inject service in app.config

** Explicitly request services from other modules using angular.injector **

Just to elaborate on kim3er's answer, you can provide services, factories, etc without changing them to providers, as long as they are included in other modules...

However, I'm not sure if the *Provider (which is made internally by angular after it processes a service, or factory) will always be available (it may depend on what else loaded first), as angular lazily loads modules.

Note that if you want to re-inject the values that they should be treated as constants.

Here's a more explicit, and probably more reliable way to do it + a working plunker

var base = angular.module('myAppBaseModule', [])
base.factory('Foo', function() { 
  console.log("Foo");
  var Foo = function(name) { this.name = name; };
  Foo.prototype.hello = function() {
    return "Hello from factory instance " + this.name;
  }
  return Foo;
})
base.service('serviceFoo', function() {
  this.hello = function() {
    return "Service says hello";
  }
  return this;
});

var app = angular.module('appModule', []);
app.config(function($provide) {
  var base = angular.injector(['myAppBaseModule']);
  $provide.constant('Foo', base.get('Foo'));
  $provide.constant('serviceFoo', base.get('serviceFoo'));
});
app.controller('appCtrl', function($scope, Foo, serviceFoo) {
  $scope.appHello = (new Foo("app")).hello();
  $scope.serviceHello = serviceFoo.hello();
});

How to define optional methods in Swift protocol?

Here is a concrete example with the delegation pattern.

Setup your Protocol:

@objc protocol MyProtocol:class
{
    func requiredMethod()
    optional func optionalMethod()
}

class MyClass: NSObject
{
    weak var delegate:MyProtocol?

    func callDelegate()
    {
        delegate?.requiredMethod()
        delegate?.optionalMethod?()
    }
}

Set the delegate to a class and implement the Protocol. See that the optional method does not need to be implemented.

class AnotherClass: NSObject, MyProtocol
{
    init()
    {
        super.init()

        let myInstance = MyClass()
        myInstance.delegate = self
    }

    func requiredMethod()
    {
    }
}

One important thing is that the optional method is optional and needs a "?" when calling. Mention the second question mark.

delegate?.optionalMethod?()

?: operator (the 'Elvis operator') in PHP

Yes, this is new in PHP 5.3. It returns either the value of the test expression if it is evaluated as TRUE, or the alternative value if it is evaluated as FALSE.

How to block until an event is fired in c#

If the current method is async then you can use TaskCompletionSource. Create a field that the event handler and the current method can access.

    TaskCompletionSource<bool> tcs = null;

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        tcs = new TaskCompletionSource<bool>();
        await tcs.Task;
        WelcomeTitle.Text = "Finished work";
    }

    private void Button_Click2(object sender, RoutedEventArgs e)
    {
        tcs?.TrySetResult(true);
    }

This example uses a form that has a textblock named WelcomeTitle and two buttons. When the first button is clicked it starts the click event but stops at the await line. When the second button is clicked the task is completed and the WelcomeTitle text is updated. If you want to timeout as well then change

await tcs.Task;

to

await Task.WhenAny(tcs.Task, Task.Delay(25000));
if (tcs.Task.IsCompleted)
    WelcomeTitle.Text = "Task Completed";
else
    WelcomeTitle.Text = "Task Timed Out";

C++ auto keyword. Why is it magic?

The auto keyword specifies that the type of the variable that is being declared will be automatically deducted from its initializer. In case of functions, if their return type is auto then that will be evaluated by return type expression at runtime.

It can be very useful when we have to use the iterator. For e.g. for below code we can simply use the "auto" instead of writing the whole iterator syntax .

int main() 
{ 

// Initialize set 
set<int> s; 

s.insert(1); 
s.insert(4); 
s.insert(2); 
s.insert(5); 
s.insert(3); 

// iterator pointing to 
// position where 2 is 
auto pos = s.find(3); 

// prints the set elements 
cout << "The set elements after 3 are: "; 
for (auto it = pos; it != s.end(); it++) 
    cout << *it << " "; 

return 0; 
}

This is how we can use "auto" keyword

python numpy machine epsilon

An easier way to get the machine epsilon for a given float type is to use np.finfo():

print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

how to make a cell of table hyperlink

Easy with onclick-function and a javascript link:

<td onclick="location.href='yourpage.html'">go to yourpage</td>

How to make html table vertically scrollable

The jQuery plugin is probably the best option. http://farinspace.com/jquery-scrollable-table-plugin/

To fixing header you can check this post

Fixing Header of GridView or HtmlTable (there might be issue that this should work in IE only)

CSS for fixing header

div#gridPanel 
{
   width:900px;
   overflow:scroll;
   position:relative;
}


div#gridPanel th
{  
   top: expression(document.getElementById("gridPanel").scrollTop-2);
   left:expression(parentNode.parentNode.parentNode.parentNode.scrollLeft);
   position: relative;
   z-index: 20;
  }

<div height="200px" id="gridPanel" runat="server" scrollbars="Auto" width="100px">
table..
</div>

or

Very good post is here for this

How to Freeze Columns Using JavaScript and HTML.

or

No its not possible but you can make use of div and put table in div

<div style="height: 100px; overflow: auto">
  <table style="height: 500px;">
   ...
  </table>
</div>

Setting background color for a JFrame

Hello There I did have the same problem and after many attempts I found that the problem is that you need a Graphics Object to be able to draw, paint(setBackgroundColor).

My code usually goes like this:

import javax.swing.*;
import java.awt.*;


public class DrawGraphics extends JFrame{

    public DrawGraphics(String title) throws HeadlessException {
      super(title);
      InitialElements();
    }

    private void InitialElements(){
      setSize(300, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
      // This one does not work
      // getContentPane().setBackground(new Color(70, 80, 70));

    }

    public void paint(Graphics draw){
      //Here you can perform any drawing like an oval...
      draw.fillOval(40, 40, 60, 50);

      getContentPane().setBackground(new Color(70,80,70));
    }
}

The missing part on almost all other answers is where to place the code. Then now you know it goes in paint(Graphics G)

Python calling method in class

Could someone explain to me, how to call the move method with the variable RIGHT

>>> myMissile = MissileDevice(myBattery)  # looks like you need a battery, don't know what that is, you figure it out.
>>> myMissile.move(MissileDevice.RIGHT)

If you have programmed in any other language with classes, besides python, this sort of thing

class Foo:
    bar = "baz"

is probably unfamiliar. In python, the class is a factory for objects, but it is itself an object; and variables defined in its scope are attached to the class, not the instances returned by the class. to refer to bar, above, you can just call it Foo.bar; you can also access class attributes through instances of the class, like Foo().bar.


Im utterly baffled about what 'self' refers too,

>>> class Foo:
...     def quux(self):
...         print self
...         print self.bar
...     bar = 'baz'
...
>>> Foo.quux
<unbound method Foo.quux>
>>> Foo.bar
'baz'
>>> f = Foo()
>>> f.bar
'baz'
>>> f
<__main__.Foo instance at 0x0286A058>
>>> f.quux
<bound method Foo.quux of <__main__.Foo instance at 0x0286A058>>
>>> f.quux()
<__main__.Foo instance at 0x0286A058>
baz
>>>

When you acecss an attribute on a python object, the interpreter will notice, when the looked up attribute was on the class, and is a function, that it should return a "bound" method instead of the function itself. All this does is arrange for the instance to be passed as the first argument.

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

We can eliminate the unnecessary file read/write by using text. My complete solution is the following:

proc1 = ['/bin/bash', '-c', 
  "/usr/bin/git ls-remote --heads ssh://repo_url.git"].execute()
proc2 = ['/bin/bash', '-c', 
  "/usr/bin/awk ' { gsub(/refs\\/heads\\//, \"\"); print \$2 }' "].execute()
all = proc1 | proc2

choices = all.text
return choices.split().toList();

Android Fragment onAttach() deprecated

Although it seems that in most cases it's enough to have onAttach(Context), there are some phones (i.e: Xiaomi Redme Note 2) where it's not being called, thus it causes NullPointerExceptions. So to be on the safe side I suggest to leave the deprecated method as well:

// onAttach(Activity) is necessary in some Xiaomi phones
@SuppressWarnings("deprecation")
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    _onAttach(activity);
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    _onAttach(context);
}

private void _onAttach(Context context) {
    // do your real stuff here
}

Gradle failed to resolve library in Android Studio

For me follwing steps helped.

It seems to be bug of Android Studio 3.4/3.5 and it was "fixed" by disabling:

File ? Settings ? Experimental ? Gradle ? Only sync the active variant

How do I use setsockopt(SO_REUSEADDR)?

I think you should use SO_LINGER options (with timeout 0). In this case, you connection will close immediately after closing your program; and next restart will be able to bind again.

example:

linger lin;
lin.l_onoff = 0;
lin.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&lin, sizeof(int));

see definition: http://man7.org/linux/man-pages/man7/socket.7.html

SO_LINGER
          Sets or gets the SO_LINGER option.  The argument is a linger
          structure.

              struct linger {
                  int l_onoff;    /* linger active */
                  int l_linger;   /* how many seconds to linger for */
              };

          When enabled, a close(2) or shutdown(2) will not return until
          all queued messages for the socket have been successfully sent
          or the linger timeout has been reached.  Otherwise, the call
          returns immediately and the closing is done in the background.
          When the socket is closed as part of exit(2), it always
          lingers in the background.

More about SO_LINGER: TCP option SO_LINGER (zero) - when it's required

How can I update window.location.hash without jumping the document?

This solution worked for me

// store the currently selected tab in the hash value
    if(history.pushState) {
        window.history.pushState(null, null, '#' + id);
    }
    else {
        window.location.hash = id;
    }

// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
$('#myTab a[href="' + hash + '"]').tab('show');

And my full js code is

$('#myTab a').click(function(e) {
  e.preventDefault();
  $(this).tab('show');
});

// store the currently selected tab in the hash value
$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
  var id = $(e.target).attr("href").substr(1);
    if(history.pushState) {
        window.history.pushState(null, null, '#' + id);
    }
    else {
        window.location.hash = id;
    }
   // window.location.hash = '#!' + id;
});

// on load of the page: switch to the currently selected tab
var hash = window.location.hash;
// console.log(hash);
$('#myTab a[href="' + hash + '"]').tab('show');

In Node.js, how do I "include" functions from my other files?

Use:

var mymodule = require("./tools.js")

app.js:

module.exports.<your function> = function () {
    <what should the function do>
}

SQL: Insert all records from one table to another table without specific the columns

Per this other post: Insert all values of a..., you can do the following:

INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table

It's important to specify the column names as indicated by the other answers.

keytool error Keystore was tampered with, or password was incorrect

Empty password worked for me on my Mac

keytool -list -v -keystore ~/.android/debug.keystore 

hit Enter then It's show you

Enter keystore password:  

here just hit Enter for empty password

"relocation R_X86_64_32S against " linking Error

I also had similar problems when trying to link static compiled fontconfig and expat into a linux shared object:

/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/fontconfig/lib/linux-x86_64/libfontconfig.a(fccfg.o): relocation R_X86_64_32 against `.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC
/opt/rh/devtoolset-7/root/usr/libexec/gcc/x86_64-redhat-linux/7/ld: /3rdparty/expat/lib/linux-x86_64/libexpat.a(xmlparse.o): relocation R_X86_64_PC32 against symbol `stderr@@GLIBC_2.2.5' can not be used when making a shared object; recompile with -fPIC
[...]

This contrary to the fact that I was already passing -fPIC flags though CFLAGS variable, and other compilers/linkers variants (clang/lld) were perfectly working with the same build configuration. It ended up that these dependencies control position-independent code settings through despicable autoconf scripts and need --with-pic switch during build configuration on linux gcc/ld combination, and its lack probably overrides same the setting in CFLAGS. Pass the switch to configure script and the dependencies will be correctly compiled with -fPIC.

Is Safari on iOS 6 caching $.ajax results?

My workaround in ASP.NET (pagemethods, webservice, etc.)

protected void Application_BeginRequest(object sender, EventArgs e)
{
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
}

Time part of a DateTime Field in SQL

SELECT DISTINCT   
                 CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108)  
FROM  
      CONSOLIDATED_LIST AS A  
WHERE   
      CONVERT(VARCHAR(17), A.SOURCE_DEPARTURE_TIME, 108) BETWEEN '15:00:00' AND '15:45:00'

How do I call Objective-C code from Swift?

  1. Create a .h file from NewFile -> Source -> header file
  2. Then save the name of file Your_Target_Name-Bridging-Header.h People here gets common mistake by taking their project name but it should be the Project's Target's name if in case both are different, generally they are same.
  3. Then in build settings search for Objective-C Bridging Header flag and put the address of your newly created bridging file, you can do it right click on the file -> show in finder -> drag the file in the text area then the address will be populated.
  4. Using #import Your_Objective-C_file.h
  5. In the swift file you can access the ObjC file but in swift language only.

Failed binder transaction when putting an bitmap dynamically in a widget

This is caused because all the changes to the RemoteViews are serialised (e.g. setInt and setImageViewBitmap ). The bitmaps are also serialised into an internal bundle. Unfortunately this bundle has a very small size limit.

You can solve it by scaling down the image size this way:

 public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight, Context context) {

 final float densityMultiplier = context.getResources().getDisplayMetrics().density;        

 int h= (int) (newHeight*densityMultiplier);
 int w= (int) (h * photo.getWidth()/((double) photo.getHeight()));

 photo=Bitmap.createScaledBitmap(photo, w, h, true);

 return photo;
 }

Choose newHeight to be small enough (~100 for every square it should take on the screen) and use it for your widget, and your problem will be solved :)

How to use terminal commands with Github?

You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.

What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".

There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests


To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).

To add new files to the repository or add changed files to staged area:

$ git add <files>

To commit them:

$ git commit

To commit unstaged but changed files:

$ git commit -a

To push to a repository (say origin):

$ git push origin

To push only one of your branches (say master):

$ git push origin master

To fetch the contents of another repository (say origin):

$ git fetch origin

To fetch only one of the branches (say master):

$ git fetch origin master

To merge a branch with the current branch (say other_branch):

$ git merge other_branch

Note that origin/master is the name of the branch you fetched in the previous step from origin. Therefore, updating your master branch from origin is done by:

$ git fetch origin master
$ git merge origin/master

You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:

Laravel - display a PDF file in storage without forcing download?

Retrieve File name first then in Blade file use anchor(a) tag like below shown. This would works for image view also.

<a href="{{ asset('storage/admission-document-uploads/' . $filename) }}" target="_black"> view Pdf </a>;

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

Try adding the drive letter:

include_path='.;c:\xampplite\php\pear\PEAR'

also verify that PEAR.php is actually there, it might be in \php\ instead:

include_path='.;c:\xampplite\php'

How to do IF NOT EXISTS in SQLite

You can also set a Constraint on a Table with the KEY fields and set On Conflict "Ignore"

When an applicable constraint violation occurs, the IGNORE resolution algorithm skips the one row that contains the constraint violation and continues processing subsequent rows of the SQL statement as if nothing went wrong. Other rows before and after the row that contained the constraint violation are inserted or updated normally. No error is returned when the IGNORE conflict resolution algorithm is used.

SQLite Documentation

Using MySQL with Entity Framework

It's been released - Get the MySQL connector for .Net v6.5 - this has support for [Entity Framework]

I was waiting for this the whole time, although the support is basic, works for most basic scenarios of db interaction. It also has basic Visual Studio integration.

UPDATE http://dev.mysql.com/downloads/connector/net/ Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).

How to grant remote access permissions to mysql server for user?

Open the /etc/mysql/mysql.conf.d/mysqld.cnf file and comment the following line:

#bind-address = 127.0.0.1

How to SELECT based on value of another SELECT

If you want to SELECT based on the value of another SELECT, then you probably want a "subselect":

http://beginner-sql-tutorial.com/sql-subquery.htm

For example, (from the link above):

  1. You want the first and last names from table "student_details" ...

  2. But you only want this information for those students in "science" class:

     SELECT id, first_name
     FROM student_details
     WHERE first_name IN (SELECT first_name
     FROM student_details
     WHERE subject= 'Science'); 
    

Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...

IMHO...

Angularjs ng-model doesn't work inside ng-if

You can use $parent to refer to the model defined in the parent scope like this

<input type="checkbox" ng-model="$parent.testb" />

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

You could specify per project how much heap space your project wants

Following is for Eclipse Helios/Juno/Kepler:

Right mouse click on

 Run As - Run Configuration - Arguments - Vm Arguments, 

then add this

-Xmx2048m

Mongoose: Find, modify, save

I wanted to add something very important. I use JohnnyHK method a lot but I noticed sometimes the changes didn't persist to the database. When I used .markModified it worked.

User.findOne({username: oldUsername}, function (err, user) {
   user.username = newUser.username;
   user.password = newUser.password;
   user.rights = newUser.rights;

   user.markModified(username)
   user.markModified(password)
   user.markModified(rights)
    user.save(function (err) {
    if(err) {
        console.error('ERROR!');
    }
});
});

tell mongoose about the change with doc.markModified('pathToYourDate') before saving.

How to remove all files from directory without removing directory in Node.js

How about run a command line:

require('child_process').execSync('rm -rf /path/to/directory/*')

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

try this code it might be useful -

<%# ((DataBinder.Eval(Container.DataItem,"ImageFilename").ToString()=="") ? "" :"<a
 href="+DataBinder.Eval(Container.DataItem, "link")+"><img
 src='/Images/Products/"+DataBinder.Eval(Container.DataItem,
 "ImageFilename")+"' border='0' /></a>")%>

Transform char array into String

Visit https://www.arduino.cc/en/Reference/StringConstructor to solve the problem easily.

This worked for me:

char yyy[6];

String xxx;

yyy[0]='h';

yyy[1]='e';

yyy[2]='l';

yyy[3]='l';

yyy[4]='o';

yyy[5]='\0';

xxx=String(yyy);

How can I rename a project folder from within Visual Studio?

I just solved this problem for myself writing a global dotnet tool (that also takes into account git+history).

Install via dotnet tool install -g ModernRonin.ProjectRenamer, use with renameproject <oldName> <newName>.

Documentation/Tinkering/PRs at

https://github.com/ModernRonin/ProjectRenamer

How to replace comma with a dot in the number (or any replacement)

You can also do it like this:

var tt="88,9827";
tt=tt.replace(",", ".");
alert(tt);

working fiddle example

Angular - How to apply [ngStyle] conditions

For a single style attribute, you can use the following syntax:

<div [style.background-color]="style1 ? 'red' : (style2 ? 'blue' : null)">

I assumed that the background color should not be set if neither style1 nor style2 is true.


Since the question title mentions ngStyle, here is the equivalent syntax with that directive:

<div [ngStyle]="{'background-color': style1 ? 'red' : (style2 ? 'blue' : null) }">

paint() and repaint() in Java

The paint() method supports painting via a Graphics object.

The repaint() method is used to cause paint() to be invoked by the AWT painting thread.

How to make <a href=""> link look like a button?

Yes you can do that.

Here is an example:

a{
    background:IMAGE-URL;
    display:block;
    height:IMAGE-HEIGHT;
    width:IMAGE-WIDTH;
}

Of course you can modify the above example to your need. The important thing is to make it appear as a block (display:block) or an inline block (display:inline-block).

Import .bak file to a database in SQL server

Instead of choosing Restore Database..., select Restore Files and Filegroups...

Then enter a database name, select your .bak file path as the source, check the restore checkbox, and click Ok. If the .bak file is valid, it will work.

(The SQL Server restore option names are not intuitive for what should a very simple task.)

How do you change the value inside of a textfield flutter?

Here is a full example where the parent widget controls the children widget. The parent widget updates the children widgets (Text and TextField) with a counter.

To update the Text widget, all you do is pass in the String parameter. To update the TextField widget, you need to pass in a controller, and set the text in the controller.

main.dart:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Update Text and TextField demo'),
        ),
        body: ParentWidget());
  }
}

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  int _counter = 0;
  String _text = 'no taps yet';
  var _controller = TextEditingController(text: 'initial value');

  void _handleTap() {
    setState(() {
      _counter = _counter + 1;
      _text = 'number of taps: ' + _counter.toString();
      _controller.text  = 'number of taps: ' + _counter.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(children: <Widget>[
        RaisedButton(
          onPressed: _handleTap,
          child: const Text('Tap me', style: TextStyle(fontSize: 20)),
        ),
        Text('$_text'),
        TextField(controller: _controller,),
      ]),
    );
  }
}

How to save a bitmap on internal storage

private static void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().getAbsolutePath();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();

    String fname = "Image-"+ o +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete ();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

How to get 'System.Web.Http, Version=5.2.3.0?

The packages you installed introduced dependencies to version 5.2.3.0 dll's as user Bracher showed above. Microsoft.AspNet.WebApi.Cors is an example package. The path I take is to update the MVC project proir to any package installs:

Install-Package Microsoft.AspNet.Mvc -Version 5.2.3

https://www.nuget.org/packages/microsoft.aspnet.mvc

Java JDBC - How to connect to Oracle using Service Name instead of SID

Try this: jdbc:oracle:thin:@oracle.hostserver2.mydomain.ca:1522/ABCD

Edit: per comment below this is actualy correct: jdbc:oracle:thin:@//oracle.hostserver2.mydomain.ca:1522/ABCD (note the //)

Here is a link to a helpful article

SSL cert "err_cert_authority_invalid" on mobile chrome only

if you're like me who is using AWS and CloudFront, here's how to solve the issue. it's similar to what others have shared except you don't use your domain's crt file, just what comodo emailed you.

cat COMODORSADomainValidationSecureServerCA.crt COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > ssl-bundle.crt

this worked for me and my site no longer displays the ssl warning on chrome in android.

How to pass parameter to click event in Jquery

 $('elements-to-match').click(function(){
        alert("The id is "+ this.id );
    });

no need to wrap it in a jquery object

Override intranet compatibility mode IE8

Try this metatag:

<meta http-equiv="X-UA-Compatible" content="IE=8" />

It should force IE8 to render as IE8 Standard Mode even if "Display intranet sites in compatibility view" is checked [either for intranet or all websites],I tried it my self on IE 8.0.6

Copy files without overwrite

Here it is in batch file form:

@echo off
set source=%1
set dest=%2
for %%f in (%source%\*) do if not exist "%dest%\%%~nxf" copy "%%f" "%dest%\%%~nxf"

How can I split a string with a string delimiter?

You are splitting a string on a fairly complex sub string. I'd use regular expressions instead of String.Split. The later is more for tokenizing you text.

For example:

var rx = new System.Text.RegularExpressions.Regex("is Marco and");
var array = rx.Split("My name is Marco and I'm from Italy");

Show div #id on click with jQuery

You can use jQuery toggle to show and hide the div. The script will be like this

  <script type="text/javascript">
    jQuery(function(){
      jQuery("#music").click(function () {
        jQuery("#musicinfo").toggle("slow");
      });
    });
</script>

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

The spatial functions in PostGIS are much more functional (i.e. not constrained to BBOX operations) than those in the MySQL spatial functions. Check it out: link text

Escaping HTML strings with jQuery

If your're going the regex route, there's an error in tghw's example above.

<!-- WON'T WORK -  item[0] is an index, not an item -->

var escaped = html; 
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g,"&gt;"], [/"/g,
"&quot;"]]

for(var item in findReplace) {
     escaped = escaped.replace(item[0], item[1]);   
}


<!-- WORKS - findReplace[item[]] correctly references contents -->

var escaped = html;
var findReplace = [[/&/g, "&amp;"], [/</g, "&lt;"], [/>/g, "&gt;"], [/"/g, "&quot;"]]

for(var item in findReplace) {
     escaped = escaped.replace(findReplace[item[0]], findReplace[item[1]]);
}

How do I vertically align text in a div?

<!DOCTYPE html>
<html>

  <head>
    <style>
      .container {
        height: 250px;
        background: #f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-align: center;
        justify-content: center;
      }
      p{
        font-size: 24px;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </body>

</html>

Android SDK Setup under Windows 7 Pro 64 bit

My problem was installing the Android SDK in Eclipse Helios on Windows 7 Enterprise 64bit, I was getting the following error:

Missing requirement: Android Development Tools 0.9.7.v201005071157-36220 (com.android.ide.eclipse.adt.feature.group 0.9.7.v201005071157-36220) requires 'org.eclipse.jdt.junit 0.0.0' but it could not be found

Having followed the advice above to ensure that the JDK was in my PATH variable (it wasn't), installation went smoothly. I guess the error was somewhat spurious (incidentally if you're looking for the JARs that correspond to that class, they were in my profile rather than the Eclipse installation directory)

So, check that PATH variable!

How to use local docker images with Minikube?

One idea would be to save the docker image locally and later load it into minikube as follows:

Let say, for example, you already have puckel/docker-airflow image.

  1. Save that image to local disk -

    docker save puckel/docker-airflow > puckel_docker_airflow.tar

  2. Now enter into minikube docker env -

    eval $(minikube docker-env)

  3. Load that locally saved image -

    docker load < puckel_docker_airflow.tar

It is that simple and it works like a charm.

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

Perhaps something like this for the first problem, you can simply access the columns by their names:

>>> df = pd.DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df[df['c']>.5][['b','e']]
          b         e
1  0.071146  0.132145
2  0.495152  0.420219

For the second problem:

>>> df[df['c']>.5][['b','e']].values
array([[ 0.07114556,  0.13214495],
       [ 0.49515157,  0.42021946]])

Plot multiple lines in one graph

The answer by @Federico Giorgi was a very good answer. It helpt me. Therefore, I did the following, in order to produce multiple lines in the same plot from the data of a single dataset, I used a for loop. Legend can be added as well.

plot(tab[,1],type="b",col="red",lty=1,lwd=2, ylim=c( min( tab, na.rm=T ),max( tab, na.rm=T ) )  )
for( i in 1:length( tab )) { [enter image description here][1]
lines(tab[,i],type="b",col=i,lty=1,lwd=2)
  } 
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

Understanding The Modulus Operator %

modulus is remainders system.

So 7 % 5 = 2.

5 % 7 = 5

3 % 7 = 3

2 % 7 = 2

1 % 7 = 1

When used inside a function to determine the array index. Is it safe programming ? That is a different question. I guess.

What does Visual Studio mean by normalize inconsistent line endings?

What that usually means is that you have lines ending with something other than a carriage return/line feed pair. It often happens when you copy and paste from a web page into the code editor.

Normalizing the line endings is just making sure that all of the line ending characters are consistent. It prevents one line from ending in \r\n and another ending with \r or \n; the first is the Windows line end pair, while the others are typically used for Mac or Linux files.

Since you're developing in Visual Studio, you'll obviously want to choose "Windows" from the drop down. :-)

What are the best practices for SQLite on Android?

Having had some issues, I think I have understood why I have been going wrong.

I had written a database wrapper class which included a close() which called the helper close as a mirror of open() which called getWriteableDatabase and then have migrated to a ContentProvider. The model for ContentProvider does not use SQLiteDatabase.close() which I think is a big clue as the code does use getWriteableDatabase In some instances I was still doing direct access (screen validation queries in the main so I migrated to a getWriteableDatabase/rawQuery model.

I use a singleton and there is the slightly ominous comment in the close documentation

Close any open database object

(my bolding).

So I have had intermittent crashes where I use background threads to access the database and they run at the same time as foreground.

So I think close() forces the database to close regardless of any other threads holding references - so close() itself is not simply undoing the matching getWriteableDatabase but force closing any open requests. Most of the time this is not a problem as the code is single threading, but in multi-threaded cases there is always the chance of opening and closing out of sync.

Having read comments elsewhere that explains that the SqLiteDatabaseHelper code instance counts, then the only time you want a close is where you want the situation where you want to do a backup copy, and you want to force all connections to be closed and force SqLite to write away any cached stuff that might be loitering about - in other words stop all application database activity, close just in case the Helper has lost track, do any file level activity (backup/restore) then start all over again.

Although it sounds like a good idea to try and close in a controlled fashion, the reality is that Android reserves the right to trash your VM so any closing is reducing the risk of cached updates not being written, but it cannot be guaranteed if the device is stressed, and if you have correctly freed your cursors and references to databases (which should not be static members) then the helper will have closed the database anyway.

So my take is that the approach is:

Use getWriteableDatabase to open from a singleton wrapper. (I used a derived application class to provide the application context from a static to resolve the need for a context).

Never directly call close.

Never store the resultant database in any object that does not have an obvious scope and rely on reference counting to trigger an implicit close().

If doing file level handling, bring all database activity to a halt and then call close just in case there is a runaway thread on the assumption that you write proper transactions so the runaway thread will fail and the closed database will at least have proper transactions rather than potentially a file level copy of a partial transaction.

SQL Server Convert Varchar to Datetime

As has been said, datetime has no format/string representational format.

You can change the string output with some formatting.

To convert your string to a datetime:

declare @date nvarchar(25) 
set @date = '2011-09-28 18:01:00' 

-- To datetime datatype
SELECT CONVERT(datetime, @date)

Gives:

-----------------------
2011-09-28 18:01:00.000

(1 row(s) affected)

To convert that to the string you want:

-- To VARCHAR of your desired format
SELECT CONVERT(VARCHAR(10), CONVERT(datetime, @date), 105) +' '+ CONVERT(VARCHAR(8), CONVERT(datetime, @date), 108)

Gives:

-------------------
28-09-2011 18:01:00

(1 row(s) affected)

Adding values to Arraylist

The second one would be preferred:

  • it avoids unnecessary/inefficient constructor calls
  • it makes you specify the element type for the list (if that is missing, you get a warning)

However, having two different types of object in the same list has a bit of a bad design smell. We need more context to speak on that.

How to disable button in React.js

I have had a similar problem, turns out we don't need hooks to do these, we can make an conditional render and it will still work fine.

<Button
    type="submit"
    disabled={
        name === "" || email === "" || password === "" ? true : false
    }
    fullWidth
    variant="contained"
    color="primary"
    className={classes.submit}>
    SignUP
</Button>

How to list only files and not directories of a directory Bash?

Just adding on to carlpett's answer. For a much useful view of the files, you could pipe the output to ls.

find . -maxdepth 1 -type f|ls -lt|less

Shows the most recently modified files in a list format, quite useful when you have downloaded a lot of files, and want to see a non-cluttered version of the recent ones.

How to change the default docker registry from docker.io to my private registry?

It turns out this is actually possible, but not using the genuine Docker CE or EE version.

You can either use Red Hat's fork of docker with the '--add-registry' flag or you can build docker from source yourself with registry/config.go modified to use your own hard-coded default registry namespace/index.

Synchronization vs Lock

If you're simply locking an object, I'd prefer to use synchronized

Example:

Lock.acquire();
doSomethingNifty(); // Throws a NPE!
Lock.release(); // Oh noes, we never release the lock!

You have to explicitly do try{} finally{} everywhere.

Whereas with synchronized, it's super clear and impossible to get wrong:

synchronized(myObject) {
    doSomethingNifty();
}

That said, Locks may be more useful for more complicated things where you can't acquire and release in such a clean manner. I would honestly prefer to avoid using bare Locks in the first place, and just go with a more sophisticated concurrency control such as a CyclicBarrier or a LinkedBlockingQueue, if they meet your needs.

I've never had a reason to use wait() or notify() but there may be some good ones.

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Put this in C2 and copy down

=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")

Then if the value in A isn't in B the cell in column C will say "not in B".

Deserializing a JSON into a JavaScript object

The whole point of JSON is that JSON strings can be converted to native objects without doing anything. Check this link

You can use either eval(string) or JSON.parse(string).

However, eval is risky. From json.org:

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

Install pip in docker

While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt and python-pip. Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    php5-mcrypt \
    python-pip

However, according to this answer you should think about installing the python3-pip package instead of the python-pip package when using Python 3.x.

Furthermore, to make the php5-mcrypt package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository command missing in the Ubuntu Docker image so I installed the package software-properties-common at first to make the command available.

Splitting up the statements and putting apt-get update and apt-get install into one RUN command is also recommended here.

Oh and by the way, you actually don't need the -y flag at apt-get update because there is nothing that has to be confirmed automatically.

Finally:

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
    apache2 \
    curl \
    git \
    libapache2-mod-php5 \
    php5 \
    php5-mcrypt \
    php5-mysql \
    python3.4 \
    python3-pip

Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.

Why my $.ajax showing "preflight is invalid redirect error"?

I had the same problem and it kept me up for days. At the end, I realised that my URL pointing to the app was wrong altogether. example:

URL: 'http://api.example.com/'
URL: 'https://api.example.com/'.

If it's http or https verify.
Check the redirecting URL and make sure it's the same thing you're passing along.

Use HTML5 to resize an image before upload

If some of you, like me, encounter orientation problems I have combined the solutions here with a exif orientation fix

https://gist.github.com/SagiMedina/f00a57de4e211456225d3114fd10b0d0

FormData.append("key", "value") is not working

In my case on Edge browser:

  const formData = new FormData(this.form);
  for (const [key, value] of formData.entries()) {
      formObject[key] = value;
  }

give me the same error

So I'm not using FormData and i just manually build an object

import React from 'react';    
import formDataToObject from 'form-data-to-object';

  ...

let formObject = {};

// EDGE compatibility -  replace FormData by
for (let i = 0; i < this.form.length; i++) {
  if (this.form[i].name) {
    formObject[this.form[i].name] = this.form[i].value;
  }
}

const data = formDataToObject.toObj(formObject): // convert "user[email]":"[email protected]" => "user":{"email":"[email protected]"}

const orderRes = await fetch(`/api/orders`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });

const order = await orderRes.json();

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

Passing a Bundle on startActivity()?

You can pass values from one activity to another activity using the Bundle. In your current activity, create a bundle and set the bundle for the particular value and pass that bundle to the intent.

Intent intent = new Intent(this,NewActivity.class);
Bundle bundle = new Bundle();
bundle.putString(key,value);
intent.putExtras(bundle);
startActivity(intent);

Now in your NewActivity, you can get this bundle and retrive your value.

Bundle bundle = getArguments();
String value = bundle.getString(key);

You can also pass data through the intent. In your current activity, set intent like this,

Intent intent = new Intent(this,NewActivity.class);
intent.putExtra(key,value);
startActivity(intent);

Now in your NewActivity, you can get that value from intent like this,

String value = getIntent().getExtras().getString(key);

Ruby: How to iterate over a range, but in set increments?

rng.step(n=1) {| obj | block } => rng

Iterates over rng, passing each nth element to the block. If the range contains numbers or strings, natural ordering is used. Otherwise step invokes succ to iterate through range elements. The following code uses class Xs, which is defined in the class-level documentation.

range = Xs.new(1)..Xs.new(10)
range.step(2) {|x| puts x}
range.step(3) {|x| puts x}

produces:

1 x
3 xxx
5 xxxxx
7 xxxxxxx
9 xxxxxxxxx
1 x
4 xxxx
7 xxxxxxx
10 xxxxxxxxxx

Reference: http://ruby-doc.org/core/classes/Range.html

......

How to bind to a PasswordBox in MVVM

I have done like:

XAML:

<PasswordBox x:Name="NewPassword" PasswordChanged="NewPassword_PasswordChanged"/>
<!--change tablenameViewSource: yours!-->
<Grid DataContext="{StaticResource tablenameViewSource}" Visibility="Hidden">
        <TextBox x:Name="Password" Text="{Binding password, Mode=TwoWay}"/>
</Grid>

C#:

private void NewPassword_PasswordChanged(object sender, RoutedEventArgs e)
    {
        try
        {
           //change tablenameDataTable: yours! and tablenameViewSource: yours!
           tablenameDataTable.Rows[tablenameViewSource.View.CurrentPosition]["password"] = NewPassword.Password;
        }
        catch
        {
            this.Password.Text = this.NewPassword.Password;
        }
    }

It works for me!

Is it possible to program iPhone in C++

Although Objective-C does indeed appear to be "insane" initially, I encourage you to stick with it. Once you have an "a-ha" moment, suddenly it all starts to make sense. For me it took about 2 weeks of focused Objective-C concentration to really understand the Cocoa frameworks, the language, and how it all fits together. But once I really "got" it, it was very very exciting.

It sounds cliché, but it's true. Stick it out.

Of course, if you're bringing in C++ libraries or existing C++ code, you can use those modules with Objective-C/Objective-C++.

Pass Model To Controller using Jquery/Ajax

//C# class

public class DashBoardViewModel 
{
    public int Id { get; set;} 
    public decimal TotalSales { get; set;} 
    public string Url { get; set;} 
     public string MyDate{ get; set;} 
}

//JavaScript file
//Create dashboard.js file
$(document).ready(function () {

    // See the html on the View below
    $('.dashboardUrl').on('click', function(){
        var url = $(this).attr("href"); 
    });

    $("#inpDateCompleted").change(function () {   

        // Construct your view model to send to the controller
        // Pass viewModel to ajax function 

        // Date
        var myDate = $('.myDate').val();

        // IF YOU USE @Html.EditorFor(), the myDate is as below
        var myDate = $('#MyDate').val();
        var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };


        $.ajax({
            type: 'GET',
            dataType: 'json',
            cache: false,
            url: '/Dashboard/IndexPartial',
            data: viewModel ,
            success: function (data, textStatus, jqXHR) {
                //Do Stuff 
                $("#DailyInvoiceItems").html(data.Id);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //Do Stuff or Nothing
            }
        });

    });
});

//ASP.NET 5 MVC 6 Controller
public class DashboardController {

    [HttpGet]
    public IActionResult IndexPartial(DashBoardViewModel viewModel )
    {
        // Do stuff with my model
        var model = new DashBoardViewModel {  Id = 23 /* Some more results here*/ };
        return Json(model);
    }
}

// MVC View 
// Include jQuerylibrary
// Include dashboard.js 
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically 

<div>
    <a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
    <input class="myDate" type="text"/>
//OR
   @Html.EditorFor(model => model.MyDate) 
</div>

How to get the name of a class without the package?

Class.getSimpleName()

Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.

The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".

It is actually stripping the package information from the name, but this is hidden from you.

How do you set, clear, and toggle a single bit?

A templated version (put in a header file) with support for changing multiple bits (works on AVR microcontrollers btw):

namespace bit {
  template <typename T1, typename T2>
  constexpr inline T1 bitmask(T2 bit) 
  {return (T1)1 << bit;}
  template <typename T1, typename T3, typename ...T2>
  constexpr inline T1 bitmask(T3 bit, T2 ...bits) 
  {return ((T1)1 << bit) | bitmask<T1>(bits...);}

  /** Set these bits (others retain their state) */
  template <typename T1, typename ...T2>
  constexpr inline void set (T1 &variable, T2 ...bits) 
  {variable |= bitmask<T1>(bits...);}
  /** Set only these bits (others will be cleared) */
  template <typename T1, typename ...T2>
  constexpr inline void setOnly (T1 &variable, T2 ...bits) 
  {variable = bitmask<T1>(bits...);}
  /** Clear these bits (others retain their state) */
  template <typename T1, typename ...T2>
  constexpr inline void clear (T1 &variable, T2 ...bits) 
  {variable &= ~bitmask<T1>(bits...);}
  /** Flip these bits (others retain their state) */
  template <typename T1, typename ...T2>
  constexpr inline void flip (T1 &variable, T2 ...bits) 
  {variable ^= bitmask<T1>(bits...);}
  /** Check if any of these bits are set */
  template <typename T1, typename ...T2>
  constexpr inline bool isAnySet(const T1 &variable, T2 ...bits) 
  {return variable & bitmask<T1>(bits...);}
  /** Check if all these bits are set */
  template <typename T1, typename ...T2>
  constexpr inline bool isSet (const T1 &variable, T2 ...bits) 
  {return ((variable & bitmask<T1>(bits...)) == bitmask<T1>(bits...));}
  /** Check if all these bits are not set */
  template <typename T1, typename ...T2>
  constexpr inline bool isNotSet (const T1 &variable, T2 ...bits) 
  {return ((variable & bitmask<T1>(bits...)) != bitmask<T1>(bits...));}
}

Example of use:

#include <iostream>
#include <bitset> // for console output of binary values

// and include the code above of course

using namespace std;

int main() {
  uint8_t v = 0b1111'1100;
  bit::set(v, 0);
  cout << bitset<8>(v) << endl;

  bit::clear(v, 0,1);
  cout << bitset<8>(v) << endl;

  bit::flip(v, 0,1);
  cout << bitset<8>(v) << endl;

  bit::clear(v, 0,1,2,3,4,5,6,7);
  cout << bitset<8>(v) << endl;

  bit::flip(v, 0,7);
  cout << bitset<8>(v) << endl;
}

BTW: It turns out that constexpr and inline is not used if not sending the optimizer argument (e.g.: -O3) to the compiler. Feel free to try the code at https://godbolt.org/ and look at the ASM output.

What does Maven do, in theory and in practice? When is it worth to use it?

Maven is a build tool. Along with Ant or Gradle are Javas tools for building.
If you are a newbie in Java though just build using your IDE since Maven has a steep learning curve.

Count items in a folder with PowerShell

In powershell you can to use severals commands, for looking for this commands digit: Get-Alias;

So the cammands the can to use are:

write-host (ls MydirectoryName).Count

or

write-host (dir MydirectoryName).Count

or

write-host (Get-ChildrenItem MydirectoryName).Count

Capture Image from Camera and Display in Activity

Here is code I have used for Capturing and Saving Camera Image then display it to imageview. You can use according to your need.

You have to save Camera image to specific location then fetch from that location then convert it to byte-array.

Here is method for opening capturing camera image activity.

private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;

private void captureCameraImage() {
        Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
        chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
        imageToUploadUri = Uri.fromFile(f);
        startActivityForResult(chooserIntent, CAMERA_PHOTO);
    }

then your onActivityResult() method should be like this.

@Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
                if(imageToUploadUri != null){
                    Uri selectedImage = imageToUploadUri;
                    getContentResolver().notifyChange(selectedImage, null);
                    Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
                    if(reducedSizeBitmap != null){
                        ImgPhoto.setImageBitmap(reducedSizeBitmap);
                        Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
                          uploadImageButton.setVisibility(View.VISIBLE);                
                    }else{
                        Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                    }
                }else{
                    Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
                }
            } 
        }

Here is getBitmap() method used in onActivityResult(). I have done all performance improvement that can be possible while getting camera capture image bitmap.

private Bitmap getBitmap(String path) {

        Uri uri = Uri.fromFile(new File(path));
        InputStream in = null;
        try {
            final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
            in = getContentResolver().openInputStream(uri);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, o);
            in.close();


            int scale = 1;
            while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
                    IMAGE_MAX_SIZE) {
                scale++;
            }
            Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);

            Bitmap b = null;
            in = getContentResolver().openInputStream(uri);
            if (scale > 1) {
                scale--;
                // scale to max possible inSampleSize that still yields an image
                // larger than target
                o = new BitmapFactory.Options();
                o.inSampleSize = scale;
                b = BitmapFactory.decodeStream(in, null, o);

                // resize to desired dimensions
                int height = b.getHeight();
                int width = b.getWidth();
                Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);

                double y = Math.sqrt(IMAGE_MAX_SIZE
                        / (((double) width) / height));
                double x = (y / height) * width;

                Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
                        (int) y, true);
                b.recycle();
                b = scaledBitmap;

                System.gc();
            } else {
                b = BitmapFactory.decodeStream(in);
            }
            in.close();

            Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
                    b.getHeight());
            return b;
        } catch (IOException e) {
            Log.e("", e.getMessage(), e);
            return null;
        }
    }

Hope it helps!

ios Upload Image and Text using HTTP POST

Upload image with form data using NSURLConnection class in Swift 2.2:

    func uploadImage(){
        let imageData = UIImagePNGRepresentation(UIImage(named: "dexter.jpg")!)

        if imageData != nil{
            let str = "https://staging.mywebsite.com/V2.9/uploadfile"
            let request = NSMutableURLRequest(URL: NSURL(string:str)!)
            request.HTTPMethod = "POST"

            let boundary = NSString(format: "---------------------------14737809831466499882746641449")

            let contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
            request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")

            let body = NSMutableData()

            // append image data to body
            body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(NSString(format:"Content-Disposition: form-data; name=\"file\"; filename=\"img.jpg\"\\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
            body.appendData(imageData!)
            body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)

            request.HTTPBody = body

            do {
                let returnData = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
                let returnString = NSString(data: returnData, encoding: NSUTF8StringEncoding)
                print("returnString = \(returnString!)")
            }
            catch let  error as NSError {
                print(error.description)
            }
        }
    }

Note: Always use sendAsynchronousRequest method instead of sendSynchronousRequest for uploading/downloading data to avoid blocking main thread. Here I used sendSynchronousRequest for testing purpose only.

Java Swing - how to show a panel on top of another panel?

Use a 1 by 1 GridLayout on the existing JPanel, then add your Panel to that JPanel. The only problem with a GridLayout that's 1 by 1 is that you won't be able to place other items on the JPanel. In this case, you will have to figure out a layout that is suitable. Each panel that you use can use their own layout so that wouldn't be a problem.

Am I understanding this question correctly?

How to add item to the beginning of List<T>?

Use the Insert method:

ti.Insert(0, initialItem);

How do I delete all the duplicate records in a MySQL table without temp tables

Instead of drop table TableA, you could delete all registers (delete from TableA;) and then populate original table with registers coming from TableA_Verify (insert into TAbleA select * from TAbleA_Verify). In this way you won't lost all references to original table (indexes,... )

CREATE TABLE TableA_Verify AS SELECT DISTINCT * FROM TableA;

DELETE FROM TableA;

INSERT INTO TableA SELECT * FROM TAbleA_Verify;

DROP TABLE TableA_Verify;

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

How to update and order by using ms sql

UPDATE messages SET 
 status=10 
WHERE ID in (SELECT TOP (10) Id FROM Table WHERE status=0 ORDER BY priority DESC);

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

Since I don't have a 50 reputation Stackoverflow wont let me comment on the second best answer. Found another trick for finding the culprit label in the Storyboard.

So once you know the id of the label, open your storyboard in a seperate tab with view controllers displayed and just do command F and command V and will take you straight to that label :)

Align labels in form next to input

You can do something like this:

HTML:

<div class='div'>
<label>Something</label>
<input type='text' class='input'/>
<div>

CSS:

.div{
      margin-bottom: 10px;
      display: grid;
      grid-template-columns: 1fr 4fr;
}

.input{
       width: 50%;
}

Hope this helps ! :)

jQuery - select all text from a textarea

Better way, with solution to tab and chrome problem and new jquery way

$("#element").on("focus keyup", function(e){

        var keycode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        if(keycode === 9 || !keycode){
            // Hacemos select
            var $this = $(this);
            $this.select();

            // Para Chrome's que da problema
            $this.on("mouseup", function() {
                // Unbindeamos el mouseup
                $this.off("mouseup");
                return false;
            });
        }
    });

Directory.GetFiles of certain extension

Doesn't the Directory.GetFiles(String, String) overload already do that? You would just do Directory.GetFiles(dir, "*.jpg", SearchOption.AllDirectories)

If you want to put them in a list, then just replace the "*.jpg" with a variable that iterates over a list and aggregate the results into an overall result set. Much clearer than individually specifying them. =)

Something like...

foreach(String fileExtension in extensionList){
    foreach(String file in Directory.GetFiles(dir, fileExtension, SearchOption.AllDirectories)){
        allFiles.Add(file);
    }
}

(If your directories are large, using EnumerateFiles instead of GetFiles can potentially be more efficient)

How to check if string contains Latin characters only?

No jQuery Needed

if (str.match(/[a-z]/i)) {
    // alphabet letters found
}

Best way to create unique token in Rails?

you can user has_secure_token https://github.com/robertomiranda/has_secure_token

is really simple to use

class User
  has_secure_token :token1, :token2
end

user = User.create
user.token1 => "44539a6a59835a4ee9d7b112b48cd76e"
user.token2 => "226dd46af6be78953bde1641622497a8"

How to remove anaconda from windows completely?

  1. Uninstall Anaconda from control Panel
  2. Delete related folders, cache data and configurations from Users/user
  3. Delete from AppData folder from hidden list
  4. To remove start menu entry -> Go to C:/ProgramsData/Microsoft/Windows/ and delete Anaconda folder or search for anaconda in start menu and right click on anaconda prompt -> Show in Folder option. This will do almost cleaning of every anaconda file on your system.

Show datalist labels but submit the actual value

Using PHP i've found a quite simple way to do this. Guys, Just Use something like this

<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
            <datalist id="customers">
                <?php 
    $querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
    $resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());

                while ($row_this = mysqli_fetch_array($resultSnamex)) {
                    echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
                    <input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
                }

                 ?>
            </datalist>

The Code Above lets the form carry the id of the option also selected.

How to make an anchor tag refer to nothing?

I know this is an old question, but I thought I'd add my two cents anyway:

It depends on what the link is going to do, but usually, I would be pointing the link at a url that could possibly be displaying/doing the same thing, for example, if you're making a little about box pop up:

<a id="about" href="/about">About</a>

Then with jQuery

$('#about').click(function(e) {
    $('#aboutbox').show();
    e.preventDefault();
});

This way, very old browsers (or browsers with JavaScript disabled) can still navigate to a separate about page, but more importantly, Google will also pick this up and crawl the contents of the about page.

Force an SVN checkout command to overwrite current files

I did not have 1.5 available to me, because I am not in control of the computer. The file that was causing me a problem happened to be a .jar file in the lib directory. Here is what I did to solve the problem:

rm -rf lib
svn up

This builds on Ned's answer. That is: I just removed the sub directory that was causing me a problem rather than the entire repository.

Get a UTC timestamp

"... that are independent of their timezone"

var timezone =  d.getTimezoneOffset() // difference in minutes from GMT

iOS UIImagePickerController result image orientation after upload

Here is an UIImage extension in Swift 2 based on the accepted answer by @Anomie. It uses a clearer switch case. It also takes the optional value returned by CGBitmapContextCreateImage() into consideration.

extension UIImage {
    func rotateImageByOrientation() -> UIImage {
        // No-op if the orientation is already correct
        guard self.imageOrientation != .Up else {
            return self
        }

        // We need to calculate the proper transformation to make the image upright.
        // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
        var transform = CGAffineTransformIdentity;

        switch (self.imageOrientation) {
        case .Down, .DownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
            transform = CGAffineTransformRotate(transform, CGFloat(M_PI))

        case .Left, .LeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0)
            transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))

        case .Right, .RightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, self.size.height)
            transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))

        default:
            break
        }

        switch (self.imageOrientation) {
        case .UpMirrored, .DownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0)
            transform = CGAffineTransformScale(transform, -1, 1)

        case .LeftMirrored, .RightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0)
            transform = CGAffineTransformScale(transform, -1, 1)

        default:
            break
        }

        // Now we draw the underlying CGImage into a new context, applying the transform
        // calculated above.
        let ctx = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height),
            CGImageGetBitsPerComponent(self.CGImage), 0,
            CGImageGetColorSpace(self.CGImage),
            CGImageGetBitmapInfo(self.CGImage).rawValue)
        CGContextConcatCTM(ctx, transform)
        switch (self.imageOrientation) {
        case .Left, .LeftMirrored, .Right, .RightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage)

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage)
        }

        // And now we just create a new UIImage from the drawing context
        if let cgImage = CGBitmapContextCreateImage(ctx) {
            return UIImage(CGImage: cgImage)
        } else {
            return self
        }
    }
}

Why does my 'git branch' have no master?

if it is a new repo you've cloned, it may still be empty, in which case:

git push -u origin master

should likely sort it out.

(did in my case. not sure this is the same issue, thought i should post this just incase. might help others.)

List all of the possible goals in Maven 2?

Strange nobody listed an actual command to do it:

mvn help:describe -e -Dplugin=site

If you want to list all goals of the site plugin. Output:

Name: Apache Maven Site Plugin Description: The Maven Site Plugin is a plugin that generates a site for the current project. Group Id: org.apache.maven.plugins Artifact Id: maven-site-plugin Version: 3.7.1 Goal Prefix: site

This plugin has 9 goals:

site:attach-descriptor Description: Adds the site descriptor (site.xml) to the list of files to be installed/deployed. For Maven-2.x this is enabled by default only when the project has pom packaging since it will be used by modules inheriting, but this can be enabled for other projects packaging if needed. This default execution has been removed from the built-in lifecycle of Maven 3.x for pom-projects. Users that actually use those projects to provide a common site descriptor for sub modules will need to explicitly define this goal execution to restore the intended behavior.

site:deploy Description: Deploys the generated site using wagon supported protocols to the site URL specified in the section of the POM. For scp protocol, the website files are packaged by wagon into zip archive, then the archive is transfered to the remote host, next it is un-archived which is much faster than making a file by file copy.

site:effective-site Description: Displays the effective site descriptor as an XML for this build, after inheritance and interpolation of site.xml, for the first locale.

site:help Description: Display help information on maven-site-plugin. Call mvn site:help -Ddetail=true -Dgoal= to display parameter details.

site:jar Description: Bundles the site output into a JAR so that it can be deployed to a repository.

site:run Description: Starts the site up, rendering documents as requested for faster editing. It uses Jetty as the web server.

site:site Description: Generates the site for a single project. Note that links between module sites in a multi module build will not work, since local build directory structure doesn't match deployed site.

site:stage Description: Deploys the generated site to a local staging or mock directory based on the site URL specified in the section of the POM. It can be used to test that links between module sites in a multi-module build work.

This goal requires the site to already have been generated using the site goal, such as by calling mvn site.

site:stage-deploy Description: Deploys the generated site to a staging or mock URL to the site URL specified in the section of the POM, using wagon supported protocols

For more information, run 'mvn help:describe [...] -Ddetail'

More details on https://mkyong.com/maven/how-to-display-maven-plugin-goals-and-parameters/

how to define variable in jquery

You can also use text() to set or get the text content of selected elements

var text1 = $("#idName").text();

Bootstrap 3 Multi-column within a single ul not floating properly

Thanks, Varun Rathore. It works perfectly!

For those who want graceful collapse from 4 items per row to 2 items per row depending on the screen width:

<ul class="list-group row">
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_1</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_2</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_3</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_4</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_5</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_6</li>
    <li class="list-group-item col-xs-6 col-sm-4 col-md-3">Cell_7</li>
</ul>

Fatal error: Call to undefined function mcrypt_encrypt()

Under Ubuntu I had the problem and solved it with

$ sudo apt-get install php5-mcrypt
$ sudo service apache2 reload

Replacing a fragment with another fragment inside activity group

I change fragment dynamically in single line code
It is work in any SDK version and androidx
I use navigation as BottomNavigationView

    BottomNavigationView btn_nav;
    FragmentFirst fragmentFirst;
    FragmentSecond fragmentSecond;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        fragmentFirst = new FragmentFirst();
        fragmentSecond = new FragmentSecond ();
        changeFragment(fragmentFirst); // at first time load the fragmentFirst
        btn_nav = findViewById(R.id.bottomNav);
        btn_nav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch(menuItem.getItemId()){
                    case R.id.menu_first_frag:
                        changeFragment(fragmentFirst); // change fragmentFirst
                        break;
                    case R.id.menu_second_frag:
                        changeFragment(fragmentSecond); // change fragmentSecond
                        break;
                        default:
                            Toast.makeText(SearchActivity.this, "Click on wrong bottom SORRY!", Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }
public void changeFragment(Fragment fragment) {
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout_changer, fragment).commit();
    }

Adjust table column width to content size

maybe problem with margin?

width:auto;
padding: 0px;
margin: 0px

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

Cleaning the project solved my problem.

Steps: Product -> Clean(or Shift + Cmd + K)

Creating a procedure in mySql with parameters

(IN @brugernavn varchar(64)**)**,IN @password varchar(64))

The problem is the )

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

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

" ".join(my_list)

you need to join with a space not an empty string ...

Angular ng-repeat add bootstrap row every 3 or 4 cols

The top voted answer, while effective, is not what I would consider to be the angular way, nor is it using bootstrap's own classes that are meant to deal with this situation. As @claies mentioned, the .clearfix class is meant for situations such as these. In my opinion, the cleanest implementation is as follows:

<div class="row">
    <div ng-repeat="product in products">
        <div class="clearfix" ng-if="$index % 3 == 0"></div>
        <div class="col-sm-4">
            <h2>{{product.title}}</h2>
        </div>
    </div>
</div>

This structure avoids messy indexing of the products array, allows for clean dot notation, and makes use of the clearfix class for its intended purpose.

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You don't always want your instance variables to be fully accessible from outside of the class. There are plenty of cases where allowing read access to an instance variable makes sense, but writing to it might not (e.g. a model that retrieves data from a read-only source). There are cases where you want the opposite, but I can't think of any that aren't contrived off the top of my head.

Environ Function code samples for VBA

Environ() gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:

set

If you wanted to get the username, you would do:

Environ("username")

If you wanted to get the fully qualified name, you would do:

Environ("userdomain") & "\" & Environ("username")

References

How to make background of table cell transparent

What is this? :)

background-color: #D8F0DA;

Try

 background: none

And override works only if property is exactly the same.

background doesn't override background-color.

If you want alpha transparency, then use something like this

background: rgba(100, 100, 100, 0.5);

ImportError: cannot import name NUMPY_MKL

I recently got the same error when trying to load scipy in jupyter (python3.x, win10), although just having upgraded to numpy-1.13.3+mkl through pip. The solution was to simply upgrade the scipy package (from v0.19 to v1.0.0).

Filter items which array contains any of given values

There's also terms query which should save you some work. Here example from docs:

{
  "terms" : {
      "tags" : [ "blue", "pill" ],
      "minimum_should_match" : 1
  }
}

Under hood it constructs boolean should. So it's basically the same thing as above but shorter.

There's also a corresponding terms filter.

So to summarize your query could look like this:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "terms": {
        "tags": ["c", "d"]
      }
    }
  }
}

With greater number of tags this could make quite a difference in length.

how to assign a block of html code to a javascript variable

you can make a javascript object with key being name of the html snippet, and value being an array of html strings, that are joined together.

var html = {
  top_crimes_template:
    [
      '<div class="top_crimes"><h3>Top Crimes</h3></div>',
      '<table class="crimes-table table table-responsive table-bordered">',
        '<tr>',
          '<th>',
            '<span class="list-heading">Crime:</span>',
          '</th>',
          '<th>',
            '<span id="last_crime_span"># Arrests</span>',
          '</th>',
        '</tr>',
      '</table>'
    ].join(""),
  top_teams_template:
    [
      '<div class="top_teams"><h3>Top Teams</h3></div>',
      '<table class="teams-table table table-responsive table-bordered">',
        '<tr>',
          '<th>',
            '<span class="list-heading">Team:</span>',
          '</th>',
          '<th>',
            '<span id="last_team_span"># Arrests</span>',
          '</th>',
        '</tr>',
      '</table>'
    ].join(""),
  top_players_template:
    [
      '<div class="top_players"><h3>Top Players</h3></div>',
      '<table class="players-table table table-responsive table-bordered">',
        '<tr>',
          '<th>',
            '<span class="list-heading">Players:</span>',
          '</th>',
          '<th>',
            '<span id="last_player_span"># Arrests</span>',
          '</th>',
        '</tr>',
      '</table>'
    ].join("")
};

Google Maps: How to create a custom InfoWindow?

You can even append your own css class on the popup container/canvas or how do you want. Current google maps 3.7 has popups styled by canvas element which prepends popup div container in code. So at googlemaps 3.7 You can get into rendering process by popup's domready event like this:

var popup = new google.maps.InfoWindow();
google.maps.event.addListener(popup, 'domready', function() {
  if (this.content && this.content.parentNode && this.content.parentNode.parentNode) {
    if (this.content.parentNode.parentNode.previousElementSibling) {
      this.content.parentNode.parentNode.previousElementSibling.className = 'my-custom-popup-container-css-classname';
    }
  }
});

element.previousElementSibling is not present at IE8- so if you want to make it work at it, follow this.

check the latest InfoWindow reference for events and more..

I found this most clean in some cases.

how to change the dist-folder path in angular-cli after 'ng build'

Angular CLI now uses environment files to do this.

First, add an environments section to the angular-cli.json

Something like :

{
  "apps": [{
      "environments": {
        "prod": "environments/environment.prod.ts"
      }
    }]
}

And then inside the environment file (environments/environment.prod.ts in this case), add something like :

export const environment = {
  production: true,
  "output-path": "./whatever/dist/"
};

now when you run :

ng build --prod

it will output to the ./whatever/dist/ folder.

How to query a MS-Access Table from MS-Excel (2010) using VBA

Option Explicit

Const ConnectionStrngAccessPW As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB-PW.accdb;
Jet OLEDB:Database Password=123pass;"

Const ConnectionStrngAccess As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB.accdb;
Persist Security Info=False;"

'C:\Users\BARON\Desktop\Test.accdb

Sub ModifyingExistingDataOnAccessDB()

    Dim TableConn As ADODB.Connection
    Dim TableData As ADODB.Recordset


    Set TableConn = New ADODB.Connection
    Set TableData = New ADODB.Recordset

    TableConn.ConnectionString = ConnectionStrngAccess

    TableConn.Open

On Error GoTo CloseConnection

    With TableData
        .ActiveConnection = TableConn
        '.Source = "SELECT Emp_Age FROM Roster WHERE Emp_Age > 40;"
        .Source = "Roster"
        .LockType = adLockOptimistic
        .CursorType = adOpenForwardOnly
        .Open
        On Error GoTo CloseRecordset

            Do Until .EOF
                If .Fields("Emp_Age").Value > 40 Then
                    .Fields("Emp_Age").Value = 40
                    .Update
                End If
                .MoveNext
            Loop
            .MoveFirst

        MsgBox "Update Complete"
    End With


CloseRecordset:
    TableData.CancelUpdate
    TableData.Close

CloseConnection:
    TableConn.Close

    Set TableConn = Nothing
    Set TableData = Nothing

End Sub

Sub AddingDataToAccessDB()

    Dim TableConn As ADODB.Connection
    Dim TableData As ADODB.Recordset
    Dim r As Range

    Set TableConn = New ADODB.Connection
    Set TableData = New ADODB.Recordset

    TableConn.ConnectionString = ConnectionStrngAccess

    TableConn.Open

On Error GoTo CloseConnection

    With TableData
        .ActiveConnection = TableConn
        .Source = "Roster"
        .LockType = adLockOptimistic
        .CursorType = adOpenForwardOnly
        .Open
        On Error GoTo CloseRecordset

        Sheet3.Activate
        For Each r In Range("B3", Range("B3").End(xlDown))

            MsgBox "Adding " & r.Offset(0, 1)
            .AddNew
            .Fields("Emp_ID").Value = r.Offset(0, 0).Value
            .Fields("Emp_Name").Value = r.Offset(0, 1).Value
            .Fields("Emp_DOB").Value = r.Offset(0, 2).Value
            .Fields("Emp_SOD").Value = r.Offset(0, 3).Value
            .Fields("Emp_EOD").Value = r.Offset(0, 4).Value
            .Fields("Emp_Age").Value = r.Offset(0, 5).Value
            .Fields("Emp_Gender").Value = r.Offset(0, 6).Value
            .Update

        Next r

        MsgBox "Update Complete"
    End With


CloseRecordset:
    TableData.Close

CloseConnection:
    TableConn.Close

    Set TableConn = Nothing
    Set TableData = Nothing

End Sub

How to convert Windows end of line in Unix end of line (CR/LF to LF)

In order to overcome

Ambiguous output in step `CR-LF..data'

simply solution might be to add -f flag to force conversion.

Insert data into a view (SQL Server)

Inserting 'test' to name will lead to inserting NULL values to other columns of the base table which wont be correct as Id is a PRIMARY KEY and it cannot have NULL value.

Right way to write JSON deserializer in Spring or extend it

I was trying to @Autowire a Spring-managed service into my Deserializer. Somebody tipped me off to Jackson using the new operator when invoking the serializers/deserializers. This meant no auto-wiring of Jackson's instance of my Deserializer. Here's how I was able to @Autowire my service class into my Deserializer:

context.xml

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="objectMapper" ref="objectMapper" />
    </bean>
  </mvc:message-converters>
</mvc>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <!-- Add deserializers that require autowiring -->
    <property name="deserializersByType">
        <map key-type="java.lang.Class">
            <entry key="com.acme.Anchor">
                <bean class="com.acme.AnchorDeserializer" />
            </entry>
        </map>
    </property>
</bean>

Now that my Deserializer is a Spring-managed bean, auto-wiring works!

AnchorDeserializer.java

public class AnchorDeserializer extends JsonDeserializer<Anchor> {
    @Autowired
    private AnchorService anchorService;
    public Anchor deserialize(JsonParser parser, DeserializationContext context)
             throws IOException, JsonProcessingException {
        // Do stuff
    }
}

AnchorService.java

@Service
public class AnchorService {}

Update: While my original answer worked for me back when I wrote this, @xi.lin's response is exactly what is needed. Nice find!

Select from one table where not in another

So there's loads of posts on the web that show how to do this, I've found 3 ways, same as pointed out by Johan & Sjoerd. I couldn't get any of these queries to work, well obviously they work fine it's my database that's not working correctly and those queries all ran slow.

So I worked out another way that someone else may find useful:

The basic jist of it is to create a temporary table and fill it with all the information, then remove all the rows that ARE in the other table.

So I did these 3 queries, and it ran quickly (in a couple moments).

CREATE TEMPORARY TABLE

`database1`.`newRows`

SELECT

`t1`.`id` AS `columnID`

FROM

`database2`.`table` AS `t1`

.

CREATE INDEX `columnID` ON `database1`.`newRows`(`columnID`)

.

DELETE FROM `database1`.`newRows`

WHERE

EXISTS(
    SELECT `columnID` FROM `database1`.`product_details` WHERE `columnID`=`database1`.`newRows`.`columnID`
)

SELECT inside a COUNT

Use SELECT COUNT(*) FROM t WHERE a = current_a AND c = 'const' ) as d.

What is the easiest way to get the current day of the week in Android?

Calendar.getInstance().get(Calendar.DAY_OF_WEEK)

or

new GregorianCalendar().get(Calendar.DAY_OF_WEEK);

Just the same as in Java, nothing particular to Android.

Truncate all tables in a MySQL database in one command?

SET FOREIGN_KEY_CHECKS = 0;

SELECT @str := CONCAT('TRUNCATE TABLE ', table_schema, '.', table_name, ';')
FROM   information_schema.tables
WHERE  table_type   = 'BASE TABLE'
  AND  table_schema IN ('db1_name','db2_name');

PREPARE stmt FROM @str;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;

SET FOREIGN_KEY_CHECKS = 1;

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

declare
   z exception;

begin
   if to_char(sysdate,'day')='sunday' then
     raise z;
   end if;

   exception 
     when z then
        dbms_output.put_line('to day is sunday');
end;

Node.js on multi-core machines

The cluster module allows you to utilise all cores of your machine. In fact you can take advantage of this in just 2 commands and without touching your code using a very popular process manager pm2.

npm i -g pm2
pm2 start app.js -i max

How to check for changes on remote (origin) Git repository

git status does not always show the difference between master and origin/master even after a fetch.

If you want the combination git fetch origin && git status to work, you need to specify the tracking information between the local branch and origin:

# git branch --set-upstream-to=origin/<branch> <branch>

For the master branch:

git branch --set-upstream-to=origin/master master

How do I use a regular expression to match any string, but at least 3 characters?

This is python regex, but it probably works in other languages that implement it, too.

I guess it depends on what you consider a character to be. If it's letters, numbers, and underscores:

\w{3,}

if just letters and digits:

[a-zA-Z0-9]{3,}

Python also has a regex method to return all matches from a string.

>>> import re
>>> re.findall(r'\w{3,}', 'This is a long string, yes it is.')
['This', 'long', 'string', 'yes']

What’s the best way to load a JSONObject from a json text file?

Another way of doing the same could be using the Gson Class

String filename = "path/to/file/abc.json";
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(filename));
SampleClass data = gson.fromJson(reader, SampleClass.class);

This will give an object obtained after parsing the json string to work with.

SET NAMES utf8 in MySQL?

From the manual:

SET NAMES indicates what character set the client will use to send SQL statements to the server.

More elaborately, (and once again, gratuitously lifted from the manual):

SET NAMES indicates what character set the client will use to send SQL statements to the server. Thus, SET NAMES 'cp1251' tells the server, “future incoming messages from this client are in character set cp1251.” It also specifies the character set that the server should use for sending results back to the client. (For example, it indicates what character set to use for column values if you use a SELECT statement.)

How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

Ubuntu uses AppArmor and that is whats preventing you from accessing /data/. Fedora uses selinux and that would prevent this on a RHEL/Fedora/CentOS machine.

To modify AppArmor to allow MySQL to access /data/ do the follow:

sudo gedit /etc/apparmor.d/usr.sbin.mysqld

add this line anywhere in the list of directories:

/data/ rw,

then do a :

sudo /etc/init.d/apparmor restart

Another option is to disable AppArmor for mysql altogether, this is NOT RECOMMENDED:

sudo mv /etc/apparmor.d/usr.sbin.mysqld /etc/apparmor.d/disable/

Don't forget to restart apparmor:

sudo /etc/init.d/apparmor restart

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

With PYTHONPATH set as in your example, you should be able to do

python -m gmbx

-m option will make Python search for your module in paths Python usually searches modules in, including what you added to PYTHONPATH. When you run interpreter like python gmbx.py, it looks for particular file and PYTHONPATH does not apply.

Control the dashed border stroke length and distance between strokes

This will make an orange and gray border using the class="myclass" on the div.

.myclass {
    outline:dashed darkorange  12px;
    border:solid slategray  14px;
    outline-offset:-14px;
}

Convert byte[] to char[]

You must know the source encoding.

string someText = "The quick brown fox jumps over the lazy dog.";
byte[] bytes = Encoding.Unicode.GetBytes(someText);
char[] chars = Encoding.Unicode.GetChars(bytes);

Check for null variable in Windows batch

rem set defaults:
set filename1="c:\file1.txt"
set filename2="c:\file2.txt"
set filename3="c:\file3.txt"
rem set parameters:
IF NOT "a%1"=="a" (set filename1="%1")
IF NOT "a%2"=="a" (set filename2="%2")
IF NOT "a%3"=="a" (set filename1="%3")
echo %filename1%, %filename2%, %filename3%

Be careful with quotation characters though, you may or may not need them in your variables.

Is it possible to use an input value attribute as a CSS selector?

Yes, but note: since the attribute selector (of course) targets the element's attribute, not the DOM node's value property (elem.value), it will not update while the form field is being updated.

Otherwise (with some trickery) I think it could have been used to make a CSS-only substitute for the "placeholder" attribute/functionality. Maybe that's what the OP was after? :)

Change multiple files

You could use grep and sed together. This allows you to search subdirectories recursively.

Linux: grep -r -l <old> * | xargs sed -i 's/<old>/<new>/g'
OS X: grep -r -l <old> * | xargs sed -i '' 's/<old>/<new>/g'

For grep:
    -r recursively searches subdirectories 
    -l prints file names that contain matches
For sed:
    -i extension (Note: An argument needs to be provided on OS X)

Test for multiple cases in a switch, like an OR (||)

Forget switch and break, lets play with if. And instead of asserting

if(pageid === "listing-page" || pageid === "home-page")

lets create several arrays with cases and check it with Array.prototype.includes()

var caseA = ["listing-page", "home-page"];
var caseB = ["details-page", "case04", "case05"];

if(caseA.includes(pageid)) {
    alert("hello");
}
else if (caseB.includes(pageid)) {
    alert("goodbye");
}
else {
    alert("there is no else case");
}

Convert Uppercase Letter to Lowercase and First Uppercase in Sentence using CSS

If use this on capitalized text;

p text-transform: lowercase;

Then show the text, it is lowercase but if you copy that lower-cased text, and paste it, it change back to original capitalized.

Start new Activity and finish current one in Android?

Use finish like this:

Intent i = new Intent(Main_Menu.this, NextActivity.class);
finish();  //Kill the activity from which you will go to next activity 
startActivity(i);

FLAG_ACTIVITY_NO_HISTORY you can use in case for the activity you want to finish. For exampe you are going from A-->B--C. You want to finish activity B when you go from B-->C so when you go from A-->B you can use this flag. When you go to some other activity this activity will be automatically finished.

To learn more on using Intent.FLAG_ACTIVITY_NO_HISTORY read: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_NO_HISTORY

Hibernate SessionFactory vs. JPA EntityManagerFactory

I want to add on this that you can also get Hibernate's session by calling getDelegate() method from EntityManager.

ex:

Session session = (Session) entityManager.getDelegate();

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I've updated com.google.gms:google-services from 3.1.1 to 3.2.0 and the warning stopped appearing.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files

    classpath 'com.google.gms:google-services:3.2.0'
    }
}

Understanding __getitem__ method

The [] syntax for getting item by key or index is just syntax sugar.

When you evaluate a[i] Python calls a.__getitem__(i) (or type(a).__getitem__(a, i), but this distinction is about inheritance models and is not important here). Even if the class of a may not explicitly define this method, it is usually inherited from an ancestor class.

All the (Python 2.7) special method names and their semantics are listed here: https://docs.python.org/2.7/reference/datamodel.html#special-method-names

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

If it is still not working after giving permissions try running these commands:

mkdir ~/.npm-global

npm config set prefix '~/.npm-global'

export PATH=~/.npm-global/bin:$PATH

source ~/.profile

and finally test with this command

npm install -g jshint

This does not work for Windows.

Detect click inside/outside of element with single event handler

This question can be answered with X and Y coordinates and without JQuery:

       var isPointerEventInsideElement = function (event, element) {
            var pos = {
                x: event.targetTouches ? event.targetTouches[0].pageX : event.pageX,
                y: event.targetTouches ? event.targetTouches[0].pageY : event.pageY
            };
            var rect = element.getBoundingClientRect();
            return  pos.x < rect.right && pos.x > rect.left && pos.y < rect.bottom && pos.y > rect.top;
        };

        document.querySelector('#my-element').addEventListener('click', function (event) {
           console.log(isPointerEventInsideElement(event, document.querySelector('#my-any-child-element')))
        });

How can I kill all sessions connecting to my oracle database?

I've been using something like this for a while to kill my sessions on a shared server. The first line of the 'where' can be removed to kill all non 'sys' sessions:

BEGIN
  FOR c IN (
      SELECT s.sid, s.serial#
      FROM v$session s
      WHERE (s.Osuser = 'MyUser' or s.MACHINE = 'MyNtDomain\MyMachineName')
      AND s.USERNAME <> 'SYS'
      AND s.STATUS <> 'KILLED'
  )
  LOOP
      EXECUTE IMMEDIATE 'alter system kill session ''' || c.sid || ',' || c.serial# || '''';
  END LOOP;
END;

difference between variables inside and outside of __init__()

Example code:

class inside:
    def __init__(self):
        self.l = []

    def insert(self, element):
        self.l.append(element)


class outside:
    l = []             # static variable - the same for all instances

    def insert(self, element):
        self.l.append(element)


def main():
    x = inside()
    x.insert(8)
    print(x.l)      # [8]
    y = inside()
    print(y.l)      # []
    # ----------------------------
    x = outside()
    x.insert(8)
    print(x.l)      # [8]
    y = outside()
    print(y.l)      # [8]           # here is the difference


if __name__ == '__main__':
    main()

Adding calculated column(s) to a dataframe in pandas

The exact code will vary for each of the columns you want to do, but it's likely you'll want to use the map and apply functions. In some cases you can just compute using the existing columns directly, since the columns are Pandas Series objects, which also work as Numpy arrays, which automatically work element-wise for usual mathematical operations.

>>> d
    A   B  C
0  11  13  5
1   6   7  4
2   8   3  6
3   4   8  7
4   0   1  7
>>> (d.A + d.B) / d.C
0    4.800000
1    3.250000
2    1.833333
3    1.714286
4    0.142857
>>> d.A > d.C
0     True
1     True
2     True
3    False
4    False

If you need to use operations like max and min within a row, you can use apply with axis=1 to apply any function you like to each row. Here's an example that computes min(A, B)-C, which seems to be like your "lower wick":

>>> d.apply(lambda row: min([row['A'], row['B']])-row['C'], axis=1)
0    6
1    2
2   -3
3   -3
4   -7

Hopefully that gives you some idea of how to proceed.

Edit: to compare rows against neighboring rows, the simplest approach is to slice the columns you want to compare, leaving off the beginning/end, and then compare the resulting slices. For instance, this will tell you for which rows the element in column A is less than the next row's element in column C:

d['A'][:-1] < d['C'][1:]

and this does it the other way, telling you which rows have A less than the preceding row's C:

d['A'][1:] < d['C'][:-1]

Doing ['A"][:-1] slices off the last element of column A, and doing ['C'][1:] slices off the first element of column C, so when you line these two up and compare them, you're comparing each element in A with the C from the following row.

Does WhatsApp offer an open API?

  1. is the correct answer. WhatsApp is intentionally a closed system without an API for external access.

There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.

For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).

What's the difference between '$(this)' and 'this'?

Yes you only need $() when you're using jQuery. If you want jQuery's help to do DOM things just keep this in mind.

$(this)[0] === this

Basically every time you get a set of elements back jQuery turns it into a jQuery object. If you know you only have one result, it's going to be in the first element.

$("#myDiv")[0] === document.getElementById("myDiv");

And so on...

How to make UIButton's text alignment center? Using IB

Try Like this :

yourButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
yourButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

SQL Server copy all rows from one table into another i.e duplicate table

select * into x_history from your_table_here;
truncate table your_table_here;

How to set default values in Rails?

You can override the constructor for the ActiveRecord model.

Like this:

def initialize(*args)
  super(*args)
  self.attribute_that_needs_default_value ||= default_value
  self.attribute_that_needs_another_default_value ||= another_default_value
  #ad nauseum
end

How do I find all files containing specific text on Linux?

Do the following:

grep -rnw '/path/to/somewhere/' -e 'pattern'
  • -r or -R is recursive,
  • -n is line number, and
  • -w stands for match the whole word.
  • -l (lower-case L) can be added to just give the file name of matching files.
  • -e is the pattern used during the search

Along with these, --exclude, --include, --exclude-dir flags could be used for efficient searching:

  • This will only search through those files which have .c or .h extensions:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
  • This will exclude searching all the files ending with .o extension:
grep --exclude=\*.o -rnw '/path/to/somewhere/' -e "pattern"
  • For directories it's possible to exclude one or more directories using the --exclude-dir parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"

This works very well for me, to achieve almost the same purpose like yours.

For more options check man grep.

Getting value from JQUERY datepicker

You could do it as follows - with validation just to ensure that the datepicker is bound to the element.

var dt;

if ($("div#someID").is('.hasDatepicker')) {
    dt = $("div#someID").datepicker('getDate');
}

Disabling radio buttons with jQuery

code:

function writeData() {
    jQuery("#chatTickets input:radio[id^=ticketID]:first").attr('disabled', true);
    return false;
}

See also: Selector/radio, Selector/attributeStartsWith, Selector/first

Regex to match words of a certain length

Length of characters to be matched.

{n,m}  n <= length <= m
{n}    length == n
{n,}   length >= n

And by default, the engine is greedy to match this pattern. For example, if the input is 123456789, \d{2,5} will match 12345 which is with length 5.

If you want the engine returns when length of 2 matched, use \d{2,5}?

The term "Add-Migration" is not recognized

These are the steps I followed and it solved the problem

1)Upgraded my Power shell from version 2 to 3

2)Closed the PM Console

3)Restarted Visual Studio

4)Ran the below command in PM Console dotnet restore

5)Add-Migration InitialMigration

It worked !!!

Mailto on submit button

Or you can create a form with action:mailto

<form action="mailto:[email protected]"> 

check this out.

http://webdesign.about.com/od/forms/a/aa072699mailto.htm

But this actually submits a form via email.Is this what you wanted? You can also use just

<button onclick=""> and then some javascript with it to ahieve this.

And you can make a <a> look like button. There can be a lot of ways to work this around. Do a little search.

ImageView - have height match width?

Here's how I solved that problem:

int pHeight =  picture.getHeight();
int pWidth = picture.getWidth();
int vWidth = preview.getWidth();
preview.getLayoutParams().height = (int)(vWidth*((double)pHeight/pWidth));

preview - imageView with width setted to "match_parent" and scaleType to "cropCenter"

picture - Bitmap object to set in imageView src.

That's works pretty well for me.

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

If you want to make them a lot bigger, like for multiple lines of input, you may want to use a textarea tag instead of the input tag. This allows you to put in number of rows and columns you want on your textarea without messing with css (e.g. <textarea rows="2" cols="25"></textarea>).

Text areas are resizable by default. If you want to disable that, just use the resize css rule:

#signin textarea {
    resize: none;
}

A simple solution to your question about default text that disappears when the user clicks is to use the placeholder attribute. This will work for <input> tags as well.

<textarea rows="2" cols="25" placeholder="This is the default text"></textarea>

This text will disappear when the user enters information rather than when they click, but that is common functionality for this kind of thing.

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

How to run JUnit test cases from the command line

Alternatively you can use the following methods in JunitCore class http://junit.sourceforge.net/javadoc/org/junit/runner/JUnitCore.html

run (with Request , Class classes and Runner) or runClasses from your java file.

Re-enabling window.alert in Chrome

In Chrome Browser go to setting , clear browsing history and then reload the page

CSS Printing: Avoiding cut-in-half DIVs between pages?

@media print{
    /* use your css selector */    
    div{ 
        page-break-inside: avoid;
    }
}

For all new browser this solution works. See caniuse.com/#search=page-break-inside

When to use React "componentDidUpdate" method?

When something in the state has changed and you need to call a side effect (like a request to api - get, put, post, delete). So you need to call componentDidUpdate() because componentDidMount() is already called.

After calling side effect in componentDidUpdate(), you can set the state to new value based on the response data in the then((response) => this.setState({newValue: "here"})). Please make sure that you need to check prevProps or prevState to avoid infinite loop because when setting state to a new value, the componentDidUpdate() will call again.

There are 2 places to call a side effect for best practice - componentDidMount() and componentDidUpdate()

Remove last characters from a string in C#. An elegant way?

Use lastIndexOf. Like:

string var = var.lastIndexOf(',');

WCF error - There was no endpoint listening at

You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding, and the default value for securityMode\transport for that binding is Message.

Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration attribute:

<bindings>
  <wsHttpBinding>
    <binding name="ota2010AEndpoint" 
             .......>
      <readerQuotas maxDepth="32" ... />
        <reliableSession ordered="true" .... />
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None"
                       realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
                     establishSecurityContext="true" />
          </security>
    </binding>
  </wsHttpBinding>
</bindings>    

(Snipped parts of the config to save space in the answer).

<service name="Synxis" behaviorConfiguration="SynxisWCF">
    <endpoint address="" name="wsHttpEndpoint" 
              binding="wsHttpBinding" 
              bindingConfiguration="ota2010AEndpoint"
              contract="Synxis" />

This will then assign your defined binding (with Transport security) to the endpoint.

OpenCV - Saving images to a particular folder of choice

You can do it with OpenCV's function imwrite:

import cv2
cv2.imwrite('Path/Image.jpg', image_name)