Are you familiar with the DataSet
class?
The DataSet
can also load
XML documents and you may find it easier to iterate.
http://msdn.microsoft.com/en-us/library/system.data.dataset.readxml.aspx
DataSet dt = new DataSet();
dt.ReadXml(@"c:\test.xml");
one way to accomplish this to have a server side application that waits for the data. The data can be sent using HttpRequest
objects in Java or you can write your own TCP/IP
data transfer utility. Data can be sent using JSON
format or any other format that you think is suitable. Also data can be encrypted before sending to server if it contains sensitive information. All Server application have to do is just wait for HttpRequests
to come in and parse the data and store it anywhere you want.
SWIFT 4
view.layer.contents = #imageLiteral(resourceName: "webbg").cgImage
Create custom context initializer:
public class MyDbContextInitializer : MigrateDatabaseToLatestVersion<MyDbContext, Migrations.Configuration>
{
public override void InitializeDatabase(MyDbContext context)
{
bool exists = context.Database.Exists();
base.InitializeDatabase(context);
if (!exists)
{
MyDbSeed.Seed(context);
}
}
}
Note that Migrations.Configuration is a class generating by migration command line in Package Manager Console. You may need to change internal to public modifier of the Migrations.Configuration class.
And register it from your OmModelCreating:
public partial class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<MyDbContext>(new MyDbContextInitializer());
//other code for creating model
}
}
using dollar:
Iterable<Character> chars = $('a', 'z'); // 'a', 'b', c, d .. z
given chars
you can build a "shuffled" range of characters:
Iterable<Character> shuffledChars = $('a', 'z').shuffle();
then taking the first n
chars, you get a random string of length n
. The final code is simply:
public String randomString(int n) {
return $('a', 'z').shuffle().slice(n).toString();
}
NB: the condition n > 0
is cheched by slice
EDIT
as Steve correctly pointed out, randomString
uses at most once each letter. As workaround
you can repeat the alphabet m
times before call shuffle
:
public String randomStringWithRepetitions(int n) {
return $('a', 'z').repeat(10).shuffle().slice(n).toString();
}
or just provide your alphabet as String
:
public String randomStringFromAlphabet(String alphabet, int n) {
return $(alphabet).shuffle().slice(n).toString();
}
String s = randomStringFromAlphabet("00001111", 4);
current_dir=$PWD;cd /path/to/your/command/dir;special command ARGS;cd $current_dir;
current_dir
equal to your pwd
cd
to where you need to run your commandcd
back to our variable current_dir
Another Solution by @apieceofbart
pushd && YOUR COMMAND && popd
Luke's description of the function results in these scenarios seems to be right on. I only wish to understand the root cause and the PowerShell product team would do something about the behavior. It seems to be quite common and has cost me too much debugging time.
To get around this issue I've been using global variables rather than returning and using the value from the function call.
Here's another question on the use of global variables: Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function
See the documentation for the print function: print()
The content of end
is printed after the thing you want to print. By default it contains a newline ("\n"
) but it can be changed to something else, like an empty string.
It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.
Are you doing heavy DOM manipulation? I would use jQuery and Backbone.
Very data driven app? Angular with its nice data binding.
Game programming? None - direct to canvas; maybe a game engine.
Try
<p>Click on <img src="/storage/help/button2.1.png" width="auto"
height="28"align="middle"/> button will show a page as bellow</p>
It works for me
How about using readlink
?
# if symlink, readlink returns not empty string (the symlink target)
# if string is not empty, test exits w/ 0 (normal)
#
# if non symlink, readlink returns empty string
# if string is empty, test exits w/ 1 (error)
simlink? () {
test "$(readlink "${1}")";
}
FILE=/usr/mda
if simlink? "${FILE}"; then
echo $FILE is a symlink
else
echo $FILE is not a symlink
fi
If you want to do this programmatically (no manual text entry with gedit) here's a version for a Dockerfile based on user1341296's answer above:
FROM spittet/ruby-mysql
MAINTAINER [email protected]
RUN cp -R -p /var/lib/mysql /dev/shm && \
rm -rf /var/lib/mysql && \
sed -i -e 's,/var/lib/mysql,/dev/shm/mysql,g' /etc/mysql/my.cnf && \
/etc/init.d/mysql restart
Available on Docker hub here: https://hub.docker.com/r/richardjecooke/ruby-mysql-in-memory/
The compiler needs to know the size of the second dimension in your two dimensional array. For example:
void print_graph(g_node graph_node[], double weight[][5], int nodes);
I had to add a user environment variable, HOME
, with C:\Users\<your user name>
by going to System, Advanced System Settings, in the System Properties window, the Advanced tab, Environment Variables...
Then in my C:\Users\<your user name>
I created the file .bashrc
, e.g., touch .bashrc
and added the desired aliases.
You can style (albeit with some constraints) the actual items themselves with the option
selector:
select, option { width: __; }
This way you are not only constraining the drop-down, but also all of its elements.
You just have to write sudo
instead of su
.
Then just copy the PHP file to the var/www/ directory
.
Then go to the browser, and write local host/test.php
or whatever the .php
filename is.
Make Theme.AppCompat style parent
<style name="AppTheme" parent="Theme.AppCompat">
<item name="android:colorPrimary">#005555</item>
<item name="android:colorPrimaryDark">#003333</item>
</style>
And put getSupportActionBar().getThemedContext()
in onCreate()
.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
getSupportActionBar().getThemedContext();
}
Your best bet to start is to use ?str()
. To explore some examples, let's make some data:
set.seed(3221) # this makes the example exactly reproducible
my.data <- data.frame(y=rnorm(5),
x1=c(1:5),
x2=c(TRUE, TRUE, FALSE, FALSE, FALSE),
X3=letters[1:5])
@Wilmer E Henao H's solution is very streamlined:
sapply(my.data, class)
y x1 x2 X3
"numeric" "integer" "logical" "factor"
Using str()
gets you that information plus extra goodies (such as the levels of your factors and the first few values of each variable):
str(my.data)
'data.frame': 5 obs. of 4 variables:
$ y : num 1.03 1.599 -0.818 0.872 -2.682
$ x1: int 1 2 3 4 5
$ x2: logi TRUE TRUE FALSE FALSE FALSE
$ X3: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
@Gavin Simpson's approach is also streamlined, but provides slightly different information than class()
:
sapply(my.data, typeof)
y x1 x2 X3
"double" "integer" "logical" "integer"
For more information about class
, typeof
, and the middle child, mode
, see this excellent SO thread: A comprehensive survey of the types of things in R. 'mode' and 'class' and 'typeof' are insufficient.
Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:
git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit
If you want to still have it in your local repository and only remove it from the remote, then you can use:
git push origin +HEAD^:<name of your branch, most likely 'master'>
You can use SRV records:
_service._proto.name. TTL class SRV priority weight port target.
Service: the symbolic name of the desired service.
Proto: the transport protocol of the desired service; this is usually either TCP or UDP.
Name: the domain name for which this record is valid, ending in a dot.
TTL: standard DNS time to live field.
Class: standard DNS class field (this is always IN).
Priority: the priority of the target host, lower value means more preferred.
Weight: A relative weight for records with the same priority.
Port: the TCP or UDP port on which the service is to be found.
Target: the canonical hostname of the machine providing the service, ending in a dot.
Example:
_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.
So what I think you're looking for is to add something like this to your DNS hosts file:
_sip._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25566 tekkit.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25567 pvp.arboristal.com.
On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.
You can define more details by extending AbstractMongoConfiguration.
@Configuration
@EnableMongoRepositories("demo.mongo.model")
public class SpringMongoConfig extends AbstractMongoConfiguration {
@Value("${spring.profiles.active}")
private String profileActive;
@Value("${spring.application.name}")
private String proAppName;
@Value("${spring.data.mongodb.host}")
private String mongoHost;
@Value("${spring.data.mongodb.port}")
private String mongoPort;
@Value("${spring.data.mongodb.database}")
private String mongoDB;
@Override
public MongoMappingContext mongoMappingContext()
throws ClassNotFoundException {
// TODO Auto-generated method stub
return super.mongoMappingContext();
}
@Override
@Bean
public Mongo mongo() throws Exception {
return new MongoClient(mongoHost + ":" + mongoPort);
}
@Override
protected String getDatabaseName() {
// TODO Auto-generated method stub
return mongoDB;
}
}
A Bin file is a pure binary file with no memory fix-ups or relocations, more than likely it has explicit instructions to be loaded at a specific memory address. Whereas....
ELF files are Executable Linkable Format which consists of a symbol look-ups and relocatable table, that is, it can be loaded at any memory address by the kernel and automatically, all symbols used, are adjusted to the offset from that memory address where it was loaded into. Usually ELF files have a number of sections, such as 'data', 'text', 'bss', to name but a few...it is within those sections where the run-time can calculate where to adjust the symbol's memory references dynamically at run-time.
Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.
function foo() {
var myajax = $.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
});
return myajax.responseText;
}
You can do this also:
$.ajax({
type: "POST",
url: "CHService.asmx/SavePurpose",
dataType: "text",
data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
contentType: "application/json; charset=utf-8",
async: false, //add this
}).done(function ( data ) {
Success = true;
}).fail(function ( data ) {
Success = false;
});
You can read more about the jqXHR jQuery Object
Usually, only the endpoint that issues an 'active close' should go into TIME_WAIT state. So, if possible, have your clients issue the active close which will leave the TIME_WAIT on the client and NOT on the server.
See here: http://www.serverframework.com/asynchronousevents/2011/01/time-wait-and-its-design-implications-for-protocols-and-scalable-servers.html and http://www.isi.edu/touch/pubs/infocomm99/infocomm99-web/ for details (the later also explains why it's not always possible due to protocol design that doesn't take TIME_WAIT into consideration).
I had this error for my XXX element and it was because my XSD was wrongly formatted according to javax.xml.bind v2.2.11 . I think it's using an older XSD format but I didn't bother to confirm.
My initial wrong XSD was alike the following:
<xs:element name="Document" type="Document"/>
...
<xs:complexType name="Document">
<xs:sequence>
<xs:element name="XXX" type="XXX_TYPE"/>
</xs:sequence>
</xs:complexType>
The good XSD format for my migration to succeed was the following:
<xs:element name="Document">
<xs:complexType>
<xs:sequence>
<xs:element ref="XXX"/>
</xs:sequence>
</xs:complexType>
</xs:element>
...
<xs:element name="XXX" type="XXX_TYPE"/>
And so on for every similar XSD nodes.
You can use this to go down the page in an animation format.
$('html,body').animate({scrollTop: document.body.scrollHeight},"fast");
You don't need to escape it inside. You can use the |
character to delimit searches.
"\"foo\"\'bar\'".replace(/("|')/g, "")
Don't forget to call invalidate();
canvas.drawColor(backgroundColor);
invalidate();
path.reset();
Do what blak3r suggested and define your targets classpath like so
<taskdef resource="net/sf/antcontrib/antlib.xml">
<classpath>
<fileset dir="lib">
<include name="**/*.jar"/>
</fileset>
</classpath>
</taskdef>
where lib is where you store your jar's
Is Powershell an option?
Start Powershell:
powershell
Create the VPN Connection: Add-VpnConnection
Add-VpnConnection [-Name] <string> [-ServerAddress] <string> [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential] [-UseWinlogonCredential] [-EapConfigXmlStream <xml>] [-Force] [-PassThru] [-WhatIf] [-Confirm]
Edit VPN connections: Set-VpnConnection
Set-VpnConnection [-Name] <string> [[-ServerAddress] <string>] [-TunnelType <string> {Pptp | L2tp | Sstp | Ikev2 | Automatic}] [-EncryptionLevel <string> {NoEncryption | Optional | Required | Maximum}] [-AuthenticationMethod <string[]> {Pap | Chap | MSChapv2 | Eap}] [-SplitTunneling <bool>] [-AllUserConnection] [-L2tpPsk <string>] [-RememberCredential <bool>] [-UseWinlogonCredential <bool>] [-EapConfigXmlStream <xml>] [-PassThru] [-Force] [-WhatIf] [-Confirm]
Lookup VPN Connections: Get-VpnConnection
Get-VpnConnection [[-Name] <string[]>] [-AllUserConnection]
Connect: rasdial [connectionName]
rasdial connectionname [username [password | \]] [/domain:domain*] [/phone:phonenumber] [/callback:callbacknumber] [/phonebook:phonebookpath] [/prefixsuffix**]
You can manage your VPN connections with the powershell commands above, and simply use the connection name to connect via rasdial
.
The results of Get-VpnConnection
can be a little verbose. This can be simplified with a simple Select-Object
filter:
Get-VpnConnection | Select-Object -Property Name
More information can be found here:
I've used this method (reported here )
export class AppComponent {
constructor() {
if(document.getElementById("testScript"))
document.getElementById("testScript").remove();
var testScript = document.createElement("script");
testScript.setAttribute("id", "testScript");
testScript.setAttribute("src", "assets/js/test.js");
document.body.appendChild(testScript);
}
}
it worked for me since I wanted to execute a javascript file AFTER THE COMPONENT RENDERED.
This is one way without using time a zone:
LocalDateTime now = LocalDateTime.now();
long epoch = (now.getLong(ChronoField.EPOCH_DAY) * 86400000) + now.getLong(ChronoField.MILLI_OF_DAY);
You can also use the data-interval attribute eg. <div class="carousel" data-interval="10000">
I agree with the previous answers, and is fine if you are ok to start in UTC. But I think it is also a common scenario for people to work with a tz aware value that has a datetime that has a non UTC local timezone.
If you were to just go by name, one would probably infer replace() will be applicable and produce the right datetime aware object. This is not the case.
the replace( tzinfo=... ) seems to be random in its behaviour. It is therefore useless. Do not use this!
localize is the correct function to use. Example:
localdatetime_aware = tz.localize(datetime_nonaware)
Or a more complete example:
import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())
gives me a timezone aware datetime value of the current local time:
datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)
To replace the second element in the array
arr = [1, 7, 9]
with the value 8
arr[1] = 8
Just use the -jrm
option to remove the file and directory
structures
zip -jrm /path/to/file.zip /path/to/file
Using .format
for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map
is used to map each element of the list to string
type.,
as separator.[
and ]
in the print statement to show the list braces.Reference:
.format
for string formatting PEP-3101
If you are using Anaconda and facing this issue only when running pip within an environment, you might need to reinstall python.
Run conda install python
within the desired environment.
I also faced a similar issue, the problem was the form was inside a folder and the file .aspx.designer.cs
I had the namespace referencing specifically to that directory; which caused the error to appear in several components:
El nombre no existe en el contexto actual
This in your case, a possible solution is to leave the namespace line of the Members_Jobs.aspx.designer.cs
file specified globally, ie change this
namespace stman.Members {
For this
namespace stman {
It's what helped me solve the problem.
I hope to be helpful
The fields of your object have in turn their fields, some of which do not implement Serializable
. In your case the offending class is TransformGroup
. How to solve it?
Serializable
transient
According to this helpful list of operators [an operator can be thought of as a mathematical expression] found here, you can tell the batch compiler that you are manipulating variables instead of fixed numbers by using the += operator instead of the + operator.
Hope I Helped!
Maybe this helps or maybe not. I cleaned my debug and release versions then I renamed the OBJ folder. This finally got me thorugh. Previous steps were basically project removing references and them adding them back in at the project properties.
Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.
quit := make(chan bool)
go func() {
for {
select {
case <- quit:
return
default:
// Do other stuff
}
}
}()
// Do stuff
// Quit goroutine
quit <- true
What happens in reality in case you pass string as a first parameter of function
setTimeout(
'string'
,number
)
is value of first param got evaluated when it is time to run (after number
of miliseconds passed).
Basically it is equal to
setTimeout(
eval('string')
,number
)
This is
an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.
So samples which you refer are not good samples, and may be given in different context or just simple typo.
If you invoke like this setTimeout(something, number)
, first parameter is not string, but pointer to a something called something
. And again if something
is string - then it will be evaluated. But if it is function, then function will be executed.
jsbin sample
First Install React dev tools if not installed and then use the run below code in the browser console :
__REACT_DEVTOOLS_GLOBAL_HOOK__.renderers.get(1).version
transferring file from local to remote host
scp -i (path of your key) (path for your file to be transferred) (username@ip):(path where file to be copied)
e.g scp -i aws.pem /home/user1/Desktop/testFile ec2-user@someipAddress:/home/ec2-user/
P.S. - ec2-user@someipAddress of this ip address should have access to the destination folder in my case /home/ec2-user/
Try this:
case $VAR in
normal)
echo "This doesn't do fallthrough"
;;
special)
echo -n "This does "
;&
fallthrough)
echo "fall-through"
;;
esac
lint is a tool that is used to mark the source code with some suspicious and non-structural (may cause bug). It is a static code analysis tool in C at the beginning.Now it became the generic term used to describe the software analysis tool that mark the suspicious code.
you can use the left_on and right_on options as follows:
pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')
I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)
pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')
it depends on how you trigger the event. the key you are looking is textbox.clientid.
x.aspx code
<script type="text/javascript">
function disable_textbox(tid) {
var mytextbox = document.getElementById(tid);
mytextbox.disabled=false
}
</script>
code behind x.aspx.cs
string frameScript = "<script language='javascript'>" + "disable_textbox(" + tx.ClientID ");</script>";
Page.ClientScript.RegisterStartupScript(Page.GetType(), "FrameScript", frameScript);
The portable way to do this is:
sed -e 's/[ \t][ \t]*/\
/g'
That's an actual newline between the backslash and the slash-g. Many sed implementations don't know about \n
, so you need a literal newline. The backslash before the newline prevents sed from getting upset about the newline. (in sed scripts the commands are normally terminated by newlines)
With GNU sed you can use \n
in the substitution, and \s in the regex:
sed -e 's/\s\s*/\n/g'
GNU sed also supports "extended" regular expressions (that's egrep style, not perl-style) if you give it the -r flag, so then you can use +
:
sed -r -e 's/\s+/\n/g'
If this is for Linux only, you can probably go with the GNU command, but if you want this to work on systems with a non-GNU sed (eg: BSD, Mac OS-X), you might want to go with the more portable option.
I've always thought Kohana did a pretty good job of it.
public static function title($title, $separator = '-', $ascii_only = FALSE)
{
if ($ascii_only === TRUE)
{
// Transliterate non-ASCII characters
$title = UTF8::transliterate_to_ascii($title);
// Remove all characters that are not the separator, a-z, 0-9, or whitespace
$title = preg_replace('![^'.preg_quote($separator).'a-z0-9\s]+!', '', strtolower($title));
}
else
{
// Remove all characters that are not the separator, letters, numbers, or whitespace
$title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', UTF8::strtolower($title));
}
// Replace all separator characters and whitespace by a single separator
$title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
// Trim separators from the beginning and end
return trim($title, $separator);
}
The handy UTF8::transliterate_to_ascii()
will turn stuff like ñ => n.
Of course, you could replace the other UTF8::*
stuff with mb_* functions.
Make sure that firefox must install on default place like ->(c:/Program Files (x86)/mozilla firefox OR c:/Program Files/mozilla firefox, note: at the time of firefox installation do not change the path so let it installing in default path) If firefox is installed on some other place then selenium show those error.
If you have set your firefox in Systems(Windows) environment variable then either remove it or update it with new firefox version path.
If you want to use Firefox in any other place then use below code:-
As FirefoxProfile is depricated we need to use FirefoxOptions as below:
New Code:
File pathBinary = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
DesiredCapabilities desired = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options.setBinary(firefoxBinary));
The full working code of above code is as below:
System.setProperty("webdriver.gecko.driver","D:\\Workspace\\demoproject\\src\\lib\\geckodriver.exe");
File pathBinary = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
DesiredCapabilities desired = DesiredCapabilities.firefox();
FirefoxOptions options = new FirefoxOptions();
desired.setCapability(FirefoxOptions.FIREFOX_OPTIONS, options.setBinary(firefoxBinary));
WebDriver driver = new FirefoxDriver(options);
driver.get("https://www.google.co.in/");
Download geckodriver for firefox from below URL:
https://github.com/mozilla/geckodriver/releases
Old Code which will work for old selenium jars versions
File pathBinary = new File("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
FirefoxBinary firefoxBinary = new FirefoxBinary(pathBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(firefoxBinary, firefoxProfile);
This will only work if you want to compare exact strings. It will not work in case you want to check if the column string contains any of the strings in the list.
The right way to compare with a list would be :
searchfor = ['john', 'doe']
df = df[~df.col.str.contains('|'.join(searchfor))]
https://github.com/passsy/android-HoloCircularProgressBar is one example of a library that does this. As Tenfour04 stated, it will have to be somewhat custom, in that this is not supported directly out of the box. If this library doesn't behave as you wish, you can fork it and modify the details to make it work to your liking. If you implement something that others can then reuse, you could even submit a pull request to get that merged back in!
This is not exactly what you're asking for, but you can use docker export
on a stopped container if all you want is to inspect the files.
mkdir $TARGET_DIR
docker export $CONTAINER_ID | tar -x -C $TARGET_DIR
From man curl
:
-x, --proxy <[protocol://][user:password@]proxyhost[:port]>
Use the specified HTTP proxy.
If the port number is not specified, it is assumed at port 1080.
General way:
export http_proxy=http://your.proxy.server:port/
Then you can connect through proxy from (many) application.
And, as per comment below, for https:
export https_proxy=https://your.proxy.server:port/
For me, this was something as simple as a missing version for my artifact - "1.1-SNAPSHOT"
>>> dict([('hi','goodbye')])
{'hi': 'goodbye'}
Or:
>>> [ dict([i]) for i in (('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14)) ]
[{'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}]
The git blame
command is used to examine the contents of a file line by line and see when each line was last modified and who the author of the modifications was.
If there was a bug in code,use it to identify who cased it,then you can blame him. Git blame is get blame(d).
If you need to know history of one line code,use git log -S"code here"
, simpler than git blame.
You can achieve this with: EventTarget.dispatchEvent(event)
and by passing in a new KeyboardEvent as the event.
For example: element.dispatchEvent(new KeyboardEvent('keypress', {'key': 'a'}))
Working example:
// get the element in question_x000D_
const input = document.getElementsByTagName("input")[0];_x000D_
_x000D_
// focus on the input element_x000D_
input.focus();_x000D_
_x000D_
// add event listeners to the input element_x000D_
input.addEventListener('keypress', (event) => {_x000D_
console.log("You have pressed key: ", event.key);_x000D_
});_x000D_
_x000D_
input.addEventListener('keydown', (event) => {_x000D_
console.log(`key: ${event.key} has been pressed down`);_x000D_
});_x000D_
_x000D_
input.addEventListener('keyup', (event) => {_x000D_
console.log(`key: ${event.key} has been released`);_x000D_
});_x000D_
_x000D_
// dispatch keyboard events_x000D_
input.dispatchEvent(new KeyboardEvent('keypress', {'key':'h'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keydown', {'key':'e'}));_x000D_
input.dispatchEvent(new KeyboardEvent('keyup', {'key':'y'}));
_x000D_
<input type="text" placeholder="foo" />
_x000D_
From all of the above, I came up with this version. This version also works for me in the mac recovery terminal.
find ./ -name '*.xsl' -exec cp -prv '{}' '/path/to/targetDir/' ';'
It will look in the current directory and recursively in all of the sub directories for files with the xsl extension. It will copy them all to the target directory.
cp flags are:
For the record, this is documented in How do I add resources to my JAR? (illustrated for unit tests but the same applies for a "regular" resource):
To add resources to the classpath for your unit tests, you follow the same pattern as you do for adding resources to the JAR except the directory you place resources in is
${basedir}/src/test/resources
. At this point you would have a project directory structure that would look like the following:my-app |-- pom.xml `-- src |-- main | |-- java | | `-- com | | `-- mycompany | | `-- app | | `-- App.java | `-- resources | `-- META-INF | |-- application.properties `-- test |-- java | `-- com | `-- mycompany | `-- app | `-- AppTest.java `-- resources `-- test.properties
In a unit test you could use a simple snippet of code like the following to access the resource required for testing:
... // Retrieve resource InputStream is = getClass().getResourceAsStream("/test.properties" ); // Do something with the resource ...
If you do not need a table border, apply this:
table{
table-layout:fixed;
border-collapse:collapse;
}
td{
word-wrap: break-word;
}
From the DevTools console, you can run:
document.getElementsByTagName("head")[0].innerHTML += '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"><\/script>';
Check the available jQuery version at https://code.jquery.com/jquery/.
To check whether it's loaded, see: Checking if jquery is loaded using Javascript.
I'm posting this because I didn't find this answer elsewhere. All my Arduino nano chinese (CH340) clones had this problem after upgrading to the Arduino IDE to 1.8.9. What worked for me was to use a spare official Arduino Uno that I have to burn the bootloader on the faulty nanos using the ICSP headers on the nano. For this all I did was to follow the instructions here: chinese-clone-of-arduino-nano-with-chip-ch340g-how-to-fix-it. The ONLY thing I did differently was to always set the "Old Bootloader" option as said before in this thread. Other than that I completely followed the instruction on that link and saved my nanos from that annoying problem. I hope that this helps someone out there.
Also check out the open financial exchange (ofx) http://www.ofx.net/
This is what apps like quicken, ms money etc use.
I have used this URL to obtain multiple currency market quotes.
http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USD=X,CAD=X,EUR=X
"USD",1.0000
"CAD",1.2458
"EUR",0.8396
They can be parsed in PHP like this:
$symbols = ['USD=X', 'CAD=X', 'EUR=X'];
$url = "http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=".join($symbols, ',');
$quote = array_map( 'str_getcsv', file($url) );
foreach ($quote as $key => $symb) {
$symbol = $quote[$key][0];
$value = $quote[$key][1];
}
Hi - I want to write a test to establish that an Exception is not raised in a given circumstance.
That's the default assumption -- exceptions are not raised.
If you say nothing else, that's assumed in every single test.
You don't have to actually write an any assertion for that.
I wrote a simple program that solved the easy ones. It took its input from a file which was just a matrix with spaces and numbers. The datastructure to solve it was just a 9 by 9 matrix of a bit mask. The bit mask would specify which numbers were still possible on a certain position. Filling in the numbers from the file would reduce the numbers in all rows/columns next to each known location. When that is done you keep iterating over the matrix and reducing possible numbers. If each location has only one option left you're done. But there are some sudokus that need more work. For these ones you can just use brute force: try all remaining possible combinations until you find one that works.
Modern browsers now consider displaying a custom message to be a security hazard and it has therefore been removed from all of them. Browsers now only display generic messages. Since we no longer have to worry about setting the message, it is as simple as:
// Enable navigation prompt
window.onbeforeunload = function() {
return true;
};
// Remove navigation prompt
window.onbeforeunload = null;
Read below for legacy browser support.
The orginal answer is suitable for IE6-8 and FX1-3.5 (which is what we were targeting back in 2009 when it was written), but is rather out of date now and won't work in most current browsers - I've left it below for reference.
The window.onbeforeunload
is not treated consistently by all browsers. It should be a function reference and not a string (as the original answer stated) but that will work in older browsers because the check for most of them appears to be whether anything is assigned to onbeforeunload
(including a function that returns null
).
You set window.onbeforeunload
to a function reference, but in older browsers you have to set the returnValue
of the event instead of just returning a string:
var confirmOnPageExit = function (e)
{
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = 'Any text will block the navigation and display a prompt';
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
You can't have that confirmOnPageExit
do the check and return null if you want the user to continue without the message. You still need to remove the event to reliably turn it on and off:
// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
// Turn it off - remove the function entirely
window.onbeforeunload = null;
To turn it on:
window.onbeforeunload = "Are you sure you want to leave?";
To turn it off:
window.onbeforeunload = null;
Bear in mind that this isn't a normal event - you can't bind to it in the standard way.
To check for values? That depends on your validation framework.
In jQuery this could be something like (very basic example):
$('input').change(function() {
if( $(this).val() != "" )
window.onbeforeunload = "Are you sure you want to leave?";
});
You can alternatively use NamedParameterJdbcTemplate
(naming can be useful when you have many parameters)
Map<String, Object> params = new HashMap<>();
params.put("var1",value1);
params.put("var2",value2);
namedJdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (:var1, :var2)",
params
);
Try
apt-get -d install <packages>
It is documented in man apt-get
.
Just for clarification; the downloaded packages are located in the apt package cache at
/var/cache/apt/archives
Add "name" attribute and keep the name same for all the radio buttons in a form.
i.e.,
<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3
Hope that would help.
Now, these methods I tried myself, and I got exactly what was advertised: All the modules.
Alas, really you don't care much about the stdlib, you know what you get with a python install.
Really, I want the stuff that I installed.
What actually, surprisingly, worked just fine was:
pip freeze
Which returned:
Fabric==0.9.3
apache-libcloud==0.4.0
bzr==2.3b4
distribute==0.6.14
docutils==0.7
greenlet==0.3.1
ipython==0.10.1
iterpipes==0.4
libxml2-python==2.6.21
I say "surprisingly" because the package install tool is the exact place one would expect to find this functionality, although not under the name 'freeze' but python packaging is so weird, that I am flabbergasted that this tool makes sense. Pip 0.8.2, Python 2.7.
I was getting this error because my cpp files was not added in the CMakeLists.txt file
Select SQL Management Studio from the dropdown in Download SQL Server 2012 Express.
Indexed fields (fields with numerical keys) are stored as a holy array inside the object. Therefore lookup time is O(1)
Same for a lookup array it's O(1)
Iterating through an array of objects and testing their ids against the provided one is a O(n) operation.
As in a similar question, use display: inline-block
with a placeholder element to vertically center the span inside of a block element:
html, body, #container, #placeholder { height: 100%; }_x000D_
_x000D_
#content, #placeholder { display:inline-block; vertical-align: middle; }
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="container">_x000D_
<span id="content">_x000D_
Content_x000D_
</span>_x000D_
<span id="placeholder"></span>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Vertical alignment is only applied to inline elements or table cells, so use it along with display:inline-block
or display:table-cell
with a display:table
parent when vertically centering block elements.
References:
SequenceEqual can be faster. Namely in the case where almost all of the time, both arrays have indeed the same length and are not the same object.
It's still not the same functionality as the OP's function, as it won't silently compare null values.
$host
is a variable of the Core module.
$host
This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.
This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.
$http_host
is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER
(ref).
$http_HEADER
The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;
Summarizing:
$http_host
equals always the HTTP_HOST
request header.$host
equals $http_host
, lowercase and without the port number (if present), except when HTTP_HOST
is absent or is an empty value. In that case, $host
equals the value of the server_name
directive of the server which processed the request.I had this problem too but it looks like it depends on the Kubernetes offering and how everything was installed. In Azure, if you are using acs-engine install, you can find the shell script that is actually being run to provision it at:
/opt/azure/containers/provision.sh
To get a more fine-grained understanding, just read through it and run the commands that it specifies. For me, I had to run as root:
systemctl enable kubectl
systemctl restart kubectl
I don't know if the enable is necessary and I can't say if these will work with your particular installation, but it definitely worked for me.
Link statically to libstdc++ with -static-libstdc++
gcc option.
open http://localhost:8080/ in browser, if you get tomcat home page. it means tomcat is running
x='buffalo'
exec("%s = %d" % (x,2))
After that you can check it by:
print buffalo
As an output you will see:
2
These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.
If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.
Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.
The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.window.width',0)
profile.set_preference('browser.window.height',0)
profile.update_preferences()
write this code into setup part of your test code, before the: webdriver.Firefox()
line.
in my case, the tortoise icon not showing at all, I tried this and solved my problem :
(the point is to place all tortoise folder at top)
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
You can use reflection
A Chinese website provides a relevant solution: http://blog.csdn.net/peihang1354092549/article/details/41957369
If you don't understand Chinese, please try to read it with the translation software.
He provides this code for the old version:
public void JSONArray_remove(int index, JSONArray JSONArrayObject) throws Exception{
if(index < 0)
return;
Field valuesField=JSONArray.class.getDeclaredField("values");
valuesField.setAccessible(true);
List<Object> values=(List<Object>)valuesField.get(JSONArrayObject);
if(index >= values.size())
return;
values.remove(index);
}
Previous answer is not correct in my experience, you can't pass it a simple string, needs to be a datetime object. So:
import datetime
df.loc[datetime.date(year=2014,month=1,day=1):datetime.date(year=2014,month=2,day=1)]
rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3
function rgb(...values){
return values.reduce((acc, cur) => {
let val = cur >= 255 ? 'ff' : cur <= 0 ? '00' : Number(cur).toString(16);
return acc + (val.length === 1 ? '0'+val : val);
}, '').toUpperCase();
}
Following width worked well in HTML5: -
<table >
<tr>
<th style="min-width:120px">Month</th>
<th style="min-width:60px">Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
Please note that
Either what Ant says, or accumulate into a string, then print once:
s = '';
for i in xrange(20):
s += 'a'
print s
//for excluding zero
public class SmallestInt {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
System.out.println("enter number");
int val=input.nextInt();
int min=val;
//String notNull;
while(input.hasNextInt()==true)
{
val=input.nextInt();
if(val<min)
min=val;
}
System.out.println("min is: "+min);
}
}
If you are using "n" library @ https://github.com/tj/n . Do the following
echo $NODE_PATH
If node path is empty, then
sudo n latest - sudo is optional depending on your system
After switching Node.js versions using n, npm may not work properly.
curl -0 -L https://npmjs.com/install.sh | sudo sh
echo NODE_PATH
You should see your Node Path now. Else, it might be something else
I had the same problem, just use console.log(...)
(like firebug), and the install a log viewer application, this will allow you to view all the logs for your browser.
Open Task Manager and Kill both of these processes. They will autostart back up. Then try debugging your project again.
You can try this new library. JellyGif respects Gif frame duration while being highly CPU & Memory performant. It works great with UITableViewCell & UICollectionViewCell too. To get started you just need to
import JellyGif
let imageView = JellyGifImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
//Animates Gif from the main bundle
imageView.startGif(with: .name("Gif name"))
//Animates Gif with a local path
let url = URL(string: "Gif path")!
imageView.startGif(with: .localPath(url))
//Animates Gif with data
imageView.startGif(with: .data(Data))
For more information you can look at its README
Try this code:
<form id="myform">
<!-- form elements -->
<a href="#" onclick="document.getElementById('myform').submit()">Submit</a>
</form>
But users with disabled JavaScript won't be able to submit the form, so you could add the following code:
<noscript>
<input type="submit" value="Submit form!" />
</noscript>
There is no need to update anything in config/mail.php. just put you credential in .env with this specific key's. This is my .env file.
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=********
MAIL_ENCRYPTION=tls
I had the same issue after long time debugging and googling i have found the solution. that by enabling less secure apps. the email started working.
if your gmail is secure with 2 step verification you can't enable less secure app. so turn off 2 step verification and enable less secure app. by click here enable less secure apps on your gmail account
It's used to write js codes inside of href
instead of event listeners like onclick
and avoiding #
links in href
to make a
tags valid for HTML.
I had a research on how to use javascript:
inside of href
attribute and got the result that I can write multiple lines in it!
<a href="
javascript:
a = 4;
console.log(a++);
a += 2;
console.log(a++);
if(a < 6){
console.log('a is lower than 6');
}
else
console.log('a is greater than 6');
function log(s){
console.log(s);
}
log('function implementation working too');
">Click here</a>
Tested in chrome Version 68.0.3440.106 (Official Build) (64-bit)
Tested in Firefox Quantum 61.0.1 (64-bit)
set height: auto;
If you want to have minimum height to x then you can write
height:auto;
min-height:30px;
height:auto !important; /* for IE as it does not support min-height */
height:30px; /* for IE as it does not support min-height */
Here is a more complete example of an XML filter (the example above by itself will not work since it just shows a snippet and is missing the <FindBugsFilter>
begin and end tags):
<FindBugsFilter>
<Match>
<Class name="com.mycompany.foo" />
<Method name="bar" />
<Bug pattern="NP_BOOLEAN_RETURN_NULL" />
</Match>
</FindBugsFilter>
If you are using the Android Studio FindBugs plugin, browse to your XML filter file using File->Other Settings->Default Settings->Other Settings->FindBugs-IDEA->Filter->Exclude filter files->Add.
For JDBC based project (directly or indirectly, e.g. JPA, EJB, ...) you can mockup not the entire database (in such case it would be better to use a test db on a real RDBMS), but only mockup at JDBC level.
Advantage is abstraction which comes with that way, as JDBC data (result set, update count, warning, ...) are the same whatever is the backend: your prod db, a test db, or just some mockup data provided for each test case.
With JDBC connection mocked up for each case there is no need to manage test db (cleanup, only one test at time, reload fixtures, ...). Every mockup connection is isolated and there is no need to clean up. Only minimal required fixtures are provided in each test case to mock up JDBC exchange, which help to avoid complexity of managing a whole test db.
Acolyte is my framework which includes a JDBC driver and utility for this kind of mockup: http://acolyte.eu.org .
You can also use shuf
(available in coreutils).
shuf -i 1-100000 -n 1
I'm not expert enough in the inner workings of Postgres to know why your query with the double condition in the WHERE
clause be not working. But one way to get around this would be to use a UNION
of the two queries which you know do work:
SELECT * FROM table_name WHERE boolean_column IS NULL
UNION
SELECT * FROM table_name WHERE boolean_column = FALSE
You could also try using COALESCE
:
SELECT * FROM table_name WHERE COALESCE(boolean_column, FALSE) = FALSE
This second query will replace all NULL
values with FALSE
and then compare against FALSE
in the WHERE
condition.
Deleting the .git
folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:
Checkout
git checkout --orphan latest_branch
Add all the files
git add -A
Commit the changes
git commit -am "commit message"
Delete the branch
git branch -D main
Rename the current branch to main
git branch -m main
Finally, force update your repository
git push -f origin main
PS: this will not keep your old commit history around
JPanel p=new JPanel();
GridBagLayout layout=new GridBagLayout();
p.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.gridx=0;
gbc.gridy=0;
p2.add("",gbc);
A swiftease version based on the very first answer!
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if ( event?.subtype == .motionShake )
{
print("stop shaking me!")
}
}
You'll want to include action="javascript:void(0);"
to your form to prevent page reloads and maintain HTML standard.
meshgrid helps in creating a rectangular grid from two 1-D arrays of all pairs of points from the two arrays.
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])
Now, if you have defined a function f(x,y) and you wanna apply this function to all the possible combination of points from the arrays 'x' and 'y', then you can do this:
f(*np.meshgrid(x, y))
Say, if your function just produces the product of two elements, then this is how a cartesian product can be achieved, efficiently for large arrays.
Referred from here
What you are asking, Sir, is as the answer of RedFilter. This answer as well helps in understanding why group by is somehow a simpler version or partition over: SQL Server: Difference between PARTITION BY and GROUP BY since it changes the way the returned value is calculated and therefore you could (somehow) return columns group by can not return.
!python 'script.py'
replace script.py with your real file name, DON'T forget ''
You asked if it is possible to change the circular dependency checking in those slf4j classes.
The simple answer is no.
static
initializer block ... so you can't override the implementation, and you can't stop it happening.So the only way to change this would be to download the source code, modify the core classes to "fix" them, build and use them. That is probably a bad idea (in general) and probably not solution in this case; i.e. you risk triggering the stack overflow problem that the message warns about.
Reference:
The real solution (as you identified in your Answer) is to use the right JARs. My understanding is that the circularity that was detected is real and potentially problematic ... and unnecessary.
I use:
gmap.setZoom(24); //this looks a high enough zoom value
gmap.fitBounds(bounds); //now the fitBounds should make the zoom value only less
This will use the smaller of 24 and the necessary zoom level according to your code, however it probably changes the zoom anyway and doesn't care about how much you zoomed out.
Please Check below code that using that You can find all Music Files from sdcard :
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_animations);
getAllSongsFromSDCARD();
}
public void getAllSongsFromSDCARD() {
String[] STAR = { "*" };
Cursor cursor;
Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
cursor = managedQuery(allsongsuri, STAR, selection, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("sonng name"+fullpath);
} while (cursor.moveToNext());
}
cursor.close();
}
}
}
I have also added following line in the AndroidManifest.xml file as below:
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
From Jimmy Bogard: CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());
It's in one of the comments at his blog.
At least as far back as MySQL 5.5 you can use format:
SELECT FORMAT(123456789.123456789,2);
/* produces 123,456,789.12 */
SELECT FORMAT(123456789.123456789,2,'de_DE');
/*
produces 123.456.789,12
note the swapped . and , for the de_DE locale (German-Germany)
*/
From the MySQL docs: https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_format
Available locales are listed elsewhere in the docs: https://dev.mysql.com/doc/refman/5.5/en/locale-support.html
For Android Studio 3.5, fount it using instructions here: https://developer.android.com/studio/debug/device-file-explorer (View -> Tool Windows -> Device File Explorer -> -> databases
The title of the question asks about precision. BigDecimal distinguishes between scale and precision. Scale is the number of decimal places. You can think of precision as the number of significant figures, also known as significant digits.
Some examples in Clojure.
(.scale 0.00123M) ; 5
(.precision 0.00123M) ; 3
(In Clojure, The M
designates a BigDecimal literal. You can translate the Clojure to Java if you like, but I find it to be more compact than Java!)
You can easily increase the scale:
(.setScale 0.00123M 7) ; 0.0012300M
But you can't decrease the scale in the exact same way:
(.setScale 0.00123M 3) ; ArithmeticException Rounding necessary
You'll need to pass a rounding mode too:
(.setScale 0.00123M 3 BigDecimal/ROUND_HALF_EVEN) ;
; Note: BigDecimal would prefer that you use the MathContext rounding
; constants, but I don't have them at my fingertips right now.
So, it is easy to change the scale. But what about precision? This is not as easy as you might hope!
It is easy to decrease the precision:
(.round 3.14159M (java.math.MathContext. 3)) ; 3.14M
But it is not obvious how to increase the precision:
(.round 3.14159M (java.math.MathContext. 7)) ; 3.14159M (unexpected)
For the skeptical, this is not just a matter of trailing zeros not being displayed:
(.precision (.round 3.14159M (java.math.MathContext. 7))) ; 6
; (same as above, still unexpected)
FWIW, Clojure is careful with trailing zeros and will show them:
4.0000M ; 4.0000M
(.precision 4.0000M) ; 5
Back on track... You can try using a BigDecimal constructor, but it does not set the precision any higher than the number of digits you specify:
(BigDecimal. "3" (java.math.MathContext. 5)) ; 3M
(BigDecimal. "3.1" (java.math.MathContext. 5)) ; 3.1M
So, there is no quick way to change the precision. I've spent time fighting this while writing up this question and with a project I'm working on. I consider this, at best, A CRAZYTOWN API, and at worst a bug. People. Seriously?
So, best I can tell, if you want to change precision, you'll need to do these steps:
These steps, as Clojure code:
(def x 0.000691M) ; the input number
(def p' 1) ; desired precision
(def s' (+ (.scale x) p' (- (.precision x)))) ; desired new scale
(.setScale x s' BigDecimal/ROUND_HALF_EVEN)
; 0.0007M
I know, this is a lot of steps just to change the precision!
Why doesn't BigDecimal already provide this? Did I overlook something?
You can dispatch a click event, though this is not the same as a real click. For instance, it can't be used to trick a cross-domain iframe document into thinking it was clicked.
All modern browsers support document.elementFromPoint
and HTMLElement.prototype.click()
, since at least IE 6, Firefox 5, any version of Chrome and probably any version of Safari you're likely to care about. It will even follow links and submit forms:
document.elementFromPoint(x, y).click();
https://developer.mozilla.org/En/DOM:document.elementFromPoint https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
It actually tells you what's wrong, but you ignored it because you didn't check the error returned from json.Marshal
.
json: unsupported type: map[int]main.Foo
JSON spec doesn't support anything except strings for object keys, while javascript won't be fussy about it, it's still illegal.
You have two options:
1 Use map[string]Foo
and convert the index to string (using fmt.Sprint for example):
datas := make(map[string]Foo, N)
for i := 0; i < 10; i++ {
datas[fmt.Sprint(i)] = Foo{Number: 1, Title: "test"}
}
j, err := json.Marshal(datas)
fmt.Println(string(j), err)
2 Simply just use a slice (javascript array):
datas2 := make([]Foo, N)
for i := 0; i < 10; i++ {
datas2[i] = Foo{Number: 1, Title: "test"}
}
j, err = json.Marshal(datas2)
fmt.Println(string(j), err)
I had a similar problem, with a lot of help from the web and this post I made a small application, my target is VCD and SVCD and I don't delete the source but I reckon it will be fairly easy to adapt to your own needs.
It can convert 1 video and cut it or can convert all videos in a folder, rename them and put them in a subfolder /VCD
I also add a small interface, hope someone else find it useful!
I put the code and file in here btw: http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/
You need reinstall VS.
Language Pack Support in Visual Studio 2017 RC
Issue:
This release of Visual Studio supports only a single language pack for the user interface. You cannot install two languages for the user interface in the same instance of Visual Studio. In addition, you must select the language of Visual Studio during the initial install, and cannot change it during Modify.
Workaround:
These are known issues that will be fixed in an upcoming release. To change the language in this release, you can uninstall and reinstall Visual Studio.
Reference: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#november-16-2016
This error could caused by a username with Chinese characters.
$dbc
is returning false. Your query has an error in it:
SELECT users.*, profile.* --You do not join with profile anywhere.
FROM users
INNER JOIN contact_info
ON contact_info.user_id = users.user_id
WHERE users.user_id=3");
The fix for this in general has been described by Raveren.
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
Here is simple solution with Jquery. It works globally. Have a look on the code.
$('document').on("click", ".clear", function(){
$(this).closest('form').trigger("reset");
})
Add a clear class to a button in every form you need to reset it. For example:
<button class="button clear" type="reset">Clear</button>
I would do it in the Initialize event of the controller like this...
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
const string culture = "en-US";
CultureInfo ci = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
}
The Range object has both width and height properties, which are measured in points.
Originally it was used as an anchor to jump to an element with the same name/id.
However, nowadays it's usually used with AJAX-based pages since changing the hash can be detected using JavaScript and allows you to use the back/forward button without actually triggering a full page reload.
this should solve your problem.
\cp -rf foo/* bar/
You can use the maven-assembly-plugin and create a jar with all dependencies included.
If you're pulling this value directly from a SQL Database and the value is null in there, it will actually be the DBNull
object rather than null. Either place a check prior to your conversion & use a default value in the event of DBNull
, or replace your null check afterwards with a check on rdrSelect[23]
for DBNull
.
why don't u try using an absolute xPath
//soap:Envelope[1]/soap:Body[1]/PaymentNotification[1]/payment
or since u know that it is a payment and payment doesn't have any attributes just select directly from payment
//soap:Envelope[1]/soap:Body[1]/PaymentNotification[1]/payment/*
For Windows Vista and Windows 7 you need to get the Remote Server Administration Tools (RSAT) - the Active Directory Users & Computers Snap-In is included in that pack. Download link: Remote Server Administration Tools for Windows 7.
Usage of javascript:void(0)
means that the author of the HTML is misusing the anchor element in place of the button element.
Anchor tags are often abused with the onclick event to create pseudo-buttons by setting href to "#" or "javascript:void(0)" to prevent the page from refreshing. These values cause unexpected behavior when copying/dragging links, opening links in a new tabs/windows, bookmarking, and when JavaScript is still downloading, errors out, or is disabled. This also conveys incorrect semantics to assistive technologies (e.g., screen readers). In these cases, it is recommended to use a
<button>
instead. In general you should only use an anchor for navigation using a proper URL.
Source: MDN's <a>
Page.
I think this may help you. I had a similar issue. If your array looks like this:
var array = ["page1","1973","Jimmy"];
You can do a simple "for" loop to return the instance in the array when you get a match.
var c;
for (i = 0; i < array.length; i++) {
if (array[i].indexOf("page") > -1){
c = i;}
}
We create an empty variable, c to host our answer. We then loop through the array to find where the array object (e.g. "page1") matches our indexOf("page"). In this case, it's 0 (the first result)
Happy to expand if you need further support.
Regarding the 'build' directory exclusion -
If you place your build files in a different directory from your source, as I do, you don't have the folder in the tree to worry about.
This also makes life simpler for sharing your code, preventing bloated backups, and even when you have dependencies to other Xcode projects (while require the builds to be in the same directory as each other)
You can grab an up-to-date copy from the Github gist https://gist.github.com/708713
My current .gitignore file is
# Mac OS X
*.DS_Store
# Xcode
*.pbxuser
*.mode1v3
*.mode2v3
*.perspectivev3
*.xcuserstate
project.xcworkspace/
xcuserdata/
# Generated files
*.o
*.pyc
#Python modules
MANIFEST
dist/
build/
# Backup files
*~.nib
Write Thread.sleep(1000);
it will make the thread sleep for 1000ms
We use Groovy and Spock for writing highly expressive BDD style tests. Unbeatable combo! Jersey Client API or HttpClient is used for handling the HTTP requests.
For manual/acceptance testing we use Curl or Chrome apps as Postman or Dev HTTP Client.
Other solutions are great but they didn't take care of the fact that watermark shouldn't get selected on selection from the mouse. This fiddle takes care or that: https://jsfiddle.net/MiKr13/d1r4o0jg/9/
This will be better option for pdf or static html.
CSS:
#watermark {
opacity: 0.2;
font-size: 52px;
color: 'black';
background: '#ccc';
position: absolute;
cursor: default;
user-select: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
right: 5px;
bottom: 5px;
}
Douglas Crockford has some very good explanations of inheritance in JavaScript:
I have used the technique said above, still I found that the time given in the Code:Blocks IDE was more or less similar to the result obtained-(may be it will differ by little micro seconds)..
You can achieve an expected result with requests
library as well:
import requests
url = "http://www.mywebsite.org/Data%20Set.zip"
print(f"Before: {url}")
print(f"After: {requests.utils.unquote(url)}")
Output:
$ python3 test_url_unquote.py
Before: http://www.mywebsite.org/Data%20Set.zip
After: http://www.mywebsite.org/Data Set.zip
Might be handy if you are already using requests
, without using another library for this job.
Your mistake is the parameters to Substring. The first parameter should be the start index and the second should be the length or offset from the startindex.
string newString = url.Substring(18, 7);
If the length of the substring can vary you need to calculate the length.
Something in the direction of (url.Length - 18) - 4
(or url.Length - 22
)
In the end it will look something like this
string newString = url.Substring(18, url.Length - 22);
If you want to add a class to the first and second td you can use .each()
and slice()
$(".location table tbody tr").each(function(){
$(this).find("td").slice(0, 2).addClass("black");
});
With gitk
you can view the two branches graphically:
gitk branch1 branch2
And then it's easy to find the common ancestor in the history of the two branches.
Still pretty bewildering. It seems some combination of the above suggestions worked in Eclipse 3.7.2.
First, I had to move to a network that dl-ssl.google.com hasn't blocked (this is an ongoing problem with the Google server) (Easy with a laptop, less so with my tower.)
The Eclipse folks should look at this problem. The user sees an error, something about a missing package "org.eclipse.wst.sse.core', say. There are 50 or so plugin repositories listed. which of these is the one that has this package??? None has a name containing a 'wst' or 'sse'.
This is very poor. There needs to be a way for the user to associate the error message with a repository solution.
Anyway: after some hunt-and-peck I ended up selecting (and reloading each repository, and with Contact all update sites during install to find required software checked)
One of these provided the packages needed for the Android plugin . Best guess: Helios.
If that question is connected to your other Hudson questions use the command they provide. This way with XML from the command line:
$ curl -X POST -d '<run>...</run>' \
http://user:pass@myhost:myport/path/of/url
You need to change it a little bit to read from a file:
$ curl -X POST -d @myfilename http://user:pass@myhost:myport/path/of/url
Read the manpage. following an abstract for -d Parameter.
-d/--data
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F/--form.
-d/--data is the same as --data-ascii. To post data purely binary, you should instead use the --data-binary option. To URL-encode the value of a form field you may use --data-urlencode.
If any of these options is used more than once on the same command line, the data pieces specified will be merged together with a separating &-symbol. Thus, using '-d name=daniel -d skill=lousy' would generate a post chunk that looks like 'name=daniel&skill=lousy'.
If you start the data with the letter @, the rest should be a file name to read the data from, or - if you want curl to read the data from stdin. The contents of the file must already be URL-encoded. Multiple files can also be specified. Posting data from a file named 'foobar' would thus be done with --data @foobar.
check this out jquery calendar to show only year and month
or something like this
$("#datepicker").datepicker( "option", "dateFormat", "yy" );?
In my app I have app delegate and other classes that need to be accessed by the tests as public. As outlined here, I then import my my app into my tests.
When I recently created two new classes ,their test targets were both the main and testing parts. Removing them from their membership from the tests solved the issue.
Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:
__init__
method are static elements; they belong to the class.__init__
method are elements of the object (self
); they don't belong to the class.You'll see it more clearly with some code:
class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.static_elem, c1.object_elem
123 456
>>> print c2.static_elem, c2.object_elem
123 456
# Nothing new so far ...
# Let's try changing the static element
MyClass.static_elem = 999
>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456
# Now, let's try changing the object element
c1.object_elem = 888
>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456
As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.
If you are using Kotlin + Retrofit + Coroutines then just use try
and catch
for network operations like,
viewModelScope.launch(Dispatchers.IO) {
try {
val userListResponseModel = apiEndPointsInterface.usersList()
returnusersList(userListResponseModel)
} catch (e: Exception) {
e.printStackTrace()
}
}
Where, Exception is type of kotlin
and not of java.lang
This will handle every exception like,
Here is my usersList()
function
@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel
Note:
Your RetrofitClient Classs must have this as client
OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
Building off of Mulfix's answer, if you have Visual Studio Community 2015, try Add Reference... -> COM -> Type Libraries -> 'Microsoft Excel 15.0 Object Library'.
Try this:
CREATE TABLE `test_table` (
`id` INT( 10 ) NOT NULL,
`created_at` TIMESTAMP NOT NULL DEFAULT 0,
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE = INNODB;
Go into your Gradle and look for sourceCompatibility and change it from 1.6 to 7. That worked for me at least.
You can also go into your module settings and set the Source/Target Compatibility to 1.7.
That will produce the following code in your Gradle:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
I fall here when I was looking exactly for the same problem and maybe it can help other.
I think the real solution is:
cat *.log | grep -H somethingtosearch
I'm going to use the streams api to convert a stream of integers into a single string. The problem with some of the provided answers is that they produce a O(n^2) runtime because of String building. A better solution is to use a StringBuilder, and then join the strings together as the final step.
// Create a stream of integers
String result = Arrays.stream(new int[]{1,2,3,4,5,6 })
// collect into a single StringBuilder
.collect(StringBuilder::new, // supplier function
// accumulator - converts cur integer into a string and appends it to the string builder
(builder, cur) -> builder.append(Integer.toString(cur)),
// combiner - combines two string builders if running in parallel
StringBuilder::append)
// convert StringBuilder into a single string
.toString();
You can take this process a step further by converting the collection of object to a single string.
// Start with a class definition
public static class AClass {
private int value;
public int getValue() { return value; }
public AClass(int value) { this.value = value; }
@Override
public String toString() {
return Integer.toString(value);
}
}
// Create a stream of AClass objects
String resultTwo = Arrays.stream(new AClass[]{
new AClass(1),
new AClass(2),
new AClass(3),
new AClass(4)
})
// transform stream of objects into a single string
.collect(StringBuilder::new,
(builder, curObj) -> builder.append(curObj.toString()),
StringBuilder::append
)
// finally transform string builder into a single string
.toString();
if you want to add directly to input as attribute, use this
onclick="return false;"
<input id = "btnPlay" type="button" onclick="return false;" value="play" />
this will prevent form submit behaviour
The following code results in the error below:
pd.set_option('display.max_colwidth', -1)
FutureWarning: Passing a negative integer is deprecated in version 1.0 and will not be supported in future version. Instead, use None to not limit the column width.
Instead, use:
pd.set_option('display.max_colwidth', None)
This accomplishes the task and complies with versions of pandas following version 1.0.
May be i am late
$e = explode("?",basename($_SERVER['REQUEST_URI']));
$filename = $e[0];
For solving this issue i would recommend to define explicitly the version for the ext variables
at the android/build.gradle
at your root project
ext {
googlePlayServicesVersion = "16.1.0" // default: "+"
firebaseVersion = "15.0.2" // default: "+"
// Other settings
compileSdkVersion = <Your compile SDK version> // default: 23
buildToolsVersion = "<Your build tools version>" // default: "23.0.1"
targetSdkVersion = <Your target SDK version> // default: 23
supportLibVersion = "<Your support lib version>" // default: 23.1.1
}
reference https://github.com/zo0r/react-native-push-notification/issues/1109#issuecomment-506414941
@Sheridan thx.. if I try your example with "DisplayedImagePath" on both sides, it works with absolute path as you show.
As for the relative paths, this is how I always connect relative paths, I first include the subdirectory (!) and the image file in my project.. then I use ~ character to denote the bin-path..
public string DisplayedImagePath
{
get { return @"~\..\images\osc.png"; }
}
This was tested, see below my Solution Explorer in VS2015..
Note: if you want a Click event, use the Button tag around the image,
<Button Click="image_Click" Width="128" Height="128" Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Left">_x000D_
<Image x:Name="image" Source="{Binding DisplayedImagePath}" Margin="0,0,0,0" />_x000D_
</Button>
_x000D_
If you are on firefox install JSONovich. Not really a PHP solution I know, but it does the trick for development purposes/debugging.
You can add information about parameters, returns, etc. as well using:
/**
* This is the foo function
* @param bar This is the bar parameter
* @returns returns a string version of bar
*/
function foo(bar: number): string {
return bar.toString()
}
This will cause editors like VS Code to display it as the following:
The basic framework suggested looks fine, but the error object as defined is too limited. One often cannot use a single value to express the problem, and instead a chain of problems and causes is needed.
I did a little research and found that the most common format for returning error (exceptions) is a structure of this form:
{
"success": false,
"error": {
"code": "400",
"message": "main error message here",
"target": "approx what the error came from",
"details": [
{
"code": "23-098a",
"message": "Disk drive has frozen up again. It needs to be replaced",
"target": "not sure what the target is"
}
],
"innererror": {
"trace": [ ... ],
"context": [ ... ]
}
}
}
This is the format proposed by the OASIS data standard OASIS OData and seems to be the most standard option out there, however there does not seem to be high adoption rates of any standard at this point. This format is consistent with the JSON-RPC specification.
You can find the complete open source library that implements this at: Mendocino JSON Utilities. This library supports the JSON Objects as well as the exceptions.
The details are discussed in my blog post on Error Handling in JSON REST API
This one just works by auto detecting the current user location.
import moment from "moment/min/moment-with-locales";
// Then use it as you always do.
moment(yourDate).format("MMMM Do YYYY, h:mm a")
ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.count).row
ActiveSheet can be replaced with WorkSheets(1)
or WorkSheets("name here")
If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".
First, checkout temp branch and start standard merge
git checkout -b temp
git merge origin/master
You will have to resolve conflicts, but only once and only real ones. Then stage all files and finish merge.
git commit -m "Merge branch 'origin/master' into 'temp'"
Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.
git checkout alpha
git rebase origin/master -X theirs
Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.
git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)
And delete temporary branch
git branch -D temp
That's all. We did a rebase via hidden merge.
Also I wrote a script, so that can be done in a dialog manner, you can find it here.
$("tr.item").each(function() {
$this = $(this);
var value = $this.find("span.value").html();
var quantity = $this.find("input.quantity").val();
});
one thing that tripped me up on a new install of mySQL and wonder why I couldn't get the default password to work and why even the reset methods where not working. well turns out that on Ubuntu 18 the most recent version of mysql server does not use password auth at all for the root user by default. So this means it doesn't matter what you set it to, it won't let you use it. it's expecting you to login from a privileged socket. so
mysql -u root -p
will not work at all, even if you are using the correct password!!! it will deny access no matter what you put in.
Instead you need to use
sudo mysql
that will work with out any password. then once you in you need type in
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Password you want to use';
then log out and now the bloody thing will finally accept your password
Use the Format function.
Format(Date, "yyyy-mm-dd hh:MM:ss")
I have used the below code, and it is working fine for me, for both cases, HTTP and HTTPS.
function curPageURL() {
if(isset($_SERVER["HTTPS"]) && !empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] != 'on' )) {
$url = 'https://'.$_SERVER["SERVER_NAME"];//https url
} else {
$url = 'http://'.$_SERVER["SERVER_NAME"];//http url
}
if(( $_SERVER["SERVER_PORT"] != 80 )) {
$url .= $_SERVER["SERVER_PORT"];
}
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
echo curPageURL();
A String
in Java can be converted to "binary" with its getBytes(Charset)
method.
byte[] encoded = "????????!".getBytes(StandardCharsets.UTF_8);
The argument to this method is a "character-encoding"; this is a standardized mapping between a character and a sequence of bytes. Often, each character is encoded to a single byte, but there aren't enough unique byte values to represent every character in every language. Other encodings use multiple bytes, so they can handle a wider range of characters.
Usually, the encoding to use will be specified by some standard or protocol that you are implementing. If you are creating your own interface, and have the freedom to choose, "UTF-8" is an easy, safe, and widely supported encoding.
Also, would I be right in concluding that a list comprehension is the most efficient way to do this?
Maybe. List comprehensions are not inherently computationally efficient. It is still running in linear time.
From my personal experience: I have significantly reduced computation time when dealing with large data sets by replacing list comprehensions (specifically nested ones) with for-loop/list-appending type structures you have above. In this application I doubt you will notice a difference.
Performance wise substring(0, 1)
is better as found by following:
String example = "something";
String firstLetter = "";
long l=System.nanoTime();
firstLetter = String.valueOf(example.charAt(0));
System.out.println("String.valueOf: "+ (System.nanoTime()-l));
l=System.nanoTime();
firstLetter = Character.toString(example.charAt(0));
System.out.println("Character.toString: "+ (System.nanoTime()-l));
l=System.nanoTime();
firstLetter = example.substring(0, 1);
System.out.println("substring: "+ (System.nanoTime()-l));
Output:
String.valueOf: 38553
Character.toString: 30451
substring: 8660
Load names with tf.train.match_filenames_once get the number of files to iterate over with tf.size open session and enjoy ;-)
import tensorflow as tf
import numpy as np
import matplotlib;
from PIL import Image
matplotlib.use('Agg')
import matplotlib.pyplot as plt
filenames = tf.train.match_filenames_once('./images/*.jpg')
count_num_files = tf.size(filenames)
filename_queue = tf.train.string_input_producer(filenames)
reader=tf.WholeFileReader()
key,value=reader.read(filename_queue)
img = tf.image.decode_jpeg(value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
num_files = sess.run(count_num_files)
for i in range(num_files):
image=img.eval()
print(image.shape)
Image.fromarray(np.asarray(image)).save('te.jpeg')
go run .
will run all of your files. The entry point is the function main()
which has to be unique to the main
package.
Another option is to build the binary with go build
and run it.
Another alternative (other than binary operators suggested by @jm-) is to use ng-switch:
<span ng-switch on="interface">
<img ng-switch-when="UP" src='green-checkmark.png'>
<img ng-switch-default src='big-black-X.png'>
</span>
ng-switch will likely be better/easier if you have more than two images.
how will I know that some tables are locked?
You can use SHOW OPEN TABLES command to view locked tables.
how do I unlock tables manually?
If you know the session ID that locked tables - 'SELECT CONNECTION_ID()', then you can run KILL command to terminate session and unlock tables.
static arrary meens with giving on elements in side the array
dynamic arrary meens without giving on elements in side the array
example:
char a[10]; //static array
char a[]; //dynamic array
Despite the plethora of wrong answers here that attempt to circumvent the error by numerically manipulating the predictions, the root cause of your error is a theoretical and not computational issue: you are trying to use a classification metric (accuracy) in a regression (i.e. numeric prediction) model (LinearRegression
), which is meaningless.
Just like the majority of performance metrics, accuracy compares apples to apples (i.e true labels of 0/1 with predictions again of 0/1); so, when you ask the function to compare binary true labels (apples) with continuous predictions (oranges), you get an expected error, where the message tells you exactly what the problem is from a computational point of view:
Classification metrics can't handle a mix of binary and continuous target
Despite that the message doesn't tell you directly that you are trying to compute a metric that is invalid for your problem (and we shouldn't actually expect it to go that far), it is certainly a good thing that scikit-learn at least gives you a direct and explicit warning that you are attempting something wrong; this is not necessarily the case with other frameworks - see for example the behavior of Keras in a very similar situation, where you get no warning at all, and one just ends up complaining for low "accuracy" in a regression setting...
I am super-surprised with all the other answers here (including the accepted & highly upvoted one) effectively suggesting to manipulate the predictions in order to simply get rid of the error; it's true that, once we end up with a set of numbers, we can certainly start mingling with them in various ways (rounding, thresholding etc) in order to make our code behave, but this of course does not mean that our numeric manipulations are meaningful in the specific context of the ML problem we are trying to solve.
So, to wrap up: the problem is that you are applying a metric (accuracy) that is inappropriate for your model (LinearRegression
): if you are in a classification setting, you should change your model (e.g. use LogisticRegression
instead); if you are in a regression (i.e. numeric prediction) setting, you should change the metric. Check the list of metrics available in scikit-learn, where you can confirm that accuracy is used only in classification.
Compare also the situation with a recent SO question, where the OP is trying to get the accuracy of a list of models:
models = []
models.append(('SVM', svm.SVC()))
models.append(('LR', LogisticRegression()))
models.append(('LDA', LinearDiscriminantAnalysis()))
models.append(('KNN', KNeighborsClassifier()))
models.append(('CART', DecisionTreeClassifier()))
models.append(('NB', GaussianNB()))
#models.append(('SGDRegressor', linear_model.SGDRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('BayesianRidge', linear_model.BayesianRidge())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('LassoLars', linear_model.LassoLars())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('ARDRegression', linear_model.ARDRegression())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('PassiveAggressiveRegressor', linear_model.PassiveAggressiveRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('TheilSenRegressor', linear_model.TheilSenRegressor())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
#models.append(('LinearRegression', linear_model.LinearRegression())) #ValueError: Classification metrics can't handle a mix of binary and continuous targets
where the first 6 models work OK, while all the rest (commented-out) ones give the same error. By now, you should be able to convince yourself that all the commented-out models are regression (and not classification) ones, hence the justified error.
A last important note: it may sound legitimate for someone to claim:
OK, but I want to use linear regression and then just round/threshold the outputs, effectively treating the predictions as "probabilities" and thus converting the model into a classifier
Actually, this has already been suggested in several other answers here, implicitly or not; again, this is an invalid approach (and the fact that you have negative predictions should have already alerted you that they cannot be interpreted as probabilities). Andrew Ng, in his popular Machine Learning course at Coursera, explains why this is a bad idea - see his Lecture 6.1 - Logistic Regression | Classification at Youtube (explanation starts at ~ 3:00), as well as section 4.2 Why Not Linear Regression [for classification]? of the (highly recommended and freely available) textbook An Introduction to Statistical Learning by Hastie, Tibshirani and coworkers...
I am working on JUnit in java 8 environment, using jUnit4.12
for me: compiler was not able to find the method assertNotEquals, even when I used
import org.junit.Assert;
So I changed assertNotEquals("addb", string);
toAssert.assertNotEquals("addb", string);
So if you are facing problem regarding assertNotEqual
not recognized, then change it to Assert.assertNotEquals(,);
it should solve your problem
The next approach work to me with Visual Studio 2013 Update 4 1- From Solution Explorer right click on References then select add references 2- Assemblies > Framework > System.Data.OracleClient > OK and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE
OracleConnection oraConnection = new OracleConnection(@"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}
and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method
public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;
if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
Johnsyweb's answer didn't work for me, but it works for me with Mutt:
echo "Message body" | mutt -s "Message subject" -a myfile.txt [email protected]
Unit testing
- is an approach of testing where the unit(class, method) is under control.
Test double
- is not a primary object(from OOP world). It is a realisation which is created temporary to test, check or during development. Test doubles types:
fake object
is a real implementation of interface(protocol) or an extend which is using an inheritance or other approaches which can be used to create - is
dependency. Usually it is created by developer as a simplest solution to substitute some dependency
stub object
is a bare object(0, nil and methods without logic) with extra state which is predefined(by developer) to define returned values. Usually it is created by framework
mock object
is very similar to stub object
but the extra state is changed during program execution to check if something happened(method was called).
spy object
is a real object with a "partial mocking". It means that you work with a non-double object except mocked behavior
dummy object
is object which is necessary to run a test but no one variable or method of this object is not called.
stub vs mock
There is a difference in that the stub uses state verification while the mock uses behavior verification.
Resolved by simply "Refresh All Gradle Projects"
I believe I have encountered the same quandary. I started encountering the problem when I changed to:
</system.web>
<httpRuntime targetFramework="4.5"/>
Which gives the error message you describe above.
adding:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
Solves the issue, but then it makes your validation controls/scripts throw Javascript runtime errors. If you change to:
</system.web>
<httpRuntime targetFramework="4.0"/>
You should be OK, but you’ll have to make sure the rest of your code does/ behaves as desired. You might also have to forgo some new features only available in 4.5 onward.
P.S. It is highly recommended that you read the following before implementing this solution. Especially, if you use Async functionality:
https://blogs.msdn.microsoft.com/webdev/2012/11/19/all-about-httpruntime-targetframework/
UPDATE April 2017: After some some experimentation and testing I have come up with a combination that works:
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<httpRuntime targetFramework="4.5.1" />
with:
jQuery version 1.11.3
I think this may help you solve your issue.
Imagine you have a dictionary like this:
dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}
And you want to change values by this one:
dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}
You can use code bellow to change values of dic0
properly respected to dic0t01
without worrying yourself about indexes in dictionary:
for x, y in dic0.items():
dic0[x] = dic0to1[y]
Now you have:
>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}
This also can happen just by having multiple supported frameworks defined in the app.config file and, forcing the app to run in a different .NET framework other than the one mentioned first in the app.config file.
And also this fires when you have both of the mentioned frameworks available in your system.
As a workaround, bring up the target framework you are going to use for the debugging up in the app.config
ex: if you trying to run in .NET 4, config file should have something similar to this,
<supportedRuntime version="v4.0"/>
<supportedRuntime version="v2.0.50727"/>
One set of familiar operations that you can do in MapReduce is the set of normal SQL operations: SELECT, SELECT WHERE, GROUP BY, ect.
Another good example is matrix multiply, where you pass one row of M and the entire vector x and compute one element of M * x.
JavaScript will "convert" numeric string to integer, if you perform calculations on it (as JS is weakly typed). But you can convert it yourself using parseInt
or parseFloat
.
Just remember to put radix in parseInt
!
In case of integer inputs:
var x = parseInt(prompt("Enter a Value", "0"), 10);
var y = parseInt(prompt("Enter a Value", "0"), 10);
In case of float:
var x = parseFloat(prompt("Enter a Value", "0"));
var y = parseFloat(prompt("Enter a Value", "0"));
This answer might be helpful for a future Googler.
#include <stdio.h>
#include <unistd.h>
int main(){
int p, f;
int rw_setup[2];
char message[20];
p = pipe(rw_setup);
if(p < 0){
printf("An error occured. Could not create the pipe.");
_exit(1);
}
f = fork();
if(f > 0){
write(rw_setup[1], "Hi from Parent", 15);
}
else if(f == 0){
read(rw_setup[0],message,15);
printf("%s %d\n", message, r_return);
}
else{
printf("Could not create the child process");
}
return 0;
}
You can find an advanced two-way pipe call example here.
Using the ampersand (&) will run the command in a child process (child to the current bash session). However, when you exit the session, all child processes will be killed.
using nohup + ampersand (&) will do the same thing, except that when the session ends, the parent of the child process will be changed to "1" which is the "init" process, thus preserving the child from being killed.
What I can quickly think of is, generate the pdf and store it in webapp/downloads/< RANDOM-FILENAME>.pdf from the code and send a forward to this file using HttpServletRequest
request.getRequestDispatcher("/downloads/<RANDOM-FILENAME>.pdf").forward(request, response);
or if you can configure your view resolver something like,
<bean id="pdfViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="order" value=”2"/>
<property name="prefix" value="/downloads/" />
<property name="suffix" value=".pdf" />
</bean>
then just return
return "RANDOM-FILENAME";
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
Once you declare the type of a variable, you don't need to cast it to that same type. So you can write a=&b;
. Finally, you declared c
incorrectly. Since you assign it to be the address of a
, where a
is a pointer to int
, you must declare it to be a pointer to a pointer to int
.
#include <stdio.h>
int main(void)
{
int b=10;
int *a=&b;
int **c=&a;
printf("%d", **c);
return 0;
}
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();