Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0
first, then cd %~dp0
. This will change the directory to the batch file's drive, then change to its folder.
Alternatively, for #oneLinerLovers, as @Omni pointed out in the comments cd /d %~dp0
will change both the drive and directory :)
Hope this helps someone.
yes I often need to have 3 or more JVM's installed. For example, I've noticed that sometimes the JRE is slightly different to the JDK version of the JRE.
My go to solution on Windows for a bit of 'packaging' is something like this:
@echo off
setlocal
@rem _________________________
@rem
@set JAVA_HOME=b:\lang\java\jdk\v1.6\u45\x64\jre
@rem
@set JAVA_EXE=%JAVA_HOME%\bin\java
@set VER=test
@set WRK=%~d0%~p0%VER%
@rem
@pushd %WRK%
cd
@echo.
@echo %JAVA_EXE% -jar %WRK%\openmrs-standalone.jar
%JAVA_EXE% -jar %WRK%\openmrs-standalone.jar
@rem
@rem _________________________
popd
endlocal
@exit /b
I think it is straightforward. The main thing is the setlocal and endlocal give your app a "personal environment" for what ever it does -- even if there's other programs to run.
Once you set the app.config file, visual studio will generate a copy in the bin folder named App.exe.config. Copy this to the application directory during deployment. Sounds obvious but surprisingly a lot of people miss this step. WinForms developers are not used to config files :).
Usage of javascript:void(0)
means that the author of the HTML is misusing the anchor element in place of the button element.
Anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. These values cause unexpected behavior when copying/dragging links, opening links in a new tabs/windows, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a
<button>
instead. In general you should only use an anchor for navigation using a proper URL.
Source: MDN's <a>
Page.
You can do this:
satView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
}
}
);
How do I change Android Studio editor's background color?
Changing Editor's Background
Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there
IDE will display a dialog like this, Press 'No'
Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?
Changing IDE's Theme
Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there
Press OK. Android Studio will ask you to restart the IDE.
Either use
<embed src="file.pdf" />
if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff
First of all, input
element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden
).
Second thing, you need the after()
, not append()
function.
With MySQL 5.x you can use:
ALTER TABLE table_name
CHANGE COLUMN old_column_name new_column_name DATATYPE NULL DEFAULT NULL;
Try getting the element with the ID and check if the return value is null:
document.getElementById('some_nonexistent_id') === null
If you're using jQuery, you can do:
$('#some_nonexistent_id').length === 0
The variable to use would be process.platform
On Mac the variable returns darwin
. On Windows, it returns win32
(even on 64 bit).
aix
darwin
freebsd
linux
openbsd
sunos
win32
I just set this at the top of my jakeFile:
var isWin = process.platform === "win32";
Since assertThat
which was the old answer is now deprecated, I am posting the correct solution:
assertTrue(objectUnderTest instanceof TargetObject);
I would suggest this for matching Chrome's style, extended from Jarish's example. Notice the cursor property which previous answers have omitted.
cursor: text;
border: 1px solid #ccc;
font: medium -moz-fixed;
font: -webkit-small-control;
height: 200px;
overflow: auto;
padding: 2px;
resize: both;
-moz-box-shadow: inset 0px 1px 2px #ccc;
-webkit-box-shadow: inset 0px 1px 2px #ccc;
box-shadow: inset 0px 1px 2px #ccc;
You should be able to specify the whole path to the destination of your choice. E.g.:
plt.savefig('E:\New Folder\Name of the graph.jpg')
Make sure your first line is:
#!/bin/bash
Enter your path to bash if it is not /bin/bash
Try running:
dos2unix script.sh
That wil convert line endings, etc from Windows to unix format. i.e. it strips \r (CR) from line endings to change them from \r\n (CR+LF)
to \n (LF)
.
More details about the dos2unix
command (man page)
Another way to tell if your file is in dos/Win format:
cat scriptname.sh | sed 's/\r/<CR>/'
The output will look something like this:
#!/bin/sh<CR>
<CR>
echo Hello World<CR>
<CR>
This will output the entire file text with <CR>
displayed for each \r
character in the file.
The %pdb
magic command is good to use as well. Just say %pdb on
and subsequently the pdb
debugger will run on all exceptions, no matter how deep in the call stack. Very handy.
If you have a particular line that you want to debug, just raise an exception there (often you already are!) or use the %debug
magic command that other folks have been suggesting.
If you are using bash 4 you can use the following approach:
x="HELLO"
echo $x # HELLO
y=${x,,}
echo $y # hello
z=${y^^}
echo $z # HELLO
Use only one ,
or ^
to make the first letter lowercase
or uppercase
.
I have an S3 and used this guide from Google:
https://developers.google.com/chrome-developer-tools/docs/remote-debugging
Really easy, works flawlessly.
Try this command
msiexec /x {product-id} /qr
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
The cherry-pick command can read the list of commits from the standard input.
The following command cherry-picks commits authored by the user John that exist in the "develop" branch but not in the "release" branch, and does so in the chronological order.
git log develop --not release --format=%H --reverse --author John | git cherry-pick --stdin
var newItem = document.createElement("LI"); // Create a <li> node
var textnode = document.createTextNode("Water"); // Create a text node
newItem.appendChild(textnode); // Append the text to <li>
var list = document.getElementById("myList"); // Get the <ul> element to insert a new node
list.insertBefore(newItem, list.childNodes[0]); // Insert <li> before the first child of <ul>
No you can't use bind variables that way. In your second example :into_bind
in v_query_str
is just a placeholder for value of variable v_num_of_employees
. Your select into statement will turn into something like:
SELECT COUNT(*) INTO FROM emp_...
because the value of v_num_of_employees
is null
at EXECUTE IMMEDIATE
.
Your first example presents the correct way to bind the return value to a variable.
Edit
The original poster has edited the second code block that I'm referring in my answer to use OUT
parameter mode for v_num_of_employees
instead of the default IN
mode. This modification makes the both examples functionally equivalent.
To answer the original question specifically (using IO.FileAttributes):
Get-ChildItem c:\mypath -Recurse | Where-Object {$_.Attributes -and [IO.FileAttributes]::Directory}
I do prefer Marek's solution though (Where-Object { $_ -is [System.IO.DirectoryInfo] }
).
You can use the ??
test operator:
This checks if the attribute of the object is not null:
<#if object.attribute??></#if>
This checks if object or attribute is not null:
<#if (object.attribute)??></#if>
Source: FreeMarker Manual
To just get your IP address:
echo `ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://'`
This will give you the IP address of eth0.
Edit: Due to name changes of interfaces in recent versions of Ubuntu, this doesn't work anymore. Instead, you could just use this:
hostname --all-ip-addresses
or hostname -I
, which does the same thing (gives you ALL IP addresses of the host).
I had the same issue when i reference the Class library into my MVC web application,
the issue was the nuget package version number mismatch between two projects.
ex: my class library had log4net of 1.2.3 but my webapp had 1.2.6
fix: just make sure both the project have the same version number referenced.
You can get your menu back by pressing/holding alt, you can then toggle the menu back on via the View menu.
As for your settings, you can open your user settings through the command palette:
From there you can delete the file's contents and save to reset your settings.
For a more manual route, the settings files are located in the following locations:
%APPDATA%\Code\User\settings.json
$HOME/Library/Application Support/Code/User/settings.json
$HOME/.config/Code/User/settings.json
Extensions are located in the following locations:
%USERPROFILE%\.vscode\extensions
~/.vscode/extensions
~/.vscode/extensions
Well, depending on your needs you can choose any of the following. Out put is written against each method
You can choose the one you need
This will round
decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58
This will ensure that 2 decimal places are written.
d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50
if you want to write commas you can use this
d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54
if you want to return the rounded of decimal value you can do this
d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58
this seems to be working :
#canvas{
border: solid 1px blue;
width:100%;
}
function functABC(){
// returns a promise that can be used later.
return $.ajax({
url: 'myPage.php',
data: {id: id}
});
}
functABC().then( response =>
console.log(response);
);
Nice read e.g. here.
This is not "synchronous" really, but I think it achieves what the OP intends.
async
option has since been deprecated):All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify
async: false
like described here
Note, however, that in most cases asynchronous execution (via callback on success) is just fine.
The following automatically uses the best precision:
/**
* Compare to floats for (almost) equality. Will check whether they are
* at most 5 ULP apart.
*/
public static boolean isFloatingEqual(float v1, float v2) {
if (v1 == v2)
return true;
float absoluteDifference = Math.abs(v1 - v2);
float maxUlp = Math.max(Math.ulp(v1), Math.ulp(v2));
return absoluteDifference < 5 * maxUlp;
}
Of course, you might choose more or less than 5 ULPs (‘unit in the last place’).
If you’re into the Apache Commons library, the Precision
class has compareTo()
and equals()
with both epsilon and ULP.
In my case changing firebase library version from 2.6.0 to 2.4.2 fixed the issue
Cross join :Cross Joins produce results that consist of every combination of rows from two or more tables. That means if table A has 3 rows and table B has 2 rows, a CROSS JOIN will result in 6 rows. There is no relationship established between the two tables – you literally just produce every possible combination.
Full outer Join : A FULL OUTER JOIN is neither "left" nor "right"— it's both! It includes all the rows from both of the tables or result sets participating in the JOIN. When no matching rows exist for rows on the "left" side of the JOIN, you see Null values from the result set on the "right." Conversely, when no matching rows exist for rows on the "right" side of the JOIN, you see Null values from the result set on the "left."
For those who are using this format all the timme like me I did an extension method. I just wanted to share because I think it can be usefull to you.
/// <summary>
/// Convert a date to a human readable ISO datetime format. ie. 2012-12-12 23:01:12
/// this method must be put in a static class. This will appear as an available function
/// on every datetime objects if your static class namespace is declared.
/// </summary>
public static string ToIsoReadable(this DateTime dateTime)
{
return dateTime.ToString("yyyy-MM-dd HH':'mm':'ss");
}
str_replace(
array("search","items"),
array("replace", "items"),
$string
);
In response to the final part of your question, which is still unanswered... When you write $('#video').duration
, you're asking for the duration
property of the jQuery collection object, which doesn't exist. The native DOM video element does have the duration. You can get that in a few ways.
Here's one:
// get the native element directly
document.getElementById('video').duration
Here's another:
// get it out of the jQuery object
$('#video').get(0).duration
And another:
// use the event object
v.bind('loadeddata', function(e) {
console.log(e.target.duration);
});
You can use the title
attribute.
<img height="90" width="90"
src="http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif"
alt="Google Images" title="Google Images" />
Hmm, surprised I don't see this answer yet, suppose I'll throw my hat in the ring.
class Action {
const cancelable = 0;
const target = 1
const type = 2;
public $cancelable;
public $target;
public $type;
__construct( $opt = [] ){
$this->cancelable = isset($opt[cancelable]) ? $opt[cancelable] : true;
$this->target = isset($opt[target]) ? $opt[target] : NULL;
$this->type = isset($opt[type]) ? $opt[type] : 'action';
}
}
$myAction = new Action( [
Action::cancelable => false,
Action::type => 'spin',
.
.
.
]);
You can optionally separate the options into their own class, such as extending SplEnum.
abstract class ActionOpt extends SplEnum{
const cancelable = 0;
const target = 1
const type = 2;
}
I realize that this is an old question, with an established answer. The reason I'm posting is that is the accepted answer has many elements of k-NN (k-nearest neighbors), a different algorithm.
Both k-NN and NaiveBayes are classification algorithms. Conceptually, k-NN uses the idea of "nearness" to classify new entities. In k-NN 'nearness' is modeled with ideas such as Euclidean Distance or Cosine Distance. By contrast, in NaiveBayes, the concept of 'probability' is used to classify new entities.
Since the question is about Naive Bayes, here's how I'd describe the ideas and steps to someone. I'll try to do it with as few equations and in plain English as much as possible.
Before someone can understand and appreciate the nuances of Naive Bayes', they need to know a couple of related concepts first, namely, the idea of Conditional Probability, and Bayes' Rule. (If you are familiar with these concepts, skip to the section titled Getting to Naive Bayes')
Conditional Probability in plain English: What is the probability that something will happen, given that something else has already happened.
Let's say that there is some Outcome O. And some Evidence E. From the way these probabilities are defined: The Probability of having both the Outcome O and Evidence E is: (Probability of O occurring) multiplied by the (Prob of E given that O happened)
One Example to understand Conditional Probability:
Let say we have a collection of US Senators. Senators could be Democrats or Republicans. They are also either male or female.
If we select one senator completely randomly, what is the probability that this person is a female Democrat? Conditional Probability can help us answer that.
Probability of (Democrat and Female Senator)= Prob(Senator is Democrat) multiplied by Conditional Probability of Being Female given that they are a Democrat.
P(Democrat & Female) = P(Democrat) * P(Female | Democrat)
We could compute the exact same thing, the reverse way:
P(Democrat & Female) = P(Female) * P(Democrat | Female)
Conceptually, this is a way to go from P(Evidence| Known Outcome) to P(Outcome|Known Evidence). Often, we know how frequently some particular evidence is observed, given a known outcome. We have to use this known fact to compute the reverse, to compute the chance of that outcome happening, given the evidence.
P(Outcome given that we know some Evidence) = P(Evidence given that we know the Outcome) times Prob(Outcome), scaled by the P(Evidence)
The classic example to understand Bayes' Rule:
Probability of Disease D given Test-positive =
P(Test is positive|Disease) * P(Disease)
_______________________________________________________________
(scaled by) P(Testing Positive, with or without the disease)
Now, all this was just preamble, to get to Naive Bayes.
So far, we have talked only about one piece of evidence. In reality, we have to predict an outcome given multiple evidence. In that case, the math gets very complicated. To get around that complication, one approach is to 'uncouple' multiple pieces of evidence, and to treat each of piece of evidence as independent. This approach is why this is called naive Bayes.
P(Outcome|Multiple Evidence) =
P(Evidence1|Outcome) * P(Evidence2|outcome) * ... * P(EvidenceN|outcome) * P(Outcome)
scaled by P(Multiple Evidence)
Many people choose to remember this as:
P(Likelihood of Evidence) * Prior prob of outcome
P(outcome|evidence) = _________________________________________________
P(Evidence)
Notice a few things about this equation:
base rates
and they are a way to scale our predicted probabilities.Just run the formula above for each possible outcome. Since we are trying to classify, each outcome is called a class
and it has a class label.
Our job is to look at the evidence, to consider how likely it is to be this class or that class, and assign a label to each entity.
Again, we take a very simple approach: The class that has the highest probability is declared the "winner" and that class label gets assigned to that combination of evidences.
Let's try it out on an example to increase our understanding: The OP asked for a 'fruit' identification example.
Let's say that we have data on 1000 pieces of fruit. They happen to be Banana, Orange or some Other Fruit. We know 3 characteristics about each fruit:
This is our 'training set.' We will use this to predict the type of any new fruit we encounter.
Type Long | Not Long || Sweet | Not Sweet || Yellow |Not Yellow|Total
___________________________________________________________________
Banana | 400 | 100 || 350 | 150 || 450 | 50 | 500
Orange | 0 | 300 || 150 | 150 || 300 | 0 | 300
Other Fruit | 100 | 100 || 150 | 50 || 50 | 150 | 200
____________________________________________________________________
Total | 500 | 500 || 650 | 350 || 800 | 200 | 1000
___________________________________________________________________
We can pre-compute a lot of things about our fruit collection.
The so-called "Prior" probabilities. (If we didn't know any of the fruit attributes, this would be our guess.) These are our base rates.
P(Banana) = 0.5 (500/1000)
P(Orange) = 0.3
P(Other Fruit) = 0.2
Probability of "Evidence"
p(Long) = 0.5
P(Sweet) = 0.65
P(Yellow) = 0.8
Probability of "Likelihood"
P(Long|Banana) = 0.8
P(Long|Orange) = 0 [Oranges are never long in all the fruit we have seen.]
....
P(Yellow|Other Fruit) = 50/200 = 0.25
P(Not Yellow|Other Fruit) = 0.75
Let's say that we are given the properties of an unknown fruit, and asked to classify it. We are told that the fruit is Long, Sweet and Yellow. Is it a Banana? Is it an Orange? Or Is it some Other Fruit?
We can simply run the numbers for each of the 3 outcomes, one by one. Then we choose the highest probability and 'classify' our unknown fruit as belonging to the class that had the highest probability based on our prior evidence (our 1000 fruit training set):
P(Banana|Long, Sweet and Yellow)
P(Long|Banana) * P(Sweet|Banana) * P(Yellow|Banana) * P(banana)
= _______________________________________________________________
P(Long) * P(Sweet) * P(Yellow)
= 0.8 * 0.7 * 0.9 * 0.5 / P(evidence)
= 0.252 / P(evidence)
P(Orange|Long, Sweet and Yellow) = 0
P(Other Fruit|Long, Sweet and Yellow)
P(Long|Other fruit) * P(Sweet|Other fruit) * P(Yellow|Other fruit) * P(Other Fruit)
= ____________________________________________________________________________________
P(evidence)
= (100/200 * 150/200 * 50/200 * 200/1000) / P(evidence)
= 0.01875 / P(evidence)
By an overwhelming margin (0.252 >> 0.01875
), we classify this Sweet/Long/Yellow fruit as likely to be a Banana.
Look at what it eventually comes down to. Just some counting and multiplication. We can pre-compute all these terms, and so classifying becomes easy, quick and efficient.
Let z = 1 / P(evidence).
Now we quickly compute the following three quantities.
P(Banana|evidence) = z * Prob(Banana) * Prob(Evidence1|Banana) * Prob(Evidence2|Banana) ...
P(Orange|Evidence) = z * Prob(Orange) * Prob(Evidence1|Orange) * Prob(Evidence2|Orange) ...
P(Other|Evidence) = z * Prob(Other) * Prob(Evidence1|Other) * Prob(Evidence2|Other) ...
Assign the class label of whichever is the highest number, and you are done.
Despite the name, Naive Bayes turns out to be excellent in certain applications. Text classification is one area where it really shines.
Hope that helps in understanding the concepts behind the Naive Bayes algorithm.
(command | tee out.txt; exit ${PIPESTATUS[0]})
Unlike @cODAR's answer this returns the original exit code of the first command and not only 0 for success and 127 for failure. But as @Chaoran pointed out you can just call ${PIPESTATUS[0]}
. It is important however that all is put into brackets.
This is probably because of the column() and row() functions. I am not sure how they are applied in conditional formatting. Try creating a new column with the value from this formula and then use it for your formatting needs.
You cannot pass custom parameters in addTarget:
.One alternative is set the tag
property of button and do work based on the tag.
button.tag = 5
button.addTarget(self, action: "buttonClicked:",
forControlEvents: UIControlEvents.TouchUpInside)
Or for Swift 2.2 and greater:
button.tag = 5
button.addTarget(self,action:#selector(buttonClicked),
forControlEvents:.TouchUpInside)
Now do logic based on tag
property
@objc func buttonClicked(sender:UIButton)
{
if(sender.tag == 5){
var abc = "argOne" //Do something for tag 5
}
print("hello")
}
Yes there is
int temp;
int.TryParse("141241", out temp) = true
int.TryParse("232a23", out temp) = false
int.TryParse("12412a", out temp) = false
Hope this helps.
I am using this example in my project:
html:
<hr class="my-3 dividerClass"/>
css:
.dividerClass{
border-top-color: #999
}
It seems that Luiggi Mendoza
and joey rohan
both already answered this, but I think it can be clarified a little.
You can write it as a single if
statement:
if (inventory.contains("bread") && !inventory.contains("water")) {
// do something
}
Easy peasy. Your data frame will look like this:
df <- data.frame(sex=c('M','F','M'),
occupation=c('Student','Analyst','Analyst'))
You can then do the equivalent of a COUNTIF
by first specifying the IF
part, like so:
df$sex == 'M'
This will give you a boolean vector, i.e. a vector of TRUE
and FALSE
. What you want is to count the observations for which the condition is TRUE
. Since in R TRUE
and FALSE
double as 1 and 0 you can simply sum()
over the boolean vector. The equivalent of COUNTIF(sex='M')
is therefore
sum(df$sex == 'M')
Should there be rows in which the sex
is not specified the above will give back NA
. In that case, if you just want to ignore the missing observations use
sum(df$sex == 'M', na.rm=TRUE)
In Ruby and Bash, you can use $
inside parentheses.
/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|$)
(This solution is similar to Pete Boughton's, but preserves the usage of $
, which means end of line, rather than using \z
, which means end of string.)
If you want to keep the heredoc indented for readability:
$ perl -pe 's/^\s*//' << EOF
line 1
line 2
EOF
The built-in method for supporting indented heredoc in Bash only supports leading tabs, not spaces.
Perl can be replaced with awk to save a few characters, but the Perl one is probably easier to remember if you know basic regular expressions.
They are the accessors for the public property Name.
You would use them to get/set the value of that property in an instance of Genre.
I was using CodeIgniter and used the code below to get it. May be useful for someone in future.
$this->input->get_request_header('X-Requested-With');
If this is long array you could use
var sb = arr.Aggregate(new StringBuilder(), ( s, i ) => s.Append( i ), s.ToString());
I also faced the same problem. In my case I was hitting a java.util.UnknownFormatConversionException
. I figured this out only after putting a printStackTrace
call. I resolved it by changing my code as shown below.
from:
StringBuilder sb = new StringBuilder();
sb.append("***** Test Details *****\n");
String.format("[Test: %1]", sb.toString());
to:
String.format("[Test: %s]", sb.toString());
Can monitor registry changes made by specific program.
https://www.nirsoft.net/utils/reg_file_from_application.html
UPDATE: Just download NirLauncher (which includes all applications from NirSoft). It is one of the best additions to your Windows toolbox. https://launcher.nirsoft.net/
add
credits: {
enabled: false
}
[NOTE] that it is in the same line with
xAxis: {}
and yAxis: {}
My app was built in an older version of VS, and didn't have a bin folder. I had upgraded it to a newer version, and had a nightmare getting it to deploy. I finally tracked this error down to the Project > Properties > Application. The Target Framework was set to 2.0; changing it on the server to match in the IIS Manager/App Pool solved the issue for me.
Firstly, application.properties in the @PropertySource should read application-test.properties
if that's what the file is named (matching these things up matters):
@PropertySource("classpath:application-test.properties ")
That file should be under your /src/test/resources
classpath (at the root).
I don't understand why you'd specify a dependency hard coded to a file called application-test.properties
. Is that component only to be used in the test environment?
The normal thing to do is to have property files with the same name on different classpaths. You load one or the other depending on whether you are running your tests or not.
In a typically laid out application, you'd have:
src/test/resources/application.properties
and
src/main/resources/application.properties
And then inject it like this:
@PropertySource("classpath:application.properties")
The even better thing to do would be to expose that property file as a bean in your spring context and then inject that bean into any component that needs it. This way your code is not littered with references to application.properties and you can use anything you want as a source of properties. Here's an example: how to read properties file in spring project?
'In Visual Basic
Dim FileName = "newfile.xml" ' The Name of file with its Extension Example A.txt or A.xml
Dim FilePath ="C:\MyFolderName" & "\" & FileName 'First Name of Directory and Then Name of Folder if it exists and then attach the name of file you want to search.
If System.IO.File.Exists(FilePath) Then
MsgBox("The file exists")
Else
MsgBox("the file doesn't exist")
End If
I am unsure if the author originally was just asking whether or not this allows duplicate values or if there was an implied question here asking, "How to allow duplicate NULL
values while using UNIQUE
?" Or "How to only allow one UNIQUE
NULL
value?"
The question has already been answered, yes you can have duplicate NULL
values while using the UNIQUE
index.
Since I stumbled upon this answer while searching for "how to allow one UNIQUE
NULL
value." For anyone else who may stumble upon this question while doing the same, the rest of my answer is for you...
In MySQL you can not have one UNIQUE
NULL
value, however you can have one UNIQUE
empty value by inserting with the value of an empty string.
Warning: Numeric and types other than string may default to 0 or another default value.
The origin of this error lies in the fact that each and every promise is expected to handle promise rejection i.e. have a .catch(...) . you can avoid the same by adding .catch(...) to a promise in the code as given below.
for example, the function PTest() will either resolve or reject a promise based on the value of a global variable somevar
var somevar = false;
var PTest = function () {
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
var myfunc = PTest();
myfunc.then(function () {
console.log("Promise Resolved");
}).catch(function () {
console.log("Promise Rejected");
});
In some cases, the "unhandled promise rejection" message comes even if we have .catch(..) written for promises. It's all about how you write your code. The following code will generate "unhandled promise rejection" even though we are handling catch
.
var somevar = false;
var PTest = function () {
return new Promise(function (resolve, reject) {
if (somevar === true)
resolve();
else
reject();
});
}
var myfunc = PTest();
myfunc.then(function () {
console.log("Promise Resolved");
});
// See the Difference here
myfunc.catch(function () {
console.log("Promise Rejected");
});
The difference is that you don't handle .catch(...)
as chain but as separate. For some reason JavaScript engine treats it as promise without un-handled promise rejection.
For viewers who got this error after upgrading React Native to 0.40+, you may need to run react-native upgrade
on the command line.
Because this seems to not be marked as answered yet... The Answer of Thomas Arildsen should be the proper one: just use
np.flipud(your_array)
if it is a 1d array (column array).
With matrizes do
fliplr(matrix)
if you want to reverse rows and flipud(matrix)
if you want to flip columns. No need for making your 1d column array a 2dimensional row array (matrix with one None layer) and then flipping it.
Advice for R
newcomers like me : beware, the following is a list of a single object :
> mylist <- list (1:10)
> length (mylist)
[1] 1
In such a case you are not looking for the length of the list, but of its first element :
> length (mylist[[1]])
[1] 10
This is a "true" list :
> mylist <- list(1:10, rnorm(25), letters[1:3])
> length (mylist)
[1] 3
Also, it seems that R
considers a data.frame as a list :
> df <- data.frame (matrix(0, ncol = 30, nrow = 2))
> typeof (df)
[1] "list"
In such a case you may be interested in ncol()
and nrow()
rather than length()
:
> ncol (df)
[1] 30
> nrow (df)
[1] 2
Though length()
will also work (but it's a trick when your data.frame has only one column) :
> length (df)
[1] 30
> length (df[[1]])
[1] 2
a profanity filtering system will never be perfect, even if the programmer is cocksure and keeps abreast of all nude developments
that said, any list of 'naughty words' is likely to perform as well as any other list, since the underlying problem is language understanding which is pretty much intractable with current technology
so, the only practical solution is twofold:
One could use the queryParam method, passing it parameter name and an array of values:
public WebTarget queryParam(String name, Object... values);
Example (jersey-client 2.23.2):
WebTarget target = ClientBuilder.newClient().target(URI.create("http://localhost"));
target.path("path")
.queryParam("param_name", Arrays.asList("paramVal1", "paramVal2").toArray())
.request().get();
This will issue request to following URL:
http://localhost/path?param_name=paramVal1¶m_name=paramVal2
In my case there was a static variable which was not initialized. When I initialized it, the error was removed. I don't know the logic behind it but worked for me. I know its a little late but other people with similar problem might get some help.
I would say that it depends on what you want to do.
If your dropdown is a component for a form that manages a state, I would leverage the two-way binding of Angular2. For this, I would use two attributes: an input one to get the associated object and an output one to notify when the state changes.
Here is a sample:
export class DropdownValue {
value:string;
label:string;
constructor(value:string,label:string) {
this.value = value;
this.label = label;
}
}
@Component({
selector: 'dropdown',
template: `
<ul>
<li *ngFor="let value of values" (click)="select(value.value)">{{value.label}}</li>
</ul>
`
})
export class DropdownComponent {
@Input()
values: DropdownValue[];
@Input()
value: string[];
@Output()
valueChange: EventEmitter;
constructor(private elementRef:ElementRef) {
this.valueChange = new EventEmitter();
}
select(value) {
this.valueChange.emit(value);
}
}
This allows you to use it this way:
<dropdown [values]="dropdownValues" [(value)]="value"></dropdown>
You can build your dropdown within the component, apply styles and manage selections internally.
Edit
You can notice that you can either simply leverage a custom event in your component to trigger the selection of a dropdown. So the component would now be something like this:
export class DropdownValue {
value:string;
label:string;
constructor(value:string,label:string) {
this.value = value;
this.label = label;
}
}
@Component({
selector: 'dropdown',
template: `
<ul>
<li *ngFor="let value of values" (click)="selectItem(value.value)">{{value.label}}</li>
</ul>
`
})
export class DropdownComponent {
@Input()
values: DropdownValue[];
@Output()
select: EventEmitter;
constructor() {
this.select = new EventEmitter();
}
selectItem(value) {
this.select.emit(value);
}
}
Then you can use the component like this:
<dropdown [values]="dropdownValues" (select)="action($event.value)"></dropdown>
Notice that the action
method is the one of the parent component (not the dropdown one).
This add-in claims to have the functionality that I believe you seek:
JavaScript: Convert String to Array JavaScript Split
var str = "This-javascript-tutorial-string-split-method-examples-tutsmake."_x000D_
_x000D_
var result = str.split('-'); _x000D_
_x000D_
console.log(result);_x000D_
_x000D_
document.getElementById("show").innerHTML = result;
_x000D_
<html>_x000D_
<head>_x000D_
<title>How do you split a string, breaking at a particular character in javascript?</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p id="show"></p> _x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
https://www.tutsmake.com/javascript-convert-string-to-array-javascript/
Convert binary file to base64 & vice versa. Prove in python 3.5.2
import base64
read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()
b64 = base64.b64encode(data)
print (b64)
# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)
# Test in python 3.5.2
var ele = document.getElementById('newSkill')
ele.onchange = function(){
var length = ele.children.length
for(var i=0; i<length;i++){
if(ele.children[i].selected){alert(ele.children[i].text)};
}
}
Ok, maybe I'm missing something here, but this is the way I do it:
public static Byte[] ToByteArray(this Stream stream) {
Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
Byte[] buffer = new Byte[length];
stream.Read(buffer, 0, length);
return buffer;
}
I got this error when one of my properties that was required for the constructor was not public. Make sure all the parameters in the constructor go to properties that are public if this is the case:
using statements namespace someNamespace
public class ExampleClass {
//Properties - one is not visible to the class calling the constructor
public string Property1 { get; set; }
string Property2 { get; set; }
//Constructor
public ExampleClass(string property1, string property2)
{
this.Property1 = property1;
this.Property2 = property2; //this caused that error for me
}
}
You need to handle the MouseDown and MouseUp and set some flag or something to track it "later down the road"... :(
Wouldn't it just be:
SELECT CURRENT_DATE - CHDLM FROM CHCART00 WHERE CHSTAT = '05';
That should return the number of days between the two dates, if I understand how date arithmetic works in DB2 correctly.
If CHDLM isn't a date you'll have to convert it to one. According to IBM the DATE() function would not be sufficient for the yyyymmdd format, but it would work if you can format like this: yyyy-mm-dd.
You want the Pillow library, here is how to install it on Python 3:
pip3 install Pillow
If that does not work for you (it should), try normal pip
:
pip install Pillow
//HashSet allows only the unique values to the list
HashSet<int> uniqueList = new HashSet<int>();
var a = uniqueList.Add(1);
var b = uniqueList.Add(2);
var c = uniqueList.Add(3);
var d = uniqueList.Add(2); // should not be added to the list but will not crash the app
//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1,"Happy");
dict.Add(2, "Smile");
dict.Add(3, "Happy");
dict.Add(2, "Sad"); // should be failed // Run time error "An item with the same key has already been added." App will crash
//Dictionary allows only the unique Keys to the list, Values can be repeated
Dictionary<string, int> dictRev = new Dictionary<string, int>();
dictRev.Add("Happy", 1);
dictRev.Add("Smile", 2);
dictRev.Add("Happy", 3); // should be failed // Run time error "An item with the same key has already been added." App will crash
dictRev.Add("Sad", 2);
In my legacy app Array.from of prototype js was conflicting with angular's Array.from that was causing this problem. I resolved it by saving angular's Array.from version and reassigning it after prototype load.
To do this, I use a custom filter.
In my app:
myApp.filter('rawHtml', ['$sce', function($sce){
return function(val) {
return $sce.trustAsHtml(val);
};
}]);
Then, in the view:
<h1>{{ stuff.title}}</h1>
<div ng-bind-html="stuff.content | rawHtml"></div>
I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..
I have to find distinct rows with the following details
class : Scountry
columns: countryID, countryName,isactive
There is no primary key in this. I have succeeded with the followin queries
public DbSet<SCountry> country { get; set; }
public List<SCountry> DoDistinct()
{
var query = (from m in country group m by new { m.CountryID, m.CountryName, m.isactive } into mygroup select mygroup.FirstOrDefault()).Distinct();
var Countries = query.ToList().Select(m => new SCountry { CountryID = m.CountryID, CountryName = m.CountryName, isactive = m.isactive }).ToList();
return Countries;
}
var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'
Prefix you literal with 0b
like in
int i = 0b11111111;
See here.
Creat XML called border.xml in drawable folder as below :
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp" android:right="5dp" android:top="5dp" >
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
then add this to linear layout as backgound as this:
android:background="@drawable/border"
To answer your question with a working example:
<script type="text/javascript">
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = new Array();
for (var index in array[i]) {
line.push('"' + array[i][index] + '"');
}
str += line.join(';');
str += '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + encodeURIComponent(str));
}
</script>
In node, you can just say
console.log(aa)
and it will format it as it should.
If you need to use the resulting string you should use
JSON.stringify(aa)
Try to use:
Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = "MySheet"
If you want to check whether a sheet with the same name already exists, you can create a function:
Function funcCreateList(argCreateList)
For Each Worksheet In ThisWorkbook.Worksheets
If argCreateList = Worksheet.Name Then
Exit Function ' if found - exit function
End If
Next Worksheet
Worksheets.Add (After:=Worksheets(Worksheets.Count)).Name = argCreateList
End Function
When the function is created, you can call it from your main Sub, e.g.:
Sub main
funcCreateList "MySheet"
Exit Sub
Check your routing method:
if your routing state is like this
.state('app.register', {
url: '/register',
views: {
'menuContent': {
templateUrl: 'templates/register.html',
}
}
})
then you should use
$location.path("/app/register");
I won't address the READ UNCOMMITTED
argument, just your original question.
Yes, you need WITH(NOLOCK)
on each table of the join. No, your queries are not the same.
Try this exercise. Begin a transaction and insert a row into table1 and table2. Don't commit or rollback the transaction yet. At this point your first query will return successfully and include the uncommitted rows; your second query won't return because table2 doesn't have the WITH(NOLOCK)
hint on it.
w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.
You can get more information on w3wp.exe here
http://www.processlibrary.com/en/directory/files/w3wp/25761/
One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?
Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...
<div id="checkboxes">
<input type="checkbox" /> Some label<br />
<input type="checkbox" /> Some other label<br />
</div>
<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>
Based on this markup your jquery could bind to the click
event of the button and manipulate the DOM.
$('#addCheckbox').click(function() {
var text = $('#newCheckText').val();
$('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});
tableColumns
null
for all columns as in SELECT * FROM ...
new String[] { "column1", "column2", ... }
for specific columns as in SELECT column1, column2 FROM ...
- you can also put complex expressions here:new String[] { "(SELECT max(column1) FROM table1) AS max" }
would give you a column named max
holding the max value of column1
whereClause
WHERE
without that keyword, e.g. "column1 > 5"
?
for things that are dynamic, e.g. "column1=?"
-> see whereArgs
whereArgs
?
in whereClause
in the order they appearthe others
whereClause
the statement after the keyword or null
if you don't use it.Example
String[] tableColumns = new String[] {
"column1",
"(SELECT max(column1) FROM table2) AS max"
};
String whereClause = "column1 = ? OR column1 = ?";
String[] whereArgs = new String[] {
"value1",
"value2"
};
String orderBy = "column1";
Cursor c = sqLiteDatabase.query("table1", tableColumns, whereClause, whereArgs,
null, null, orderBy);
// since we have a named column we can do
int idx = c.getColumnIndex("max");
is equivalent to the following raw query
String queryString =
"SELECT column1, (SELECT max(column1) FROM table1) AS max FROM table1 " +
"WHERE column1 = ? OR column1 = ? ORDER BY column1";
sqLiteDatabase.rawQuery(queryString, whereArgs);
By using the Where/Bind -Args version you get automatically escaped values and you don't have to worry if input-data contains '
.
Unsafe: String whereClause = "column1='" + value + "'";
Safe: String whereClause = "column1=?";
because if value contains a '
your statement either breaks and you get exceptions or does unintended things, for example value = "XYZ'; DROP TABLE table1;--"
might even drop your table since the statement would become two statements and a comment:
SELECT * FROM table1 where column1='XYZ'; DROP TABLE table1;--'
using the args version XYZ'; DROP TABLE table1;--
would be escaped to 'XYZ''; DROP TABLE table1;--'
and would only be treated as a value. Even if the '
is not intended to do bad things it is still quite common that people have it in their names or use it in texts, filenames, passwords etc. So always use the args version. (It is okay to build int
and other primitives directly into whereClause
though)
<div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
<strong>Column 0 </strong><br>
<strong>Column 1</strong><br>
<strong>Column 2</strong><br>
<strong>Column 3</strong><br>
<strong>Column 4</strong><br>
<strong>Column 5</strong><br>
<strong>Column 6</strong><br>
<strong>Column 7</strong><br>
<strong>Column 8</strong><br>
<strong>Column 9</strong><br>
<strong>Column 10</strong><br>
<strong>Column 11</strong><br>
<strong>Column 12</strong><br>
<strong>Column 13</strong><br>
</div>
</div>
You can loop through variable with list of directories:
- name: Copy files from several directories
copy:
src: "{{ item }}"
dest: "/etc/fooapp/"
owner: root
mode: "0600"
loop: "{{ files }}"
vars:
files:
- "dir1/"
- "dir2/"
You can use this:
@Html.DropDownListFor(x => x.Tipo, new List<SelectListItem>
{
new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}
})
I'm just beginner to help you for getting edittext value to textview. Try out this code -
EditText edit = (EditText)findViewById(R.id.editext1);
TextView tview = (TextView)findViewById(R.id.textview1);
String result = edit.getText().toString();
tview.setText(result);
This will get the text which is in EditText
Hope this helps you.
if (Value1.StartsWith("abc")) { found = true; }
I think it depends on the operations you'll be needing to do most frequently.
If you need the full value as a decimal number, then use decimal with appropriate precision and scale. Float is way beyond your needs, I believe.
If you'll be converting to/from degºmin'sec"fraction notation often, I'd consider storing each value as an integer type (smallint, tinyint, tinyint, smallint?).
Use cut:
echo 'someletters_12345_moreleters.ext' | cut -d'_' -f 2
More generic:
INPUT='someletters_12345_moreleters.ext'
SUBSTRING=$(echo $INPUT| cut -d'_' -f 2)
echo $SUBSTRING
You can use the "Join" function to create a single string out of the array of labels, like this:
=Join(Parameters!Product.Label, ",")
If you want to skip US holidays as well as weekends, this worked for me (using pandas 0.23.3):
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar
from pandas.tseries.offsets import CustomBusinessDay
US_BUSINESS_DAY = CustomBusinessDay(calendar=USFederalHolidayCalendar())
july_5 = pd.datetime(2018, 7, 5)
result = july_5 - 2 * US_BUSINESS_DAY # 2018-7-2
To convert to a python date object I did this:
result.to_pydatetime().date()
I'll suggest to set padding and margin to 0.
If this does not solve your problem you can try playing with line-height even if not reccomended.
Or you can pass by reference:
function byRef($x, &$a, &$b)
{
$a = 10 * $x;
$b = 100 * $x;
}
$a = 0;
$b = 0;
byRef(10, $a, $b);
echo $a . "\n";
echo $b;
This would output
100
1000
There are several problems here:
The newdata
argument of predict()
needs a predictor variable. You should thus pass it values for Coupon
, instead of Total
, which is the response variable in your model.
The predictor variable needs to be passed in as a named column in a data frame, so that
predict()
knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).
For this to work, your original call should pass df
in through the data
argument, rather than using it directly in your formula. (This way, the name of the column in newdata
will be able to match the name on the RHS of the formula).
With those changes incorporated, this will work:
model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")
I had a similar issue; upgrading to Apache HTTPClient 4.5.3 fixed it.
In addition to @pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN
like this
SELECT * FROM expense INNER JOIN refuel
ON exp_id = expense_id
WHERE refuel_id = 1
via raw query like this -
String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
+ " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
+ " WHERE " + RefuelTable.ID + " = " + id;
Cursor c = db.rawQuery(
rawQuery,
null
);
because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -
SELECT *
FROM expense, refuel
WHERE exp_id = expense_id AND refuel_id = 1
and hence be able to take advanatage of the SQLiteDatabase.query() helper method
Cursor c = db.query(
RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " + id,
null,
null,
null,
null
);
For a detailed blog post check this http://blog.championswimmer.in/2015/12/doing-a-table-join-in-android-without-using-rawquery
The keycodes are different. Keypad 0-9 is Keycode 96
to 105
Your if
statement should be:
if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
// 0-9 only
}
Here's a reference guide for keycodes
-- UPDATE --
This is an old answer and keyCode
has been deprecated. There are now alternative methods to achieve this, such as using key
:
if ((e.key >= 48 && e.key <= 57) || (e.key >= 96 && e.key <= 105)) {
// 0-9 only
}
Here's an output tester for event.key, thanks to @Danziger for the link.
The example Java data structure in the original question does not match the description of the JSON structure in the comment.
The JSON is described as
"an array of {object with an array of {object}}".
In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is
"an array of {TypeDTO object with an array of {ItemDTO object}}".
But the Java data structure provided in the question is not this. Instead it's
"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".
A two-dimensional array != a single-dimensional array.
This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false},
{"id":4,"name":"name4","valid":true}
]
},
{
"id":5,
"name":"name5",
"items":
[
{"id":6,"name":"name6","valid":true},
{"id":7,"name":"name7","valid":false}
]
},
{
"id":8,
"name":"name8",
"items":
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items;
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false}
],
[
{"id":4,"name":"name4","valid":true}
]
]
},
{
"id":5,
"name":"name5",
"items":
[
[
{"id":6,"name":"name6","valid":true}
],
[
{"id":7,"name":"name7","valid":false}
]
]
},
{
"id":8,
"name":"name8",
"items":
[
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false}
],
[
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items[];
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
Regarding the remaining two questions:
is Gson extremely fast?
Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.
That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.
Or am I better to stick with what I've got working already?
I wouldn't. I would most always rather have one simple line of code like
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
Yes, it's important to memorize your calculated return value from each recursion method call, so that you can display the series in calling method.
There are some refinement in the implementation provided. Please find below implementation which gives us more correct and versatile output:
import java.util.HashMap;
import java.util.stream.Collectors;
public class Fibonacci {
private static HashMap<Long, Long> map;
public static void main(String[] args) {
long n = 50;
map = new HashMap<>();
findFibonacciValue(n);
System.out.println(map.values().stream().collect(Collectors.toList()));
}
public static long findFibonacciValue(long number) {
if (number <= 1) {
if (number == 0) {
map.put(number, 0L);
return 0L;
}
map.put(number, 1L);
return 1L;
} else if (map.containsKey(number)) {
return map.get(number);
} else {
long fibonacciValue = findFibonacciValue(number - 1L) + findFibonacciValue(number - 2L);
map.put(number, fibonacciValue);
return fibonacciValue;
}
}
}
Output for number 50 is:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025]
localStorage.clear();
or
window.localStorage.clear();
to clear particular item
window.localStorage.removeItem("item_name");
To remove particular value by id :
var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];
$.each(item_detail, function(index, obj){
if (key_id == data('key')) {
item_detail.splice(index,1);
localStorage["key_name"] = JSON.stringify(item_detail);
return false;
}
});
So there's loads of posts on the web that show how to do this, I've found 3 ways, same as pointed out by Johan & Sjoerd. I couldn't get any of these queries to work, well obviously they work fine it's my database that's not working correctly and those queries all ran slow.
So I worked out another way that someone else may find useful:
The basic jist of it is to create a temporary table and fill it with all the information, then remove all the rows that ARE in the other table.
So I did these 3 queries, and it ran quickly (in a couple moments).
CREATE TEMPORARY TABLE
`database1`.`newRows`
SELECT
`t1`.`id` AS `columnID`
FROM
`database2`.`table` AS `t1`
.
CREATE INDEX `columnID` ON `database1`.`newRows`(`columnID`)
.
DELETE FROM `database1`.`newRows`
WHERE
EXISTS(
SELECT `columnID` FROM `database1`.`product_details` WHERE `columnID`=`database1`.`newRows`.`columnID`
)
gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT HON env variable.
This means the Python env. variable should point to the executable python file, in my case:
SET PYTHON=C:\work\_env\Python27\python.exe
You can't do that. It's not possible to resize an array. You have to create a new array and copy the data to it:
bArray = addByteToArray(bArray, newByte);
code:
public byte[] addByteToArray(byte[] bArray, byte newByte)
{
byte[] newArray = new byte[bArray.Length + 1];
bArray.CopyTo(newArray, 1);
newArray[0] = newByte;
return newArray;
}
When initializing your repository, skip the git command that contains
-u
and it shouldn't be an issue.
If the column happens to be a 'status' type column, and your model lends itself to the use of state machines, consider using the aasm gem, after which you can simply do
aasm column: "status" do
state :available, initial: true
state :used
# transitions
end
It still doesn't initialize the value for unsaved records, but it's a bit cleaner than rolling your own with init
or whatever, and you reap the other benefits of aasm such as scopes for all your statuses.
It's not too late for the newcomers.
plt.axvline(x, color='r')
It takes the range of y as well, using ymin and ymax.
REST is just a software architecture style for exposing resources.
A typical REST call to return information about customer 34456 could look like:
http://example.com/customer/34456
Have a look at the IBM tutorial for REST web services
JOptionPane.showOptionDialog
JOptionPane.showMessageDialog
....
Have a look on this tutorial on how to make dialogs.
You need to create an event source and a message file for it. Code looks something like this:
var data = new EventSourceCreationData("yourApp", "Application");
data.MessageResourceFile = pathToYourMessageFile;
EventLog.CreateEventSource(data);
Then you will need to create a message file. There is also this article that explains things (I did not read it all but it seems fairly complete).
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
Taken from http://docs.python.org/reference/expressions.html
Example 1:
6%2
evaluates to 0
because there's no remainder if 6 is divided by 2 ( 3 times ).
Example 2: 7%2
evaluates to 1
because there's a remainder of 1
when 7 is divided by 2 ( 3 times ).
So to summarise that, it returns the remainder of a division operation, or 0
if there is no remainder. So 6%2
means find the remainder of 6 divided by 2.
This is working fine for me :
public class MethodInvokerClass {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, ClassNotFoundException, InvocationTargetException, InstantiationException {
Class c = Class.forName(MethodInvokerClass.class.getName());
Object o = c.newInstance();
Class[] paramTypes = new Class[1];
paramTypes[0]=String.class;
String methodName = "countWord";
Method m = c.getDeclaredMethod(methodName, paramTypes);
m.invoke(o, "testparam");
}
public void countWord(String input){
System.out.println("My input "+input);
}
}
Output:
My input testparam
I am able to invoke the method by passing its name to another method (like main).
As per the documentation on the return
statement, return
may only occur syntactically nested in a function definition. The same is true for yield
.
you can try
$(function()
{
$(window).bind('load', function()
{
// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...
});
});
i had the same problem and this code worked for me. how it works for you too!
Try this code. By using the parent>child selector "#productList li" it should find all li elements. Then, you can iterate through the result object using the each() method which will only alter li elements that have been found.
listItems = $("#productList li").each(function(){
var product = $(this);
var productid = product.children(".productId").val();
var productPrice = product.find(".productPrice").val();
var productMSRP = product.find(".productMSRP").val();
totalItemsHidden.val(parseInt(totalItemsHidden.val(), 10) + 1);
subtotalHidden.val(parseFloat(subtotalHidden.val()) + parseFloat(productMSRP));
savingsHidden.val(parseFloat(savingsHidden.val()) + parseFloat(productMSRP - productPrice));
totalHidden.val(parseFloat(totalHidden.val()) + parseFloat(productPrice));
});
// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
throw new IOException("File is too large!");
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
InputStream is = new FileInputStream(file);
try {
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
} finally {
is.close();
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
return bytes;
}
(I tried previous answers but they lacks in some points. For example if you don't do a return;
after finishing activity, remaining activity code runs. Also you need to edit onCreate with return. If you doesn't run super.onCreate() you will get a runtime error)
Say you have MainActivity
and ChildActivity
.
Inside ChildActivity add this:
Intent intent = new Intent(ChildActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
return true;
Inside MainActivity's onCreate add this:
@Override
public void onCreate(Bundle savedInstanceState) {
mContext = getApplicationContext();
super.onCreate(savedInstanceState);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
return;
}
// your current codes
// your current codes
}
I was stuck at "Authenticating with the iTunes Store" today. I had used the same version and build number as a previous submission. After I updated the build number, the upload went fine. I don't know if it's related, or if it was a coincidence.
All you need on the iframe is:
...wmode="opaque"></iframe>
and in the URL:
http://www.youtube.com/embed/123?wmode=transparent
I am going to assume this is a WinForms questions (which it feels like, based on it being a "program" rather than a website/app). In which case you can simple do the following to change the text colour of a label:
myLabel.ForeColor = System.Drawing.Color.Red;
Or any other colour of your choice. If you want to be more specific you can use an RGB value like so:
myLabel.ForeColor = Color.FromArgb(0, 0, 0);//(R, G, B) (0, 0, 0 = black)
Having different colours for different users can be done a number of ways. For example, you could allow each user to specify their own RGB value colours, store these somewhere and then load them when the user "connects".
An alternative method could be to just use 2 colours - 1 for the current user (running the app) and another colour for everyone else. This would help the user quickly identify their own messages above others.
A third approach could be to generate the colour randomly - however you will likely get conflicting values that do not show well against your background, so I would suggest not taking this approach. You could have a pre-defined list of "acceptable" colours and just pop one from that list for each user that joins.
First things first, i'd not like that as a user.
The best way to do is probably using a small flash applet that plays your sound in the background.
Also answered here: Cross-platform, cross-browser way to play sound from Javascript?
You might like the function GetInfoFromClosedFile()
Edit: Since the above link does not seem to work anymore, I am adding alternate link 1 and alternate link 2 + code:
Private Function GetInfoFromClosedFile(ByVal wbPath As String, _
wbName As String, wsName As String, cellRef As String) As Variant
Dim arg As String
GetInfoFromClosedFile = ""
If Right(wbPath, 1) <> "" Then wbPath = wbPath & ""
If Dir(wbPath & "" & wbName) = "" Then Exit Function
arg = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)
On Error Resume Next
GetInfoFromClosedFile = ExecuteExcel4Macro(arg)
End Function
This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.
To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell
2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.
Import-Module MSOnline
After it complete, we can use this command to check it.
PS C:\Users> Get-Module -ListAvailable -Name MSOnline*
Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 1.1.166.0 MSOnline {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest 1.1.166.0 MSOnlineExtended {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
More information about this issue, please refer to it.
Update:
We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.
Change it to a table-valued function
Please refer to the following link, for example.
You can always find out the location of the tnsnames.ora file being used by running TNSPING to check connectivity (9i or later):
C:\>tnsping dev
TNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 08-JAN-2009 12:48:38
Copyright (c) 1997, 2005, Oracle. All rights reserved.
Used parameter files:
C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = XXX)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = DEV)))
OK (30 msec)
C:\>
Sometimes, the problem is with the entry you made in tnsnames.ora, not that the system can't find it. That said, I agree that having a tns_admin environment variable set is a Good Thing, since it avoids the inevitable issues that arise with determining exactly which tnsnames file is being used in systems with multiple oracle homes.
Some frameworks are using this header to detect xhr requests e.g. grails spring security is using this header to identify xhr request and give either a json response or html response as response.
Most Ajax libraries (Prototype, JQuery, and Dojo as of v2.1) include an X-Requested-With header that indicates that the request was made by XMLHttpRequest instead of being triggered by clicking a regular hyperlink or form submit button.
Source: http://grails-plugins.github.io/grails-spring-security-core/guide/helperClasses.html
It was RAM problem for me.
I was having the same problem even on a server with 12 CPU cores and 32 GB RAM. I researched more and tried to free up RAM. Here is the command I used on Ubuntu 14.04 to free up RAM:
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
And, it fixed everything. I have set it under cron to run every hour.
crontab -e
0 * * * * bash /root/ram.sh;
And, you can use this command to check how much free RAM available:
free -h
And, you will get something like this:
total used free shared buffers cached
Mem: 31G 12G 18G 59M 1.9G 973M
-/+ buffers/cache: 9.9G 21G
Swap: 8.0G 368M 7.6G
The getimagesize() should be the most definite way of working out whether the file is an image:
if(@is_array(getimagesize($mediapath))){
$image = true;
} else {
$image = false;
}
because this is a sample getimagesize() output:
Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)
npm install
npm run start
if this didn't work, try to install the nodejs and run repair
or clean npm cache npm cache clean --force
Edit the system environmental variable
Environment Variables...
Path
variable nameEdit..
C:\Program Files\nodejs
on the list, if not add thisJust like the others said before the way to do this is to press ctrl+w and then o. This will "maximize" the current window, while closing the others. If you'd like to be able to "unmaximize" it, there's a plugin called ZoomWin for that. Otherwise you'd have to recreate the window setup from scratch.
Eric Baker's comment tipped me off to the core idea that in order for a view to have its size be determined by the content placed within it, then the content placed within it must have an explicit relationship with the containing view in order to drive its height (or width) dynamically. "Add subview" does not create this relationship as you might assume. You have to choose which subview is going to drive the height and/or width of the container... most commonly whatever UI element you have placed in the lower right hand corner of your overall UI. Here's some code and inline comments to illustrate the point.
Note, this may be of particular value to those working with scroll views since it's common to design around a single content view that determines its size (and communicates this to the scroll view) dynamically based on whatever you put in it. Good luck, hope this helps somebody out there.
//
// ViewController.m
// AutoLayoutDynamicVerticalContainerHeight
//
#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end
@implementation ViewController
- (void)viewDidLoad
{
// INVOKE SUPER
[super viewDidLoad];
// INIT ALL REQUIRED UI ELEMENTS
self.contentView = [[UIView alloc] init];
self.myLabel = [[UILabel alloc] init];
self.myOtherLabel = [[UILabel alloc] init];
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);
// TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;
// ESTABLISH VIEW HIERARCHY
[self.view addSubview:self.contentView]; // View adds content view
[self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
[self.contentView addSubview:self.myOtherLabel];
// LAYOUT
// Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
// Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet
/* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
// ^To me this is what's weird... but okay once you understand...
// Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
// Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
// Note, this is the view that we are choosing to use to drive the height (and width) of our container...
// The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];
// Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];
// COLOR VIEWS
self.view.backgroundColor = [UIColor purpleColor];
self.contentView.backgroundColor = [UIColor redColor];
self.myLabel.backgroundColor = [UIColor orangeColor];
self.myOtherLabel.backgroundColor = [UIColor greenColor];
// CONFIGURE VIEWS
// Configure MY LABEL
self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
self.myLabel.numberOfLines = 0; // Let it flow
// Configure MY OTHER LABEL
self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
self.myOtherLabel.numberOfLines = 0;
self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}
@end
CodePen Working Example
For more GitHub repo
<!DOCTYPE html>
<html>
<head>
<title>Count Up Numbers Example</title>
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<style type="text/css">
/*
Courtesy: abcc.com
https://abcc.com/en
https://abcc.com/en/at-mining
*/
.rewards {
background-color: #160922;
}
.th-num-bold {
font-family: "Arial" ;
}
.ff-arial {
font-family: "Arial" ;
}
.scroll-wrap .scroll-exchange-fee .exchange_time {
color: hsla(0,0%,100%,.7);
font-size: 13px;
}
.f14 {
font-size: 14px;
}
.flex {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
.jcsb {
-ms-flex-pack: justify!important;
-webkit-box-pack: justify!important;
justify-content: space-between!important;
}
.aic {
-ms-flex-align: center!important;
-webkit-box-align: center!important;
align-items: center!important;
}
li {
list-style: none;
}
.pull-left {
float: left!important;
}
.rewards-wrap {
height: 100%;
}
.at-equity-wrap .rewards .calculate_container {
-webkit-box-shadow: rgba(0,0,0,.03) 0 5px 10px 0;
background: url(https://s.abcc.com/portal/static/img/home-bg-pc.c9207cd.png);
background-repeat: no-repeat;
background-size: 1440px 100%;
box-shadow: 0 5px 10px 0 rgba(0,0,0,.03);
margin: 0 auto;
max-width: 1200px;
overflow: hidden;
position: relative;
}
.rewards-pc-wrap .current-profit .point {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .current-profit .integer {
color: #fff;
font-size: 45px;
}
.rewards-pc-wrap .current-profit .decimal {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .current-profit .unit {
color: #fff;
font-size: 24px;
margin-right: 5px;
margin-top: 18px;
}
.rewards-pc-wrap .yesterday-profit .point {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .yesterday-profit .integer {
color: #fff;
font-size: 45px;
}
.rewards-pc-wrap .yesterday-profit .decimal {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .yesterday-profit .unit {
color: #fff;
font-size: 24px;
margin-right: 5px;
margin-top: 18px;
}
.rewards-pc-wrap .profit-rate-100 .point {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .profit-rate-100 .integer {
color: #fff;
font-size: 45px;
}
.rewards-pc-wrap .profit-rate-100 .decimal {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .profit-rate-100 .unit {
color: #fff;
font-size: 24px;
margin-right: 5px;
margin-top: 18px;
}
.rewards-pc-wrap .total-profit .point {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .total-profit .integer {
color: #fff;
font-size: 45px;
}
.rewards-pc-wrap .total-profit .decimal {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .total-profit .unit {
color: #fff;
font-size: 24px;
margin-right: 5px;
margin-top: 18px;
}
.rewards-pc-wrap {
height: 400px;
margin-left: 129px;
padding-top: 100px;
width: 630px;
}
.itm-rv {
-ms-flex: 1;
-webkit-box-flex: 1;
flex: 1;
font-family: "Arial";
}
.fb {
font-weight: 700;
}
.main-p {
color: hsla(0,0%,100%,.7);
font-size: 13px;
margin-bottom: 8px;
margin-top: 10px;
}
.sub-p {
color: hsla(0,0%,100%,.5);
font-size: 12px;
margin-top: 12px;
}
.fb-r {
font-weight: 300;
}
.price-btc {
color: hsla(0,0%,100%,.5);
font-size: 13px;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="at-equity-wrap">
<div class="rewards" >
<div class="calculate_container">
<div class="rewards-wrap">
<div class="flex jcc aic">
<div class="rewards-pc-wrap slideInUp" id="nuBlock">
<div class="flex jcsb aic">
<div class="itm-rv" style="margin-right: 60px;">
<div class="current-profit th-num-bold fb"><span class="unit pull-left">$</span> <span class="integer" id="cr_prft_int" >0</span> <span class="point">.</span> <span class="decimal" id="cr_prft_dcml" >00</span></div>
<p class="main-p">Platform Rewards to Be Distributed Today</p>
<p class="sub-p fb-r">Total circulating KAT eligible for rewards:100,000,000</p>
</div>
<div class="itm-rv">
<div class="profit-rate-100 th-num-bold"><span class="unit pull-left">$</span> <span class="integer" id="dly_prft_int" >0</span> <span class="point">.</span><span class="decimal" id="dly_prft_dcml" >00</span></div>
<p class="main-p">Daily Rewards of 1000 KAT</p>
<div class="profit-rate sub-p fb-r"><span >Daily KAT Rewards Rate</span> <span class="integer">0</span> <span class="decimal">.00</span> <span class="unit">%</span></div>
</div>
</div>
<div class="flex jcsb aic" style="margin-top: 40px;">
<div class="itm-rv" style="margin-right: 60px;">
<div class="yesterday-profit th-num-bold fb'"><span class="unit pull-left">$</span> <span class="integer" id="ytd_prft_int" >0</span> <span class="point">.</span><span class="decimal" id="ytd_prft_dcml" >00</span></div>
<div class="price-btc fb-r">/ 0.00000000 BTC</div>
<p class="main-p fb-r">Platform Rewards Distributed Yesterday</p>
</div>
<div class="itm-rv">
<div class="total-profit th-num-bold fb'"><span class="unit pull-left">$</span> <span class="integer" id="ttl_prft_int" >0</span> <span class="point">.</span><span class="decimal" id="ttl_prft_dcml" >00</span></div>
<div class="price-btc fb-r">/ 0.00000000 BTC</div>
<p class="main-p fb-r">Cumulative Platform Rewards Distributed</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$(document).on('ready', function(){
setTimeout(function(){
cr_countUp();
dly_countUp();
ytd_countUp();
ttl_countUp();
}, 2000);
});
unit = "$";
var cr_data, dly_data, ytd_data, ttl_data;
cr_data = dly_data = ytd_data = ttl_data = ["670.0000682", "670.002", "660.000068", "660.002", "650.000000063", "650.01", "640.00000006", "640.01", "630.0000000602", "630.01", "620.0000000622", "620.01", "610.00000016", "610.002", "600.00000015998", "600.002", "590.00000094", "590.002", "580.0000009", "580.002", "760.0000682", "760.002", "660.000068", "660.002", "560.000000063", "560.01", "460.00000006", "460.01", "360.0000000602", "360.01", "260.0000000622", "260.01", "160.00000016", "160.002", "060.00000015998", "060.002", "950.00000094", "950.002", "850.0000009", "850.002"];
cr_start = 0;
cr_stop = cr_data.length - 1;
cr_nu = 20;
function cr_countUp(){
setTimeout(function(){
$("#cr_prft_int").text(cr_data[cr_start].split(".")[0]);
$("#cr_prft_dcml").text(cr_data[cr_start].split(".")[1]);
if(cr_start < cr_stop){
cr_start += 1;
cr_countUp();
}
}, cr_nu);
}
dly_start = 0;
dly_stop = dly_data.length - 1;
dly_nu = 20;
function dly_countUp(){
setTimeout(function(){
$("#dly_prft_int").text(dly_data[dly_start].split(".")[0]);
$("#dly_prft_dcml").text(dly_data[dly_start].split(".")[1]);
if(dly_start < dly_stop){
dly_start += 1;
dly_countUp();
}
}, dly_nu);
}
ytd_start = 0;
ytd_stop = ytd_data.length - 1;
ytd_nu = 20;
function ytd_countUp(){
setTimeout(function(){
$("#ytd_prft_int").text(ytd_data[ytd_start].split(".")[0]);
$("#ytd_prft_dcml").text(ytd_data[ytd_start].split(".")[1]);
if(ytd_start < ytd_stop){
ytd_start += 1;
ytd_countUp();
}
}, ytd_nu);
}
ttl_start = 0;
ttl_stop = ttl_data.length - 1;
ttl_nu = 20;
function ttl_countUp(){
setTimeout(function(){
$("#ttl_prft_int").text(ttl_data[ttl_start].split(".")[0]);
$("#ttl_prft_dcml").text(ttl_data[ttl_start].split(".")[1]);
if(ttl_start < ttl_stop){
ttl_start += 1;
ttl_countUp();
}
}, ttl_nu);
}
</script>
</html>
In Celery 3+:
CLI:
$ celery -A proj purge
Programatically:
>>> from proj.celery import app
>>> app.control.purge()
http://docs.celeryproject.org/en/latest/faq.html#how-do-i-purge-all-waiting-tasks
Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =
here's angular 5 method version of this with unminified syntax for those who struggling with that y
, z
, tt
in accepted answer. usage: parseXlsx().subscribe((data)=> {...})
parseXlsx() {
let self = this;
return Observable.create(observer => {
this.http.get('./assets/input.xlsx', { responseType: 'arraybuffer' }).subscribe((data: ArrayBuffer) => {
const XLSX = require('xlsx');
let file = new Uint8Array(data);
let workbook = XLSX.read(file, { type: 'array' });
let sheetNamesList = workbook.SheetNames;
let allLists = {};
sheetNamesList.forEach(function (sheetName) {
let worksheet = workbook.Sheets[sheetName];
let currentWorksheetHeaders: object = {};
let data: Array<any> = [];
for (let cellName in worksheet) {//cellNames example: !ref,!margins,A1,B1,C1
//skipping serviceCells !margins,!ref
if (cellName[0] === '!') {
continue
};
//parse colName, rowNumber, and getting cellValue
let numberPosition = self.getCellNumberPosition(cellName);
let colName = cellName.substring(0, numberPosition);
let rowNumber = parseInt(cellName.substring(numberPosition));
let cellValue = worksheet[cellName].w;// .w is XLSX property of parsed worksheet
//treating '-' cells as empty on Spot Indices worksheet
if (cellValue.trim() == "-") {
continue;
}
//storing header column names
if (rowNumber == 1 && cellValue) {
currentWorksheetHeaders[colName] = typeof (cellValue) == "string" ? cellValue.toCamelCase() : cellValue;
continue;
}
//creating empty object placeholder to store current row
if (!data[rowNumber]) {
data[rowNumber] = {}
};
//if header is date - for spot indices headers are dates
data[rowNumber][currentWorksheetHeaders[colName]] = cellValue;
}
//dropping first two empty rows
data.shift();
data.shift();
allLists[sheetName.toCamelCase()] = data;
});
this.parsed = allLists;
observer.next(allLists);
observer.complete();
})
});
}
To be slightly more specific, you would use this to do
SELECT 1 FROM MyUserTable WHERE user_id = 33487
instead of doing
SELECT * FROM MyUserTable WHERE user_id = 33487
because you don't care about looking at the results. Asking for the number 1 is very easy for the database (since it doesn't have to do any look-ups).
This thread seems to be talking about the same issue - it sounds like this error is usually caused by having some data sent out of the server before the namespace statement is encountered.
On the other hand, it could also be a bug in ImageUploader... the main PHP file puts the namespace after the class definition, which I haven't seen in the PHP documentation, which says it should be the very first PHP code. From this page:
Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.
There's no declare keyword here, so perhaps this is a bug in the source code that slips by the developer's version of PHP, because he doesn't put the namespace first:
<?php
class BulletProofException extends Exception{}
namespace BulletProof;
/**
* BulletProof ImageUploder:
...
I'm using Scala and I've got this message where I've mistakenly shared a Mock between two Object
s. So, be sure that your tests are independent of each other. The parallel test execution obviously creates some flaky situations since the objects in Scala are singleton compositions.
In some cases _hostingEnvironment.ContentRootPath
and System.IO.Directory.GetCurrentDirectory()
targets to source directory. Here is bug about it.
The solution proposed there helped me
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Before MySQL 5.7.6 this works from the command line:
mysql -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('$w0rdf1sh');"
I don't have a mysql install to test on but I think in your case it would be
mysql -e "UPDATE mysql.user SET Password=PASSWORD('$w0rdf1sh') WHERE User='tate256';"
I am now using Google Apps (for Email) and Heroku as web server. I am using Google Apps 301 Permanent Redirect feature to redirect the naked domain to WWW.your_domain.com
You can find the step-by-step instructions here https://stackoverflow.com/a/20115583/1440255
The Swift 2 version:
// start detecting pan gesture
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(TTAltimeterDetailViewController.panGestureDetected(_:)))
panGestureRecognizer.minimumNumberOfTouches = 1
self.chartOverlayView.addGestureRecognizer(panGestureRecognizer)
func panGestureDetected(panGestureRecognizer: UIPanGestureRecognizer) {
print("pan gesture recognized")
}
The .Cells range isn't limited to ones that are being used, so your code is clearing the content of 1,048,576 rows and 16,384 columns - 17,179,869,184 total cells. That's going to take a while. Just clear the UsedRange instead:
Sheets("Zeros").UsedRange.ClearContents
Alternately, you can delete the sheet and re-add it:
Application.DisplayAlerts = False
Sheets("Zeros").Delete
Application.DisplayAlerts = True
Dim sheet As Worksheet
Set sheet = Sheets.Add
sheet.Name = "Zeros"
<div class="foo">Foo Bar</div>
and in your CSS file:
.foo {
background-image: url("images/foo.png");
}
Try the SetField method:
table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);
This should get the job done and is a bit "cleaner" than using Rows[i][j].
{
"success": true,
"data": {
"BLR": {
"origin": "JAI",
"destination": "BLR",
"price": 127,
"transfers": 0,
"airline": "LB",
"flight_number": 655,
"departure_at": "2017-06-03T18:20:00Z",
"return_at": "2017-06-07T08:30:00Z",
"expires_at": "2017-03-05T08:40:31Z"
}
}
};
Merging typed data structure trees is not trivial, you need to define the precedence, handle incompatible types, define how they will be casted and merged...
So in my opinion, you won't avoid
... pulling them all apart and individually adding in by puts`.
If your question is: Has someone done it for me yet?
Then I think you can have a look at this YAML merging library/tool I revived. (YAML is a superset of JSON), and the principles are applicable to both.
(However, this particular code returns YAML objects, not JSON. Feel free to extend the project and send a PR.)
You can increase the performance of excel export by following these steps:
1) When you fetch data from database, avoid casting the result set to the list of entity classes. Instead assign it directly to List
List<Object[]> resultList =session.createSQLQuery("SELECT t1.employee_name, t1.employee_id ... from t_employee t1 ").list();
instead of
List<Employee> employeeList =session.createSQLQuery("SELECT t1.employee_name, t1.employee_id ... from t_employee t1 ").list();
2) Create excel workbook object using SXSSFWorkbook instead of XSSFWorkbook and create new row using SXSSFRow when the data is not empty.
3) Use java.util.Iterator to iterate the data list.
Iterator itr = resultList.iterator();
4) Write data into excel using column++.
int rowCount = 0;
int column = 0;
while(itr.hasNext()){
SXSSFRow row = xssfSheet.createRow(rowCount++);
Object[] object = (Object[]) itr.next();
//column 1
row.setCellValue(object[column++]); // write logic to create cell with required style in setCellValue method
//column 2
row.setCellValue(object[column++]);
itr.remove();
}
5) While iterating the list, write the data into excel sheet and remove the row from list using remove method. This is to avoid holding unwanted data from the list and clear the java heap size.
itr.remove();
what about simply constructing your frame from a standard list ?
frame = bytes([0xA2,0x01,0x02,0x03,0x04])
the bytes()
constructor can build a byte frame from an iterable containing int
values. an iterable is anything which implements the iterator protocol: an list, an iterator, an iterable object like what is returned by range()
...
What worked for me - should really be moved to iPhone:
Charles
Mac
iPhone
Voila, you can now view encrypted traffic from the domain added in the SSL proxying
I have an old project that tests two different implementations of a Dictionary interface. One is an unsorted ArrayList and the other is a HashTable. The two implementations are timed, so that a comparison can be made. You can choose which data structure from the command line args. Now.. I have another data structure which is a tree structure. I want to test the time of it, in order to compare it to the HashTable. So.. In the new dataStructure project, I need to implement the Dictionary interface. In the Dictionary project, I need to be able to add code specific to my new dataStructure project. There is a circular dependency. This means that when Eclipse goes to find out which projects are dependent on project A, then it finds project B. When it needs to find out the sub-dependencies of the dependent projects, it finds A, which is again, dependent on B. There is no tree, rather a graph with a cycle.
When you go to configure your build path, instead of entering dependent projects ('projects' tab), go to the Libraries tab. Click the 'Add Class Folder...' button (assuming that your referenced projects are in your workspace), and select the class folder. Mine is \target. Select this as a library folder. Do this in project A, to reference project B. Do this in project B to reference project A. Make sure that you don't reference \target\projectNameFolder or you won't have a matching import. Now you won't have to remove a dependency and then reset it, in order to force a rebuild.
Use class libraries instead of project references.
I hope I understand your question correctly: assuming that the values are of type String
, the most efficient way is probably to convert to a HashSet
and iterate over it:
ArrayList<String> values = ... //Your values
HashSet<String> uniqueValues = new HashSet<>(values);
for (String value : uniqueValues) {
... //Do something
}
Honestly, this is the sort of situation where I just open up Python on the command line and start messing around:
>>> x = "Dana Larose is playing with find()"
>>> x.find("Dana")
0
>>> x.find("ana")
1
>>> x.find("La")
5
>>> x.find("La", 6)
-1
Python's interpreter makes this sort of experimentation easy. (Same goes for other languages with a similar interpreter)
Assuming you did the normal installation with virtual box, vagrant etc.. This can happen to new people. PHP can be installed on your PC but all the modules PHP for your laravel project is on your VM So to access your VM, go to your homestead folder and type: vagrant ssh
then to go your project path and execute the php artisan migrate.
jQuery Solution!
Demo: http://jsfiddle.net/69wP6/2/
Another Demo Below(updated!)
I needed something similar in a case when i had some fixed Options and i wanted one other option to be editable! In this case i made a hidden input that would overlap the select option and would be editable and used jQuery to make it all work seamlessly.
I am sharing the fiddle with all of you!
HTML
<div id="billdesc">
<select id="test">
<option class="non" value="option1">Option1</option>
<option class="non" value="option2">Option2</option>
<option class="editable" value="other">Other</option>
</select>
<input class="editOption" style="display:none;"></input>
</div>
CSS
body{
background: blue;
}
#billdesc{
padding-top: 50px;
}
#test{
width: 100%;
height: 30px;
}
option {
height: 30px;
line-height: 30px;
}
.editOption{
width: 90%;
height: 24px;
position: relative;
top: -30px
}
jQuery
var initialText = $('.editable').val();
$('.editOption').val(initialText);
$('#test').change(function(){
var selected = $('option:selected', this).attr('class');
var optionText = $('.editable').text();
if(selected == "editable"){
$('.editOption').show();
$('.editOption').keyup(function(){
var editText = $('.editOption').val();
$('.editable').val(editText);
$('.editable').html(editText);
});
}else{
$('.editOption').hide();
}
});
Edit : Added some simple touches design wise, so people can clearly see where the input ends!
JS Fiddle : http://jsfiddle.net/69wP6/4/
On Arch Linux run the following:
sudo pacman -S base-devel
I believe the correct answer is actually a combination of both approaches: viewWIllTransition(toSize:)
and NotificationCenter
's UIDeviceOrientationDidChange
.
viewWillTransition(toSize:)
notifies you before the transition.
NotificationCenter
UIDeviceOrientationDidChange
notifies you after.
You have to be very careful. For example, in UISplitViewController
when the device rotates into certain orientations, the DetailViewController
gets popped off the UISplitViewController
's viewcontrollers
array, and pushed onto the master's UINavigationController
. If you go searching for the detail view controller before the rotation has finished, it may not exist and crash.
I forgot to return self in an init-Method... ;)
Cygwin + sftp/scp natrually
There is a Visual Studio Code issue you can track and thumbs up for this feature. There was also a User Voice issue, but I believe they moved voting to GitHub issues.
It seems they want auto import functionality in TypeScript, so it can be reused. TypeScript auto import issue to track and thumbs up here.
Here is one way to calculate log return using .shift()
. And the result is similar to but not the same as the gross return calculated by pct_change()
. Can you upload a copy of your sample data (dropbox share link) to reproduce the inconsistency you saw?
import pandas as pd
import numpy as np
np.random.seed(0)
df = pd.DataFrame(100 + np.random.randn(100).cumsum(), columns=['price'])
df['pct_change'] = df.price.pct_change()
df['log_ret'] = np.log(df.price) - np.log(df.price.shift(1))
Out[56]:
price pct_change log_ret
0 101.7641 NaN NaN
1 102.1642 0.0039 0.0039
2 103.1429 0.0096 0.0095
3 105.3838 0.0217 0.0215
4 107.2514 0.0177 0.0176
5 106.2741 -0.0091 -0.0092
6 107.2242 0.0089 0.0089
7 107.0729 -0.0014 -0.0014
.. ... ... ...
92 101.6160 0.0021 0.0021
93 102.5926 0.0096 0.0096
94 102.9490 0.0035 0.0035
95 103.6555 0.0069 0.0068
96 103.6660 0.0001 0.0001
97 105.4519 0.0172 0.0171
98 105.5788 0.0012 0.0012
99 105.9808 0.0038 0.0038
[100 rows x 3 columns]
You could use wmic command:
wmic logicaldisk where drivetype=2 get <DeviceID, VolumeName, Description, ...>
Drivetype 2 indicates that its a removable disk.
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
real deal is:
docker volume create xdata
docker volume inspect xdata
so you see its mount poit dir.
just copy your stuff there
then
docker run --name=example1 --mount source=xdata,destination=/xdata -it yessa bash
where yessa
is image name
You can use templates.
template <typename T> const char* typeof(T&) { return "unknown"; } // default
template<> const char* typeof(int&) { return "int"; }
template<> const char* typeof(float&) { return "float"; }
In the example above, when the type is not matched it will print "unknown".
Swift 4
extension String {
func SizeOf(_ font: UIFont) -> CGSize {
return self.size(withAttributes: [NSAttributedStringKey.font: font])
}
}
I use this trick:
.pvw-title {
text-indent: -999px;
}
.pvw-title:after {
text-indent: 0px;
float: left;
content: 'My New Content';
}
I've even used this to handle internationalization of pages by just changing a base class...
.translate-es .welcome {
text-indent: -999px;
}
.translate-es .welcome:after {
text-indent: 0px;
float: left;
content: '¡Bienvenidos!';
}
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.
To affect all flex-items of the container, choose this:
You have to set align-items: flex-start;
to div
and all flex-items of this container get the height of their content.
div {_x000D_
align-items: flex-start;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}
_x000D_
<div>_x000D_
<span>This is some text.</span>_x000D_
</div>
_x000D_
To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start;
to this flex-item. All other flex-items of the container aren't affected.
div {_x000D_
display: flex;_x000D_
height: 200px;_x000D_
background: tan;_x000D_
}_x000D_
span.only {_x000D_
background: red;_x000D_
align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
background:green;_x000D_
}
_x000D_
<div>_x000D_
<span class="only">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
Why is this happening to the span
?
The default value of the property align-items
is stretch
. This is the reason why the span
fill the height of the div
.
Difference between baseline
and flex-start
?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start
the flex-item will be set to the top of the container (without space).
div {_x000D_
align-items: baseline;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
<span class="fontsize">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
You can find more information about the difference between
baseline
andflex-start
here:
What's the difference between flex-start and baseline?
To fix this error on Centos 7:
Install PHP extension:
sudo yum install php-xml
Restart your web server. In my case it's php-fpm:
services php-fpm restart
run:
npm install -g [email protected]
- or whatever version you want after the @ symbol (This works as of 2019)
Change in IIS Settings application pool advanced settings.Enable 32 bit application
To filter an array irrespective of the property type (i.e. for all property types), we can create a custom filter pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: "filter" })
export class ManualFilterPipe implements PipeTransform {
transform(itemList: any, searchKeyword: string) {
if (!itemList)
return [];
if (!searchKeyword)
return itemList;
let filteredList = [];
if (itemList.length > 0) {
searchKeyword = searchKeyword.toLowerCase();
itemList.forEach(item => {
//Object.values(item) => gives the list of all the property values of the 'item' object
let propValueList = Object.values(item);
for(let i=0;i<propValueList.length;i++)
{
if (propValueList[i]) {
if (propValueList[i].toString().toLowerCase().indexOf(searchKeyword) > -1)
{
filteredList.push(item);
break;
}
}
}
});
}
return filteredList;
}
}
//Usage
//<tr *ngFor="let company of companyList | filter: searchKeyword"></tr>
Don't forget to import the pipe in the app module
We might need to customize the logic to filer with dates.
If you need one single regex, try:
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)
A short explanation:
(?=.*[a-z]) // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z]) // use positive look ahead to see if at least one upper case letter exists
(?=.*\d) // use positive look ahead to see if at least one digit exists
(?=.*\W]) // use positive look ahead to see if at least one non-word character exists
And I agree with SilentGhost, \W
might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?]
(feel free to add more of course!)
I found this implementation very easy to use. Also has a generous BSD-style license:
jsSHA: https://github.com/Caligatio/jsSHA
I needed a quick way to get the hex-string representation of a SHA-256 hash. It only took 3 lines:
var sha256 = new jsSHA('SHA-256', 'TEXT');
sha256.update(some_string_variable_to_hash);
var hash = sha256.getHash("HEX");
You can set up a cloudfront distribution that has www.google-analytics.com as its origin server and set a longer expiry header in the cloudfront distribution settings. Then modify that domain in the Google snippet. This prevents the load on your own server and the need to keep updating the file in a cron job.
This is setup & forget. So you may want to add a billing alert to cloudfront in case someone "copies" your snippet and steals your bandwidth ;-)
Edit: I tried it and it's not that easy, Cloudfront passes through the Cache-Control header with no easy way to remove it
You don't need to convert to Calendar
for this, you can just use getTime()
/setTime()
instead.
getTime()
: Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
setTime(long time)
: Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. )
There are 1000 milliseconds in a second, and 60 seconds in a minute. Just do the math.
Date now = new Date();
Date oneMinuteInFuture = new Date(now.getTime() + 1000L * 60);
System.out.println(now);
System.out.println(oneMinuteInFuture);
The L
suffix in 1000
signifies that it's a long
literal; these calculations usually overflows int
easily.
I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).
URL for accessing my app:
http://myapp.com/amazing_url?token=super_token
Then when the user loads the page:
http://myapp.com/amazing_url?token=super_token#/amazing_url
Then when the user navigates:
http://myapp.com/amazing_url?token=super_token#/another_url
With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.
So don't enable the HTML5 mode and then add this controller:
.config ($stateProvider)->
$stateProvider.state('home-loading', {
url: '/',
controller: 'homeController'
})
.controller 'homeController', ($state, $location)->
if window.location.pathname != '/'
$location.url(window.location.pathname+window.location.search).replace()
else
$state.go('home', {}, { location: 'replace' })
You would be best off using collections.defaultdict
(added in Python 2.5). This allows you to specify the default object type of a missing key (such as a list
).
So instead of creating a key if it doesn't exist first and then appending to the value of the key, you cut out the middle-man and just directly append to non-existing keys to get the desired result.
A quick example using your data:
>>> from collections import defaultdict
>>> data = [(2010, 2), (2009, 4), (1989, 8), (2009, 7)]
>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> for year, month in data:
... d[year].append(month)
...
>>> d
defaultdict(<type 'list'>, {2009: [4, 7], 2010: [2], 1989: [8]})
This way you don't have to worry about whether you've seen a digit associated with a year or not. You just append and forget, knowing that a missing key will always be a list. If a key already exists, then it will just be appended to.
This worked in SSMS:
Select Jobtitle,
concat(Upper(LEFT(jobtitle,1)), SUBSTRING(jobtitle,2,LEN(jobtitle))) as Propercase
From [HumanResources].[Employee]
In symfony >= 3.2, documentation states that:
An alternative way to get the current user in a controller is to type-hint the controller argument with UserInterface (and default it to null if being logged-in is optional):
use Symfony\Component\Security\Core\User\UserInterface\UserInterface; public function indexAction(UserInterface $user = null) { // $user is null when not logged-in or anon. }
This is only recommended for experienced developers who don't extend from the Symfony base controller and don't use the ControllerTrait either. Otherwise, it's recommended to keep using the getUser() shortcut.
Blog post about it
To hide and show div on button click in angular 6.
Html Code
<button (click)=" isShow=!isShow">FormatCell</button>
<div class="ruleOptionsPanel" *ngIf=" isShow">
<table>
<tr>
<td>Name</td>
<td>Ram</td>
</tr>
</table>
</div>
Component .ts Code
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent{
isShow=false;
}
this works for me and it is way to replace ng-hide and ng-show in angular6.
enjoy...
Thanks
The GitHub repository setup page is just a suggested list of commands (and GitHub now suggests using the HTTPS protocol). Unless you have administrative access to GitHub's site, I don't know of any way to change their suggested commands.
If you'd rather use the SSH protocol, simply add a remote branch like so (i.e. use this command in place of GitHub's suggested command). To modify an existing branch, see the next section.
$ git remote add origin [email protected]:nikhilbhardwaj/abc.git
As you already know, to switch a pre-existing repository to use SSH instead of HTTPS, you can change the remote url within your .git/config
file.
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
-url = https://github.com/nikhilbhardwaj/abc.git
+url = [email protected]:nikhilbhardwaj/abc.git
A shortcut is to use the set-url
command:
$ git remote set-url origin [email protected]:nikhilbhardwaj/abc.git
insert
is better from the point of exception safety.
The expression map[key] = value
is actually two operations:
map[key]
- creating a map element with default value.= value
- copying the value into that element.An exception may happen at the second step. As result the operation will be only partially done (a new element was added into map, but that element was not initialized with value
). The situation when an operation is not complete, but the system state is modified, is called the operation with "side effect".
insert
operation gives a strong guarantee, means it doesn't have side effects (https://en.wikipedia.org/wiki/Exception_safety). insert
is either completely done or it leaves the map in unmodified state.
http://www.cplusplus.com/reference/map/map/insert/:
If a single element is to be inserted, there are no changes in the container in case of exception (strong guarantee).
you have to do like this in your project level gradle file
allprojects {
repositories {
jcenter()
maven { url "http://dl.appnext.com/" }
maven { url "https://maven.google.com" }
}
}
max_connections
You can change max_connections
while MySQL is running via SET
:
mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| max_connections | 5000 |
+-----------------+-------+
1 row in set (0.00 sec)
timeout
relatedI had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.
I suggest that you increase this value to 100k or disable connection pooling Pooling=false
he has two questions.
Q1 - what happens if I disable pooling
Slow down making DB connection. connection pooling
is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool
Q2 - Can the value of pooling be increased or the maximum is 100?
you can increase but I'm sure what is MAX value, maybe max_connections
in my.cnf
My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.
If you have Stress Test tool like JMeter
you can test youself.
I can't see pass-by-reference in the examples where people try to demonstrate such. I only see pass-by-value.
In the case of variables that hold a reference to an object, the reference is the value of those variables, and therefore the reference is passed, which is then pass-by-value.
In a statement like this,
var a = {
b: "foo",
c: "bar"
};
the value of the 'a' is not the Object, but the (so far only) reference to it. In other words, the object is not in the variable a
- a reference to it is. I think this is something that seems difficult for programmers who are mainly only familiar with JavaScript. But it is easy for people who know also e.g. Java, C#, and C.