You can use those queries to find all FKs for your table.
Declare @SchemaName VarChar(200) = 'Schema Name'
Declare @TableName VarChar(200) = 'Table name'
-- Find FK in This table.
SELECT
'IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].['
+ OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
-- Find the FKs in the tables in which this table is used
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].['
+ OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
' ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
The following will truncate the log.
USE [yourdbname]
GO
-- TRUNCATE TRANSACTION LOG --
DBCC SHRINKFILE(yourdbname_log, 1)
BACKUP LOG yourdbname WITH TRUNCATE_ONLY
DBCC SHRINKFILE(yourdbname_log, 1)
GO
-- CHECK DATABASE HEALTH --
ALTER FUNCTION [dbo].[checker]() RETURNS int AS BEGIN RETURN 0 END
GO
For enable PHP Extension intl , follow the Steps..
kindly remove the starting semicolon ( ; )
Like :
;extension=php_intl.dll
to
extension=php_intl.dll
Save the xampp/php/php.ini file.
Hope its work..Cheers..
Well, you need to incorporate exec-maven-plugin
, this plug-in performs the same thing that you do on command prompt when you type in java -cp .;jarpaths TestMain
. You can pass argument and define which phase (test
, package
, integration
, verify
, or deploy
), you want this plug-in to call your main class.
You need to add this plug-in under <build>
tag and specify parameters. For example
<project>
...
...
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1.1</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>my.company.name.packageName.TestMain</mainClass>
<arguments>
<argument>myArg1</argument>
<argument>myArg2</argument>
</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
...
</project>
Now, if you right-click on on the project folder and do Run As > Maven Test
, or Run As > Maven Package
or Run As > Maven Install
, the test phase
will execute and so your Main class.
Basically you need to have loading image Download free one from here http://www.ajaxload.info/
$(function() {
$("#client").on("change", function() {
var clientid=$("#client").val();
$('#loadingmessage').show();
$.ajax({
type:"post",
url:"clientnetworkpricelist/yourfile.php",
data:"title="+clientid,
success:function(data){
$('#loadingmessage').hide();
$("#result").html(data);
}
});
});
});
On html body
<div id='loadingmessage' style='display:none'>
<img src='img/ajax-loader.gif'/>
</div>
Probably this could help you
You can see a detailed description here.
ini_set('display_errors', 1);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
Changelog
5.4.0 E_STRICT became part of E_ALL
5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.
5.2.0 E_RECOVERABLE_ERROR introduced.
5.0.0 E_STRICT introduced (not part of E_ALL).
Try tracert to resolve the hostname. IE you have Ip address 8.8.8.8 so you would use; tracert 8.8.8.8
You must specify the file to be downloaded (attachment) by the client in the http header:
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", "attachment: filename=excelTest.xls"
http://classicasp.aspfaq.com/general/how-do-i-prompt-a-save-as-dialog-for-an-accepted-mime-type.html
In my case, issue was occured even after all these configurations have done (@Pekka has mentioned changes in httpd.conf & .htaccess files). It was resolved only after I add
<Directory "project/path">
Order allow,deny
Allow from all
AllowOverride All
</Directory>
to virtual host configuration in vhost file
Edit on 29/09/2017 (For Apache 2.4 <) Refer this answer
<VirtualHost dropbox.local:80>
DocumentRoot "E:/Documenten/Dropbox/Dropbox/dummy-htdocs"
ServerName dropbox.local
ErrorLog "logs/dropbox.local-error.log"
CustomLog "logs/dropbox.local-access.log" combined
<Directory "E:/Documenten/Dropbox/Dropbox/dummy-htdocs">
# AllowOverride All # Deprecated
# Order Allow,Deny # Deprecated
# Allow from all # Deprecated
# --New way of doing it
Require all granted
</Directory>
this.input
is undefined until the ref
callback is called. Try setting this.input
to some initial value in your constructor.
From the React docs on refs, emphasis mine:
the callback will be executed immediately after the component is mounted or unmounted
I'm also struck with this same problem, finally i got simple solution. just added one line to action bar style.
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:textColorPrimary">@color/colorAccent</item>
<item name="android:colorBackground">@color/colorAppWhite</item>
</style>
"android:colorBackground" is enough to change option menu background
In Bootstrap 3+ the most appropriate way to change the size of a modal dialog is to use the size property. Below is an example, notice the modal-sm
along the modal-dialog
class, indicating a small modal. It can contain the values sm
for small, md
for medium and lg
for large.
<div class="modal fade" id="ww_vergeten" tabindex="-1" role="dialog" aria-labelledby="modal_title" aria-hidden="true">
<div class="modal-dialog modal-sm"> <!-- property to determine size -->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="modal_title">Some modal</h4>
</div>
<div class="modal-body">
<!-- modal content -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="some_button" data-loading-text="Loading...">Send</button>
</div>
</div>
</div>
</div>
Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")
Or, in a more structured way...
Sub openwb()
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"
Set wb = Workbooks.Open(sFile)
End Sub
Looks like the inner JSON struct is passed along as a string. You'll have to JSON.parse() it once more to get that data as an object.
try {
responseData = JSON.parse(responseData);
}
catch (e) {}
Edit: Try the following:
$.ajax({
type: 'GET',
dataType: "json",
url: "http://someotherdomain.com/service.svc",
success: function (responseData, textStatus, jqXHR) {
console.log("in");
var data = JSON.parse(responseData['AuthenticateUserResult']);
console.log(data);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
This is an old question, and I know its asking specifically about adding a script tag into the head, however based on the OPs explanation they actually just intend to execute some JS code which has been obtained via some other JS function.
This is much simpler than adding a script tag into the page.
Simply:
eval(decoded);
Eval will execute a string of JS in-line, without any need to add it to the DOM at all.
I don't think there's ever really a need to add an in-line script tag to the DOM after page load.
More info here: http://www.w3schools.com/jsref/jsref_eval.asp
I had the same issue with spring
MarshallingMessageConverter
and by pre-proccess code.
Mayby someone will need reason: BytesMessage #readBytes - reading bytes.. and i forgot that reading is one direction operation. You can not read twice.
It's hard to tell what you're going for in that example. exports =
is about exporting from external modules, but the code sample you linked is an internal module.
Rule of thumb: If you write module foo { ... }
, you're writing an internal module; if you write export something something
at top-level in a file, you're writing an external module. It's somewhat rare that you'd actually write export module foo
at top-level (since then you'd be double-nesting the name), and it's even rarer that you'd write module foo
in a file that had a top-level export (since foo
would not be externally visible).
The following things make sense (each scenario delineated by a horizontal rule):
// An internal module named SayHi with an exported function 'foo'
module SayHi {
export function foo() {
console.log("Hi");
}
export class bar { }
}
// N.B. this line could be in another file that has a
// <reference> tag to the file that has 'module SayHi' in it
SayHi.foo();
var b = new SayHi.bar();
file1.ts
// This *file* is an external module because it has a top-level 'export'
export function foo() {
console.log('hi');
}
export class bar { }
file2.ts
// This file is also an external module because it has an 'import' declaration
import f1 = module('file1');
f1.foo();
var b = new f1.bar();
file1.ts
// This will only work in 0.9.0+. This file is an external
// module because it has a top-level 'export'
function f() { }
function g() { }
export = { alpha: f, beta: g };
file2.ts
// This file is also an external module because it has an 'import' declaration
import f1 = require('file1');
f1.alpha(); // invokes f
f1.beta(); // invokes g
For builtin JS types you can use:
function getTypeName(val) {
return {}.toString.call(val).slice(8, -1);
}
Here we use 'toString' method from 'Object' class which works different than the same method of another types.
Examples:
// Primitives
getTypeName(42); // "Number"
getTypeName("hi"); // "String"
getTypeName(true); // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null); // "Null"
getTypeName(undefined); // "Undefined"
// Non-primitives
getTypeName({}); // "Object"
getTypeName([]); // "Array"
getTypeName(new Date); // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/); // "RegExp"
getTypeName(new Error); // "Error"
If you need a class name you can use:
instance.constructor.name
Examples:
({}).constructor.name // "Object"
[].constructor.name // "Array"
(new Date).constructor.name // "Date"
function MyClass() {}
let my = new MyClass();
my.constructor.name // "MyClass"
But this feature was added in ES2015.
You can just as easily access each element in the list using e.g. path[[1]]
. You can't put a set of matrices into an atomic vector and access each element. A matrix is an atomic vector with dimension attributes. I would use the list structure returned by split
, it's what it was designed for. Each list element can hold data of different types and sizes so it's very versatile and you can use *apply
functions to further operate on each element in the list. Example below.
# For reproducibile data
set.seed(1)
# Make some data
userid <- rep(1:2,times=4)
data1 <- replicate(8 , paste( sample(letters , 3 ) , collapse = "" ) )
data2 <- sample(10,8)
df <- data.frame( userid , data1 , data2 )
# Split on userid
out <- split( df , f = df$userid )
#$`1`
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
#$`2`
# userid data1 data2
#2 2 xfv 4
#4 2 bfe 10
#6 2 mrx 2
#8 2 fqd 9
Access each element using the [[
operator like this:
out[[1]]
# userid data1 data2
#1 1 gjn 3
#3 1 yqp 1
#5 1 rjs 6
#7 1 jtw 5
Or use an *apply
function to do further operations on each list element. For instance, to take the mean of the data2
column you could use sapply like this:
sapply( out , function(x) mean( x$data2 ) )
# 1 2
#3.75 6.25
Here more flexible variant: it uses external shell, but allows to check for arbitrary conditions:
ifeq ($(shell test ".$(GCC_MINOR)" = .4 -o \
".$(GCC_MINOR)" = .5 -o \
".$(TODAY)" = .Friday && printf "true"), true)
CFLAGS += -fno-strict-overflow
endif
Besides these given great answers, What I have learned is that:
NEVER compare objects with == unless you intend to be comparing them by their references.
Here's my 2 cents:
import sys
sys.path.append('/Users/John/Desktop')
import mapping #mapping.py is the name of my module file
shipit = mapping.Shipment() #Shipment is the name of the class I need to use in the mapping module
from mapping import Mapping
shipit = Shipment() #Now you don't have to use the .notation
An important consideration for accessing mysql from a shell script used in cron, is that mysql looks at the logged in user to determine a .my.cnf to load.
That does not work with cron. It can also get confusing if you are using su/sudo as the logged in user might not be the user you are running as.
I use something like:
mysql --defaults-extra-file=/path/to/specific/.my.cnf -e 'SELECT something FROM sometable'
Just make sure that user and group ownership and permissions are set appropriately and tightly on the .my.cnf file.
I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.
Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.
In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.
Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.
For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :
20/2 = 10
10/2 = 5
Hence our answer is 5 + 1 + 1 = 7
. (The 1 + 1 because we divided the number 20 twice).
Real VNC Viewer (5.0.3) - Free :
Options->Expert->UseAllMonitors = True
As mentioned by BalusC, the border is set by PrimeFaces on the generated tr
and td
elements, not on the table
. However when trying with PrimeFaces version 5, it looks like there is a more specific match from the PrimeFaces CSS .ui-panelgrid .ui-panelgrid-cell > solid
which still result in black borders being shown when appyling the style suggested.
Try using following style in order to overide the Primefaces one without using the !important
declaration:
.companyHeaderGrid tr, .companyHeaderGrid td.ui-panelgrid-cell {
border: none;
}
As mention make sure your CSS is loaded after the PrimeFaces one.
If you want to get what is the difference between two hashes, you can do this:
h1 = {:a => 20, :b => 10, :c => 44}
h2 = {:a => 2, :b => 10, :c => "44"}
result = {}
h1.each {|k, v| result[k] = h2[k] if h2[k] != v }
p result #=> {:a => 2, :c => "44"}
Yes, ./
means the current working directory. You can just reference the file directly by name, without it.
yes
and no
, where no
is the default value.standalone="yes"
means that the XML processor must use the DTD for validation only. In that case it will not be used for:
standalone="yes"
may add validity constraints if the document uses an external DTD. When the document contains things that would require modification of the XML, such as default values for attributes, and standalone="yes"
is used then the document is invalid.standalone="yes"
may help to optimize performance of document processing.Source: The standalone pseudo-attribute is only relevant if a DTD is used
import sys
for x in range(10000):
print "HAPPY >> %s <<\r" % str(x),
sys.stdout.flush()
This issue came for me due to the fact that .. i was running server with selenium-server-standalone-2.32.0 and client registered with selenium-server-standalone-2.37.0 .. When i made both selenium-server-standalone-2.32.0 and ran then things worked fine
You need a back inserter to copy into vectors:
std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));
Simple. One line.
<button onclick="javascript:window.history.back();">Go Back</button>
Like Wim's and Malik's answer, but just in one line.
You can use java.lang.Runtime.exec
to run simple code. This gives you back a Process
and you can read its standard output directly without having to temporarily store the output on disk.
For example, here's a complete program that will showcase how to do it:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class testprog {
public static void main(String args[]) {
String s;
Process p;
try {
p = Runtime.getRuntime().exec("ls -aF");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
}
When compiled and run, it outputs:
line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0
as expected.
You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).
If you want to merge the process standard output and error from Java (as opposed to using 2>&1
in the actual command), you should look into ProcessBuilder
.
Restarting the SQL Server will clear up the log space used by your database. If this however is not an option, you can try the following:
* Issue a CHECKPOINT command to free up log space in the log file.
* Check the available log space with DBCC SQLPERF('logspace'). If only a small
percentage of your log file is actually been used, you can try a DBCC SHRINKFILE
command. This can however possibly introduce corruption in your database.
* If you have another drive with space available you can try to add a file there in
order to get enough space to attempt to resolve the issue.
Hope this will help you in finding your solution.
Something like this perhaps?
x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)
You should investigate why VBA can't find queryname.
I have a saved query named qryAddLoginfoRow. It inserts a row with the current time into my loginfo table. That query runs successfully when called by name by CurrentDb.Execute
.
CurrentDb.Execute "qryAddLoginfoRow"
My guess is that either queryname is a variable holding the name of a query which doesn't exist in the current database's QueryDefs collection, or queryname is the literal name of an existing query but you didn't enclose it in quotes.
Edit:
You need to find a way to accept that queryname does not exist in the current db's QueryDefs collection. Add these 2 lines to your VBA code just before the CurrentDb.Execute
line.
Debug.Print "queryname = '" & queryname & "'"
Debug.Print CurrentDb.QueryDefs(queryname).Name
The second of those 2 lines will trigger run-time error 3265, "Item not found in this collection." Then go to the Immediate window to verify the name of the query you're asking CurrentDb
to Execute
.
The selected answer would work for as long as you know the key itself that you want to delete but if it should be truly dynamic you would need to use the [] notation instead of the dot notation.
For example:
var keyToDelete = "key1";
var myObj = {"test": {"key1": "value", "key2": "value"}}
//that will not work.
delete myObj.test.keyToDelete
instead you would need to use:
delete myObj.test[keyToDelete];
Substitute the dot notation with [] notation for those values that you want evaluated before being deleted.
If you face the "This file cannot be checked for viruses" intermezzo page, the download is not that easy.
You essentially need to first download the normal download link, which however redirects you to the "Download anyway" page. You need to store cookies from this first request, find out the link pointed to by the "Download anyway" button, and then use this link to download the file, but reusing the cookies you got from the first request.
Here's a bash variant of the download process using CURL:
curl -c /tmp/cookies "https://drive.google.com/uc?export=download&id=DOCUMENT_ID" > /tmp/intermezzo.html
curl -L -b /tmp/cookies "https://drive.google.com$(cat /tmp/intermezzo.html | grep -Po 'uc-download-link" [^>]* href="\K[^"]*' | sed 's/\&/\&/g')" > FINAL_DOWNLOADED_FILENAME
Notes:
-P
) and the \K
"operator" which essentially means "do not include anything preceding \K
to the matched result. I don't know which version of grep introduced these options, but ancient or non-Ubuntu versions probably don't have itI was testing a function that had multiple UPDATE
statements within IF-ELSE
blocks.
I was testing all possible paths, so I reset the tables to their previous values with 'manual' UPDATE
statements each time before running the function again.
I noticed that the issue would happen just after those UPDATE
statements;
I added a COMMIT;
after the UPDATE
statement I used to reset the tables and that solved the problem.
So, caution, the problem was not the function itself...
Fetch does not use cookie by default. To enable cookie, do this:
fetch(url, {
credentials: "same-origin"
}).then(...).catch(...);
You can also directly get selected value using following code
<select ng-options='t.name for t in templates'
ng-change='selectedTemplate(t.url)'></select>
script.js
$scope.selectedTemplate = function(pTemplate) {
//Your logic
alert('Template Url is : '+pTemplate);
}
VS is kinda funny about C++ and IntelliSense. There are times it won't notice that it's supposed to be popping up something. This is due in no small part to the complexity of the language, and all the compiling (or at least parsing) that'd need to go on in order to make it better.
If it doesn't work for you at all, and it used to, and you've checked the VS options, maybe this can help.
In ubuntu desktop 16.04, I did this:
open file: /etc/mysql/mysql.conf.d/mysqld.cnf
in an editor of your choice.
Look for: sql_mode
, it will be somewhere under [mysqld]
.
and set sql_mode
to the following:
NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Save and then restart mysql service by doing:
sudo service mysql restart
Simplify things by using the following settings.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<proxies>
<proxy>
<id>myproxy</id>
<active>true</active>
<protocol>http</protocol>
<username>user</username> <!-- Put your username here -->
<password>pass</password> <!-- Put your password here -->
<host>123.45.6.78</host> <!-- Put the IP address of your proxy server here -->
<port>80</port> <!-- Put your proxy server's port number here -->
<nonProxyHosts>local.net|some.host.com</nonProxyHosts> <!-- Do not use this setting unless you know what you're doing. -->
</proxy>
</proxies>
</settings>
Under Linux/Unix, place it under ~/.m2/settings.xml
. Under Windows place it under c:\documents and settings\youruser\.m2\settings.xml
or c:\users\youruser\.m2\settings.xml
.
You don't need the <mirrors/>
, <profiles/>
and <settings/>
sections, unless you really know what they're for.
I would highly recommend Open rico. It is difficult to implement in the the beginning, but once you grab it you will never look back.
Disclamer: This is just a wild guess
I know everybody loves an easy-to-read list:
toBe(<value>)
- The returned value is the same as <value>
toBeTrue()
- Checks if the returned value is true
toBeTruthy()
- Check if the value, when cast to a boolean, will be a truthy value
Truthy values are all values that aren't 0
, ''
(empty string), false
, null
, NaN
, undefined
or []
(empty array)*.
* Notice that when you run !![]
, it returns true
, but when you run [] == false
it also returns true
. It depends on how it is implemented. In other words: (!![]) === ([] == false)
On your example, toBe(true)
and toBeTrue()
will yield the same results.
Here is a function to do this for any number of columns.
def mean_first(df):
ncols = df.shape[1] # Get the number of columns
index = list(range(ncols)) # Create an index to reorder the columns
index.insert(0,ncols) # This puts the last column at the front
return(df.assign(mean=df.mean(1)).iloc[:,index]) # new df with last column (mean) first
You can use String#substring()
if(str != null && str.length() > 8) {
return str.substring(0, 8) + "...";
} else {
return str;
}
You could however make a function where you pass the maximum number of characters that can be displayed. The ellipsis would then cut in only if the width specified isn't enough for the string.
public String getShortString(String input, int width) {
if(str != null && str.length() > width) {
return str.substring(0, width - 3) + "...";
} else {
return str;
}
}
// abcdefgh...
System.out.println(getShortString("abcdefghijklmnopqrstuvwxyz", 11));
// abcdefghijk
System.out.println(getShortString("abcdefghijk", 11)); // no need to trim
Slightly modifying answer by @Yogeesh Seralathan. His answer works perfectly, just run these commands at once.
adb shell input keyevent 26 && adb shell input touchscreen swipe 930 880 930 380 && adb shell input text XXXX && adb shell input keyevent 66
I agree with everything that is said already, just trying to put some other words on it.
A delegate can be seen as a placeholder for a/some method(s).
By defining a delegate, you are saying to the user of your class, "Please feel free to assign, any method that matches this signature, to the delegate and it will be called each time my delegate is called".
Typical use is of course events. All the OnEventX delegate to the methods the user defines.
Delegates are useful to offer to the user of your objects some ability to customize their behavior. Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done.
Five options:
Use the free jsonutils web tool without installing anything.
If you have Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class.
Use the free jsonclassgenerator.exe
The web tool app.quicktype.io does not require installing anything.
The web tool json2csharp also does not require installing anything.
Pros and Cons:
jsonclassgenerator converts to PascalCase but the others do not.
app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.
I think you need OpenSessionInViewFilter to keep your session open during view rendering (but it is not too good practice).
My quick solution was to close all opened files in text editor area and then reopen them again from Solution Explorer.
Add this code in the activity from where you want to exit from the app on pressing back button:
@Override
public void onBackPressed() {
super.onBackPressed();
exitFromApp();
}
private void exitFromApp() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
<!DOCTYPE html>
<html>
<head>
<style>
.block-system-branding-block {
flex: 0 1 40%;
}
@media screen and (min-width: 48em) {
.block-system-branding-block {
flex: 0 1 420px;
margin: 2.5rem 0;
text-align: left;
}
}
.flex-containerrow {
display: flex;
}
.flex-containerrow > div {
justify-content: center;
align-items: center;
}
.flex-containercolumn {
display: flex;
flex-direction: column;
}
.flex-containercolumn > div {
width: 300px;
margin: 10px;
text-align: left;
line-height: 20px;
font-size: 16px;
}
.flex-containercolumn > site-slogan {font-size: 12px;}
.flex-containercolumn > div > span{ font-size: 12px;}
</style>
</head>
<body>
<div id="block-umami-branding" class="block-system block-
system-branding-block">
<div class="flex-containerrow">
<div>
<a href="/" rel="home" class="site-logo">
<img src="https://placehold.it/120x120" alt="Home">
</a>
</div><div class="flex-containerrow"><div class="flex-containercolumn">
<div class="site-name ">
<a href="/" title="Home" rel="home">This is my sitename</a>
</div>
<div class="site-slogan "><span>Department of Test | Ministry of Test |
TGoII</span></div>
</div></div>
</div>
</div>
</body>
</html>
- file:
path: /etc/some_directory
state: directory
mode: 0755
owner: someone
group: somegroup
That's the way you can actually also set the permissions, the owner and the group. The last three parameters are not obligatory.
The '\r' stands for "Carriage Return" - it's a holdover from the days of typewriters and really old printers. The best example is in Windows and other DOSsy OSes, where a newline is given as "\r\n". These are the instructions sent to an old printer to start a new line: first move the print head back to the beginning, then go down one.
Different OSes will use other newline sequences. Linux and OSX just use '\n'. Older Mac OSes just use '\r'. Wikipedia has a more complete list, but those are the important ones.
Hope this helps!
PS: As for why you get that weird output... Perhaps the console is moving the "cursor" back to the beginning of the line, and then overwriting the first bit with spaces or summat.
Creating a concurrent queue
let concurrentQueue = DispatchQueue(label: "queuename", attributes: .concurrent)
concurrentQueue.sync {
}
Create a serial queue
let serialQueue = DispatchQueue(label: "queuename")
serialQueue.sync {
}
Get main queue asynchronously
DispatchQueue.main.async {
}
Get main queue synchronously
DispatchQueue.main.sync {
}
To get one of the background thread
DispatchQueue.global(qos: .background).async {
}
Xcode 8.2 beta 2:
To get one of the background thread
DispatchQueue.global(qos: .default).async {
}
DispatchQueue.global().async {
// qos' default value is ´DispatchQoS.QoSClass.default`
}
If you want to learn about using these queues .See this answer
You are using a table variable i.e. you should declare the table. This is not a temporary table.
You create a temp table like so:
CREATE TABLE #customer
(
Name varchar(32) not null
)
You declare a table variable like so:
DECLARE @Customer TABLE
(
Name varchar(32) not null
)
Notice that a temp table is declared using # and a table variable is declared using a @. Go read about the difference between table variables and temp tables.
UPDATE:
Based on your comment below you are actually trying to create tables in a stored procedure. For this you would need to use dynamic SQL. Basically dynamic SQL allows you to construct a SQL Statement in the form of a string and then execute it. This is the ONLY way you will be able to create a table in a stored procedure. I am going to show you how and then discuss why this is not generally a good idea.
Now for a simple example (I have not tested this code but it should give you a good indication of how to do it):
CREATE PROCEDURE sproc_BuildTable
@TableName NVARCHAR(128)
,@Column1Name NVARCHAR(32)
,@Column1DataType NVARCHAR(32)
,@Column1Nullable NVARCHAR(32)
AS
DECLARE @SQLString NVARCHAR(MAX)
SET @SQString = 'CREATE TABLE '+@TableName + '( '+@Column1Name+' '+@Column1DataType +' '+@Column1Nullable +') ON PRIMARY '
EXEC (@SQLString)
GO
This stored procedure can be executed like this:
sproc_BuildTable 'Customers','CustomerName','VARCHAR(32)','NOT NULL'
There are some major problems with this type of stored procedure.
Its going to be difficult to cater for complex tables. Imagine the following table structure:
CREATE TABLE [dbo].[Customers] (
[CustomerID] [int] IDENTITY(1,1) NOT NULL,
[CustomerName] [nvarchar](64) NOT NULL,
[CustomerSUrname] [nvarchar](64) NOT NULL,
[CustomerDateOfBirth] [datetime] NOT NULL,
[CustomerApprovedDiscount] [decimal](3, 2) NOT NULL,
[CustomerActive] [bit] NOT NULL,
CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Customers] ADD CONSTRAINT [DF_Customers_CustomerApprovedDiscount] DEFAULT ((0.00)) FOR [CustomerApprovedDiscount]
GO
This table is a little more complex than the first example, but not a lot. The stored procedure will be much, much more complex to deal with. So while this approach might work for small tables it is quickly going to be unmanageable.
Creating tables require planning. When you create tables they should be placed strategically on different filegroups. This is to ensure that you don't cause disk I/O contention. How will you address scalability if everything is created on the primary file group?
Could you clarify why you need tables to be created dynamically?
UPDATE 2:
Delayed update due to workload. I read your comment about needing to create a table for each shop and I think you should look at doing it like the example I am about to give you.
In this example I make the following assumptions:
Let say this e-commerce site sells gaming consoles (i.e. Wii, PS3, XBOX360).
Looking at my assumptions I see a classical many-to-many relationship. A shop can sell many items (goods) and items (goods) can be sold at many shops. Let's break this down into tables.
First I would need a shop table to store all the information about the shop.
A simple shop table might look like this:
CREATE TABLE [dbo].[Shop](
[ShopID] [int] IDENTITY(1,1) NOT NULL,
[ShopName] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_Shop] PRIMARY KEY CLUSTERED
(
[ShopID] ASC
) WITH (
PAD_INDEX = OFF
, STATISTICS_NORECOMPUTE = OFF
, IGNORE_DUP_KEY = OFF
, ALLOW_ROW_LOCKS = ON
, ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
) ON [PRIMARY]
GO
Let's insert three shops into the database to use during our example. The following code will insert three shops:
INSERT INTO Shop
SELECT 'American Games R US'
UNION
SELECT 'Europe Gaming Experience'
UNION
SELECT 'Asian Games Emporium'
If you execute a SELECT * FROM Shop
you will probably see the following:
ShopID ShopName
1 American Games R US
2 Asian Games Emporium
3 Europe Gaming Experience
Right, so now let's move onto the Items (goods) table. Since the items/goods are products of various companies I am going to call the table product. You can execute the following code to create a simple Product table.
CREATE TABLE [dbo].[Product](
[ProductID] [int] IDENTITY(1,1) NOT NULL,
[ProductDescription] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
[ProductID] ASC
)WITH (PAD_INDEX = OFF
, STATISTICS_NORECOMPUTE = OFF
, IGNORE_DUP_KEY = OFF
, ALLOW_ROW_LOCKS = ON
, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Let's populate the products table with some products. Execute the following code to insert some products:
INSERT INTO Product
SELECT 'Wii'
UNION
SELECT 'PS3'
UNION
SELECT 'XBOX360'
If you execute SELECT * FROM Product
you will probably see the following:
ProductID ProductDescription
1 PS3
2 Wii
3 XBOX360
OK, at this point you have both product and shop information. So how do you bring them together? Well we know we can identify the shop by its ShopID primary key column and we know we can identify a product by its ProductID primary key column. Also, since each shop has a different price for each product we need to store the price the shop charges for the product.
So we have a table that maps the Shop to the product. We will call this table ShopProduct. A simple version of this table might look like this:
CREATE TABLE [dbo].[ShopProduct](
[ShopID] [int] NOT NULL,
[ProductID] [int] NOT NULL,
[Price] [money] NOT NULL,
CONSTRAINT [PK_ShopProduct] PRIMARY KEY CLUSTERED
(
[ShopID] ASC,
[ProductID] ASC
)WITH (PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
So let's assume the American Games R Us shop only sells American consoles, the Europe Gaming Experience sells all consoles and the Asian Games Emporium sells only Asian consoles. We would need to map the primary keys from the shop and product tables into the ShopProduct table.
Here is how we are going to do the mapping. In my example the American Games R Us has a ShopID value of 1 (this is the primary key value) and I can see that the XBOX360 has a value of 3 and the shop has listed the XBOX360 for $159.99
By executing the following code you would complete the mapping:
INSERT INTO ShopProduct VALUES(1,3,159.99)
Now we want to add all product to the Europe Gaming Experience shop. In this example we know that the Europe Gaming Experience shop has a ShopID of 3 and since it sells all consoles we will need to insert the ProductID 1, 2 and 3 into the mapping table. Let's assume the prices for the consoles (products) at the Europe Gaming Experience shop are as follows: 1- The PS3 sells for $259.99 , 2- The Wii sells for $159.99 , 3- The XBOX360 sells for $199.99.
To get this mapping done you would need to execute the following code:
INSERT INTO ShopProduct VALUES(3,2,159.99) --This will insert the WII console into the mapping table for the Europe Gaming Experience Shop with a price of 159.99
INSERT INTO ShopProduct VALUES(3,1,259.99) --This will insert the PS3 console into the mapping table for the Europe Gaming Experience Shop with a price of 259.99
INSERT INTO ShopProduct VALUES(3,3,199.99) --This will insert the XBOX360 console into the mapping table for the Europe Gaming Experience Shop with a price of 199.99
At this point you have mapped two shops and their products into the mapping table. OK, so now how do I bring this all together to show a user browsing the website? Let's say you want to show all the product for the European Gaming Experience to a user on a web page – you would need to execute the following query:
SELECT Shop.*
, ShopProduct.*
, Product.*
FROM Shop
INNER JOIN ShopProduct ON Shop.ShopID = ShopProduct.ShopID
INNER JOIN Product ON ShopProduct.ProductID = Product.ProductID
WHERE Shop.ShopID=3
You will probably see the following results:
ShopID ShopName ShopID ProductID Price ProductID ProductDescription
3 Europe Gaming Experience 3 1 259.99 1 PS3
3 Europe Gaming Experience 3 2 159.99 2 Wii
3 Europe Gaming Experience 3 3 199.99 3 XBOX360
Now for one last example, let's assume that your website has a feature which finds the cheapest price for a console. A user asks to find the cheapest prices for XBOX360.
You can execute the following query:
SELECT Shop.*
, ShopProduct.*
, Product.*
FROM Shop
INNER JOIN ShopProduct ON Shop.ShopID = ShopProduct.ShopID
INNER JOIN Product ON ShopProduct.ProductID = Product.ProductID
WHERE Product.ProductID =3 -- You can also use Product.ProductDescription = 'XBOX360'
ORDER BY Price ASC
This query will return a list of all shops which sells the XBOX360 with the cheapest shop first and so on.
You will notice that I have not added the Asian Games shop. As an exercise, add the Asian games shop to the mapping table with the following products: the Asian Games Emporium sells the Wii games console for $99.99 and the PS3 console for $159.99. If you work through this example you should now understand how to model a many-to-many relationship.
I hope this helps you in your travels with database design.
If you are using the Underscore.js library, you can use function keys:
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]
X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!
There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.
Source: classroomm.com
One thing that caused me a massive headache when using this code (might affect others and I wish that somebody had left a comment like this one here for me to read):
My solution will be to run the code (On timer event) from another hidden form that opens with the database.
Although this is an old thread, I had the same issue today, last week I updated some NuGet packages and although the MVC website worked OK on my dev machine when I published to the testing server it failed.
I read numerous posts but none worked. I finally compared the DLL's in my local bin to those in the testing server and found that the netstandard.dll was not uploaded, once uploaded the website worked OK, not sure why VS2017 web deploy did not publish the DLL.
Just something to look out for in case none of the above work for you.
getTimezoneOffset()
returns the opposite sign of the format required by the spec that you referenced.
This format is also known as ISO8601, or more precisely as RFC3339.
In this format, UTC is represented with a Z
while all other formats are represented by an offset from UTC. The meaning is the same as JavaScript's, but the order of subtraction is inverted, so the result carries the opposite sign.
Also, there is no method on the native Date
object called format
, so your function in #1 will fail unless you are using a library to achieve this. Refer to this documentation.
If you are seeking a library that can work with this format directly, I recommend trying moment.js. In fact, this is the default format, so you can simply do this:
var m = moment(); // get "now" as a moment
var s = m.format(); // the ISO format is the default so no parameters are needed
// sample output: 2013-07-01T17:55:13-07:00
This is a well-tested, cross-browser solution, and has many other useful features.
Try setting the HOME environment variable in Windows to your home folder (c:\users\username
).
( you can confirm that this is the problem by doing echo $HOME
in git bash and echo %HOME%
in cmd - latter might not be available )
You could go to SmallestDotNet using IE from the server. That will tell you the version and also provide a download link if you're out of date.
I've used Aspose.Words to do mail merge in .NET. I believe that they also have a Java version.
InputStream is = new FileInputStream("c://filename");
return is;
You could use the DirectoryInfo and FileInfo classes.
//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");
//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;
I had the same problem but solved it in this way:
df = pd.read_csv('your-array.csv', skiprows=[0])
Open Graph data:
<meta property="og:title" content="Title of your website | website.com"/>
<meta property="og:type" content="Most popular business directory of Bangladesh"/>
<meta property="og:url" content="http://www.website.com/"/>
<meta property="og:image" content="http://www.moumaachi.com/images/dhaka-city.jpg"/>
<meta property="og:site_name" content="@website"/>
<meta property="fb:admins" content="Author"/>
<meta property="og:description" content="website.com is your online business directory of Country"/>
Use getattr
to get an attribute from a name in a string. In other words, get the instance as
instance = getattr(modul, class_name)()
According to Hanselman - Using Directive and Assembly Loading... and other such articles there is technically no difference.
My preference is to put them outside of namespaces.
I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:
login : Debian Live User
password : live
I hope this helps
Double number = new Double("5.25");
Double tDouble =
new BigDecimal(number).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
this will return it will return 5.3
Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:
<location path="YourWebservice.asmx">
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</location>
Swift 4.2 / Xcode 10.1:
Just uncheck behavior Enabled in your storyboard -> attributes inspector.
With ES6 syntax
list = list.filter((x, i, a) => a.indexOf(x) === i)
x --> item in array
i --> index of item
a --> array reference, (in this case "list")
With ES5 syntax
list = list.filter(function (x, i, a) {
return a.indexOf(x) === i;
});
Browser Compatibility: IE9+
For Mac OS X
1) Update to Python 3.6.5 using the native app installer downloaded from the official Python language website https://www.python.org/downloads/
I've found that the installer is taking care of updating the links and symlinks for the new Python a lot better than homebrew.
2) Install a new certificate using "./Install Certificates.command" which is in the refreshed Python 3.6 directory
> cd "/Applications/Python 3.6/"
> sudo "./Install Certificates.command"
It is not possible to display alerts from the controller. Because MVC views and controllers are entirely separated from each other. You can only display information in the view only. So it is required to pass the information to be displayed from controller to view by using either ViewBag
, ViewData
or TempData
. If you are trying to display the content stored in TempData["Message"]
, It is possible to perform in the view page by adding few javascript lines.
<script>
alert(@TempData["Message"]);
</script>
for just debugging purpose, use one line code -
msg.writeTo(System.out);
as I learned while working with react.
props are used by a component to get data from external environment i.e another component ( pure, functional or class) or a general class or javascript/typescript code
states are used to manage the internal environment of a component means the data changes inside the component
This error may occurs in the case you use un-defined prefix such as:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabHost
XYZ:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</TabHost>
Android compiler does not know what is XYZ since it was not defined yet.
In your case, you should add below define to root node of the xml file.
xmlns:android="http://schemas.android.com/apk/res/android"
The non deprecated Objective-C version would be:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://apple.com"] options:@{} completionHandler:nil];
You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:
try:
import datetime
import foo
import sys
except ImportError:
pass
Let's say foo
doesn't exist. Then only datetime
will be imported.
What you can do is import the sys module at the beginning of the file, before the try/except statement:
import sys
try:
import numpy as np
import pyfits as pf
import scipy.ndimage as nd
import pylab as pl
import os
import heapq
from scipy.optimize import leastsq
except ImportError:
print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
sys.exit()
I've found three commands on how you can change your Git branch name, and these commands are a faster way to do that:
git branch -m old_branch new_branch # Rename branch locally
git push origin :old_branch # Delete the old branch
git push --set-upstream origin new_branch # Push the new branch, set local branch to track the new remote
If you need step-by-step you can read this great article:
You can create a temp table matching your proc output and insert into it.
CREATE TABLE #Temp (
Col1 INT
)
INSERT INTO #Temp
EXEC MyProc
String in C# is immutable. If you concatenate it with any string, you are actually making a new string, that is new string object ! But StringBuilder creates mutable string.
I was having a similar issue with my very first java program.
I was issuing this command
java HelloWorld.class
Which resulted in the same error.
Turns out you need to exclude the .class
java HelloWorld
Open Sublime Text console ? paste in opened field:
sublime.packages_path()
? Enter. You get result in console output.
This answer is relevant for April 2018. In the future, the data of this answer may be obsolete.
I'm not recommended @osiris answer. Arguments:
Packages
folder."The problem is that i cant find a way to set a fixed number of rows"
You don't need to set the number of rows. Use a TableModel
. A DefaultTableModel
in particular.
String col[] = {"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
DefaultTableModel tableModel = new DefaultTableModel(col, 0);
// The 0 argument is number rows.
JTable table = new JTable(tableModel);
Then you can add rows to the tableModel
with an Object[]
Object[] objs = {1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19};
tableModel.addRow(objs);
You can loop to add your Object[] arrays.
Note: JTable does not currently allow instantiation with the input data as an ArrayList
. It must be a Vector
or an array.
See JTable and DefaultTableModel. Also, How to Use JTable tutorial
"I created an arrayList from it and I somehow can't find a way to store this information into a JTable."
You can do something like this to add the data
ArrayList<FootballClub> originalLeagueList = new ArrayList<FootballClub>();
originalLeagueList.add(new FootballClub(1, "Arsenal", 35, 11, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(2, "Liverpool", 30, 9, 3, 3, 15, 34, 18, 16));
originalLeagueList.add(new FootballClub(3, "Chelsea", 30, 9, 2, 2, 15, 30, 11, 19));
originalLeagueList.add(new FootballClub(4, "Man City", 29, 9, 2, 4, 15, 41, 15, 26));
originalLeagueList.add(new FootballClub(5, "Everton", 28, 7, 1, 7, 15, 23, 14, 9));
originalLeagueList.add(new FootballClub(6, "Tottenham", 27, 8, 4, 3, 15, 15, 16, -1));
originalLeagueList.add(new FootballClub(7, "Newcastle", 26, 8, 5, 2, 15, 20, 21, -1));
originalLeagueList.add(new FootballClub(8, "Southampton", 23, 6, 4, 5, 15, 19, 14, 5));
for (int i = 0; i < originalLeagueList.size(); i++){
int position = originalLeagueList.get(i).getPosition();
String name = originalLeagueList.get(i).getName();
int points = originalLeagueList.get(i).getPoinst();
int wins = originalLeagueList.get(i).getWins();
int defeats = originalLeagueList.get(i).getDefeats();
int draws = originalLeagueList.get(i).getDraws();
int totalMatches = originalLeagueList.get(i).getTotalMathces();
int goalF = originalLeagueList.get(i).getGoalF();
int goalA = originalLeagueList.get(i).getGoalA();
in ttgoalD = originalLeagueList.get(i).getTtgoalD();
Object[] data = {position, name, points, wins, defeats, draws,
totalMatches, goalF, goalA, ttgoalD};
tableModel.add(data);
}
Try the following:
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
class Program
{
static void Main(string[] args)
{
var source = @"
<!DOCTYPE html>
<html>
<body>
<p>An image from W3Schools:</p>
<img
src=""http://www.w3schools.com/images/w3schools_green.jpg""
alt=""W3Schools.com""
width=""104""
height=""142"">
</body>
</html>";
StartBrowser(source);
Console.ReadLine();
}
private static void StartBrowser(string source)
{
var th = new Thread(() =>
{
var webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.DocumentCompleted +=
webBrowser_DocumentCompleted;
webBrowser.DocumentText = source;
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
static void
webBrowser_DocumentCompleted(
object sender,
WebBrowserDocumentCompletedEventArgs e)
{
var webBrowser = (WebBrowser)sender;
using (Bitmap bitmap =
new Bitmap(
webBrowser.Width,
webBrowser.Height))
{
webBrowser
.DrawToBitmap(
bitmap,
new System.Drawing
.Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(@"filename.jpg",
System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.
If you have a relationship setup in your database with a foriegn key restraint on BreedId don't you get that already?
So I can now call:
internal Album GetAlbum(int albumId)
{
return Albums.SingleOrDefault(a => a.AlbumID == albumId);
}
And in the code that calls that:
var album = GetAlbum(1);
foreach (Photo photo in album.Photos)
{
[...]
}
So in your instance you'd be calling something like dog.Breed.BreedName - as I said, this relies on your database being set up with these relationships.
As others have mentioned, the DataLoadOptions will help reduce the database calls if that's an issue.
When making an Android app in eclipse, just right-click on the res
folder, click New -> Other
, and select Android Icon Set
under Android.
This allows you to make more icons (or replace any existing ones) easily.
The steps mentioned by Jason are very good and should work. There is a little twist with SQL Developer, though. It caches the connection specifications (host, service name, port) the first time it reads the tnsnames.ora file. Then, it does not invalidate the specs when the original entry is removed from the tnsname.ora file. The cache persists even after SQL Developer has been terminated and restarted. This is not such an illogical way of handling the situation. Even if a tnsnames.ora file is temporarily unavailable, SQL Developer can still make the connection as long as the original specifications are still true. The problem comes with their next little twist. SQL Developer treats service names in the tnsnames.ora file as case-sensitive values when resolving the connection. So if you used to have an entry name ABCD.world in the file and you replaced it with an new entry named abcd.world, SQL Developer would NOT update its connection specs for ABCD.world - it will treat abcd.world as a different connection altogether. Why am I not surprised that an Oracle product would treat as case-sensitive the contents of an oracle-developed file format that is expressly case-insensitive?
This will return true if String only contains ASCII characters and false when it does not
Charset.forName("US-ASCII").newEncoder().canEncode(str)
If You want to remove non ASCII , here is the snippet:
if(!Charset.forName("US-ASCII").newEncoder().canEncode(str)) {
str = str.replaceAll("[^\\p{ASCII}]", "");
}
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
I think you're almost there, try removing the extra square brackets around the lst
's (Also you don't need to specify the column names when you're creating a dataframe from a dict like this):
import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)
percentile_list = pd.DataFrame(
{'lst1Title': lst1,
'lst2Title': lst2,
'lst3Title': lst3
})
percentile_list
lst1Title lst2Title lst3Title
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
...
If you need a more performant solution you can use np.column_stack
rather than zip
as in your first attempt, this has around a 2x speedup on the example here, however comes at bit of a cost of readability in my opinion:
import numpy as np
percentile_list = pd.DataFrame(np.column_stack([lst1, lst2, lst3]),
columns=['lst1Title', 'lst2Title', 'lst3Title'])
import tensorflow as tf
sess = tf.Session()
this code will show an Attribute error on version 2.x
to use version 1.x code in version 2.x
try this
import tensorflow.compat.v1 as tf
sess = tf.Session()
I have the same error but with different case. Let me quote the solution from here:
Luckly I also have the same set up on my desktop. I have installed first default instance and then Sql Express. Everything is fine for me for several days. Then I tried connecting the way you trying, i.e with MachineName\MsSqlServer to default instance and I got exctaly the same error.
So the solution is when you trying to connect to default instance you don't need to provide instance name.(well this is something puzzled me, why it is failing when we are giving instance name when it is a default instance? Is it some bug, don't know)
Just try with - PC-NAME and everything will be fine. PC-NAME is the MSSQLServer instance.
Edit : Well after reading your question again I realized that you are not aware of the fact that MSSQLSERVER is the default instance of Sql Server. And for connecting to default instance (MSSQLSERVER) you don't need to provide the instance name in connection string. The "MachineName" is itself means "MachineName\MSSQLSERVER".
Also check your URL rewriter. It may throw 404 if something "weird" was found.
I'd consider using a nullable types.
DateTime? myDate
instead of DateTime myDate
.
In case you are having this issue when working with WordPress control panel and using a ThemeRoller generated theme - be sure that you are using 1.7.3 Version of theme, 1.8.13 will not work. (If you look closely, the element is being rendered, but .ui-helper-hidden-accessible is causing it to not be displayed.
Current WP Version: 3.1.3
The incorrect profile could be fixed by:
Note: This solution uses the Qt Library.
Here is a minimal example I have written in C++ in order to demonstrate how to implement the proposed solution:
QPixmap pixmap;
pixmap.load("badProfileImage.png");
QFile file("goodProfileImage.png");
file.open(QIODevice::WriteOnly);
pixmap.save(&file, "PNG");
The complete source code of a GUI application based on this example is available on GitHub.
UPDATE FROM 05.12.2019: The answer was and is still valid, however there was a bug in the GUI application I have shared on GitHub, causing the output image to be empty. I have just fixed it and apologise for the inconvenience!
The main choice is do you want to treat the HTTP status code as part of your REST API or not.
Both ways work fine. I agree that, strictly speaking, one of the ideas of REST is that you should use the HTTP Status code as a part of your API (return 200 or 201 for a successful operation and a 4xx or 5xx depending on various error cases.) However, there are no REST police. You can do what you want. I have seen far more egregious non-REST APIs being called "RESTful."
At this point (August, 2015) I do recommend that you use the HTTP Status code as part of your API. It is now much easier to see the return code when using frameworks than it was in the past. In particular, it is now easier to see the non-200 return case and the body of non-200 responses than it was in the past.
The HTTP Status code is part of your api
You will need to carefully pick 4xx codes that fit your error conditions. You can include a rest, xml, or plaintext message as the payload that includes a sub-code and a descriptive comment.
The clients will need to use a software framework that enables them to get at the HTTP-level status code. Usually do-able, not always straight-forward.
The clients will have to distinguish between HTTP status codes that indicate a communications error and your own status codes that indicate an application-level issue.
The HTTP Status code is NOT part of your api
The HTTP status code will always be 200 if your app received the request and then responded (both success and error cases)
ALL of your responses should include "envelope" or "header" information. Typically something like:
envelope_ver: 1.0 status: # use any codes you like. Reserve a code for success. msg: "ok" # A human string that reflects the code. Useful for debugging. data: ... # The data of the response, if any.
This method can be easier for clients since the status for the response is always in the same place (no sub-codes needed), no limits on the codes, no need to fetch the HTTP-level status-code.
Here's a post with a similar idea: http://yuiblog.com/blog/2008/10/15/datatable-260-part-one/
Main issues:
Be sure to include version numbers so you can later change the semantics of the api if needed.
Document...
I usually manually set the port that I am listening on in the app.js
file (assuming you are using express.js
var server = app.listen(8080, function() {
console.log('Ready on port %d', server.address().port);
});
This will log Ready on port 8080
to your console.
On Java 14 you can do this
List<String> strings = Arrays.asList("one", "two", "three");
There is such possibility even if they are not Parent - Child relationship - and that's Flux. There is pretty good (for me personally) implementation for that called Alt.JS (with Alt-Container).
For example you can have Sidebar that is dependent on what is set in component Details. Component Sidebar is connected with SidebarActions and SidebarStore, while Details is DetailsActions and DetailsStore.
You could use then AltContainer like that
<AltContainer stores={{
SidebarStore: SidebarStore
}}>
<Sidebar/>
</AltContainer>
{this.props.content}
Which would keep stores (well I could use "store" instead of "stores" prop). Now, {this.props.content} CAN BE Details depending on the route. Lets say that /Details redirect us to that view. Details would have for example a checkbox that would change Sidebar element from X to Y if it would be checked.
Technically there is no relationship between them and it would be hard to do without flux. BUT WITH THAT it is rather easy.
Now let's get to DetailsActions. We will create there
class SiteActions {
constructor() {
this.generateActions(
'setSiteComponentStore'
);
}
setSiteComponent(value) {
this.dispatch({value: value});
}
}
and DetailsStore
class SiteStore {
constructor() {
this.siteComponents = {
Prop: true
};
this.bindListeners({
setSiteComponent: SidebarActions.COMPONENT_STATUS_CHANGED
})
}
setSiteComponent(data) {
this.siteComponents.Prop = data.value;
}
}
And now, this is the place where magic begin.
As You can see there is bindListener to SidebarActions.ComponentStatusChanged which will be used IF setSiteComponent will be used.
now in SidebarActions
componentStatusChanged(value){
this.dispatch({value: value});
}
We have such thing. It will dispatch that object on call. And it will be called if setSiteComponent in store will be used (that you can use in component for example during onChange on Button ot whatever)
Now in SidebarStore we will have
constructor() {
this.structures = [];
this.bindListeners({
componentStatusChanged: SidebarActions.COMPONENT_STATUS_CHANGED
})
}
componentStatusChanged(data) {
this.waitFor(DetailsStore);
_.findWhere(this.structures[0].elem, {title: 'Example'}).enabled = data.value;
}
Now here you can see, that it will wait for DetailsStore. What does it mean? more or less it means that this method need to wait for DetailsStoreto update before it can update itself.
tl;dr One Store is listening on methods in a store, and will trigger an action from component action, which will update its own store.
I hope it can help you somehow.
You can try Kafka Magic - it's free and you can write complex queries in JavaScript referencing message properties and metadata. Works with Avro serialization too
In your test code your are trying to pass App
to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:
1) Where the click handler calls a function passed as a prop, e.g.
class App extends Component {
myClickFunc = () => {
console.log('clickity clickcty');
this.props.someCallback();
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now pass in a spy function as a prop to the component, and assert that it is called:
describe('my sweet test', () => {
it('clicks it', () => {
const spy = jest.fn();
const app = shallow(<App someCallback={spy} />)
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
2) Where the click handler sets some state on the component, e.g.
class App extends Component {
state = {
aProperty: 'first'
}
myClickFunc = () => {
console.log('clickity clickcty');
this.setState({
aProperty: 'second'
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now make assertions about the state of the component, i.e.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const p = app.find('.App-intro')
p.simulate('click')
expect(app.state('aProperty')).toEqual('second');
})
})
A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 bits, BIT(64). For a boolean values, BIT(1) is pretty common.
GroupBox
is better.But not only group box, even you can use Panels
(System.Windows.Forms.Panel
).
after upgrading to Android 3.4.2 and FTC SDK5.2. I got these errors when building APK:
Android resource linking failed C:\Users\idsid\FTC\SkyStone\TeamCode\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1205: error: resource android:attr/fontVariationSettings not found. C:\Users\idsid\FTC\SkyStone\TeamCode\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml:1206: error: resource android:attr/ttcIndex not found. error: failed linking references.
What I did is to add following section to project build gradle and problem is fixed.
subprojects {
afterEvaluate {project ->
if (project.hasProperty("android")) {
android {
compileSdkVersion 28
buildToolsVersion '29.0.2'
}
}
}
}
Good luck.
It seems that for m, I dragged the files into the project and after that didn't work, clicked file "add files to project". Both were the incorrect approach. just drag it into the projects folder (in finder) that houses the other .h and .m files.
I've managed to achieve it with minimal effort (just as simple as with ASP.NET Core).
For that I use OWIN Startup.cs
file and Microsoft.Owin.Security.Jwt
library.
In order for the app to hit Startup.cs
we need to amend Web.config
:
<configuration>
<appSettings>
<add key="owin:AutomaticAppStartup" value="true" />
...
Here's how Startup.cs
should look:
using MyApp.Helpers;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;
[assembly: OwinStartup(typeof(MyApp.App_Start.Startup))]
namespace MyApp.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters()
{
ValidAudience = ConfigHelper.GetAudience(),
ValidIssuer = ConfigHelper.GetIssuer(),
IssuerSigningKey = ConfigHelper.GetSymmetricSecurityKey(),
ValidateLifetime = true,
ValidateIssuerSigningKey = true
}
});
}
}
}
Many of you guys use ASP.NET Core nowadays, so as you can see it doesn't differ a lot from what we have there.
It really got me perplexed first, I was trying to implement custom providers, etc. But I didn't expect it to be so simple. OWIN
just rocks!
Just one thing to mention - after I enabled OWIN Startup NSWag
library stopped working for me (e.g. some of you might want to auto-generate typescript HTTP proxies for Angular app).
The solution was also very simple - I replaced NSWag
with Swashbuckle
and didn't have any further issues.
Ok, now sharing ConfigHelper
code:
public class ConfigHelper
{
public static string GetIssuer()
{
string result = System.Configuration.ConfigurationManager.AppSettings["Issuer"];
return result;
}
public static string GetAudience()
{
string result = System.Configuration.ConfigurationManager.AppSettings["Audience"];
return result;
}
public static SigningCredentials GetSigningCredentials()
{
var result = new SigningCredentials(GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256);
return result;
}
public static string GetSecurityKey()
{
string result = System.Configuration.ConfigurationManager.AppSettings["SecurityKey"];
return result;
}
public static byte[] GetSymmetricSecurityKeyAsBytes()
{
var issuerSigningKey = GetSecurityKey();
byte[] data = Encoding.UTF8.GetBytes(issuerSigningKey);
return data;
}
public static SymmetricSecurityKey GetSymmetricSecurityKey()
{
byte[] data = GetSymmetricSecurityKeyAsBytes();
var result = new SymmetricSecurityKey(data);
return result;
}
public static string GetCorsOrigins()
{
string result = System.Configuration.ConfigurationManager.AppSettings["CorsOrigins"];
return result;
}
}
Another important aspect - I sent JWT Token via Authorization header, so typescript code looks for me as follows:
(the code below is generated by NSWag)
@Injectable()
export class TeamsServiceProxy {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : "https://localhost:44384";
}
add(input: TeamDto | null): Observable<boolean> {
let url_ = this.baseUrl + "/api/Teams/Add";
url_ = url_.replace(/[?&]$/, "");
const content_ = JSON.stringify(input);
let options_ : any = {
body: content_,
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Bearer " + localStorage.getItem('token')
})
};
See headers part - "Authorization": "Bearer " + localStorage.getItem('token')
So i tried the above :javascript which works :) However HAML wraps the generated code in CDATA like so:
<script type="text/javascript">
//<![CDATA[
$(document).ready( function() {
$('body').addClass( 'test' );
} );
//]]>
</script>
The following HAML will generate the typical tag for including (for example) typekit or google analytics code.
%script{:type=>"text/javascript"}
//your code goes here - dont forget the indent!
In Scala and Spark 2+, try this (assuming your column name is "s"):
df.select('s).as[String].collect
Answering this old question (for others which may help)
Configuring your httpd conf correctly will make the problem solved. Install any httpd server, if you don't have one.
Listing my config here.
[smilyface@box002 ~]$ cat /etc/httpd/conf/httpd.conf | grep shirts | grep -v "#"
ProxyPass /shirts-service http://local.box002.com:16743/shirts-service
ProxyPassReverse /shirts-service http://local.box002.com:16743/shirts-service
ProxyPass /shirts http://local.box002.com:16443/shirts
ProxyPassReverse /shirts http://local.box002.com:16443/shirts
...
...
...
edit the file as above and then restart httpd as below
[smilyface@box002 ~]$ sudo service httpd restart
And then request with with https
will work without exception.
Also request with http
will forward to https
! No worries.
The top answer here didn't quite fix the problem, although it's probably a necessary step:
sudo chown -R user:user ~/.local/share/jupyter
(user should be whoever is the logged in user running the notebook server) This changes the folder owner to the user running the server, giving it full access.
After doing this, the error message said it didn't have permission to create the checkpoint file in ~/.ipynb_checkpoints/ so I also changed ownership of that folder (which was previously root)
sudo chown -R user:user ~/.ipynb_checkpoints/
And then I was able to create and save a notebook!
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
var streetaddress = addy.substr(0, addy.indexOf('.'));
(You should read through a javascript tutorial, esp. the part about String functions)
I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).
This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.
Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.
Then under Tfvc: Location you can paste the location of the executable.
For 2017 it'll be
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
Or for 2019 (Preview)
C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe
After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.
After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone
pasted my repo:
Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen
Then chose the new method of authentication
Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).
Click Continue
Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.
Cheers!
I have the following config in my private project:
git config alias.auto 'commit -a -m "changes made from [device name]"'
That way, when I'm in a hurry I do
git auto
git push
And at least I know what device the commit was made from.
Just that i want to show how to do what do said @JafarKhQ in Kotlin for those who use kotlin that might help them and save theme time too:
so you have to create a companion objet to create new newInstance function
you can set the paremter of the function whatever you want. using
val args = Bundle()
you can set your args.
You can now use args.putSomthing
to add you args which u give as a prameter in your newInstance function.
putString(key:String,str:String)
to add string for example and so on
Now to get the argument you can use
arguments.getSomthing(Key:String)
=> like arguments.getString("1")
here is a full example
class IntervModifFragment : DialogFragment(), ModContract.View
{
companion object {
fun newInstance( plom:String,type:String,position: Int):IntervModifFragment {
val fragment =IntervModifFragment()
val args = Bundle()
args.putString( "1",plom)
args.putString("2",type)
args.putInt("3",position)
fragment.arguments = args
return fragment
}
}
...
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fillSpinerPlom(view,arguments.getString("1"))
fillSpinerType(view, arguments.getString("2"))
confirmer_virme.setOnClickListener({on_confirmClick( arguments.getInt("3"))})
val dateSetListener = object : DatePickerDialog.OnDateSetListener {
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int,
dayOfMonth: Int) {
val datep= DateT(year,monthOfYear,dayOfMonth)
updateDateInView(datep.date)
}
}
}
...
}
Now how to create your dialog you can do somthing like this in another class
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
like this for example
class InterListAdapter(private val context: Context, linkedList: LinkedList<InterItem> ) : RecyclerView.Adapter<InterListAdapter.ViewHolder>()
{
...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
...
holder.btn_update!!.setOnClickListener {
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
dialog.show(ft, ContentValues.TAG)
}
...
}
..
}
How bad is this?
function(obj){
for(var key in obj){
return false; // not empty
}
return true; // empty
}
You define the dependent module inside the setup.py of your own package with the "install_requires" option.
If your package needs to have some console script generated then you can use the "console_scripts" entry point in order to generate a wrapper script that will be placed within the 'bin' folder (e.g. of your virtualenv environment).
I think the best ranking is
1.node-schedule
2.later
3.crontab
and the sample of node-schedule is below:
var schedule = require("node-schedule");
var rule = new schedule.RecurrenceRule();
//rule.minute = 40;
rule.second = 10;
var jj = schedule.scheduleJob(rule, function(){
console.log("execute jj");
});
Maybe you can find the answer from node modules.
Uncaught ReferenceError: google is not defined error will be gone when removed the async defer from the map API script tag.
Everyone seems to starts off with a few greps and perl expressions and you sorta kinda get something that works for your particular dataset but you have no idea if it's imported the data correctly or not. I'm seriously surprised nobody's built a solid library that can convert between the two.
Here a list of ALL the differences in SQL syntax that I know about between the two file formats: The lines starting with:
are not used in MySQL
CREATE TABLE/INSERT INTO "table_name"
and MySQL uses CREATE TABLE/INSERT INTO table_name
INSERT INTO
clausesINSERT INTO
clauses't'
and 'f'
for booleans, MySQL uses 1
and 0
(a simple regex for this can fail when you have a string like: 'I do, you don't' inside your INSERT INTO
)AUTOINCREMENT
, MySQL uses AUTO_INCREMENT
Here is a very basic hacked up perl script which works for my dataset and checks for many more of these conditions that other perl scripts I found on the web. Nu guarantees that it will work for your data but feel free to modify and post back here.
#! /usr/bin/perl
while ($line = <>){
if (($line !~ /BEGIN TRANSACTION/) && ($line !~ /COMMIT/) && ($line !~ /sqlite_sequence/) && ($line !~ /CREATE UNIQUE INDEX/)){
if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/i){
$name = $1;
$sub = $2;
$sub =~ s/\"//g;
$line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n";
}
elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/i){
$line = "INSERT INTO $1$2\n";
$line =~ s/\"/\\\"/g;
$line =~ s/\"/\'/g;
}else{
$line =~ s/\'\'/\\\'/g;
}
$line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g;
$line =~ s/THIS_IS_TRUE/1/g;
$line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g;
$line =~ s/THIS_IS_FALSE/0/g;
$line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g;
print $line;
}
}
I had an issue with Modals as well. I should have declare jquery.min.js before bootstrap.min.js (in my layout page). From official site : "all plugins depend on jQuery (this means jQuery must be included before the plugin files)"
The array decays to a pointer when passed.
Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.
That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc
and all being library functions - something the compiler links to, rather than sees and reasons about the body of).
Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?
Symbian did have a AllocSize()
function that returned the size of an allocation with malloc()
; this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.
You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.
This part has problems:
Card* cardArray;
void Deck() {
cardArray = new Card[NUM_TOTAL_CARDS];
int cardCount = 0;
for (int i = 0; i > NUM_SUITS; i++) { //Error
for (int j = 0; j > NUM_RANKS; j++) { //Error
cardArray[cardCount] = Card(Card::Rank(i), Card::Suit(j) );
cardCount++;
}
}
}
cardArray
is a dynamic array, but not a member of Card
class. It is strange if you would like to initialize a dynamic array which is not member of the classvoid Deck()
is not constructor of class Deck since you missed the
scope resolution operator. You may be confused with defining the constructor and the function with name Deck
and return type void
.<
not >
otherwise, loop will never
be executed.Here is how you allow extra HTTP Verbs using the IIS Manager GUI.
In IIS Manager, select the site you wish to allow PUT or DELETE for.
Click the "Request Filtering" option. Click the "HTTP Verbs" tab.
Click the "Allow Verb..." link in the sidebar.
In the box that appears type "DELETE", click OK.
Click the "Allow Verb..." link in the sidebar again.
In the box that appears type "PUT", click OK.
Here's a very practical, true/false difference. The only difference between the two versions of the following code is that in the second version Person inherits from object. Other than that, the two versions are identical, but with different results:
Old-style classes
class Person():
_names_cache = {}
def __init__(self,name):
self.name = name
def __new__(cls,name):
return cls._names_cache.setdefault(name,object.__new__(cls,name))
ahmed1 = Person("Ahmed")
ahmed2 = Person("Ahmed")
print ahmed1 is ahmed2
print ahmed1
print ahmed2
>>> False
<__main__.Person instance at 0xb74acf8c>
<__main__.Person instance at 0xb74ac6cc>
>>>
New-style classes
class Person(object):
_names_cache = {}
def __init__(self,name):
self.name = name
def __new__(cls,name):
return cls._names_cache.setdefault(name,object.__new__(cls,name))
ahmed1 = Person("Ahmed")
ahmed2 = Person("Ahmed")
print ahmed2 is ahmed1
print ahmed1
print ahmed2
>>> True
<__main__.Person object at 0xb74ac66c>
<__main__.Person object at 0xb74ac66c>
>>>
First of all, public static
non-final
fields are evil. Spring does not allow injecting to such fields for a reason.
Your workaround is valid, you don't even need getter/setter, private
field is enough. On the other hand try this:
@Value("${my.name}")
public void setPrivateName(String privateName) {
Sample.name = privateName;
}
(works with @Autowired
/@Resource
). But to give you some constructive advice: Create a second class with private
field and getter instead of public static
field.
Just in case you want to see all of the gory details in human readable form, you can use:
import platform;
print(platform.sys.version);
Output for my system:
3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0]
Something very detailed but machine parsable would be to get the version_info
object from platform.sys
, instead, and then use its properties to take a predetermined course of action. For example:
import platform;
print(platform.sys.version_info)
Output on my system:
sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0)
Your regex is good altough I would replace it with the empty string
String resultString = subjectString.replaceAll("[\t\n\r]", "");
You expect a space between "text." and "And" right?
I get that space when I try the regex by copying your sample
"This is my text. "
So all is well here. Maybe if you just replace it with the empty string it will work. I don't know why you replace it with \s. And the alternation | is not necessary in a character class.
I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX
You can find complete project here: github-link
MainActivity.kt
class MainActivity : AppCompatActivity() {
val position = LatLng(-33.920455, 18.466941)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
with(mapView) {
// Initialise the MapView
onCreate(null)
// Set the map ready callback to receive the GoogleMap object
getMapAsync{
MapsInitializer.initialize(applicationContext)
setMapLocation(it)
}
}
}
private fun setMapLocation(map : GoogleMap) {
with(map) {
moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
addMarker(MarkerOptions().position(position))
mapType = GoogleMap.MAP_TYPE_NORMAL
setOnMapClickListener {
Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
}
}
}
override fun onResume() {
super.onResume()
mapView.onResume()
}
override fun onPause() {
super.onPause()
mapView.onPause()
}
override fun onDestroy() {
super.onDestroy()
mapView.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView.onLowMemory()
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="API_KEY_HERE" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.gms.maps.MapView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="@+id/mapView"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Consider the following code:
public String removeChar(String str, Integer n) {
String front = str.substring(0, n);
String back = str.substring(n+1, str.length());
return front + back;
}
The correct options are (in increasing order of recommendation):
# Single POSIX test command with -o operator (not recommended anymore).
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 -o "$stats" -eq 0 ]
# Two POSIX test commands joined in a list with ||.
# Quotes strongly recommended to guard against empty or undefined variables.
while [ "$stats" -gt 300 ] || [ "$stats" -eq 0 ]
# Two bash conditional expressions joined in a list with ||.
while [[ $stats -gt 300 ]] || [[ $stats -eq 0 ]]
# A single bash conditional expression with the || operator.
while [[ $stats -gt 300 || $stats -eq 0 ]]
# Two bash arithmetic expressions joined in a list with ||.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 )) || (( stats == 0 ))
# And finally, a single bash arithmetic expression with the || operator.
# $ optional, as a string can only be interpreted as a variable
while (( stats > 300 || stats == 0 ))
Some notes:
Quoting the parameter expansions inside [[ ... ]]
and ((...))
is optional; if the variable is not set, -gt
and -eq
will assume a value of 0.
Using $
is optional inside (( ... ))
, but using it can help avoid unintentional errors. If stats
isn't set, then (( stats > 300 ))
will assume stats == 0
, but (( $stats > 300 ))
will produce a syntax error.
The problem is that you are asking for an object of type ChannelSearchEnum
but what you actually have is an object of type List<ChannelSearchEnum>
.
You can achieve this with:
Type collectionType = new TypeToken<List<ChannelSearchEnum>>(){}.getType();
List<ChannelSearchEnum> lcs = (List<ChannelSearchEnum>) new Gson()
.fromJson( jstring , collectionType);
Like this
li span{
display:block;
width:50px;
word-break:break-all;
}
You can try something like this:
Image logo = Image.GetInstance("pathToTheImage")
logo.ScaleAbsolute(500, 300)
Try this code. You get android device name.
public static String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return model;
}
return manufacturer + " " + model;
}
I know there are already enough answers, but since this question comes up on Google searched for "detect adblock" at the topic, I wanted to provide some insight in case you're not using adsense.
Specifically, with this example you can detect if the default Adblock-list provided by Firefox Adblock is used. It takes advantage that in this blocklist there is an element blocked with the CSS id #bottomAd
. If I include such an element in the page and test for it's height, I know whether adblocking is active or not:
<!-- some code before -->
<div id="bottomAd" style="font-size: 2px;"> </div>
<!-- some code after -->
The rest is done via the usual jQuery suspect:
$(document).ready( function() {
window.setTimeout( function() {
var bottomad = $('#bottomAd');
if (bottomad.length == 1) {
if (bottomad.height() == 0) {
// adblocker active
} else {
// no adblocker
}
}
}, 1);
}
As can be seen, I'm using setTimeout
with at least a timeout of 1ms. I've tested this on various browsers and most of the time, directly checking for the element in ready
always returned 0; no matter whether the adblocker was active or not. I was having two ideas about this: either rendering wasn't yet done or Adblock didn't kick in yet. I didn't bother to investigate further.
Your example creates multiple key: value pairs if using fromkeys
. If you don't want this, you can use one key and create an alias for the key. For example if you are using a register map, your key can be the register address and the alias can be register name. That way you can perform read/write operations on the correct register.
>>> mydict = {}
>>> mydict[(1,2)] = [30, 20]
>>> alias1 = (1,2)
>>> print mydict[alias1]
[30, 20]
>>> mydict[(1,3)] = [30, 30]
>>> print mydict
{(1, 2): [30, 20], (1, 3): [30, 30]}
>>> alias1 in mydict
True
The first suggestion in latkin's answer seems good, although I would suggest the less long-winded way below.
PS c:\temp> $global:test="one"
PS c:\temp> $test
one
PS c:\temp> function changet() {$global:test="two"}
PS c:\temp> changet
PS c:\temp> $test
two
His second suggestion however about being bad programming practice, is fair enough in a simple computation like this one, but what if you want to return a more complicated output from your variable? For example, what if you wanted the function to return an array or an object? That's where, for me, PowerShell functions seem to fail woefully. Meaning you have no choice other than to pass it back from the function using a global variable. For example:
PS c:\temp> function changet([byte]$a,[byte]$b,[byte]$c) {$global:test=@(($a+$b),$c,($a+$c))}
PS c:\temp> changet 1 2 3
PS c:\temp> $test
3
3
4
PS C:\nb> $test[2]
4
I know this might feel like a bit of a digression, but I feel in order to answer the original question we need to establish whether global variables are bad programming practice and whether, in more complex functions, there is a better way. (If there is one I'd be interested to here it.)
Actually what Luis proposed did not work for me. I had to figure out another way. This is what helped me. Might help you too. Links:
*.getEncoded(): https://docs.oracle.com/javase/7/docs/api/java/security/Key.html
Encoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html
Decoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html
Code snippets: For encoding:
String temp = new String(Base64.getEncoder().encode(key.getEncoded()));
For decoding:
byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");
With Express 3.0:
<%- include myview.ejs %>
the path is relative from the caller who includes the file, not from the views directory set with app.set("views", "path/to/views")
.
(Update: the newest syntax for ejs v3.0.1 is <%- include('myview.ejs') %>
)
Not directly. In fact, form elements in general are either problematic or impossible to style using CSS alone. the best approach is to:
javascript
var labels = $("ul.radioButtons).delegate("input", "keyup", function () { //keyboard use
if (this.checked) {
select($(this).parent());
}
}).find("label").bind("click", function (event) { //mouse use
select($(this));
});
function select(el) {
labels.removeClass("selected");
el.addClass("selected");
}
html
<ul class="radioButtons">
<li>
<label for="employee1">
employee1
<input type="radio" id="employee1" name="employee" />
</label>
</li>
<li>
<label for="employee2">
employee1
<input type="radio" id="employee2" name="employee" />
</label>
</li>
</ul>
Using the jQuery timer will also allow you to have a name associated with the timers that are attached to the object. So you could attach several timers to an object and stop any one of them.
$("#myid").oneTime(1000, "mytimer1" function() {
$("#something").hide();
}).oneTime(2000, "mytimer2" function() {
$("#somethingelse").show();
});
$("#myid").stopTime("mytimer2");
The eval function (and its relatives, Function, setTimeout, and setInterval) provide access to the JavaScript compiler. This is sometimes necessary, but in most cases it indicates the presence of extremely bad coding. The eval function is the most misused feature of JavaScript.
In addition to NateW's answer, if you have hyphens in your css class name, you should wrap that class within (single) quotes:
<th
class="initial "
v-on:click="myFilter"
v-bind:class="{ 'is-active' : isActive}"
>
<span class="wkday">M</span>
</th>
See this topic for more on the subject.
Try with "update tablet set (row='value' where id=0001'), (row='value2' where id=0002'), ...
I've faced the same issue, the possible reason is due to parallel execution of testng and the solution is to add Priority option or simply update preserve-order="true" in your testng.xml.
<test name="Firefox Test" preserve-order="true">
I've had a similar issue, that took a bit to troubleshoot, so I thought to share it:
The namespace that could not be resolved in my case was Company.Project.Common.Models.EF. I had added a file in a new Company.Project.BusinessLogic.Common namespace.
The majority of the files were having a
using Company.Project;
And then referencing the models as Common.Models.EF. All the files that also had a
using Company.Project.BusinessLogic;
Were failing as VS could not determine which namespace to use.
The solution has been to change the second namespace to Company.Project.BusinessLogic.CommonServices
%hash1 = (%hash1, %hash2) ## or else ... @hash1{keys %hash2} = values %hash2; ## or with references ... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
undef
, zero, empty string, false
, falsy ...)1 * (aka associative-array, aka dictionary)
You could use if type(ele) is dict
or use isinstance(ele, dict)
which would work if you had subclassed dict
:
d = {'abc': 'abc', 'def': {'ghi': 'ghi', 'jkl': 'jkl'}}
for element in d.values():
if isinstance(element, dict):
for k, v in element.items():
print(k,' ',v)
For understanding templates, it's of huge advantage to get the terminology straight because the way you speak about them determines the way to think about them.
Specifically, Area
is not a template class, but a class template. That is, it is a template from which classes can be generated. Area<int>
is such a class (it's not an object, but of course you can create an object from that class in the same ways you can create objects from any other class). Another such class would be Area<char>
. Note that those are completely different classes, which have nothing in common except for the fact that they were generated from the same class template.
Since Area
is not a class, you cannot derive the class Rectangle
from it. You only can derive a class from another class (or several of them). Since Area<int>
is a class, you could, for example, derive Rectangle
from it:
class Rectangle:
public Area<int>
{
// ...
};
Since Area<int>
and Area<char>
are different classes, you can even derive from both at the same time (however when accessing members of them, you'll have to deal with ambiguities):
class Rectangle:
public Area<int>,
public Area<char>
{
// ...
};
However you have to specify which classed to derive from when you define Rectangle
. This is true no matter whether those classes are generated from a template or not. Two objects of the same class simply cannot have different inheritance hierarchies.
What you can do is to make Rectangle
a template as well. If you write
template<typename T> class Rectangle:
public Area<T>
{
// ...
};
You have a template Rectangle
from which you can get a class Rectangle<int>
which derives from Area<int>
, and a different class Rectangle<char>
which derives from Area<char>
.
It may be that you want to have a single type Rectangle
so that you can pass all sorts of Rectangle
to the same function (which itself doesn't need to know the Area type). Since the Rectangle<T>
classes generated by instantiating the template Rectangle
are formally independent of each other, it doesn't work that way. However you can make use of multiple inheritance here:
class Rectangle // not inheriting from any Area type
{
// Area independent interface
};
template<typename T> class SpecificRectangle:
public Rectangle,
public Area<T>
{
// Area dependent stuff
};
void foo(Rectangle&); // A function which works with generic rectangles
int main()
{
SpecificRectangle<int> intrect;
foo(intrect);
SpecificRectangle<char> charrect;
foo(charrect);
}
If it is important that your generic Rectangle
is derived from a generic Area
you can do the same trick with Area
too:
class Area
{
// generic Area interface
};
class Rectangle:
public virtual Area // virtual because of "diamond inheritance"
{
// generic rectangle interface
};
template<typename T> class SpecificArea:
public virtual Area
{
// specific implementation of Area for type T
};
template<typename T> class SpecificRectangle:
public Rectangle, // maybe this should be virtual as well, in case the hierarchy is extended later
public SpecificArea<T> // no virtual inheritance needed here
{
// specific implementation of Rectangle for type T
};
I recommend using dynamic programming (DP) for computing binomial coefficients. In contrast to direct computation, it avoids multiplication and division of large numbers. In addition to recursive solution, it stores previously solved overlapping sub-problems in a table for fast look-up. The code below shows bottom-up (tabular) DP and top-down (memoized) DP implementations for computing binomial coefficients.
def binomial_coeffs1(n, k):
#top down DP
if (k == 0 or k == n):
return 1
if (memo[n][k] != -1):
return memo[n][k]
memo[n][k] = binomial_coeffs1(n-1, k-1) + binomial_coeffs1(n-1, k)
return memo[n][k]
def binomial_coeffs2(n, k):
#bottom up DP
for i in range(n+1):
for j in range(min(i,k)+1):
if (j == 0 or j == i):
memo[i][j] = 1
else:
memo[i][j] = memo[i-1][j-1] + memo[i-1][j]
#end if
#end for
#end for
return memo[n][k]
def print_array(memo):
for i in range(len(memo)):
print('\t'.join([str(x) for x in memo[i]]))
#main
n = 5
k = 2
print("top down DP")
memo = [[-1 for i in range(6)] for j in range(6)]
nCk = binomial_coeffs1(n, k)
print_array(memo)
print("C(n={}, k={}) = {}".format(n,k,nCk))
print("bottom up DP")
memo = [[-1 for i in range(6)] for j in range(6)]
nCk = binomial_coeffs2(n, k)
print_array(memo)
print("C(n={}, k={}) = {}".format(n,k,nCk))
Note: the size of the memo table is set to a small value (6) for display purposes, it should be increased if you are computing binomial coefficients for large n and k.
Months in Calendar object start from 0
0 = January = Calendar.JANUARY
1 = february = Calendar.FEBRUARY
Before answering your question:
If you do not have a Person
class, first you must consider whether you want to create a Person
class. Do you plan to reuse the concept of a Person
very often? If so, you should create a Person
class. (You have access to this data in the form of a passed-in variable and you don't care about being messy and sloppy.)
To answer your question:
You have access to their birthyear, so in that case you likely have a Person
class with a someperson.birthdate
field. In that case, you have to ask yourself, is someperson.age
a value that is reusable?
The answer is yes. We often care about age more than the birthdate, so if the birthdate is a field, age should definitely be a derived field. (A case where we would not do this: if we were calculating values like someperson.chanceIsFemale
or someperson.positionToDisplayInGrid
or other irrelevant values, we would not extend the Person
class; you just ask yourself, "Would another program care about the fields I am thinking of extending the class with?" The answer to that question will determine if you extend the original class, or make a function (or your own class like PersonAnalysisData
or something).)
As I cannot comment, so I will write this as an answer!
Please understand the difference between css selector ":hover" and the hover event!
":hover" is a css selector and was indeed removed with the event when used like this $("#elementId").is(":hover")
, but in it's meaning it has really nothing to do with the jQuery event hover.
if you code $("#elementId:hover")
, the element will only be selected when you hover with the mouse. the above statement will work with all jQuery versions as your selecting this element with pure and legit css selection.
On the other hand the event hover which is
$("#elementId").hover(
function() {
doSomething();
}
);
is indeed deprecaded as jQuery 1.8 here the state from jQuery website:
When the event name "hover" is used, the event subsystem converts it to "mouseenter mouseleave" in the event string. This is annoying for several reasons:
Semantics: Hovering is not the same as the mouse entering and leaving an element, it implies some amount of deceleration or delay before firing. Event name: The event.type returned by the attached handler is not hover, but either mouseenter or mouseleave. No other event does this. Co-opting the "hover" name: It is not possible to attach an event with the name "hover" and fire it using .trigger("hover"). The docs already call this name "strongly discouraged for new code", I'd like to deprecate it officially for 1.8 and eventually remove it.
Why they removed the usage is(":hover") is unclear but oh well, you can still use it like above and here is a little hack to still use it.
(function ($) {
/**
* :hover selector was removed from jQuery 1.8+ and cannot be used with .is(":hover")
* but using it in this way it works as :hover is css selector!
*
**/
$.fn.isMouseOver = function() {
return $(this).parent().find($(this).selector + ":hover").length > 0;
};
})(jQuery);
Oh and I would not recomment the timeout version as this brings a lot of complexity, use timeout functionalities for this kind of stuff if there is no other way and believe me, in 95% percent of all cases there is another way!
Hope I could help a couple people out there.
Greetz Andy
Are you trying to echo out a style or an inline style? An inline style would be like
echo "<p style=\"font-color: #ff0000;\">text here</p>";
window.location
always refers to the location of the current window. Changing it will affect only the current window.
One thing that can be done is forcing a click on the link after setting its target
attribute to _blank
:
Check this: http://www.techfoobar.com/2012/jquery-programmatically-clicking-a-link-and-forcing-the-default-action
Disclaimer: Its my blog.
Addition to above all simplified responses.
If you are working with files in bash script, it's better to use file descriptor.
For example: If you want to read and write from/to the file "test.txt", use the file descriptor as show below:
FILE=$1 # give the name of file in the command line
exec 5<>$FILE # '5' here act as the file descriptor
# Reading from the file line by line using file descriptor
while read LINE; do
echo "$LINE"
done <&5
# Writing to the file using descriptor
echo "Adding the date: `date`" >&5
exec 5<&- # Closing a file descriptor
If you have python 3 installed then add this line to the top of the file:
#!/usr/bin/env python3
You should also check the file have the right to be execute. chmod +x file.py
For more details, follow the official forum:
https://askubuntu.com/questions/761365/how-to-run-a-python-program-directly
There are numerous ways to store credentials while still using boto3.resource(). I'm using the AWS CLI method myself. It works perfectly.
Check out TrueZip.
It does exactly what you want (to edit files inline inside a jar file), through a virtual file system API. It also supports nested archives (jar inside a jar) as well.
In my case, when I changed the wshttpbinding
protocol from https
to http
it started working.
You need xlutils.copy
. Try something like this:
from xlutils.copy import copy
w = copy('book1.xls')
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')
Keep in mind you can't overwrite cells by default as noted in this question.
Based on user @andygjp's answer, its better if you override the base Db.SaveChanges()
method and add a function to override any date which does not fall between SqlDateTime.MinValue and SqlDateTime.MaxValue.
Here is the sample code
public class MyDb : DbContext
{
public override int SaveChanges()
{
UpdateDates();
return base.SaveChanges();
}
private void UpdateDates()
{
foreach (var change in ChangeTracker.Entries().Where(x => (x.State == EntityState.Added || x.State == EntityState.Modified)))
{
var values = change.CurrentValues;
foreach (var name in values.PropertyNames)
{
var value = values[name];
if (value is DateTime)
{
var date = (DateTime)value;
if (date < SqlDateTime.MinValue.Value)
{
values[name] = SqlDateTime.MinValue.Value;
}
else if (date > SqlDateTime.MaxValue.Value)
{
values[name] = SqlDateTime.MaxValue.Value;
}
}
}
}
}
}
Taken from the user @sky-dev's comment on https://stackoverflow.com/a/11297294/9158120
In short:
import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)
Many examples on the matplotlib website. The one I most commonly use is here
A regular expressoin would be the easiest way. If you write the regex the correct way, you wont need multiple calls.
Change it to this:
string s = System.Text.RegularExpressions.Regex.Replace(s, @"\s{2,}", " ");
The real question is why does it generate a 500 error. If it is related to any input parameters, then I would argue that it should be handled internally and returned as a 400 series error. Generally a 400, 404 or 406 would be appropriate to reflect bad input since the general convention is that a RESTful resource is uniquely identified by the URL and a URL that cannot generate a valid response is a bad request (400) or similar.
If the error is caused by anything other than the inputs explicitly or implicitly supplied by the request, then I would say a 500 error is likely appropriate. So a failed database connection or other unpredictable error is accurately represented by a 500 series error.
Unless you plan to import huge .sql files, just read the entire file into memory, and run it as a query.
It's been a while since I've used PHP, so, pseudo code:
all_query = read_file("/my/file.sql")
con = mysql_connect("localhost")
con.mysql_select_db("mydb")
con.mysql_query(all_query)
con.close()
Unless the files are huge (say, over several megabytes), there's no reason to execute it line-at-a-time, or try and split it into multiple queries (by splitting using ;
, which as I commented on cam8001's answer, will break if the query has semi-colons within strings)..
I've found out the solution! Thanks to Firebug ;)
//"markers" is an array that I declared which contains all the marker of the map
//"i" is the index of the marker in the array that I want to trigger the OnClick event
//V2 version is:
GEvent.trigger(markers[i], 'click');
//V3 version is:
google.maps.event.trigger(markers[i], 'click');
Seems, css transforms can be used
"‘transform’ property establishes a new local coordinate system at the element",
but ... this is not cross-browser, seems only Opera works correctly
Here's a Bash one-liner that compares the current branch's HEAD commit hash against its remote upstream branch, no heavy git fetch
or git pull --dry-run
operations required:
[ $(git rev-parse HEAD) = $(git ls-remote $(git rev-parse --abbrev-ref @{u} | \
sed 's/\// /g') | cut -f1) ] && echo up to date || echo not up to date
Here's how this somewhat dense line is broken down:
$(x)
Bash command-substitution syntax.git rev-parse --abbrev-ref @{u}
returns an abbreviated upstream ref (e.g. origin/master
), which is then converted into space-separated fields by the piped sed
command, e.g. origin master
.git ls-remote
which returns the head commit of the remote branch. This command will communicate with the remote repository. The piped cut
command extracts just the first field (the commit hash), removing the tab-separated reference string.git rev-parse HEAD
returns the local commit hash.[ a = b ] && x || y
completes the one-liner: this is a Bash string-comparison =
within a test construct [ test ]
, followed by and-list and or-list constructs && true || false
.To run once, daily at 10PM you should do something like this:
0 22 * * *
Full size image: http://i.stack.imgur.com/BeXHD.jpg
Source: softpanorama.org
None of the above worked for me. And it took me long to figure it out, hopefully this helps the next guy.
I'm using Ubuntu 12.04 LTS with mailutils v2.1.
I found this solutions somewhere on the net, don't know where, can't find it again:
-aFrom:[email protected]
Full Command used:
cat /root/Reports/ServerName-Report-$DATE.txt | mail -s "Server-Name-Report-$DATE" [email protected] -aFrom:[email protected]
I find this particularly useful for when you want to 'store' a function call.
For example, suppose I have some unit tests for a function 'add':
def add(a, b): return a + b
tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
for test, result in tests.items():
print 'test: adding', test, '==', result, '---', add(*test) == result
There is no other way to call add, other than manually doing something like add(test[0], test[1])
, which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.
Another place this is useful is for defining Factory objects (objects that create objects for you).
Suppose you have some class Factory, that makes Car objects and returns them.
You could make it so that myFactory.make_car('red', 'bmw', '335ix')
creates Car('red', 'bmw', '335ix')
, then returns it.
def make_car(*args):
return Car(*args)
This is also useful when you want to call a superclass' constructor.
Here is another option: =OFFSET($A$1;COUNTA(A:A)-1;0)
Jus use this code on Document.read()
$.fn.modal.Constructor.prototype.enforceFocus = function () {};
Here's a dynamic SQL approach that also gives you the schema as well:
DECLARE @sql nvarchar(MAX)
SELECT
@sql = COALESCE(@sql + ' UNION ALL ', '') +
'SELECT
''' + s.name + ''' AS ''Schema'',
''' + t.name + ''' AS ''Table'',
COUNT(*) AS Count
FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name)
FROM sys.schemas s
INNER JOIN sys.tables t ON t.schema_id = s.schema_id
ORDER BY
s.name,
t.name
EXEC(@sql)
If needed, it would be trivial to extend this to run over all databases in the instance (join to sys.databases
).
If you are looking for something in production winston is probably the best choice.
If you just want to do dev stuff quickly, output directly to a file (I think this works only for *nix systems):
nohup node simple-server.js > output.log &
functional programming
const fs = require('fs')
const path = require('path')
const R = require('ramda')
const getDirectories = pathName => {
const isDirectory = pathName => fs.lstatSync(pathName).isDirectory()
const mapDirectories = pathName => R.map(name => path.join(pathName, name), fs.readdirSync(pathName))
const filterDirectories = listPaths => R.filter(isDirectory, listPaths)
return {
paths:R.pipe(mapDirectories)(pathName),
pathsFiltered: R.pipe(mapDirectories, filterDirectories)(pathName)
}
}
Now you can get time for the current location but for this you have to set the system's persistent default time zone.setTimeZone(String timeZone)
which can be get from
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
TimeZone current = calendar.getTimeZone();
setAutoTimeEnabled(boolean enabled)
Sets whether or not wall clock time should sync with automatic time updates from NTP.
TimeManager timeManager = TimeManager.getInstance();
// Use 24-hour time
timeManager.setTimeFormat(TimeManager.FORMAT_24);
// Set clock time to noon
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 12);
long timeStamp = calendar.getTimeInMillis();
timeManager.setTime(timeStamp);
I was looking for that type of answer I read your answer but didn't satisfied and it was bit old. I found the new solution and share it. :)
For more information visit: https://developer.android.com/things/reference/com/google/android/things/device/TimeManager.html
wrap the table in a div with class="container"
div.container {
width: 100%;
overflow-x: auto;
}
then
#table_id tr td {
white-space:nowrap;
}
result
Run the following in Jupyter,
import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
If you've set up your environment properly, you'll get the following output in the terminal where you ran "jupyter notebook",
2017-10-05 14:51:46.335323: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\gpu\gpu_device.cc:1030] Creating TensorFlow device (/gpu:0) -> (device: 0, name: Quadro K620, pci bus id: 0000:02:00.0)
Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: Quadro K620, pci bus id: 0000:02:00.0
2017-10-05 14:51:46.337418: I c:\tf_jenkins\home\workspace\release-win\m\windows-gpu\py\35\tensorflow\core\common_runtime\direct_session.cc:265] Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: Quadro K620, pci bus id: 0000:02:00.0
You can see here I'm using TensorFlow with an Nvidia Quodro K620.
here the writer suggests this:
public boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException | InterruptedException e) { e.printStackTrace(); }
return false;
}
Possible Questions
read the link. its seems very good
EDIT: in my exp of using it, it's not as fast as this method:
public boolean isOnline() {
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
they are a bit different but in the functionality for just checking the connection to internet the first method may become slow due to the connection variables.
Out-File
defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii
to change this behavior. In your case
Out-File -Encoding Ascii -append textfile.txt.
Add-Content
uses Ascii and also appends by default.
"This is a test" | Add-Content textfile.txt.
As for the lack of newline: You did not send a newline so it will not write one to file.
Your exception says it all "Connection reset". The connection between your java process and the db server was lost, which could have happened for almost any reason(like network issues). The SQLRecoverableException just means that its recoverable, but the root cause is connection reset.
Warning invalid argument supplied for foreach()
display tweets.
go to /wp-content/plugins/display-tweets-php
.
Then insert this code on line number 591, It will run perfectly.
if (is_array($tweets)) {
foreach ($tweets as $tweet)
{
...
}
}
You have to add
<script>jQuery.noConflict();</script>
after
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
You can use pandas
, by transforming the list
to a pd.Series
then simply use .value_counts()
import pandas as pd
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
a_cnts = pd.Series(a).value_counts().to_dict()
Input >> a_cnts["1"], a_cnts["10"]
Output >> (6, 2)
Look at the find command.
What you are looking for is something like
find . -name "*.xls" -type f -exec program
Post edit
find . -name "*.xls" -type f -exec xls2csv '{}' '{}'.csv;
will execute xls2csv file.xls file.xls.csv
Closer to what you want.
This answer is similar to @PaulMcG's answer but doesn't require sorting the input.
For those into functional programming, groupBy
can be written in one line (not including imports!), and unlike itertools.groupby
it doesn't require the input to be sorted:
from functools import reduce # import needed for python3; builtin in python2
from collections import defaultdict
def groupBy(key, seq):
return reduce(lambda grp, val: grp[key(val)].append(val) or grp, seq, defaultdict(list))
(The reason for ... or grp
in the lambda
is that for this reduce()
to work, the lambda
needs to return its first argument; because list.append()
always returns None
the or
will always return grp
. I.e. it's a hack to get around python's restriction that a lambda can only evaluate a single expression.)
This returns a dict whose keys are found by evaluating the given function and whose values are a list of the original items in the original order. For the OP's example, calling this as groupBy(lambda pair: pair[1], input)
will return this dict:
{'KAT': [('11013331', 'KAT'), ('9843236', 'KAT')],
'NOT': [('9085267', 'NOT'), ('11788544', 'NOT')],
'ETH': [('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH')]}
And as per @PaulMcG's answer the OP's requested format can be found by wrapping that in a list comprehension. So this will do it:
result = {key: [pair[0] for pair in values],
for key, values in groupBy(lambda pair: pair[1], input).items()}
My favorite is this one-liner:
git log --oneline $( git fsck --no-reflogs | awk '/dangling commit/ {print $3}' )
This is basically the same idea as this answer but much shorter. Of course, you can still add --graph
to get a tree-like display.
When you have found the commit in the list, apply with
git stash apply THE_COMMIT_HASH_FOUND
For me, using --no-reflogs
did reveal the lost stash entry, but --unreachable
(as found in many other answers) did not.
Run it on git bash when you are under Windows.
Credits: The details of the above commands are taken from https://gist.github.com/joseluisq/7f0f1402f05c45bac10814a9e38f81bf