View the source at http://whatsmy.browsersize.com (lines 14-120).
Here is the abstracted cross browser code on jsbin for flash detection only, works on: FF/IE/Safari/Opera/Chrome.
C# has a static constructor for this purpose.
static class YourClass
{
static YourClass()
{
// perform initialization here
}
}
From MSDN:
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced
.
The answers to your two questions are related. I'll start with the second:
Once you have staged a file (often with git add
, though some other commands implicitly stage the changes as well, like git rm
) you can back out that change with git reset -- <file>
.
In your case you must have used git rm
to remove the file, which is equivalent to simply removing it with rm
and then staging that change. If you first unstage it with git reset -- <file>
you can then recover it with git checkout -- <file>
.
Yes, right click the project. Click Run as
then Run Configurations
. You can change the parameters passed to the JVM in the Arguments
tab in the VM Arguments
box.
That configuration can then be used as the default when running the project.
You can check out libvideo. It's much more up-to-date than YoutubeExtractor, and is fast and clean to use.
$conn=new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
// If this is your connection then you have to assign null
// to your connection variable as follows:
$conn=null;
// By this way you can close connection in PDO.
#include<stdio.h>
void main ()
{
int num;
printf ("=====This Program Converts ASCII to Alphabet!=====\n");
printf ("Enter ASCII: ");
scanf ("%d", &num);
printf("%d is ASCII value of '%c'", num, (char)num );
}
#include<stdio.h>
void main ()
{
char alphabet;
printf ("=====This Program Converts Alphabet to ASCII code!=====\n");
printf ("Enter Alphabet: ");
scanf ("%c", &alphabet);
printf("ASCII value of '%c' is %d", alphabet, (char)alphabet );
}
I'm running SQL Server 2014 64 bit
on Windows 10. I tried everything, the thing that made it work was:
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 0
I don't know why the AllowInProcess turned off makes it work but that was the key in my case. Thank you for the suggestion of turning all the options off on the linkserver.
You can use the git merge-base
command to find the latest common commit between the two branches. If that commit is the same as your branch head, then the branch has been completely merged.
Note that
git branch -d
does this sort of thing already because it will refuse to delete a branch that hasn't already been completely merged.
Use VerticalScrollBar
with the TextBlock
control in WPF. In your code behind, add the following code:
In the constructor, define an event handler for the scrollbar:
scrollBar1.ValueChanged += new RoutedPropertyChangedEventHandler<double>(scrollBar1_ValueChanged);
scrollBar1.Minimum = 0;
scrollBar1.Maximum = 1;
scrollBar1.SmallChange = 0.1;
Then in the event handler, add:
void scrollBar1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
FteHolderText.Text = scrollBar1.Value.ToString();
}
Here is the original snippet from my code... make necessary changes.. :)
public NewProjectPlan()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(NewProjectPlan_Loaded);
scrollBar1.ValueChanged += new RoutedPropertyChangedEventHandler<double>(scrollBar1_ValueChanged);
scrollBar1.Minimum = 0;
scrollBar1.Maximum = 1;
scrollBar1.SmallChange = 0.1;
// etc...
}
void scrollBar1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
FteHolderText.Text = scrollBar1.Value.ToString();
}
If you're working with .net core, you can use the dotnet CLI, for instance
dotnet add package <package name>
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
Git command Quick Reference
git [command] -help
Git command Manual Pages
git help [command]
git [command] --help
Autocomplete
git <tab>
Cheat Sheets
When taking Distinct we have to cast into IEnumerable too. If list is model means, need to write code like this
IEnumerable<T> ids = list.Select(x => x).Distinct();
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
//alert(html);
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
and the html
<input id="search" style="height:36px; font-size:13px;" type="text" class="form-control" placeholder="Enter Mobile Number or Email" value="<?php echo stripcslashes($_REQUEST["string"]); ?>" name="string" />
<h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
<ul id="results"></ul>
In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.
flex-basis: 25%;
This will be a lot smoother when testing.
// VARIABLES
$screen-xs: 480px;
$screen-sm: 768px;
$screen-md: 992px;
$screen-lg: 1200px;
$screen-xl: 1400px;
$screen-xxl: 1600px;
// QUERIES
@media screen (max-width: $screen-lg) {
flex-basis: 25%;
}
@media screen (max-width: $screen-md) {
flex-basis: 33.33%;
}
This solution doesn't require you to use any data structures or make a different file.
Basically, you define all your enum values in a #define, then use them in the operator <<. Very similar to @jxh's answer.
ideone link for final iteration: http://ideone.com/hQTKQp
Full code:
#include <iostream>
#define ERROR_VALUES ERROR_VALUE(NO_ERROR)\
ERROR_VALUE(FILE_NOT_FOUND)\
ERROR_VALUE(LABEL_UNINITIALISED)
enum class Error
{
#define ERROR_VALUE(NAME) NAME,
ERROR_VALUES
#undef ERROR_VALUE
};
inline std::ostream& operator<<(std::ostream& os, Error err)
{
int errVal = static_cast<int>(err);
switch (err)
{
#define ERROR_VALUE(NAME) case Error::NAME: return os << "[" << errVal << "]" #NAME;
ERROR_VALUES
#undef ERROR_VALUE
default:
// If the error value isn't found (shouldn't happen)
return os << errVal;
}
}
int main() {
std::cout << "Error: " << Error::NO_ERROR << std::endl;
std::cout << "Error: " << Error::FILE_NOT_FOUND << std::endl;
std::cout << "Error: " << Error::LABEL_UNINITIALISED << std::endl;
return 0;
}
Output:
Error: [0]NO_ERROR
Error: [1]FILE_NOT_FOUND
Error: [2]LABEL_UNINITIALISED
A nice thing about doing it this way is that you can also specify your own custom messages for each error if you think you need them:
#include <iostream>
#define ERROR_VALUES ERROR_VALUE(NO_ERROR, "Everything is fine")\
ERROR_VALUE(FILE_NOT_FOUND, "File is not found")\
ERROR_VALUE(LABEL_UNINITIALISED, "A component tried to the label before it was initialised")
enum class Error
{
#define ERROR_VALUE(NAME,DESCR) NAME,
ERROR_VALUES
#undef ERROR_VALUE
};
inline std::ostream& operator<<(std::ostream& os, Error err)
{
int errVal = static_cast<int>(err);
switch (err)
{
#define ERROR_VALUE(NAME,DESCR) case Error::NAME: return os << "[" << errVal << "]" #NAME <<"; " << DESCR;
ERROR_VALUES
#undef ERROR_VALUE
default:
return os << errVal;
}
}
int main() {
std::cout << "Error: " << Error::NO_ERROR << std::endl;
std::cout << "Error: " << Error::FILE_NOT_FOUND << std::endl;
std::cout << "Error: " << Error::LABEL_UNINITIALISED << std::endl;
return 0;
}
Output:
Error: [0]NO_ERROR; Everything is fine
Error: [1]FILE_NOT_FOUND; File is not found
Error: [2]LABEL_UNINITIALISED; A component tried to the label before it was initialised
If you like making your error codes/descriptions very descriptive, you might not want them in production builds. Turning them off so only the value is printed is easy:
inline std::ostream& operator<<(std::ostream& os, Error err)
{
int errVal = static_cast<int>(err);
switch (err)
{
#ifndef PRODUCTION_BUILD // Don't print out names in production builds
#define ERROR_VALUE(NAME,DESCR) case Error::NAME: return os << "[" << errVal << "]" #NAME <<"; " << DESCR;
ERROR_VALUES
#undef ERROR_VALUE
#endif
default:
return os << errVal;
}
}
Output:
Error: 0
Error: 1
Error: 2
If this is the case, finding error number 525 would be a PITA. We can manually specify the numbers in the initial enum like this:
#define ERROR_VALUES ERROR_VALUE(NO_ERROR, 0, "Everything is fine")\
ERROR_VALUE(FILE_NOT_FOUND, 1, "File is not found")\
ERROR_VALUE(LABEL_UNINITIALISED, 2, "A component tried to the label before it was initialised")\
ERROR_VALUE(UKNOWN_ERROR, -1, "Uh oh")
enum class Error
{
#define ERROR_VALUE(NAME,VALUE,DESCR) NAME=VALUE,
ERROR_VALUES
#undef ERROR_VALUE
};
inline std::ostream& operator<<(std::ostream& os, Error err)
{
int errVal = static_cast<int>(err);
switch (err)
{
#ifndef PRODUCTION_BUILD // Don't print out names in production builds
#define ERROR_VALUE(NAME,VALUE,DESCR) case Error::NAME: return os << "[" #VALUE "]" #NAME <<"; " << DESCR;
ERROR_VALUES
#undef ERROR_VALUE
#endif
default:
return os <<errVal;
}
}
ERROR_VALUES
#undef ERROR_VALUE
#endif
default:
{
// If the error value isn't found (shouldn't happen)
return os << static_cast<int>(err);
break;
}
}
}
Output:
Error: [0]NO_ERROR; Everything is fine
Error: [1]FILE_NOT_FOUND; File is not found
Error: [2]LABEL_UNINITIALISED; A component tried to the label before it was initialised
Error: [-1]UKNOWN_ERROR; Uh oh
You might be in formula view:
Hit Ctrl + ` to switch
ref means that the value in the ref parameter is already set, the method can read and modify it. Using the ref keyword is the same as saying that the caller is responsible for initializing the value of the parameter.
out tells the compiler that the initialization of object is the responsibility of the function, the function has to assign to the out parameter. It's not allowed to leave it unassigned.
You can use a static Map in your enum that maps Strings to enum constants. Use it in a 'getEnum' static method. This skips the need to iterate through the enums each time you want to get one from its String value.
public enum RandomEnum {
StartHere("Start Here"),
StopHere("Stop Here");
private final String strVal;
private RandomEnum(String strVal) {
this.strVal = strVal;
}
public static RandomEnum getEnum(String strVal) {
if(!strValMap.containsKey(strVal)) {
throw new IllegalArgumentException("Unknown String Value: " + strVal);
}
return strValMap.get(strVal);
}
private static final Map<String, RandomEnum> strValMap;
static {
final Map<String, RandomEnum> tmpMap = Maps.newHashMap();
for(final RandomEnum en : RandomEnum.values()) {
tmpMap.put(en.strVal, en);
}
strValMap = ImmutableMap.copyOf(tmpMap);
}
@Override
public String toString() {
return strVal;
}
}
Just make sure the static initialization of the map occurs below the declaration of the enum constants.
BTW - that 'ImmutableMap' type is from the Google guava API, and I definitely recommend it in cases like this.
EDIT - Per the comments:
I encountered this error while there is an invisible view in an activity xml layout. At that time it was not used in my case so I have removed it and the crash is not seen anymore.
Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the contents). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string:
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class TripleDESTest {
public static void main(String[] args) throws Exception {
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
System.out.println(decodedtext); // This correctly shows "kyle boon"
}
public byte[] encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
return cipherText;
}
public String decrypt(byte[] message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
}
Another way, for variety. Although this is somewhat less flexible than the others. Unfortunately, the graphs appear one above the other, rather than side-by-side, which you did request in your original question. But it is very concise.
df.plot(subplots=True)
If the dataframe has more than the two series, and you only want to plot those two, you'll need to replace df
with df[['korisnika','osiguranika']]
.
Just use notepad ++ with encoding UTF-8 without BOM.
Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate
now has second parameter values
, which is being used for new record, but not for search
$user = User::firstOrCreate([
'email' => '[email protected]'
], [
'firstName' => 'Taylor',
'lastName' => 'Otwell'
]);
I was facing with this problem some time ago and I found java.util.LinkedList
is best for my case. It has several methods, with different namings, but they're doing what is needed:
push() -> LinkedList.addLast(); // Or just LinkedList.add();
pop() -> LinkedList.pollLast();
shift() -> LinkedList.pollFirst();
unshift() -> LinkedList.addFirst();
Your condition will never be true, because its like "if (a == a + b)".
I'd try the following:
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]
This will capture "google.com" from "www.google.com" into %1, the rest in $1 and after that combining the 2, when HTTP_HOST starts with www (with or without https).
To anyone using Windows and Windows Subsystem for Linux, make sure that when you run the python command from the command line, it's not accidentally running the python installation from WSL! This gave me quite a headache just now. A quick check you can do for this is just
which <python command you're using>
If that prints something like /usr/bin/python2
even though you're in powershell, that's probably what's going on.
It is being pointed out not directly in the file which is caused the error. But it is actually triggered in a controller file. It happens when a return value from a method defined inside in a controller file is set on a boolean value. It must not be set on a boolean type but on the other hand, it must be set or given a value of a string type. It can be shown as follows :
public function saveFormSummary(Request $request) {
...
$status = true;
return $status;
}
Given the return value of a boolean type above in a method, to be able to solve the problem to handle the error specified. Just change the type of the return value into a string type
as follows :
public function saveFormSummary(Request $request) {
...
$status = "true";
return $status;
}
If you want every cell in the grid to have the same background color, you can just do this:
dataGridView1.DefaultCellStyle.BackColor = Color.Green;
I've occasionally found the following idiom useful:
a?.b?.c
can be rewritten as:
((a||{}).b||{}).c
This takes advantage of the fact that getting unknown attributes on an object returns undefined, rather than throwing an exception as it does on null
or undefined
, so we replace null and undefined with an empty object before navigating.
Using MoveToElement you will be able to find or click in whatever point you want, you have just to define the first parameter, it can be the session(winappdriver) or driver(in other ways) which is created when you instance WindowsDriver. Otherwise you can set as first parameter a grid (my case), a list, a panel or whatever you want.
Note: The top-left of your first parameter element will be the position X = 0 and Y = 0
Actions actions = new Actions(this.session);
int xPosition = this.session.FindElementsByAccessibilityId("GraphicView")[0].Size.Width - 530;
int yPosition = this.session.FindElementsByAccessibilityId("GraphicView")[0].Size.Height- 150;
actions.MoveToElement(this.xecuteClientSession.FindElementsByAccessibilityId("GraphicView")[0], xPosition, yPosition).ContextClick().Build().Perform();
Few points
struct Vector y = (struct Vector*)malloc(sizeof(struct Vector));
is wrong
it should be struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector));
since y
holds pointer to struct Vector
.
1st malloc()
only allocates memory enough to hold Vector structure (which is pointer to double + int)
2nd malloc()
actually allocate memory to hold 10 double.
Get a list of all duplicate rows from table:
Select * from TABLE1 where PRIMARY_KEY_COLUMN NOT IN ( SELECT PRIMARY_KEY_COLUMN
FROM TABLE1
GROUP BY DUP_COLUMN_NAME having (count(*) >= 1))
taskkill /F /IM notepad.exe this is the best way to kill the task from task manager.
All you have to do it insert you exact db details and restart your mysql server
Configure the maven-compiler-plugin to use the same character encoding that your source files are encoded in (e.g):
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
Many maven plugins will by default use the "project.build.sourceEncoding" property so setting this in your pom will cover most plugins.
<project>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
...
However, I prefer setting the encoding in each plugin's configuration that supports it as I like to be explicit.
When your source code is compiled by the maven-compiler-plugin your source code files are read in by the compiler plugin using whatever encoding the compiler plugin is configured with. If your source files have a different encoding than the compiler plugin is using then it is possible that some characters may not exist in both encodings.
Many people prefer to set the encoding on their source files to UTF-8 so as to avoid this problem. To do this in Eclipse you can right click on a project and select Properties->Resource->Text File Encoding and change it to UTF-8. This will encode all your source files in UTF-8. (You should also explicitly configure the maven-compiler-plugin as mentioned above to use UTF-8 encoding.) With your source files and the compiler plugin both using the same encoding you shouldn't have any more unmappable characters during compilation.
Note, You can also set the file encoding globally in eclipse through Window->Preferences->General->Workspace->Text File Encoding. You can also set the encoding per file type through Window->Preferences->General->Content Types.
if 'a' is already a decimal; adding '.' would make 3.4/b(for example) into 3.4./b
Try float(a)/b
The issue is two-fold:
As a prerequisite (as of August, 2016), you need to link an AdSense account and then turn on monetization in your YouTube channel. It's a painful change that broke a lot of live streams.
You will need to use the following URL format for the embed:
<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>
The &autoplay=1
is not necessary, but I like to include it. Change CHANNEL
to your channel's ID. One thing to note is that WordPress may reformat the URL once you commit your change. Therefore, you'll need a plugin that allows you to use raw code and not have it override. Using a custom PHP code plugin can help and you would just echo the code like so:
<?php echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>'; ?>
Let me know if that worked for you!
Try http://support.microsoft.com/kb/207438 which will work for 2007 if you follow v12.0 in the registry.
Single quotes work fine too, even without escaping the double quotes, at least in Excel 2016:
'text with spaces, and a comma','more text with spaces','spaces and "quoted text" and more spaces','nospaces','NOSPACES1234'
Excel will put that in 5 columns (if you choose the single quote as "Text qualifier" in the "Text to columns" wizard)
You want to init an array of ints in your constructor? Point it to a static array.
class C
{
public:
int *cArray;
};
C::C {
static int c_init[]{1,2,3};
cArray = c_init;
}
I have found a simple solution to banding by content at Pearson Software Consulting: Let's say the header is from A1 to B1, table data is from A2 to B5, the controling cell is in the A column
I got the same error when using %
as a percent character in my format string. The solution to this is to double up the %%
.
Yes, yes you can.
#y.x {
/* will select element of id="y" that also has class="x" */
}
Similarly:
.x#y {
/* will select elements of class="x" that also have an id="y" */
}
Incidentally this might be useful in some use cases (wherein classes are used to represent some form of event or interaction), but for the most part it's not necessarily that useful, since id
s are unique in the document anyway. But if you're using classes for user-interaction then it can be useful to know.
oops! just found myself: just add this line on any element you need
-webkit-appearance: none;
use overflow:
overflow: visible;
Sadly no, there is no such thing as drop if exists, or CREATE IF NOT EXIST
You could write a plsql script to include the logic there.
http://download.oracle.com/docs/cd/B12037_01/server.101/b10759/statements_9003.htm
I'm not much into Oracle Syntax, but i think @Erich's script would be something like this.
declare
cant integer
begin
select into cant count(*) from dba_tables where table_name='Table_name';
if count>0 then
BEGIN
DROP TABLE tableName;
END IF;
END;
I needed proper CSV parsing, not cut
/ awk
and prayer. I'm trying this on a mac without csvtool
, but macs do come with ruby, so you can do:
echo "require 'csv'; CSV.read('new.csv').each {|data| puts data[34]}" | ruby
If you are using JavaScript to render then use escape_JavaScript("<%=render partial: partial_name, locals=>{@newval=>@oldval}%>");
http://jquerypriceformat.com/#examples
https://github.com/flaviosilveira/Jquery-Price-Format
html input runing for live chance.
<input type="text" name="v7" class="priceformat"/>
<input type="text" name="v8" class="priceformat"/>
$('.priceformat').each(function( index ) {
$(this).priceFormat({ prefix: '', thousandsSeparator: '' });
});
//5000.00
//5.000,00
//5,000.00
Receive POST and GET request in nodejs :
1).Server
var http = require('http');
var server = http.createServer ( function(request,response){
response.writeHead(200,{"Content-Type":"text\plain"});
if(request.method == "GET")
{
response.end("received GET request.")
}
else if(request.method == "POST")
{
response.end("received POST request.");
}
else
{
response.end("Undefined request .");
}
});
server.listen(8000);
console.log("Server running on port 8000");
2). Client :
var http = require('http');
var option = {
hostname : "localhost" ,
port : 8000 ,
method : "POST",
path : "/"
}
var request = http.request(option , function(resp){
resp.on("data",function(chunck){
console.log(chunck.toString());
})
})
request.end();
Variable declaration. Initially, it was short for "dimension", which is not a term that is used in programming (outside of this specific keyword) to any significant degree.
http://in.answers.yahoo.com/question/index?qid=20090310095555AANmiAZ
You see the two empty -D
entries in the g++
command line? They're causing the problem. You must have values in the -D
items e.g. -DWIN32
if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:
SYSTEM ?= generic
ENVIRONMENT ?= generic
in the makefile which gives them default values.
Your output looks to be missing the all important output:
<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers
just to clarify, what actually got sent to g++
was -D -DWindows_NT
, i.e. define a preprocessor macro called -DWindows_NT
; which is of course not a valid identifier (similarly for -D -I.
)
For JDBC the proper format is slightly different and as follows:
jdbc:microsoft:sqlserver://mycomputer.test.xxx.com:49843
Note the colon instead of the comma.
Using the Drag and Drop method
cmd
to pull up the windows bar operation.Open File Location
.Copy to Desktop
while dragging and before dropping, then push down and hold the Control key until you see the message. Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.
If InStr(myString, "A") > 0 Then
For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.
Left(oldStr, InStr(oldStr, "A"))
Use iloc to access by position (rather than label):
In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])
In [12]: df
Out[12]:
A B
a 1 2
b 3 4
In [13]: df.iloc[0] # first row in a DataFrame
Out[13]:
A 1
B 2
Name: a, dtype: int64
In [14]: df['A'].iloc[0] # first item in a Series (Column)
Out[14]: 1
pandas.DataFrame.plot()
, matplotlib.axes.Axes
is returned when creating a plot from a dataframe. As such, the dataframe plot can be assigned to a variable, ax
, which enables the usage of the associated formatting methods.pandas
, is matplotlib
.import pandas as pd
# test dataframe
data = {'a': range(20), 'date': pd.bdate_range('2021-01-09', freq='D', periods=20)}
df = pd.DataFrame(data)
# plot the dataframe and assign the returned axes
ax = df.plot(x='date', color='green', ylabel='values', xlabel='date', figsize=(8, 6))
# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('magenta')
ax.spines['left'].set_color('orange')
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both') # 'both' refers to minor and major axes
Most answers here forget the obvious culprit why recursion is often slower than iterative solutions. It's linked with the build up and tear down of stack frames but is not exactly that. It's generally a big difference in the storage of the auto variable for each recursion. In an iterative algorithm with a loop, the variables are often held in registers and even if they spill, they will reside in the Level 1 cache. In a recursive algorithm, all intermediary states of the variable are stored on the stack, meaning they will engender many more spills to memory. This means that even if it makes the same amount of operations, it will have a lot memory accesses in the hot loop and what makes it worse, these memory operations have a lousy reuse rate making the caches less effective.
TL;DR recursive algorithms have generally a worse cache behavior than iterative ones.
Maybe you included the .c
file in makefile multiple times.
Have a look at this Stack Overflow answer.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
You can use the method to animate:
I.e.:
var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);
git reset
does know five "modes": soft, mixed, hard, merge and keep. I will start with the first three, since these are the modes you'll usually encounter. After that you'll find a nice little a bonus, so stay tuned.
When using git reset --soft HEAD~1
you will remove the last commit from the current branch, but the file changes will stay in your working tree. Also the changes will stay on your index, so following with a git commit
will create a commit with the exact same changes as the commit you "removed" before.
This is the default mode and quite similar to soft. When "removing" a commit with git reset HEAD~1
you will still keep the changes in your working tree but not on the index; so if you want to "redo" the commit, you will have to add the changes (git add
) before commiting.
When using git reset --hard HEAD~1
you will lose all uncommited changes in addition to the changes introduced in the last commit. The changes won't stay in your working tree so doing a git status
command will tell you that you don't have any changes in your repository.
Tread carefully with this one. If you accidentally remove uncommited changes which were never tracked by git
(speak: committed or at least added to the index), you have no way of getting them back using git
.
git reset --keep HEAD~1
is an interesting and useful one. It only resets the files which are different between the current HEAD
and the given commit. It aborts the reset if one or more of these files has uncommited changes. It basically acts as a safer version of hard
.
You can read more about that in the git reset documentation.
Note
When doing git reset
to remove a commit the commit isn't really lost, there just is no reference pointing to it or any of it's children. You can still recover a commit which was "deleted" with git reset
by finding it's SHA-1 key, for example with a command such as git reflog
.
One equivalent of lsof could be combined output from Sysinternals' handle and listdlls, i.e.:
c:\SysInternals>handle
[...]
------------------------------------------------------------------------------
gvim.exe pid: 5380 FOO\alois.mahdal
10: File (RW-) C:\Windows
1C: File (RW-) D:\some\locked\path\OpenFile.txt
[...]
c:\SysInternals>listdlls
[...]
------------------------------------------------------------------------------
Listdlls.exe pid: 6840
Command line: listdlls
Base Size Version Path
0x00400000 0x29000 2.25.0000.0000 D:\opt\SysinternalsSuite\Listdlls.exe
0x76ed0000 0x180000 6.01.7601.17725 C:\Windows\SysWOW64\ntdll.dll
[...]
c:\SysInternals>listdlls
Unfortunately, you have to "run as Administrator" to be able to use them.
Also listdlls and handle do not produce continuous table-like form so filtering filename would hide PID. findstr /c:pid: /c:<filename>
should get you very close with both utilities, though
c:\SysinternalsSuite>handle | findstr /c:pid: /c:Driver.pm
System pid: 4 \<unable to open process>
smss.exe pid: 308 NT AUTHORITY\SYSTEM
avgrsa.exe pid: 384 NT AUTHORITY\SYSTEM
[...]
cmd.exe pid: 7140 FOO\alois.mahdal
conhost.exe pid: 1212 FOO\alois.mahdal
gvim.exe pid: 3408 FOO\alois.mahdal
188: File (RW-) D:\some\locked\path\OpenFile.txt
taskmgr.exe pid: 6016 FOO\alois.mahdal
[...]
Here we can see that gvim.exe is the one having this file open.
I needed to have an ImageView and an Bitmap, so the Bitmap is scaled to ImageView size, and size of the ImageView is the same of the scaled Bitmap :).
I was looking through this post for how to do it, and finally did what I want, not the way described here though.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/acpt_frag_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/imageBackground"
android:orientation="vertical">
<ImageView
android:id="@+id/acpt_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:layout_margin="@dimen/document_editor_image_margin"
android:background="@color/imageBackground"
android:elevation="@dimen/document_image_elevation" />
and then in onCreateView method
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_scanner_acpt, null);
progress = view.findViewById(R.id.progress);
imageView = view.findViewById(R.id.acpt_image);
imageView.setImageBitmap( bitmap );
imageView.getViewTreeObserver().addOnGlobalLayoutListener(()->
layoutImageView()
);
return view;
}
and then layoutImageView() code
private void layoutImageView(){
float[] matrixv = new float[ 9 ];
imageView.getImageMatrix().getValues(matrixv);
int w = (int) ( matrixv[Matrix.MSCALE_X] * bitmap.getWidth() );
int h = (int) ( matrixv[Matrix.MSCALE_Y] * bitmap.getHeight() );
imageView.setMaxHeight(h);
imageView.setMaxWidth(w);
}
And the result is that image fits inside perfectly, keeping aspect ratio, and doesn't have extra leftover pixels from ImageView when the Bitmap is inside.
It's important ImageView to have wrap_content and adjustViewBounds to true, then setMaxWidth and setMaxHeight will work, this is written in the source code of ImageView,
/*An optional argument to supply a maximum height for this view. Only valid if
* {@link #setAdjustViewBounds(boolean)} has been set to true. To set an image to be a
* maximum of 100 x 100 while preserving the original aspect ratio, do the following: 1) set
* adjustViewBounds to true 2) set maxWidth and maxHeight to 100 3) set the height and width
* layout params to WRAP_CONTENT. */
Use:
/*/ITEM[starts-with(REVENUE_YEAR,'2552')]/REGION
Note: Unless your host language can't handle element instance as result, do not use text nodes specially in mixed content data model. Do not start expressions with //
operator when the schema is well known.
As far as I'm aware this is the only answer here that works correctly with spaces:
space:=
space+=
CURRENT_PATH := $(subst $(lastword $(notdir $(MAKEFILE_LIST))),,$(subst $(space),\$(space),$(shell realpath '$(strip $(MAKEFILE_LIST))')))
It essentially works by escaping space characters by substituting ' '
for '\ '
which allows Make to parse it correctly, and then it removes the filename of the makefile in MAKEFILE_LIST
by doing another substitution so you're left with the directory that makefile is in. Not exactly the most compact thing in the world but it does work.
You'll end up with something like this where all the spaces are escaped:
$(info CURRENT_PATH = $(CURRENT_PATH))
CURRENT_PATH = /mnt/c/Users/foobar/gDrive/P\ roje\ cts/we\ b/sitecompiler/
Include this dependencies in your POM.xml and run Maven -> Update
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>0.99</version>
</dependency>
In some cases it is tied to how the field is used. In some DB engines the field differences determine how (and if) you search for text in the field. CharFields are typically used for things that are searchable, like if you want to search for "one" in the string "one plus two". Since the strings are shorter they are less time consuming for the engine to search through. TextFields are typically not meant to be searched through (like maybe the body of a blog) but are meant to hold large chunks of text. Now most of this depends on the DB Engine and like in Postgres it does not matter.
Even if it does not matter, if you use ModelForms you get a different type of editing field in the form. The ModelForm will generate an HTML form the size of one line of text for a CharField and multiline for a TextField.
I'd recomment using good old javascript:
document.getElementById("addRunner").reset();
For the people who need to wait for a specific element to show up. (used c#)
public static void WaitForElement(IWebDriver driver, By element)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
wait.Until(ExpectedConditions.ElementIsVisible(element));
}
Then if you want to wait for example if an class="error-message" exists in the DOM you simply do:
WaitForElement(driver, By.ClassName("error-message"));
For id, it will then be
WaitForElement(driver, By.Id("yourid"));
cmd.Parameters.Add(String parameterName, Object value)
is deprecated now. Instead use cmd.Parameters.AddWithValue(String parameterName, Object value)
There is no difference in terms of functionality. The reason they deprecated the
cmd.Parameters.Add(String parameterName, Object value)
in favor ofAddWithValue(String parameterName, Object value)
is to give more clarity. Here is the MSDN reference for the same
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).
So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.
For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.
(This goes for everyone else reading this too.)
You should use method listName.isEmpty()
If you can't create an locally valid security token, it seems like you've ruled all out every option bar Win32 API and WNetAddConnection*.
Tons of information on MSDN about WNet - PInvoke information and sample code that connects to a UNC path here:
http://www.pinvoke.net/default.aspx/mpr/WNetAddConnection2.html#
MSDN Reference here:
http://msdn.microsoft.com/en-us/library/aa385391(VS.85).aspx
Simply place this on a new line in .gitignore
**/.DS_Store
From git documentation
- A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".
This is the easiest way I found:
BtnUpload.Style.Add("display", "none");
FileUploader.Style.Add("display", "none");
BtnAccept.Style.Add("display", "inherit");
BtnClear.Style.Add("display", "inherit");
I have the opposite in the Else, so it handles displaying them as well. This can go in the Page's Load or in a method to refresh the controls on the page.
You can use inline styles but you will have some limitations if you are using them in all of your stylings, some known limitations are you can't use CSS pseudo selectors and media queries in there.
You can use Radium to solve this but still, I feel has the project grows its gonna get cumbersome.
I would recommend using CSS modules.
using CSS Modules you will have the freedom of writing CSS in CSS file and don't have to worry about the naming clashes, it will be taken care by CSS Modules.
An advantage of this method is that it gives you styling functionality to the specific component. This will create much more maintainable code and readable project architecture for the next developer to work on your project.
window.opener=window;
window.close();
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
I have found the solution:
We have to create two "apps" in the firebase project, and then we can download json file from any one app (I downloaded from the flavoured app). It will contain the data for both the apps. We can simply copy the json file to the app's root directory.
Source: https://firebase.googleblog.com/2016/08/organizing-your-firebase-enabled-android-app-builds.html
If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.
I just answered a question here explaining how to obtain the ROOT CA and get things to show up: How to install self-signed certificates in iOS 11
Here is a version that doesn't require an UDF and works even if the HTML contains tags without matching closing tags.
TRY_CAST(REPLACE(REPLACE(REPLACE([HtmlCol], '>', '/> '), '</', '<'), '--/>', '-->') AS XML).value('.', 'NVARCHAR(MAX)')
If you are trying to insert the therefore symbol into a WORD DOCUMENT
Hold down the ALT key and type 8756
Hope the answer ur question Regards Al~Hash.
As Mentioned in above repilies:
Starting with MySQL 8.0.4, the MySQL team changed the default authentication plugin for MySQL server from mysql_native_password to caching_sha2_password.
So there are three ways to resolve this issue:
1. drop USER 'user_name'@'localhost';
flush privileges;
CREATE USER 'user_name'@'localhost' IDENTIFIED BY 'user_name';
GRANT ALL PRIVILEGES ON * . * TO 'user_name'@'localhost';
ALTER USER 'user_name'@'localhost' IDENTIFIED WITH mysql_native_password BY
'user_name';
2. drop USER 'user_name'@'localhost';
flush privileges;
CREATE USER 'user_name'@'localhost' IDENTIFIED WITH mysql_native_password BY 'user_name';
GRANT ALL PRIVILEGES ON * . * TO 'user_name'@'localhost'
3. If the user is already created, the use the following command:
ALTER USER 'user_name'@'localhost' IDENTIFIED WITH mysql_native_password BY
'user_name';
If you work with JDK 1.5 or below the keytool utility will not have the -importkeystore
option (see JDK 1.5 keytool documentation) and the solution by MikeD will be available only by transferring the .pfx
on a machine with a newer JDK (1.6 or above).
Another option in JDK 1.5 or below (if you have Oracle WebLogic product), is to follow the instructions from this Oracle document: Using PFX and PEM Certificate Formats with Keystores.
It describes the conversion into .pem
format, how to extract certificates information from this textual format, and import it into .jks
format with java utils.ImportPrivateKey
utility (this is an utility included with WebLogic product).
There are several different approaches you can take.
The RESTful purists will want you to use BASIC authentication, and send credentials on every request. Their rationale is that no one is storing any state.
The client service could store a cookie, which maintains a session ID. I don't personally find this as offensive as some of the purists I hear from - it can be expensive to authenticate over and over again. It sounds like you're not too fond of this idea, though.
From your description, it really sounds like you might be interested in OAuth2 My experience so far, from what I've seen, is that it's kind of confusing, and kind of bleeding edge. There are implementations out there, but they're few and far between. In Java, I understand that it has been integrated into Spring3's security modules. (Their tutorial is nicely written.) I've been waiting to see if there will be an extension in Restlet, but so far, although it's been proposed, and may be in the incubator, it's still not been fully incorporated.
TOP and square brackets are specific to Transact-SQL. In ANSI SQL one uses LIMIT and backticks (`).
select * from `Table_Name` LIMIT 5;
Perhaps the best way would be to implement your app as a web app. I think you can also make web apps that run direct on the phone, without internet access or a remote server.
Web app, sounds lame? But a lot can be done with DHTML / HTML5 / JavaScript. It's a rare app that requires more power and couldn't be done as a web app. And you get pretty good cross platform with Web / JavaScript - the browsers vary a bit but a good web dev can write one web app that works pretty much everywhere.
Of course if you're writing a high-performance 3D game, the browser might not deliver what you need! maybe in a few years... Apparently some Google hackers ported Quake 2 to HTML5 already!
http://web.appstorm.net/roundups/browsers/10-html5-games-paving-the-way/
I ended up adding a method setCurrentTimeout(int timeout)
to the RetryPolicy
and it's implementation in DefaultRetryPolicy
.
Then I added a setCurrentTimeout(int timeout)
in the Request class and called it .
This seems to do the job.
Sorry for my laziness by the way and hooray for open source.
The @
operator calls the array's __matmul__
method, not dot
. This method is also present in the API as the function np.matmul
.
>>> a = np.random.rand(8,13,13)
>>> b = np.random.rand(8,13,13)
>>> np.matmul(a, b).shape
(8, 13, 13)
From the documentation:
matmul
differs fromdot
in two important ways.
- Multiplication by scalars is not allowed.
- Stacks of matrices are broadcast together as if the matrices were elements.
The last point makes it clear that dot
and matmul
methods behave differently when passed 3D (or higher dimensional) arrays. Quoting from the documentation some more:
For matmul
:
If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.
For np.dot
:
For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b
For difference between dates including holidays I went this way:
1) Table with Holidays:
CREATE TABLE [dbo].[Holiday](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Date] [datetime] NOT NULL)
2) I had my plannings Table like this and wanted to fill column Work_Days which was empty:
CREATE TABLE [dbo].[Plan_Phase](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Id_Plan] [int] NOT NULL,
[Id_Phase] [int] NOT NULL,
[Start_Date] [datetime] NULL,
[End_Date] [datetime] NULL,
[Work_Days] [int] NULL)
3) So in order to get "Work_Days" to later fill in my column just had to:
SELECT Start_Date, End_Date,
(DATEDIFF(dd, Start_Date, End_Date) + 1)
-(DATEDIFF(wk, Start_Date, End_Date) * 2)
-(SELECT COUNT(*) From Holiday Where Date >= Start_Date AND Date <= End_Date)
-(CASE WHEN DATENAME(dw, Start_Date) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, End_Date) = 'Saturday' THEN 1 ELSE 0 END)
-(CASE WHEN (SELECT COUNT(*) From Holiday Where Start_Date = Date) > 0 THEN 1 ELSE 0 END)
-(CASE WHEN (SELECT COUNT(*) From Holiday Where End_Date = Date) > 0 THEN 1 ELSE 0 END) AS Work_Days
from Plan_Phase
Hope that I could help.
Cheers
According to the docs, router.push seems like the preferred method:
To navigate to a different URL, use router.push. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.
source: https://router.vuejs.org/en/essentials/navigation.html
FYI : Webpack & component setup, single page app (where you import the router through Main.js), I had to call the router functions by saying:
this.$router
Example: if you wanted to redirect to a route called "Home" after a condition is met:
this.$router.push('Home')
First things first, you need to loop to < a.length
rather than a.length - 1
. As this is strictly less than you need to include the upper bound.
So, to check all pairs of elements you can do:
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
But this will compare, for example a[2]
to a[3]
and then a[3]
to a[2]
. Given that you are checking !=
this seems wasteful.
A better approach would be to compare each element i
to the rest of the array:
for (int i = 0; i < a.length; i++) {
for (int k = i + 1; k < a.length; k++) {
if (a[i] != a[k]) {
//do stuff
}
}
}
So if you have the indices [1...5] the comparison would go
1 -> 2
1 -> 3
1 -> 4
1 -> 5
2 -> 3
2 -> 4
2 -> 5
3 -> 4
3 -> 5
4 -> 5
So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.
pyMedia's sound example does just that. This should be all you need.
import time, wave, pymedia.audio.sound as sound
f= wave.open( 'YOUR FILE NAME', 'rb' )
sampleRate= f.getframerate()
channels= f.getnchannels()
format= sound.AFMT_S16_LE
snd= sound.Output( sampleRate, channels, format )
s= f.readframes( 300000 )
snd.play( s )
by using service you can achieve this :
public class PopupService extends Service{
private static final String TAG = PopupService.class.getSimpleName();
WindowManager mWindowManager;
View mView;
String type ;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// registerOverlayReceiver();
type = intent.getStringExtra("type");
Utils.printLog("type = "+type);
showDialog(intent.getStringExtra("msg"));
return super.onStartCommand(intent, flags, startId);
}
private void showDialog(String aTitle)
{
if(type.equals("when screen is off") | type.equals("always"))
{
Utils.printLog("type = "+type);
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
WakeLock mWakeLock = pm.newWakeLock((PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "YourServie");
mWakeLock.acquire();
mWakeLock.release();
}
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mView = View.inflate(getApplicationContext(), R.layout.dialog_popup_notification_received, null);
mView.setTag(TAG);
int top = getApplicationContext().getResources().getDisplayMetrics().heightPixels / 2;
LinearLayout dialog = (LinearLayout) mView.findViewById(R.id.pop_exit);
// android.widget.LinearLayout.LayoutParams lp = (android.widget.LinearLayout.LayoutParams) dialog.getLayoutParams();
// lp.topMargin = top;
// lp.bottomMargin = top;
// mView.setLayoutParams(lp);
final EditText etMassage = (EditText) mView.findViewById(R.id.editTextInPopupMessageReceived);
ImageButton imageButtonSend = (ImageButton) mView.findViewById(R.id.imageButtonSendInPopupMessageReceived);
// lp = (LayoutParams) imageButton.getLayoutParams();
// lp.topMargin = top - 58;
// imageButton.setLayoutParams(lp);
imageButtonSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Utils.printLog("clicked");
// mView.setVisibility(View.INVISIBLE);
if(!etMassage.getText().toString().equals(""))
{
Utils.printLog("sent");
etMassage.setText("");
}
}
});
TextView close = (TextView) mView.findViewById(R.id.TextViewCloseInPopupMessageReceived);
close.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
hideDialog();
}
});
TextView view = (TextView) mView.findViewById(R.id.textviewViewInPopupMessageReceived);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
hideDialog();
}
});
TextView message = (TextView) mView.findViewById(R.id.TextViewMessageInPopupMessageReceived);
message.setText(aTitle);
final WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, 0, 0,
WindowManager.LayoutParams.TYPE_SYSTEM_ERROR,
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
// | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON ,
PixelFormat.RGBA_8888);
mView.setVisibility(View.VISIBLE);
mWindowManager.addView(mView, mLayoutParams);
mWindowManager.updateViewLayout(mView, mLayoutParams);
}
private void hideDialog(){
if(mView != null && mWindowManager != null){
mWindowManager.removeView(mView);
mView = null;
}
}
}
Router Link
routerLink with brackets and none - simple explanation.
The difference between routerLink= and [routerLink] is mostly like relative and absolute path.
Similar to a href you may want to navigate to ./about.html or https://your-site.com/about.html.
When you use without brackets then you navigate relative and without params;
my-app.com/dashboard/client
"jumping" from my-app.com/dashboard to my-app.com/dashboard/client
<a routerLink="client/{{ client.id }}" .... rest the same
When you use routerLink with brackets then you execute app to navigate absolute and you can add params how is the puzzle of your new link
first of all it will not include the "jump" from dashboard/ to dashboard/client/client-id and bring you data of client/client-id which is more helpful for EDIT CLIENT
<a [routerLink]="['/client', client.id]" ... rest the same
The absolute way or brackets routerLink require additional set up of you components and app.routing.module.ts
The code without error will "tell you more/what is the purpose of []" when you make the test. Just check this with or without []. Than you may experiments with selectors which - as mention above - helps with dynamics routing.
See whats the routerLink construct
Note: If you're using AngularJS, then in addition to changing the step value, you may have to set ng-model-options="{updateOn: 'blur change'}"
on the html input.
The reason for this is in order to have the validators run less often, as they are preventing the user from entering a decimal point. This way, the user can type in a decimal point and the validators go into effect after the user blurs.
The placeholder is not affected by line-height
and padding
is inconsistent on browsers.
I have found another solution though.
VERTICAL-ALIGN
. This is probably the only time it works but try that instead and cave many lines of CSS code.
I often use a quick-n-dirty trick to read a fixed number of arguments from the command-line:
[filename] = sys.argv[1:]
in_file = open(filename) # Don't need the "r"
This will assign the one argument to filename
and raise an exception if there isn't exactly one argument.
I had a similar problem. Using a freeware utility called Unlocker (version 1.9.2), I found that my antivirus software (Panda free) had left a hanging lock on the executable file even though it didn't detect any threat. Unlocker was able to unlock it.
I used Identity2 then Scripts didn't load for anonymous user then I add this code in webconfig and Sloved.
<location path="bundles">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.
[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.
await Future.delayed(Duration(milliseconds: 1000));
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
In PHP, even if the individual items within an array or properties of an object are empty, the array or object will not evaluate to empty using the empty($subject)
function. In other words, cobbling together a bunch of data that individually tests as "empty" creates a composite that is non-empty.
Use the following PHP function to determine if the items in an array or properties of an object are empty:
function functionallyEmpty($o)
{
if (empty($o)) return true;
else if (is_numeric($o)) return false;
else if (is_string($o)) return !strlen(trim($o));
else if (is_object($o)) return functionallyEmpty((array)$o);
// If it's an array!
foreach($o as $element)
if (functionallyEmpty($element)) continue;
else return false;
// all good.
return true;
}
Example Usage:
$subject = array('', '', '');
empty($subject); // returns false
functionallyEmpty($subject); // returns true
class $Subject {
a => '',
b => array()
}
$theSubject = new Subject();
empty($theSubject); // returns false
functionallyEmpty($theSubject); // returns true
If you are using Node.js modules, __dirname
and __filename
don't exist.
From the Node.js documentation:
No require, exports, module.exports, __filename, __dirname
These CommonJS variables are not available in ES modules.
require
can be imported into an ES module usingmodule.createRequire()
.Equivalents of
__filename
and__dirname
can be created inside of each file viaimport.meta.url
:
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
https://nodejs.org/docs/latest-v15.x/api/esm.html#esm_no_filename_or_dirname
See C++ FAQ Lite How do I convert a std::string to a number?
See C++ Super-FAQ How do I convert a std::string to a number?
Please note that with your requirements you can't distinguish all the the allowed string representations of zero from the non numerical strings.
// the requested function
#include <sstream>
double string_to_double( const std::string& s )
{
std::istringstream i(s);
double x;
if (!(i >> x))
return 0;
return x;
}
// some tests
#include <cassert>
int main( int, char** )
{
// simple case:
assert( 0.5 == string_to_double( "0.5" ) );
// blank space:
assert( 0.5 == string_to_double( "0.5 " ) );
assert( 0.5 == string_to_double( " 0.5" ) );
// trailing non digit characters:
assert( 0.5 == string_to_double( "0.5a" ) );
// note that with your requirements you can't distinguish
// all the the allowed string representation of zero from
// the non numerical strings:
assert( 0 == string_to_double( "0" ) );
assert( 0 == string_to_double( "0." ) );
assert( 0 == string_to_double( "0.0" ) );
assert( 0 == string_to_double( "0.00" ) );
assert( 0 == string_to_double( "0.0e0" ) );
assert( 0 == string_to_double( "0.0e-0" ) );
assert( 0 == string_to_double( "0.0e+0" ) );
assert( 0 == string_to_double( "+0" ) );
assert( 0 == string_to_double( "+0." ) );
assert( 0 == string_to_double( "+0.0" ) );
assert( 0 == string_to_double( "+0.00" ) );
assert( 0 == string_to_double( "+0.0e0" ) );
assert( 0 == string_to_double( "+0.0e-0" ) );
assert( 0 == string_to_double( "+0.0e+0" ) );
assert( 0 == string_to_double( "-0" ) );
assert( 0 == string_to_double( "-0." ) );
assert( 0 == string_to_double( "-0.0" ) );
assert( 0 == string_to_double( "-0.00" ) );
assert( 0 == string_to_double( "-0.0e0" ) );
assert( 0 == string_to_double( "-0.0e-0" ) );
assert( 0 == string_to_double( "-0.0e+0" ) );
assert( 0 == string_to_double( "foobar" ) );
return 0;
}
Modified version of jockeisorby's answer that fixes the event handler not being properly removed.
copyToClipboard(item): void {
let listener = (e: ClipboardEvent) => {
e.clipboardData.setData('text/plain', (item));
e.preventDefault();
};
document.addEventListener('copy', listener);
document.execCommand('copy');
document.removeEventListener('copy', listener);
}
This is very often a symptom of an antipattern. The tool which produced the line numbers may well be replaced with one which deletes the lines right away. For example;
grep -nh error logfile | cut -d: -f1 | deletelines logfile
(where deletelines
is the utility you are imagining you need) is the same as
grep -v error logfile
Having said that, if you are in a situation where you genuinely need to perform this task, you can generate a simple sed
script from the file of line numbers. Humorously (but perhaps slightly confusingly) you can do this with sed
.
sed 's%$%d%' linenumbers
This accepts a file of line numbers, one per line, and produces, on standard output, the same line numbers with d
appended after each. This is a valid sed
script, which we can save to a file, or (on some platforms) pipe to another sed
instance:
sed 's%$%d%' linenumbers | sed -f - logfile
On some platforms, sed -f
does not understand the option argument -
to mean standard input, so you have to redirect the script to a temporary file, and clean it up when you are done, or maybe replace the lone dash with /dev/stdin
or /proc/$pid/fd/1
if your OS (or shell) has that.
As always, you can add -i
before the -f
option to have sed
edit the target file in place, instead of producing the result on standard output. On *BSDish platforms (including OSX) you need to supply an explicit argument to -i
as well; a common idiom is to supply an empty argument; -i ''
.
I think their are a lots of answer for thumbnail, but I want to add some other URLs to get YouTube thumbnail very easily. I am just taking some text from Asaph's answer. Here are some URLs to get YouTube thumbnails:
https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/default.jpg
For the high quality version of the thumbnail use a URL similar to this:
https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg
There is also a medium quality version of the thumbnail, using a URL similar to the high quality:
https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
For the standard definition version of the thumbnail, use a URL similar to this:
https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/sddefault.jpg
For the maximum resolution version of the thumbnail use a URL similar to this:
https://ytimg.googleusercontent.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
Credit to @Gert Grenander , @Alaa.Kh , and Ross Shanon
Trying to make some order:
it all works - all but the firefox bookmarking function. for some reason the 'window.sidebar.addPanel' is not a function for the debugger, though it is working fine.
The problem is that it takes its values from the calling <a ..>
tag: title as the bookmark name and href as the bookmark address.
so this is my code:
javascript:
$("#bookmarkme").click(function () {
var url = 'http://' + location.host; // i'm in a sub-page and bookmarking the home page
var name = "Snir's Homepage";
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1){ //chrome
alert("In order to bookmark go to the homepage and press "
+ (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ?
'Command/Cmd' : 'CTRL') + "+D.")
}
else if (window.sidebar) { // Mozilla Firefox Bookmark
//important for firefox to add bookmarks - remember to check out the checkbox on the popup
$(this).attr('rel', 'sidebar');
//set the appropriate attributes
$(this).attr('href', url);
$(this).attr('title', name);
//add bookmark:
// window.sidebar.addPanel(name, url, '');
// window.sidebar.addPanel(url, name, '');
window.sidebar.addPanel('', '', '');
}
else if (window.external) { // IE Favorite
window.external.addFavorite(url, name);
}
return;
});
html:
<a id="bookmarkme" href="#" title="bookmark this page">Bookmark This Page</a>
In internet explorer there is a different between 'addFavorite':
<a href="javascript:window.external.addFavorite('http://tiny.cc/snir','snir-site')">..</a>
and 'AddFavorite': <span onclick="window.external.AddFavorite(location.href, document.title);">..</span>
.
example here: http://www.yourhtmlsource.com/javascript/addtofavorites.html
Important, in chrome we can't add bookmarks using js (aspnet-i): http://www.codeproject.com/Questions/452899/How-to-add-bookmark-in-Google-Chrome-Opera-and-Saf
In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.
MyClass.php
namespace com\company\lib;
class MyClass {
}
index.php
namespace com\company\lib;
//Works fine
$i = new MyClass();
$cname = 'MyClass';
//Errors
//$i = new $cname;
//Works fine
$cname = "com\\company\\lib\\".$cname;
$i = new $cname;
You can simple read this way .
List<string> lines = System.IO.File.ReadLines(completePath).ToList();
As others here have stated, you can just use full datetime objects throughout:
from datetime import datetime, date, time, timedelta
sometime = time(8,00) # 8am
later = (datetime.combine(date.today(), sometime) + timedelta(seconds=3)).time()
However, I think it's worth explaining why full datetime objects are required. Consider what would happen if I added 2 hours to 11pm. What's the correct behavior? An exception, because you can't have a time larger than 11:59pm? Should it wrap back around?
Different programmers will expect different things, so whichever result they picked would surprise a lot of people. Worse yet, programmers would write code that worked just fine when they tested it initially, and then have it break later by doing something unexpected. This is very bad, which is why you're not allowed to add timedelta objects to time objects.
$file="./doc.txt";
$doc=file_get_contents($file);
$line=explode("\n",$doc);
foreach($line as $newline){
echo '<h3 style="color:#453288">'.$newline.'</h3><br>';
}
After trying all the solutions, none of them where working for me.
In my case I had the Android Studio and the adb was correctly working but the Android Studio was not capable to detect the adb. These was because I installed it with homebrew in another directory, not the /Users/$USER/Library/Android/sdk but Usr/Library blabla
Apparently AS needed to have it in his route /Users/$USER/Library/Android/sdk (same place as in preferences SDK installation route)
So I deleted all the adb from my computer (I installed several) and executed these terminal commands:
echo 'export ANDROID_HOME=/Users/$USER/Library/Android/sdk' >> ~/.bash_profile
echo 'export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' >> ~/.bash_profile
source ~/.bash_profile
adb devices
Well, after that, still wasn't working, because for some reason the route for the adb was /Users/$USER/Library/Android/sdk/platform-tools/platform-tools (yes, repeated) so I just copied the last platform-tools into the first directory with all the license files and started working.
Weird but true
How about doing this?
import string
def isAscii(s):
for c in s:
if c not in string.ascii_letters:
return False
return True
If that is the entire line, it very well might be because you are missing a ;
at the end of the line.
The new tests you wrote (directly or indirectly) use classes that log using Log4j.
Log4J needs to be configured for this logging to work properly.
Put a log4j.properties (or log4j.xml) file in the root of your test classpath.
It should have some basic configuration such as
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# An alternative logging format:
# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n
An appender outputs to the console by default, but you can also explicitly set the target like this:
log4j.appender.A1.Target=System.out
This will redirect all output in a nice format to the console. More info can be found here in the Log4J manual,
Log4J Logging will then be properly configured and this warning will disappear.
As your content is 24dp x 24dp you should use 24dp icon. And then set android:scaleType="center"
in your ImageButton to avoid auto resize.
It is an old post, but I came across this recently
Selecting a specific interval
As @aleroot already mentioned, by using
table.setRowSelectionInterval(index0, index1);
You can specify an interval, which should be selected.
Adding an interval to the existing selection
You can also keep the current selection, and simply add additional rows by using this here
table.getSelectionModel().addSelectionInterval(index0, index1);
This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.
I have to admit I'd do something rather insane.
When they find and remove the LicenseCheck, what fun will follow when the DLL starts segmentation faulting.
This answer will require some privilege in server to work.
Assemblies are a good option for you. There are a lot of sites that explain how to create it. The one I think is very well explained is this one
If you want, I have already created the assembly, and it is possible to download the DLL here.
Once you have downloaded it, you will need to run the following script in your SQL Server:
EXEC sp_configure 'show advanced options', 1
RECONFIGURE;
EXEC sp_configure 'clr strict security', 1;
RECONFIGURE;
CREATE Assembly concat_assembly
AUTHORIZATION dbo
FROM '<PATH TO Concat.dll IN SERVER>'
WITH PERMISSION_SET = SAFE;
GO
CREATE AGGREGATE dbo.concat (
@Value NVARCHAR(MAX)
, @Delimiter NVARCHAR(4000)
) RETURNS NVARCHAR(MAX)
EXTERNAL Name concat_assembly.[Concat.Concat];
GO
sp_configure 'clr enabled', 1;
RECONFIGURE
Observe that the path to assembly may be accessible to server. Since you have successfully done all the steps, you can use the function like:
SELECT dbo.Concat(field1, ',')
FROM Table1
Hope it helps!!!
UPDATE:
Since MS-SQL 2017 it is possible to use the STRING_AGG function
Maybe is late now but following Spacedman, did you try duplicate="strip" or any other option?
x=runif(1000)
y=runif(1000)
z=rnorm(1000)
s=interp(x,y,z,duplicate="strip")
surface3d(s$x,s$y,s$z,color="blue")
points3d(s)
If you want to print an arraylist with integer numbers, as an example you can use below code.
class Test{
public static void main(String[] args){
ArrayList<Integer> arraylist = new ArrayList<Integer>();
for(int i=0; i<=10; i++){
arraylist .add(i);
}
for (Integer n : arraylist ){
System.out.println(n);
}
}
}
The output is above code:
0
1
2
3
4
5
6
7
8
9
10
As Wagner Francisco said, (in JADE)
input(type="text", ng-model="someModel", placeholder="{{someScopeVariable}}")`
And in your controller :
$scope.someScopeVariable = 'somevalue'
Can anyone tell me why json_encode adds slashes?
Forward slash characters can cause issues (when preceded by a <
it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.
Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.
It doesn't. In JSON "/"
and "\/"
are equivalent.
The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode
and parseJSON
.
you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.
You don't have to do a replace, you can get the length of the children text and subtract that from the overall length, and slice into the original text. That should be substantially faster.
Below corrected zack's code (https://stackoverflow.com/a/11144999/9996503). Be careful with regular expressions! Consider this:
$string = 'Round brackets (parentheses) "()", square brackets "()"';
$find = '()';
$replace = '[]';
// Zack's code:
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
var_dump($result); // Output: NULL
// Correct code:
$result = strrev(preg_replace('/'.preg_quote(strrev($find)).'/', strrev($replace), strrev($string), 1));
echo $result; //Output: Round brackets (parentheses) "()", square brackets "[]"
To ensure an enum value exists and then parse it, you can also do the following.
// Fake Day of Week
string strDOWFake = "SuperDay";
// Real Day of Week
string strDOWReal = "Friday";
// Will hold which ever is the real DOW.
DayOfWeek enmDOW;
// See if fake DOW is defined in the DayOfWeek enumeration.
if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
{
// This will never be reached since "SuperDay"
// doesn't exist in the DayOfWeek enumeration.
enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
}
// See if real DOW is defined in the DayOfWeek enumeration.
else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
{
// This will parse the string into it's corresponding DOW enum object.
enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);
}
// Can now use the DOW enum object.
Console.Write("Today is " + enmDOW.ToString() + ".");
You can also sort the column by importing the spark sql functions
import org.apache.spark.sql.functions._
df.orderBy(asc("col1"))
Or
import org.apache.spark.sql.functions._
df.sort(desc("col1"))
importing sqlContext.implicits._
import sqlContext.implicits._
df.orderBy($"col1".desc)
Or
import sqlContext.implicits._
df.sort($"col1".desc)
Loki has both a Factory Method and an Abstract Factory. Both are documented (extensively) in Modern C++ Design, by Andei Alexandrescu. The factory method is probably closer to what you seem to be after, though it's still a bit different (at least if memory serves, it requires you to register a type before the factory can create objects of that type).
Sometimes, this error occurs when you're trying to target an element that is wrapped in a condition, for example:
<div *ngIf="canShow"> <p #target>Targeted Element</p></div>
In this code, if canShow
is false on render, Angular won't be able to get that element as it won't be rendered, hence the error that comes up.
One of the solutions is to use a display: hidden
on the element instead of the *ngIf
so the element gets rendered but is hidden until your condition is fulfilled.
Read More over at Github
float(item)
do the right thing: it converts its argument to float and and return it, but it doesn't change argument in-place. A simple fix for your code is:
new_list = []
for item in list:
new_list.append(float(item))
The same code can written shorter using list comprehension: new_list = [float(i) for i in list]
To change list in-place:
for index, item in enumerate(list):
list[index] = float(item)
BTW, avoid using list
for your variables, since it masquerades built-in function with the same name.
// Loading from a file, you can also load from a stream
var xml = XDocument.Load(@"C:\contacts.xml");
// Query the data and write out a subset of contacts
var query = from c in xml.Root.Descendants("contact")
where (int)c.Attribute("id") < 4
select c.Element("firstName").Value + " " +
c.Element("lastName").Value;
foreach (string name in query)
{
Console.WriteLine("Contact's Full Name: {0}", name);
}
Reference: LINQ to XML at MSDN
Consider using cellspacing
and cellpadding
attributes for table
tag or border-spacing
css property.
Also from here, which explains the math of it very well.
This is basically a bunch of functions to convert to and from HSL (Hue Saturation Lightness)
Tested and working on PHP 5.6.15
TL;DR: The full code can be found here on Pastebin.
Input: Hex color in format: [#]0f4 or [#]00ff44 (pound sign optional)
Output: HSL in Degrees, Percent, Percent
/**
* Input: hex color
* Output: hsl(in ranges from 0-1)
*
* Takes the hex, converts it to RGB, and sends
* it to RGBToHsl. Returns the output.
*
*/
function hexToHsl($hex) {
$r = "";
$g = "";
$b = "";
$hex = str_replace('#', '', $hex);
if (strlen($hex) == 3) {
$r = substr($hex, 0, 1);
$r = $r . $r;
$g = substr($hex, 1, 1);
$g = $g . $g;
$b = substr($hex, 2, 1);
$b = $b . $b;
} elseif (strlen($hex) == 6) {
$r = substr($hex, 0, 2);
$g = substr($hex, 2, 2);
$b = substr($hex, 4, 2);
} else {
return false;
}
$r = hexdec($r);
$g = hexdec($g);
$b = hexdec($b);
$hsl = rgbToHsl($r,$g,$b);
return $hsl;
}
Input: RGB in range 0-255 Output: HSL in Degrees, Percent, Percent.
/**
*
*Credits:
* https://stackoverflow.com/questions/4793729/rgb-to-hsl-and-back-calculation-problems
* http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/
*
* Called by hexToHsl by default.
*
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/.
* Assumes r, g, and b are contained in the range [0 - 255] and
* returns h, s, and l in the format Degrees, Percent, Percent.
*
* @param Number r The red color value
* @param Number g The green color value
* @param Number b The blue color value
* @return Array The HSL representation
*/
function rgbToHsl($r, $g, $b){
//For the calculation, rgb needs to be in the range from 0 to 1. To convert, divide by 255 (ff).
$r /= 255;
$g /= 255;
$b /= 255;
$myMax = max($r, $g, $b);
$myMin = min($r, $g, $b);
$maxAdd = ($myMax + $myMin);
$maxSub = ($myMax - $myMin);
//luminence is (max + min)/2
$h = 0;
$s = 0;
$l = ($maxAdd / 2.0);
//if all the numbers are equal, there is no saturation (greyscale).
if($myMin != $myMax){
if ($l < 0.5) {
$s = ($maxSub / $maxAdd);
} else {
$s = (2.0 - $myMax - $myMin); //note order of opperations - can't use $maxSub here
$s = ($maxSub / $s);
}
//find hue
switch($myMax){
case $r:
$h = ($g - $b);
$h = ($h / $maxSub);
break;
case $g:
$h = ($b - $r);
$h = ($h / $maxSub);
$h = ($h + 2.0);
break;
case $b:
$h = ($r - $g);
$h = ($h / $maxSub);
$h = ($h + 4.0);
break;
}
}
$hsl = hslToDegPercPerc($h, $s, $l);
return $hsl;
}
For the math calculations, HSL is easier to deal with in the 0-1 range, but for human readability, it's easier in Degrees, Percent, Percent. This function takes HSL in the ranges 0-1, and returns HSL in Degrees, Percent, Percent.
/**
* Input: HSL in ranges 0-1.
* Output: HSL in format Deg, Perc, Perc.
*
* Note: rgbToHsl calls this function by default.
*
* Multiplies $h by 60, and $s and $l by 100.
*/
function hslToDegPercPerc($h, $s, $l) {
//convert h to degrees
$h *= 60;
if ($h < 0) {
$h += 360;
}
//convert s and l to percentage
$s *= 100;
$l *= 100;
$hsl['h'] = $h;
$hsl['s'] = $s;
$hsl['l'] = $l;
return $hsl;
}
This function converts HSL in the format Degrees, Percent, Percent, to the ranges 0-1 for easier computing.
/**
* Input: HSL in format Deg, Perc, Perc
* Output: An array containing HSL in ranges 0-1
*
* Divides $h by 60, and $s and $l by 100.
*
* hslToRgb calls this by default.
*/
function degPercPercToHsl($h, $s, $l) {
//convert h, s, and l back to the 0-1 range
//convert the hue's 360 degrees in a circle to 1
$h /= 360;
//convert the saturation and lightness to the 0-1
//range by multiplying by 100
$s /= 100;
$l /= 100;
$hsl['h'] = $h;
$hsl['s'] = $s;
$hsl['l'] = $l;
return $hsl;
}
Input: HSL in the format Degrees, Percent, Percent
Output: RGB in the format 255, 255, 255
.
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/.
* Assumes h, s, and l are in the format Degrees,
* Percent, Percent, and returns r, g, and b in
* the range [0 - 255].
*
* Called by hslToHex by default.
*
* Calls:
* degPercPercToHsl
* hueToRgb
*
* @param Number h The hue value
* @param Number s The saturation level
* @param Number l The luminence
* @return Array The RGB representation
*/
function hslToRgb($h, $s, $l){
$hsl = degPercPercToHsl($h, $s, $l);
$h = $hsl['h'];
$s = $hsl['s'];
$l = $hsl['l'];
//If there's no saturation, the color is a greyscale,
//so all three RGB values can be set to the lightness.
//(Hue doesn't matter, because it's grey, not color)
if ($s == 0) {
$r = $l * 255;
$g = $l * 255;
$b = $l * 255;
}
else {
//calculate some temperary variables to make the
//calculation eaisier.
if ($l < 0.5) {
$temp2 = $l * (1 + $s);
} else {
$temp2 = ($l + $s) - ($s * $l);
}
$temp1 = 2 * $l - $temp2;
//run the calculated vars through hueToRgb to
//calculate the RGB value. Note that for the Red
//value, we add a third (120 degrees), to adjust
//the hue to the correct section of the circle for
//red. Simalarly, for blue, we subtract 1/3.
$r = 255 * hueToRgb($temp1, $temp2, $h + (1 / 3));
$g = 255 * hueToRgb($temp1, $temp2, $h);
$b = 255 * hueToRgb($temp1, $temp2, $h - (1 / 3));
}
$rgb['r'] = $r;
$rgb['g'] = $g;
$rgb['b'] = $b;
return $rgb;
}
This function is called by hslToRgb to convert the hue into the separate RGB values.
/**
* Converts an HSL hue to it's RGB value.
*
* Input: $temp1 and $temp2 - temperary vars based on
* whether the lumanence is less than 0.5, and
* calculated using the saturation and luminence
* values.
* $hue - the hue (to be converted to an RGB
* value) For red, add 1/3 to the hue, green
* leave it alone, and blue you subtract 1/3
* from the hue.
*
* Output: One RGB value.
*
* Thanks to Easy RGB for this function (Hue_2_RGB).
* http://www.easyrgb.com/index.php?X=MATH&$h=19#text19
*
*/
function hueToRgb($temp1, $temp2, $hue) {
if ($hue < 0) {
$hue += 1;
}
if ($hue > 1) {
$hue -= 1;
}
if ((6 * $hue) < 1 ) {
return ($temp1 + ($temp2 - $temp1) * 6 * $hue);
} elseif ((2 * $hue) < 1 ) {
return $temp2;
} elseif ((3 * $hue) < 2 ) {
return ($temp1 + ($temp2 - $temp1) * ((2 / 3) - $hue) * 6);
}
return $temp1;
}
Input: HSL in format Degrees, Percent, Percent
Output: Hex in format 00ff22
(no pound sign).
Converts to RGB, then converts separately to hex.
/**
* Converts HSL to Hex by converting it to
* RGB, then converting that to hex.
*
* string hslToHex($h, $s, $l[, $prependPound = true]
*
* $h is the Degrees value of the Hue
* $s is the Percentage value of the Saturation
* $l is the Percentage value of the Lightness
* $prependPound is a bool, whether you want a pound
* sign prepended. (optional - default=true)
*
* Calls:
* hslToRgb
*
* Output: Hex in the format: #00ff88 (with
* pound sign). Rounded to the nearest whole
* number.
*/
function hslToHex($h, $s, $l, $prependPound = true) {
//convert hsl to rgb
$rgb = hslToRgb($h,$s,$l);
//convert rgb to hex
$hexR = $rgb['r'];
$hexG = $rgb['g'];
$hexB = $rgb['b'];
//round to the nearest whole number
$hexR = round($hexR);
$hexG = round($hexG);
$hexB = round($hexB);
//convert to hex
$hexR = dechex($hexR);
$hexG = dechex($hexG);
$hexB = dechex($hexB);
//check for a non-two string length
//if it's 1, we can just prepend a
//0, but if it is anything else non-2,
//it must return false, as we don't
//know what format it is in.
if (strlen($hexR) != 2) {
if (strlen($hexR) == 1) {
//probably in format #0f4, etc.
$hexR = "0" . $hexR;
} else {
//unknown format
return false;
}
}
if (strlen($hexG) != 2) {
if (strlen($hexG) == 1) {
$hexG = "0" . $hexG;
} else {
return false;
}
}
if (strlen($hexB) != 2) {
if (strlen($hexB) == 1) {
$hexB = "0" . $hexB;
} else {
return false;
}
}
//if prependPound is set, will prepend a
//# sign to the beginning of the hex code.
//(default = true)
$hex = "";
if ($prependPound) {
$hex = "#";
}
$hex = $hex . $hexR . $hexG . $hexB;
return $hex;
}
There is a better way to do this now. You can use the bottom property.
.my-element {
position: absolute;
bottom: 30px;
}
add html = true to the tooltip options
$({selector}).tooltip({html: true});
Update
it's not relevant for jQuery ui tooltip property - it's true in bootstrap ui tooltip - my bad!
The reasons why (including the data in the leaf level of the index) have been nicely explained. The reason that you give two shakes about this, is that when you run your query, if you don't have the additional columns included (new feature in SQL 2005) the SQL Server has to go to the clustered index to get the additional columns which takes more time, and adds more load to the SQL Server service, the disks, and the memory (buffer cache to be specific) as new data pages are loaded into memory, potentially pushing other more often needed data out of the buffer cache.
This works better in my case if you have object or multi-dimensional array. It will shows only first items, other will be just ignored in loop.
.filter('limitItems', function () {
return function (items) {
var result = {}, i = 1;
angular.forEach(items, function(value, key) {
if (i < 5) {
result[key] = value;
}
i = i + 1;
});
return result;
};
});
Change 5 on what you want.
The best solution is
do like this comment(add use_unicode=True
and charset="utf8"
)
db = MySQLdb.connect(host="localhost", user = "root", passwd = "", db = "testdb", use_unicode=True, charset="utf8") – KyungHoon Kim Mar 13 '14 at 17:04
detail see :
class Connection(_mysql.connection):
"""MySQL Database Connection Object"""
default_cursor = cursors.Cursor
def __init__(self, *args, **kwargs):
"""
Create a connection to the database. It is strongly recommended
that you only use keyword parameters. Consult the MySQL C API
documentation for more information.
host
string, host to connect
user
string, user to connect as
passwd
string, password to use
db
string, database to use
port
integer, TCP/IP port to connect to
unix_socket
string, location of unix_socket to use
conv
conversion dictionary, see MySQLdb.converters
connect_timeout
number of seconds to wait before the connection attempt
fails.
compress
if set, compression is enabled
named_pipe
if set, a named pipe is used to connect (Windows only)
init_command
command which is run once the connection is created
read_default_file
file from which default client values are read
read_default_group
configuration group to use from the default file
cursorclass
class object, used to create cursors (keyword only)
use_unicode
If True, text-like columns are returned as unicode objects
using the connection's character set. Otherwise, text-like
columns are returned as strings. columns are returned as
normal strings. Unicode objects will always be encoded to
the connection's character set regardless of this setting.
charset
If supplied, the connection character set will be changed
to this character set (MySQL-4.1 and newer). This implies
use_unicode=True.
sql_mode
If supplied, the session SQL mode will be changed to this
setting (MySQL-4.1 and newer). For more details and legal
values, see the MySQL documentation.
client_flag
integer, flags to use or 0
(see MySQL docs or constants/CLIENTS.py)
ssl
dictionary or mapping, contains SSL connection parameters;
see the MySQL documentation for more details
(mysql_ssl_set()). If this is set, and the client does not
support SSL, NotSupportedError will be raised.
local_infile
integer, non-zero enables LOAD LOCAL INFILE; zero disables
autocommit
If False (default), autocommit is disabled.
If True, autocommit is enabled.
If None, autocommit isn't set and server default is used.
There are a number of undocumented, non-standard methods. See the
documentation for the MySQL C API for some hints on what they do.
"""
Type this in Windows PowerShell
or CMD
:
"[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")"
After running the command, please restart PowerShell
or CMD
. If it still doesn't work, restart your PC.
You must put the updatepanel id in the first argument if the control causing the script is inside the updatepanel else use the keyword 'this' instead of update panel here is the code
ScriptManager.RegisterStartupScript(UpdatePanel3, this.GetType(), UpdatePanel3.UniqueID, "showError();", true);
I had a similar error with NSManagedObject and it was because I was using Core Data but was missing the Core Data framework in Build Phases - Link Binary With Libraries, as some others have answered
You forgot the return types in your member function definitions:
int ttTree::ttTreeInsert(int value) { ... }
^^^
and so on.
Below command used to export collection to CSV format.
Note: naag
is database, employee1_json
is a collection.
mongoexport --db naag--collection employee1_json --type csv --out /home/orienit/work/mongodb/employee1_csv_op1
If you want to unstage all the changes use below command,
git reset --soft HEAD
In the case you want to unstage changes and revert them from the working directory,
git reset --hard HEAD
Here's an extremely simple answer
yourPlot +
theme(
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.line = element_line(colour = "black")
)
It's that easy. Source: the end of this article
Run this program from commandline:
// File: Main.java
public class Main {
public static void main(String[] args) {
System.out.println(System.getProperty("java.home"));
}
}
$ javac Main.java
$ java Main
If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received.
int func(int arr[], ...){
.
.
.
}
int func(int arr[SIZE], ...){
.
.
.
}
int func(int* arr, ...){
.
.
.
}
So, you are modifying the original values.
Thanks !!!
Although I would suggest the Apache approach is better, SVN Serve works fine and is pretty straightforward.
Assuming your repository is called "my_repo", and it is stored in C:\svn_repos:
Create a file called "passwd" in "C:\svn_repos\my_repo\conf". This file should look like:
[Users]
username = password
john = johns_password
steve = steves_password
In C:\svn_repos\my_repo\conf\svnserve.conf set:
[general]
password-db = passwd
auth-access=read
auth-access=write
This will force users to log in to read or write to this repository.
Follow these steps for each repository, only including the appropriate users in the passwd
file for each repository.
This one has always been a gotcha for me and many others. In short, the opening and closing tags for the <textarea>
element must be on the same line, otherwise a newline character occupies it. The placeholder will therefore not be displayed since the input area contains content (a newline character is, technically, valid content).
Good:
<textarea></textarea>
Bad:
<textarea>
</textarea>
This is not true anymore, according to the HTML5 parsing spec:
If the next token is a U+000A LINE FEED (LF) character token,
then ignore that token and move on to the next one. (Newlines
at the start of textarea elements are ignored as an authoring
convenience.)
You might still have trouble if you editor insists on ending lines with CRLF, though.
[Update]
The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.
Now, as J-P correctly states, jQuery has the functions outerWidth and outerHeight which include the border
and padding
by default, and also the margin
if the first argument of the function is true
[Original answer]
The width
method no longer requires the dimensions
plugin, because it has been added to the jQuery Core
What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the width
method
Something like this:
var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width
Split into multiple lines to make it more readable
That way you will always get the correct computed value, even if you change the padding or margin values from the css
In case you are using Spring Boot and want to pass the argument file.encoding
in JVM you have to run it like that:
mvn spring-boot:run -Drun.jvmArguments="-Dfile.encoding=UTF-8"
this was needed for us since we were using JTwig
templates and the operating system had ANSI_X3.4-1968
that we found out through System.out.println(System.getProperty("file.encoding"));
Hope this helps someone!
justify-content: space-between
anddisplay: flex
is all we needed, but thanks to @Pratul for the inspiration!
What were you doing before? For self-signed certificates, I would normally install the certificate locally on the client system.
You may be able to use Group Policy to push a certificate to every system.
Here is how you can do it:
BOOL flag = NO;
NSLog(flag ? @"YES" : @"NO");
You can install pidof
with Homebrew:
brew install pidof
pidof <process_name>
My Dark Color scheme for QtCreator is at:
https://github.com/borzh/qt-creator-css/blob/master/qt-creator.css
To use with Vim (dark) scheme.
Hope it is useful for someone.
Before answering when to use which one, a little background:
edit: I should mention that this comparison is really from the perspective of using them in a browser with JavaScript. It's not the way either data format has to be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.
JSON is both more compact and (in my view) more readable - in transmission it can be "faster" simply because less data is transferred.
In parsing, it depends on your parser. A parser turning the code (be it JSON or XML) into a data structure (like a map) may benefit from the strict nature of XML (XML Schemas disambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:
myJSON = {"age" : 12,
"name" : "Danielle"}
The parser doesn't need to be intelligent enough to realise that 12
represents a number, (and Danielle
is a string like any other). So in javascript we can do:
anObject = JSON.parse(myJSON);
anObject.age === 12 // True
anObject.name == "Danielle" // True
anObject.age === "12" // False
In XML we'd have to do something like the following:
<person>
<age>12</age>
<name>Danielle</name>
</person>
(as an aside, this illustrates the point that XML is rather more verbose; a concern for data transmission). To use this data, we'd run it through a parser, then we'd have to call something like:
myObject = parseThatXMLPlease();
thePeople = myObject.getChildren("person");
thePerson = thePeople[0];
thePerson.getChildren("name")[0].value() == "Danielle" // True
thePerson.getChildren("age")[0].value() == "12" // True
Actually, a good parser might well type the age
for you (on the other hand, you might well not want it to). What's going on when we access this data is - instead of doing an attribute lookup like in the JSON example above - we're doing a map lookup on the key name
. It might be more intuitive to form the XML like this:
<person name="Danielle" age="12" />
But we'd still have to do map lookups to access our data:
myObject = parseThatXMLPlease();
age = myObject.getChildren("person")[0].getAttr("age");
EDIT: Original:
In most programming languages (not all, by any stretch) a map lookup such as this will be more costly than an attribute lookup (like we got above when we parsed the JSON).
This is misleading: remember that in JavaScript (and other dynamic languages) there's no difference between a map lookup and a field lookup. In fact, a field lookup is just a map lookup.
If you want a really worthwhile comparison, the best is to benchmark it - do the benchmarks in the context where you plan to use the data.
As I have been typing, Felix Kling has already put up a fairly succinct answer comparing them in terms of when to use each one, so I won't go on any further.
I was not able to find any solution for this type of animation using ViewPropertyAnimator.
Here's an example:
Layout:
<FrameLayout
android:id="@+id/child_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/child_view"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal"
/>
</FrameLayout>
Animate - Right to left and exit view:
final childView = findViewById(R.id.child_view);
View containerView = findViewById(R.id.child_view_container);
childView.animate()
.translationXBy(-containerView.getWidth())
.setDuration(TRANSLATION_DURATION)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
childView.setVisibility(View.GONE);
}
});
Animate - Right to left enter view:
final View childView = findViewById(R.id.child_view);
View containerView = findViewById(R.id.child_view_container);
childView.setTranslationX(containerView.getWidth());
childView.animate()
.translationXBy(-containerView.getWidth())
.setDuration(TRANSLATION_DURATION)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
childView.setVisibility(View.VISIBLE);
}
});
How could I have figured that out for myself (other than asking this question here)? Can I somehow tell apt-get to list all packages, and grep for ssl? Or do I need to know the "lib*-dev" naming convention?
If you're linking with -lfoo
then the library is likely libfoo.so
. The library itself is probably part of the libfoo
package, and the headers are in the libfoo-dev
package as you've discovered.
Some people use the GUI "synaptic" app (sudo synaptic
) to (locate and) install packages, but I prefer to use the command line. One thing that makes it easier to find the right package from the command line is the fact that apt-get
supports bash completion.
Try typing sudo apt-get install libssl
and then hit tab to see a list of matching package names (which can help when you need to select the correct version of a package that has multiple versions or other variations available).
Bash completion is actually very useful... for example, you can also get a list of commands that apt-get
supports by typing sudo apt-get
and then hitting tab.
Today there is a simpler way to do that.
Just create the .env.local file in your root directory and set the variables there. In your case:
REACT_APP_API_KEY = 'my-secret-api-key'
Then you call it en your js file in that way:
process.env.REACT_APP_API_KEY
React supports environment variables since [email protected] .You don't need external package to do that.
*note: I propose .env.local instead of .env because create-react-app add this file to gitignore when create the project.
Files priority:
npm start: .env.development.local, .env.development, .env.local, .env
npm run build: .env.production.local, .env.production, .env.local, .env
npm test: .env.test.local, .env.test, .env (note .env.local is missing)
More info: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Per the jQuery documentation, try this:
$('input[inputName\\[\\]=someValue]')
[EDIT] However, I'm not sure that's the right syntax for your selector. You probably want:
$('input[name="inputName[]"][value="someValue"]')
Something else you can use is isnull
:
isnull( SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1), PostCode)
How about
if (dr.GetSchemaTable().Columns.Contains("accounttype"))
do something
else
do something
It probably would not be as efficient in a loop
The one place I've run across it is in containers which allocate a contiguous buffer and then fill it with objects as required. As mentioned, std::vector might do this, and I know some versions of MFC CArray and/or CList did this (because that's where I first ran across it). The buffer over-allocation method is a very useful optimization, and placement new is pretty much the only way to construct objects in that scenario. It is also used sometimes to construct objects in memory blocks allocated outside of your direct code.
I have used it in a similar capacity, although it doesn't come up often. It's a useful tool for the C++ toolbox, though.
You might try using my mailer module.
from mailer import Mailer
from mailer import Message
message = Message(From="[email protected]",
To="[email protected]")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""
sender = Mailer('smtp.example.com')
sender.send(message)
Check Requires full screen is enabled or not. If not enable it.
You can find that option in the below steps.
Targets -> General -> Deployment Info -> Requires full screen.
Just extending on the many other excellent answers - if you are using jQuery - you could just do something like
$.fn.getMonthName = function(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];
return monthNames[date.getMonth()];
};
where date
is equal to the var d = new Date(somevalue)
. The primary advantage of this is per @nickf said about avoiding the global namespace.
Using inputStream.available()
It is always acceptable for System.in.available() to return 0.
I've found the opposite - it always returns the best value for the number of bytes available. Javadoc for InputStream.available()
:
Returns an estimate of the number of bytes that can be read (or skipped over)
from this input stream without blocking by the next invocation of a method for
this input stream.
An estimate is unavoidable due to timing/staleness. The figure can be a one-off underestimate because new data are constantly arriving. However it always "catches up" on the next call - it should account for all arrived data, bar that arriving just at the moment of the new call. Permanently returning 0 when there are data fails the condition above.
First Caveat: Concrete subclasses of InputStream are responsible for available()
InputStream
is an abstract class. It has no data source. It's meaningless for it to have available data. Hence, javadoc for available()
also states:
The available method for class InputStream always returns 0.
This method should be overridden by subclasses.
And indeed, the concrete input stream classes do override available(), providing meaningful values, not constant 0s.
Second Caveat: Ensure you use carriage-return when typing input in Windows.
If using System.in
, your program only receives input when your command shell hands it over. If you're using file redirection/pipes (e.g. somefile > java myJavaApp or somecommand | java myJavaApp ), then input data are usually handed over immediately. However, if you manually type input, then data handover can be delayed. E.g. With windows cmd.exe shell, the data are buffered within cmd.exe shell. Data are only passed to the executing java program following carriage-return (control-m or <enter>
). That's a limitation of the execution environment. Of course, InputStream.available() will return 0 for as long as the shell buffers the data - that's correct behaviour; there are no available data at that point. As soon as the data are available from the shell, the method returns a value > 0. NB: Cygwin uses cmd.exe too.
Just use this:
byte[] inputData = new byte[1024];
int result = is.read(inputData, 0, is.available());
// result will indicate number of bytes read; -1 for EOF with no data read.
OR equivalently,
BufferedReader br = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")),1024);
// ...
// inside some iteration / processing logic:
if (br.ready()) {
int readCount = br.read(inputData, bufferOffset, inputData.length-bufferOffset);
}
Declare this:
public static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis)
throws IOException {
int bufferOffset = 0;
long maxTimeMillis = System.currentTimeMillis() + timeoutMillis;
while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < b.length) {
int readLength = java.lang.Math.min(is.available(),b.length-bufferOffset);
// can alternatively use bufferedReader, guarded by isReady():
int readResult = is.read(b, bufferOffset, readLength);
if (readResult == -1) break;
bufferOffset += readResult;
}
return bufferOffset;
}
Then use this:
byte[] inputData = new byte[1024];
int readCount = readInputStreamWithTimeout(System.in, inputData, 6000); // 6 second timeout
// readCount will indicate number of bytes read; -1 for EOF with no data read.
I had the same error. Basically, I suspect that the path cannot start either with "U" or "User" after "C:\". I changed my directory to "c:\file_name.png" by putting the file that I want to access from python right under the 'c:\' path.
In your case, if you have to access the "python" folder, perhaps reinstall the python, and change the installation path to something like "c:\python". Otherwise, just avoid the "...\User..." in your path, and put your project under C:.
I had the same problem when I'm using spring-context version 4.0.6 and spring-security version 4.1.0.
When changing spring-security version to 4.0.4 (because 4.0.6 of spring-security not available) in my pom and security xml-->schemaLocation, it gets compiled without internet.
So that mean you can also solve this by:
changing spring-security to a older or same version than spring-context.
changing spring-context to a newer or same version than spring-security.
(any way spring-context to be newer or same version to spring-security)
AsynHelper Java library includes a set of utility classes/methods for such asynchronous calls (and wait).
If it is desired to run a set of method calls or code blocks asynchronously, the It includes an useful helper method AsyncTask.submitTasks as in below snippet.
AsyncTask.submitTasks(
() -> getMethodParam1(arg1, arg2),
() -> getMethodParam2(arg2, arg3)
() -> getMethodParam3(arg3, arg4),
() -> {
//Some other code to run asynchronously
}
);
If it is desired to wait till all asynchronous codes are completed running, the AsyncTask.submitTasksAndWait varient can be used.
Also if it is desired to obtain a return value from each of the asynchronous method call or code block, the AsyncSupplier.submitSuppliers can be used so that the result can be then obtained by from the result suppliers array returned by the method. Below is the sample snippet:
Supplier<Object>[] resultSuppliers =
AsyncSupplier.submitSuppliers(
() -> getMethodParam1(arg1, arg2),
() -> getMethodParam2(arg3, arg4),
() -> getMethodParam3(arg5, arg6)
);
Object a = resultSuppliers[0].get();
Object b = resultSuppliers[1].get();
Object c = resultSuppliers[2].get();
myBigMethod(a,b,c);
If the return type of each method differ, use the below kind of snippet.
Supplier<String> aResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam1(arg1, arg2));
Supplier<Integer> bResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam2(arg3, arg4));
Supplier<Object> cResultSupplier = AsyncSupplier.submitSupplier(() -> getMethodParam3(arg5, arg6));
myBigMethod(aResultSupplier.get(), bResultSupplier.get(), cResultSupplier.get());
The result of the asynchronous method calls/code blocks can also be obtained at a different point of code in the same thread or a different thread as in the below snippet.
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam1(arg1, arg2), "a");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam2(arg3, arg4), "b");
AsyncSupplier.submitSupplierForSingleAccess(() -> getMethodParam3(arg5, arg6), "c");
//Following can be in the same thread or a different thread
Optional<String> aResult = AsyncSupplier.waitAndGetFromSupplier(String.class, "a");
Optional<Integer> bResult = AsyncSupplier.waitAndGetFromSupplier(Integer.class, "b");
Optional<Object> cResult = AsyncSupplier.waitAndGetFromSupplier(Object.class, "c");
myBigMethod(aResult.get(),bResult.get(),cResult.get());
to force running only one instace of a program in .net (C#) use this code in program.cs file:
public static Process PriorProcess()
// Returns a System.Diagnostics.Process pointing to
// a pre-existing process with the same name as the
// current one, if any; or null if the current process
// is unique.
{
Process curr = Process.GetCurrentProcess();
Process[] procs = Process.GetProcessesByName(curr.ProcessName);
foreach (Process p in procs)
{
if ((p.Id != curr.Id) &&
(p.MainModule.FileName == curr.MainModule.FileName))
return p;
}
return null;
}
and the folowing:
[STAThread]
static void Main()
{
if (PriorProcess() != null)
{
MessageBox.Show("Another instance of the app is already running.");
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form());
}
If you want to generate a random float in a range, try a next solution.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float
random_float(const float min, const float max)
{
if (max == min) return min;
else if (min < max) return (max - min) * ((float)rand() / RAND_MAX) + min;
// return 0 if min > max
return 0;
}
int
main (const int argc, const char *argv[])
{
srand(time(NULL));
char line[] = "-------------------------------------------";
float data[10][2] = {
{-10, 10},
{-5., 5},
{-1, 1},
{-0.25, -0.15},
{1.5, 1.52},
{-1700, 8000},
{-0.1, 0.1},
{-1, 0},
{-1, -2},
{1.2, 1.1}
};
puts(line);
puts(" From | Result | To");
puts(line);
int i;
for (i = 0; i < 10; ++i) {
printf("%12f | %12f | %12f\n", data[i][0], random_float(data[i][0], data[i][1]), data[i][1]);
}
puts(line);
return 0;
}
A result (values is fickle)
-------------------------------------------
From | Result | To
-------------------------------------------
-10.000000 | 2.330828 | 10.000000
-5.000000 | -4.945523 | 5.000000
-1.000000 | 0.004242 | 1.000000
-0.250000 | -0.203197 | -0.150000
1.500000 | 1.513431 | 1.520000
-1700.000000 | 3292.941895 | 8000.000000
-0.100000 | -0.021541 | 0.100000
-1.000000 | -0.148299 | 0.000000
-1.000000 | 0.000000 | -2.000000
1.200000 | 0.000000 | 1.100000
-------------------------------------------
Brute is your best bet!
Here is a script that helped me out:
https://code.google.com/p/android-keystore-password-recover/wiki/HowTo
You can optionally give it a list of words the password might include for a very fast recover (for me it worked in <1 sec)
No, if a is true (in a or
test), b will not be tested, as the result of the test will always be true, whatever is the value of the b expression.
Make a simple test:
if (true || ((String) null).equals("foobar")) {
...
}
will not throw a NullPointerException
!
For loading weights, you need to have a model first. It must be:
existingModel.save_weights('weightsfile.h5')
existingModel.load_weights('weightsfile.h5')
If you want to save and load the entire model (this includes the model's configuration, it's weights and the optimizer states for further training):
model.save_model('filename')
model = load_model('filename')
Steps that you should follow if you want the thread dump of your StandAlone Java Process
Step 1: Get the Process ID for the shell script calling the java program
linux$ ps -aef | grep "runABCD"
user1 **8535** 4369 0 Mar 25 ? 0:00 /bin/csh /home/user1/runABCD.sh
user1 17796 17372 0 08:15:41 pts/49 0:00 grep runABCD
Step 2: Get the Process ID for the Child which was Invoked by the runABCD. Use the above PID to get the childs.
linux$ ps -aef | grep **8535**
user1 **8536** 8535 0 Mar 25 ? 126:38 /apps/java/jdk/sun4/SunOS5/1.6.0_16/bin/java -cp /home/user1/XYZServer
user1 8535 4369 0 Mar 25 ? 0:00 /bin/csh /home/user1/runABCD.sh
user1 17977 17372 0 08:15:49 pts/49 0:00 grep 8535
Step 3: Get the JSTACK for the particular process. Get the Process id of your XYSServer process. i.e. 8536
linux$ jstack **8536** > threadDump.log
I find the most simple is
shell "explorer.exe URL"
This also works to open local folders.
The css and js files are located within the package: bootstrap/docs/assets/
UPDATE:
since v3 there is a dist
folder in the package that contains all css, js and fonts.
Another option (if you just want to fetch single files) might be: pulldown. Configuration is extremely simple and you can easily add your own files/urls to the list.
You'll want to check your docs for your version of gcc & ld:
However for me (OS X gcc 4.0.1) I find these for ld
-dead_strip
Remove functions and data that are unreachable by the entry point or exported symbols.
-dead_strip_dylibs
Remove dylibs that are unreachable by the entry point or exported symbols. That is, suppresses the generation of load command commands for dylibs which supplied no symbols during the link. This option should not be used when linking against a dylib which is required at runtime for some indirect reason such as the dylib has an important initializer.
And this helpful option
-why_live symbol_name
Logs a chain of references to symbol_name. Only applicable with
-dead_strip
. It can help debug why something that you think should be dead strip removed is not removed.
There's also a note in the gcc/g++ man that certain kinds of dead code elimination are only performed if optimization is enabled when compiling.
While these options/conditions may not hold for your compiler, I suggest you look for something similar in your docs.
Continuing this answer, There is another difference that if you want your method to return different values for example when it is first time called, second time called etc then you can pass values so for example...
PowerMockito.doReturn(false, false, true).when(SomeClass.class, "SomeMethod", Matchers.any(SomeClass.class));
So it will return false when the method is called in same test case and then it will return false again and lastly true.
The success option of ajax should not be altered because DataTables uses it internally to execute the table draw when the data load is complete. The recommendation is used "dataSrc" to alter the received data.
Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.
The Upgrade element inside the Product element, combined with proper scheduling of the action will perform the uninstall you're after. Be sure to list the upgrade codes of all the products you want to remove.
<Property Id="PREVIOUSVERSIONSINSTALLED" Secure="yes" />
<Upgrade Id="00000000-0000-0000-0000-000000000000">
<UpgradeVersion Minimum="1.0.0.0" Maximum="1.0.5.0" Property="PREVIOUSVERSIONSINSTALLED" IncludeMinimum="yes" IncludeMaximum="no" />
</Upgrade>
Note that, if you're careful with your builds, you can prevent people from accidentally installing an older version of your product over a newer one. That's what the Maximum field is for. When we build installers, we set UpgradeVersion Maximum to the version being built, but IncludeMaximum="no" to prevent this scenario.
You have choices regarding the scheduling of RemoveExistingProducts. I prefer scheduling it after InstallFinalize (rather than after InstallInitialize as others have recommended):
<InstallExecuteSequence>
<RemoveExistingProducts After="InstallFinalize"></RemoveExistingProducts>
</InstallExecuteSequence>
This leaves the previous version of the product installed until after the new files and registry keys are copied. This lets me migrate data from the old version to the new (for example, you've switched storage of user preferences from the registry to an XML file, but you want to be polite and migrate their settings). This migration is done in a deferred custom action just before InstallFinalize.
Another benefit is efficiency: if there are unchanged files, Windows Installer doesn't bother copying them again when you schedule after InstallFinalize. If you schedule after InstallInitialize, the previous version is completely removed first, and then the new version is installed. This results in unnecessary deletion and recopying of files.
For other scheduling options, see the RemoveExistingProducts help topic in MSDN. This week, the link is: http://msdn.microsoft.com/en-us/library/aa371197.aspx
You can make this.
CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]
@CODE XML
,@ERRFLAG CHAR(1) = '0' OUTPUT
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DELETE tb_SampleTest WHERE CODE IN( SELECT Item.value('.', 'VARCHAR(20)') FROM @CODE.nodes('RecordList/ID') AS x(Item) )
IF @@ROWCOUNT = 0 SET @ERRFLAG = 200
SET NOCOUNT OFF
Use this Remove title and image from top.
Before:
setContentView(R.layout.actii);
Write this code:
requestWindowFeature(Window.FEATURE_NO_TITLE);
In java syntax:
rdd.collect().forEach(line -> System.out.println(line));
I prefer to turn the tibble to data.frame. It shows everything and you're done
df %>% data.frame
you can use this command by getting your data. this will extract your data...
select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';
org.springframework.core.io.Resource
is part of spring-core-<version>.jar
But this lib is already in your lib folder. So I guess it is just a Deployment Problem. -- Try to clean your server and redeploy your application.
Update for React Router 5.1+.
import React from 'react';
import { useLocation, Switch } from 'react-router-dom';
const App = () => {
const location = useLocation();
React.useEffect(() => {
console.log('Location changed');
}, [location]);
return (
<Switch>
{/* Routes go here */}
</Switch>
);
};
One can use:
android:largeHeap="true"
in Android Manifest under application tag.
This solved the issue in my case!