i think Access is a best choice for your case. But you have to split database, see: http://accessblog.net/2005/07/how-to-split-database-into-be-and-fe.html
•How can we make sure that the write-user can make changes to the table data while other users use the data? Do the read-users put locks on tables? Does the write-user have to put locks on the table? Does Access do this for us or do we have to explicitly code this?
there are no read locks unless you put them explicitly. Just use "No Locks"
•Are there any common problems with "MS Access transactions" that we should be aware of?
should not be problems with 1-2 write users
•Can we work on forms, queries etc. while they are being used? How can we "program" without being in the way of the users?
if you split database - then no problem to work on FE design.
•Which settings in MS Access have an influence on how things are handled?
What do you mean?
•Our background is mostly in Oracle, where is Access different in handling multiple users? Is there such thing as "isolation levels" in Access?
no isolation levels in access. BTW, you can then later move data to oracle and keep access frontend, if you have lot of users and big database.
The option I use is as follows:
columns.Bound(p => p.OrderDate).Format("{0:d}").ClientTemplate("#=formatDate(OrderDate)#");
function formatDate(OrderDate) {
var formatedOrderDate = kendo.format("{0:d}", OrderDate);
return formatedOrderDate;
}
I want to share with you one more solution if you have absolute part in the URL
SharePoint solution with ${_spPageContextInfo.webAbsoluteUrl}
HTML:
<button (click)="onNavigate()">Google</button>
TypeScript:
onNavigate()
{
let link = `${_spPageContextInfo.webAbsoluteUrl}/SiteAssets/Pages/help.aspx#/help`;
window.open(link, "_blank");
}
and url will be opened in new tab.
i got the same error, but with no relation to Hibernate. I got scared here from all frightening suggestions, which i guess relevant in case of Hibernate and lazy loading... However, in my case i got the error since in an inner class i had no getters/setters, so the BeanSerializer could not serialize the data...
Adding getters & setters resolved the problem.
I try to write working code example, I test it and everything works.
Hare is code:
HTML:
<input type="file" class="attachment_input" name="file" onchange="checkFileSize(this, @Model.MaxSize.ToString(),@Html.Raw(Json.Encode(Model.FileExtensionsList)))" />
Javascript:
//function for check attachment size and extention match
function checkFileSize(element, maxSize, extentionsArray) {
var val = $(element).val(); //get file value
var ext = val.substring(val.lastIndexOf('.') + 1).toLowerCase(); // get file extention
if ($.inArray(ext, extentionsArray) == -1) {
alert('false extension!');
}
var fileSize = ($(element)[0].files[0].size / 1024 / 1024); //size in MB
if (fileSize > maxSize) {
alert("Large file");// if Maxsize from Model > real file size alert this
}
}
Ok so for me this implementation is working really good:
@property (nonatomic, assign) CGPoint lastContentOffset;
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
_lastContentOffset.x = scrollView.contentOffset.x;
_lastContentOffset.y = scrollView.contentOffset.y;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
if (_lastContentOffset.x < (int)scrollView.contentOffset.x) {
// moved right
NSLog(@"right");
}
else if (_lastContentOffset.x > (int)scrollView.contentOffset.x) {
// moved left
NSLog(@"left");
}else if (_lastContentOffset.y<(int)scrollView.contentOffset.y){
NSLog(@"up");
}else if (_lastContentOffset.y>(int)scrollView.contentOffset.y){
NSLog(@"down");
[self.txtText resignFirstResponder];
}
}
So this will fire textView to dismiss after drag ends
This worked for me.
using System.IO;
//
string readStr = File.ReadAllText(file.FullName);
string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);
You have to use XmlSerializer for XML serialization. Below is a sample snippet.
XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
var subReq = new MyObject();
var xml = "";
using(var sww = new StringWriter())
{
using(XmlWriter writer = XmlWriter.Create(sww))
{
xsSubmit.Serialize(writer, subReq);
xml = sww.ToString(); // Your XML
}
}
Immediately after your execute statement you can have an if statement. For example
ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}
You would write a comparator class, for example:
struct CompareAge {
bool operator()(Person const & p1, Person const & p2) {
// return "true" if "p1" is ordered before "p2", for example:
return p1.age < p2.age;
}
};
and use that as the comparator argument:
priority_queue<Person, vector<Person>, CompareAge>
Using greater
gives the opposite ordering to the default less
, meaning that the queue will give you the lowest value rather than the highest.
The answer is YES, but shouldn't use 'Background Fetch' or 'Remote notification'. PushKit is the answer you desire.
In summary, PushKit, the new framework in ios 8, is the new push notification mechanism which can silently launch your app into the background with no visual alert prompt even your app was killed by swiping out from app switcher, amazingly you even cannot see it from app switcher.
PushKit reference from Apple:
The PushKit framework provides the classes for your iOS apps to receive pushes from remote servers. Pushes can be of one of two types: standard and VoIP. Standard pushes can deliver notifications just as in previous versions of iOS. VoIP pushes provide additional functionality on top of the standard push that is needed to VoIP apps to perform on-demand processing of the push before displaying a notification to the user.
To deploy this new feature, please refer to this tutorial: https://zeropush.com/guide/guide-to-pushkit-and-voip - I've tested it on my device and it works as expected.
Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:
Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)
or like this:
Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)
Your onCreate()
method has several huge flaws:
1) onCreate
prepares your Activity - so nothing that you do here will be made visible to the user until this method finishes! For example - you will never be able to alter a TextView
's text here more than ONE time as only the last change will be drawn and thus visible to the user!
2) Keep in mind that an Android program will - by default - run in ONE thread only! Thus: never use Thread.sleep()
or Thread.wait()
in your main thread which is responsible for your UI! (read "Keep your App Responsive" for further information!)
What your initialization of your Activity does is:
TextView
object t
!TextView
in the variable t
later.t
(but keep in mind: it will be displayed only after onCreate()
finishes and the main event loop of your application runs!)onCreate
method - this must never be done as it stops all UI activity and will definitely force an ANR (Application Not Responding, see link above!)onCreate()
method finishes and several other Activity lifecycle methods have been processed!The solution:
Set text only once in onCreate()
- this must be the first text that should be visible.
Create a Runnable
and a Handler
private final Runnable mUpdateUITimerTask = new Runnable() {
public void run() {
// do whatever you want to change here, like:
t.setText("Second text to display!");
}
};
private final Handler mHandler = new Handler();
install this runnable as a handler, possible in onCreate()
(but read my advice below):
// run the mUpdateUITimerTask's run() method in 10 seconds from now
mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
Advice: be sure you know an Activity
's lifecycle! If you do stuff like that in onCreate()
this will only happen when your Activity
is created the first time! Android will possibly keep your Activity
alive for a longer period of time, even if it's not visible!
When a user "starts" it again - and it is still existing - you will not see your first text anymore!
=> Always install handlers in onResume()
and disable them in onPause()
! Otherwise you will get "updates" when your Activity
is not visible at all!
In your case, if you want to see your first text again when it is re-activated, you must set it in onResume()
, not onCreate()
!
If you want to always prune
when you fetch
, I can suggest to use Aliases.
Just type git config -e
to open your editor and change the configuration for a specific project and add a section like
[alias]
pfetch = fetch --prune
the when you fetch with git pfetch
the prune will be done automatically.
Clone is slow. For performance should probably start with blank hash and merge. Doesn't cover case of nested hashes...
require 'benchmark'
def bench Benchmark.bm do |b|
test = {'a' => 1, 'b' => 2, 'c' => 3, 4 => 'd'}
b.report 'clone' do
1_000_000.times do |i|
h = test.clone
h['new'] = 5
end
end
b.report 'merge' do
1_000_000.times do |i|
h = {}
h['new'] = 5
h.merge! test
end
end
b.report 'inject' do
1_000_000.times do |i|
h = test.inject({}) do |n, (k, v)|
n[k] = v;
n
end
h['new'] = 5
end
end
end
end
bench user system total ( real) clone 1.960000 0.080000 2.040000 ( 2.029604) merge 1.690000 0.080000 1.770000 ( 1.767828) inject 3.120000 0.030000 3.150000 ( 3.152627)
You will want to use the YYYYMMDD for unambiguous date determination in SQL Server.
insert into table1(approvaldate)values('20120618 10:34:09 AM');
If you are married to the dd-mm-yy hh:mm:ss xm
format, you will need to use CONVERT with the specific style.
insert into table1 (approvaldate)
values (convert(datetime,'18-06-12 10:34:09 PM',5));
5
here is the style for Italian dates. Well, not just Italians, but that's the culture it's attributed to in Books Online.
There are lots of differences between ISO 8601 and RFC 3339. Here is some examples to give you an idea:
2020-12-09T16:09:53+00:00
is a date time value that is compliant both both standards.
2020-12-09 16:09:53+00:00
uses a space to separate the date and time. This is allowed by RFC 3339 but not allowed by ISO 8601.
2020-12-09T16:09:53-00:00
has a negative sign in the time offset. This is allowed by RFC 3339 but not allowed by ISO 8601.
20201209T160953Z
omits the hyphens. This is allowed by ISO 8601 but not allowed by RFC 3339.
ISO 8601 allows for things like ordinal dates such as 2020-344
which represents the 344th day of year 2020. RFC 3339 doesn't allow for that.
For your questions:
Is one just an extension?
No. As shown above each standard supports syntax variations not supported by the the other standard. So one syntax is not a superset or an extension of the other.
Should I use one over the other?
Of course this depends on your scenario. A safe general strategy is to generate date time strings that are valid by both standards.
Another good general strategy is to use an existing standard library for parsing/formatting date time strings and not write custom implementations unless you are addressing a genuinely custom scenario.
Do I really need to care that bad?
Well, that's up to you. Most regular developers who deal with date time strings should have a high level understanding but don't need to dive into the details.
The line
SELECT @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))
is wrong.
@Prefix
is 'J'
and LEN(...anything...)
is an int
, hence the type mismatch.
It seems to me, you actually want to do,
SELECT
@maxCode = MAX(
CAST(SUBSTRING(
Voucher_No,
@startFrom + 1,
LEN(Voucher_No) - (@startFrom + 1)) AS INT)
FROM
dbo.Journal_Entry;
SELECT @Prefix + CAST(@maxCode AS VARCHAR(10));
but, I couldn't say. If you illustrated before and after data, it would help.
The Swift version from String to Data and back to String:
Xcode 10.1 • Swift 4.2.1
extension Data {
var string: String? {
return String(data: self, encoding: .utf8)
}
}
extension StringProtocol {
var data: Data {
return Data(utf8)
}
}
extension String {
var base64Decoded: Data? {
return Data(base64Encoded: self)
}
}
Playground
let string = "Hello World" // "Hello World"
let stringData = string.data // 11 bytes
let base64EncodedString = stringData.base64EncodedString() // "SGVsbG8gV29ybGQ="
let stringFromData = stringData.string // "Hello World"
let base64String = "SGVsbG8gV29ybGQ="
if let data = base64String.base64Decoded {
print(data) // 11 bytes
print(data.base64EncodedString()) // "SGVsbG8gV29ybGQ="
print(data.string ?? "nil") // "Hello World"
}
let stringWithAccent = "Olá Mundo" // "Olá Mundo"
print(stringWithAccent.count) // "9"
let stringWithAccentData = stringWithAccent.data // "10 bytes" note: an extra byte for the acute accent
let stringWithAccentFromData = stringWithAccentData.string // "Olá Mundo\n"
You also need the change post-max-size.
I use this way, you should put a backslash at the end of the directory name to avoid that place exists in a file without extension with the same name as the directory you specified, never use "C:\VTS" because it can a file exists with the name "VTS" saved in "C:" partition, the correct way is to use "C:\VTS\", check out the backslash after the VTS, so is the right way.
@echo off
@break off
@title Create folder with batch but only if it doesn't already exist - D3F4ULT
@color 0a
@cls
setlocal EnableDelayedExpansion
if not exist "C:\VTS\" (
mkdir "C:\VTS\"
if "!errorlevel!" EQU "0" (
echo Folder created successfully
) else (
echo Error while creating folder
)
) else (
echo Folder already exists
)
pause
exit
By XPath: inspect the element on target page, copy Xpath and use the below script:worked for me.
WebElement nameInputField = driver.findElement(By.xpath("html/body/div[6]/div[1]/div[3]/div/div/div[1]/div[3]/ul/li[4]/a"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", nameInputField);
It looks like you want the return
keyword
def check_ping():
hostname = "taylor"
response = os.system("ping -c 1 " + hostname)
# and then check the response...
if response == 0:
pingstatus = "Network Active"
else:
pingstatus = "Network Error"
return pingstatus
You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:
pingstatus = check_ping()
NOTE: ping -c
is for Linux, for Windows use ping -n
Some info on python functions:
http://www.tutorialspoint.com/python/python_functions.htm
http://www.learnpython.org/en/Functions
It's probably worth going through a good introductory tutorial to Python, which will cover all the fundamentals. I recommend investigating Udacity.com and codeacademy.com
You can use DataTable.Select
:
var strExpr = "CostumerID = 1 AND OrderCount > 2";
var strSort = "OrderCount DESC";
// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);
Or you can use DataView
:
ds.Tables[0].DefaultView.RowFilter = strExpr;
UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:
var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);
# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.
keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]
Trust this certificate: [Yes]
changeit is the default truststore password
All the methods and variables in Color are static. You can not instantiate a Color object.
The Color class defines methods for creating and converting color ints.
Colors are represented as packed ints, made up of 4 bytes: alpha, red, green, blue.
The values are unpremultiplied, meaning any transparency is stored solely in the alpha component, and not in the color components.
The components are stored as follows (alpha << 24) | (red << 16) | (green << 8) | blue.
Each component ranges between 0..255 with 0 meaning no contribution for that component, and 255 meaning 100% contribution.
Thus opaque-black would be 0xFF000000 (100% opaque but no contributions from red, green, or blue), and opaque-white would be 0xFFFFFFFF
There is no defined maximum size for HTTP POST requests. If you notice such a limit then it's an arbitrary limitation of your HTTP Server/Client.
You might get a better answer if you tell how big the XML is.
You have two pythons installed on your machine, one is the standard python that comes with Mac OSX and the second is the one you installed with ports (this is the one that has matplotlib
installed in its library, the one that comes with macosx does not).
/usr/bin/python
Is the standard mac python and since it doesn't have matplotlib
you should always start your script with the one installed with ports.
If python your_script.py
works then change the #!
to:
#!/usr/bin/env python
Or put the full path to the python interpreter that has the matplotlib
installed in its library.
If you have ids in both tables, the following works:
update table2
set value = (select value from table1 where table1.id = table2.id)
Perhaps a better approach is a join:
update table2
set value = table1.value
from table1
where table1.id = table2.id
Note that this syntax works in SQL Server but may be different in other databases.
you will need to use window.open(url);
references:
http://www.htmlcodetutorial.com/linking/linking_famsupp_120.html
http://www.w3schools.com/jsref/met_win_open.asp
This can be done easily in 3 steps using SourceTree.
This can all be done in a matter of seconds in SourceTree, where you can just click on the files (or even individual lines) you want to add. Once added, just commit them to a temporary commit. Next, click the checkbox to add all changes, then click stash to stash everything. With the stashed changes out of the way, glance over at your commit list and note the hash for the commit before your temporary commit, then run 'git reset hash_b4_temp_commit', which is basically like "popping" the commit by resetting your branch to the commit right before it. Now, you're left with just the stuff you didn't want stashed.
A .NET Core version for replacing a defined set of string chars to a specific char. It leverages the recently introduced Span
type and string.Create
method.
The idea is to prepare a replacement array, so no actual comparison operations would be required for the each string char. Thus, the replacement process reminds the way a state machine works. In order to avoid initialization of all items of the replacement array, let's store oldChar ^ newChar
(XOR'ed) values there, what gives the following benefits:
ch ^ ch = 0
- no need to initialize non-changing itemsch ^ repl[ch]
:
ch ^ 0 = ch
- not changed chars casech ^ (ch ^ newChar) = newChar
- replaced charSo the only requirement would be to ensure that the replacement array is zero-ed when initialized. We'll be using ArrayPool<char>
to avoid allocations each time the ReplaceAll
method is called. And, in order to ensure that the arrays are zero-ed without expensive call to Array.Clear
method, we'll be maintaining a pool dedicated for the ReplaceAll
method. We'll be clearing the replacement array (exact items only) before returning it to the pool.
public static class StringExtensions
{
private static readonly ArrayPool<char> _replacementPool = ArrayPool<char>.Create();
public static string ReplaceAll(this string str, char newChar, params char[] oldChars)
{
// If nothing to do, return the original string.
if (string.IsNullOrEmpty(str) ||
oldChars is null ||
oldChars.Length == 0)
{
return str;
}
// If only one character needs to be replaced,
// use the more efficient `string.Replace`.
if (oldChars.Length == 1)
{
return str.Replace(oldChars[0], newChar);
}
// Get a replacement array from the pool.
var replacements = _replacementPool.Rent(char.MaxValue + 1);
try
{
// Intialize the replacement array in the way that
// all elements represent `oldChar ^ newChar`.
foreach (var oldCh in oldChars)
{
replacements[oldCh] = (char)(newChar ^ oldCh);
}
// Create a string with replaced characters.
return string.Create(str.Length, (str, replacements), (dst, args) =>
{
var repl = args.replacements;
foreach (var ch in args.str)
{
dst[0] = (char)(repl[ch] ^ ch);
dst = dst.Slice(1);
}
});
}
finally
{
// Clear the replacement array.
foreach (var oldCh in oldChars)
{
replacements[oldCh] = char.MinValue;
}
// Return the replacement array back to the pool.
_replacementPool.Return(replacements);
}
}
}
Well, the above does work, here is my solution that requires a little less markup and is more flexible.
.cells {_x000D_
display: inline-block;_x000D_
float: left;_x000D_
padding: 1px;_x000D_
}_x000D_
.cells>.content {_x000D_
background: #EEE;_x000D_
display: table-cell;_x000D_
float: left;_x000D_
padding: 3px;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<div id="div1" class="cells"><div class="content">My Cell 1</div></div>_x000D_
<div id="div2" class="cells"><div class="content">My Cell 2</div></div>
_x000D_
zlib
handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.
You can try libzip. It is free, portable and easy to use.
UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:
#include <zip.h>
int main()
{
//Open the ZIP archive
int err = 0;
zip *z = zip_open("foo.zip", 0, &err);
//Search for the file of given name
const char *name = "file.txt";
struct zip_stat st;
zip_stat_init(&st);
zip_stat(z, name, 0, &st);
//Alloc memory for its uncompressed contents
char *contents = new char[st.size];
//Read the compressed file
zip_file *f = zip_fopen(z, name, 0);
zip_fread(f, contents, st.size);
zip_fclose(f);
//And close the archive
zip_close(z);
//Do something with the contents
//delete allocated memory
delete[] contents;
}
Vertical align only works in some select cases. The easiest way to make it function is to set display: table
in the parent element's CSS and display: table-cell;
to the child element and then apply your vertical align attribute.
The reason I used a +
instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.
word[Aa]\s+word[Bb]\s+word[Cc]
will match:
wordA wordB wordC
worda wordb wordc
wordA wordb wordC
The words, in this expression, will have to be specific, and also in order (a, b, then c)
Use the ES6 destructuring assignment: It will unpack values from arrays, or properties from objects, into distinct variables.
let [variable1 , variable2, variable3] =
["Hello, World!", "Testing...", 42];
console.log(variable1); // Hello, World!
console.log(variable2); // Testing...
console.log(variable3); // 42
_x000D_
Here you get all available services and their status in your local machine.
ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
Console.WriteLine(service.ServiceName+"=="+ service.Status);
}
You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx
EX:
<input type="textbox" ondrop="return false;" onpaste="return false;">
Use these attributes in the required textbox in HTML. Now the drag-and-drop and the paste functionality are disabled.
The alpha channel defines the transparency value of a color, so any color is 100% transparent as long as the alpha value is 0. Typically this four-channel color type is known as RGBA.
You can specify RGBA in CSS like so:
div {
background: rgba(200, 54, 54, 0.5); /* 50% transparent */
}
Note that not all browsers support RGBA, in which case you can specify a fallback:
div {
background: rgb(200, 54, 54); /* fallback */
background: rgba(200, 54, 54, 0.5); /* 50% transparent */
}
More information regarding browser support and workarounds can be found here.
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind
functions to each result callback; the order of parameters is: (success, failure)
. So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: @get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401
// Some more complex constant variable/pointer declaration.
// Observing cases when we get error and warning would help
// understanding it better.
int main(void)
{
char ca1[10]= "aaaa"; // char array 1
char ca2[10]= "bbbb"; // char array 2
char *pca1= ca1;
char *pca2= ca2;
char const *ccs= pca1;
char * const csc= pca2;
ccs[1]='m'; // Bad - error: assignment of read-only location ‘*(ccs + 1u)’
ccs= csc; // Good
csc[1]='n'; // Good
csc= ccs; // Bad - error: assignment of read-only variable ‘csc’
char const **ccss= &ccs; // Good
char const **ccss1= &csc; // Bad - warning: initialization from incompatible pointer type
char * const *cscs= &csc; // Good
char * const *cscs1= &ccs; // Bad - warning: initialization from incompatible pointer type
char ** const cssc= &pca1; // Good
char ** const cssc1= &ccs; // Bad - warning: initialization from incompatible pointer type
char ** const cssc2= &csc; // Bad - warning: initialization discards ‘const’
// qualifier from pointer target type
*ccss[1]= 'x'; // Bad - error: assignment of read-only location ‘**(ccss + 8u)’
*ccss= ccs; // Good
*ccss= csc; // Good
ccss= ccss1; // Good
ccss= cscs; // Bad - warning: assignment from incompatible pointer type
*cscs[1]= 'y'; // Good
*cscs= ccs; // Bad - error: assignment of read-only location ‘*cscs’
*cscs= csc; // Bad - error: assignment of read-only location ‘*cscs’
cscs= cscs1; // Good
cscs= cssc; // Good
*cssc[1]= 'z'; // Good
*cssc= ccs; // Bad - warning: assignment discards ‘const’
// qualifier from pointer target type
*cssc= csc; // Good
*cssc= pca2; // Good
cssc= ccss; // Bad - error: assignment of read-only variable ‘cssc’
cssc= cscs; // Bad - error: assignment of read-only variable ‘cssc’
cssc= cssc1; // Bad - error: assignment of read-only variable ‘cssc’
}
If you look at the examples on the api page there is this: Example: Creates a different alias instead of jQuery to use in the rest of the script.
var j = jQuery.noConflict();
// Do something with jQuery
j("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';
Put the var j = jQuery.noConflict()
after you bring in jquery and then bring in the conflicting scripts. You can then use the j
in place of $
for all your jquery needs and use the $
for the other script.
I have the same problem today, stuck on the kb2999226 for over an hour. First, i thought it is because i am using a VM on my local machine. But decided to cancel the installation, then install kb2999226 first, then install the vs2015 community again, it works out much better, the installation move forward and progressing. thx.
I had already committed the changes and added all the files, had the same origin as remote, still kept getting that error. My simple solution to this was just:
git push
You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.
I used CountIf below, but there is lots of different ways to check existence of a value in a range.
Public Sub test()
Dim rng As Range
Dim aNumber As Long
aNumber = 666
Set rng = Sheet5.Range("B16:B615")
If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
Else
MsgBox aNumber & " does not exist in range " & rng.Address
End If
End Sub
ALTERNATIVE WAY
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Long
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
If Not IsError(Application.Match(aNumber, rng, 0)) Then
rowNum = Application.Match(aNumber, rng, 0)
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
OR
Public Sub test()
Dim rng As Range
Dim aNumber As Variant
Dim rowNum As Variant
aNumber = "2gg"
Set rng = Sheet5.Range("B1:B20")
rowNum = Application.Match(aNumber, rng, 0)
If Not IsError(rowNum) Then
MsgBox rowNum
Else
MsgBox "error"
End If
End Sub
Perhaps you'll have to check the nodetype too:
if(element.nodeType == 1){//element of type html-object/tag
if(element.tagName=="a"){
//this is an a-element
}
if(element.tagName=="div"){
//this is a div-element
}
}
Edit: Corrected the nodeType-value
First off, BigDecimal.multiply()
returns a BigDecimal
and you're trying to store that in an int
.
Second, it takes another BigDecimal
as the argument, not an int
.
If you just use the BigDecimal
for all variables involved in these calculations, it should work fine.
[ES6] This code works for me.
let result = array.map(item => item.id === updatedItem.id ? updatedItem : item)
Add this to your .htaccess code
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R,L]
Replace www.yourdomain.com with your domain name. This will force all the urls of your domain to use https. Make sure you have https certificate installed and configured on your domain. If you do not see https in green as secure, press f12 on chrome and fix all the mixed errors in the console tab.
Hope this helps!
You might want to take a look at (and maybe expand) my little tool kqwait
. Currently it just sits around and waits for a write event on a single file, but the kqueue architecture allows for hierarchical event stacking...
If you ejected and are curious, this change on the CRA repo is what is causing the error.
To fix it, you need to apply their changes; namely, the last set of files:
Personally, I think you should manually apply the changes because, unless you have been keeping up-to-date with all the changes, you could introduce another bug to your webpack bundle (because of a dependency mismatch or something).
OR, you could do what Geo Angelopoulos suggested. It might take a while but at least your project would be in sync with the CRA repo (and get all their latest enhancements!).
If you are on a OS X, this probably has nothing to do with the sed command. On the OSX version of sed
, the -i
option expects an extension
argument so your command is actually parsed as the extension
argument and the file path is interpreted as the command code.
Try adding the -e
argument explicitly and giving ''
as argument to -i
:
find ./ -type f -exec sed -i '' -e "s/192.168.20.1/new.domain.com/" {} \;
See this.
I like some of the answers here, but there is a sed command that should do the trick on any platform:
sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'
Anyway, it's easy to understand. And knowing about the y command can come in handy sometimes.
Using extract-css-chunks-webpack-plugin and css-loader loader work for me, see below:
webpack.config.js Import extract-css-chunks-webpack-plugin
const ExtractCssChunks = require('extract-css-chunks-webpack-plugin');
webpack.config.js Add the css rule, Extract css Chunks first then the css loader css-loader will embed them into the html document, ensure css-loader and extract-css-chunks-webpack-plugin are in the package.json dev dependencies
rules: [
{
test: /\.css$/,
use: [
{
loader: ExtractCssChunks.loader,
},
'css-loader',
],
}
]
webpack.config.js Make instance of the plugin
plugins: [
new ExtractCssChunks({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css'
})
]
And now importing css is possible And now in a tsx file like index.tsx i can use import like this import './Tree.css' where Tree.css contains css rules like
body {
background: red;
}
My app is using typescript and this works for me, check my repo for the source : https://github.com/nickjohngray/staticbackeditor
Then there is always Rosetta Code, which shows crc32 implemented in dozens of computer languages. https://rosettacode.org/wiki/CRC-32 and has links to many explanations and implementations.
The best way to resolve this one is. Download the latest container-selinux package from http://mirror.centos.org/centos/7/extras/x86_64/Packages/ into the VM or the Machine where docker needs to be installed. Error : sometime it will ask for red hat subscription to download from repo. we can do it manually with out subscription as below Run the below command this will install dependencies manually rpm -i container-selinux-2.107-3.el7.noarch.rpm then run the yum install docker-ce
thanks Saa
Another solution is to use a shortcut file to cmd.exe instead of a batch file.
Edit the shortcut's start in property to %~dp0.
You achieve the same thing, except it has the Cmd icon (and you can change this).
Some people don't like clicking on batch files without knowing what's in them, and some corporate network drives have a ban on .bat files...
This worked for me Option + left-arrow
or Option + right-arrow
for moving the cursor to the start or end of the line.
Mac Os Version: Catalina
http://docs.notepad-plus-plus.org/index.php/Inserting_Variable_Text
Notepad++ comes equipped with a Edit -> Column "Alt+C" Editor which can work on a rectangular selection in two different ways: Coledit.png inserting some fixed text on every line including and following the current line, at the column of the insertion point (aka caret). Initially selected text is left untouched. As the picture illustrates, a linear series of numbers can be inserted in the same manner. The starting value and increment are to be provided. Left padding with zeroes is an option, and the number may be entered in base 2, 8, 10 or 16 - this is how the computed values will be displayed too, padding being based on the largest.
puts 'abcdefg'.start_with?('abc') #=> true
[edit] This is something I didn't know before this question: start_with
takes multiple arguments.
'abcdefg'.start_with?( 'xyz', 'opq', 'ab')
I tried the above answer - using page.html#ID_name
it gave me a 404 page doesn't exist error.
Then instead of using .html
, I simply put a slash /
before the #
and that worked fine. So my example on the sending page between the link tags looks like:
<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>
Just use /
instead of .html
.
First you add the Navigation back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Then, add the Method in your HostActivity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home)
{
super.onBackPressed();
Toast.makeText(this, "OnBAckPressed Works", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
Try this, definitely work.
This is because you have specified the form method as GET
Change code in the view to this:
using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){
}
In order to access elements from another class you can simply use
findViewById(R.id.**nameOfYourelementID**).setVisibility(View.GONE);
You can use PrivateObject Class
Class target = new Class();
PrivateObject obj = new PrivateObject(target);
var retVal = obj.Invoke("PrivateMethod");
Assert.AreEqual(expectedVal, retVal);
Note: PrivateObject and PrivateType are not available for projects targeting netcoreapp2.0 - GitHub Issue 366
Try:
$data = file_get_contents ("file.json");
$json = json_decode($data, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br/>';
}
}
}
If using company LAN, disconnect try with other internet network.
ClickOnce applications are stored under the user's profile at %LocalAppData%\Apps\2.0\
.
From there, use the search function to find your application.
This is the easiest way I found:
BtnUpload.Style.Add("display", "none");
FileUploader.Style.Add("display", "none");
BtnAccept.Style.Add("display", "inherit");
BtnClear.Style.Add("display", "inherit");
I have the opposite in the Else, so it handles displaying them as well. This can go in the Page's Load or in a method to refresh the controls on the page.
This is what happens when you store your dates and times in a non-standard format. Working with them become problematic.
$datetime = DateTime::createFromFormat('YmdHi', '201308131830');
echo $datetime->format('D');
I've tried this and it works:
yourelement.next().val();
yourelement could be:
$('#elementIdName').next().val();
good luck!
If you are searching for the index of the last occurrence of myvalue
in mylist
:
len(mylist) - mylist[::-1].index(myvalue) - 1
Use intersection
or intersection_update
intersection :
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
ans = sorted(set(a).intersection(set(xyz)))
intersection_update:
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
b = set(a)
b.intersection_update(xyz)
then b
is your answer
Put the table in a div and give that div the class pre-scrollable
.
Try to use protocol relative links.
Your link is http://example.com/script.js, use:
<script src="//example.com/script.js" type="text/javascript"></script>
In this way, you can leave the scheme free (do not indicate the protocol in the links) and trust that the browser uses the protocol of the embedded Web page. If your users visit the HTTP version of your Web page, the script will be loaded over http:// and if your users visit the HTTPS version of your Web site, the script will be loaded over https://.
Seen in: https://developer.mozilla.org/es/docs/Seguridad/MixedContent/arreglar_web_con_contenido_mixto
You can do a distinct count as follows:
SELECT COUNT(DISTINCT column_name) FROM table_name;
EDIT:
Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:
Now you're probably going to want to use a subquery:
select COUNT(*) column_name FROM (SELECT DISTINCT column_name);
Let me know if this isn't quite what you're looking for.
I think it bears repeating: html_safe
does not HTML-escape your string. In fact, it will prevent your string from being escaped.
<%= "<script>alert('Hello!')</script>" %>
will put:
<script>alert('Hello!')</script>
into your HTML source (yay, so safe!), while:
<%= "<script>alert('Hello!')</script>".html_safe %>
will pop up the alert dialog (are you sure that's what you want?). So you probably don't want to call html_safe
on any user-entered strings.
StringUtils is an Apache Commons project. You need to download and add the library to your classpath.
To use:
import org.apache.commons.lang3.StringUtils;
There may be multiple ways to count the tables of a database. My favorite is this on:
SELECT
COUNT(*)
FROM
`information_schema`.`tables`
WHERE
`table_schema` = 'my_database_name'
;
The trick to make infinity's answer work without the flickering is to put the scroll-check on another div then the one you want to have fixed.
Derived from the code viixii.com uses I ended up using this:
function sticky_relocate() {
var window_top = $(window).scrollTop();
var div_top = $('#sticky-anchor').offset().top;
if (window_top > div_top)
$('#sticky-element').addClass('sticky');
else
$('#sticky-element').removeClass('sticky');
}
$(function() {
$(window).scroll(sticky_relocate);
sticky_relocate();
});
This way the function is only called once the sticky-anchor is reached and thus won't be removing and adding the '.sticky' class on every scroll event.
Now it adds the sticky class when the sticky-anchor reaches the top and removes it once the sticky-anchor return into view.
Just place an empty div with a class acting like an anchor just above the element you want to have fixed.
Like so:
<div id="sticky-anchor"></div>
<div id="sticky-element">Your sticky content</div>
All credit for the code goes to viixii.com
You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams>
and you are passing var model = tm.Name.ToList();
name list. You have to pass list of Teams.
You have to pass following model
var model = new List<Teams>();
model.Add(new Teams { Name = new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name = new List<string>(){"John","XYZ"} });
return View(model);
If nothing of the above helps, make sure you have a proper "Execution environment" selected, and not an "Alternate JRE".
To be found under:
Project -> Build Path -> Libraries
Select the JRE System Library
and click Edit...
.
If "Alternate JRE ..." is selected, change it to a fitting "Execution Environment" like JavaSE-1.8 (jre1.8.0_60)
. No idea why, but this will solve it.
setup.py can be used in two scenarios , First, you want to install a Python package. Second, you want to create your own Python package. Usually standard Python package has couple of important files like setup.py, setup.cfg and Manifest.in. When you are creating the Python package, these three files will determine the (content in PKG-INFO under egg-info folder) name, version, description, other required installations (usually in .txt file) and few other parameters. setup.cfg is read by setup.py while package is created (could be tar.gz ). Manifest.in is where you can define what should be included in your package. Anyways you can do bunch of stuff using setup.py like
python setup.py build
python setup.py install
python setup.py sdist <distname> upload [-r urltorepo] (to upload package to pypi or local repo)
There are bunch of other commands which could be used with setup.py . for help
python setup.py --help-commands
String coolString = "cool string";
byte[] byteArray = coolString.getBytes();
String reconstitutedString = new String(byteArray);
System.out.println(reconstitutedString);
That outputs "cool string" to the console.
It's pretty darn easy.
I also have the same problem, and the solution is I didn't bind the event in my onClick. so when it renders for the first time and the data is more, which ends up calling the state setter again, which triggers React to call your function again and so on.
export default function Component(props) {
function clickEvent (event, variable){
console.log(variable);
}
return (
<div>
<IconButton
key="close"
aria-label="Close"
color="inherit"
onClick={e => clickEvent(e, 10)} // or you can call like this:onClick={() => clickEvent(10)}
>
</div>
)
}
It sounds to me as if you actually mean "linux guests" and not "linux hosts".
But in any case, I suspect you did not install the VMWare Tools: doubleclick on that icon on the Desktop that can be seen on your screenshot. It will install some drivers that communicate with VMWare that, among other things, allow to adjust the screen resolution dynamically.
When the installation process is finished, you'll most likely have to reboot the VM.
Your code should look like:
<?php
if ( that_happened ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
if ( something_else_happened ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
// Your function should return FALSE if something goes wrong
if ( !update_database() ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
// the script can also fail on the above line
// e.g. a mysql error occurred
header('HTTP/1.1 200 OK');
?>
I assume you stop execution if something goes wrong.
Select the datecolumn of month so that u can get only one row per link, e.g.:
select link, min(datecolumn) from posted WHERE ad='$key' ORDER BY day, month
Good luck............
Or
u if you have date column as timestamp convert the format to date and perform distinct on link so that you can get distinct link values based on date instead datetime
C99 has log2
(as well as log2f
and log2l
for float and long double).
All the tools you would need are already available to you on most modern distributions of Linux.
As several have pointed out you can pipe the serial data through netcat. However you would need to relaunch a new instance each time there is a connection. In order to have this persist between connections you can create a xinetd service using the following configuration:
service testservice
{
port = 5900
socket_type = stream
protocol = tcp
wait = yes
user = root
server = /usr/bin/netcat
server_args = "-l 5900 < /dev/ttyS0"
}
Be sure to change the /dev/ttyS0
to match the serial device you are attempting to interface with.
I like to stick with the standard meaning of the words used: An article
would apply to, well, articles. I would define blog posts, documents, and news articles as articles
. Sections on the other hand, would refer to layout/ux items: sidebar, header, footer would be sections. However this is all my own personal interpretation -- as you pointed out, the specification for these elements are not well defined.
Supporting this, the w3c defines an article
element as a section of content that can independently stand on its own. A blog post could stand on it's own as a valuable and consumable item of content. However, a header would not.
Here is an interesting article about one mans madness in trying to differenciate between the two new elements. The basic point of the article, that I also feel is correct, is to try and use what ever element you feel best actually represents what it contains.
What’s more problematic is that article and section are so very similar. All that separates them is the word “self-contained”. Deciding which element to use would be easy if there were some hard and fast rules. Instead, it’s a matter of interpretation. You can have multiple articles within a section, you can have multiple sections within and article, you can nest sections within sections and articles within sections. It’s up to you to decide which element is the most semantically appropriate in any given situation.
Here is a very good answer to the same question here on SO
Why don't you try to grep the return of your command ? Something like :
adb devices -l | grep 123abc12
It should return only the line you want to.
overflow-x: scroll;
overflow-y: hidden;
EDIT:
It works for me:
<div style='overflow-x:scroll;overflow-y:hidden;width:250px;height:200px'>
<div style='width:400px;height:250px'></div>
</div>
This should work
Integer i= Integer.parseInt(text.substring(text.length() - 7));
An email address must not exceed 254 characters.
This was accepted by the IETF following submitted erratum. A full diagnosis of any given address is available online. The original version of RFC 3696 described 320 as the maximum length, but John Klensin subsequently accepted an incorrect value, since a Path is defined as
Path = "<" [ A-d-l ":" ] Mailbox ">"
So the Mailbox element (i.e., the email address) has angle brackets around it to form a Path, which a maximum length of 254 characters to restrict the Path length to 256 characters or fewer.
The maximum length specified in RFC 5321 states:
The maximum total length of a reverse-path or forward-path is 256 characters.
RFC 3696 was corrected here.
People should be aware of the errata against RFC 3696 in particular. Three of the canonical examples are in fact invalid addresses.
I've collated a couple hundred test addresses, which you can find at http://www.dominicsayers.com/isemail
In my case I resolved this issue by
login
and password
)My environment was Jenkins installed in the Windows. The UI question was why the warning was placed before the tool to resolve it.
I see two possible situations here. First, you want to know if there is a SQL standard for this, that you can use in general regardless of the database. No, there is not. Second, you want to know with regard to a specific dbms product. Then you need to identify it. But I imagine the most likely answer is that you'll get back something like "a.id, b.id" since that's how you'd need to identify the columns in your SQL expression. And the easiest way to find out what the default is, is just to submit such a query and see what you get back. If you want to specify what prefix comes before the dot, you can use "SELECT * FROM a AS my_alias", for instance.
Recently I had similar problem, I solved it by importing a HTML file, the baseline example would be like this:
<html xmlns:v="urn:schemas-microsoft-com:vml"
xmlns:o="urn:schemas-microsoft-com:office:office"
xmlns:x="urn:schemas-microsoft-com:office:excel"
xmlns="http://www.w3.org/TR/REC-html40">
<head>
<style>
<!--
br {mso-data-placement:same-cell;}
-->
</style>
</head>
<body>
<table>
<tr>
<td>first line<br/>second line</td>
<td style="white-space:normal">first line<br/>second line</td>
</tr>
</table>
</body>
</html>
I know, it is not a CSV, and might work differently for various versions of Excel, but I think it is worth a try.
I hope this helps ;-)
Based on an answer by Clay Bridges, here is an example of filtering using blocks (change yourArray
to your array variable name and testFunc
to the name of your testing function):
yourArray = [yourArray objectsAtIndexes:[yourArray indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return [self testFunc:obj];
}]];
Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.
I tried with an alternate method:
Hit F12 key Then, at right hand side in the drop down menu, select internet explorer version 9.
That's it and it worked for me.
You've seen this example on Google Code's issue page and (only recently) on Stack Overflow's edit page.
CMS's answer doesn't revert the positioning when you scroll back up. Here's the shamelessly stolen code from Stack Overflow:
function moveScroller() {
var $anchor = $("#scroller-anchor");
var $scroller = $('#scroller');
var move = function() {
var st = $(window).scrollTop();
var ot = $anchor.offset().top;
if(st > ot) {
$scroller.css({
position: "fixed",
top: "0px"
});
} else {
$scroller.css({
position: "relative",
top: ""
});
}
};
$(window).scroll(move);
move();
}
<div id="sidebar" style="width:270px;">
<div id="scroller-anchor"></div>
<div id="scroller" style="margin-top:10px; width:270px">
Scroller Scroller Scroller
</div>
</div>
<script type="text/javascript">
$(function() {
moveScroller();
});
</script>
And a simple live demo.
A nascent, script-free alternative is position: sticky
, which is supported in Chrome, Firefox, and Safari. See the article on HTML5Rocks and demo, and Mozilla docs.
I've recently done a similar formatting like 1 (XXX) XXX-XXXX for Android EditText. Please find the code below. Just use the TextWatcher sub-class as the text changed listener : ....
UsPhoneNumberFormatter addLineNumberFormatter = new UsPhoneNumberFormatter(
new WeakReference<EditText>(mYourEditText));
mYourEditText.addTextChangedListener(addLineNumberFormatter);
...
private class UsPhoneNumberFormatter implements TextWatcher {
//This TextWatcher sub-class formats entered numbers as 1 (123) 456-7890
private boolean mFormatting; // this is a flag which prevents the
// stack(onTextChanged)
private boolean clearFlag;
private int mLastStartLocation;
private String mLastBeforeText;
private WeakReference<EditText> mWeakEditText;
public UsPhoneNumberFormatter(WeakReference<EditText> weakEditText) {
this.mWeakEditText = weakEditText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
if (after == 0 && s.toString().equals("1 ")) {
clearFlag = true;
}
mLastStartLocation = start;
mLastBeforeText = s.toString();
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO: Do nothing
}
@Override
public void afterTextChanged(Editable s) {
// Make sure to ignore calls to afterTextChanged caused by the work
// done below
if (!mFormatting) {
mFormatting = true;
int curPos = mLastStartLocation;
String beforeValue = mLastBeforeText;
String currentValue = s.toString();
String formattedValue = formatUsNumber(s);
if (currentValue.length() > beforeValue.length()) {
int setCusorPos = formattedValue.length()
- (beforeValue.length() - curPos);
mWeakEditText.get().setSelection(setCusorPos < 0 ? 0 : setCusorPos);
} else {
int setCusorPos = formattedValue.length()
- (currentValue.length() - curPos);
if(setCusorPos > 0 && !Character.isDigit(formattedValue.charAt(setCusorPos -1))){
setCusorPos--;
}
mWeakEditText.get().setSelection(setCusorPos < 0 ? 0 : setCusorPos);
}
mFormatting = false;
}
}
private String formatUsNumber(Editable text) {
StringBuilder formattedString = new StringBuilder();
// Remove everything except digits
int p = 0;
while (p < text.length()) {
char ch = text.charAt(p);
if (!Character.isDigit(ch)) {
text.delete(p, p + 1);
} else {
p++;
}
}
// Now only digits are remaining
String allDigitString = text.toString();
int totalDigitCount = allDigitString.length();
if (totalDigitCount == 0
|| (totalDigitCount > 10 && !allDigitString.startsWith("1"))
|| totalDigitCount > 11) {
// May be the total length of input length is greater than the
// expected value so we'll remove all formatting
text.clear();
text.append(allDigitString);
return allDigitString;
}
int alreadyPlacedDigitCount = 0;
// Only '1' is remaining and user pressed backspace and so we clear
// the edit text.
if (allDigitString.equals("1") && clearFlag) {
text.clear();
clearFlag = false;
return "";
}
if (allDigitString.startsWith("1")) {
formattedString.append("1 ");
alreadyPlacedDigitCount++;
}
// The first 3 numbers beyond '1' must be enclosed in brackets "()"
if (totalDigitCount - alreadyPlacedDigitCount > 3) {
formattedString.append("("
+ allDigitString.substring(alreadyPlacedDigitCount,
alreadyPlacedDigitCount + 3) + ") ");
alreadyPlacedDigitCount += 3;
}
// There must be a '-' inserted after the next 3 numbers
if (totalDigitCount - alreadyPlacedDigitCount > 3) {
formattedString.append(allDigitString.substring(
alreadyPlacedDigitCount, alreadyPlacedDigitCount + 3)
+ "-");
alreadyPlacedDigitCount += 3;
}
// All the required formatting is done so we'll just copy the
// remaining digits.
if (totalDigitCount > alreadyPlacedDigitCount) {
formattedString.append(allDigitString
.substring(alreadyPlacedDigitCount));
}
text.clear();
text.append(formattedString.toString());
return formattedString.toString();
}
}
In Node.js,
res.writeHead(200, {'Content-Type': 'text/plain', 'Link': 'rel="shortcut icon" href="#"'} );
Below is a batch file that will run corflags.exe
against all dlls
and exes
in the current working directory and all sub-directories, parse the results and display the target architecture of each.
Depending on the version of corflags.exe
that is used, the line items in the output will either include 32BIT
, or 32BITREQ
(and 32BITPREF
). Whichever of these two is included in the output is the critical line item that must be checked to differentiate between Any CPU
and x86
. If you are using an older version of corflags.exe
(pre Windows SDK v8.0A), then only the 32BIT
line item will be present in the output, as others have indicated in past answers. Otherwise 32BITREQ
and 32BITPREF
replace it.
This assumes corflags.exe
is in the %PATH%
. The simplest way to ensure this is to use a Developer Command Prompt
. Alternatively you could copy it from it's default location.
If the batch file below is run against an unmanaged dll
or exe
, it will incorrectly display it as x86
, since the actual output from Corflags.exe
will be an error message similar to:
corflags : error CF008 : The specified file does not have a valid managed header
@echo off
echo.
echo Target architecture for all exes and dlls:
echo.
REM For each exe and dll in this directory and all subdirectories...
for %%a in (.exe, .dll) do forfiles /s /m *%%a /c "cmd /c echo @relpath" > testfiles.txt
for /f %%b in (testfiles.txt) do (
REM Dump corflags results to a text file
corflags /nologo %%b > corflagsdeets.txt
REM Parse the corflags results to look for key markers
findstr /C:"PE32+">nul .\corflagsdeets.txt && (
REM `PE32+` indicates x64
echo %%~b = x64
) || (
REM pre-v8 Windows SDK listed only "32BIT" line item,
REM newer versions list "32BITREQ" and "32BITPREF" line items
findstr /C:"32BITREQ : 0">nul /C:"32BIT : 0" .\corflagsdeets.txt && (
REM `PE32` and NOT 32bit required indicates Any CPU
echo %%~b = Any CPU
) || (
REM `PE32` and 32bit required indicates x86
echo %%~b = x86
)
)
del corflagsdeets.txt
)
del testfiles.txt
echo.
Just do Ctrl + Enter inside the text box
Quoting spaces inside variables such that the shell will re-interpret things properly is hard. It's this type of thing that prompts me to reach for a stronger language. Whether that's perl or python or ruby or whatever (I choose perl, but that's not always for everyone), it's just something that will allow you to bypass the shell for quoting.
It's not that I've never managed to get it right with liberal doses of eval, but just that eval gives me the eebie-jeebies (becomes a whole new headache when you want to take user input and eval it, though in this case you'd be taking stuff that you wrote and evaling that instead), and that I've gotten headaches in debugging.
With perl, as my example, I'd be able to do something like:
@tar_cmd = ( qw(tar cv), $directory );
@encrypt_cmd = ( qw(openssl des3 -salt) );
@split_cmd = ( qw(split -b 1024m -), $backup_file );
The hard part here is doing the pipes - but a bit of IO::Pipe, fork, and reopening stdout and stderr, and it's not bad. Some would say that's worse than quoting the shell properly, and I understand where they're coming from, but, for me, this is easier to read, maintain, and write. Heck, someone could take the hard work out of this and create a IO::Pipeline module and make the whole thing trivial ;-)
You need to encode the URI to replace illegal characters with legal encoded characters. If you first make a URL (so you don't have to do the parsing yourself) and then make a URI using the five-argument constructor, then the constructor will do the encoding for you.
import java.net.*;
public class Test {
public static void main(String[] args) {
String myURL = "http://finance.yahoo.com/q/h?s=^IXIC";
try {
URL url = new URL(myURL);
String nullFragment = null;
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), nullFragment);
System.out.println("URI " + uri.toString() + " is OK");
} catch (MalformedURLException e) {
System.out.println("URL " + myURL + " is a malformed URL");
} catch (URISyntaxException e) {
System.out.println("URI " + myURL + " is a malformed URL");
}
}
}
accept
can continuously provide new client connections. However, note that it, and other socket calls are usually blocking. Therefore you have a few options at this point:
Kinda surprised nobody's pointed out the direct way to do it, which is easy enough.
double roundToDecimalPlaces(double value, int decimalPlaces)
{
double shift = Math.pow(10,decimalPlaces);
return Math.round(value*shift)/shift;
}
Pretty sure this does not do half-even rounding though.
For what it's worth, half-even rounding is going to be chaotic and unpredictable any time you mix binary-based floating-point values with base-10 arithmetic. I'm pretty sure it cannot be done. The basic problem is that a value like 1.105 cannot be represented exactly in floating point. The floating point value is going to be something like 1.105000000000001, or 1.104999999999999. So any attempt to perform half-even rounding is going trip up on representational encoding errors.
IEEE floating point implementations will do half-rounding, but they do binary half-rounding, not decimal half-rounding. So you're probably ok
#include <QFile>
#include <QCoreApplication>
#include <QTextStream>
int main(int argc, char *argv[])
{
// Create a new file
QFile file("out.txt");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << "This file is generated by Qt\n";
// optional, as QFile destructor will already do it:
file.close();
//this would normally start the event loop, but is not needed for this
//minimal example:
//return app.exec();
return 0;
}
You may want to double check the authorized_keys file permissions:
$ chmod 600 ~/.ssh/authorized_keys
Newer SSH server versions are very picky on this respect.
This way you can create a new object with a custom property name.
$my_property = 'foo';
$value = 'bar';
$a = (object) array($my_property => $value);
Now you can reach it like:
echo $a->foo; //returns bar
You should separate the host from the port number. You could have something, like:
development:
adapter: mysql2
encoding: utf8
database: my_db_name
username: root
password: my_password
host: 127.0.0.1
port: 3306
In my case, I was using wrong linking.
It was managed c++ (cli) but with native exporting. I have added to linker -> input -> assembly link resource the dll of the library from which the function is exported. But native c++ linking requires .lib file to "see" implementations in cpp correctly, so for me helped to add the .lib file to linker -> input -> additional dependencies.
[Usually managed code does not use dll export and import, it uses references, but that was unique situation.]
Assuming a as double and we need a rounded number with no decimal place . Use Math.round() function.
This goes as my solution .
double a = 0.99999;
int rounded_a = (int)Math.round(a);
System.out.println("a:"+rounded_a );
Output :
a:1
var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");
Use the global(g
) flag
Both
SuperClass.__init__(self, x)
or
super(SubClass,self).__init__( x )
will work (I prefer the 2nd one, as it adheres more to the DRY principle).
See here: http://docs.python.org/reference/datamodel.html#basic-customization
One of my colleagues noticed that most of the HttpClient
methods all call SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
under the hood, which is a virtual method off of HttpMessageInvoker
:
So by far the easiest way to mock out HttpClient
was to simply mock that particular method:
var mockClient = new Mock<HttpClient>();
mockClient.Setup(client => client.SendAsync(It.IsAny<HttpRequestMessage>(), It.IsAny<CancellationToken>())).ReturnsAsync(_mockResponse.Object);
and your code can call most (but not all) of the HttpClient
class methods, including a regular
httpClient.SendAsync(req)
Check here to confirm https://github.com/dotnet/corefx/blob/master/src/System.Net.Http/src/System/Net/Http/HttpClient.cs
CSS to detect screen orientation:
@media screen and (orientation:portrait) { … }
@media screen and (orientation:landscape) { … }
The CSS definition of a media query is at http://www.w3.org/TR/css3-mediaqueries/#orientation
Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?
It depends on your input; i.e. the stuff you fetch from the URL. If the value of the "datasets" attribute is an associative array rather than a plain array, you will get a ClassCastException
.
But then again, the correctness of your old version also depends on the input. In the situation where your new version throws a ClassCastException
, the old version will throw JSONException
. Reference: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)
You'll need to use fs
for that: http://nodejs.org/api/fs.html
And in particular the fs.rename()
function:
var fs = require('fs');
fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
if ( err ) console.log('ERROR: ' + err);
});
Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.
fs.readFile('/path/to/countries.json', function(error, data) {
if (error) {
console.log(error);
return;
}
var obj = JSON.parse(data);
for(var p in obj) {
fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
if ( err ) console.log('ERROR: ' + err);
});
}
});
(This assumes here that your .json
file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)
Is it possible to get this above example:
jQuery.fn.highlight = function (str, className)
{
var regex = new RegExp(str, "g");
return this.each(function ()
{
this.innerHTML = this.innerHTML.replace(
regex,
"<span class=\"" + className + "\">" + str + "</span>"
);
});
};
not to replace text inside html-tags like , this otherwise breakes the page.
In the beginning I was also having a bit of trouble figuring out how this works so I wanted to post a better explanation of what is actually going on.
According to my research the best way to handle things like this is using the Command Bindings. What happens is a "Message" is broadcast to everything in the program. So what you have to do is use the CommandBinding
. What this essentially does is say "When you hear this Message do this".
So in the Question the User is trying to Close the Window. The first thing we need to do is setup our Functions that will be called when the SystemCommand.CloseWindowCommand
is broadcast. Optionally you can assign a Function that determines if the Command should be executed. An example would be closing a Form and checking if the User has saved.
void CloseApp( object target, ExecutedRoutedEventArgs e ) {
/*** Code to check for State before Closing ***/
this.Close();
}
void CloseAppCanExecute( object sender, CanExecuteRoutedEventArgs e ) {
/*** Logic to Determine if it is safe to Close the Window ***/
e.CanExecute = true;
}
Now we need to setup the "Connection" between the SystemCommands.CloseWindowCommand
and the CloseApp
and CloseAppCanExecute
<Window.CommandBindings>
<CommandBinding Command="SystemCommands.CloseWindowCommand"
Executed="CloseApp"
CanExecute="CloseAppCanExecute"/>
</Window.CommandBindings>
You can omit the CanExecute if you know that the Command should be able to always be executed Save might be a good example depending on the Application. Here is a Example:
<Window.CommandBindings>
<CommandBinding Command="SystemCommands.CloseWindowCommand"
Executed="CloseApp"/>
</Window.CommandBindings>
Finally you need to tell the UIElement to send out the CloseWindowCommand.
<Button Command="SystemCommands.CloseWindowCommand">
Its actually a very simple thing to do, just setup the link between the Command and the actual Function to Execute then tell the Control to send out the Command to the rest of your program saying "Ok everyone run your Functions for the Command CloseWindowCommand".
This is actually a very nice way of handing this because, you can reuse the Executed Function all over without having a wrapper like you would with say WinForms (using a ClickEvent and calling a function within the Event Function) like:
protected override void OnClick(EventArgs e){
/*** Function to Execute ***/
}
In WPF you attach the Function to a Command and tell the UIElement to execute the Function attached to the Command instead.
I hope this clears things up...
Honestly, for simplistic stuff like that I typically whip up a quick HTML form in a local file and load that up in a browser.
wmic is a very complete tool
wmic diskdrive list
provide a (too much) detailed list, for instance
for less info
wmic diskdrive list brief
Sebastian Godelet mentions in the comments:
In C:
system("wmic diskdrive list");
As commented, you can also call the WinAPI, but... as shown in "How to obtain data from WMI using a C Application?", this is quite complex (and generally done with C++, not C).
Or with PowerShell:
Get-WmiObject Win32_DiskDrive
Probably you want something like:
firstline = True
for row in kidfile:
if firstline: #skip first line
firstline = False
continue
# parse the line
An other way to achive the same result is calling readline
before the loop:
kidfile.readline() # skip the first line
for row in kidfile:
#parse the line
here is an utility which is up to transform json2object or Object2json, whatever your pojo (entity T)
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
*
* @author TIAGO.MEDICI
*
*/
public class JsonUtils {
public static boolean isJSONValid(String jsonInString) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
}
public static String serializeAsJsonString(Object object) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
StringWriter sw = new StringWriter();
objMapper.writeValue(sw, object);
return sw.toString();
}
public static String serializeAsJsonString(Object object, boolean indent) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objMapper = new ObjectMapper();
if (indent == true) {
objMapper.enable(SerializationFeature.INDENT_OUTPUT);
objMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
StringWriter stringWriter = new StringWriter();
objMapper.writeValue(stringWriter, object);
return stringWriter.toString();
}
public static <T> T jsonStringToObject(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper objMapper = new ObjectMapper();
obj = objMapper.readValue(content, clazz);
return obj;
}
@SuppressWarnings("rawtypes")
public static <T> T jsonStringToObjectArray(String content) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
obj = mapper.readValue(content, new TypeReference<List>() {
});
return obj;
}
public static <T> T jsonStringToObjectArray(String content, Class<T> clazz) throws JsonParseException, JsonMappingException, IOException {
T obj = null;
ObjectMapper mapper = new ObjectMapper();
mapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
obj = mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
return obj;
}
For people trying to grab the component instance inside a *ngIf
or *ngSwitchCase
, you can follow this trick.
Create an init
directive.
import {
Directive,
EventEmitter,
Output,
OnInit,
ElementRef
} from '@angular/core';
@Directive({
selector: '[init]'
})
export class InitDirective implements OnInit {
constructor(private ref: ElementRef) {}
@Output() init: EventEmitter<ElementRef> = new EventEmitter<ElementRef>();
ngOnInit() {
this.init.emit(this.ref);
}
}
Export your component with a name such as myComponent
@Component({
selector: 'wm-my-component',
templateUrl: 'my-component.component.html',
styleUrls: ['my-component.component.css'],
exportAs: 'myComponent'
})
export class MyComponent { ... }
Use this template to get the ElementRef
AND MyComponent
instance
<div [ngSwitch]="type">
<wm-my-component
#myComponent="myComponent"
*ngSwitchCase="Type.MyType"
(init)="init($event, myComponent)">
</wm-my-component>
</div>
Use this code in TypeScript
init(myComponentRef: ElementRef, myComponent: MyComponent) {
}
All your firebase version should be with same Version whatever it
like this
compile 'com.google.firebase:firebase-core:9.0.0'
compile 'com.google.firebase:firebase-database:9.0.0'
compile 'com.google.firebase:firebase-auth:9.0.0'
compile 'com.google.firebase:firebase-messaging:9.0.0'
There are a few ways to do this it seems.
Angular provides an $anchorScroll
service, but the documentation is severely lacking and I've not been able to get it to work.
Check out http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html for some insight into $anchorScroll
.
Another way I tested out was creating a custom directive and using el.scrollIntoView()
.
This works pretty decently by basically doing the following in your directive link function:
var el = document.getElementById(attrs.href);
el.scrollIntoView();
However, it seems a bit overblown to do both of these when the browser natively supports this, right?
If you take a look at http://docs.angularjs.org/guide/dev_guide.services.$location and its HTML Link Rewriting section, you'll see that links are not rewritten in the following:
Links that contain target element
Example:
<a href="/ext/link?a=b" target="_self">link</a>
So, all you have to do is add the target
attribute to your links, like so:
<a href="#anchorLinkID" target="_self">Go to inpage section</a>
Angular defaults to the browser and since its an anchor link and not a different base url, the browser scrolls to the correct location, as desired.
I went with option 3 because its best to rely on native browser functionality here, and saves us time and effort.
Gotta note that after a successful scroll and hash change, Angular does follow up and rewrite the hash to its custom style. However, the browser has already completed its business and you are good to go.
In Swift 4.2 and Xcode 10
self.navigationController?.isNavigationBarHidden = true //Hide
self.navigationController?.isNavigationBarHidden = false //Show
If you don't want to display Navigation bar only in 1st VC, but you want display in 2nd VC onword's
In your 1st VC write this code.
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = true //Hide
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = false //Show
}
First, install unzip on colab:
!apt install unzip
then use unzip to extract your files:
!unzip source.zip -d destination.zip
just adding to above answers, when we have a static code (ie code block is instance independent) that needs to be present in memory, we can have the class returned so we'll use Class.forname("someName") else if we dont have static code we can go for Class.forname().newInstance("someName") as it will load object level code blocks(non static) to memory
Simple thing i did to get it working:
Went in eclipse > Window > Preferences
(Optional)typed in the search box "file" to help trim the tree of options. Went to General > Editors > File associations.
Clicked the ".class" type. Below there were 2 editors present, i clicked on the "Class File Editor" - the one with the icon from JD, clicked the "Default" button on the right.
Done. Now all ur class are belong to us.
If you're deploying a local website just for yourself or certain clients, you can get around this by running mklink /D MyImages "C:/MyImages"
in the website root directory as an admin in cmd. Then in the html, do <img src="MyImages/whatever.jpg">
and the symbolic link established by mklink will connect the relative src link with the link on your C drive. It solved this issue for me, so it may help others who come to this question.
(Obviously this won't work for public websites since you can't run cmd commands on people's computers easily)
Use serialize
and deserialize
methods in SerializationUtils
from commons-lang.
The keyword you need is flatten an array. Modern javascript array comes with a flat method. You can use third party libraries like underscorejs in case you need to support older browsers.
Native Ex:
var response=[1,2,3,4[12,15],[20,21]];
var data=response.flat(); //data=[1,2,3,4,12,15,20,21]
Underscore Ex:
var response=[1,2,3,4[12,15],[20,21]];
var data=_.flatten(response);
BufferedWriter is more efficient. It saves up small writes and writes in one larger chunk if memory serves me correctly. If you are doing lots of small writes then I would use BufferedWriter. Calling write calls to the OS which is slow so having as few writes as possible is usually desirable.
If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.
However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.
Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:
[client]
user = <username>
password = <password>
Make sure to change the file permissions so that only you can read the file.
Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.
I have tried above all issue but was not working for me What I tried is
First of all, I want to go with manual code signing process, I am not doing via automatic code signing
You will good to go now
Here's an example that uses proper usings and implementation of idisposable:
static void WriteToFile(string sourceFile, string destinationfile, bool append = true, int bufferSize = 4096)
{
using (var sourceFileStream = new FileStream(sourceFile, FileMode.OpenOrCreate))
{
using (var destinationFileStream = new FileStream(destinationfile, FileMode.OpenOrCreate))
{
while (sourceFileStream.Position < sourceFileStream.Length)
{
destinationFileStream.WriteByte((byte)sourceFileStream.ReadByte());
}
}
}
}
...and there's also this
public static void WriteToFile(Stream stream, string destinationFile, int bufferSize = 4096, FileMode mode = FileMode.OpenOrCreate, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.ReadWrite)
{
using (var destinationFileStream = new FileStream(destinationFile, mode, access, share))
{
while (stream.Position < stream.Length)
{
destinationFileStream.WriteByte((byte)stream.ReadByte());
}
}
}
The key is understanding the proper use of using (which should be implemented on the instantiation of the object that implements idisposable as shown above), and having a good idea as to how the properties work for streams. Position is literally the index within the stream (which starts at 0) that is followed as each byte is read using the readbyte method. In this case I am essentially using it in place of a for loop variable and simply letting it follow through all the way up to the length which is LITERALLY the end of the entire stream (in bytes). Ignore in bytes because it is practically the same and you will have something simple and elegant like this that resolves everything cleanly.
Keep in mind, too, that the ReadByte method simply casts the byte to an int in the process and can simply be converted back.
I'm gonna add another implementation I recently wrote to create a dynamic buffer of sorts to ensure sequential data writes to prevent massive overload
private void StreamBuffer(Stream stream, int buffer)
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
var memoryBuffer = memoryStream.GetBuffer();
for (int i = 0; i < memoryBuffer.Length;)
{
var networkBuffer = new byte[buffer];
for (int j = 0; j < networkBuffer.Length && i < memoryBuffer.Length; j++)
{
networkBuffer[j] = memoryBuffer[i];
i++;
}
//Assuming destination file
destinationFileStream.Write(networkBuffer, 0, networkBuffer.Length);
}
}
}
The explanation is fairly simple: we know that we need to keep in mind the entire set of data we wish to write and also that we only want to write certain amounts, so we want the first loop with the last parameter empty (same as while). Next, we initialize a byte array buffer that is set to the size of what's passed, and with the second loop we compare j to the size of the buffer and the size of the original one, and if it's greater than the size of the original byte array, end the run.
import Image
def fig2img ( fig ): """ @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it @param fig a matplotlib figure @return a Python Imaging Library ( PIL ) image """ # put the figure pixmap into a numpy array buf = fig2data ( fig ) w, h, d = buf.shape return Image.frombytes( "RGBA", ( w ,h ), buf.tostring( ) )
def fig2data ( fig ): """ @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it @param fig a matplotlib figure @return a numpy 3D array of RGBA values """ # draw the renderer fig.canvas.draw ( )
# Get the RGBA buffer from the figure
w,h = fig.canvas.get_width_height()
buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
buf.shape = ( w, h, 4 )
# canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
buf = np.roll ( buf, 3, axis = 2 )
return buf
def rgba2rgb(img, c=(0, 0, 0), path='foo.jpg', is_already_saved=False, if_load=True): if not is_already_saved: background = Image.new("RGB", img.size, c) background.paste(img, mask=img.split()[3]) # 3 is the alpha channel
background.save(path, 'JPEG', quality=100)
is_already_saved = True
if if_load:
if is_already_saved:
im = Image.open(path)
return np.array(im)
else:
raise ValueError('No image to load.')
If you are using pdo, it will look like
$sql = "UPDATE users SET firstname = :firstname, lastname = :lastname WHERE id= :id";
$query = $this->pdo->prepare($sql);
$result = $query->execute(array(':firstname' => $firstname, ':lastname' => $lastname, ':id' => $id));
To simplify to operation, we can use the below command to reinstall version 2:
brew install python@2
Then on my mac, it looks as below:
? python -V
Python 2.7.10
? python2 -V
Python 2.7.14
? python3 -V
Python 3.6.5
? pip2 -V
pip 9.0.3 from /usr/local/lib/python2.7/site-packages (python 2.7)
? pip3 -V
pip 9.0.3 from /usr/local/lib/python3.6/site-packages (python 3.6)
? pip --version
pip 9.0.3 from /usr/local/lib/python2.7/site-packages (python 2.7)
def rescale_by_height(image, target_height, method=cv2.INTER_LANCZOS4):
"""Rescale `image` to `target_height` (preserving aspect ratio)."""
w = int(round(target_height * image.shape[1] / image.shape[0]))
return cv2.resize(image, (w, target_height), interpolation=method)
def rescale_by_width(image, target_width, method=cv2.INTER_LANCZOS4):
"""Rescale `image` to `target_width` (preserving aspect ratio)."""
h = int(round(target_width * image.shape[0] / image.shape[1]))
return cv2.resize(image, (target_width, h), interpolation=method)
I think what you really want is an ArrayList or Vector. Arrays in Java are not like those in Javascript.
Worked this out, turns out that android.R.color.black is not the same as Color.BLACK. Changed the code to:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);
and it all works fine now!!
I would use the minted package as mentioned from the developer Konrad Rudolph instead of the listing package. Here is why:
listing package
The listing package does not support colors by default. To use colors you would need to include the color package and define color-rules by yourself with the \lstset command as explained for matlab code here.
Also, the listing package doesn't work well with unicode, but you can fix those problems as explained here and here.
The following code
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=html]
<html>
<head>
<title>Hello</title>
</head>
<body>Hello</body>
</html>
\end{lstlisting}
\end{document}
produces the following image:
minted package
The minted package supports colors, unicode and looks awesome. However, in order to use it, you need to have python 2.6 and pygments. In Ubuntu, you can check your python version in the terminal with
python --version
and you can install pygments with
sudo apt-get install python-pygments
Then, since minted makes calls to pygments, you need to compile it with -shell-escape like this
pdflatex -shell-escape yourfile.tex
If you use a latex editor like TexMaker or something, I would recommend to add a user-command, so that you can still compile it in the editor.
The following code
\documentclass{article}
\usepackage{minted}
\begin{document}
\begin{minted}{html}
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>Hello</body>
</html>
\end{minted}
\end{document}
produces the following image:
This worked for me..
HTML:
<input type="radio" class="radioClass" name="radioName" value="1" />Test<br/>
<input type="radio" class="radioClass" name="radioName" value="2" />Practice<br/>
<input type="radio" class="radioClass" name="radioName" value="3" />Both<br/>
Jquery:
$(".radioClass").each(function() { if($(this).is(':checked')) alert($(this).val()); });
Hope it helps..
All that the test
attribute looks for to determine if something is true is the string "true" (case in-sensitive). For example, the following code will print "Hello world!"
<c:if test="true">Hello world!</c:if>
The code within the <%= %>
returns a boolean, so it will either print the string "true" or "false", which is exactly what the <c:if>
tag looks for.
Mac Users
Instead of running MongoDB with:
sudo mongod
You can use mongod
instead if you:
sudo chmod -R ugo+rw data
If you need to use sudo
when running mongodb (sudo mongod
), that means you don't have read and write permission on the mongodb data folder
Small addition to all of above:
Better use map
, when you need to get elements by range, as they are sorted and you can just iterate over them from one boundary to another.
You can use flexbox to center your text. By the way no need for extra containers because text is considered as anonymous flex item.
From flexbox specs:
Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item. However, an anonymous flex item that contains only white space (i.e. characters that can be affected by the
white-space
property) is not rendered (just as if it weredisplay:none
).
So just make grid items as flex containers (display: flex
), and add align-items: center
and justify-content: center
to center both vertically and horizontally.
Also performed optimization of HTML and CSS:
html,_x000D_
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-template-rows: 100vh;_x000D_
_x000D_
font-family: Raleway;_x000D_
font-size: large;_x000D_
}_x000D_
_x000D_
.left_bg,_x000D_
.right_bg {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.left_bg {_x000D_
background-color: #3498db;_x000D_
}_x000D_
_x000D_
.right_bg {_x000D_
background-color: #ecf0f1;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left_bg">Review my stuff</div>_x000D_
<div class="right_bg">Hire me!</div>_x000D_
</div>
_x000D_
Very much agreed with @Patrik M, but the thing with Arrays.toString is that it includes "[" and "]" and "," in the output. So I'll simply use a regex to remove them from outout like this
String strOfInts = Arrays.toString(intArray).replaceAll("\\[|\\]|,|\\s", "");
and now you have a String which can be parsed back to java.lang.Number
, for example,
long veryLongNumber = Long.parseLong(intStr);
Or you can use the java 8 streams, if you hate regex,
String strOfInts = Arrays
.stream(intArray)
.mapToObj(String::valueOf)
.reduce((a, b) -> a.concat(",").concat(b))
.get();
You are going wrong here:
int retval = chooser.showOpenDialog(null);
public boolean accept(File directory, String fileName) {`
return fileName.endsWith(".txt");`
}
You first show the file chooser dialog and then apply the filter! This wont work. First apply the filter and then show the dialog:
public boolean accept(File directory, String fileName) {
return fileName.endsWith(".txt");
}
int retval = chooser.showOpenDialog(null);
I'd start with something like this (and if there is something wrong with my code, I'd of course appreciate any comment):
public class ItemsList extends ListActivity {
private ItemsAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_list);
this.adapter = new ItemsAdapter(this, R.layout.items_list_item, ItemManager.getLoadedItems());
setListAdapter(this.adapter);
}
private class ItemsAdapter extends ArrayAdapter<Item> {
private Item[] items;
public ItemsAdapter(Context context, int textViewResourceId, Item[] items) {
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.items_list_item, null);
}
Item it = items[position];
if (it != null) {
ImageView iv = (ImageView) v.findViewById(R.id.list_item_image);
if (iv != null) {
iv.setImageDrawable(it.getImage());
}
}
return v;
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
this.adapter.getItem(position).click(this.getApplicationContext());
}
}
E.g. extending ArrayAdapter with own type of Items (holding information about your pictures) and overriden getView()
method, that prepares view for items within list. There is also method add()
on ArrayAdapter to add items to the end of the list.
R.layout.items_list
is simple layout with ListView
R.layout.items_list_item
is layout representing one item in list
For Microsoft, the answer is different. VS2013 is largely C99 compliant but "[t]he hh, j, z, and t length prefixes are not supported." For size_t "that is, unsigned __int32 on 32-bit platforms, unsigned __int64 on 64-bit platforms" use prefix I (capital eye) with type specifier o, u, x, or X. See VS2013 Size specification
As for off_t, it is defined as long in VC\include\sys\types.h.
If you use performSelectorInBackground:withObject:
to spawn a new thread, then the performed selector is responsible for setting up the new thread's autorelease pool, run loop and other configuration details – see "Using NSObject to Spawn a Thread" in Apple's Threading Programming Guide.
You'd probably be better off using Grand Central Dispatch, though:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self getResultSetFromDB:docids];
});
GCD is a newer technology, and is more efficient in terms of memory overhead and lines of code.
Updated with a hat tip to Chris Nolet, who suggested a change that makes the above code simpler and keeps up with Apple's latest GCD code examples.
You can use a simple API from http://www.geoplugin.net/
$xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=".getRealIpAddr());
echo $xml->geoplugin_countryName ;
echo "<pre>";
foreach ($xml as $key => $value)
{
echo $key , "= " , $value , " \n" ;
}
echo "</pre>";
Function Used
function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
Output
United States
geoplugin_city= San Antonio
geoplugin_region= TX
geoplugin_areaCode= 210
geoplugin_dmaCode= 641
geoplugin_countryCode= US
geoplugin_countryName= United States
geoplugin_continentCode= NA
geoplugin_latitude= 29.488899230957
geoplugin_longitude= -98.398696899414
geoplugin_regionCode= TX
geoplugin_regionName= Texas
geoplugin_currencyCode= USD
geoplugin_currencySymbol= $
geoplugin_currencyConverter= 1
It makes you have so many options you can play around with
Thanks
:)
Unicode currently has 74605 CJK characters. CJK characters not only includes characters used by Chinese, but also Japanese Kanji, Korean Hanja, and Vietnamese Chu Nom. Some CJK characters are not Chinese characters.
Code points U+4E00 to U+9FCC.
Code points U+3400 to U+4DB5. Unicode 3.0 (1999).
Code points U+20000 to U+2A6D6. Unicode 3.1 (2001).
Code points U+2A700 to U+2B734. Unicode 5.2 (2009).
Code points U+2B740 to U+2B81D. Unicode 6.0 (2010).
If the above is not spaghetti enough, take a look at known issues. Have fun =)
I found DragSortListView worked well, although getting started on it could have been easier. Here's a brief tutorial on using it in Android Studio with an in-memory list:
Add this to the build.gradle
dependencies for your app:
compile 'asia.ivity.android:drag-sort-listview:1.0' // Corresponds to release 0.6.1
Create a resource for the drag handle ID by creating or adding to values/ids.xml
:
<resources>
... possibly other resources ...
<item type="id" name="drag_handle" />
</resources>
Create a layout for a list item that includes your favorite drag handle image, and assign its ID to the ID you created in step 2 (e.g. drag_handle
).
Create a DragSortListView layout, something like this:
<com.mobeta.android.dslv.DragSortListView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dslv="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
dslv:drag_handle_id="@id/drag_handle"
dslv:float_background_color="@android:color/background_light"/>
Set an ArrayAdapter
derivative with a getView
override that renders your list item view.
final ArrayAdapter<MyItem> itemAdapter = new ArrayAdapter<MyItem>(this, R.layout.my_item, R.id.my_item_name, items) { // The third parameter works around ugly Android legacy. http://stackoverflow.com/a/18529511/145173
@Override public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
MyItem item = getItem(position);
((TextView) view.findViewById(R.id.my_item_name)).setText(item.getName());
// ... Fill in other views ...
return view;
}
};
dragSortListView.setAdapter(itemAdapter);
Set a drop listener that rearranges the items as they are dropped.
dragSortListView.setDropListener(new DragSortListView.DropListener() {
@Override public void drop(int from, int to) {
MyItem movedItem = items.get(from);
items.remove(from);
if (from > to) --from;
items.add(to, movedItem);
itemAdapter.notifyDataSetChanged();
}
});
Instead of trying to create a div and measure its width, I think it's more reliable to measure the width directly using a canvas element which is more accurate.
function measureTextWidth(txt, font) {
var element = document.createElement('canvas');
var context = element.getContext("2d");
context.font = font;
return context.measureText(txt).width;
}
Now you can use this to measure what the width of some input element should be at any point in time by doing this:
// assuming inputElement is a reference to an input element (DOM, not jQuery)
var style = window.getComputedStyle(inputElement, null);
var text = inputElement.value || inputElement.placeholder;
var width = measureTextWidth(text, style.font);
This returns a number (possibly floating point). If you want to account for padding you can try this:
var desiredWidth = (parseInt(style.borderLeftWidth) +
parseInt(style.paddingLeft) +
Math.ceil(width) +
1 + // extra space for cursor
parseInt(style.paddingRight) +
parseInt(style.borderRightWidth))
inputElement.style.width = desiredWidth + "px";
include the entire namespace
@model namespace.myclasses.mymodel
int i = 65;
char c = Convert.ToChar(i);
if you use ini_set on the fly then you will find here http://php.net/manual/en/ini.core.php the information that e.g. upload_max_filesize and post_max_size is not changeable on the fly (PHP_INI_PERDIR).
Only a php.ini, .htaccess or vhost config change seems to change these variables.
As almost noted in comments to @BoltClock's answer, in modern browsers, you can actually add some html markup to pseudo-elements using the (url()
) in combination with svg's <foreignObject>
element.
You can either specify an URL pointing to an actual svg file, or create it with a dataURI version (data:image/svg+xml; charset=utf8, + encodeURIComponent(yourSvgMarkup)
)
But note that it is mostly a hack and that there are a lot of limitations :
document.styleSheets
. for this part, DOMParser
and XMLSerializer
may help.<img>
tags, this won't work in pseudo-elements (at least as of today, I don't know if it is specified anywhere that it shouldn't, so it may be a not-yet implemented feature).Now, a small demo of some html markup in a pseudo element :
/* _x000D_
** original svg code :_x000D_
*_x000D_
*<svg width="200" height="60"_x000D_
* xmlns="http://www.w3.org/2000/svg">_x000D_
*_x000D_
* <foreignObject width="100%" height="100%" x="0" y="0">_x000D_
* <div xmlns="http://www.w3.org/1999/xhtml" style="color: blue">_x000D_
* I am <pre>HTML</pre>_x000D_
* </div>_x000D_
* </foreignObject>_x000D_
*</svg>_x000D_
*_x000D_
*/
_x000D_
#log::after {_x000D_
content: url('data:image/svg+xml;%20charset=utf8,%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%2260%22%20width%3D%22200%22%3E%0A%0A%20%20%3CforeignObject%20y%3D%220%22%20x%3D%220%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%0A%09%3Cdiv%20style%3D%22color%3A%20blue%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%0A%09%09I%20am%20%3Cpre%3EHTML%3C%2Fpre%3E%0A%09%3C%2Fdiv%3E%0A%20%20%3C%2FforeignObject%3E%0A%3C%2Fsvg%3E');_x000D_
}
_x000D_
<p id="log">hi</p>
_x000D_
Everything in the java.lang
package is implicitly imported (including String) and you do not need to do so yourself. This is simply a feature of the Java language. ArrayList and HashMap are however in the java.util
package, which is not implicitly imported.
The package java.lang mostly includes essential features, such a class version of primitives, basic exceptions and the Object class. This being integral to most programs, forcing people to import them is redundant and thus the contents of this package are implicitly imported.
var isProduction = (process.argv.indexOf("production")>-1);
CLI gulp production
calls my production task and sets a flag for any conditionals.
//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));
The difference between pointers and references is quite simple: a pointer can be null, a reference can not.
Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).
Here it looks like references are more appropriate.
While the w32tm /resync
in theory does the job, it only does so under certain conditions. When "down to the millisecond" matters, however, I found that Windows wouldn't actually make the adjustment; as if "oh, I'm off by 2.5 seconds, close enough bro, nothing to see or do here".
In order to truly force the resync (Windows 7):
w32tm /resync
watch -n 0.1 date
on a Linux machine on the network that I had SSH'd over into)--- Rapid Method ---
net start w32time
(Time Service must be running)time 8
(where 8 may be replaced by any 'hour' value, presumably 0-23)w32tm /resync
I've had this error when there's been different RxJS-versions across projects. The internal checks in RxJS fails because there are several different Symbol_observable
. Eventually this function throws once called from a flattening operator like switchMap
.
Try importing symbol-observable in some entry point.
// main index.ts
import 'symbol-observable';
SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%Foo%'
AND ROUTINE_TYPE='PROCEDURE'
SELECT OBJECT_NAME(id)
FROM SYSCOMMENTS
WHERE [text] LIKE '%Foo%'
AND OBJECTPROPERTY(id, 'IsProcedure') = 1
GROUP BY OBJECT_NAME(id)
SELECT OBJECT_NAME(object_id)
FROM sys.sql_modules
WHERE OBJECTPROPERTY(object_id, 'IsProcedure') = 1
AND definition LIKE '%Foo%'
I tried the solution from Bill using $(document).ready... but at first it did not work. I discovered that if the script is placed after the html section, it will not work. If it is the head section it will work but only in IE. The script does not work in Firefox.
I solved the problem by changing the StartupType of the ssh-agent to Manual
via Set-Service ssh-agent -StartupType Manual
.
Then I was able to start the service via Start-Service ssh-agent
or just ssh-agent.exe
.
I found this on exceljet.net and works for me:
=LEFT(B4,FIND(" ",B4)-1)
While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.
Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter
Because they have different meanings. The @Transient
annotation tells the JPA provider to not persist any (non-transient
) attribute. The other tells the serialization framework to not serialize an attribute. You might want to have a @Transient
property and still serialize it.
You can do this with a single image using something like this:
//get the image view
ImageView imageView = (ImageView)findViewById(R.id.ImageView);
//set the ontouch listener
imageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
ImageView view = (ImageView) v;
//overlay is black with transparency of 0x77 (119)
view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
view.invalidate();
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
ImageView view = (ImageView) v;
//clear the overlay
view.getDrawable().clearColorFilter();
view.invalidate();
break;
}
}
return false;
}
});
I will probably be making this into a subclass of ImageView (or ImageButton as it is also a subclass of ImageView) for easier re-usability, but this should allow you to apply a "selected" look to an imageview.
Just to add: you also get different values for their sizes.
printf("sizeof s[] = %zu\n", sizeof(s)); //6
printf("sizeof *s = %zu\n", sizeof(s)); //4 or 8
As mentioned above, for an array '\0'
will be allocated as the final element.
I was facing the same issue and get it resolved using the below simple steps:
1) Download the InstallCert.java from google
2) Compile it using javac InstallCert.java
3) Run InstallCert.java using java InstallCert.java, with the hostname and https port, and press “1” when asking for input. It will add the “localhost” as a trusted keystore, and generate a file named “jssecacerts“ as below:
java InstallCert localhost:443
4) copy the jssecacerts into $JAVA_HOME/jre/lib/security folder
Main source to resolve the issue here is:
https://ankurjain26.blogspot.in/2017/11/javaxnetsslsslhandshakeexception.html
Do I need to setup specific URLconf patters for uploaded media?
Yes. For development, it's as easy as adding this to your URLconf:
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
)
However, for production, you'll want to serve the media using Apache, lighttpd, nginx, or your preferred web server.
Wrap your two+ function calls in another function/method. Here are a couple variants of that idea:
1) Separate method
var Test = React.createClass({
onClick: function(event){
func1();
func2();
},
render: function(){
return (
<a href="#" onClick={this.onClick}>Test Link</a>
);
}
});
or with ES6 classes:
class Test extends React.Component {
onClick(event) {
func1();
func2();
}
render() {
return (
<a href="#" onClick={this.onClick}>Test Link</a>
);
}
}
2) Inline
<a href="#" onClick={function(event){ func1(); func2()}}>Test Link</a>
or ES6 equivalent:
<a href="#" onClick={() => { func1(); func2();}}>Test Link</a>
var ind=0;
foreach(string s in sList){
if(s.equals("ok")){
return true;
}
ind++;
}
if (ind==sList.length){
return false;
}
This will delete all the files in a directory (and below) that are size zero.
find /tmp -size 0 -print -delete
If you just want a particular file;
if [ ! -s /tmp/foo ] ; then
rm /tmp/foo
fi
Use org.apache.commons.lang3.StringUtils:
name = StringUtils.defaultString(city.getName(), "N/A");
Also take a look at ILSpy by SharpDevelop. It's in early stages of development and they just made a release on the 24th of February. That in itself works pretty good for me. From their website:
ILSpy is the open-source .NET assembly browser and decompiler.
Development started after Red Gate announced that the free version of .NET Reflector would cease to exist by end of February 2011.
Update: JetBrains has released dotPeek, its free .NET decompiler.
Update 2: Telerik also has a free decompiler: JustDecompile.
Use a function in place of MidpointRounding.AwayFromZero
:
myRound(1.11125,4)
Answer:- 1.1114
public static Double myRound(Double Value, int places = 1000)
{
Double myvalue = (Double)Value;
if (places == 1000)
{
if (myvalue - (int)myvalue == 0.5)
{
myvalue = myvalue + 0.1;
return (Double)Math.Round(myvalue);
}
return (Double)Math.Round(myvalue);
places = myvalue.ToString().Substring(myvalue.ToString().IndexOf(".") + 1).Length - 1;
} if ((myvalue * Math.Pow(10, places)) - (int)(myvalue * Math.Pow(10, places)) > 0.49)
{
myvalue = (myvalue * Math.Pow(10, places + 1)) + 1;
myvalue = (myvalue / Math.Pow(10, places + 1));
}
return (Double)Math.Round(myvalue, places);
}
Use this
SELECT *
INTO new_table_name
FROM current_table_name
Enable virtualization Technology
This is worked in my case
Restart Computer Continuously press Esc and then F10 to enter BIOS setup configuration Check Virtualization technology
My PC is HP Zbook 1. Boot the unit to BIOS (Reboot the unit and keep tapping on F10).
Navigate to Advanced>Device or System Configuration> Click on the check box Virtualization Technology (VTx) and Virtualization Technology for Directed I/O (VTd)
Save changes and Exit.
This will display a list of the full path to each file that contains the search string:
foreach ($file in Get-ChildItem | Select-String -pattern "dummy" | Select-Object -Unique path) {$file.path}
Note that it doesn't display a header above the results and doesn't display the lines of text containing the search string. All it tells you is where you can find the files that contain the string.
Technology used: Windows 7, UFT 32 bit, Data Source ODBC pointing out to 32 bit C:\Windows\System32\odbcad32.exe
, Oracle client with both versions installed 32 bit and 64 bit.
What worked for me:
1.Start -> search for Edit the system environment variables
2.System Variables -> Edit Path
3.Place the path for Oracle client 32 bit
in front of the path for Oracle Client 64 bit
.
Ex:
C:\APP\ORACLE\product\11.2.0\client_32\bin;C:\APP\ORACLE\product\11.2.0\client_64\bin
1. Include the Open Graph XML namespace extension to your HTML declaration
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://ogp.me/ns/fb#">
2. Inside your <head></head>
use the following meta tag to define the image you want to use
<meta property="og:image" content="fully_qualified_image_url_here" />
Read more about open graph protocol here.
After doing the above, use the Facebook "Object Debugger" if the image does not show up correctly. Also note the first time shared it still won't show up unless height and width are also specified, see Share on Facebook - Thumbnail not showing for the first time
Just set Integrated Security=False
and it will work ,according to a comment difference between True
and False
is:
True
ignoresUser ID
andPassword
if provided and uses those of the running process,SSPI(Security Support Provider Interface )
it will use them if provided which is why MS prefers this. They are equivalent in that they use the same security mechanism to authenticate but that is it.
The best way is to create a variable of type Worksheet
, assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet
.
This will help you avoid bugs that will eventually show up when your program grows in size.
For example something like Range("A1:C10").Sort Key1:=Range("A2")
is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn't work, adjust it to ShTest1.Range("A1:C10").Sort Key1:=Range("A2")
... and find out that it still doesn't work.
Here is the correct way:
Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")