THERE IS NO DIFFERENCE BETWEEN smoke and sanity as per ISTQB.
sanity is synonym of smoke.
Check it here : https://glossary.istqb.org/en/search/sanity
The answer provided by Zin Min solved my problem with a single line of code. Excellent!
I was having the same issue of converting a generic List to a generic ObservableCollection to use the values from my List to populate a ComboBox that is participating in binding via a factory class for a WPF Window.
_expediteStatuses = new ObservableCollection<ExpediteStatus>(_db.getExpediteStatuses());
Here is the signature for the getExpediteStatuses method:
public List<ExpediteStatus> getExpediteStatuses()
import json
list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
Write to json File:
with open('/home/ubuntu/test.json', 'w') as fout:
json.dump(list , fout)
Read Json file:
with open(r"/home/ubuntu/test.json", "r") as read_file:
data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
To add to the other answers. I had the same problem and this is the code i used in my express server to allow REST calls:
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'URLs to trust of allow');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if ('OPTIONS' == req.method) {
res.sendStatus(200);
} else {
next();
}
});
What this code basically does is intercepts all the requests and adds the CORS headers, then continue with my normal routes. When there is a OPTIONS request it responds only with the CORS headers.
EDIT: I was using this fix for two separate nodejs express servers on the same machine. In the end I fixed the problem with a simple proxy server.
If you use C/C++, there's no "range" syntax. You can only list all values after each "case" segment. Language Ada or Pascal support range syntax.
Just in normal mode press:
Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at
and updated_at
fields.
class TimeStampMixin(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.
class Posts(TimeStampMixin):
name = models.CharField(max_length=50)
...
...
In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)
If you're casting to a dropdownvalue[]
when mocking data for example, compose it as an array of objects with value and display properties.
example:
[{'value': 'test1', 'display1': 'test display'},{'value': 'test2', 'display': 'test display2'},]
You could use a negative look-ahead assertion:
^(?!tbd_).+
Or a negative look-behind assertion:
(^.{1,3}$|^.{4}(?<!tbd_).*)
Or just plain old character sets and alternations:
^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*
the simpler, the better.
index.php
<?
if (empty($_SERVER['QUERY_STRING'])) {
$name="index";
} else {
$name=basename($_SERVER['QUERY_STRING']);
}
$file="txt/".$name.".htm";
if (is_readable($file)) {
include 'header.php';
readfile($file);
} else {
header("HTTP/1.0 404 Not Found");
exit;
}
?>
header.php
<a href="index.php">Main page</a><br>
<a href=?about>About</a><br>
<a href=?links>Links</a><br>
<br><br>
the actual static html pages stored in the txt
folder in the page
.htm format
Can we see the structure of your table? If I am understanding this, then the assumption made by the query is that a record can be only meta_key - 'lat'
or meta_key = 'long'
not both because each row only has one meta_key
column and can only contain 1 corresponding value, not 2. That would explain why you don't get results when you connect the with an AND
; it's impossible.
Expand your one liner into multiple lines. Then it becomes easy:
f.write(re.split("Tech ID:|Name:|Account #:",line)[-1])
parts = re.split("Tech ID:|Name:|Account #:",line)
wanted_part = parts[-1]
wanted_part_stripped = wanted_part.strip()
f.write(wanted_part_stripped)
In your controller add the following:
@RequestParam(value = "_csrf", required = false) String csrf
And on jsp page add
<form:form modelAttribute="someName" action="someURI?${_csrf.parameterName}=${_csrf.token}
replace $
sign with jQuery
like this:
jQuery(function(){
//your code here
});
create_table :you_table_name do |t| t.references :studant, index: { name: 'name_for_studant_index' } t.references :teacher, index: { name: 'name_for_teacher_index' } end
Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
' replace the target with nothing
' Replace() returns a new String and does not modify the current one
Return stringToCleanUp.Replace(characterToRemove, "")
End Function
Here's more information about VB's Replace function
Beginning of line or beginning of string?
/^CTR.*$/
/
= delimiter
^
= start of string
CTR
= literal CTR
$
= end of string
.*
= zero or more of any character except newline
/^CTR.*$/m
/
= delimiter
^
= start of line
CTR
= literal CTR
$
= end of line
.*
= zero or more of any character except newline
m
= enables multi-line mode, this sets regex to treat every line as a string, so ^
and $
will match start and end of line
While in multi-line mode you can still match the start and end of the string with \A\Z
permanent anchors
/\ACTR.*\Z/m
\A
= means start of string
CTR
= literal CTR
.*
= zero or more of any character except newline
\Z
= end of string
m
= enables multi-line mode
As such, another way to match the start of the line would be like this:
/(\A|\r|\n|\r\n)CTR.*/
or
/(^|\r|\n|\r\n)CTR.*/
\r
= carriage return / old Mac OS newline
\n
= line-feed / Unix/Mac OS X newline
\r\n
= windows newline
Note, if you are going to use the backslash \
in some program string that supports escaping, like the php double quotation marks ""
then you need to escape them first
so to run \r\nCTR.*
you would use it as "\\r\\nCTR.*"
Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.
No there is not. Wikipedia has a nice article about this and provides an alternative using JavaScript and CSS: http://en.wikipedia.org/wiki/Blink_element
In Python 2.7 with iPython:
>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default."""
return environ.get(key, default)
File: ~/venv/lib/python2.7/os.py
Type: function
So we can conclude os.getenv
is just a simple wrapper around os.environ.get
.
You can install android-sdk in different ways
homebrew
Install brew using command from brew.sh
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Install android-sdk
using
brew install android-sdk
Now android-sdk
will be installed in /usr/local/opt/android-sdk
export ANDROID_HOME=/usr/local/opt/android-sdk
If you installed android studio following the website,
android-sdk
will be installed in ~/Library/Android/sdk
export ANDROID_HOME=~/Library/Android/sdk
I think these defaults make sense and its better to stick to it
I was trying do the same of making a particular file my default page, instead of directory structure. So in IIS server I had to go to Default Document, add the page that I want to make as default and at the same time, go to the Web.config file and update the defaultDocument header with "enabled=true". This worked for me. Hopefully it helps.
On latest version of NPM you can just do:
npm install gitAuthor/gitRepo#tag
If the repo is a valid NPM package it will be auto-aliased in package.json as:
{
"NPMPackageName": "gitAuthor/gitRepo#tag"
}
If you could add this to @justingordon 's answer there is no need for manual aliasing now !
I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:
in your onCreate you'll need to use a webview and assign a WebViewClient, as below:
browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());
then handle the click on a phone number like this:
private class InternalWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.indexOf("tel:") > -1) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
return true;
} else {
return false;
}
}
}
Let me know if you need more pointers.
Here is my easy solution for this:
Click on Gradle
button, you can find at the right side top. you will see all the gradle files. Now go to android, and double click on signingReport. Once the gradle build finishes, you see the SHA key. Check the below images for step by step guide.
Once you click on Gradle check the below images. Hope this helps someone.
STEP 1:
STEP 2:
You could try this:
List<Int32> copy = new List<Int32>(original);
or if you're using C# 3 and .NET 3.5, with Linq, you can do this:
List<Int32> copy = original.ToList();
Go to Run configurations in your eclipse then -VM arguments add this: -Dlog4j.configuration=log4j-config_folder/log4j.xml
replace log4j-config_folder with your folder structure where you have your log4j.xml file
Try this to get all the list at first, then your desired element (say the First in your case):
var desiredElementCompoundValueList = new List<YourType>();
dic.Values.ToList().ForEach( elem =>
{
desiredElementCompoundValue.Add(elem.ComponentValue("Dep"));
});
var x = desiredElementCompoundValueList.FirstOrDefault();
To get directly the first element value without a lot of foreach iteration and variable assignment:
var desiredCompoundValue = dic.Values.ToList().Select( elem => elem.CompoundValue("Dep")).FirstOrDefault();
See the difference between the two approaches: in the first one you get the list through a ForEach, then your element. In the second you can get your value in a straight way.
Same result, different computation ;)
Make some invisible HTML tags like <label>, <p>, <input>
etc. and name its id, and the class name is a pattern so that you can retrieve it later.
Let you have two lists maintenance_next[] and maintenance_block_time[] of the same length, and you want to pass these two list's data to javascript using the flask. So you take some invisible label tag and set its tag name is a pattern of list's index and set its class name as value at index.
{% for i in range(maintenance_next|length): %}_x000D_
<label id="maintenance_next_{{i}}" name="{{maintenance_next[i]}}" style="display: none;"></label>_x000D_
<label id="maintenance_block_time_{{i}}" name="{{maintenance_block_time[i]}}" style="display: none;"></label>_x000D_
{% endfor%}
_x000D_
Now you can retrieve the data in javascript using some javascript operation like below -
<script>_x000D_
var total_len = {{ total_len }};_x000D_
_x000D_
for (var i = 0; i < total_len; i++) {_x000D_
var tm1 = document.getElementById("maintenance_next_" + i).getAttribute("name");_x000D_
var tm2 = document.getElementById("maintenance_block_time_" + i).getAttribute("name");_x000D_
_x000D_
//Do what you need to do with tm1 and tm2._x000D_
_x000D_
console.log(tm1);_x000D_
console.log(tm2);_x000D_
}_x000D_
</script>
_x000D_
Just use Hour
and Minute
properties
var date = DateTime.Now;
date.Hour;
date.Minute;
Or you can easily zero the seconds using
var zeroSecondDate = date.AddSeconds(-date.Second);
For faster and short solution you can use HashSet
instead of List
.
a.Overlaps(b);
This method is an O(n) instead of O(n^2) with two lists.
<a href="/shopcart/">
<button class="btn" disabled> Make an Order </button>
</a>
Having disabled attribute on a <button>
by default does not let clicks go through <button>
element up to <a>
element. So <a>
element does not even know that some clicks happened. Manipulate by adding/removing disabled attribute on a <button>
.
I had issues with subtrees and submodules that the other answers suggest... mainly because I am using SourceTree and it seems fairly buggy.
Instead, I ended up using SymLinks and that seems to work well so I am posting it here as a possible alternative.
There is a complete guide here: http://www.howtogeek.com/howto/16226/complete-guide-to-symbolic-links-symlinks-on-windows-or-linux/
But basically you just need to mklink the two paths in an elevated command prompt. Make sure you use the /J hard link prefix. Something along these lines: mklink /J C:\projects\MainProject\plugins C:\projects\SomePlugin
You can also use relative folder paths and put it in a bat to be executed by each person when they first check out your project.
Example: mklink /J .\Assets\TaqtileTools ..\TaqtileHoloTools
Once the folder has been linked you may need to ignore the folder within your main repository that is referencing it. Otherwise you are good to go.
Note I've deleted my duplicate answer from another post as that post was marked as a duplicate question to this one.
In case when 'dotnet restore' not works, following steps may help:
You could use Timestamp.valueOf(String)
. The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...]
, so you might need to change the field separators in your incoming string.
Then again, if you're going to do that then you could just parse it yourself and use the setNanos
method to store the microseconds.
This also could be happening if you're copying code from another document (like a PDF) into your console and trying to run it.
I was trying to run some example code out of a Javascript book I'm reading and was surprised it didn't run in the console.
Apparently, copying from the PDF introduces some unexpected, illegal, and invisible characters into the code.
there are two ways to install mysql client on centOS.
download rpm package from mysql website https://downloads.mysql.com/archives/community/
if you download this rpm package like picture, it's filename like mysql-community-client-8.0.21-1.el8.x86_64.rpm.
then execute sudo rpm -ivh --nodeps --force mysql-community-client-8.0.21-1.el8.x86_64.rpm
can install the rpm package the parameters -ivh
means install, print output, don't verify and check.
if raise error, maybe version conflict, you can execute rpm -pa | grep mysql
to find conflicting package, then execute rpm -e --nodeps <package name>
to remove them, and install once more.
finnaly, you can execute which mysql
, it's success if print /usr/bin/mysql.
Please refer to this official website:
Problem statement – Getting java.awt.HeadlessException while trying to initialize java.awt.Component from the application as the tomcat environment does not have any head(terminal).
Issue – The linux virtual environment was setup without a virtual display terminal. Tried to install virtual display – Xvfb, but Xvfb has been taken off by the redhat community.
Solution – Installed ‘xorg-x11-drv-vmware.x86_64’ using yum install xorg-x11-drv-vmware.x86_64 and executed startx. Finally set the display to :0.0 using export DISPLAY=:0.0 and then executed xhost +
You may wish to consider self-certifying your projects:
This error tells you everything:
undefined reference toHash::insert(int, char)
You're not linking with the implementations of functions defined in Hash.h
. Don't you have a Hash.cpp
to also compile and link?
AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh
. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program
JavaScript runs in the context of the current HTML document, so it won't be able to determine anything about a current user unless it's in the current page or you do AJAX calls to a server-side script to get more information.
JavaScript will not be able to determine your Windows user name.
$ mail -s "test message from centos" [email protected]
hello from centos linux command line
Ctrl+D to finish
If, like me, you're running gVim on Windows then your .vimrc file may be sourcing another 'example' Vimscript file that automatically sets textwidth
(in my case to 78
) for text files.
My answer to a similar question as this one – How to stop gVim wrapping text at column 80 – on the Vi and Vim Stack Exchange site:
In my case, Vitor's comment suggested I run the following:
:verbose set tw?
Doing so gave me the following output:
textwidth=78 Last set from C:\Program Files (x86)\Vim\vim74\vimrc_example.vim
In vimrc_example.vim, I found the relevant lines:
" Only do this part when compiled with support for autocommands. if has("autocmd") ... " For all text files set 'textwidth' to 78 characters. autocmd FileType text setlocal textwidth=78 ...
And I found that my .vimrc is sourcing that file:
source $VIMRUNTIME/vimrc_example.vim
In my case, I don't want
textwidth
to be set for any files, so I just commented out the relevant line in vimrc_example.vim.
Here's the beginnings of a parser class to get you started. This ended up being my solution to a similar problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace XML
{
public class Parser
{
private string _FilePath = string.Empty;
private XDocument _XML_Doc = null;
public Parser(string filePath)
{
_FilePath = filePath;
_XML_Doc = XDocument.Load(_FilePath);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in all elements.
/// </summary>
/// <param name="attributeName"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string attributeName, string newValue)
{
ReplaceAtrribute(string.Empty, attributeName, new List<string> { }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in elements with a given name (elementName).
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, string newValue)
{
ReplaceAtrribute(elementName, attributeName, new List<string> { }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName) and value (oldValue)
/// with the specified new value (newValue) in elements with a given name (elementName).
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="oldValue"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, string oldValue, string newValue)
{
ReplaceAtrribute(elementName, attributeName, new List<string> { oldValue }, newValue);
}
/// <summary>
/// Replaces values of all attributes of a given name (attributeName), which has one of a list of values (oldValues),
/// with the specified new value (newValue) in elements with a given name (elementName).
/// If oldValues is empty then oldValues will be ignored.
/// </summary>
/// <param name="elementName"></param>
/// <param name="attributeName"></param>
/// <param name="oldValues"></param>
/// <param name="newValue"></param>
public void ReplaceAtrribute(string elementName, string attributeName, List<string> oldValues, string newValue)
{
List<XElement> elements = _XML_Doc.Elements().Descendants().ToList();
foreach (XElement element in elements)
{
if (elementName == string.Empty | element.Name.LocalName.ToString() == elementName)
{
if (element.Attribute(attributeName) != null)
{
if (oldValues.Count == 0 || oldValues.Contains(element.Attribute(attributeName).Value))
{ element.Attribute(attributeName).Value = newValue; }
}
}
}
}
public void SaveChangesToFile()
{
_XML_Doc.Save(_FilePath);
}
}
}
If someone wants to try a slightly different approach, they can use FLEX.
HTML
<div class="test">
<div>Div 1</div>
<div>Div 2</div>
<div>Div 3</div>
<div>Div 4</div>
</div>
CSS
.test {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
}
.test > div {
margin-top: 10px;
padding: 20px;
background-color: #FF0000;
}
Here is the fiddle: http://jsfiddle.net/ynemh3c2/ (Try adding/removing divs as well)
Here is where I learned about this: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).
You can use the GUI to do the installation, or you can script the installation of msbuild:
vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet
Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:
You can find documentation about the other available CLI switches here.
The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet
there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin
.
If you don't see them there, try running without --quiet
to see any error messages that may occur during installation.
in my case
my service has function to download Files
and this error only shown up on trying to download Big Files
so I found this answer to Increase maxRequestLength
to needed value in web.config
I know that's weird, but problem solved
if you don't make any upload or download operations maybe this answer will not help you
The best two libraries I found on the net are on github:
Hope that will help you
In order to checkout a git tag , you would execute the following command
git checkout tags/tag-name -b branch-name
eg as mentioned below.
git checkout tags/v1.0 -b v1.0-branch
To fetch the all tags use the command
git fetch --all --tags
I've lifted this from http://www.mail-archive.com/[email protected]/msg02716.html which is an explanation I wrote several years ago.
I'll use JavaScript in this example, but many other languages will work as well.
Our goal is to be able to write a recursive function of 1 variable using only functions of 1 variables and no assignments, defining things by name, etc. (Why this is our goal is another question, let's just take this as the challenge that we're given.) Seems impossible, huh? As an example, let's implement factorial.
Well step 1 is to say that we could do this easily if we cheated a little. Using functions of 2 variables and assignment we can at least avoid having to use assignment to set up the recursion.
// Here's the function that we want to recurse.
X = function (recurse, n) {
if (0 == n)
return 1;
else
return n * recurse(recurse, n - 1);
};
// This will get X to recurse.
Y = function (builder, n) {
return builder(builder, n);
};
// Here it is in action.
Y(
X,
5
);
Now let's see if we can cheat less. Well firstly we're using assignment, but we don't need to. We can just write X and Y inline.
// No assignment this time.
function (builder, n) {
return builder(builder, n);
}(
function (recurse, n) {
if (0 == n)
return 1;
else
return n * recurse(recurse, n - 1);
},
5
);
But we're using functions of 2 variables to get a function of 1 variable. Can we fix that? Well a smart guy by the name of Haskell Curry has a neat trick, if you have good higher order functions then you only need functions of 1 variable. The proof is that you can get from functions of 2 (or more in the general case) variables to 1 variable with a purely mechanical text transformation like this:
// Original
F = function (i, j) {
...
};
F(i,j);
// Transformed
F = function (i) { return function (j) {
...
}};
F(i)(j);
where ... remains exactly the same. (This trick is called "currying" after its inventor. The language Haskell is also named for Haskell Curry. File that under useless trivia.) Now just apply this transformation everywhere and we get our final version.
// The dreaded Y-combinator in action!
function (builder) { return function (n) {
return builder(builder)(n);
}}(
function (recurse) { return function (n) {
if (0 == n)
return 1;
else
return n * recurse(recurse)(n - 1);
}})(
5
);
Feel free to try it. alert() that return, tie it to a button, whatever. That code calculates factorials, recursively, without using assignment, declarations, or functions of 2 variables. (But trying to trace how it works is likely to make your head spin. And handing it, without the derivation, just slightly reformatted will result in code that is sure to baffle and confuse.)
You can replace the 4 lines that recursively define factorial with any other recursive function that you want.
Setup JAVA_OPTS as a system variable with the following content:
JAVA_OPTS="-Xms256m -Xmx512m"
After that in a command prompt run the following commands:
SET JAVA_OPTS="-Xms256m -Xmx512m"
This can be explained as follows:
These values should be changed according to application requirements.
EDIT:
You can also try adding it through the Environment Properties menu which can be found at:
EDIT 2:
JAVA_OPTS is a system variable that stores various settings/configurations for your local Java Virtual Machine. By having JAVA_OPTS set as a system variable all applications running on top of the JVM will take their settings from this parameter.
To setup a system variable you have to complete the steps listed above from 1 to 4.
Try with below code it`s working for me.
AES Encryption
public static String getEncryptedString(String value) {
try {
byte[] key = your Key in byte array;
byte[] input = sault in byte array
return Base64.encodeToString(encrypt(value.getBytes("UTF-8"), key, input), Base64.DEFAULT);
} catch (UnsupportedEncodingException e) {
return "";
}
}
public static byte[] encrypt(byte[] data, byte[] key, byte[] ivs) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
byte[] finalIvs = new byte[16];
int len = ivs.length > 16 ? 16 : ivs.length;
System.arraycopy(ivs, 0, finalIvs, 0, len);
IvParameterSpec ivps = new IvParameterSpec(finalIvs);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivps);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
AES DECRYPTION
public static String decrypt(String encrypted) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
byte[] key = your Key in byte array;
byte[] input = sault in byte array
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(input);
Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
ecipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
byte[] raw = Base64.decode(encrypted, Base64.DEFAULT);
byte[] originalBytes = ecipher.doFinal(raw);
String original = new String(originalBytes, "UTF8");
return original;
}
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
$('#myanchor').click(function(){
window.location.hash = "myanchor"; //set hash
return false; //disables browser anchor jump behavior
});
$(window).bind('hashchange', function () { //detect hash change
var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
//do sth here, hell yeah!
});
This will solve the problem ;)
While the marked answer gets it working, all you really need to add to the webconfig is:
<handlers>
<!-- Your other remove tags-->
<remove name="UrlRoutingModule-4.0"/>
<!-- Your other add tags-->
<add name="UrlRoutingModule-4.0" path="*" verb="*" type="System.Web.Routing.UrlRoutingModule" preCondition=""/>
</handlers>
Note that none of those have a particular order, though you want your removes before your adds.
The reason that we end up getting a 404 is because the Url Routing Module only kicks in for the root of the website in IIS. By adding the module to this application's config, we're having the module to run under this application's path (your subdirectory path), and the routing module kicks in.
GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back.
They're optional though.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
As @pcans suggested you can do this overriding dispatchTouchEvent(MotionEvent event)
in your activity.
Here we get the touch coordinates and comparing them to view bounds. If touch is performed outside of a view then do something.
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View yourView = (View) findViewById(R.id.view_id);
if (yourView != null && yourView.getVisibility() == View.VISIBLE) {
// touch coordinates
int touchX = (int) event.getX();
int touchY = (int) event.getY();
// get your view coordinates
final int[] viewLocation = new int[2];
yourView.getLocationOnScreen(viewLocation);
// The left coordinate of the view
int viewX1 = viewLocation[0];
// The right coordinate of the view
int viewX2 = viewLocation[0] + yourView.getWidth();
// The top coordinate of the view
int viewY1 = viewLocation[1];
// The bottom coordinate of the view
int viewY2 = viewLocation[1] + yourView.getHeight();
if (!((touchX >= viewX1 && touchX <= viewX2) && (touchY >= viewY1 && touchY <= viewY2))) {
Do what you want...
// If you don't want allow touch outside (for example, only hide keyboard or dismiss popup)
return false;
}
}
}
return super.dispatchTouchEvent(event);
}
Also it's not necessary to check view existance and visibility if your activity's layout doesn't change during runtime (e.g. you don't add fragments or replace/remove views from the layout). But if you want to close (or do something similiar) custom context menu (like in the Google Play Store when using overflow menu of the item) it's necessary to check view existance. Otherwise you will get a NullPointerException
.
That seems fairly reasonable for what you're trying to do.
A slightly shorter version which leans on Python to do more of the heavy lifting might be:
for logs in mydir:
for line in mylog:
#...if the conditions are met
list1.append(line)
if any(True for line in list1 if "string" in line):
list2.extend(list1)
del list1
....
The (True for line in list1 if "string" in line)
iterates over list
and emits True
whenever a match is found. any()
uses short-circuit evaluation to return True
as soon as the first True
element is found. list2.extend()
appends the contents of list1
to the end.
An example statement that uses a sub-select :
select * into MyNewTable
from
(
select
*
from
[SomeOtherTablename]
where
EventStartDatetime >= '01/JAN/2018'
)
) mysourcedata
;
note that the sub query must be given a name .. any name .. e.g. above example gives the subquery a name of mysourcedata. Without this a syntax error is issued in SQL*server 2012.
The database should reply with a message like: (9999 row(s) affected)
Spring has org.springframework.core.io.Resource which is designed for such situations. From context.xml you can pass classpath to the bean
<bean class="test.Test1">
<property name="path" value="classpath:/test/test1.xml" />
</bean>
and you get it in your bean as Resource:
public void setPath(Resource path) throws IOException {
File file = path.getFile();
System.out.println(file);
}
output
D:\workspace1\spring\target\test-classes\test\test1.xml
Now you can use it in new FileReader(file)
screen -S your_session_name
Ctrl+a, : sessionname YOUR_SESSION_NAME Enter
You must be inside the session
If you're using an IntelliJ editor such as WebStorm, PyCharm, RubyMine, or IntelliJ IDEA:
In the Environments section of File/Settings/JavaScript/Code Quality Tools/JSHint, click on the jQuery checkbox.
After having compared the options a few answers here provided to F# features, I discovered F# to have a way better support for type-based switching (although I'm still sticking to C#).
You might want to see here and here.
You are trying to to an Insert (with ExecuteNonQuery()
) on a SQL connection that is used by this reader already:
while (myReader.Read())
Either read all the values in a list first, close the reader and then do the insert, or use a new SQL connection.
Adding below to pom.xml solved my problem
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
We had a similar issue. We were trying to GET from:
[RoutePrefix("api/car")]
public class CarController: ApiController{
[HTTPGet]
[Route("")]
public virtual async Task<ActionResult> GetAll(){
}
}
So we would .GET("/api/car")
and this would throw a 405 error
.
The CarController.cs
file was in the directory /api/car
so when we were requesting this api endpoint, IIS would send back an error because it looked like we were trying to access a virtual directory that we were not allowed to.
Option 1: change / rename the directory the controller is in
Option 2: change the route prefix to something that doesn't match the virtual directory.
For executing something in the UI Thread after 5 seconds:
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
//Do something here
}
}, 5000);
Late to the party - here as a pure java solution for those when JNI is not an option.JTransforms
I wrapped Jsch with some utility methods to make it a bit friendlier and called it
Available here: https://github.com/willwarren/jscp
SCP utility to tar a folder, zip it, and scp it somewhere, then unzip it.
Usage:
// create secure context
SecureContext context = new SecureContext("userName", "localhost");
// set optional security configurations.
context.setTrustAllHosts(true);
context.setPrivateKeyFile(new File("private/key"));
// Console requires JDK 1.7
// System.out.println("enter password:");
// context.setPassword(System.console().readPassword());
Jscp.exec(context,
"src/dir",
"destination/path",
// regex ignore list
Arrays.asList("logs/log[0-9]*.txt",
"backups")
);
Also includes useful classes - Scp and Exec, and a TarAndGzip, which work in pretty much the same way.
The best way that I usually use is very simple, I fully disable context menu in the whole page, pure html+javascript:
<body oncontextmenu="return false;">
That's it! I do that because you can always see the source by right click.
Ok, you say: "I can use directly the browser view source" and it's true but we start from the fact that you CAN'T stop downloading html5
videos.
1. Style parent element: style="display:flex; flex-direction:column; flex:1;"
2. Style the element you want to stay at bottom: style="margin-top: auto;"
3. Done! Wow. That was easy.
Example:
<section style="display:flex; flex-wrap:wrap;"> // For demo, not necessary
<div style="display:flex; flex-direction:column; flex:1;"> // Parent element
<button style="margin-top: auto;"> I </button> // Target element
</div>
... 5 more identical divs, for demo ...
</section>
The easiest way is to use LINQ's Union
method:
var aUb = A.Union(B).ToList();
With React 16.8. We can do this with hooks like the following example
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const options = [
"Monty Python and the Holy Grail",
"Monty Python's Life of Brian",
"Monty Python's The Meaning of Life"
];
const filmsByTati = [
{
id: 1,
title: "Jour de fête",
releasedYear: 1949
},
{
id: 2,
title: "Play time",
releasedYear: 1967
},
{
id: 3,
releasedYear: 1958,
title: "Mon Oncle"
}
];
const [selectedOption, setSelectedOption] = useState(options[0]);
const [selectedTatiFilm, setSelectedTatiFilm] = useState(filmsByTati[0]);
return (
<div className="App">
<h1>Select Example</h1>
<select
value={selectedOption}
onChange={(e) => setSelectedOption(e.target.value)}
>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
<span>Selected option: {selectedOption}</span>
<select
value={selectedTatiFilm}
onChange={(e) =>
setSelectedTatiFilm(
filmsByTati.find(film => (film.id == e.target.value))
)
}
>
{filmsByTati.map((film) => (
<option key={film.id} value={film.id}>
{film.title}
</option>
))}
</select>
<span>Selected option: {selectedTatiFilm.title}</span>
</div>
);
}
Maybe this will help someone else, but I've seen this error when the RHS of the mapping contains a colon without enclosing quotes, such as:
someKey: another key: Change to make today: work out more
should be
someKey: another key: "Change to make today: work out more"
I use it like this in asp.net core 3.1
var url =Request.Scheme+"://"+ Request.Host.Value;
I didnt unserstood your objective, Do you wanted your test to automatically download file when test is getting executed, if yes, then You need to use custom Firefox profile in your test execution.
In the custom profile, for first time execute test manually and if download dialog comes, the set it Save it to Disk, also check Always perform this action checkbox which will ensure that file automatically get downloaded next time you run your test.
you may check this http://coenraets.org/blog/2011/10/sample-application-with-jquery-mobile-and-phonegap/ and you can also check http://mobile.tutsplus.com/category/tutorials/phonegap/ which provide you with a good sample
I have done this with OOP style
$res=[1=>[2,3,7,8,19],3=>[4,12],2=>[5,9],5=>6,7=>[10,13],10=>[11,18],8=>[14,20],12=>15,6=>[16,17]];
class MultiToSingle{
public $result=[];
public function __construct($array){
if(!is_array($array)){
echo "Give a array";
}
foreach($array as $key => $value){
if(is_array($value)){
for($i=0;$i<count($value);$i++){
$this->result[]=$value[$i];
}
}else{
$this->result[]=$value;
}
}
}
}
$obj= new MultiToSingle($res);
$array=$obj->result;
print_r($array);
You can also get BLOB object directly from XMLHttpRequest. Setting responseType to blob makes the trick. Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/image.jpg");
xhr.responseType = "blob";
xhr.onload = response;
xhr.send();
And the response function looks like this:
function response(e) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(this.response);
document.querySelector("#image").src = imageUrl;
}
We just have to make an empty image element in HTML:
<img id="image"/>
Most Previous answers were correct but here is the answer and example for Python 3.7. Yes, you can create an abstract class and method. Just as a reminder sometimes a class should define a method which logically belongs to a class, but that class cannot specify how to implement the method. For example, in the below Parents and Babies classes they both eat but the implementation will be different for each because babies and parents eat a different kind of food and the number of times they eat is different. So, eat method subclasses overrides AbstractClass.eat.
from abc import ABC, abstractmethod
class AbstractClass(ABC):
def __init__(self, value):
self.value = value
super().__init__()
@abstractmethod
def eat(self):
pass
class Parents(AbstractClass):
def eat(self):
return "eat solid food "+ str(self.value) + " times each day"
class Babies(AbstractClass):
def eat(self):
return "Milk only "+ str(self.value) + " times or more each day"
food = 3
mom = Parents(food)
print("moms ----------")
print(mom.eat())
infant = Babies(food)
print("infants ----------")
print(infant.eat())
OUTPUT:
moms ----------
eat solid food 3 times each day
infants ----------
Milk only 3 times or more each day
For windows machine (I'm on windows 10), if CTRL + C (Cancel/Abort) Command on cli doesn't work, and the screen shows up like this:
Try to hit ENTER first (or any key would do) and then CTRL + C and the current process would ask if you want to terminate the batch job:
Perhaps CTRL+C only terminates the parent process while npm start runs with other child processes. Quite unsure why you have to hit that extra key though prior to CTRL+ C, but it works better than having to close the command line and start again.
A related issue you might want to check: https://github.com/mysticatea/npm-run-all/issues/74
I have done a microbenchmark (JMH) to compare Moneta (java currency JSR 354 implementation) against BigDecimal in terms of performance.
Surprisingly, BigDecimal performance seems to be better than moneta's. I have used following moneta config:
org.javamoney.moneta.Money.defaults.precision=19 org.javamoney.moneta.Money.defaults.roundingMode=HALF_UP
package com.despegar.bookedia.money;
import org.javamoney.moneta.FastMoney;
import org.javamoney.moneta.Money;
import org.openjdk.jmh.annotations.*;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.concurrent.TimeUnit;
@Measurement(batchSize = 5000, iterations = 10, time = 2, timeUnit = TimeUnit.SECONDS)
@Warmup(iterations = 2)
@Threads(value = 1)
@Fork(value = 1)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.Throughput)
public class BigDecimalBenchmark {
private static final Money MONEY_BASE = Money.of(1234567.3444, "EUR");
private static final Money MONEY_SUBSTRACT = Money.of(232323, "EUR");
private static final FastMoney FAST_MONEY_SUBSTRACT = FastMoney.of(232323, "EUR");
private static final FastMoney FAST_MONEY_BASE = FastMoney.of(1234567.3444, "EUR");
MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
@Benchmark
public void bigdecimal_string() {
new BigDecimal("1234567.3444").subtract(new BigDecimal("232323")).multiply(new BigDecimal("3.4"), mc).divide(new BigDecimal("5.456"), mc);
}
@Benchmark
public void bigdecimal_valueOf() {
BigDecimal.valueOf(12345673444L, 4).subtract(BigDecimal.valueOf(232323L)).multiply(BigDecimal.valueOf(34, 1), mc).divide(BigDecimal.valueOf(5456, 3), mc);
}
@Benchmark
public void fastmoney() {
FastMoney.of(1234567.3444, "EUR").subtract(FastMoney.of(232323, "EUR")).multiply(3.4).divide(5.456);
}
@Benchmark
public void money() {
Money.of(1234567.3444, "EUR").subtract(Money.of(232323, "EUR")).multiply(3.4).divide(5.456);
}
@Benchmark
public void money_static(){
MONEY_BASE.subtract(MONEY_SUBSTRACT).multiply(3.4).divide(5.456);
}
@Benchmark
public void fastmoney_static() {
FAST_MONEY_BASE.subtract(FAST_MONEY_SUBSTRACT).multiply(3.4).divide(5.456);
}
}
Resulting in
Benchmark Mode Cnt Score Error Units
BigDecimalBenchmark.bigdecimal_string thrpt 10 479.465 ± 26.821 ops/s
BigDecimalBenchmark.bigdecimal_valueOf thrpt 10 1066.754 ± 40.997 ops/s
BigDecimalBenchmark.fastmoney thrpt 10 83.917 ± 4.612 ops/s
BigDecimalBenchmark.fastmoney_static thrpt 10 504.676 ± 21.642 ops/s
BigDecimalBenchmark.money thrpt 10 59.897 ± 3.061 ops/s
BigDecimalBenchmark.money_static thrpt 10 184.767 ± 7.017 ops/s
Please feel free to correct me if i'm missing something
There are a couple of options. You can use the --device
flag that use can use to access USB devices without --privileged
mode:
docker run -t -i --device=/dev/ttyUSB0 ubuntu bash
Alternatively, assuming your USB device is available with drivers working, etc. on the host in /dev/bus/usb
, you can mount this in the container using privileged mode and the volumes option. For example:
docker run -t -i --privileged -v /dev/bus/usb:/dev/bus/usb ubuntu bash
Note that as the name implies, --privileged
is insecure and should be handled with care.
Here is my successful run
apiVersion: v1
kind: Pod
metadata:
labels:
run: busybox
name: busybox
spec:
containers:
- command:
- /bin/sh
- -c
- |
echo "running below scripts"
i=0;
while true;
do
echo "$i: $(date)";
i=$((i+1));
sleep 1;
done
name: busybox
image: busybox
The SaveFileDialog
control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.
Set the property InitialDirectory
to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.
That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).
Just as a quick example (there are alternative ways to do it).
savefile
is a control of type SaveFileDialog
SaveFileDialog savefile = new SaveFileDialog();
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (savefile.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(savefile.FileName))
sw.WriteLine ("Hello World!");
}
The existing answers (pass the data in the Intent
passed to startActivity()
) show the normal way to solve this problem. There is another solution that can be used in the odd case where you're creating an Activity that will be started by another app (for example, one of the edit activities in a Tasker plugin) and therefore do not control the Intent
which launches the Activity
.
You can create a base-class Activity
that has a constructor with a parameter, then a derived class that has a default constructor which calls the base-class constructor with a value, as so:
class BaseActivity extends Activity
{
public BaseActivity(String param)
{
// Do something with param
}
}
class DerivedActivity extends BaseActivity
{
public DerivedActivity()
{
super("parameter");
}
}
If you need to generate the parameter to pass to the base-class constructor, simply replace the hard-coded value with a function call that returns the correct value to pass.
If infinity is a possible value, I would use numpy.isfinite
numpy.isfinite(myarray).all()
If the above evaluates to True
, then myarray
contains no, numpy.nan
, numpy.inf
or -numpy.inf
values.
numpy.nan
will be OK with numpy.inf
values, for example:
In [11]: import numpy as np
In [12]: b = np.array([[4, np.inf],[np.nan, -np.inf]])
In [13]: np.isnan(b)
Out[13]:
array([[False, False],
[ True, False]], dtype=bool)
In [14]: np.isfinite(b)
Out[14]:
array([[ True, False],
[False, False]], dtype=bool)
"Conda" installs some of the special packages that might have compiled in C or other languages. You can use "pip install tensorflow" and it will work.
You are passing floats to a classifier which expects categorical values as the target vector. If you convert it to int
it will be accepted as input (although it will be questionable if that's the right way to do it).
It would be better to convert your training scores by using scikit's labelEncoder
function.
The same is true for your DecisionTree and KNeighbors qualifier.
from sklearn import preprocessing
from sklearn import utils
lab_enc = preprocessing.LabelEncoder()
encoded = lab_enc.fit_transform(trainingScores)
>>> array([1, 3, 2, 0], dtype=int64)
print(utils.multiclass.type_of_target(trainingScores))
>>> continuous
print(utils.multiclass.type_of_target(trainingScores.astype('int')))
>>> multiclass
print(utils.multiclass.type_of_target(encoded))
>>> multiclass
Expanding upon @aquinas:
Get-something | select -ExpandProperty PropertyName
or
Get-something | select -expand PropertyName
or
Get-something | select -exp PropertyName
I made these suggestions for those that might just be looking for a single-line command to obtain some piece of information and wanted to include a real-world example.
In managing Office 365 via PowerShell, here was an example I used to obtain all of the users/groups that had been added to the "BookInPolicy" list:
Get-CalendarProcessing [email protected] | Select -expand BookInPolicy
Just using "Select BookInPolicy" was cutting off several members, so thank you for this information!
You forgot to reset the position of the memory stream:
private void Test()
{
System.IO.MemoryStream data = new System.IO.MemoryStream();
System.IO.Stream str = TestStream();
str.CopyTo(data);
// Reset memory stream
data.Seek(0, SeekOrigin.Begin);
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
}
Update:
There is one more thing to note: It usually pays not to ignore the return values of methods. A more robust implementation should check how many bytes have been read after the call returns:
private void Test()
{
using(MemoryStream data = new MemoryStream())
{
using(Stream str = TestStream())
{
str.CopyTo(data);
}
// Reset memory stream
data.Seek(0, SeekOrigin.Begin);
byte[] buf = new byte[data.Length];
int bytesRead = data.Read(buf, 0, buf.Length);
Debug.Assert(bytesRead == data.Length,
String.Format("Expected to read {0} bytes, but read {1}.",
data.Length, bytesRead));
}
}
Yes. std::exception
is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?
boost has an excellent document on good style for exceptions and error handling. It's worth a read.
This might be more desirable, that is use float instead
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
// prepare json data
let mapDict = [ "1":"First", "2":"Second"]
let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData
// create post request
let url = NSURL(string: "http://httpbin.org/post")!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData as Data
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
return
}
do {
let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
print("Result",result!)
} catch {
print("Error -> \(error)")
}
}
task.resume()
About efficient method. You can use CursorLoader. For example I included my action. And you must implement ContentProvider for your data base. https://developer.android.com/reference/android/content/ContentProvider.html
If you implement this, you will call you data base very efficient.
public class LoadEntitiesActionImp implements LoaderManager.LoaderCallbacks<Cursor> {
public interface OnLoadEntities {
void onSuccessLoadEntities(List<Entities> entitiesList);
}
private OnLoadEntities onLoadEntities;
private final Context context;
private final LoaderManager loaderManager;
public LoadEntitiesActionImp(Context context, LoaderManager loaderManager) {
this.context = context;
this.loaderManager = loaderManager;
}
public void setCallback(OnLoadEntities onLoadEntities) {
this.onLoadEntities = onLoadEntities;
}
public void loadEntities() {
loaderManager.initLoader(LOADER_ID, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(context, YOUR_URI, null, YOUR_SELECTION, YOUR_ARGUMENTS_FOR_SELECTION, YOUR_SORT_ORDER);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
As others have said, you are likely reading past the end of the file as you're only checking for x != ' '
. Instead you also have to check for EOF in the inner loop (but in this case don't use a char, but a sufficiently large type):
while ( ! file.eof() )
{
std::ifstream::int_type x = file.get();
while ( x != ' ' && x != std::ifstream::traits_type::eof() )
{
word += static_cast<char>(x);
x = file.get();
}
std::cout << word << '\n';
word.clear();
}
But then again, you can just employ the stream's streaming operators, which already separate at whitespace (and better account for multiple spaces and other kinds of whitepsace):
void readFile( )
{
std::ifstream file("program.txt");
for(std::string word; file >> word; )
std::cout << word << '\n';
}
And even further, you can employ a standard algorithm to get rid of the manual loop altogether:
#include <algorithm>
#include <iterator>
void readFile( )
{
std::ifstream file("program.txt");
std::copy(std::istream_iterator<std::string>(file),
std::istream_itetator<std::string>(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
I found the following solution:
public static Double getFloatAsDouble(Float fValue) {
return Double.valueOf(fValue.toString());
}
If you use float and double instead of Float and Double use the following:
public static double getFloatAsDouble(float value) {
return Double.valueOf(Float.valueOf(value).toString()).doubleValue();
}
Exceptions are usually immutable: you can't change their message after they've been created. What you can do, though, is chain exceptions:
throw new TransactionProblemException(transNbr, originalException);
The stack trace will look like
TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
Declare them outside the subroutines, like this:
Public wbA as Workbook
Public wbB as Workbook
Sub MySubRoutine()
Set wbA = Workbooks.Open("C:\file.xlsx")
Set wbB = Workbooks.Open("C:\file2.xlsx")
OtherSubRoutine
End Sub
Sub OtherSubRoutine()
MsgBox wbA.Name, vbInformation
End Sub
Alternately, you can pass variables between subroutines:
Sub MySubRoutine()
Dim wbA as Workbook
Dim wbB as Workbook
Set wbA = Workbooks.Open("C:\file.xlsx")
Set wbB = Workbooks.Open("C:\file2.xlsx")
OtherSubRoutine wbA, wbB
End Sub
Sub OtherSubRoutine(wb1 as Workbook, wb2 as Workbook)
MsgBox wb1.Name, vbInformation
MsgBox wb2.Name, vbInformation
End Sub
Or use Functions
to return values:
Sub MySubroutine()
Dim i as Long
i = MyFunction()
MsgBox i
End Sub
Function MyFunction()
'Lots of code that does something
Dim x As Integer, y as Double
For x = 1 to 1000
'Lots of code that does something
Next
MyFunction = y
End Function
In the second method, within the scope of OtherSubRoutine
you refer to them by their parameter names wb1
and wb2
. Passed variables do not need to use the same names, just the same variable types. This allows you some freedom, for example you have a loop over several workbooks, and you can send each workbook to a subroutine to perform some action on that Workbook, without making all (or any) of the variables public in scope.
A Note About User Forms
Personally I would recommend keeping Option Explicit
in all of your modules and forms (this prevents you from instantiating variables with typos in their names, like lCoutn
when you meant lCount
etc., among other reasons).
If you're using Option Explicit
(which you should), then you should qualify module-scoped variables for style and to avoid ambiguity, and you must qualify user-form Public
scoped variables, as these are not "public" in the same sense. For instance, i
is undefined, though it's Public
in the scope of UserForm1
:
You can refer to it as UserForm1.i
to avoid the compile error, or since forms are New
-able, you can create a variable object to contain reference to your form, and refer to it that way:
NB: In the above screenshots x
is declared Public x as Long
in another standard code module, and will not raise the compilation error. It may be preferable to refer to this as Module2.x
to avoid ambiguity and possible shadowing in case you re-use variable names...
Of course.
Declaring a class abstract only means that you don't allow it to be instantiated on its own.
Declaring a method abstract means that subclasses have to provide an implementation for that method.
The two are separate concepts, though obviously you can't have an abstract method in a non-abstract class. You can even have abstract classes with final
methods but never the other way around.
Perhaps using the textDecoder will be sufficient.
Not supported in IE though.
var decoder = new TextDecoder('utf-8'),
decodedMessage;
decodedMessage = decoder.decode(message.data);
In this example, we decode the Russian text "??????, ???!", which means "Hello, world." In our TextDecoder() constructor, we specify the Windows-1251 character encoding, which is appropriate for Cyrillic script.
let win1251decoder = new TextDecoder('windows-1251');
let bytes = new Uint8Array([207, 240, 232, 226, 229, 242, 44, 32, 236, 232, 240, 33]);
console.log(win1251decoder.decode(bytes)); // ??????, ???!
_x000D_
The interface for the TextDecoder is described here.
Retrieving a byte array from a string is equally simpel:
const decoder = new TextDecoder();
const encoder = new TextEncoder();
const byteArray = encoder.encode('Größe');
// converted it to a byte array
// now we can decode it back to a string if desired
console.log(decoder.decode(byteArray));
_x000D_
If you have it in a different encoding then you must compensate for that upon encoding. The parameter in the constructor for the TextEncoder is any one of the valid encodings listed here.
If you would like to open link in a new tab, you can:
$("a#thing_to_click").on('click',function(){
window.open('https://yoururl.com', '_blank');
});
This is the best solution, clean and work good :
$("#select2Id").select2 () ;
$("#select2Id").select2 ('container').find ('.select2-search').addClass ('hidden') ;
Then, create a class .hidden { display;none; }
You should look at http://libccv.org/
It's fairly new, but it provides a free open source high level API for face detection.
(...and, I dare say, is pretty damn amazing)
Edit: Worth noting also, that this is one of the few libs that does NOT depend on opencv, and just for kicks, here's a copy of the code for face detection off the documentation page, to give you an idea of whats involved:
#include <ccv.h>
int main(int argc, char** argv)
{
ccv_dense_matrix_t* image = 0;
ccv_read(argv[1], &image, CCV_IO_GRAY | CCV_IO_ANY_FILE);
ccv_bbf_classifier_cascade_t* cascade = ccv_load_bbf_classifier_cascade(argv[2]); ccv_bbf_params_t params = { .interval = 8, .min_neighbors = 2, .accurate = 1, .flags = 0, .size = ccv_size(24, 24) };
ccv_array_t* faces = ccv_bbf_detect_objects(image, &cascade, 1, params);
int i;
for (i = 0; i < faces->rnum; i++)
{
ccv_comp_t* face = (ccv_comp_t*)ccv_array_get(faces, i);
printf("%d %d %d %d\n", face->rect.x, face->rect.y, face->rect.width, face->rect.y);
}
ccv_array_free(faces);
ccv_bbf_classifier_cascade_free(cascade);
ccv_matrix_free(image);
return 0;
}
You can use your IP address to get your 'country', 'city', 'isp' etc...
Just use one of the web-services that provide you with a simple api like http://ip-api.com which provide you a JSON service at http://ip-api.com/json. Simple send a Ajax (or Xhr) request and then parse the JSON to get whatever data you need.
var requestUrl = "http://ip-api.com/json";
$.ajax({
url: requestUrl,
type: 'GET',
success: function(json)
{
console.log("My country is: " + json.country);
},
error: function(err)
{
console.log("Request failed, error= " + err);
}
});
you could utilize bootstrap events:: as
//when modal opens
$('#yourModal').on('shown.bs.modal', function (e) {
$("#pageContent").css({ opacity: 0.5 });
})
//when modal closes
$('#yourModal').on('hidden.bs.modal', function (e) {
$("#pageContent").css({ opacity: 1 });
})
You shouldn't really worry about undefined being renamed. If someone renames undefined, you will be in a lot more trouble than just a few if checks failing. If you really want to protect your code, wrap it in an IFFE (immediately invoked function expression) like this:
(function($, Backbone, _, undefined) {
//undefined is undefined here.
})(jQuery, Backbone, _);
If you're working with global variables (which is wrong already) in a browser enviroment, I'd check for undefined like this:
if(window.neverDefined === undefined) {
//Code works
}
Since global variables are a part of the window object, you can simply check against undefined instead of casting to a string and comparing strings.
On top of that, why are your variables not defined? I've seen a lot of code where they check a variables existence and perform some action based on that. Not once have I seen where this approach has been correct.
For VS Code 1.38 or if you could not find any "lightbulb" button. Pay close attention to the greyed out text above the conflicts; there is a list of actions you can take.
As Fragments Version 1.3.0-alpha01
The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).
Note that, for PIPE
being any command or sequence of commands, then:
if PIPE ; then
# do one thing if PIPE returned with zero status ($?=0)
else
# do another thing if PIPE returned with non-zero status ($?!=0), e.g. error
fi
For the record, [ expr ]
is a shell builtin† shorthand for test expr
.
Since grep
returns with status 0 in case of a match, and non-zero status in case of no matches, you can use:
if grep -lq '^MYSQL_ROLE=master' ; then
# do one thing
else
# do another thing
fi
Note the use of -l
which only cares about the file having at least one match (so that grep
returns as soon as it finds one match, without needlessly continuing to parse the input file.)
†on some platforms [ expr ]
is not a builtin, but an actual executable /bin/[
(whose last argument will be ]
), which is why [ expr ]
should contain blanks around the square brackets, and why it must be followed by one of the command list separators (;
, &&
, ||
, |
, &
, newline)
You have to give a separate id to the label too.
<label for="foo" id="foo_label">text</label>
#foo_label {display: none;}
Or hide the whole row
<tr id="foo_row">/***/</tr>
#foo_row {display: none;}
You don't import methods in Java, only types:
import Dan.Vik;
class Kab
{
public static void main(String args[])
{
Vik Sam = new Vik();
Sam.disp();
}
}
The exception is so-called "static imports", which let you import class (static
) methods from other types.
In my case error is because i have put ">>" twice
mongodump --db=$DB_NAME --collection=$col --out=$BACKUP_LOCATION/$DB_NAME-$BACKUP_DATE >> >> $LOG_PATH
i just correct it as
mongodump --db=$DB_NAME --collection=$col --out=$BACKUP_LOCATION/$DB_NAME-$BACKUP_DATE >> $LOG_PATH
I wrote some ruby code to generate a single 500 element multi-row insert from a series of insert statements which was considerably faster than running the individual inserts. Then I tried simply wrapping the multiple inserts into a single transaction and found that I could get the same kind of speed up with considerably less code.
BEGIN TRANSACTION;
INSERT INTO table VALUES (1,1,1,1);
INSERT INTO table VALUES (2,2,2,2);
...
COMMIT;
package test;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
try {
String fileContent = getFileFromResources("resourcesFile.txt");
System.out.println(fileContent);
} catch (Exception e) {
e.printStackTrace();
}
}
//USE THIS FUNCTION TO READ CONTENT OF A FILE, IT MUST EXIST IN "RESOURCES" FOLDER
public static String getFileFromResources(String fileName) throws Exception {
ClassLoader classLoader = Main.class.getClassLoader();
InputStream stream = classLoader.getResourceAsStream(fileName);
String text = null;
try (Scanner scanner = new Scanner(stream, StandardCharsets.UTF_8.name())) {
text = scanner.useDelimiter("\\A").next();
}
return text;
}
}
You can also use a variant array as the return result to return a sequence of arbitrary values:
Function f(i As Integer, s As String) As Variant()
f = Array(i + 1, "ate my " + s, Array(1#, 2#, 3#))
End Function
Sub test()
result = f(2, "hat")
i1 = result(0)
s1 = result(1)
a1 = result(2)
End Sub
Ugly and bug prone because your caller needs to know what's being returned to use the result, but occasionally useful nonetheless.
There are two approaches that I know of. The first is to tell the browser not to cache the page. Setting the Response to no cache takes care of that, however as you suspect the browser will often ignore this directive. The other approach is to set the date time of your response to a point in the future. I believe all browsers will correct this to the current time when they add the page to the cache, but it will show the page as newer when the comparison is made. I believe there may be some cases where a comparison is not made. I am not sure of the details and they change with each new browser release. Final note I have had better luck with pages that "refresh" themselves (another response directive). The refresh seems less likely to come from the cache.
Hope that helps.
An anonymous namespace makes the enclosed variables, functions, classes, etc. available only inside that file. In your example it's a way to avoid global variables. There is no runtime or compile time performance difference.
There isn't so much an advantage or disadvantage aside from "do I want this variable, function, class, etc. to be public or private?"
mv
in unix-ish systems, move
in dos/windows.
e.g.
C:\> move c:\users\you\somefile.txt c:\temp\newlocation.txt
and
$ mv /home/you/somefile.txt /tmp/newlocation.txt
In order to access the users location in iOS. You need to add two keys
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
into the Info.plist file.
<key>NSLocationWhenInUseUsageDescription</key>
<string>Because I want to know where you are!</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Want to know where you are!</string>
See this below image.
/apps/jboss-eap-6.2/bin/standalone.sh -version
Sample output:
=========================================================================
JBoss Bootstrap Environment
JBOSS_HOME: /apps/jboss-eap-6.2
JAVA: /apps/jdks/jdk_1.7/bin/java
JAVA_OPTS: -server -XX:+UseCompressedOops -Xms1303m -Xmx1303m -XX:MaxPermSize=256m -Djava.net.preferIPv4Stack=true -Djboss.modules.system.pkgs=org.jboss.byteman -Djava.awt.headless=true
=========================================================================
21:07:20,380 INFO [org.jboss.modules] (main) JBoss Modules version 1.3.3.Final-redhat-1
21:07:22,206 INFO [stdout] (main) JBoss EAP 6.2.2.GA (AS 7.3.2.Final-redhat-2)
For Cordova OR Ionic Hybrid App
I have the very similar problem with my Ionic 1 Cordova Build after Integrating the Firebase Cloud Messaging ( FCM )
I fixed this issue by the following steps
So one fix will be: inside platforms/android open project.properties (Its a file ) , you will have something like this
cordova.system.library.1=com.google.android.gms:play-services-ads:+
cordova.system.library.2=com.google.firebase:firebase-core:+
cordova.system.library.3=com.google.firebase:firebase-messaging:+
Replace the
+
Sign with your target version number - like the following
cordova.system.library.1=com.google.android.gms:play-services-ads:9.0.0
cordova.system.library.2=com.google.firebase:firebase-core:9.0.0
cordova.system.library.3=com.google.firebase:firebase-messaging:9.0.0
Save the file
Then take build using
ionic cordova run android
I hope this will work for everyone
Perhaps something like this :
LinkedHashMap<Integer, String> myMap;
public String getFirstKey() {
String out = null;
for (int key : myMap.keySet()) {
out = myMap.get(key);
break;
}
return out;
}
public String getLastKey() {
String out = null;
for (int key : myMap.keySet()) {
out = myMap.get(key);
}
return out;
}
display: none;
_x000D_
This should make the element disappear and not take up any space.
A more modern approach:
const changeFavicon = link => {
let $favicon = document.querySelector('link[rel="icon"]')
// If a <link rel="icon"> element already exists,
// change its href to the given link.
if ($favicon !== null) {
$favicon.href = link
// Otherwise, create a new element and append it to <head>.
} else {
$favicon = document.createElement("link")
$favicon.rel = "icon"
$favicon.href = link
document.head.appendChild($favicon)
}
}
You can then use it like this:
changeFavicon("http://www.stackoverflow.com/favicon.ico")
As a newbie in React world, I came across a similar issues where I could not edit
the textarea and struggled
with binding. It's worth knowing about controlled
and uncontrolled
elements when it comes to react.
The value of the following uncontrolled textarea
cannot be changed because of value
<textarea type="text" value="some value"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following uncontrolled textarea
can be changed because of use of defaultValue
or no value attribute
<textarea type="text" defaultValue="sample"
onChange={(event) => this.handleOnChange(event)}></textarea>
<textarea type="text"
onChange={(event) => this.handleOnChange(event)}></textarea>
The value of the following controlled textarea
can be changed because of how
value is mapped to a state as well as the onChange
event listener
<textarea value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
Here is my solution using different syntax. I prefer the auto-bind
than manual binding however, if I were to not use {(event) => this.onXXXX(event)}
then that would cause the content of textarea
to be not editable OR the event.preventDefault()
does not work as expected. Still a lot to learn I suppose.
class Editor extends React.Component {
constructor(props) {
super(props)
this.state = {
textareaValue: ''
}
}
handleOnChange(event) {
this.setState({
textareaValue: event.target.value
})
}
handleOnSubmit(event) {
event.preventDefault();
this.setState({
textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
})
}
render() {
return <div>
<form onSubmit={(event) => this.handleOnSubmit(event)}>
<textarea rows={10} cols={30} value={this.state.textareaValue}
onChange={(event) => this.handleOnChange(event)}></textarea>
<br/>
<input type="submit" value="Save"/>
</form>
</div>
}
}
ReactDOM.render(<Editor />, document.getElementById("content"));
The versions of libraries are
"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4"
You can implement paging in this simple way by passing PageIndex
Declare @PageIndex INT = 1
Declare @PageSize INT = 20
Select ROW_NUMBER() OVER ( ORDER BY Products.Name ASC ) AS RowNumber,
Products.ID,
Products.Name
into #Result
From Products
SELECT @RecordCount = COUNT(*) FROM #Results
SELECT *
FROM #Results
WHERE RowNumber
BETWEEN
(@PageIndex -1) * @PageSize + 1
AND
(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
Maybe grid on
will suffice.
In Swift Language, if you want to show you need to use it in this way. To assign double value in UITextView, for example:
let result = 23.954893
resultTextView.text = NSString(format:"%.2f", result)
If you want to show in LOG like as objective-c does using NSLog(), then in Swift Language you can do this way:
println(NSString(format:"%.2f", result))
I recently needed to provide a more mobile-friendly, responsive version of a .pdf document, because narrow phone screens required scrolling right and left a lot. To allow just vertical scrolling and avoid horizontal scrolling, the following steps worked for me:
The result looked good and was usable in both desktop and mobile environments.
Suppose we want to find the string variable needle
in the string variable haystack
. There are three gotchas:
string.toUpperCase
and string.toLowerCase
. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i");
followed by needleRegExp.test(haystack)
.needle
. Be careful that needle
does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
.needle
and haystack
, just ignoring case, make sure to add "^"
at the start and "$"
at the end of your regular expression constructor.Taking points (1) and (2) into consideration, an example would be:
var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
alert(result);
To append a new data element,just do this...
Document doc = docBuilder.parse(is);
Node root=doc.getFirstChild();
Element newserver=doc.createElement("new_server");
root.appendChild(newserver);
easy.... 'is' is an InputStream object. rest is similar to your code....tried it just now...
If you don't really need the button element, just move the classes to a regular link:
<div class="btn-group">
<a href="/save/1" class="btn btn-primary active">
<i class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></i> Save
</a>
<a href="/cancel/1" class="btn btn-default">Cancel</a>
</div>
Conversely, you can also change a button to appear like a link:
<button type="button" class="btn btn-link">Link</button>
Is above javascript code the one you're using in your web application ? If so - i would like to point few errors in it: firstly - it has an additional '{' sign in definition of 'success' callback function secondly - it has no ')' sign after definition of ajax callback. Valid code should look like:
$.ajax({
type:'POST',
data: 'args',
url: '@Url.Action("PostBack")',
success: function (data, textStatus, jqXHR) {
alert(data.message);
}
});
try using above code - it gave me 'Yay' alert on all 3 IE versions ( 7,8,9 ).
if when decoding we get a string with ASCII characters, then the string was not encoded
(RoR) ruby solution:
def encoded?(str)
Base64.decode64(str.downcase).scan(/[^[:ascii:]]/).count.zero?
end
def decoded?(str)
Base64.decode64(str.downcase).scan(/[^[:ascii:]]/).count > 0
end
In case the issue surfaces when launching the application from within an IDE (i.e. starting from Eclipse or IntelliJ Idea), and using Maven, the key to the solution is in the Spring-boot Getting Started documentation:
If you are using Maven, execute:
mvn package && java -jar target/gs-spring-boot-0.1.0.jar
The important part of which is adding the package
goal to be run before the application is actually started. (Idea: Run
menu, Edit Configrations...
, Add
, and there select Run Maven Goal
, and specify the package
goal in the field)
Security warning:
rand()
is not a cryptographically secure pseudorandom number generator. Look elsewhere for generating a cryptographically secure pseudorandom string in PHP.
Try this (use strlen
instead of count
, because count
on a string is always 1
):
function randomPassword() {
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
You're getting into looping most likely due to these rules:
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
Just comment it out and try again in a new browser.
Add this code inside your input tag
<?php if ($tag_1 == 'yes') echo "checked='checked'"; ?>
Use SELECT CONVERT(date, '20140327')
In your case,
SELECT [FIRST_NAME],
[MIDDLE_NAME],
[LAST_NAME],
CONVERT(date, [GRADUATION_DATE])
FROM mydb
@vnr you can retrieve all the sort keys associated with a partition key by just using the query using partion key. No need of scan. The point here is partition key is compulsory in a query . Sort key are used only to get range of data
Here is an example for Python 3 that you can edit for Python 2 ;)
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import os
root = Tk()
root.geometry("550x300+300+150")
root.resizable(width=True, height=True)
def openfn():
filename = filedialog.askopenfilename(title='open')
return filename
def open_img():
x = openfn()
img = Image.open(x)
img = img.resize((250, 250), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
panel = Label(root, image=img)
panel.image = img
panel.pack()
btn = Button(root, text='open image', command=open_img).pack()
root.mainloop()
Click on SVG's <g>
element in <object>
with click event. Works 100%. Take a look on the nested javascript in <svg>
. Don't forget to insert window.parent.location.href=
if you want to redirect the parent page.
The most pythonic way to do this to use map
function.
df.columns = df.columns.map(' '.join).str.strip()
Output print(df.columns)
:
Index(['USAF', 'WBAN', 'day', 'month', 's_CD sum', 's_CL sum', 's_CNT sum',
's_PC sum', 'tempf amax', 'tempf amin', 'year'],
dtype='object')
df.columns = [f'{f} {s}' if s != '' else f'{f}'
for f, s in df.columns]
print(df.columns)
Output:
Index(['USAF', 'WBAN', 'day', 'month', 's_CD sum', 's_CL sum', 's_CNT sum',
's_PC sum', 'tempf amax', 'tempf amin', 'year'],
dtype='object')
In theory, malloc gets memory from the operating system for this application. However, since you may only want 4 bytes, and the OS needs to work in pages (often 4k), malloc does a little more than that. It takes a page, and puts it's own information in there so it can keep track of what you have allocated and freed from that page.
When you allocate 4 bytes, for instance, malloc gives you a pointer to 4 bytes. What you may not realize is that the memory 8-12 bytes before your 4 bytes is being used by malloc to make a chain of all the memory you have allocated. When you call free, it takes your pointer, backs up to where it's data is, and operates on that.
When you free memory, malloc takes that memory block off the chain... and may or may not return that memory to the operating system. If it does, than accessing that memory will probably fail, as the OS will take away your permissions to access that location. If malloc keeps the memory ( because it has other things allocated in that page, or for some optimization ), then the access will happen to work. It's still wrong, but it might work.
DISCLAIMER: What I described is a common implementation of malloc, but by no means the only possible one.
A mock is both a technical and a functional object.
The mock is technical. It is indeed created by a mocking library (EasyMock, JMockit and more recently Mockito are known for these) thanks to byte code generation.
The mock implementation is generated in a way where we could instrument it to return a specific value when a method is invoked but also some other things such as verifying that a mock method was invoked with some specific parameters (strict check) or whatever the parameters (no strict check).
Instantiating a mock :
@Mock Foo fooMock
Recording a behavior :
when(fooMock.hello()).thenReturn("hello you!");
Verifying an invocation :
verify(fooMock).hello()
These are clearly not the natural way to instantiate/override the Foo class/behavior. That's why I refer to a technical aspect.
But the mock is also functional because it is an instance of the class we need to isolate from the SUT. And with recorded behaviors on it, we could use it in the SUT in the same way than we would do with a stub.
The stub is just a functional object : that is an instance of the class we need to isolate from the SUT and that's all.
That means that both the stub class and all behaviors fixtures needed during our unit tests have to be defined explicitly.
For example to stub hello()
would need to subclass the Foo
class (or implements its interface it has it) and to override hello()
:
public class HelloStub extends Hello{
public String hello {
return "hello you!";
}
}
If another test scenario requires another value return, we would probably need to define a generic way to set the return :
public class HelloStub extends Hello{
public HelloStub(String helloReturn){
this.helloReturn = helloReturn;
}
public String hello {
return helloReturn;
}
}
Other scenario : if I had a side effect method (no return) and I would check that that method was invoked, I should probably have added a boolean or a counter in the stub class to count how many times the method was invoked.
Conclusion
The stub requires often much overhead/code to write for your unit test. What mock prevents thanks to providing recording/verifying features out of the box.
That's why nowadays, the stub approach is rarely used in practice with the advent of excellent mock libraries.
About the Martin Fowler Article : I don't think to be a "mockist" programmer while I use mocks and I avoid stubs.
But I use mock when it is really required (annoying dependencies) and I favor test slicing and mini-integration tests when I test a class with dependencies which mocking would be an overhead.
This is an example for a RelativeLayout:
RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(R.id.RelativeLayoutLeft);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
relativeLayout.setLayoutParams(params);
With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.
You use an addtional attribute; fill-opacity
: This attribute takes a decimal number between 0.0 and 1.0, inclusive; where 0.0 is completely transparent.
For example:
<rect ... fill="#044B94" fill-opacity="0.4"/>
Additionally you have the following:
stroke-opacity
attribute for the strokeopacity
for the entire objectThought this might help as well. A) it was designed to keep payload to its minimum while sending back to server, after each sort. (instead of sending all elements each time or iterating through many elements that server might chuck out) B) I needed to send back custom id without compromising the id / name of the element. This code will get the list from asp.net server and then upon sorting only 2 values will be sent back: The db id of sorted element and db id of the element next to which it was dropped. Based on those 2 values, server can easily identify the new postion.
<div id="planlist" style="width:1000px">
<ul style="width:1000px">
<li plid="listId1"><a href="#pl-1">List 1</a></li>
<li plid="listId2"><a href="#pl-2">List 1</a></li>
<li plid="listId3"><a href="#pl-3">List 1</a></li>
<li plid="listId4"><a href="#pl-4">List 1</a></li>
</ul>
<div id="pl-1"></div>
<div id="pl-2"></div>
<div id="pl-3"></div>
<div id="pl-4"></div>
</div>
<script type="text/javascript" language="javascript">
$(function () {
var tabs = $("#planlist").tabs();
tabs.find(".ui-tabs-nav").sortable({
axis: "x",
stop: function () {
tabs.tabs("refresh");
},
update: function (event, ui) {
//db id of the item sorted
alert(ui.item.attr('plid'));
//db id of the item next to which the dragged item was dropped
alert(ui.item.prev().attr('plid'));
//make ajax call
}
});
});
</script>
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
I don't know of any out-of-the-box way to achieve this. As you say, this is not how SharePoint lists are intended used. It might work to create a custom site column displaying the path to the document, as this might be used in a filter. Have never tried it, though.
os.chmod(path, 0444)
is the Python command for changing file permissions in Python 2.x. For a combined Python 2 and Python 3 solution, change 0444
to 0o444
.
You could always use Python to call the chmod command using subprocess
. I think this will only work on Linux though.
import subprocess
subprocess.call(['chmod', '0444', 'path'])
No need for the option, just make the preferred width of the last column the maximum and it will take all the extra space.
table.getColumnModel().getColumn(0).setPreferredWidth(27);
table.getColumnModel().getColumn(1).setPreferredWidth(120);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(90);
table.getColumnModel().getColumn(4).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(120);
table.getColumnModel().getColumn(7).setPreferredWidth(100);
table.getColumnModel().getColumn(8).setPreferredWidth(95);
table.getColumnModel().getColumn(9).setPreferredWidth(40);
table.getColumnModel().getColumn(10).setPreferredWidth(Integer.MAX_INT);
I had this same problem - some users could pull from git and everything ran fine. Some would pull and get a very similar exception:
Could not load file or assembly '..., Version=..., Culture=neutral, PublicKeyToken=...' or one of its dependencies. The system cannot find the file specified.
In my particular case it was AjaxMin, so the actual error looked like this but the details don't matter:
Could not load file or assembly 'AjaxMin, Version=4.95.4924.12383, Culture=neutral, PublicKeyToken=21ef50ce11b5d80f' or one of its dependencies. The system cannot find the file specified.
It turned out to be a result of the following actions on a Solution:
NuGet Package Restore was turned on for the Solution.
A Project was added, and a Nuget package was installed into it (AjaxMin in this case).
The Project was moved to different folder in the Solution.
The Nuget package was updated to a newer version.
And slowly but surely this bug started showing up for some users.
The reason was the Solution-level packages/respositories.config kept the old Project reference, and now had a new, second entry for the moved Project. In other words it had this before the reorg:
<repository path="..\Old\packages.config" />
And this after the reorg:
<repository path="..\Old\packages.config" />
<repository path="..\New\packages.config" />
So the first line now refers to a Project that, while on disk, is no longer part of my Solution.
With Nuget Package Restore on, both packages.config files were being read, which each pointed to their own list of Nuget packages and package versions. Until a Nuget package was updated to a newer version however, there weren't any conflicts.
Once a Nuget package was updated, however, only active Projects had their repositories listings updated. NuGet Package Restore chose to download just one version of the library - the first one it encountered in repositories.config, which was the older one. The compiler and IDE proceeded as though it chose the newer one. The result was a run-time exception saying the DLL was missing.
The answer obviously is to delete any lines from this file that referenced Projects that aren't in your Solution.
Use:
sed -e **'s/^[ \t]*//'** name_of_file_from_which_you_want_to_remove_space > 'name _file_where_you_want_to_store_output'
For example:
sed -e 's/^[ \t]*//' file1.txt > output.txt
Note:
s/
: Substitute command ~ replacement for pattern (^[ \t]*
) on each addressed line
^[ \t]*
: Search pattern ( ^ – start of the line; [ \t]*
match one or more blank spaces including tab)
//
: Replace (delete) all matched patterns
Most answers suggest to just add ServerName localhost
to /etc/apache2/apache2.conf
.
But quoting Apache documentation :
The presence of this error message also indicates that Apache httpd was unable to obtain a fully-qualified hostname by doing a reverse lookup on your server's IP address. While the above instructions will get rid of the warning in any case, it is also a good idea to fix your name resolution so that this reverse mapping works.
Therefore adding such a line to /etc/hosts
is probably a more robust solution :
192.0.2.0 foobar.example.com foobar
where 192.0.2.0 is the static IP address of the server named foobar
within the example.com
domain.
One can check the FQDN e.g. with
hostname -A
(shortcut for hostname --all-fqdn
).
I had the same problem, and didn´t want to rewrite the code, so I wrote a function to modify the code and create the inline declarated events:
function compile(qSel){
var matches = [];
var match = null;
var c = 0;
var html = $(qSel).html();
var pattern = /(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/mg;
while (match = pattern.exec(html)) {
var arr = [];
for (i in match) {
if (!isNaN(i)) {
arr.push(match[i]);
}
}
matches.push(arr);
}
var items_with_events = [];
var compiledHtml = html;
for ( var i in matches ){
var item_with_event = {
custom_id : "my_app_identifier_"+i,
code : matches[i][5],
on : matches[i][3],
};
items_with_events.push(item_with_event);
compiledHtml = compiledHtml.replace(/(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/m, "<$2 custom_id='"+item_with_event.custom_id+"' $7 $8");
}
$(qSel).html(compiledHtml);
for ( var i in items_with_events ){
$("[custom_id='"+items_with_events[i].custom_id+"']").bind(items_with_events[i].on, function(){
eval(items_with_events[i].code);
});
}
}
$(document).ready(function(){
compile('#content');
})
This should remove all inline events from the selected node, and recreate them with jquery instead.
I tried the proposed solution above:
df[df["A"].str.contains("Hello|Britain")]
and got an error:
ValueError: cannot mask with array containing NA / NaN values
you can transform NA values into False
, like this:
df[df["A"].str.contains("Hello|Britain", na=False)]
I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824
You can use kill -0
for checking whether a particular pid is running or not.
Assuming, you have list of pid
numbers in a file called pid
in pwd
while true;
do
if [ -s pid ] ; then
for pid in `cat pid`
do
echo "Checking the $pid"
kill -0 "$pid" 2>/dev/null || sed -i "/^$pid$/d" pid
done
else
echo "All your process completed" ## Do what you want here... here all your pids are in finished stated
break
fi
done
why dont you add a "source" column to each of the queries with a static value like
select 'source 1' as Source, column1, column2...
from table1
UNION ALL
select 'source 2' as Source, column1, column2...
from table2
I think you are confusing the working mechanisms between int()
and round()
.
int()
always truncates the decimal numbers if a floating number is given; whereas round()
, in case of 2.5
where 2
and 3
are both within equal distance from 2.5
, Python returns whichever that is more away from the 0 point.
round(2.5) = 3
int(2.5) = 2
I had this same issue. I was working with a team of developers using a Mac and everybody else on the team was running Windows. However we were using the Anroid Studio 2.2-beta with jdk 1.8. If you are on a mac and come across this issue, here is how to solve it. DONT USE Android Studio 2.2-beta. I spent hours trying to debug this error in 2.2-beta. I solved it by simply changing to Android Studio 2.1.3. Our app ran instantly after changing the Android Studio version. Also on Android Studio's website before you download it warns mac users about running jdk 1.8 on 2.2 beta. Guess I should have read the fine print haha
Small edit to @seengee answer: In order to work, you need curly braces around the variable, otherwise you'll get an error.
header("Content-type: {$imginfo['mime']}");
$('.btnMedio').click(function(event) {
// Preventing default action of the event
event.preventDefault();
// Getting the height of the document
var n = $(document).height();
$('html, body').animate({ scrollTop: n }, 50);
// | |
// | --- duration (milliseconds)
// ---- distance from the top
});
Auth::user()->products->sum('price');
The documentation is a little light for some of the Collection
methods but all the query builder aggregates are seemingly available besides avg()
that can be found at http://laravel.com/docs/queries#aggregates.
Firebug lite plugin in Safari extensions didn't work (it's made by slicefactory, I don't think it's offical). btw, #2 works for me!
You can redirect anything or more URL via javascript, Just simple window.location.href
with if else
Use this code,
<script>
if(window.location.href == 'old_url')
{
window.location.href="new_url";
}
//Another url redirect
if(window.location.href == 'old_url2')
{
window.location.href="new_url2";
}
</script>
You can redirect many URL's by this procedure. Thanks.
Instead of using a dot, like: 1.2, try to input like this: 1,2.
As discussed somewhat in the question comments, this is one way you could do it:
<input ... ng-model="$parent.storeDefault" value="{{location.id}}">
The above assumes that each location has a field (e.g., id) that holds a unique value.
Note that $parent.storeDefault is used because ng-repeat creates a child scope, and we want to manipulate the storeDefault parameter on the parent scope.
I may be way way too late but it could help someone in the future.
This answer is a modification to mangu23
answer
I only added a for loop to avoid repetition and to easily add more fragments without boilerplate code.
We first need a list of the fragments that should be displayed
public class MainActivity extends AppCompatActivity{
//...
List<Fragment> fragmentList = new ArrayList<>();
}
Then we need to fill it with our fragments
@Override
protected void onCreate(Bundle savedInstanceState) {
//...
HomeFragment homeFragment = new HomeFragment();
MessagesFragment messagesFragment = new MessagesFragment();
UserFragment userFragment = new UserFragment();
FavoriteFragment favoriteFragment = new FavoriteFragment();
MapFragment mapFragment = new MapFragment();
fragmentList.add(homeFragment);
fragmentList.add(messagesFragment);
fragmentList.add(userFragment);
fragmentList.add(favoriteFragment);
fragmentList.add(mapFragment);
}
And we need a way to know which fragment were selected from the list, so we need getFragmentIndex
function
private int getFragmentIndex(Fragment fragment) {
int index = -1;
for (int i = 0; i < fragmentList.size(); i++) {
if (fragment.hashCode() == fragmentList.get(i).hashCode()){
return i;
}
}
return index;
}
And finally, the displayFragment
method will like this:
private void displayFragment(Fragment fragment) {
int index = getFragmentIndex(fragment);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (fragment.isAdded()) { // if the fragment is already in container
transaction.show(fragment);
} else { // fragment needs to be added to frame container
transaction.add(R.id.placeholder, fragment);
}
// hiding the other fragments
for (int i = 0; i < fragmentList.size(); i++) {
if (fragmentList.get(i).isAdded() && i != index) {
transaction.hide(fragmentList.get(i));
}
}
transaction.commit();
}
In this way, we can call displayFragment(homeFragment)
for example.
This will automatically show the HomeFragment
and hide any other fragment in the list.
This solution allows you to append more fragments to the fragmentList
without having to repeat the if
statements in the old displayFragment
version.
I hope someone will find this useful.
its working for me. I use genymotion for Run App.
1.Firstly i was checked my local ip. goto command mode>> And write ipconfig. Example: Windows 10>> search cmd>>then Write ipconfig . 2. Then get your local ip information >>> 3.Use give your localhost ip and virtual box ip. You need to use virtual box ip for genymotion.Check below screenshot. You can you below any ip under virtualbox host network
Double check if you have set and initial value for int and decimal values to be printed.
This sample is printing an empty line
declare @Number INT
print 'The number is : ' + CONVERT(VARCHAR, @Number)
And this sample is printing -> The number is : 1
declare @Number INT = 1
print 'The number is : ' + CONVERT(VARCHAR, @Number)
No need to extract the month and year.Just need to use the unix_timestamp(date String,format String) function.
For Example:
select yourdate_column
from your_table
where unix_timestamp(yourdate_column, 'yyyy-MM-dd') >= unix_timestamp('2014-06-02', 'yyyy-MM-dd')
and unix_timestamp(yourdate_column, 'yyyy-MM-dd') <= unix_timestamp('2014-07-02','yyyy-MM-dd')
order by yourdate_column limit 10;
I have been struggling to find a proper way to create a timeline, which I could finally do with this modification. Usually while creating a timeline the problem was that I could not add a text to explain each date clearly with a longer text. I modified and further utilized @Zoe Gagnon's latex script. Please feel free to see the following:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{snakes}
\usepackage{rotating}
\begin{document}
\begin{center}
\begin{tikzpicture}
% draw horizontal line
\draw (-5,0) -- (6,0);
% draw vertical lines
\foreach \x in {-5,-4,-3,-2, -1,0,1,2}
\draw (\x cm,3pt) -- (\x cm,-3pt);
% draw nodes
\draw (-5,0) node[below=3pt] {$ 0 $} node[above=3pt] {$ $};
\draw (-4,0) node[below=3pt] {$ 1 $} node[above=3pt] {$\begin{turn}{45}
All individuals vote
\end{turn}$};
\draw (-3,0) node[below=3pt] {$ 2 $} node[above=3pt] {$\begin{turn}{45}
Policy vector decided
\end{turn}$};
\draw (-2,0) node[below=3pt] {$ 3 $} node[above=3pt] {$\begin{turn}{45} Becoming a bureaucrat \end{turn} $};
\draw (-1,0) node[below=3pt] {$ 4 $} node[above=3pt] {$\begin{turn}{45} Bureaucrats' effort choice \end{turn}$};
\draw (0,0) node[below=3pt] {$ 5 $} node[above=3pt] {$\begin{turn}{45} Tax evasion decision made \end{turn}$};
\draw (1,0) node[below=3pt] {$ 6$} node[above=3pt] {$\begin{turn}{45} $p(x_{t})$ tax evaders caught \end{turn}$};
\draw (2,0) node[below=3pt] {$ 7 $} node[above=3pt] {$\begin{turn}{45} $q_{t}$ shirking bureaucrats \end{turn}$};
\draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$\begin{turn}{45} Public service provided \end{turn} $};
\end{tikzpicture}
\end{center}
\end{document}
Longer texts are not allowed, unfortunately. It will look like this:
Read this (supplementary) answer (that is sometimes the answer) to understand where this is going and why some people in this thread complain that "it is still not working"
I wrote exactly same code as one of the answers here. But I still had an issue. I placed break point on
var mi = o.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance );
It executed but mi == null
And it continued behavior like this until I did "re-build" on all projects involved. I was unit testing one assembly while the reflection method was sitting in third assembly. It was totally confusing but I used Immediate Window to discover methods and I found that a private method I tried to unit test had old name (I renamed it). This told me that old assembly or PDB is still out there even if unit test project builds - for some reason project it tests didn't built. "rebuild" worked
I know that this is rather old also. I recently had a need to create a context menu that I inject into other sites that have different properties based n the element clicked.
It's rather rough, and there are probable better ways to achieve this. It uses the jQuery Context menu Library Located Here
I enjoyed creating it and though that you guys might have some use out of it.
Here is the fiddle. I hope that it can hopefully help someone out there.
$(function() {
function createSomeMenu() {
var all_array = '{';
var x = event.clientX,
y = event.clientY,
elementMouseIsOver = document.elementFromPoint(x, y);
if (elementMouseIsOver.closest('a')) {
all_array += '"Link-Fold": {"name": "Link", "icon": "fa-external-link", "items": {"fold2-key1": {"name": "Open Site in New Tab"}, "fold2-key2": {"name": "Open Site in Split Tab"}, "fold2-key3": {"name": "Copy URL"}}},';
}
if (elementMouseIsOver.closest('img')) {
all_array += '"Image-Fold": {"name": "Image","icon": "fa-picture-o","items": {"fold1-key1": {"name":"Download Image"},"fold1-key2": {"name": "Copy Image Location"},"fold1-key3": {"name": "Go To Image"}}},';
}
all_array += '"copy": {"name": "Copy","icon": "copy"},"paste": {"name": "Paste","icon": "paste"},"edit": {"name": "Edit HTML","icon": "fa-code"}}';
return JSON.parse(all_array);
}
// setup context menu
$.contextMenu({
selector: 'body',
build: function($trigger, e) {
return {
callback: function(key, options) {
var m = "clicked: " + key;
console.log(m);
},
items: createSomeMenu()
};
}
});
});
This was already mentioned in a comment by benvoliot above. But, I think it's worth a top-level post because it sure had me scratching my head. I'm posting this in case it helps someone else out.
I wrote a simple test client and the CoreConnectionPNames.CONNECTION_TIMEOUT
timeout works perfectly in that case. The request gets canceled if the server doesn't respond.
Inside the server code I was actually trying to test however, the identical code never times out.
Changing it to time out on the socket connection activity (CoreConnectionPNames.SO_TIMEOUT
) rather than the HTTP connection (CoreConnectionPNames.CONNECTION_TIMEOUT
) fixed the problem for me.
Also, read the Apache docs carefully: http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/params/CoreConnectionPNames.html#CONNECTION_TIMEOUT
Note the bit that says
Please note this parameter can only be applied to connections that are bound to a particular local address.
I hope that saves someone else all the head scratching I went through. That will teach me not to read the documentation thoroughly!
Consider adding this to your CSS to resolve the problem:
button {
margin: 0 auto;
display: block;
}
Perl's behavior, with the code given in the OP can take none or several arguments, and if an argument is a single hyphen -
this is understood as stdin. Moreover, it's always possible to have the filename with $ARGV
.
None of the answers given so far really mimic Perl's behavior in these respects. Here's a pure Bash possibility. The trick is to use exec
appropriately.
#!/bin/bash
(($#)) || set -- -
while (($#)); do
{ [[ $1 = - ]] || exec < "$1"; } &&
while read -r; do
printf '%s\n' "$REPLY"
done
shift
done
Filename's available in $1
.
If no arguments are given, we artificially set -
as the first positional parameter. We then loop on the parameters. If a parameter is not -
, we redirect standard input from filename with exec
. If this redirection succeeds we loop with a while
loop. I'm using the standard REPLY
variable, and in this case you don't need to reset IFS
. If you want another name, you must reset IFS
like so (unless, of course, you don't want that and know what you're doing):
while IFS= read -r line; do
printf '%s\n' "$line"
done
Please check the xml file whether it has any junk character like this ?.If exists,please use the following syntax to remove that.
String XString = writer.toString();
XString = XString.replaceAll("[^\\x20-\\x7e]", "");
Functional Interface:
Example 1:
interface CalcArea { // --functional interface
double calcArea(double rad);
}
Example 2:
interface CalcGeometry { // --functional interface
double calcArea(double rad);
default double calcPeri(double rad) {
return 0.0;
}
}
Example 3:
interface CalcGeometry { // -- not functional interface
double calcArea(double rad);
double calcPeri(double rad);
}
Java8 annotation -- @FunctionalInterface
Applications of Functional Interface:
To learn functional interfaces, learn first default methods in interface, and after learning functional interface, it will be easy to you to understand method reference and lambda expression
I have a workaround for this, see the following example on default value for int&
:
class Helper
{
public:
int x;
operator int&() { return x; }
};
// How to use it:
void foo(int &x = Helper())
{
}
You can do it for any trivial data type you want, such as bool
, double
...
I came across this error due to the improper closing of the statement,
@using (Html.BeginForm("DeleteSelected", "Employee", FormMethod.Post))
{
} //This curly bracket needed to be closed at the end.
In Index.cshtml view file.I didn't close the statement at the end of the program. instead, I ended up closing improperly and ran into this error.
I was sure there isn't a need of checking Controller ActionMethod code because I have returned the Controller method properly to the View. So It has to be the view that's not responding and met with similar Error.
An excellent 2014 IBM research paper “An Updated Performance Comparison of Virtual Machines and Linux Containers” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: Docker is nearly identical to native performance and faster than KVM in every category.
The exception to this is Docker’s NAT — if you use port mapping (e.g., docker run -p 8080:8080
), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., docker run --net=host
) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down).
They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native.
Just because it’s a really useful paper, here are some other figures. Please download it for full access.
Taking a look at Disk I/O:
Now looking at CPU overhead:
Now some examples of memory (read the paper for details, memory can be extra tricky):
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:
public static double SumRootN(int root)
{
double result = 0;
for (int i = 1; i < 10000000; i++)
{
result += Math.Exp(Math.Log(i) / root);
}
return result;
}
Execution of this method takes about 0.5sec.
I called it 200 times using Parallel:
Parallel.For(0, 200, (int i) =>
{
SumRootN(10);
});
Then I called it 200 times using the old-fashioned way:
List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
{
Task t = new Task(() => SumRootN(10));
t.Start();
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.
The only proper way to put server side data into generated javascript code:
<?php $jsString= 'testing'; ?>
<html>
<body>
<script type="text/javascript">
var jsStringFromPhp=<?php echo json_encode($jsString); ?>;
alert(jsStringFromPhp);
</script>
</body>
</html>
With simple quotes the content of your variable is not escaped against HTML and javascript, so it is vulnerable by XSS attacks...
For similar reasons I recommend to use document.createTextNode()
instead of setting the innerHTML
. Ofc. it is slower, but more secure...
this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)
DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
*/
DECLARE NAME_FOUND VARCHAR DEFAULT "";
SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
RETURN NAME_FOUND;
END;//
You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.
So if you want to use your code, you could do:
df = DataFrame(eval(data))
But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:
data = []
for row in result_set:
data.append({'value': row["tag_expression"], 'key': row["tag_name"]})
But probably even this is not needed, as depending on what is exactly in your result_set
you could probably:
DataFrame(result_set)
read_sql_query
function to do this for you (see docs on this)You can wrap your query in another SELECT
:
select count(*)
from
(
select count(SID) tot -- add alias
from Test
where Date = '2012-12-10'
group by SID
) src; -- add alias
In order for it to work, the count(SID)
need a column alias and you have to provide an alias to the subquery itself.
It is easier to remove the "Default Web Site" and create a new one if you do not have any limitations.
I did it and my problem solved.
You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?
I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.
Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.
you can use character classes
/[[:cntrl:]]+/
If you omit the particular index character then use this method
function removeByIndex(str,index) {
return str.slice(0,index) + str.slice(index+1);
}
var str = "Hello world", index=3;
console.log(removeByIndex(str,index));
// Output: "Helo world"
You're looking for a hash based collection (like a Dictionary or Hashset) which the ObservableCollection is not. The best solution might be to derive from a hash based collection and implement INotifyCollectionChanged which will give you the same behavior as an ObservableCollection.