Programs & Examples On #Glow

CSS/HTML: Create a glowing border around an Input Field

_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').focus(function() {_x000D_
    $(this).parent().addClass('open');_x000D_
});_x000D_
_x000D_
$('.form-fild input,.form-fild textarea').blur(function() {_x000D_
    $(this).parent().removeClass('open');_x000D_
});
_x000D_
.open {_x000D_
  color:red;   _x000D_
}_x000D_
.form-fild {_x000D_
 position: relative;_x000D_
 margin: 30px 0;_x000D_
}_x000D_
.form-fild label {_x000D_
 position: absolute;_x000D_
 top: 5px;_x000D_
 left: 10px;_x000D_
 padding:5px;_x000D_
}_x000D_
_x000D_
.form-fild.open label {_x000D_
 top: -25px;_x000D_
 left: 10px;_x000D_
 /*background: #ffffff;*/_x000D_
}_x000D_
.form-fild input[type="text"] {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild textarea {_x000D_
 padding-left: 80px;_x000D_
}_x000D_
.form-fild.open textarea, _x000D_
.form-fild.open input[type="text"] {_x000D_
 padding-left: 10px;_x000D_
}_x000D_
textarea,_x000D_
input[type="text"] {_x000D_
 padding: 10px;_x000D_
 width: 100%;_x000D_
}_x000D_
textarea,_x000D_
input,_x000D_
.form-fild.open label,_x000D_
.form-fild label {_x000D_
 -webkit-transition: all 0.2s ease-in-out;_x000D_
       -moz-transition: all 0.2s ease-in-out;_x000D_
         -o-transition: all 0.2s ease-in-out;_x000D_
            transition: all 0.2s ease-in-out;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
 <div class="row">_x000D_
     <form>_x000D_
        <div class="form-fild">_x000D_
            <label>Name :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Email :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Number :</label>_x000D_
            <input type="text">_x000D_
        </div>_x000D_
        <div class="form-fild">_x000D_
            <label>Message :</label>_x000D_
            <textarea cols="10" rows="5"></textarea>_x000D_
        </div>_x000D_
    </form>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS: create white glow around image

Depends on what your target browsers are. In newer ones it's as simple as:

   -moz-box-shadow: 0 0 5px #fff;
-webkit-box-shadow: 0 0 5px #fff;
        box-shadow: 0 0 5px #fff;

For older browsers you have to implement workarounds, e.g., based on this example, but you will most probably need extra mark-up.

How to style icon color, size, and shadow of Font Awesome Icons

For Sizing Icons

Both our Web Fonts + CSS and SVG + JS frameworks include some basic controls for sizing icons in the context of your page’s UI.

you can use like

<i class="fas fa-camera fa-xs"></i>
<i class="fas fa-camera fa-sm"></i>
<i class="fas fa-camera fa-lg"></i>
<i class="fas fa-camera fa-2x"></i>
<i class="fas fa-camera fa-3x"></i>
<i class="fas fa-camera fa-5x"></i>
<i class="fas fa-camera fa-7x"></i>
<i class="fas fa-camera fa-10x"></i>

https://fontawesome.com/how-to-use/on-the-web/styling/sizing-icons

Posting form to different MVC post action depending on the clicked submit button

you can use ajax calls to call different methods without a postback

$.ajax({
    type: "POST",
     url: "@(Url.Action("Action", "Controller"))",
     data: {id: 'id', id1: 'id1' },
     contentType: "application/json; charset=utf-8",
     cache: false,
     async: true,
     success: function (result) {
        //do something
     }
});

How to turn on WCF tracing?

The following configuration taken from MSDN can be applied to enable tracing on your WCF service.

<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true" >
        <listeners>
             <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource"
              switchValue="Information, ActivityTracing">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
        <add name="xml"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="Error.svclog" />
    </sharedListeners>
  </system.diagnostics>
</configuration>

To view the log file, you can use "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe".

If "SvcTraceViewer.exe" is not on your system, you can download it from the "Microsoft Windows SDK for Windows 7 and .NET Framework 4" package here:

Windows SDK Download

You don't have to install the entire thing, just the ".NET Development / Tools" part.

When/if it bombs out during installation with a non-sensical error, Petopas' answer to Windows 7 SDK Installation Failure solved my issue.

Multi-threading in VBA

As you probably learned VBA does not natively support multithreading but. There are 3 methods to achieve multithreading:

  1. COM/dlls - e.g. C# and the Parallel class to run in separate threads
  2. Using VBscript worker threads - run your VBA code in separate VBscript threads
  3. Using VBA worker threads executed e.g. via VBscript - copy the Excel workbook and run your macro in parallel.

I compared all thread approaches here: http://analystcave.com/excel-multithreading-vba-vs-vbscript-vs-c-net/

Considering approach #3 I also made a VBA Multithreading Tool that allows you to easily add multithreading to VBA: http://analystcave.com/excel-vba-multithreading-tool/

See the examples below:

Multithreading a For Loop

Sub RunForVBA(workbookName As String, seqFrom As Long, seqTo As Long)
    For i = seqFrom To seqTo
        x = seqFrom / seqTo
    Next i
End Sub

Sub RunForVBAMultiThread()
    Dim parallelClass As Parallel 

    Set parallelClass = New Parallel 

    parallelClass.SetThreads 4 

    Call parallelClass.ParallelFor("RunForVBA", 1, 1000) 
End Sub

Run an Excel macro asynchronously

Sub RunAsyncVBA(workbookName As String, seqFrom As Long, seqTo As Long)
    For i = seqFrom To seqTo
        x = seqFrom / seqTo
    Next i
End Sub

Sub RunForVBAAndWait()
    Dim parallelClass As Parallel

    Set parallelClass  = New Parallel

    Call parallelClass.ParallelAsyncInvoke("RunAsyncVBA", ActiveWorkbook.Name, 1, 1000) 
    'Do other operations here
    '....

    parallelClass.AsyncThreadJoin 
End Sub

How do I enable the column selection mode in Eclipse?

Additionally, you can change the keys view window -> preferences then type: 'keys' and when the key preference page opens you can type 'toggle block selection' and voila!

How to wrap text using CSS?

The better option if you cannot control user input, it is to establish the css property, overflow:hidden, so if the string is superior to the width, it will not deform the design.

Edited:

I like the answer: "word-wrap: break-word", and for those browsers that do not support it, for example, IE6 or IE7, I would use my solution.

How do I register a DLL file on Windows 7 64-bit?

Part of the confusion regarding regsvr32 is that on 64-bit windows the name and path have not changed, but it now registers 64-bit DLLs. The 32-bit regsvr32 exists in SysWOW64, a name that appears to represent 64-bit applications. However the WOW64 in the name refers to Windows on Windows 64, or more explicity Windows 32-bit on Windows 64-bit. When you think of it this way the name makes sense even though it is confusing in this context.

I cannot find my original source on an MSDN blog but it is referenced in this Wikipedia article http://en.wikipedia.org/wiki/WoW64

How to stop creating .DS_Store on Mac?

this file starts to appear when you choose the system shows you the hidden files: $defaults write com.apple.finder AppleShowAllFiles TRUE If you run this command disapear $defaults write com.apple.finder AppleShowAllFiles FALSE Use terminal

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

Suppose your project has the following structure and you want to do imports in the notebook.ipynb:

/app
  /mypackage
    mymodule.py
  /notebooks
    notebook.ipynb

If you are running Jupyter inside a docker container without any virtualenv it might be useful to create Jupyter (ipython) config in your project folder:

/app
  /profile_default
    ipython_config.py

Content of ipython_config.py:

c.InteractiveShellApp.exec_lines = [
    'import sys; sys.path.append("/app")'
]

Open the notebook and check it out:

print(sys.path)

['', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages/IPython/extensions', '/root/.ipython', '/app']

Now you can do imports in your notebook without any sys.path appending in the cells:

from mypackage.mymodule import myfunc

jQuery .live() vs .on() method for adding a click event after loading dynamic html

I know it's a little late for an answer, but I've created a polyfill for the .live() method. I've tested it in jQuery 1.11, and it seems to work pretty well. I know that we're supposed to implement the .on() method wherever possible, but in big projects, where it's not possible to convert all .live() calls to the equivalent .on() calls for whatever reason, the following might work:

if(jQuery && !jQuery.fn.live) {
    jQuery.fn.live = function(evt, func) {
        $('body').on(evt, this.selector, func);
    }
}

Just include it after you load jQuery and before you call live().

Loading/Downloading image from URL on Swift

You can use pod SDWebImage to achieve the same. Its easy to use. Yo can get documentaion here SDWebImage

Here is the sample code

self.yourImage.sd_setImage(with: NSURL(string: StrUrl as String ) as URL!, placeholderImage: placeholderImage, options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in
                if( error != nil)
                {
                    print("Error while displaying image" , (error?.localizedDescription)! as String)
                }
            })

How to remove all .svn directories from my application directories

You almost had it. If you want to pass the output of a command as parameters to another one, you'll need to use xargs. Adding -print0 makes sure the script can handle paths with whitespace:

find . -type d -name .svn -print0|xargs -0 rm -rf

Run Executable from Powershell script with parameters

Try quoting the argument list:

Start-Process -FilePath "C:\Program Files\MSBuild\test.exe" -ArgumentList "/genmsi/f $MySourceDirectory\src\Deployment\Installations.xml"

You can also provide the argument list as an array (comma separated args) but using a string is usually easier.

What is the behavior of integer division?

Will result always be the floor of the division?

No. The result varies, but variation happens only for negative values.

What is the defined behavior?

To make it clear floor rounds towards negative infinity,while integer division rounds towards zero (truncates)

For positive values they are the same

int integerDivisionResultPositive= 125/100;//= 1
double flooringResultPositive= floor(125.0/100.0);//=1.0

For negative value this is different

int integerDivisionResultNegative= -125/100;//=-1
double flooringResultNegative= floor(-125.0/100.0);//=-2.0

jQuery Refresh/Reload Page if Ajax Success after time

$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)

What size should apple-touch-icon.png be for iPad and iPhone?

The icon on Apple's site is 152x152 pixels.
http://www.apple.com/apple-touch-icon.png

Hope that answers your question.

How do I find the width & height of a terminal window?

As I mentioned in lyceus answer, his code will fail on non-English locale Windows because then the output of mode may not contain the substrings "columns" or "lines":

                                         mode command output

You can find the correct substring without looking for text:

 preg_match('/---+(\n[^|]+?){2}(?<cols>\d+)/', `mode`, $matches);
 $cols = $matches['cols'];

Note that I'm not even bothering with lines because it's unreliable (and I actually don't care about them).

Edit: According to comments about Windows 8 (oh you...), I think this may be more reliable:

 preg_match('/CON.*:(\n[^|]+?){3}(?<cols>\d+)/', `mode`, $matches);
 $cols = $matches['cols'];

Do test it out though, because I didn't test it.

Xcode warning: "Multiple build commands for output file"

One of simple way is,

  • Go to App target
  • Go to Build Phases
  • Output files
  • Delete path of out put files, then build project. It will run successfully.

How can I set multiple CSS styles in JavaScript?

set multiple css style properties in Javascript

document.getElementById("yourElement").style.cssText = cssString;

or

document.getElementById("yourElement").setAttribute("style",cssString);

Example:

document
.getElementById("demo")
.style
.cssText = "margin-left:100px;background-color:red";

document
.getElementById("demo")
.setAttribute("style","margin-left:100px; background-color:red");

Expand a random range from 1–5 to 1–7

I think I have four answers, two giving exact solutions like that of @Adam Rosenfield but without the infinite loop problem, and other two with almost perfect solution but faster implementation than first one.

The best exact solution requires 7 calls to rand5, but lets proceed in order to understand.

Method 1 - Exact

Strength of Adam's answer is that it gives a perfect uniform distribution, and there is very high probability (21/25) that only two calls to rand5() will be needed. However, worst case is infinite loop.

The first solution below also gives a perfect uniform distribution, but requires a total of 42 calls to rand5. No infinite loops.

Here is an R implementation:

rand5 <- function() sample(1:5,1)

rand7 <- function()  (sum(sapply(0:6, function(i) i + rand5() + rand5()*2 + rand5()*3 + rand5()*4 + rand5()*5 + rand5()*6)) %% 7) + 1

For people not familiar with R, here is a simplified version:

rand7 = function(){
  r = 0 
  for(i in 0:6){
    r = r + i + rand5() + rand5()*2 + rand5()*3 + rand5()*4 + rand5()*5 + rand5()*6
  }
  return r %% 7 + 1
}

The distribution of rand5 will be preserved. If we do the math, each of the 7 iterations of the loop has 5^6 possible combinations, thus total number of possible combinations are (7 * 5^6) %% 7 = 0. Thus we can divide the random numbers generated in equal groups of 7. See method two for more discussion on this.

Here are all the possible combinations:

table(apply(expand.grid(c(outer(1:5,0:6,"+")),(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6),1,sum) %% 7 + 1)

    1     2     3     4     5     6     7 
15625 15625 15625 15625 15625 15625 15625 

I think it's straight forward to show that Adam's method will run much much faster. The probability that there are 42 or more calls to rand5 in Adam's solution is very small ((4/25)^21 ~ 10^(-17)).

Method 2 - Not Exact

Now the second method, which is almost uniform, but requires 6 calls to rand5:

rand7 <- function() (sum(sapply(1:6,function(i) i*rand5())) %% 7) + 1

Here is a simplified version:

rand7 = function(){
  r = 0 
  for(i in 1:6){
    r = r + i*rand5()
  }
  return r %% 7 + 1
}

This is essentially one iteration of method 1. If we generate all possible combinations, here is resulting counts:

table(apply(expand.grid(1:5,(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6),1,sum) %% 7 + 1)

   1    2    3    4    5    6    7 
2233 2232 2232 2232 2232 2232 2232

One number will appear once more in 5^6 = 15625 trials.

Now, in Method 1, by adding 1 to 6, we move the number 2233 to each of the successive point. Thus the total number of combinations will match up. This works because 5^6 %% 7 = 1, and then we do 7 appropriate variations, so (7 * 5^6 %% 7 = 0).

Method 3 - Exact

If the argument of method 1 and 2 is understood, method 3 follows, and requires only 7 calls to rand5. At this point, I feel this is the minimum number of calls needed for an exact solution.

Here is an R implementation:

rand5 <- function() sample(1:5,1)

rand7 <- function()  (sum(sapply(1:7, function(i) i * rand5())) %% 7) + 1

For people not familiar with R, here is a simplified version:

rand7 = function(){
  r = 0 
  for(i in 1:7){
    r = r + i * rand5()
  }
  return r %% 7 + 1
}

The distribution of rand5 will be preserved. If we do the math, each of the 7 iterations of the loop has 5 possible outcomes, thus total number of possible combinations are (7 * 5) %% 7 = 0. Thus we can divide the random numbers generated in equal groups of 7. See method one and two for more discussion on this.

Here are all the possible combinations:

table(apply(expand.grid(0:6,(1:5)),1,sum) %% 7 + 1)

1 2 3 4 5 6 7  
5 5 5 5 5 5 5 

I think it's straight forward to show that Adam's method will still run faster. The probability that there are 7 or more calls to rand5 in Adam's solution is still small ((4/25)^3 ~ 0.004).

Method 4 - Not Exact

This is a minor variation of the the second method. It is almost uniform, but requires 7 calls to rand5, that is one additional to method 2:

rand7 <- function() (rand5() + sum(sapply(1:6,function(i) i*rand5())) %% 7) + 1

Here is a simplified version:

rand7 = function(){
  r = 0 
  for(i in 1:6){
    r = r + i*rand5()
  }
  return (r+rand5()) %% 7 + 1
}

If we generate all possible combinations, here is resulting counts:

table(apply(expand.grid(1:5,(1:5)*2,(1:5)*3,(1:5)*4,(1:5)*5,(1:5)*6,1:5),1,sum) %% 7 + 1)

    1     2     3     4     5     6     7 
11160 11161 11161 11161 11161 11161 11160

Two numbers will appear once less in 5^7 = 78125 trials. For most purposes, I can live with that.

Programmatically navigate using React router

For this one, who does not control the server side and because of this is using hash router v2:

Place your history into separate file (e.g. app_history.js ES6):

import { useRouterHistory } from 'react-router'
import { createHashHistory } from 'history'
const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });

export default appHistory;

And use it everywhere!

Your entry point for react-router (app.js ES6):

import React from 'react'
import { render } from 'react-dom'
import { Router, Route, Redirect } from 'react-router'
import appHistory from './app_history'
...
const render((
  <Router history={appHistory}>
  ...
  </Router>
), document.querySelector('[data-role="app"]'));

Your navigation inside any component (ES6):

import appHistory from '../app_history'
...
ajaxLogin('/login', (err, data) => {
  if (err) {
    console.error(err); // login failed
  } else {
    // logged in
    appHistory.replace('/dashboard'); // or .push() if you don't need .replace()
  }
})

Maven and Spring Boot - non resolvable parent pom - repo.spring.io (Unknown host)

The issue is with your project which is not able to complete maven build. Steps to follow :

  1. Right Click Application and RunAs maven install.
  2. If you get any error while reaching the repos online try giving the proxies in settings.xml under your .m2 directory.Check this link for setting proxies for maven build.
  3. Once done , try doing a Update Project by Right Click Project , Maven->Update Maven Project and select codebase and do check the Force Update of Snapshot/Release check box.

This will update your maven build and will surely remove your errors with pom.xml

How to reload the datatable(jquery) data?

None of these solutions worked for me, but I did do something similar to Masood's answer. Here it is for posterity. This assumes you have <table id="mytable"></table> in your page somewhere:

function generate_support_user_table() {
        $('#mytable').hide();
        $('#mytable').dataTable({
            ...
            "bDestroy": true,
            "fnInitComplete": function () { $('#support_user_table').show(); },
            ...
        });
}

The important parts are:

  1. bDestroy, which wipes out the current table before loading.
  2. The hide() call and fnInitComplete, which ensures that the table only appears after everything is loaded. Otherwise it resizes and looks weird while loading.

Just add the function call to $(document).ready() and you should be all set. It will load the table initially, as well as reload later on a button click or whatever.

How do I check whether an array contains a string in TypeScript?

The same as in JavaScript, using Array.prototype.indexOf():

console.log(channelArray.indexOf('three') > -1);

Or using ECMAScript 2016 Array.prototype.includes():

console.log(channelArray.includes('three'));

Note that you could also use methods like showed by @Nitzan to find a string. However you wouldn't usually do that for a string array, but rather for an array of objects. There those methods were more sensible. For example

const arr = [{foo: 'bar'}, {foo: 'bar'}, {foo: 'baz'}];
console.log(arr.find(e => e.foo === 'bar')); // {foo: 'bar'} (first match)
console.log(arr.some(e => e.foo === 'bar')); // true
console.log(arr.filter(e => e.foo === 'bar')); // [{foo: 'bar'}, {foo: 'bar'}]

Reference

Array.find()

Array.some()

Array.filter()

Android Studio was unable to find a valid Jvm (Related to MAC OS)

I have same problem and fixed with this way:

You should install Java from Official Apple page.

http://support.apple.com/kb/DL1572

How to add a hook to the application context initialization event?

I had a single page application on entering URL it was creating a HashMap (used by my webpage) which contained data from multiple databases. I did following things to load everything during server start time-

1- Created ContextListenerClass

public class MyAppContextListener implements ServletContextListener
    @Autowired

    private  MyDataProviderBean myDataProviderBean; 

    public MyDataProviderBean getMyDataProviderBean() {

        return MyDataProviderBean;

    }

    public void setMyDataProviderBean(MyDataProviderBean MyDataProviderBean) {

        this.myDataProviderBean = MyDataProviderBean;

    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

        System.out.println("ServletContextListener destroyed");

    }


    @Override

    public void contextInitialized(ServletContextEvent context) {

        System.out.println("ServletContextListener started");

        ServletContext sc = context.getServletContext();

        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(sc);

        MyDataProviderBean MyDataProviderBean = (MyDataProviderBean)springContext.getBean("myDataProviderBean");

        Map<String, Object> myDataMap = MyDataProviderBean.getDataMap();

        sc.setAttribute("myMap", myDataMap);

    }

2- Added below entry in web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 
<listener>
    <listener-class>com.context.listener.MyAppContextListener</listener-class>
</listener>

3- In my Controller Class updated code to first check for Map in servletContext

    @RequestMapping(value = "/index", method = RequestMethod.GET)
        public String index(@ModelAttribute("model") ModelMap model) {

            Map<String, Object> myDataMap = new HashMap<String, Object>();
            if (context != null && context.getAttribute("myMap")!=null)
            {

                myDataMap=(Map<String, Object>)context.getAttribute("myMap");
            }

            else
            {

                myDataMap = myDataProviderBean.getDataMap();
            }

            for (String key : myDataMap.keySet())
            {
                model.addAttribute(key, myDataMap.get(key));
            }
            return "myWebPage";

        }

With this much change when I start my tomcat it loads dataMap during startTime and puts everything in servletContext which is then used by Controller Class to get results from already populated servletContext .

npm command to uninstall or prune unused packages in Node.js

Note: Recent npm versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production flag.


Run npm prune to remove modules not listed in package.json.

From npm help prune:

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified, this command will remove the packages specified in your devDependencies.

How to run Tensorflow on CPU

The environment variable solution doesn't work for me running tensorflow 2.3.1. I assume by the comments in the github thread that the below solution works for versions >=2.1.0.

From tensorflow github:

import tensorflow as tf

# Hide GPU from visible devices
tf.config.set_visible_devices([], 'GPU')

Make sure to do this right after the import with fresh tensorflow instance (if you're running jupyter notebook, restart the kernel).

And to check that you're indeed running on the CPU:

# To find out which devices your operations and tensors are assigned to
tf.debugging.set_log_device_placement(True)

# Create some tensors and perform an operation
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)

print(c)

Expected output:

2.3.1
Executing op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0
tf.Tensor(
[[22. 28.]
 [49. 64.]], shape=(2, 2), dtype=float32)

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

How does one create an InputStream from a String?

Instead of CharSet.forName, using com.google.common.base.Charsets from Google's Guava (http://code.google.com/p/guava-libraries/wiki/StringsExplained#Charsets) is is slightly nicer:

InputStream is = new ByteArrayInputStream( myString.getBytes(Charsets.UTF_8) );

Which CharSet you use depends entirely on what you're going to do with the InputStream, of course.

React Native fixed footer

import {Dimensions} from 'react-native'

const WIDTH = Dimensions.get('window').width;
const HEIGHT = Dimensions.get('window').height;

then on the write this styles

 position: 'absolute',
 top: HEIGHT-80,
 left: 0,
 right: 0,

worked like a charm

Where can I get a list of Ansible pre-defined variables?

Some variables are not available on every host, e.g. ansible_domain and domain. If the situation needs to be debugged, I login to the server and issue:

user@server:~$ ansible -m setup localhost | grep domain
 [WARNING]: provided hosts list is empty, only localhost is available
    "ansible_domain": "prd.example.com",

How should I have explained the difference between an Interface and an Abstract class?

I will give you an example first:

public interface LoginAuth{
   public String encryptPassword(String pass);
   public void checkDBforUser();
}

Suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 methods:

public class DBMySQL implements LoginAuth{
          // Needs to implement both methods
}
public class DBOracle implements LoginAuth{
          // Needs to implement both methods
}
public class DBAbc implements LoginAuth{
          // Needs to implement both methods
}

But what if encryptPassword() is not database dependent, and it's the same for each class? Then the above would not be a good approach.

Instead, consider this approach:

public abstract class LoginAuth{
   public String encryptPassword(String pass){
            // Implement the same default behavior here 
            // that is shared by all subclasses.
   }

   // Each subclass needs to provide their own implementation of this only:
   public abstract void checkDBforUser();
}

Now in each child class, we only need to implement one method - the method that is database dependent.

Send parameter to Bootstrap modal window?

First of all you should fix modal HTML structure. Now it's not correct, you don't need class .hide:

<div id="edit-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body edit-content">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

Then links should point to this modal via data-target attribute:

<a href="#myModal" data-toggle="modal" id="1" data-target="#edit-modal">Edit 1</a>

Finally Js part becomes very simple:

    $('#edit-modal').on('show.bs.modal', function(e) {

        var $modal = $(this),
            esseyId = e.relatedTarget.id;

        $.ajax({
            cache: false,
            type: 'POST',
            url: 'backend.php',
            data: 'EID=' + essayId,
            success: function(data) {
                $modal.find('.edit-content').html(data);
            }
        });
    })

Demo: http://plnkr.co/edit/4XnLTZ557qMegqRmWVwU?p=preview

Select something that has more/less than x character

Today I was trying same in db2 and used below, in my case I had spaces at the end of varchar column data

SELECT EmployeeName FROM EmployeeTable WHERE LENGTH(TRIM(EmployeeName))> 4;

How to capture the android device screen content?

if you want to do screen capture from Java code in Android app AFAIK you must have Root provileges.

Attach the Java Source Code

Normally, if you have installed the JDK6u14, eclipse should detect it and declare it automatically in its "installed JRE" list.

If not, you can add that JDK through "Windows/Preferences": Java > Installed JREs:

Just point to the root directory of your JDK installation: it should include the sources of the JDK (src.zip), automatically detected and attached to rt.jar by eclipse.

Add JRE VM, from pic.dhe.ibm.com/infocenter/iadthelp/v8r0/topic/org.eclipse.jdt.doc.user/tasks/images/task-add_jre_std_vm.PNG

Ng-model does not update controller value

Have a look at this fiddle http://jsfiddle.net/ganarajpr/MSjqL/

I have ( I assume! ) done exactly what you were doing and it seems to be working. Can you check what is not working here for you?

Position: absolute and parent height?

Here is my workaround,
In your example you can add a third element with "same styles" of .one & .two elements, but without the absolute position and with hidden visibility:

HTML

<article>
   <div class="one"></div>
   <div class="two"></div>
   <div class="three"></div>
</article>

CSS

.three{
    height: 30px;
    z-index: -1;
    visibility: hidden;
}

Share cookie between subdomain and domain

Please everyone note that you can set a cookie from a subdomain on a domain.

(sent in the response for requesting subdomain.mydomain.com)

Set-Cookie: name=value; Domain=mydomain.com // GOOD

But you CAN'T set a cookie from a domain on a subdomain.

(sent in the response for requesting mydomain.com)

Set-Cookie: name=value; Domain=subdomain.mydomain.com // Browser rejects cookie

WHY ?

According to the specifications RFC 6265 section 5.3.6 Storage Model

If the canonicalized request-host does not domain-match the domain-attribute: Ignore the cookie entirely and abort these steps.

and RFC 6265 section 5.1.3 Domain Matching

Domain Matching

A string domain-matches a given domain string if at least one of the following conditions hold:

  1. The domain string and the string are identical. (Note that both the domain string and the string will have been canonicalized to lower case at this point.)

  2. All of the following conditions hold:

    • The domain string is a suffix of the string.

    • The last character of the string that is not included in the domain string is a %x2E (".") character.

    • The string is a host name (i.e., not an IP address).

So "subdomain.mydomain.com" domain-matches "mydomain.com", but "mydomain.com" does NOT domain-match "subdomain.mydomain.com"

Check this answer also.

How can I change IIS Express port for a site

If you just want to change the port because it is already in use. Follow the following steps.

In Visual studio

  1. Right-click on Project Node and Unload Project
  2. Right-click on Project Node and Edit .csproj file.
  3. Search for the following tags and remove them
<DevelopmentServerPort>62140</DevelopmentServerPort>
<DevelopmentServerVPath></DevelopmentServerVPath>
<IISUrl>http://localhost:62116/</IISUrl>
  1. press Ctrl + S to save the document
  2. Right-click on Project Node and load Project

It will work by selecting another port randomly.

For further information. please click

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

You can try to turn support on in spring's converter

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // add converter suport Content-Type: 'application/x-www-form-urlencoded'
        converters.stream()
                .filter(AllEncompassingFormHttpMessageConverter.class::isInstance)
                .map(AllEncompassingFormHttpMessageConverter.class::cast)
                .findFirst()
                .ifPresent(converter -> converter.addSupportedMediaTypes(MediaType.APPLICATION_FORM_URLENCODED_VALUE));
    }

}

Add key value pair to all objects in array

@Redu's solution is a good solution

arrOfObj.map(o => o.isActive = true;) but Array.map still counts as looping through all items.

if you absolutely don't want to have any looping here's a dirty hack :

Object.defineProperty(Object.prototype, "isActive",{
  value: true,
  writable: true,
  configurable: true,
  enumerable: true
});

my advice is not to use it carefully though, it will patch absolutely all javascript Objects (Date, Array, Number, String or any other that inherit Object ) which is really bad practice...

Redirecting to a certain route based on condition

I have been trying to do the same. Came up with another simpler solution after working with a colleague. I have a watch set up on $location.path(). That does the trick. I am just starting to learn AngularJS and find this to be more cleaner and readable.

$scope.$watch(function() { return $location.path(); }, function(newValue, oldValue){  
    if ($scope.loggedIn == false && newValue != '/login'){  
            $location.path('/login');  
    }  
});

How to get Url Hash (#) from server side

Just to rule out the possibility you aren't actually trying to see the fragment on a GET/POST and actually want to know how to access that part of a URI object you have within your server-side code, it is under Uri.Fragment (MSDN docs).

MongoDB or CouchDB - fit for production?

Speaking production, seamless failover/recovery both require a baby sitter
1- Couchbase, there is no seamless failover/recovery, manual intervention is required.
rebalancing takes too much time, too much risk if more than one node get lost.

2- Mongo with shards, data recovery from loosing a config server, is not an easy task

Repository access denied. access via a deployment key is read-only

for this error : conq: repository access denied. access via a deployment key is read-only.

I change the name of my key, example

cd /home/try/.ssh/
mv try id_rsa
mv try.pub id_rsa.pub

I work on my own key on bitbucket

C# nullable string error

Please note that in upcoming version of C# which is 8, the answers are not true.

All the reference types are non-nullable by default and you can actually do the following:

public string? MyNullableString; 
this.MyNullableString = null; //Valid

However,

public string MyNonNullableString; 
this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning. 

The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.

More info

To the moderator who is deleting all the answers, don't do it. I strongly believe this answer adds value and deleting would simply keep someone from knowing what is right at the time. Since you have deleted all the answers, I'm re-posting answer here. The link that was sent regarding "duplicates" is simply an opening of some people and I do not think it is an official recommendation.

How to fill OpenCV image with one solid color?

Use numpy.full. Here's a Python that creates a gray, blue, green and red image and shows in a 2x2 grid.

import cv2
import numpy as np

gray_img = np.full((100, 100, 3), 127, np.uint8)

blue_img = np.full((100, 100, 3), 0, np.uint8)
green_img = np.full((100, 100, 3), 0, np.uint8)
red_img = np.full((100, 100, 3), 0, np.uint8)

full_layer = np.full((100, 100), 255, np.uint8)

# OpenCV goes in blue, green, red order
blue_img[:, :, 0] = full_layer
green_img[:, :, 1] = full_layer
red_img[:, :, 2] = full_layer

cv2.imshow('2x2_grid', np.vstack([
    np.hstack([gray_img, blue_img]), 
    np.hstack([green_img, red_img])
]))
cv2.waitKey(0)
cv2.destroyWindow('2x2_grid')

Using jQuery to center a DIV on the screen

I dont think having an absolute position would be best if you want an element always centered in the middle of the page. You probably want a fixed element. I found another jquery centering plugin that used fixed positioning. It is called fixed center.

JAXB Exception: Class not known to this context

I had the same exception on Tomcat.. I found another problem - when i use wsimport over maven plugin to generate stubs for more then 1 WSDLs - class ObjectFactory (stubs references to this class) contains methods ONLY for one wsdl. So you should merge all methods in one ObjectFactory class (for each WSDL) or generate each wsdl stubs in different directories (there will be separates ObjectFactory classes). It solves problem for me with this exception..J

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

With ES6 supporting Promises, we can use them without any third-party aid.

const sleep = (seconds) => {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, (seconds * 1000));
    });
};

// We are not using `reject` anywhere, but it is good to
// stick to standard signature.

Then use it like this:

const waitThenDo(howLong, doWhat) => {
    return sleep(howLong).then(doWhat);
};

Note that the doWhat function becomes the resolve callback within the new Promise(...).

Also note that this is ASYNCHRONOUS sleep. It does not block the event loop. If you need blocking sleep, use this library which realizes blocking sleep with the help of C++ bindings. (Although the need for a blocking sleep in Node like async environments is rare.)

https://github.com/erikdubbelboer/node-sleep

Styling twitter bootstrap buttons

In order to completely override the bootstrap button styles, you need to override a list of properties. See the below example.

    .btn-primary, .btn-primary:hover, .btn-primary:focus, .btn-primary.focus, 
    .btn-primary:active, .btn-primary.active, .btn-primary:visited,
    .btn-primary:active:hover, .btn-primary.active:hover{
        background-color: #F19425;
        color:#fff;
        border: none;
        outline: none;
    }

If you don't use all the listed styles then you will see the default styles at performing actions on button. For example once you click the button and remove mouse pointer from button, you will see the default color visible. Or keep the button pressed you will see default colors. So, I have listed all the pseudo-styles that are to be overridden.

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Assigning more than one class for one event

Have you tried this:

 function doSomething() {
     if ($(this).hasClass('clickedTag')){
         // code here
     } else {
         // and here
     }
 }

 $('.tag1, .tag2').click(doSomething);

Meaning of tilde in Linux bash (not home directory)

It's a Bash feature called "tilde expansion". It's a function of the shell, not the OS. You'll get different behavior with csh, for example.

To answer your question about where the information comes from: your home directory comes from the variable $HOME (no matter what you store there), while other user's homes are retrieved real-time using getpwent(). This function is usually controlled by NSS; so by default values are pulled out of /etc/passwd, though it can be configured to retrieve the information using any source desired, such as NIS, LDAP or an SQL database.

Tilde expansion is more than home directory lookup. Here's a summary:

~              $HOME
~fred          (freds home dir)

~+             $PWD       (your current working directory)
~-             $OLDPWD    (your previous directory)
~1             `dirs +1`
~2             `dirs +2`
~-1            `dirs -1`

dirs and ~1, ~-1, etc., are used in conjunction with pushd and popd.

JavaScript: Passing parameters to a callback function

If you are not sure how many parameters are you going to be passed into callback functions, use apply function.

function tryMe (param1, param2) {
  alert (param1 + " and " + param2);
}

function callbackTester(callback,params){
    callback.apply(this,params);
}

callbackTester(tryMe,['hello','goodbye']);

C++ alignment when printing cout <<

IO manipulators are what you need. setw, in particular. Here's an example from the reference page:

// setw example
#include <iostream>
#include <iomanip>
using namespace std;

int main () {
  cout << setw (10);
  cout << 77 << endl;
  return 0;
}

Justifying the field to the left and right is done with the left and right manipulators.

Also take a look at setfill. Here's a more complete tutorial on formatting C++ output with io manipulators.

How to amend a commit without changing commit message (reusing the previous one)?

To extend on the accepted answer, you can also do:

git commit --amend --no-edit -a

to add the currently changed files.

How to do an update + join in PostgreSQL?

For those wanting to do a JOIN that updates ONLY the rows your join returns use:

UPDATE a
SET price = b_alias.unit_price
FROM      a AS a_alias
LEFT JOIN b AS b_alias ON a_alias.b_fk = b_alias.id
WHERE a_alias.unit_name LIKE 'some_value' 
AND a.id = a_alias.id
--the below line is critical for updating ONLY joined rows
AND a.pk_id = a_alias.pk_id;

This was mentioned above but only through a comment..Since it's critical to getting the correct result posting NEW answer that Works

char initial value in Java

Either you initialize the variable to something

char retChar = 'x';

or you leave it automatically initialized, which is

char retChar = '\0';

an ascii 0, the same as

char retChar = (char) 0;

What can one initialize char values to?

Sounds undecided between automatic initialisation, which means, you have no influence, or explicit initialisation. But you cannot change the default.

Why am I getting an OPTIONS request instead of a GET request?

I had the same problem. My fix was to add headers to my PHP script which are present only when in dev environment.

This allows cross-domain requests:

header("Access-Control-Allow-Origin: *");

This tells the preflight request that it is OK for the client to send any headers it wants:

header("Access-Control-Allow-Headers: *");

This way there is no need to modify the request.

If you have sensitive data in your dev database that might potentially be leaked, then you might think twice about this.

how to draw directed graphs using networkx in python?

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_node("A")
G.add_node("B")
G.add_node("C")
G.add_node("D")
G.add_node("E")
G.add_node("F")
G.add_node("G")
G.add_edge("A","B")
G.add_edge("B","C")
G.add_edge("C","E")
G.add_edge("C","F")
G.add_edge("D","E")
G.add_edge("F","G")

print(G.nodes())
print(G.edges())

pos = nx.spring_layout(G)

nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edge_color='r', arrows = True)

plt.show()

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

You only need these CSS properties in .container class of Bootstrap and you can put inside him the normal grid system without someone content of the container will be out of him (without scroll-x in the viewport).

HTML:

<div class="container">
    <div class="row">
        <div class="col-xs-12">
            Your content here!
            ...    
        </div>
    </div>
    ... more rows
</div>

CSS:

/* Bootstrap custom */
.container{
    padding-left: 0rem;
    padding-right: 0rem;
    overflow: hidden;
}

How can I find the dimensions of a matrix in Python?

The number of rows of a list of lists would be: len(A) and the number of columns len(A[0]) given that all rows have the same number of columns, i.e. all lists in each index are of the same size.

round value to 2 decimals javascript

If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"
    

And, as you can see above, using toFixed() is also far easier to type. ;)

Why is document.write considered a "bad practice"?

Browser Violation

.write is considered a browser violation as it halts the parser from rendering the page. The parser receives the message that the document is being modified; hence, it gets blocked until JS has completed its process. Only at this time will the parser resume.

Performance

The biggest consequence of employing such a method is lowered performance. The browser will take longer to load page content. The adverse reaction on load time depends on what is being written to the document. You won't see much of a difference if you are adding a <p> tag to the DOM as opposed to passing an array of 50-some references to JavaScript libraries (something which I have seen in working code and resulted in an 11 second delay - of course, this also depends on your hardware).

All in all, it's best to steer clear of this method if you can help it.

For more info see Intervening against document.write()

How can I wait for a thread to finish with .NET?

The previous two answers are great and will work for simple scenarios. There are other ways to synchronize threads, however. The following will also work:

public void StartTheActions()
{
    ManualResetEvent syncEvent = new ManualResetEvent(false);

    Thread t1 = new Thread(
        () =>
        {
            // Do some work...
            syncEvent.Set();
        }
    );
    t1.Start();

    Thread t2 = new Thread(
        () =>
        {
            syncEvent.WaitOne();

            // Do some work...
        }
    );
    t2.Start();
}

ManualResetEvent is one of the various WaitHandle's that the .NET framework has to offer. They can provide much richer thread synchronization capabilities than the simple, but very common tools like lock()/Monitor, Thread.Join, etc.

They can also be used to synchronize more than two threads, allowing complex scenarios such as a 'master' thread that coordinates multiple 'child' threads, multiple concurrent processes that are dependent upon several stages of each other to be synchronized, etc.

Get PostGIS version

Other way to get the minor version is:

SELECT extversion
FROM pg_catalog.pg_extension
WHERE extname='postgis'

How to pass a null variable to a SQL Stored Procedure from C#.net code

Old question, but here's a fairly clean way to create a nullable parameter:

new SqlParameter("@note", (object) request.Body ?? DBNull.Value);

If request.Body has a value, then it's value is used. If it's null, then DbNull.Value is used.

How to refresh Gridview after pressed a button in asp.net

Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.

Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
    GridView1.DataBind()
End Sub

How to load Spring Application Context

Add this at the start of main

ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");

JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");

//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();
launcher.run(job, jobParameters);
sw.stop();
//initialize the log same way inside main
logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

How to get child element by class name?

The accepted answer only checks immediate children. Often times we're looking for any descendants with that class name.

Also, sometimes we want any child that contains a className.

For example: <div class="img square"></div> should match a search on className "img", even though it's exact className is not "img".

Here's a solution for both of these issues:

Find the first instance of a descendant element with the class className

   function findFirstChildByClass(element, className) {
        var foundElement = null, found;
        function recurse(element, className, found) {
            for (var i = 0; i < element.childNodes.length && !found; i++) {
                var el = element.childNodes[i];
                var classes = el.className != undefined? el.className.split(" ") : [];
                for (var j = 0, jl = classes.length; j < jl; j++) {
                    if (classes[j] == className) {
                        found = true;
                        foundElement = element.childNodes[i];
                        break;
                    }
                }
                if(found)
                    break;
                recurse(element.childNodes[i], className, found);
            }
        }
        recurse(element, className, false);
        return foundElement;
    }

ESRI : Failed to parse source map

Check if you're using some Chrome extension (Night mode or something else). Disable that and see if the 'inject' gone.

Validate Dynamically Added Input fields

$('#form-btn').click(function () {
//set global rules & messages array to use in validator
   var rules = {};
   var messages = {};
//get input, select, textarea of form
   $('#formId').find('input, select, textarea').each(function () {
      var name = $(this).attr('name');
      rules[name] = {};
      messages[name] = {};

      rules[name] = {required: true}; // set required true against every name
//apply more rules, you can also apply custom rules & messages
      if (name === "email") {
         rules[name].email = true;
         //messages[name].email = "Please provide valid email";
      }
      else if(name==='url'){
        rules[name].required = false; // url filed is not required
//add other rules & messages
      }
   });
//submit form and use above created global rules & messages array
   $('#formId').submit(function (e) {
            e.preventDefault();
        }).validate({
            rules: rules,
            messages: messages,
            submitHandler: function (form) {
            console.log("validation success");
            }
        });
});

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

In my case (remote connnection) helped turning off firewall on server.

service iptables stop

How do I capture response of form.submit

I am doing it this way and its working.

$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(){
        console.log('form submitted.');
      }
    });
    return false;
});

Messagebox with input field

You can reference Microsoft.VisualBasic.dll.

Then using the code below.

Microsoft.VisualBasic.Interaction.InputBox("Question?","Title","Default Text");

Alternatively, by adding a using directive allowing for a shorter syntax in your code (which I'd personally prefer).

using Microsoft.VisualBasic;
...
Interaction.InputBox("Question?","Title","Default Text");

Or you can do what Pranay Rana suggests, that's what I would've done too...

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0) you are less likely to to see a difference between the two approaches.

How to get folder path for ClickOnce application

Assuming the question is about accessing files in the application folder after the ClickOnce (true == System.Deployment.ApplicationDeploy.IsNetworkDeployed) application is installed on the user's PC, their are three ways to get this folder by the application itself:

String path1 = System.AppDomain.CurrentDomain.BaseDirectory;
String path2 = System.IO.Directory.GetCurrentDirectory();    
String path3 = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; //Remove the last path component, the executing assembly itself.

These work from VS IDE and from a deployed/installed ClickedOnce app, no "true == System.Deployment.ApplicationDeploy.IsNetworkDeployed" check required. ClickOnce picks up any files included in the Visual Studio 2017 project so really the application can access any and all deployed files using relative paths from within the application.

This is based on Windows 10 and Visual Studio 2017

Save attachments to a folder and rename them

Public Sub Extract_Outlook_Email_Attachments()

Dim OutlookOpened As Boolean
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outFolder As Outlook.MAPIFolder
Dim outAttachment As Outlook.Attachment
Dim outItem As Object
Dim saveFolder As String
Dim outMailItem As Outlook.MailItem
Dim inputDate As String, subjectFilter As String


saveFolder = "Y:\Wingman" ' THIS IS WHERE YOU WANT TO SAVE THE ATTACHMENT TO

If Right(saveFolder, 1) <> "\" Then saveFolder = saveFolder & "\"

subjectFilter = ("Daily Operations Custom All Req Statuses Report") ' THIS IS WHERE YOU PLACE THE EMAIL SUBJECT FOR THE CODE TO FIND

OutlookOpened = False
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
    Set outApp = New Outlook.Application
    OutlookOpened = True
End If
On Error GoTo 0

If outApp Is Nothing Then
    MsgBox "Cannot start Outlook.", vbExclamation
    Exit Sub
End If

Set outNs = outApp.GetNamespace("MAPI")
Set outFolder = outNs.GetDefaultFolder(olFolderInbox)

If Not outFolder Is Nothing Then
    For Each outItem In outFolder.Items
        If outItem.Class = Outlook.OlObjectClass.olMail Then
            Set outMailItem = outItem
                If InStr(1, outMailItem.Subject, subjectFilter) > 0 Then 'removed the quotes around subjectFilter
                    For Each outAttachment In outMailItem.Attachments
                    outAttachment.SaveAsFile saveFolder & outAttachment.filename

                    Set outAttachment = Nothing

                    Next
                End If
        End If
    Next
End If

If OutlookOpened Then outApp.Quit

Set outApp = Nothing

End Sub

Get row-index values of Pandas DataFrame as list?

If you're only getting these to manually pass into df.set_index(), that's unnecessary. Just directly do df.set_index['your_col_name', drop=False], already.

It's very rare in pandas that you need to get an index as a Python list (unless you're doing something pretty funky, or else passing them back to NumPy), so if you're doing this a lot, it's a code smell that you're doing something wrong.

How to execute logic on Optional if not present?

First of all, your dao.find() should either return an Optional<Obj> or you will have to create one.

e.g.

Optional<Obj> = dao.find();

or you can do it yourself like:

Optional<Obj> = Optional.ofNullable(dao.find());

this one will return Optional<Obj> if present or Optional.empty() if not present.

So now let's get to the solution,

public Obj getObjectFromDB() {
   return Optional.ofNullable(dao.find()).flatMap(ob -> {
            ob.setAvailable(true);
            return Optional.of(ob);    
        }).orElseGet(() -> {
            logger.fatal("Object not available");
            return null;
        });
    }

This is the one liner you're looking for :)

Simplest way to serve static data from outside the application server in a Java web application

Requirement : Accessing the static Resources (images/videos., etc.,) from outside of WEBROOT directory or from local disk

Step 1 :
Create a folder under webapps of tomcat server., let us say the folder name is myproj

Step 2 :
Under myproj create a WEB-INF folder under this create a simple web.xml

code under web.xml

<web-app>
</web-app>

Directory Structure for the above two steps

c:\programfile\apachesoftwarefoundation\tomcat\...\webapps
                                                            |
                                                            |---myproj
                                                            |   |
                                                            |   |---WEB-INF
                                                                |   |
                                                                    |---web.xml

Step 3:
Now create a xml file with name myproj.xml under the following location

c:\programfile\apachesoftwarefoundation\tomcat\conf\catalina\localhost

CODE in myproj.xml:

<Context path="/myproj/images" docBase="e:/myproj/" crossContext="false" debug="0" reloadable="true" privileged="true" /> 

Step 4:
4 A) Now create a folder with name myproj in E drive of your hard disk and create a new

folder with name images and place some images in images folder (e:myproj\images\)

Let us suppose myfoto.jpg is placed under e:\myproj\images\myfoto.jpg

4 B) Now create a folder with name WEB-INF in e:\myproj\WEB-INF and create a web.xml in WEB-INF folder

Code in web.xml

<web-app>
</web-app>

Step 5:
Now create a .html document with name index.html and place under e:\myproj

CODE under index.html Welcome to Myproj

The Directory Structure for the above Step 4 and Step 5 is as follows

E:\myproj
    |--index.html
    |
    |--images
    |     |----myfoto.jpg
    |
    |--WEB-INF
    |     |--web.xml

Step 6:
Now start the apache tomcat server

Step 7:
open the browser and type the url as follows

http://localhost:8080/myproj    

then u display the content which is provided in index.html

Step 8:
To Access the Images under your local hard disk (outside of webroot)

http://localhost:8080/myproj/images/myfoto.jpg

Java - Change int to ascii

In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)

Meaning the first answer was correct actually char ch = (char) yourInt;

if in yourint=49 (or 0x31), ch will be '1'

Regular expression to limit number of characters to 10

pattern: /[\w\W]{1,10}/g

I used this expression for my case, it includes all the characters available in the text.

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

install cx_oracle for python

Try to reinstall it with the following code:

!pip install --proxy http://username:[email protected]:8080 --upgrade --force-reinstall cx_Oracle

In Java what is the syntax for commenting out multiple lines?

  • The simple question to your answer is already answered a lot of times:

    /*
    LINES I WANT COMMENTED
    LINES I WANT COMMENTED
    LINES I WANT COMMENTED
    */
    
  • From your question it sounds like you want to comment out a lot of code?? I would advise to use a repository(git/github) to manage your files instead of commenting out lines.

  • My last advice would be to learn about javadoc if not already familiar because documenting your code is really important.

Get string character by index - Java

Like this:

String a ="hh1hhhhhhhh";
char s = a.charAt(3);

How to set iframe size dynamically

Have you tried height="100%" in the definition of your iframe ? It seems to do what you seek, if you add height:100% in the css for "body" (if you do not, 100% will be "100% of your content").

EDIT: do not do this. The height attribute (as well as the width one) must have an integer as value, not a string.

Python: avoid new line with print command

In Python 3.x, you can use the end argument to the print() function to prevent a newline character from being printed:

print("Nope, that is not a two. That is a", end="")

In Python 2.x, you can use a trailing comma:

print "this should be",
print "on the same line"

You don't need this to simply print a variable, though:

print "Nope, that is not a two. That is a", x

Note that the trailing comma still results in a space being printed at the end of the line, i.e. it's equivalent to using end=" " in Python 3. To suppress the space character as well, you can either use

from __future__ import print_function

to get access to the Python 3 print function or use sys.stdout.write().

How to delete/unset the properties of a javascript object?

simply use delete, but be aware that you should read fully what the effects are of using this:

 delete object.index; //true
 object.index; //undefined

but if I was to use like so:

var x = 1; //1
delete x; //false
x; //1

but if you do wish to delete variables in the global namespace, you can use it's global object such as window, or using this in the outermost scope i.e

var a = 'b';
delete a; //false
delete window.a; //true
delete this.a; //true

http://perfectionkills.com/understanding-delete/

another fact is that using delete on an array will not remove the index but only set the value to undefined, meaning in certain control structures such as for loops, you will still iterate over that entity, when it comes to array's you should use splice which is a prototype of the array object.

Example Array:

var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

if I was to do:

delete myCars[1];

the resulting array would be:

["Saab", undefined, "BMW"]

but using splice like so:

myCars.splice(1,1);

would result in:

["Saab", "BMW"]

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

Read data from a text file using Java

If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
 // Do something with line
}

(Note that this code doesn't handle exceptions or close the stream, etc)

Why does adb return offline after the device string?

Had this on client's machine it turned out he had an out of date version of adb installed via website offering adb and fastboot. The client in question didn't want to install the whole SDK because of perceived bloat :S .

So if you're seeing offline make sure you've downloaded and using the latest adb. I ended up emailing him adb executable.

Also worth checking that the adb you are using is the correct one in the Path. i.e on Mac

$ which adb
/Users/me/dev/adt-bundle-mac-x86_64/sdk-macosx/platform-tools/adb 

Extract MSI from EXE

Launch the installer, but don't press the Install > button. Then

cd "%AppData%\..\LocalLow\Sun\Java"

and find your MSI file in one of sub-directories (e.g., jre1.7.0_25).

Note that Data1.cab from that sub-directory will be required as well.

Update MySQL using HTML Form and PHP

you have error in your sql syntax.

please use this query and checkout.

$query = mysql_query("UPDATE `anstalld` SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn' ");

Log4j output not displayed in Eclipse console

There is a case I make: exception happen in somewhere, but I catched the exception without print anything, thus the code didn't even reach the log4j code, so no output.

How to get all checked checkboxes

For a simple two- (or one) liner this code can be:

checkboxes = document.getElementsByName("NameOfCheckboxes");
selectedCboxes = Array.prototype.slice.call(checkboxes).filter(ch => ch.checked==true);

Here the Array.prototype.slice.call() part converts the object NodeList of all the checkboxes holding that name ("NameOfCheckboxes") into a new array, on which you then use the filter method. You can then also, for example, extract the values of the checkboxes by adding a .map(ch => ch.value) on the end of line 2. The => is javascript's arrow function notation.

python's re: return True if string contains regex pattern

Here's a function that does what you want:

import re

def is_match(regex, text):
    pattern = re.compile(regex, text)
    return pattern.search(text) is not None

The regular expression search method returns an object on success and None if the pattern is not found in the string. With that in mind, we return True as long as the search gives us something back.

Examples:

>>> is_match('ba[rzd]', 'foobar')
True
>>> is_match('ba[zrd]', 'foobaz')
True
>>> is_match('ba[zrd]', 'foobad')
True
>>> is_match('ba[zrd]', 'foobam')
False

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Install / upgrade gradle on Mac OS X

Two Method

  • using homebrew auto install:
    • Steps:
      • brew install gradle
    • Pros and cons
      • Pros: easy
      • Cons: (probably) not latest version
  • manually install (for latest version):
    • Pros and cons
      • Pros: use your expected any (or latest) version
      • Cons: need self to do it
    • Steps
      • download latest version binary (gradle-6.0.1) from Gradle | Releases
      • unzip it (gradle-6.0.1-all.zip) and added gradle path into environment variable PATH
        • normally is edit and add following config into your startup script( ~/.bashrc or ~/.zshrc etc.):
export GRADLE_HOME=/path_to_your_gradle/gradle-6.0.1
export PATH=$GRADLE_HOME/bin:$PATH

some other basic note

Q: How to make PATH take effect immediately?

A: use source:

source ~/.bashrc

it will make/execute your .bashrc, so make PATH become your expected latest values, which include your added gradle path.

Q: How to check PATH is really take effect/working now?

A: use echo to see your added path in indeed in your PATH

?  ~ echo $PATH
xxx:/Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin:xxx

you can see we added /Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin into your PATH

Q: How to verify gradle is installed correctly on my Mac ?

A: use which to make sure can find gradle

?  ~ which gradle
/Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin/gradle

AND to check and see gradle version

?  ~ gradle --version

------------------------------------------------------------
Gradle 6.0.1
------------------------------------------------------------

Build time:   2019-11-18 20:25:01 UTC
Revision:     fad121066a68c4701acd362daf4287a7c309a0f5

Kotlin:       1.3.50
Groovy:       2.5.8
Ant:          Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM:          1.8.0_112 (Oracle Corporation 25.112-b16)
OS:           Mac OS X 10.14.6 x86_64

this means the (latest) gradle is correctly installed on your mac ^_^.

for more detail please refer my (Chinese) post ?????mac???maven

"E: Unable to locate package python-pip" on Ubuntu 18.04

Try following command sequence on Ubuntu terminal:

sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip

scp from Linux to Windows

This one worked for me.

scp /home/ubuntu/myfile username@IP_of_windows_machine:/C:/Users/Anshul/Desktop 

Convert a video to MP4 (H.264/AAC) with ffmpeg

You need to compile ffmpeg with an AAC encoder. You can find one at AudioCoding.

How can I declare dynamic String array in Java

Maybe you are looking for Vector. It's capacity is automatically expanded if needed. It's not the best choice but will do in simple situations. It's worth your time to read up on ArrayList instead.

PHP CURL DELETE request

switch ($method) {
    case "GET":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
        break;
    case "POST":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        break;
    case "PUT":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
        break;
    case "DELETE":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
        break;
}

How to test whether a service is running from the command line

if you don't mind to combine the net command with grep you can use the following script.

@echo off
net start | grep -x "Service"
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo trouble
goto end
:started
echo started
goto end
:stopped
echo stopped
goto end
:end

Disable cache for some images

Changing the image source is the solution. You can indeed do this by adding a timestamp or random number to the image.

Better would be to add a checksum of eg the data the image represents. This enables caching when possible.

Add carriage return to a string

string s2 = s1.Replace(",", ",\r\n");

Best way to implement keyboard shortcuts in a Windows Forms application?

The best way is to use menu mnemonics, i.e. to have menu entries in your main form that get assigned the keyboard shortcut you want. Then everything else is handled internally and all you have to do is to implement the appropriate action that gets executed in the Click event handler of that menu entry.

Simple function to sort an array of objects

I modified @Geuis 's answer by using lambda and convert it upper case first:

people.sort((a, b) => a.toLocaleUpperCase() < b.toLocaleUpperCase() ? -1 : 1);

How to SELECT based on value of another SELECT

SELECT x.name, x.summary, (x.summary / COUNT(*)) as percents_of_total
FROM tbl t
INNER JOIN 
(SELECT name, SUM(value) as summary
FROM tbl
WHERE year BETWEEN 2000 AND 2001
GROUP BY name) x ON x.name = t.name
GROUP BY x.name, x.summary

Adding +1 to a variable inside a function

Move points into test:

def test():
    points = 0
    addpoint = raw_input ("type ""add"" to add a point")
    ...

or use global statement, but it is bad practice. But better way it move points to parameters:

def test(points=0):
    addpoint = raw_input ("type ""add"" to add a point")
    ...

mssql '5 (Access is denied.)' error during restoring database

The account does not have access to the location for backup file. Take the following steps to access the SQL Server Configuration Manager via Computer Manager easily

  1. Click the Windows key + R to open the Run window.
  2. Type compmgmt.msc in the Open: box.
  3. Click OK.
  4. Expand Services and Applications.
  5. Expand SQL Server Configuration Manager.
  6. Change User Account in Log On As tab .

Now you can Restore Data Base easily

iPhone Debugging: How to resolve 'failed to get the task for process'?

I Had the same issue, but resolved it by following simple following steps :

  1. Make sure you have selected debug rather than release.
  2. In Debug configurations, in project settings, you should have selected developer's profile & no need of specifying the entitlements plist.
  3. Also same setting are there under: Targets: , if not manuall change them to the above for the debug config. It will work.

All the best.

Convert Pandas DataFrame to JSON format

instead of using dataframe.to_json(orient = “records”) use dataframe.to_json(orient = “index”) my above code convert the dataframe into json format of dict like {index -> {column -> value}}

Find commit by hash SHA in Git

git log -1 --format="%an %ae%n%cn %ce" a2c25061

The Pretty Formats section of the git show documentation contains

  • format:<string>

The format:<string> format allows you to specify which information you want to show. It works a little bit like printf format, with the notable exception that you get a newline with %n instead of \n

The placeholders are:

  • %an: author name
  • %ae: author email
  • %cn: committer name
  • %ce: committer email

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Defining TypeScript callback type

Here is an example - accepting no parameters and returning nothing.

class CallbackTest
{
    public myCallback: {(): void;};

    public doWork(): void
    {
        //doing some work...
        this.myCallback(); //calling callback
    }
}

var test = new CallbackTest();
test.myCallback = () => alert("done");
test.doWork();

If you want to accept a parameter, you can add that too:

public myCallback: {(msg: string): void;};

And if you want to return a value, you can add that also:

public myCallback: {(msg: string): number;};

String comparison technique used by Python

Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior.

How to remove specific elements in a numpy array

If you don't know the index, you can't use logical_and

x = 10*np.random.randn(1,100)
low = 5
high = 27
x[0,np.logical_and(x[0,:]>low,x[0,:]<high)]

Laravel 5: Retrieve JSON array from $request

 $postbody='';
 // Check for presence of a body in the request
 if (count($request->json()->all())) {
     $postbody = $request->json()->all();
 }

This is how it's done in laravel 5.2 now.

excel VBA run macro automatically whenever a cell is changed

I was creating a form in which the user enters an email address used by another macro to email a specific cell group to the address entered. I patched together this simple code from several sites and my limited knowledge of VBA. This simply watches for one cell (In my case K22) to be updated and then kills any hyperlink in that cell.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("K22")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

        Range("K22").Select
        Selection.Hyperlinks.Delete

    End If 
End Sub

How to convert a String to CharSequence?

Since String IS-A CharSequence, you can pass a String wherever you need a CharSequence, or assign a String to a CharSequence:

CharSequence cs = "string";
String s = cs.toString();
foo(s); // prints "string"

public void foo(CharSequence cs) { 
  System.out.println(cs);
}

If you want to convert a CharSequence to a String, just use the toString method that must be implemented by every concrete implementation of CharSequence.

Hope it helps.

How do I bind a List<CustomObject> to a WPF DataGrid?

You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:

<Grid>
    <DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799"  ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  CanUserAddRows="False"> </Grid>

C#

Public Class Test 
{
    public string m_field1_Test{get;set;}
    public string m_field2_Test { get; set; }
    public Test()
    {
        m_field1_Test = "field1";
        m_field2_Test = "field2";
    }
    public MainWindow()
    {

        listTest = new List<Test>();

        for (int i = 0; i < 10; i++)
        {
            obj = new Test();
            listTest.Add(obj);

        }

        this.MyDatagrid.ItemsSource = ListTest;

        InitializeComponent();

    }

angular.service vs angular.factory

All the answers here seem to be around service and factory, and that's valid since that was what was being asked about. But it's also important to keep in mind that there are several others including provider(), value(), and constant().

The key to remember is that each one is a special case of the other. Each special case down the chain allowing you to do the same thing with less code. Each one also having some additional limitation.

To decide when to use which you just see which one allows you to do what you want in less code. Here is an image illustrating just how similar they are:

enter image description here

For a complete step by step breakdown and quick reference of when to use each you can visit the blog post where I got this image from:

http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

Minimal example

And just to make what Mizux said as a minimal example:

main_c.c

#include <stdio.h>

int main(void) {
    puts("hello");
}

main_cpp.cpp

#include <iostream>

int main(void) {
    std::cout << "hello" << std::endl;
}

Then, without any Makefile:

make CFLAGS='-g -O3' \
     CXXFLAGS='-ggdb3 -O0' \
     CPPFLAGS='-DX=1 -DY=2' \
     CCFLAGS='--asdf' \
     main_c \
     main_cpp

runs:

cc -g -O3 -DX=1 -DY=2   main_c.c   -o main_c
g++ -ggdb3 -O0 -DX=1 -DY=2   main_cpp.cpp   -o main_cpp

So we understand that:

  • make had implicit rules to make main_c and main_cpp from main_c.c and main_cpp.cpp
  • CFLAGS and CPPFLAGS were used as part of the implicit rule for .c compilation
  • CXXFLAGS and CPPFLAGS were used as part of the implicit rule for .cpp compilation
  • CCFLAGS is not used

Those variables are only used in make's implicit rules automatically: if compilation had used our own explicit rules, then we would have to explicitly use those variables as in:

main_c: main_c.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -o $@ $<

main_cpp: main_c.c
    $(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $@ $<

to achieve a similar affect to the implicit rules.

We could also name those variables however we want: but since Make already treats them magically in the implicit rules, those make good name choices.

Tested in Ubuntu 16.04, GNU Make 4.1.

How to add a spinner icon to button when it's in the Loading state?

The only thing I found that worked was a post here: https://stackoverflow.com/a/44548729/9488229

I improved it, and now it provides all these features:

  • Disable the button after click
  • Show an animated loading icon using native bootstrap
  • Re-enable the button after the page is done loading
  • Text goes back to original when page loading is done

Javascript:

$(document).ready(function () {
    $('.btn').on('click', function() {
        var e=this;
        setTimeout(function() {
            e.innerHTML='<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Searching...';
            e.disabled=true;
        },0);
        return true;
    });
});

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

Learn about CORS, try crossorigin.me is work fine

Example: https://crossorigin.me/https://fr.s.us/js/jquery-ui.css

Not show a message error and continue page white, u need see error is try

http://cors.io/?u=https://fr.s.us/js/jquery-ui.css

enjoin us ;-)

Calling startActivity() from outside of an Activity context

I had the same problem. The problem is with context. If you want to open any links (for example share any link through chooser) pass activity context, not application context.

Dont forget to add myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) if you are not in your activity.

How to disassemble a binary executable in Linux to get the assembly code?

I don't think gcc has a flag for it, since it's primarily a compiler, but another of the GNU development tools does. objdump takes a -d/--disassemble flag:

$ objdump -d /path/to/binary

The disassembly looks like this:

080483b4 <main>:
 80483b4:   8d 4c 24 04             lea    0x4(%esp),%ecx
 80483b8:   83 e4 f0                and    $0xfffffff0,%esp
 80483bb:   ff 71 fc                pushl  -0x4(%ecx)
 80483be:   55                      push   %ebp
 80483bf:   89 e5                   mov    %esp,%ebp
 80483c1:   51                      push   %ecx
 80483c2:   b8 00 00 00 00          mov    $0x0,%eax
 80483c7:   59                      pop    %ecx
 80483c8:   5d                      pop    %ebp
 80483c9:   8d 61 fc                lea    -0x4(%ecx),%esp
 80483cc:   c3                      ret    
 80483cd:   90                      nop
 80483ce:   90                      nop
 80483cf:   90                      nop

How to put a delay on AngularJS instant search?

 <input type="text"
    ng-model ="criteria.searchtext""  
    ng-model-options="{debounce: {'default': 1000, 'blur': 0}}"
    class="form-control" 
    placeholder="Search" >

Now we can set ng-model-options debounce with time and when blur, model need to be changed immediately otherwise on save it will have older value if delay is not completed.

Identifying country by IP address

Here is my solution in Python 3.x to return geo-location info given a dataframe containing IP Address(s); efficient parallelized application of function on vectorized pd.series/dataframe is the way to go.

Will contrast performance of two popular libraries to return location.

TLDR: use geolite2 method.

1. geolite2 package from geolite2 library

Input

# !pip install maxminddb-geolite2
import time
from geolite2 import geolite2
geo = geolite2.reader()
df_1 = train_data.loc[:50,['IP_Address']]

def IP_info_1(ip):
    try:
        x = geo.get(ip)
    except ValueError:   #Faulty IP value
        return np.nan
    try:
        return x['country']['names']['en'] if x is not None else np.nan
    except KeyError:   #Faulty Key value
        return np.nan

s_time = time.time()
# map IP --> country
#apply(fn) applies fn. on all pd.series elements
df_1['country'] = df_1.loc[:,'IP_Address'].apply(IP_info_1)
print(df_1.head(), '\n')
print('Time:',str(time.time()-s_time)+'s \n')

print(type(geo.get('48.151.136.76')))

Output

       IP_Address         country
0   48.151.136.76   United States
1    94.9.145.169  United Kingdom
2   58.94.157.121           Japan
3  193.187.41.186         Austria
4   125.96.20.172           China 

Time: 0.09906983375549316s 

<class 'dict'>

2. DbIpCity package from ip2geotools library

Input

# !pip install ip2geotools
import time
s_time = time.time()
from ip2geotools.databases.noncommercial import DbIpCity
df_2 = train_data.loc[:50,['IP_Address']]
def IP_info_2(ip):
    try:
        return DbIpCity.get(ip, api_key = 'free').country
    except:
        return np.nan
df_2['country'] = df_2.loc[:, 'IP_Address'].apply(IP_info_2)
print(df_2.head())
print('Time:',str(time.time()-s_time)+'s')

print(type(DbIpCity.get('48.151.136.76',api_key = 'free')))

Output

       IP_Address country
0   48.151.136.76      US
1    94.9.145.169      GB
2   58.94.157.121      JP
3  193.187.41.186      AT
4   125.96.20.172      CN

Time: 80.53318452835083s 

<class 'ip2geotools.models.IpLocation'>

A reason why the huge time difference could be due to the Data structure of the output, i.e direct subsetting from dictionaries seems way more efficient than indexing from the specicialized ip2geotools.models.IpLocation object.

Also, the output of the 1st method is dictionary containing geo-location data, subset respecitively to obtain needed info:

x = geolite2.reader().get('48.151.136.76')
print(x)

>>>
    {'city': {'geoname_id': 5101798, 'names': {'de': 'Newark', 'en': 'Newark', 'es': 'Newark', 'fr': 'Newark', 'ja': '??????', 'pt-BR': 'Newark', 'ru': '??????'}},

 'continent': {'code': 'NA', 'geoname_id': 6255149, 'names': {'de': 'Nordamerika', 'en': 'North America', 'es': 'Norteamérica', 'fr': 'Amérique du Nord', 'ja': '?????', 'pt-BR': 'América do Norte', 'ru': '???????? ???????', 'zh-CN': '???'}}, 

'country': {'geoname_id': 6252001, 'iso_code': 'US', 'names': {'de': 'USA', 'en': 'United States', 'es': 'Estados Unidos', 'fr': 'États-Unis', 'ja': '???????', 'pt-BR': 'Estados Unidos', 'ru': '???', 'zh-CN': '??'}}, 

'location': {'accuracy_radius': 1000, 'latitude': 40.7355, 'longitude': -74.1741, 'metro_code': 501, 'time_zone': 'America/New_York'}, 

'postal': {'code': '07102'}, 

'registered_country': {'geoname_id': 6252001, 'iso_code': 'US', 'names': {'de': 'USA', 'en': 'United States', 'es': 'Estados Unidos', 'fr': 'États-Unis', 'ja': '???????', 'pt-BR': 'Estados Unidos', 'ru': '???', 'zh-CN': '??'}}, 

'subdivisions': [{'geoname_id': 5101760, 'iso_code': 'NJ', 'names': {'en': 'New Jersey', 'es': 'Nueva Jersey', 'fr': 'New Jersey', 'ja': '?????????', 'pt-BR': 'Nova Jérsia', 'ru': '???-??????', 'zh-CN': '????'}}]}

What is SYSNAME data type in SQL Server?

Let me list a use case below. Hope it helps. Here I'm trying to find the Table Owner of the Table 'Stud_dtls' from the DB 'Students'. As Mikael mentioned, sysname could be used when there is a need for creating some dynamic sql which needs variables holding table names, column names and server names. Just thought of providing a simple example to supplement his point.

USE Students

DECLARE @TABLE_NAME sysname

SELECT @TABLE_NAME = 'Stud_dtls'

SELECT TABLE_SCHEMA 
  FROM INFORMATION_SCHEMA.Tables
 WHERE TABLE_NAME = @TABLE_NAME

add class with JavaScript

Here is a method adapted from Jquery 2.1.1 that take a dom element instead of a jquery object (so jquery is not needed). Includes type checks and regex expressions:

function addClass(element, value) {
    // Regex terms
    var rclass = /[\t\r\n\f]/g,
        rnotwhite = (/\S+/g);

    var classes,
        cur,
        curClass,
        finalValue,
        proceed = typeof value === "string" && value;

    if (!proceed) return element;

    classes = (value || "").match(rnotwhite) || [];

    cur = element.nodeType === 1
        && (element.className
                ? (" " + element.className + " ").replace(rclass, " ")
                : " "
        );

    if (!cur) return element;

    var j = 0;

    while ((curClass = classes[j++])) {

        if (cur.indexOf(" " + curClass + " ") < 0) {

            cur += curClass + " ";

        }

    }

    // only assign if different to avoid unneeded rendering.
    finalValue = cur.trim();

    if (element.className !== finalValue) {

        element.className = finalValue;

    }

    return element;
};

CSS performance relative to translateZ(0)

It forces the browser to use hardware acceleration to access the device’s graphical processing unit (GPU) to make pixels fly. Web applications, on the other hand, run in the context of the browser, which lets the software do most (if not all) of the rendering, resulting in less horsepower for transitions. But the Web has been catching up, and most browser vendors now provide graphical hardware acceleration by means of particular CSS rules.

Using -webkit-transform: translate3d(0,0,0); will kick the GPU into action for the CSS transitions, making them smoother (higher FPS).

Note: translate3d(0,0,0) does nothing in terms of what you see. It moves the object by 0px in x,y and z axis. It's only a technique to force the hardware acceleration.

Good read here: http://www.smashingmagazine.com/2012/06/21/play-with-hardware-accelerated-css/

How to simulate POST request?

Simple way is to use curl from command-line, for example:

DATA="foo=bar&baz=qux"
curl --data "$DATA" --request POST --header "Content-Type:application/x-www-form-urlencoded" http://example.com/api/callback | python -m json.tool

or here is example how to send raw POST request using Bash shell (JSON request):

exec 3<> /dev/tcp/example.com/80

DATA='{"email": "[email protected]"}'
LEN=$(printf "$DATA" | wc -c)

cat >&3 << EOF
POST /api/retrieveInfo HTTP/1.1
Host: example.com
User-Agent: Bash
Accept: */*
Content-Type:application/json
Content-Length: $LEN
Connection: close

$DATA
EOF

# Read response.
while read line <&3; do
   echo $line
done

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

It's not a Git error message, it's the editor as git uses your default editor.

To solve this:

  1. press "i" (i for insert)
  2. write your merge message
  3. press "esc" (escape)
  4. write ":wq" (write & quit)
  5. then press enter

Java ArrayList how to add elements at the beginning

You can use list methods, remove and add

list.add(lowestIndex, element);
list.remove(highestIndex, element);

java.lang.OutOfMemoryError: Java heap space in Maven

To temporarily work around this problem, I found the following to be the quickest way:

export JAVA_TOOL_OPTIONS="-Xmx1024m -Xms1024m"

How to support different screen size in android

You can figure out the dimensions of the screen dynamically

Display mDisplay= activity.getWindowManager().getDefaultDisplay();
int width= mDisplay.getWidth();
int Height= mDisplay.getHeight();

The layout can be set using the width and the height obtained using this method.

How to give credentials in a batch script that copies files to a network location?

Try using the net use command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.

net use \\<network-location>\<some-share> password /USER:username

Don't leave a trailing \ at the end of the

Unit Testing: DateTime.Now

You can change the class you are testing to use a Func<DateTime> which will be passed through it's constructor parameters, so when you create instance of the class in real code, you can pass () => DateTime.UtcNow to the Func<DateTime> parameter, and on the test, you can pass the time you wish to test.

For example:

    [TestMethod]
    public void MyTestMethod()
    {
        var instance = new MyClass(() => DateTime.MinValue);
        Assert.AreEqual(instance.MyMethod(), DateTime.MinValue);
    } 

    public void RealWorldInitialization()
    {
        new MyClass(() => DateTime.UtcNow);
    }

    class MyClass
    {
        private readonly Func<DateTime> _utcTimeNow;

        public MyClass(Func<DateTime> UtcTimeNow)
        {
            _utcTimeNow = UtcTimeNow;
        }

        public DateTime MyMethod()
        {
            return _utcTimeNow();
        }
    }

Adding new column to existing DataFrame in Python pandas

It seems that in recent Pandas versions the way to go is to use df.assign:

df1 = df1.assign(e=np.random.randn(sLength))

It doesn't produce SettingWithCopyWarning.

d3 add text to circle

Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.

_x000D_
_x000D_
var width = 960,_x000D_
  height = 500,_x000D_
  json = {_x000D_
    "nodes": [{_x000D_
      "x": 100,_x000D_
      "r": 20,_x000D_
      "label": "Node 1",_x000D_
      "color": "red"_x000D_
    }, {_x000D_
      "x": 200,_x000D_
      "r": 25,_x000D_
      "label": "Node 2",_x000D_
      "color": "blue"_x000D_
    }, {_x000D_
      "x": 300,_x000D_
      "r": 30,_x000D_
      "label": "Node 3",_x000D_
      "color": "green"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
  .attr("width", width)_x000D_
  .attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
  .append("pattern")_x000D_
  .attr({_x000D_
    "id": "stripes",_x000D_
    "width": "8",_x000D_
    "height": "8",_x000D_
    "fill": "red",_x000D_
    "patternUnits": "userSpaceOnUse",_x000D_
    "patternTransform": "rotate(60)"_x000D_
  })_x000D_
  .append("rect")_x000D_
  .attr({_x000D_
    "width": "4",_x000D_
    "height": "8",_x000D_
    "transform": "translate(0,0)",_x000D_
    "fill": "grey"_x000D_
  });_x000D_
_x000D_
function plotChart(json) {_x000D_
  /* Define the data for the circles */_x000D_
  var elem = svg.selectAll("g myCircleText")_x000D_
    .data(json.nodes)_x000D_
_x000D_
  /*Create and place the "blocks" containing the circle and the text */_x000D_
  var elemEnter = elem.enter()_x000D_
    .append("g")_x000D_
    .attr("class", "node-group")_x000D_
    .attr("transform", function(d) {_x000D_
      return "translate(" + d.x + ",80)"_x000D_
    })_x000D_
_x000D_
  /*Create the circle for each block */_x000D_
  var circleInner = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", function(d) {_x000D_
      return d.color;_x000D_
    });_x000D_
_x000D_
  var circleOuter = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", "url(#stripes)");_x000D_
_x000D_
  /* Create the text for each block */_x000D_
  elemEnter.append("text")_x000D_
    .text(function(d) {_x000D_
      return d.label_x000D_
    })_x000D_
    .attr({_x000D_
      "text-anchor": "middle",_x000D_
      "font-size": function(d) {_x000D_
        return d.r / ((d.r * 10) / 100);_x000D_
      },_x000D_
      "dy": function(d) {_x000D_
        return d.r / ((d.r * 25) / 100);_x000D_
      }_x000D_
    });_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
  fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Output:

enter image description here

Below is the link to codepen also:

See the Pen D3-Circle-Pattern-Text by Manish Kumar (@mkdudeja) on CodePen.

Thanks, Manish Kumar

yii2 hidden input value

You can do it with the options

echo   $form->field($model, 'hidden1', 
      ['options' => ['value'=> 'your value'] ])->hiddenInput()->label(false);

How to determine when a Git branch was created?

Use:

git reflog

to show all the living cycle of your repository in current folder. The branch name that first appear (from down to up) is the source that was created.

855a3ce HEAD@{0}: checkout: moving from development to feature-sut-46
855a3ce HEAD@{1}: checkout: moving from feature-sut-46 to development
855a3ce HEAD@{2}: checkout: moving from feature-jira35 to feature-sut-46
535dd9d HEAD@{3}: checkout: moving from feature-sut-46 to feature-jira35
855a3ce HEAD@{4}: checkout: moving from development to feature-sut-46
855a3ce HEAD@{5}: checkout: moving from feature-jira35 to development
535dd9d HEAD@{6}: commit: insert the format for vendor specific brower - screen.css
855a3ce HEAD@{7}: checkout: moving from development to feature-jira35
855a3ce HEAD@{8}: checkout: moving from master to development

That mean:

  • Branch development is created (checkout -b) from master

  • Branch feature-jira35 is created (checkout -b) from development

  • Branch feature-jira-sut-46 is created (checkout -b) from development

Error Code: 2013. Lost connection to MySQL server during query

Go to Workbench Edit ? Preferences ? SQL Editor ? DBMS connections read time out : Up to 3000. The error no longer occurred.

Change color of Button when Mouse is over

<Button Content="Click" Width="200" Height="50">
<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="LightBlue" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="Border" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="LightGreen" TargetName="Border" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Button.Style>

What is the proper #include for the function 'sleep()'?

What is the proper #include for the function 'sleep()'?

sleep() isn't Standard C, but POSIX so it should be:

#include <unistd.h>

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

When we create a customer directive, the scope of the directive could be in Isolated scope, It means the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.

  1. Data can be passed as a string using the @ string literal, pass string value, one way binding.
  2. Data can be passed as an object using the = string literal, pass object, 2 ways binding.
  3. Data can be passed as a function the & string literal, calls external function, can pass data from directive to controller.

Powershell import-module doesn't find modules

try with below on powershell:

Set-ExecutionPolicy -ExecutionPolicy Unrestricted
import-module [\path\]XMLHelpers.psm1

Instead of [] put the full path

Full explanation of this and that

Background color of text in SVG

Instead of using a <text> tag, the <foreignObject> tag can be used, which allows for XHTML content with CSS.

Toggle display:none style with JavaScript

Give your ul an id,

<ul id='yourUlId' class="subforums" style="display: none; overflow-x: visible; overflow-y: visible; ">

then do

var yourUl = document.getElementById("yourUlId");
yourUl.style.display = yourUl.style.display === 'none' ? '' : 'none';

IF you're using jQuery, this becomes:

var $yourUl = $("#yourUlId"); 
$yourUl.css("display", $yourUl.css("display") === 'none' ? '' : 'none');

Finally, you specifically said that you wanted to manipulate this css property, and not simply show or hide the underlying element. Nonetheless I'll mention that with jQuery

$("#yourUlId").toggle();

will alternate between showing or hiding this element.

String formatting: % vs. .format vs. string literal

As I discovered today, the old way of formatting strings via % doesn't support Decimal, Python's module for decimal fixed point and floating point arithmetic, out of the box.

Example (using Python 3.3.5):

#!/usr/bin/env python3

from decimal import *

getcontext().prec = 50
d = Decimal('3.12375239e-24') # no magic number, I rather produced it by banging my head on my keyboard

print('%.50f' % d)
print('{0:.50f}'.format(d))

Output:

0.00000000000000000000000312375239000000009907464850 0.00000000000000000000000312375239000000000000000000

There surely might be work-arounds but you still might consider using the format() method right away.

Where is the Global.asax.cs file?

It don't create normally; you need to add it by yourself.

After adding Global.asax by

  • Right clicking your website -> Add New Item -> Global Application Class -> Add

You need to add a class

  • Right clicking App_Code -> Add New Item -> Class -> name it Global.cs -> Add

Inherit the newly generated by System.Web.HttpApplication and copy all the method created Global.asax to Global.cs and also add an inherit attribute to the Global.asax file.

Your Global.asax will look like this: -

<%@ Application Language="C#" Inherits="Global" %>

Your Global.cs in App_Code will look like this: -

public class Global : System.Web.HttpApplication
{
    public Global()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    /// Many other events like begin request...e.t.c, e.t.c
}

How to Sort a List<T> by a property in the object

Make use of LiNQ OrderBy

List<Order> objListOrder=new List<Order> ();
    objListOrder=GetOrderList().OrderBy(o=>o.orderid).ToList();

Send data through routing paths in Angular

There is a lot of confusion on this topic because there are so many different ways to do it.

Here are the appropriate types used in the following screen shots:

private route: ActivatedRoute
private router: Router

1) Required Routing Parameters:

enter image description here

2) Route Optional Parameters:

enter image description here

3) Route Query Parameters:

enter image description here

4) You can use a service to pass data from one component to another without using route parameters at all.

For an example see: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

I have a plunker of this here: https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview

JSON.parse unexpected character error

Not true for the OP, but this error can be caused by using single quotation marks (') instead of double (") for strings.

The JSON spec requires double quotation marks for strings.

E.g:

JSON.parse(`{"myparam": 'myString'}`)

gives the error, whereas

JSON.parse(`{"myparam": "myString"}`)

does not. Note the quotation marks around myString.

Related: https://stackoverflow.com/a/14355724/1461850

How to use BeginInvoke C#

I guess your code relates to Windows Forms.
You call BeginInvoke if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)

If BeginInvoke is called for Delegate type the delegate is just invoked asynchronously.
(Invoke for the sync version.)

If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task with the according context. (TaskScheduler.FromCurrentSynchronizationContext())

And to add a little to already said by others: Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var with lambdas: compiler needs a hint.

UPDATE:

this requires .Net v4.0 and higher

// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();

// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);

// also can be called anywhere. Task  will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked) 
task.Start(scheduler);

If you started the task from other thread and need to wait for its completition task.Wait() will block calling thread till the end of the task.

Read more about tasks here.

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

In VB.NET

<%=Html.ActionLink("Contact Us", "ContactUs", "Home", Nothing, New With {.class = "link"})%>

This will assign css class "link" to the Contact Us.

This will generate following HTML :

<a class="link" href="www.domain.com/Home/ContactUs">Contact Us</a>

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

Without the update-and-join notation (not all DBMS support that), use:

UPDATE QuestionTrackings
   SET QuestionID = (SELECT QuestionID
                        FROM AnswerTrackings
                        WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID)
   WHERE QuestionID IS NULL
     AND EXISTS(SELECT QuestionID
                        FROM AnswerTrackings
                        WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID)

Often in a query like this, you need to qualify the WHERE clause with an EXISTS clause that contains the sub-query. This prevents the UPDATE from trampling over rows where there is no match (usually nulling all the values). In this case, since a missing question ID would change the NULL to NULL, it arguably doesn't matter.

How to open the command prompt and insert commands using Java?

You just need to append your command after start in the string that you are passing.

String command = "cmd.exe /c start "+"*your command*";

Process child = Runtime.getRuntime().exec(command);

MySQL export into outfile : CSV escaping chars

I think your statement should look like:

SELECT id, 
   client,
   project,
   task,
   description, 
   time,
   date  
  INTO OUTFILE '/path/to/file.csv'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  FROM ts

Mainly without the FIELDS ESCAPED BY '""' option, OPTIONALLY ENCLOSED BY '"' will do the trick for description fields etc and your numbers will be treated as numbers in Excel (not strings comprising of numerics)

Also try calling:

SET NAMES utf8;

before your outfile select, that might help getting the character encodings inline (all UTF8)

Let us know how you get on.

Checking if sys.argv[x] is defined

Pretty close to what the originator was trying to do. Here is a function I use:

def get_arg(index):
    try:
        sys.argv[index]
    except IndexError:
        return ''
    else:
        return sys.argv[index]

So a usage would be something like:

if __name__ == "__main__":
    banner(get_arg(1),get_arg(2))

HttpClient not supporting PostAsJsonAsync method C#

I know this reply is too late, I had the same issue and i was adding the System.Net.Http.Formatting.Extension Nuget, after checking here and there I found that the Nuget is added but the System.Net.Http.Formatting.dll was not added to the references, I just reinstalled the Nuget

Getting the name of a variable as a string

You can try the following to retrieve the name of a function you defined (does not work for built-in functions though):

import re
def retrieve_name(func):
    return re.match("<function\s+(\w+)\s+at.*", str(func)).group(1)

def foo(x):
    return x**2

print(retrieve_name(foo))
# foo

android EditText - finished typing event

A different approach ... here is an example: If the user has a delay of 600-1000ms when is typing you may consider he's stopped.

_x000D_
_x000D_
 myEditText.addTextChangedListener(new TextWatcher() {_x000D_
             _x000D_
            private String s;_x000D_
            private long after;_x000D_
   private Thread t;_x000D_
            private Runnable runnable_EditTextWatcher = new Runnable() {_x000D_
                @Override_x000D_
                public void run() {_x000D_
                    while (true) {_x000D_
                        if ((System.currentTimeMillis() - after) > 600)_x000D_
                        {_x000D_
                            Log.d("Debug_EditTEXT_watcher", "(System.currentTimeMillis()-after)>600 ->  " + (System.currentTimeMillis() - after) + " > " + s);_x000D_
                            // Do your stuff_x000D_
                            t = null;_x000D_
                            break;_x000D_
                        }_x000D_
                    }_x000D_
                }_x000D_
            };_x000D_
            _x000D_
            @Override_x000D_
            public void onTextChanged(CharSequence ss, int start, int before, int count) {_x000D_
                s = ss.toString();_x000D_
            }_x000D_
            _x000D_
            @Override_x000D_
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {_x000D_
            }_x000D_
            _x000D_
            @Override_x000D_
            public void afterTextChanged(Editable ss) {_x000D_
                after = System.currentTimeMillis();_x000D_
                if (t == null)_x000D_
                {_x000D_
                    t = new Thread(runnable_EditTextWatcher);_x000D_
                      t.start();_x000D_
                }_x000D_
            }_x000D_
        });
_x000D_
_x000D_
_x000D_

What is the default boolean value in C#?

The default value is indeed false.

However you can't use a local variable is it's not been assigned first.

You can use the default keyword to verify:

bool foo = default(bool);
if (!foo) { Console.WriteLine("Default is false"); }

parse html string with jquery

MarvinS.-

Try:

$.ajax({  
        url: uri+'?js',  
        success: function(data) {  
                var imgAttr = $("img", data).attr('src'); 
                var htmlCode = $(data).html();
                $('#imgSrc').html(imgAttr);
                $('#fullHtmlOutput').html(htmlCode);
        }  
    });

This should load the whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

You may go with Plotly library. It can render interactive 3D plots directly in Jupyter Notebooks.

To do so you first need to install Plotly by running:

pip install plotly

You might also want to upgrade the library by running:

pip install plotly --upgrade

After that in you Jupyter Notebook you may write something like:

# Import dependencies
import plotly
import plotly.graph_objs as go

# Configure Plotly to be rendered inline in the notebook.
plotly.offline.init_notebook_mode()

# Configure the trace.
trace = go.Scatter3d(
    x=[1, 2, 3],  # <-- Put your data instead
    y=[4, 5, 6],  # <-- Put your data instead
    z=[7, 8, 9],  # <-- Put your data instead
    mode='markers',
    marker={
        'size': 10,
        'opacity': 0.8,
    }
)

# Configure the layout.
layout = go.Layout(
    margin={'l': 0, 'r': 0, 'b': 0, 't': 0}
)

data = [trace]

plot_figure = go.Figure(data=data, layout=layout)

# Render the plot.
plotly.offline.iplot(plot_figure)

As a result the following chart will be plotted for you in Jupyter Notebook and you'll be able to interact with it. Of course you will need to provide your specific data instead of suggeseted one.

enter image description here

VHDL - How should I create a clock in a testbench?

Concurrent signal assignment:

library ieee;
use ieee.std_logic_1164.all;

entity foo is
end;
architecture behave of foo is
    signal clk: std_logic := '0';
begin
CLOCK:
clk <=  '1' after 0.5 ns when clk = '0' else
        '0' after 0.5 ns when clk = '1';
end;

ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw

enter image description here

Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.

jQuery Data vs Attr?

The main difference between the two is where it is stored and how it is accessed.

$.fn.attr stores the information directly on the element in attributes which are publicly visible upon inspection, and also which are available from the element's native API.

$.fn.data stores the information in a ridiculously obscure place. It is located in a closed over local variable called data_user which is an instance of a locally defined function Data. This variable is not accessible from outside of jQuery directly.

Data set with attr()

  • accessible from $(element).attr('data-name')
  • accessible from element.getAttribute('data-name'),
  • if the value was in the form of data-name also accessible from $(element).data(name) and element.dataset['name'] and element.dataset.name
  • visible on the element upon inspection
  • cannot be objects

Data set with .data()

  • accessible only from .data(name)
  • not accessible from .attr() or anywhere else
  • not publicly visible on the element upon inspection
  • can be objects

Conversion from List<T> to array T[]

Use ToArray() on List<T>.

Programmatically check Play Store for app updates

Include JSoup in your apps build.gradle file :

dependencies {
    compile 'org.jsoup:jsoup:1.8.3'
}

and get current version like :

currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;

And execute following thread :

private class GetVersionCode extends AsyncTask<Void, String, String> {
    @Override
    protected String doInBackground(Void... voids) {

    String newVersion = null;
    try {
        newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName() + "&hl=it")
                .timeout(30000)
                .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                .referrer("http://www.google.com")
                .get()
                .select(".hAyfc .htlgb")
                .get(7)
                .ownText();
        return newVersion;
    } catch (Exception e) {
        return newVersion;
    }
    }

    @Override
    protected void onPostExecute(String onlineVersion) {
        super.onPostExecute(onlineVersion);
        Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);
        if (onlineVersion != null && !onlineVersion.isEmpty()) {
            if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
                //show dialog
            }
        }
    }

For more details visit : http://revisitingandroid.blogspot.in/2016/12/programmatically-check-play-store-for.html

React component initialize state from props

you could use key value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled read this https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

How to add jQuery code into HTML Page

for latest Jquery. Simply:

<script src="https://code.jquery.com/jquery-latest.min.js"></script>

How to disable Excel's automatic cell reference change after copy/paste?

Click on the cell you want to copy. In the formula bar, highlight the formula.

Press Ctrl C.

Press escape (to take you out of actively editing that formula).

Choose new cell. Ctrl V.

How do I run a Java program from the command line on Windows?

On Windows 7 I had to do the following:

quick way

  1. Install JDK http://www.oracle.com/technetwork/java/javase/downloads
  2. in windows, browse into "C:\Program Files\Java\jdk1.8.0_91\bin" (or wherever the latest version of JDK is installed), hold down shift and right click on a blank area within the window and do "open command window here" and this will give you a command line and access to all the BIN tools. "javac" is not by default in the windows system PATH environment variable.
  3. Follow comments above about how to compile the file ("javac MyFile.java" then "java MyFile") https://stackoverflow.com/a/33149828/194872

long way

  1. Install JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. After installing, in edits the Windows PATH environment variable and adds the following to the path C:\ProgramData\Oracle\Java\javapath. Within this folder are symbolic links to a handful of java executables but "javac" is NOT one of them so when trying to run "javac" from Windows command line it throws an error.
  3. I edited the path: Control Panel -> System -> Advanced tab -> "Environment Variables..." button -> scroll down to "Path", highlight and edit -> replaced the "C:\ProgramData\Oracle\Java\javapath" with a direct path to the java BIN folder "C:\Program Files\Java\jdk1.8.0_91\bin".
  4. This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.

  5. Follow comments above about how to compile the file ("javac MyFile.java" then "java MyFile") https://stackoverflow.com/a/33149828/194872

how to use JSON.stringify and json_decode() properly

When you use JSON stringify then use html_entity_decode first before json_decode.

$tempData = html_entity_decode($tempData);
$cleanData = json_decode($tempData);

What is difference between functional and imperative programming languages?

• Imperative Languages:

  • Efficient execution

  • Complex semantics

  • Complex syntax

  • Concurrency is programmer designed

  • Complex testing, has no referential transparency, has side effects

  • Has state

• Functional Languages:

  • Simple semantics

  • Simple syntax

  • Less efficient execution

  • Programs can automatically be made concurrent

  • Simple testing, has referential transparency, has no side effects

  • Has no state

gradient descent using python and numpy

Following @thomas-jungblut implementation in python, i did the same for Octave. If you find something wrong please let me know and i will fix+update.

Data comes from a txt file with the following rows:

1 10 1000
2 20 2500
3 25 3500
4 40 5500
5 60 6200

think about it as a very rough sample for features [number of bedrooms] [mts2] and last column [rent price] which is what we want to predict.

Here is the Octave implementation:

%
% Linear Regression with multiple variables
%

% Alpha for learning curve
alphaNum = 0.0005;

% Number of features
n = 2;

% Number of iterations for Gradient Descent algorithm
iterations = 10000

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% No need to update after here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

DATA = load('CHANGE_WITH_DATA_FILE_PATH');

% Initial theta values
theta = ones(n + 1, 1);

% Number of training samples
m = length(DATA(:, 1));

% X with one mor column (x0 filled with '1's)
X = ones(m, 1);
for i = 1:n
  X = [X, DATA(:,i)];
endfor

% Expected data must go always in the last column  
y = DATA(:, n + 1)

function gradientDescent(x, y, theta, alphaNum, iterations)
  iterations = [];
  costs = [];

  m = length(y);

  for iteration = 1:10000
    hypothesis = x * theta;

    loss = hypothesis - y;

    % J(theta)    
    cost = sum(loss.^2) / (2 * m);

    % Save for the graphic to see if the algorithm did work
    iterations = [iterations, iteration];
    costs = [costs, cost];

    gradient = (x' * loss) / m; % /m is for the average

    theta = theta - (alphaNum * gradient);
  endfor    

  % Show final theta values
  display(theta)

  % Show J(theta) graphic evolution to check it worked, tendency must be zero
  plot(iterations, costs);

endfunction

% Execute gradient descent
gradientDescent(X, y, theta, alphaNum, iterations);

How to delete a cookie using jQuery?

Worked for me only when path was set, i.e.:

$.cookie('name', null, {path:'/'})

Passing structs to functions

bool data(sampleData *data)
{
}

You need to tell the method which type of struct you are using. In this case, sampleData.

Note: In this case, you will need to define the struct prior to the method for it to be recognized.

Example:

struct sampleData
{
   int N;
   int M;
   // ...
};

bool data(struct *sampleData)
{

}

int main(int argc, char *argv[]) {

      sampleData sd;
      data(&sd);

}

Note 2: I'm a C guy. There may be a more c++ish way to do this.

How do I make a branch point at a specific commit?

git reset --hard 1258f0d0aae

But be careful, if the descendant commits between 1258f0d0aae and HEAD are not referenced in other branches it'll be tedious (but not impossible) to recover them, so you'd better to create a "backup" branch at current HEAD, checkout master, and reset to the commit you want.

Also, be sure that you don't have uncommitted changes before a reset --hard, they will be truly lost (no way to recover).

Import CSV to SQLite

As some websites and other article specifies, its simple have a look to this one. https://www.sqlitetutorial.net/sqlite-import-csv/

We don't need to specify the separator for csv file, becayse csv means comma separated. sqlite> .separator , no need of this line.

sqlite> create table cities(name, population);
sqlite> .mode csv
sqlite> .import c:/sqlite/city_no_header.csv cities

This will work flawlessly :)

PS: My cities.csv with header.


name,population
Abilene,115930
Akron,217074
Albany,93994
Albuquerque,448607
Alexandria,128283
Allentown,106632
Amarillo,173627
Anaheim,328014

What is the difference between Release and Debug modes in Visual Studio?

The main difference is when compiled in debug mode, pdb files are also created which allow debugging (so you can step through the code when its running). This however means that the code isn't optimized as much.

Working copy XXX locked and cleanup failed in SVN

Today I have experienced above issue saying

svn: run 'svn cleanup' to remove locks (type 'svn help cleanup' for details)

And here is my solution, got working

  1. Closed Xcode IDE, from where I was trying to commit changes.
  2. On Mac --> Go to Terminal --> type below command

svn cleanup <Dir path of my SVN project code>

exmaple:

svn cleanup /Users/Ramdhan/SVN_Repo/ProjectName

  1. Hit enter and wait for cleanup done.
  2. Go To XCode IDE and Clean and Build project
  3. Now I can commit my all changes and take update as well.

Hope this will help.

Get url without querystring

    string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
    string path = url.split('?')[0];

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Yes, it is, you will want to use the static Load method on the Assembly class, and then call then call the CreateInstance method on the Assembly instance returned to you from the call to Load.

Also, you can call one of the other static methods starting with "Load" on the Assembly class, depending on your needs.

Getting files by creation date in .NET

this could work for you.

using System.Linq;

DirectoryInfo info = new DirectoryInfo("PATH_TO_DIRECTORY_HERE");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
{
    // DO Something...
}

How can I render HTML from another file in a React component?

You can use dangerouslySetInnerHTML to do this:

import React from 'react';
function iframe() {
    return {
        __html: '<iframe src="./Folder/File.html" width="540" height="450"></iframe>'
    }
}


export default function Exercises() {
    return (
        <div>
            <div dangerouslySetInnerHTML={iframe()} />
        </div>)
}

HTML files must be in the public folder

Convert Dictionary to JSON in Swift

Sometimes it's necessary to print out server's response for debugging purposes. Here's a function I use:

extension Dictionary {

    var json: String {
        let invalidJson = "Not a valid JSON"
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? invalidJson
        } catch {
            return invalidJson
        }
    }

    func printJson() {
        print(json)
    }

}

Example of use:

(lldb) po dictionary.printJson()
{
  "InviteId" : 2,
  "EventId" : 13591,
  "Messages" : [
    {
      "SenderUserId" : 9514,
      "MessageText" : "test",
      "RecipientUserId" : 9470
    },
    {
      "SenderUserId" : 9514,
      "MessageText" : "test",
      "RecipientUserId" : 9470
    }
  ],
  "TargetUserId" : 9470,
  "InvitedUsers" : [
    9470
  ],
  "InvitingUserId" : 9514,
  "WillGo" : true,
  "DateCreated" : "2016-08-24 14:01:08 +00:00"
}

JMS Topic vs Queues

If you have N consumers then:

JMS Topics deliver messages to N of N JMS Queues deliver messages to 1 of N

You said you are "looking to have a 'thing' that will send a copy of the message to each subscriber in the same sequence as that in which the message was received by the ActiveMQ broker."

So you want to use a Topic in order that all N subscribers get a copy of the message.

Python how to exit main function

You can use sys.exit() to exit from the middle of the main function.

However, I would recommend not doing any logic there. Instead, put everything in a function, and call that from __main__ - then you can use return as normal.