Please note that 4.0 is not sufficient since ListValuedMap, was introduced in version 4.1.
You need to use this maven repository link for version 4.1. Replicated below for convenience
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
You could do this:
String json = new ObjectMapper().writeValueAsString(yourObjectHere);
No, but another great alternative is having the method use a generic template class for optional parameters as follows:
public class OptionalOut<Type>
{
public Type Result { get; set; }
}
Then you can use it as follows:
public string foo(string value, OptionalOut<int> outResult = null)
{
// .. do something
if (outResult != null) {
outResult.Result = 100;
}
return value;
}
public void bar ()
{
string str = "bar";
string result;
OptionalOut<int> optional = new OptionalOut<int> ();
// example: call without the optional out parameter
result = foo (str);
Console.WriteLine ("Output was {0} with no optional value used", result);
// example: call it with optional parameter
result = foo (str, optional);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
// example: call it with named optional parameter
foo (str, outResult: optional);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
}
I might approach it like so (CSS and HTML):
html,_x000D_
body {_x000D_
margin: 0px;_x000D_
}_x000D_
#logo {_x000D_
position: absolute; /* Reposition logo from the natural layout */_x000D_
left: 75px;_x000D_
top: 0px;_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
z-index: 2;_x000D_
}_x000D_
#content {_x000D_
margin-top: 100px; /* Provide buffer for logo */_x000D_
}_x000D_
#links {_x000D_
height: 75px;_x000D_
margin-left: 400px; /* Flush links (with a 25px "padding") right of logo */_x000D_
}
_x000D_
<div id="logo">_x000D_
<img src="https://via.placeholder.com/200x100" />_x000D_
</div>_x000D_
<div id="content">_x000D_
_x000D_
<div id="links">dssdfsdfsdfsdf</div>_x000D_
</div>
_x000D_
I have made a small library to ease changing and translating the error messages. You can even change the texts by error type which is currently not available using title
in Chrome or x-moz-errormessage
in Firefox. Go check it out on GitHub, and give feedback.
It's used like:
<input type="email" required data-errormessage-value-missing="Please input something">
There's a demo available at jsFiddle.
For Reactive Forms, you can subscribe to the changes made to all fields or just a particular field.
Get all changes of a FormGroup:
this.orderForm.valueChanges.subscribe(value => {
console.dir(value);
});
Get the change of a specific field:
this.orderForm.get('orderPriority').valueChanges.subscribe(value => {
console.log(value);
});
Type "id" on terminal to see the available user ids you can give, Then simply type
"sudo chown -R idname /data/db"
This worked out for me! Hope this resolves your issue.
OCR can be pretty CPU intensive, you might want to reconsider doing it on a smart phone.
That aside, to my knowledge the popular OCR libraries are Aspire and Tesseract. Neither are straight up Java, so you're not going to get a drop-in Android OCR library.
However, Tesseract is open source (GitHub hosted infact); so you can throw some time at porting the subset you need to Java. My understanding is its not insane C++, so depending on how badly you need OCR it might be worth the time.
So short answer: No.
Long answer: if you're willing to work for it.
I use a similar approach to what Endy Tjahjono does.
What I do is to save the value of the current state before making a transition. Lets see on an example; imagine this inside a function executed when cliking to whatever triggers the transition:
$state.go( 'state-whatever', { previousState : { name : $state.current.name } }, {} );
The key here is the params object (a map of the parameters that will be sent to the state) -> { previousState : { name : $state.current.name } }
Note: note that Im only "saving" the name attribute of the $state object, because is the only thing I need for save the state. But we could have the whole state object.
Then, state "whatever" got defined like this:
.state( 'user-edit', {
url : 'whatever'
templateUrl : 'whatever',
controller: 'whateverController as whateverController',
params : {
previousState: null,
}
});
Here, the key point is the params object.
params : {
previousState: null,
}
Then, inside that state, we can get the previous state like this:
$state.params.previousState.name
To call a specific exception such as FileNotFoundException use this format
if (-not (Test-Path $file))
{
throw [System.IO.FileNotFoundException] "$file not found."
}
To throw a general exception use the throw command followed by a string.
throw "Error trying to do a task"
When used inside a catch, you can provide additional information about what triggered the error
Check for error code 10048
try
{
TcpListener tcpListener = new TcpListener(ipAddress, portNumber);
tcpListener.Start();
}
catch(SocketException ex)
{
if(ex.ErrorCode == 10048)
{
MessageBox.Show("Port " + portNumber + " is currently in use.");
}
return;
}
<?php
$val1 = rand(1,4);
$val2=rand(1,4);
if ($pars[$last0] == "reviews" && $pars[$last] > 0) {
echo widget("Bootstrap Theme - Member Profile - Read Review",'',$w[website_id],$w);
} else { ?>
<div class="w100">
<div style="background:transparent!important;" class="w100 well" id="postreview">
<?php
$_GET[user_id] = $user[user_id];
$_GET[member_id] = $_COOKIE[userid];
$_GET[subaction] = "savereview";
$_GET[ip] = $_SERVER[REMOTE_ADDR];
$_GET[httpr] = $_ENV[requesturl];
echo form("member_review","",$w[website_id],$w);?>
</div></div>
ive replaced the 'else' with '&&' so both are placed ... argh
My personal preference is to delete the branch name after I’m done with a topic branch.
Instead of trying to use the branch name to explain the meaning of the branch, I start the subject line of the commit message in the first commit on that branch with “Branch:” and include further explanations in the body of the message if the subject does not give me enough space.
The branch name in my use is purely a handle for referring to a topic branch while working on it. Once work on the topic branch has concluded, I get rid of the branch name, sometimes tagging the commit for later reference.
That makes the output of git branch
more useful as well: it only lists long-lived branches and active topic branches, not all branches ever.
Matplolib now allows for 'annotation lines' as the OP was seeking. The annotate()
function allows several forms of connecting paths and a headless and tailess arrow, i.e., a simple line, is one of them.
ax.annotate("",
xy=(0.2, 0.2), xycoords='data',
xytext=(0.8, 0.8), textcoords='data',
arrowprops=dict(arrowstyle="-",
connectionstyle="arc3, rad=0"),
)
In the documentation it says you can draw only an arrow with an empty string as the first argument.
From the OP's example:
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")
# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
xy=(70, 100), xycoords='data',
xytext=(70, 250), textcoords='data',
arrowprops=dict(arrowstyle="-",
connectionstyle="arc3,rad=0."),
)
# draw diagonal line from (70, 90) to (90, 200)
plt.annotate("",
xy=(70, 90), xycoords='data',
xytext=(90, 200), textcoords='data',
arrowprops=dict(arrowstyle="-",
connectionstyle="arc3,rad=0."),
)
plt.show()
Just as in the approach in gcalmettes's answer, you can choose the color, line width, line style, etc..
Here is an alteration to a portion of the code that would make one of the two example lines red, wider, and not 100% opaque.
# draw vertical line from (70,100) to (70, 250)
plt.annotate("",
xy=(70, 100), xycoords='data',
xytext=(70, 250), textcoords='data',
arrowprops=dict(arrowstyle="-",
edgecolor = "red",
linewidth=5,
alpha=0.65,
connectionstyle="arc3,rad=0."),
)
You can also add curve to the connecting line by adjusting the connectionstyle
.
Look no more for IP addresses not being set in the expected header. Just do the following to inspect the whole server variables and figure out which one is suitable for your case:
print_r($_SERVER);
I was having the same problem in an application that I was maintaining, among all the adjustments to prepare the environment, I also spent almost an hour banging my head with this error "ORA-01036: illegal variable name / number" until I found out that the application connection was pointed to an outdated database, so the application passed two more parameters to the outdated database procedure causing the error.
I stumbled across this old question and I think the easiest approach is still missing.
You can use rio
to import all excel sheets with just one line of code.
library(rio)
data_list <- import_list("test.xls")
If you're a fan of the tidyverse
, you can easily import them as tibbles by adding the setclass
argument to the function call.
data_list <- import_list("test.xls", setclass = "tbl")
Suppose they have the same format, you could easily row bind them by setting the rbind
argument to TRUE
.
data_list <- import_list("test.xls", setclass = "tbl", rbind = TRUE)
require 'pp'
pp my_hash
Use pp
if you need a built-in solution and just want reasonable line breaks.
Use awesome_print if you can install a gem. (Depending on your users, you may wish to use the index:false
option to turn off displaying array indices.)
This should be the most reliable way regardless of the compiler:
m=std::stringstream();
PLEASE ADD REASON FOR DOWNVOTE
No need to use any external library to extend
In JavaScript, everything is an object (except for the three primitive datatypes, and even they are automatically wrapped with objects when needed). Furthermore, all objects are mutable.
Class Person in JavaScript
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype = {
getName: function() {
return this.name;
},
getAge: function() {
return this.age;
}
}
/* Instantiate the class. */
var alice = new Person('Alice', 93);
var bill = new Person('Bill', 30);
Modify a specific instance/object.
alice.displayGreeting = function()
{
alert(this.getGreeting());
}
Modify the class
Person.prototype.getGreeting = function()
{
return 'Hi ' + this.getName() + '!';
};
Or simply say : extend JSON and OBJECT both are same
var k = {
name : 'jack',
age : 30
}
k.gender = 'male'; /*object or json k got extended with new property gender*/
thanks to ross harmes , dustin diaz
If you are not able to find platform-tools folder, please open SDK Manager and install "Android SDK Platform-Tools" from SDK Tools tab.
I seem to remember my computer science professor say back in the day that all problems that have recursive solutions also have iterative solutions. He says that a recursive solution is usually slower, but they are frequently used when they are easier to reason about and code than iterative solutions.
However, in the case of more advanced recursive solutions, I don't believe that it will always be able to implement them using a simple for
loop.
I think you have downloaded the .NET Reflector & this FileGenerator plugin http://filegenreflector.codeplex.com/ , If you do,
Open up the Reflector.exe,
Go to View and click Add-Ins,
In the Add-Ins window click Add...,
Then find the dll you have downloaded
FileGenerator.dll (witch came wth the FileGenerator plugin),
Then close the Add-Ins window.
Go to File and click Open and choose the dll that you want to decompile,
After you have opend it, it will appear in the tree view,
Go to Tools and click Generate Files(Crtl+Shift+G),
select the output directory and select appropriate settings as your wish, Click generate files.
OR
Try this for kotlin. Add Regex and add to the when statement.
private fun getCardType(number: String): String {
val visa = Regex("^4[0-9]{12}(?:[0-9]{3})?$")
val mastercard = Regex("^5[1-5][0-9]{14}$")
val amx = Regex("^3[47][0-9]{13}$")
return when {
visa.matches(number) -> "Visa"
mastercard.matches(number) -> "Mastercard"
amx.matches(number) -> "American Express"
else -> "Unknown"
}
}
Objects are instances of classes. Classes are just the blueprints for objects. So given your class definition -
# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
name = "Unknown name"
age = 0
major = "Unknown major"
You can create a make_student
function by explicitly assigning the attributes to a new instance of Student
-
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
return student
But it probably makes more sense to do this in a constructor (__init__
) -
class Student(object):
def __init__(self, name="Unknown name", age=0, major="Unknown major"):
self.name = name
self.age = age
self.major = major
The constructor is called when you use Student()
. It will take the arguments defined in the __init__
method. The constructor signature would now essentially be Student(name, age, major)
.
If you use that, then a make_student
function is trivial (and superfluous) -
def make_student(name, age, major):
return Student(name, age, major)
For fun, here is an example of how to create a make_student
function without defining a class. Please do not try this at home.
def make_student(name, age, major):
return type('Student', (object,),
{'name': name, 'age': age, 'major': major})()
cat a.sh
#! /bin/bash
#going forward report subshell or command exit value if errors
#set -e
(cat b.txt)
echo "hi"
./a.sh; echo $?
cat: b.txt: No such file or directory
hi
0
with set -e commented out we see that echo "hi" exit status being reported and hi is printed.
cat a.sh
#! /bin/bash
#going forward report subshell or command exit value if errors
set -e
(cat b.txt)
echo "hi"
./a.sh; echo $?
cat: b.txt: No such file or directory
1
Now we see b.txt error being reported instead and no hi printed.
So default behaviour of shell script is to ignore command errors and continue processing and report exit status of last command. If you want to exit on error and report its status we can use -e option.
Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.
...assuming that bgbody.png actually exists :)
Is your CSS in a stylesheet file or in a <style>
block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.
Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.
You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:
<Grid>
<DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799" ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" CanUserAddRows="False"> </Grid>
C#
Public Class Test
{
public string m_field1_Test{get;set;}
public string m_field2_Test { get; set; }
public Test()
{
m_field1_Test = "field1";
m_field2_Test = "field2";
}
public MainWindow()
{
listTest = new List<Test>();
for (int i = 0; i < 10; i++)
{
obj = new Test();
listTest.Add(obj);
}
this.MyDatagrid.ItemsSource = ListTest;
InitializeComponent();
}
There are two ways you can do that
Start Your comment with "<!--"
then end your comment with "-->"
Example <!-- my comment goes here -->
Highlight the part you want to comment and press CTRL + SHIFT + /
<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">
If you need to 'see' the list of temporary tables, you could simply log the names used. (and as others have noted, it is possible to directly query this information)
If you need to 'see' the content of temporary tables, you will need to create real tables with a (unique) temporary name.
You can trace the SQL being executed using SQL Profiler:
[These articles target SQL Server versions later than 2000, but much of the advice is the same.]
If you have a lengthy process that is important to your business, it's a good idea to log various steps (step name/number, start and end time) in the process. That way you have a baseline to compare against when things don't perform well, and you can pinpoint which step(s) are causing the problem more quickly.
Sometimes rails generate migration add_email_to_users email:string
produces a migration like this
class AddEmailToUsers < ActiveRecord::Migration[5.0]
def change
end
end
In that case you have to manually an add_column
to change
:
class AddEmailToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :email, :string
end
end
And then run rake db:migrate
say you have var arr = [1,0,2]
arr.splice(-1,1)
will return to you array [1,0];
while arr.slice(-1,1)
will return to you array [2];
The following ex commands will (re-)split any number of windows:
:vertical ball
:ball
If there are hidden buffers, issuing these commands will also make the hidden buffers visible.
You are mixing mysqli and mysql extensions, which will not work.
You need to use
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysqli_select_db($myConnection, "mrmagicadam") or die ("no database");
mysqli
has many improvements over the original mysql
extension, so it is recommended that you use mysqli
.
Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu
.
This is the first description by the author taken from the github repository:
Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.
The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.
Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu
.
The following in an image of interface of the last version of pygubu
designer on a OS X Yosemite 10.10.2:
I would definitely give it a try, and contribute to its development.
I like using fsockopen open for this.
It also happens when you have not give enough permissions(read and write) to your sock file!
Just add expected permission to your sock contained folder and your sock file:
chmod ug+rw /path/to/your/
chmod ug+rw /path/to/your/file.sock
Then have fun!
The facade is another Request class, access it with the full path:
$input = \Request::all();
From laravel 5 you can also access it through the request()
function:
$input = request()->all();
You can do the access control at the Web server level using HTTP Basic authentication and htpasswd. There are a number of problems with this:
Unless you're building a site for internal use with few users, I wouldn't really recommend it.
RFC3986 defines two sets of characters you can use in a URI:
Reserved Characters: :/?#[]@!$&'()*+,;=
reserved = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
The purpose of reserved characters is to provide a set of delimiting characters that are distinguishable from other data within a URI. URIs that differ in the replacement of a reserved character with its corresponding percent-encoded octet are not equivalent.
Unreserved Characters: A-Za-z0-9-_.~
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
Characters that are allowed in a URI but do not have a reserved purpose are called unreserved.
The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.
To use the yaml module is extremely simple:
import yaml
config = yaml.safe_load(open("path/to/config.yml"))
look at familiar main method which takes string array as param
One more way:
j=i[0]
for k in range(1,len(i)):
j = numpy.vstack([j,i[k]])
In this case j
will be a numpy array
You can use jQuery click
instead of using onclick
attribute, Try the following:
$('table').on('click', 'input[type="button"]', function(e){
$(this).closest('tr').remove()
})
If your are looking for the value defined by applicationId
in gradle, you can simply use
BuildConfig.APPLICATION_ID
Moment.js is pretty big library to use for a single use case. I recommend using date-fns
instead. It offers basically the most functionality of Moment.js with a much smaller bundle size and many formatting options
.
import format from 'date-fns/format'
format('2013-03-10T02:00:00Z', 'YYYY-MM-DD'); // 2013-03-10, YYYY-MM-dd for 2.x
One thing to note is that, since it's the ISO 8601 time format, the browser generally converts from UTC time to local timezone. Though this is simple use case where you can probably do '2013-03-10T02:00:00Z'.substring(0, 10);
.
For more complex conversions date-fns
is the way to go.
I think, that will be good solution: /\S\w*/
For those running in such issues right now, just try to put an alias for the table, this should the trick, e.g:
SELECT myvalue
INTO myvar
FROM mytable x
WHERE x.anothervalue = 1;
It worked for me.
Cheers.
please chceck the type of file growth of the database, if its restricted make it unrestricted
emanuel.directive('hymn', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
// some ode
},
templateUrl: function(elem,attrs) {
return attrs.templateUrl || 'some/path/default.html'
}
}
});
So you can provide templateUrl via markup
<hymn template-url="contentUrl"><hymn>
Now you just take a care that property contentUrl populates with dynamically generated path.
Yes oracle is :
select * from user_tables
That is if you only want objects owned by the logged in user/schema
otherwise you can use all_tables
or dba_tables
which includes system tables.
YUI just recently added a utility specifically for this. See stylesheet.js here.
This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.
The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
clk, rst_n, data_rx_1, data_tx );
endmodule
This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.
This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.
module subcomponent(
input rst_n,
input clk,
...
It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) );
endmodule
This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.
Giving each port its own line and indenting correctly adds to the readability and code quality.
subcomponent subcomponent_instance_name (
.clk ( clk ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:
clk_gen(
.clk ( clk_sub ), // output
.en ( enable ) // input
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:
Note that the instance name for the second component has been changed
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.
wire [9:0] data_temp
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.
Use .port
with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk, // input **Auto connect**
.rst_n, // input **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
endmodule
This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.
Another trick that I think is even worse than the one above is .*
which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.
subcomponent subcomponent_instance_name (
.*, // **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.
Try:
chcp 65001
which will change the code page to UTF-8. Also, you need to use Lucida console fonts.
you can create selector file in res/drawable
example: res/drawable/selector_button.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_disabled" android:state_enabled="false" />
<item android:drawable="@drawable/btn_enabled" />
</selector>
and in layout activity, fragment or etc
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/selector_bg_rectangle_black"/>
Set the height for the parent element.
If you want to add plots to your Jupyter notebook, then %matplotlib inline
is a standard solution. And there are other magic commands will use matplotlib
interactively within Jupyter.
%matplotlib
: any plt
plot command will now cause a figure window to open, and further commands can be run to update the plot. Some changes will not draw automatically, to force an update, use plt.draw()
%matplotlib notebook
: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure
%matplotlib inline
: only draw static images in the notebook
Here is a method to merge a dictionary of data frames while keeping the column names in sync with the dictionary. Also it fills in missing values if needed:
def MergeDfDict(dfDict, onCols, how='outer', naFill=None):
keys = dfDict.keys()
for i in range(len(keys)):
key = keys[i]
df0 = dfDict[key]
cols = list(df0.columns)
valueCols = list(filter(lambda x: x not in (onCols), cols))
df0 = df0[onCols + valueCols]
df0.columns = onCols + [(s + '_' + key) for s in valueCols]
if (i == 0):
outDf = df0
else:
outDf = pd.merge(outDf, df0, how=how, on=onCols)
if (naFill != None):
outDf = outDf.fillna(naFill)
return(outDf)
def GenDf(size):
df = pd.DataFrame({'categ1':np.random.choice(a=['a', 'b', 'c', 'd', 'e'], size=size, replace=True),
'categ2':np.random.choice(a=['A', 'B'], size=size, replace=True),
'col1':np.random.uniform(low=0.0, high=100.0, size=size),
'col2':np.random.uniform(low=0.0, high=100.0, size=size)
})
df = df.sort_values(['categ2', 'categ1', 'col1', 'col2'])
return(df)
size = 5
dfDict = {'US':GenDf(size), 'IN':GenDf(size), 'GER':GenDf(size)}
MergeDfDict(dfDict=dfDict, onCols=['categ1', 'categ2'], how='outer', naFill=0)
I had almost the same problem, but with the following variation:
That's quite odd behavour, I cannot completely understand it. Hope It'll help somebody. too.
As the people above says, but I have to note one point. You have to check the checkbox:
Include in project build
Try the childElementCount property:
if ( element.childElementCount !== 0 ){
alert('i have children');
} else {
alert('no kids here');
}
One can use the textract library. It take care of both "doc" as well as "docx"
import textract
text = textract.process("path/to/file.extension")
You can even use 'antiword' (sudo apt-get install antiword) and then convert doc to first into docx and then read through docx2txt.
antiword filename.doc > filename.docx
Ultimately, textract in the backend is using antiword.
You can deserialize directly to a list by using the TypeReference
wrapper. An example method:
public static <T> T fromJSON(final TypeReference<T> type,
final String jsonPacket) {
T data = null;
try {
data = new ObjectMapper().readValue(jsonPacket, type);
} catch (Exception e) {
// Handle the problem
}
return data;
}
And is used thus:
final String json = "";
Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json);
It is not mandatory to cast the results of malloc
, since it returns void*
, and a void*
can be pointed to any datatype.
You don't need to create a user-defined setting. The built-in setting "Preprocessor Macros" works just fine. alt text http://idisk.mac.com/cdespinosa/Public/Picture%204.png
If you have multiple targets or projects that use the same prefix file, use Preprocessor Macros Not Used In Precompiled Headers instead, so differences in your macro definition don't trigger an unnecessary extra set of precompiled headers.
Here's the answer to my question I got back from Apple support.
Hi XXX,
I am following up with you about the deletion of your app, “XXX”. Recent changes have been made to the App Delete feature. In order to delete your app from iTunes Connect, you must now have one approved version before the delete button becomes available. For more information on the recent changes, please see the "Deleting an App" section of the iTunes Connect Guide (page 96-97):
You can only delete an app from the App Store if it was previously approved (meaning has one approved version).
From iTunes Connect Developer Guide - Transferring and Deleting Apps:
Apps that have not been approved yet can’t be deleted; instead, reject the app.
As of 2016, new changes have been made to iTunes Connect. Here are the screenshots of deleting an approved app from your account.
I hope people would allow them to turn things such as music off, as for button clicks, Sometimes, those are pretty cool. Use the
<audio controls autoplay hidden="hidden">
<source src="*file here*" type="*file extension (.mp3 .ogg etc.)*">
<!--This displays an error to users that don't have it supported-->
Your browser does not support the audio element.
</audio>
As you can see, I don't like to repeat myself much, But I decided with the hidden
tag.
Hope this helps.
What worked for me. The first library to import is the query library and right then call the jQuery.noConflict() method.
<head>
<script type="text/javascript" src="jquery.min.js"/>
<script>
var jq = jQuery.noConflict();
jq(document).ready(function(){
//.... your code here
});
</script>
Does GitHub have this social feature?
If the commit email is kept private, GitHub now (July 2020) proposes:
Users and organizations can now add Twitter usernames to their GitHub profiles
You can now add your Twitter username to your GitHub profile directly from your profile page, via profile settings, and also the REST API.
We've also added the latest changes:
- Organization admins can now add Twitter usernames to their profile via organization profile settings and the REST API.
- All users are now able to see Twitter usernames on user and organization profiles, as well as via the REST and GraphQL APIs.
- When sponsorable maintainers and organizations add Twitter usernames to their profiles, we'll encourage new sponsors to include that Twitter username when they share their sponsorships on Twitter.
That could be a workaround to leave a message to a GitHub user.
I have a simple solution on handling home button press. Here is my code, it can be useful:
public class LifeCycleActivity extends Activity {
boolean activitySwitchFlag = false;
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
activitySwitchFlag = true;
// activity switch stuff..
return true;
}
return false;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void onPause(){
super.onPause();
Log.v("TAG", "onPause" );
if(activitySwitchFlag)
Log.v("TAG", "activity switch");
else
Log.v("TAG", "home button");
activitySwitchFlag = false;
}
public void gotoNext(View view){
activitySwitchFlag = true;
startActivity(new Intent(LifeCycleActivity.this, NextActivity.class));
}
}
As a summary, put a boolean in the activity, when activity switch occurs(startactivity event), set the variable and in onpause event check this variable..
The term cohesion is indeed a little counter intuitive for what it means in software design.
Cohesion common meaning is that something that sticks together well, is united, which are characterized by strong bond like molecular attraction. However in software design, it means striving for a class that ideally does only one thing, so multiple sub-modules are not even involved.
Perhaps we can think of it this way. A part has the most cohesion when it is the only part (does only one thing and can't be broken down further). This is what is desired in software design. Cohesion simply is another name for "single responsibility" or "separation of concerns".
The term coupling on the hand is quite intuitive which means when a module doesn't depend on too many other modules and those that it connects with can be easily replaced for example obeying liskov substitution principle .
Probably one of the simplest examples of a potential memory leak, and how to avoid it, is the implementation of ArrayList.remove(int):
public E remove(int index) {
RangeCheck(index);
modCount++;
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index + 1, elementData, index,
numMoved);
elementData[--size] = null; // (!) Let gc do its work
return oldValue;
}
If you were implementing it yourself, would you have thought to clear the array element that is no longer used (elementData[--size] = null
)? That reference might keep a huge object alive ...
SELECT Dividend / ISNULL(NULLIF(Divisor,0), 1) AS Result from table
By catching the zero with a nullif(), then the resulting null with an isnull() you can circumvent your divide by zero error.
Rather than changing the connection string, you can use the IsValidDateTime
property of the MySqlDateTime
object to help you determine if you can cast the object as a DateTime
.
I had a scenario where I was trying to load data from an "UpdateTime" column that was only explicitly set when there was an update to the row (as opposed to the InsertedTime which was always set). For this case, I used the MySqlDataReader.GetMySqlDateTime
method like so:
using (MySqlDataReader reader = await MySqlHelper.ExecuteReaderAsync(...))
{
if (await reader.ReadAsync())
{
DateTime? updateTime = reader.GetMySqlDateTime("UpdateTime").IsValidDateTime ? (DateTime?)reader["UpdateTime"] : null;
}
}
This is also a very useful function if you are looking for a rows or data with where condition affected
function num_rows($table)
{
return $this->db->affected_rows($table);
}
With Angular 5 and up, you DON'T have to use HttpParams. You can directly send your json object as shown below.
let data = {limit: "2"};
this.httpClient.get<any>(apiUrl, {params: data});
Please note that data values should be string, ie; { params: {limit: "2"}}
Use HttpParams, HttpClient from @angular/common/http
import { HttpParams, HttpClient } from '@angular/common/http';
...
constructor(private httpClient: HttpClient) { ... }
...
let params = new HttpParams();
params = params.append("page", 1);
....
this.httpClient.get<any>(apiUrl, {params: params});
Also, try stringifying your nested object using JSON.stringify()
.
To read directory contents you can use readdir() and use a script, in my example download.php
, to download files
if ($handle = opendir('/path/to/your/dir/')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
}
}
closedir($handle);
}
In download.php
you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php
$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;
if(!file_exists($file)){ // file does not exist
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($file);
}
It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char*
could indicate an array of char
s, a char**
could indicate that it points to and array of char*
s.
In Log4j 2, you can use Logger.catching() to log a stacktrace from an exception that was caught.
try {
String msg = messages[messages.length];
logger.error("An exception should have been thrown");
} catch (Exception ex) {
logger.catching(ex);
}
Things have changed since this question was originally asked and answered. There's been a large amount of work done on getting cross-browser font embedding for body text to work using @font-face embedding.
Paul Irish put together Bulletproof @font-face syntax combining attempts from multiple other people. If you actually go through the entire article (not just the top) it allows a single @font-face statement to cover IE, Firefox, Safari, Opera, Chrome and possibly others. Basically this can feed out OTF, EOT, SVG and WOFF in ways that don't break anything.
Snipped from his article:
@font-face {
font-family: 'Graublau Web';
src: url('GraublauWeb.eot');
src: local('Graublau Web Regular'), local('Graublau Web'),
url("GraublauWeb.woff") format("woff"),
url("GraublauWeb.otf") format("opentype"),
url("GraublauWeb.svg#grablau") format("svg");
}
Working from that base, Font Squirrel put together a variety of useful tools including the @font-face Generator which allows you to upload a TTF or OTF file and get auto-converted font files for the other types, along with pre-built CSS and a demo HTML page. Font Squirrel also has Hundreds of @font-face kits.
Soma Design also put together the FontFriend Bookmarklet, which redefines fonts on a page on the fly so you can try things out. It includes drag-and-drop @font-face support in FireFox 3.6+.
More recently, Google has started to provide the Google Web Fonts, an assortment of fonts available under an Open Source license and served from Google's servers.
License Restrictions
Finally, WebFonts.info has put together a nice wiki'd list of Fonts available for @font-face embedding based on licenses. It doesn't claim to be an exhaustive list, but fonts on it should be available (possibly with conditions such as an attribution in the CSS file) for embedding/linking. It's important to read the licenses, because there are some limitations that aren't pushed forward obviously on the font downloads.
I faced the exact same problem. This problem occurred when I cloned using HTTPS URL and then tried to push the changes using Git Bash on Windows using:
git clone https://github.com/{username}/{repo}.git
However, when I used SSH URL to clone, this problem didn't occur:
git clone [email protected]:{username}/{repo}.git
This will be possible with setiosflags(ios::showpoint).
You can add a watchpoint for each variable you're interested in.
A watchpoint is a special breakpoint that stops the execution of an application whenever the value of a given expression changes, without specifying where it might occur. Unlike breakpoints (which are line-specific), watchpoints are associated with files. They take effect whenever a specified condition is true, regardless of when or where it occurred. You can set a watchpoint on a global variable by highlighting the variable in the editor, or by selecting it in the Outline view.
It's not sure what you mean with 'the program', but if you want to limit your application to one instance then you can use a Mutex to make sure that your application isn't already running.
[STAThread]
static void Main()
{
Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName");
try
{
if (mutex.WaitOne(0, false))
{
// Run the application
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
else
{
MessageBox.Show("An instance of the application is already running.");
}
}
finally
{
if (mutex != null)
{
mutex.Close();
mutex = null;
}
}
}
Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
The class java.sql.Date is designed to carry only a date without time, so the conversion result you see is correct for this type. You need to use a java.sql.Timestamp to get a full date with time.
java.util.Date newDate = result.getTimestamp("VALUEDATE");
you are using a smart quote “
instead of "
here:
git.exe clone -v “ssh://
^^^
Make sure you use the plain-old-double-quote.
If the data is in file.txt, then:
echo $(<file.txt) | tr -d ' '
The '$(<file.txt)
' reads the file and gives the contents as a series of words which 'echo' then echoes with a space between them. The 'tr' command then deletes any spaces:
22791;14336;22821;34653;21491;25522;33238;
Try PHPMyAdmin which has some really nice visualisation and editing feature. I am pretty sure you can even export to exel from it.
I found some issue about that kind of error
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database please let me know "[email protected]"
spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc
# Username and secret
spring.datasource.username = root
spring.datasource.password =
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Issue no 2.
Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine
in Xcode 8.3.2, iOS 10.3 Thats is good to now
Sample1:
let dayMoveRaw = 5
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 05
Sample2:
let dayMoveRaw = 55
let dayMove = String(format: "%02d", arguments: [dayMoveRaw])
print(dayMove) // 55
here's another one...
Select Day(DateAdd(day, -Day(DateAdd(month, 1, getdate())),
DateAdd(month, 1, getdate())))
Below is code to set footer and elements above.
import React, { Component } from 'react';
import { StyleSheet, View, Text, ScrollView } from 'react-native';
export default class App extends Component {
render() {
return (
<View style={styles.containerMain}>
<ScrollView>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
<Text> Main Content Here</Text>
</ScrollView>
<View style={styles.bottomView}>
<Text style={styles.textStyle}>Bottom View</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
containerMain: {
flex: 1,
alignItems: 'center',
},
bottomView: {
width: '100%',
height: 50,
backgroundColor: '#EE5407',
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
bottom: 0,
},
textStyle: {
color: '#fff',
fontSize: 18,
},
});
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
I've written following code which cleans object from proxies (if they are not already initialized)
public class PersistenceUtils {
private static void cleanFromProxies(Object value, List<Object> handledObjects) {
if ((value != null) && (!isProxy(value)) && !containsTotallyEqual(handledObjects, value)) {
handledObjects.add(value);
if (value instanceof Iterable) {
for (Object item : (Iterable<?>) value) {
cleanFromProxies(item, handledObjects);
}
} else if (value.getClass().isArray()) {
for (Object item : (Object[]) value) {
cleanFromProxies(item, handledObjects);
}
}
BeanInfo beanInfo = null;
try {
beanInfo = Introspector.getBeanInfo(value.getClass());
} catch (IntrospectionException e) {
// LOGGER.warn(e.getMessage(), e);
}
if (beanInfo != null) {
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
try {
if ((property.getWriteMethod() != null) && (property.getReadMethod() != null)) {
Object fieldValue = property.getReadMethod().invoke(value);
if (isProxy(fieldValue)) {
fieldValue = unproxyObject(fieldValue);
property.getWriteMethod().invoke(value, fieldValue);
}
cleanFromProxies(fieldValue, handledObjects);
}
} catch (Exception e) {
// LOGGER.warn(e.getMessage(), e);
}
}
}
}
}
public static <T> T cleanFromProxies(T value) {
T result = unproxyObject(value);
cleanFromProxies(result, new ArrayList<Object>());
return result;
}
private static boolean containsTotallyEqual(Collection<?> collection, Object value) {
if (CollectionUtils.isEmpty(collection)) {
return false;
}
for (Object object : collection) {
if (object == value) {
return true;
}
}
return false;
}
public static boolean isProxy(Object value) {
if (value == null) {
return false;
}
if ((value instanceof HibernateProxy) || (value instanceof PersistentCollection)) {
return true;
}
return false;
}
private static Object unproxyHibernateProxy(HibernateProxy hibernateProxy) {
Object result = hibernateProxy.writeReplace();
if (!(result instanceof SerializableProxy)) {
return result;
}
return null;
}
@SuppressWarnings("unchecked")
private static <T> T unproxyObject(T object) {
if (isProxy(object)) {
if (object instanceof PersistentCollection) {
PersistentCollection persistentCollection = (PersistentCollection) object;
return (T) unproxyPersistentCollection(persistentCollection);
} else if (object instanceof HibernateProxy) {
HibernateProxy hibernateProxy = (HibernateProxy) object;
return (T) unproxyHibernateProxy(hibernateProxy);
} else {
return null;
}
}
return object;
}
private static Object unproxyPersistentCollection(PersistentCollection persistentCollection) {
if (persistentCollection instanceof PersistentSet) {
return unproxyPersistentSet((Map<?, ?>) persistentCollection.getStoredSnapshot());
}
return persistentCollection.getStoredSnapshot();
}
private static <T> Set<T> unproxyPersistentSet(Map<T, ?> persistenceSet) {
return new LinkedHashSet<T>(persistenceSet.keySet());
}
}
I use this function over result of my RPC services (via aspects) and it cleans recursively all result objects from proxies (if they are not initialized).
var foo = true;
if (foo){
window.location.reload(true);
foo = false;
}
You have included the dependency for sflj's api, but not the dependency for the implementation of the api, that is a separate jar, you could try slf4j-simple-1.6.1.jar.
Here is how I solved this problem for the old (< 4.3) HttpClient (which I cannot upgrade), using the answer of Santosh Singh (who I gave a +1):
HttpClient httpclient = new HttpClient();
if (System.getProperty("http.proxyHost") != null) {
try {
HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort")));
httpclient.setHostConfiguration(hostConfiguration);
this.getLogger().warn("USING PROXY: "+httpclient.getHostConfiguration().getProxyHost());
} catch (Exception e) {
throw new ProcessingException("Cannot set proxy!", e);
}
}
EDITED
You can look into sys.tables for checking existence desired table:
IF NOT EXISTS (SELECT * FROM sys.tables
WHERE name = N'YourTable' AND type = 'U')
BEGIN
CREATE TABLE [SchemaName].[YourTable](
....
....
....
)
END
First, you have to create your own inline TS-Class, since the FormData Class is not well supported at the moment:
var data : {
name: string;
file: File;
} = {
name: "Name",
file: inputValue.files[0]
};
Then you send it to the Server with JSON.stringify(data)
let opts: RequestOptions = new RequestOptions();
opts.method = RequestMethods.Post;
opts.headers = headers;
this.http.post(url,JSON.stringify(data),opts);
You could compare String representations so:
array1.toString() == array2.toString()
array1.toString() !== array3.toString()
but that would also make
array4 = ['1',2,3,4,5]
equal to array1 if that matters to you
Observations:
#include <cstring>
should introduce std::strcpy().using namespace std;
(as written in medico.h) introduces any identifiers from std::
into the global namespace.Aside from using namespace std;
being somewhat clumsy once the application grows larger (as it introduces one hell of a lot of identifiers into the global namespace), and that you should never use using
in a header file (see below!), using namespace
does not affect identifiers introduced after the statement.
(using namespace std
is written in the header, which is included in medico.cpp, but #include <cstring>
comes after that.)
My advice: Put the using namespace std;
(if you insist on using it at all) into medico.cpp, after any includes, and use explicit std::
in medico.h.
strcmpi()
is not a standard function at all; while being defined on Windows, you have to solve case-insensitive compares differently on Linux.
(On general terms, I would like to point to this answer with regards to "proper" string handling in C and C++ that takes Unicode into account, as every application should. Summary: The standard cannot handle these things correctly; do use ICU.)
warning: deprecated conversion from string constant to ‘char*’
A "string constant" is when you write a string literal (e.g. "Hello"
) in your code. Its type is const char[]
, i.e. array of constant characters (as you cannot change the characters). You can assign an array to a pointer, but assigning to char *
, i.e. removing the const
qualifier, generates the warning you are seeing.
OT clarification: using
in a header file changes visibility of identifiers for anyone including that header, which is usually not what the user of your header file wants. For example, I could use std::string
and a self-written ::string
just perfectly in my code, unless I include your medico.h, because then the two classes will clash.
Don't use using
in header files.
And even in implementation files, it can introduce lots of ambiguity. There is a case to be made to use explicit namespacing in implementation files as well.
Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...
SELECT
(
col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
) AS my_column
FROM
mytable;
Tested on SQLite 3.8.8.3, Thanks!
It's a unicode character. In this case \u003C
and \u003E
mean :
U+003C < Less-than sign
U+003E > Greater-than sign
See a list here
Often you can use Apache commons BeanUtils or PropertyUtils which introspection (basically they cache the meta data about the classes so they don't always need to use reflection).
It is much better to use
$value = mb_convert_encode($value,'HTML-ENTITIES','UTF-8');
Specially when you are using AJAX call for submitting 'ISO-8859-1' characters. It works for Chinese, Japanese, Czech, German and many more languages.
Try to surround the path with quotes, and remove the spaces
export PYTHONPATH="/home/user/my_project":$PYTHONPATH
And don't forget to preserve previous content suffixing by :$PYTHONPATH (which is the value of the variable)
Execute the following command to check everything is configured correctly:
echo $PYTHONPATH
Short answer: in POST requests, values are sent in the "body" of the request. With web-forms they are most likely sent with a media type of application/x-www-form-urlencoded
or multipart/form-data
. Programming languages or frameworks which have been designed to handle web-requests usually do "The Right Thing™" with such requests and provide you with easy access to the readily decoded values (like $_REQUEST
or $_POST
in PHP, or cgi.FieldStorage()
, flask.request.form
in Python).
Now let's digress a bit, which may help understand the difference ;)
The difference between GET
and POST
requests are largely semantic. They are also "used" differently, which explains the difference in how values are passed.
When executing a GET
request, you ask the server for one, or a set of entities. To allow the client to filter the result, it can use the so called "query string" of the URL. The query string is the part after the ?
. This is part of the URI syntax.
So, from the point of view of your application code (the part which receives the request), you will need to inspect the URI query part to gain access to these values.
Note that the keys and values are part of the URI. Browsers may impose a limit on URI length. The HTTP standard states that there is no limit. But at the time of this writing, most browsers do limit the URIs (I don't have specific values). GET
requests should never be used to submit new information to the server. Especially not larger documents. That's where you should use POST
or PUT
.
When executing a POST
request, the client is actually submitting a new document to the remote host. So, a query string does not (semantically) make sense. Which is why you don't have access to them in your application code.
POST
is a little bit more complex (and way more flexible):
When receiving a POST request, you should always expect a "payload", or, in HTTP terms: a message body. The message body in itself is pretty useless, as there is no standard (as far as I can tell. Maybe application/octet-stream?) format. The body format is defined by the Content-Type
header. When using a HTML FORM
element with method="POST"
, this is usually application/x-www-form-urlencoded
. Another very common type is multipart/form-data if you use file uploads. But it could be anything, ranging from text/plain
, over application/json
or even a custom application/octet-stream
.
In any case, if a POST
request is made with a Content-Type
which cannot be handled by the application, it should return a 415
status-code.
Most programming languages (and/or web-frameworks) offer a way to de/encode the message body from/to the most common types (like application/x-www-form-urlencoded
, multipart/form-data
or application/json
). So that's easy. Custom types require potentially a bit more work.
Using a standard HTML form encoded document as example, the application should perform the following steps:
Content-Type
field415
status codeAgain, languages like PHP, or web-frameworks for other popular languages will probably handle this for you. The exception to this is the 415
error. No framework can predict which content-types your application chooses to support and/or not support. This is up to you.
A PUT
request is pretty much handled in the exact same way as a POST
request. The big difference is that a POST
request is supposed to let the server decide how to (and if at all) create a new resource. Historically (from the now obsolete RFC2616 it was to create a new resource as a "subordinate" (child) of the URI where the request was sent to).
A PUT
request in contrast is supposed to "deposit" a resource exactly at that URI, and with exactly that content. No more, no less. The idea is that the client is responsible to craft the complete resource before "PUTting" it. The server should accept it as-is on the given URL.
As a consequence, a POST
request is usually not used to replace an existing resource. A PUT
request can do both create and replace.
There are also "path parameters" which can be used to send additional data to the remote, but they are so uncommon, that I won't go into too much detail here. But, for reference, here is an excerpt from the RFC:
Aside from dot-segments in hierarchical paths, a path segment is considered opaque by the generic syntax. URI producing applications often use the reserved characters allowed in a segment to delimit scheme-specific or dereference-handler-specific subcomponents. For example, the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes. For example, one URI producer might use a segment such as "name;v=1.1" to indicate a reference to version 1.1 of "name", whereas another might use a segment such as "name,1.1" to indicate the same. Parameter types may be defined by scheme-specific semantics, but in most cases the syntax of a parameter is specific to the implementation of the URIs dereferencing algorithm.
<?php
$first = reset($arr_nav); // Get the first element
$last = end($arr_nav); // Get the last element
// Ensure that we have a first element and that it's an array
if(is_array($first)) {
$first['class'] = 'first';
}
// Ensure we have a last element and that it differs from the first
if(is_array($last) && $last !== $first) {
$last['class'] = 'last';
}
Now you could just echo the class inside you html-generator. Would probably need some kind of check to ensure that the class is set, or provide a default empty class to the array.
So, you essentially want to delete multiple elements in one pass? In that case, the position of the next element to delete will be offset by however many were deleted previously.
Our goal is to delete all the vowels, which are precomputed to be indices 1, 4, and 7. Note that its important the to_delete indices are in ascending order, otherwise it won't work.
to_delete = [1, 4, 7]
target = list("hello world")
for offset, index in enumerate(to_delete):
index -= offset
del target[index]
It'd be a more complicated if you wanted to delete the elements in any order. IMO, sorting to_delete
might be easier than figuring out when you should or shouldn't subtract from index
.
If they were declared as fields of the class then they would be really initialized with 0.
You're a bit confused because if you write:
class Clazz {
int a;
int b;
Clazz () {
super ();
b = 0;
}
public void printA () {
sout (a + b);
}
public static void main (String[] args) {
new Clazz ().printA ();
}
}
Then this code will print "0". It's because a special constructor will be called when you create new instance of Clazz. At first super ()
will be called, then field a
will be initialized implicitly, and then line b = 0
will be executed.
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
The Conclusion I can make is
1) We can do UI design without touching the xml part of code, to be honest I feel google has copied how UI is designed in iOS apps, it will make sense if you are familiar with UI development in iOS, but in relative layout its hard to set the constraints without touching the xml design.
2) Secondly it has flat view hierarchy unlike other layouts, so does better performance than relative layout which you might have seen from other answers
3) It also have extra things apart from what relative layout has, such as circular relative positioning where we can position another view relative to this one at certain radius with certain angle which cant do in relative layout
I am saying it again, designing UI using constraint layout is same as designing UI in iOS, so in future if you work on iOS you will find it easier if you have used constraint layout
Most SSL certificates are bound to the hostname of the machine and not the ip address.
You might get a better answer if you ask this question on serverfault.com
This is a late entry for folks, but below is my implementation. You will also notice I stubbed-out the ability to change the the KEYs default type: the details about which can be found in the following articles:
NOTES:
It should be noted that you cannot use Guid's
for your keys. This is because under the hood they are a Struct
, and as such, have no unboxing which would allow their conversion from a generic <TKey>
parameter.
THE CLASSES LOOK LIKE:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
#region <Constructors>
public ApplicationDbContext() : base(Settings.ConnectionString.Database.AdministrativeAccess)
{
}
#endregion
#region <Properties>
//public DbSet<Case> Case { get; set; }
#endregion
#region <Methods>
#region
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//modelBuilder.Configurations.Add(new ResourceConfiguration());
//modelBuilder.Configurations.Add(new OperationsToRolesConfiguration());
}
#endregion
#region
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
#endregion
#endregion
}
public class ApplicationUser : IdentityUser<string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
#region <Constructors>
public ApplicationUser()
{
Init();
}
#endregion
#region <Properties>
[Required]
[StringLength(250)]
public string FirstName { get; set; }
[Required]
[StringLength(250)]
public string LastName { get; set; }
#endregion
#region <Methods>
#region private
private void Init()
{
Id = Guid.Empty.ToString();
}
#endregion
#region public
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
#endregion
#endregion
}
public class CustomUserStore : UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
#region <Constructors>
public CustomUserStore(ApplicationDbContext context) : base(context)
{
}
#endregion
}
public class CustomUserRole : IdentityUserRole<string>
{
}
public class CustomUserLogin : IdentityUserLogin<string>
{
}
public class CustomUserClaim : IdentityUserClaim<string>
{
}
public class CustomRoleStore : RoleStore<CustomRole, string, CustomUserRole>
{
#region <Constructors>
public CustomRoleStore(ApplicationDbContext context) : base(context)
{
}
#endregion
}
public class CustomRole : IdentityRole<string, CustomUserRole>
{
#region <Constructors>
public CustomRole() { }
public CustomRole(string name)
{
Name = name;
}
#endregion
}
An optional is to use pyvirtualdisplay
like this:
from pyvirtualdisplay import Display
display = Display(visible=0, size=[800, 600])
display.start()
#do selenium job here
display.close()
A shorter version is:
with Display() as display:
# selenium job here
This is generally a python encapsulate of xvfb
, and more convinient somehow.
By the way, although PhantomJS
is a headless browser and no window will be open if you use it, it seems that PhantomJS
still needs a gui environment to work.
I got Error Code -6 when I use PhantomJS()
instead of Firefox()
in headless mode (putty-connected console). However everything is ok in desktop environment.
Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
Run below 2 commands in PowerShell window
Set-ExecutionPolicy unrestricted
Unblock-File -Path D:\PowerShell\Script.ps1
I encountered this problem when attempint to run my web application as a fat jar rather than from within my IDE (IntelliJ).
This is what worked for me. Simply adding a default profile to the application.properties file.
spring.profiles.active=default
You don't have to use default if you have already set up other specific profiles (dev/test/prod). But if you haven't this is necessary to run the application as a fat jar.
Just remove the throw
from the catch block — change it to an echo
or otherwise handle the error.
It's not telling you that objects can only be thrown in the catch block, it's telling you that only objects can be thrown, and the location of the error is in the catch block — there is a difference.
In the catch block you are trying to throw something you just caught — which in this context makes little sense anyway — and the thing you are trying to throw is a string.
A real-world analogy of what you are doing is catching a ball, then trying to throw just the manufacturer's logo somewhere else. You can only throw a whole object, not a property of the object.
Thanks for your replies. I have already solved my problem. Suppose I have my pages under http://www.yoursite.com/html, the following .htaccess rules apply.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /html/(.*).html\ HTTP/
RewriteRule .* http://localhost/html/%1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /html/(.*)\ HTTP/
RewriteRule .* %1.html [L]
</IfModule>
The other answers so far have a lot of technical information. I will try to answer, as requested, in simple terms.
Serialization is what you do to an instance of an object if you want to dump it to a raw buffer, save it to disk, transport it in a binary stream (e.g., sending an object over a network socket), or otherwise create a serialized binary representation of an object. (For more info on serialization see Java Serialization on Wikipedia).
If you have no intention of serializing your class, you can add the annotation just above your class @SuppressWarnings("serial")
.
If you are going to serialize, then you have a host of things to worry about all centered around the proper use of UUID. Basically, the UUID is a way to "version" an object you would serialize so that whatever process is de-serializing knows that it's de-serializing properly. I would look at Ensure proper version control for serialized objects for more information.
I solved the same problem here is simple solution: when you create firebase connection follow these guidelines:
Add your application name in firebase
Add your application pakage name (write same pakage name ,you are using in app)
when firebase make google-services.json file just download it and paste it in your app folder
Sync your project Problem is solved :)
Thank you
git push --tags production
I believe that if you download the offline ISO image file, and use that to install Visual Studio Express, you won't have to register.
Go here and find the link that says "All - Offline Install ISO image file". Click on it to expand it, select your language, and then click "Download".
Otherwise, it's possible that online registration is simply down for a while, as the error message indicates. You have 30 days before it expires, so give it a few days before starting to panic.
In our case, everything LOOKED ok, but it took most of the day to figure this out:
TLDR: Check your certificate paths to make sure the root certificate is correct. In the case of COMODO certificates, it should say "USERTrust" and be issued by "AddTrust External CA Root". NOT "COMODO" issued by "COMODO RSA Certification Authority".
From the CloudFront docs: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html
If the origin server returns an invalid certificate or a self-signed certificate, or if the origin server returns the certificate chain in the wrong order, CloudFront drops the TCP connection, returns HTTP error code 502, and sets the X-Cache header to Error from cloudfront.
We had the right ciphers enabled as per: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#RequestCustomEncryption
Our certificate was valid according to Google, Firefox and ssl-checker: https://www.sslshopper.com/ssl-checker.html
However the last certificate in the ssl checker chain was "COMODO RSA Domain Validation Secure Server CA", issued by "COMODO RSA Certification Authority"
It seems that CloudFront does not hold the certificate for "COMODO RSA Certification Authority" and as such thinks the certificate provided by the origin server is self signed.
This was working for a long time before apparently suddenly stopping. What happened was I had just updated our certificates for the year, but during the import, something was changed in the certificate path for all the previous certificates. They all started referencing "COMODO RSA Certification Authority" whereas before the chain was longer and the root was "AddTrust External CA Root".
Because of this, switching back to the older cert did not fix the cloudfront issue.
I had to delete the extra certificate named "COMODO RSA Certification Authority", the one that did not reference AddTrust. After doing this, all my website certificates' paths updated to point back to AddTrust/USERTrust again. Note can also open up the bad root certificate from the path, click "Details" -> "Edit Properties" and then disable it that way. This updated the path immediately. You may also need to delete multiple copies of the certificate, found under "Personal" and "Trusted Root Certificate Authorities"
Finally I had to re select the certificate in IIS to get it to serve the new certificate chain.
After all this, ssl-checker started displaying a third certificate in the chain, which pointed back to "AddTrust External CA Root"
Finally, CloudFront accepted the origin server's certificate and the provided chain as being trusted. Our CDN started working correctly again!
To prevent this happening in the future, we will need to export our newly generated certificates from a machine with the correct certificate chain, i.e. distrust or delete the certificate "COMODO RSA Certification Authroity" issued by "COMODO RSA Certification Authroity" (expiring in 2038). This only seems to affect windows machines, where this certificate is installed by default.
For Current date and time as the name for a file on the file system. Now call the string.Format method, and combine it with DateTime.Now, for a method that outputs the correct string based on the date and time.
using System;
using System.IO;
class Program
{
static void Main()
{
//
// Write file containing the date with BIN extension
//
string n = string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin",
DateTime.Now);
File.WriteAllText(n, "abc");
}
}
Output :
C:\Users\Fez\Documents\text-2020-01-08_05-23-13-PM.bin
"text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin"
text- The first part of the output required Files will all start with text-
{0: Indicates that this is a string placeholder The zero indicates the index of the parameters inserted here
yyyy- Prints the year in four digits followed by a dash This has a "year 10000" problem
MM- Prints the month in two digits
dd_ Prints the day in two digits followed by an underscore
hh- Prints the hour in two digits
mm- Prints the minute, also in two digits
ss- As expected, it prints the seconds
tt Prints AM or PM depending on the time of day
It sounds like you're looking for applicationHost.config
, which is located in C:\Windows\System32\inetsrv\config
.
Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config
and web.config
.
private void Form1_Load(object sender, EventArgs e)
{
PictureBox pb = new PictureBox();
pb.Location = new Point(0, 0);
pb.Size = new Size(150, 150);
pb.Image = Image.FromFile("E:\\Wallpaper (204).jpg");
pb.Visible = true;
this.Controls.Add(pb);
}
import pickle
intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()
Test your pickle quickly. pickle is a part of standard python library and available by default.
You have to specify any one of the above phase to resolve the above error. In most of the situations, this would have occurred due to running the build from the eclipse environment.
instead of mvn clean package or mvn package you can try only package its work fine for me
Regarding building a DLL using MinGW, here are some very brief instructions.
First, you need to mark your functions for export, so they can be used by callers of the DLL. To do this, modify them so they look like (for example)
__declspec( dllexport ) int add2(int num){
return num + 2;
}
then, assuming your functions are in a file called funcs.c, you can compile them:
gcc -shared -o mylib.dll funcs.c
The -shared flag tells gcc to create a DLL.
To check if the DLL has actually exported the functions, get hold of the free Dependency Walker tool and use it to examine the DLL.
For a free IDE which will automate all the flags etc. needed to build DLLs, take a look at the excellent Code::Blocks, which works very well with MinGW.
Edit: For more details on this subject, see the article Creating a MinGW DLL for Use with Visual Basic on the MinGW Wiki.
I would try to avoid inserting empty lists in the first place, but, would generally use:
d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty
If prior to 2.7:
d = dict( (k, v) for k,v in d.iteritems() if v )
or just:
empty_key_vals = list(k for k in k,v in d.iteritems() if v)
for k in empty_key_vals:
del[k]
We can also use Exists
:
string[] array = { "cat", "dog", "perl" };
// Use Array.Exists in different ways.
bool a = Array.Exists(array, element => element == "perl");
bool c = Array.Exists(array, element => element.StartsWith("d"));
bool d = Array.Exists(array, element => element.StartsWith("x"));
Here is another way to do this - using the API function WideCharToMultiByte:
Option Explicit
Private Declare Function WideCharToMultiByte Lib "kernel32.dll" ( _
ByVal CodePage As Long, _
ByVal dwFlags As Long, _
ByVal lpWideCharStr As Long, _
ByVal cchWideChar As Long, _
ByVal lpMultiByteStr As Long, _
ByVal cbMultiByte As Long, _
ByVal lpDefaultChar As Long, _
ByVal lpUsedDefaultChar As Long) As Long
Private Sub getUtf8(ByRef s As String, ByRef b() As Byte)
Const CP_UTF8 As Long = 65001
Dim len_s As Long
Dim ptr_s As Long
Dim size As Long
Erase b
len_s = Len(s)
If len_s = 0 Then _
Err.Raise 30030, , "Len(WideChars) = 0"
ptr_s = StrPtr(s)
size = WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, 0, 0, 0, 0)
If size = 0 Then _
Err.Raise 30030, , "WideCharToMultiByte() = 0"
ReDim b(0 To size - 1)
If WideCharToMultiByte(CP_UTF8, 0, ptr_s, len_s, VarPtr(b(0)), size, 0, 0) = 0 Then _
Err.Raise 30030, , "WideCharToMultiByte(" & Format$(size) & ") = 0"
End Sub
Public Sub writeUtf()
Dim file As Integer
Dim s As String
Dim b() As Byte
s = "äöüßµ@€|~{}[]²³\ .." & _
" OMEGA" & ChrW$(937) & ", SIGMA" & ChrW$(931) & _
", alpha" & ChrW$(945) & ", beta" & ChrW$(946) & ", pi" & ChrW$(960) & vbCrLf
file = FreeFile
Open "C:\Temp\TestUtf8.txt" For Binary Access Write Lock Read Write As #file
getUtf8 s, b
Put #file, , b
Close #file
End Sub
Typescript fails in your case because it expects all the fields to be present. Use Record and Partial utility types to solve it.
Record<string, Partial<IPerson>>
interface IPerson {
firstName: string;
lastName: string;
}
var persons: Record<string, Partial<IPerson>> = {
"p1": { firstName: "F1", lastName: "L1" },
"p2": { firstName: "F2" }
};
Explanation.
Alternate.
If you wish to make last name optional you can append a ? Typescript will know that it's optional.
lastName?: string;
https://www.typescriptlang.org/docs/handbook/utility-types.html
For Java Developers who use SpringBoot, ÜBER/FAT JAR is normally the final result of the package phase
of maven (or build task
if you use gradle
).
Inside the Fat JAR one can find a META-INF
directory inside which the MANIFEST.MF
file lives with all the info regarding the Main class. More importantly, at the same level of META-INF
directory you find the BOOT-INF
directory inside which the directory lib
lives and contains all the .jar
files that are the dependencies of your application.
On Mac OS X, the way I enabled Jenkins to pull from my (private) Github repo is:
First, ensure that your user owns the Jenkins directory
sudo chown -R me:me /Users/Shared/Jenkins
Then edit the LaunchDaemon plist for Jenkins (at /Library/LaunchDaemons/org.jenkins-ci.plist) so that your user is the GroupName and the UserName:
<key>GroupName</key>
<string>me</string>
...
<key>UserName</key>
<string>me</string>
Then reload Jenkins:
sudo launchctl unload -w /Library/LaunchDaemons/org.jenkins-ci.plist
sudo launchctl load -w /Library/LaunchDaemons/org.jenkins-ci.plist
Then Jenkins, since it's running as you, has access to your ~/.ssh directory which has your keys.
changing:
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
width: 100%;
}
to:
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
width: auto;
float:left;
}
should start you off.
In java final keyword uses for below occasions.
In java final variables can't reassign, final classes can't extends and final methods can't override.
You can use -O-
(uppercase o) to redirect content to the stdout (standard output) or to a file (even special files like /dev/null
/dev/stderr
/dev/stdout
)
wget -O- http://yourdomain.com
Or:
wget -O- http://yourdomain.com > /dev/null
Or: (same result as last command)
wget -O/dev/null http://yourdomain.com
There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.
I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.
Here's how I did it in Swift 4.2:
extension Date {
/// Create a date from specified parameters
///
/// - Parameters:
/// - year: The desired year
/// - month: The desired month
/// - day: The desired day
/// - Returns: A `Date` object
static func from(year: Int, month: Int, day: Int) -> Date? {
let calendar = Calendar(identifier: .gregorian)
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
return calendar.date(from: dateComponents) ?? nil
}
}
Usage:
let marsOpportunityLaunchDate = Date.from(year: 2003, month: 07, day: 07)
**get id from dic value. I got the result.try the below code**
get_abstracts = s.get_abstracts(session_id)
sessions = get_abstracts['sessions']
abs = {}
for a in get_abstracts['abstracts']:
a_session_id = a['session_id']
abs.setdefault(a_session_id,[]).append(a)
authors = {}
# print('authors')
# print(get_abstracts['authors'])
for au in get_abstracts['authors']:
# print(au)
au_abs_id = au['abs_id']
authors.setdefault(au_abs_id,[]).append(au)
**In jinja template**
{% for s in sessions %}
<h4><u>Session : {{ s.session_title}} - Hall : {{ s.session_hall}}</u></h4>
{% for a in abs[s.session_id] %}
<hr>
<p><b>Chief Author :</b> Dr. {{ a.full_name }}</p>
{% for au in authors[a.abs_id] %}
<p><b> {{ au.role }} :</b> Dr.{{ au.full_name }}</p>
{% endfor %}
{% endfor %}
{% endfor %}
To get to a specific committed code, you need the hash code of that commit. You can get that hash code in two ways:
git log
and check your recent commits on that branch. It will show you the hash code of your commit and the message you leaved while you were committing your code. Just copy and then do git checkout commit_hash_code
After moving to that code, if you want to work on it and make changes, you should make another branch with git checkout -b <new-branch-name>
, otherwise, the changes will not be retained.
Use FLOOR(), if you want to round your decimal to the lower integer. Examples:
FLOOR(1.9) => 1
FLOOR(1.1) => 1
Use ROUND(), if you want to round your decimal to the nearest integer. Examples:
ROUND(1.9) => 2
ROUND(1.1) => 1
Use CEIL(), if you want to round your decimal to the upper integer. Examples:
CEIL(1.9) => 2
CEIL(1.1) => 2
It depends on the nature of data. You need to contemplate it beforehand.
Although MySQL lets you use decimal(65,30), 31 for scale and 30 for precision seem to be our limits if we want to leave transfer option open.
Maximum scale and precision in most common RDBMS:
Precision Scale Oracle 31 31 T-SQL 38 38 MySQL 65 30 PostgreSQL 131072 16383
September 2015 Zimbabwean government stated it would exchange Zimbabwean dollars for US dollars at a rate of 1 USD to 35 quadrillion Zimbabwean dollars 5
We tend to say "yeah, sure... I won't need that crazy figures". Well, Zimbabweans used to say that too. Not to long ago.
Let's imagine you need to record a transaction of 1 mln USD in Zimbabwean dollars (maybe unlikely today, but who knows how this will look like in 10 years from now?).
- (1 mln USD) * (35 Quadrylion ZWL) = ( 10^6 ) * (35 * 10^15) = 35 * 10^21
- we need:
- 2 digits to store "35"
- 21 digits to store the zeros
- 4 digits to the right of decimal point
- this makes decimal(27,4) which costs us 15 bytes for each entry
- we may add one more digit on the left at no expense - we have decimal(28,4) for 15 bytes
- Now we can store 10 mln USD transaction expressed in Zimbabwean dollars, or secure from another strike of hiperinflation, which hopefully won't happen
Do you mean immediate subdirectories, or every directory right down the tree?
Either way, you could use os.walk
to do this:
os.walk(directory)
will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so
[x[0] for x in os.walk(directory)]
should give you all of the subdirectories, recursively.
Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it's not likely to save you much.
However, you could use it just to give you the immediate child directories:
next(os.walk('.'))[1]
Or see the other solutions already posted, using os.listdir
and os.path.isdir
, including those at "How to get all of the immediate subdirectories in Python".
My 2 cent. Same but different...
<script>
dosomething("blaha", function(){
alert("Yay just like jQuery callbacks!");
});
function dosomething(damsg, callback){
alert(damsg);
if(typeof callback == "function")
callback();
}
</script>
Here is a simple function with filter
demonstrating one way to take care of beginning and ending NAs with padding, and computing a weighted average (supported by filter
) using custom weights:
wma <- function(x) {
wts <- c(seq(0.5, 4, 0.5), seq(3.5, 0.5, -0.5))
nside <- (length(wts)-1)/2
# pad x with begin and end values for filter to avoid NAs
xp <- c(rep(first(x), nside), x, rep(last(x), nside))
z <- stats::filter(xp, wts/sum(wts), sides = 2) %>% as.vector
z[(nside+1):(nside+length(x))]
}
In Python 2.x this is not guaranteed as it is possible for True
and False
to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons.
In Python 3.x True
and False
are keywords and will always be equal to 1
and 0
.
Under normal circumstances in Python 2, and always in Python 3:
False
object is of type bool
which is a subclass of int
:
object
|
int
|
bool
It is the only reason why in your example, ['zero', 'one'][False]
does work. It would not work with an object which is not a subclass of integer, because list indexing only works with integers, or objects that define a __index__
method (thanks mark-dickinson).
Edit:
It is true of the current python version, and of that of Python 3. The docs for python 2 and the docs for Python 3 both say:
There are two types of integers: [...] Integers (int) [...] Booleans (bool)
and in the boolean subsection:
Booleans: These represent the truth values False and True [...] Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.
There is also, for Python 2:
In numeric contexts (for example when used as the argument to an arithmetic operator), they [False and True] behave like the integers 0 and 1, respectively.
So booleans are explicitly considered as integers in Python 2 and 3.
So you're safe until Python 4 comes along. ;-)
You can use extension method, recursion to resolve this problem:
public static bool DeepCompare(this object obj, object another)
{
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
//Compare two object's class, return false if they are difference
if (obj.GetType() != another.GetType()) return false;
var result = true;
//Get all properties of obj
//And compare each other
foreach (var property in obj.GetType().GetProperties())
{
var objValue = property.GetValue(obj);
var anotherValue = property.GetValue(another);
if (!objValue.Equals(anotherValue)) result = false;
}
return result;
}
public static bool CompareEx(this object obj, object another)
{
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
if (obj.GetType() != another.GetType()) return false;
//properties: int, double, DateTime, etc, not class
if (!obj.GetType().IsClass) return obj.Equals(another);
var result = true;
foreach (var property in obj.GetType().GetProperties())
{
var objValue = property.GetValue(obj);
var anotherValue = property.GetValue(another);
//Recursion
if (!objValue.DeepCompare(anotherValue)) result = false;
}
return result;
}
or compare by using Json (if object is very complex) You can use Newtonsoft.Json:
public static bool JsonCompare(this object obj, object another)
{
if (ReferenceEquals(obj, another)) return true;
if ((obj == null) || (another == null)) return false;
if (obj.GetType() != another.GetType()) return false;
var objJson = JsonConvert.SerializeObject(obj);
var anotherJson = JsonConvert.SerializeObject(another);
return objJson == anotherJson;
}
OpenCV HSV range is: H: 0 to 179 S: 0 to 255 V: 0 to 255
On Gimp (or other photo manipulation sw) Hue range from 0 to 360, since opencv put color info in a single byte, the maximum number value in a single byte is 255 therefore openCV Hue values are equivalent to Hue values from gimp divided by 2.
I found when trying to do object detection based on HSV color space that a range of 5 (opencv range) was sufficient to filter out a specific color. I would advise you to use an HSV color palate to figure out the range that works best for your application.
In case you are into functional this is a function written in Scala showing how you could copy an input stream to an output stream using only vals (and not vars).
def copyInputToOutputFunctional(inputStream: InputStream, outputStream: OutputStream,bufferSize: Int) {
val buffer = new Array[Byte](bufferSize);
def recurse() {
val len = inputStream.read(buffer);
if (len > 0) {
outputStream.write(buffer.take(len));
recurse();
}
}
recurse();
}
Note that this is not recommended to use in a java application with little memory available because with a recursive function you could easily get a stack overflow exception error
Now you can make use of sets to do that easily.
let a= ['a', 'a', 'a', 'a']; // true_x000D_
let b =['a', 'a', 'b', 'a'];// false_x000D_
_x000D_
console.log(new Set(a).size === 1);_x000D_
console.log(new Set(b).size === 1);
_x000D_
There are two widely-used memory allocation techniques: automatic allocation and dynamic allocation. Commonly, there is a corresponding region of memory for each: the stack and the heap.
The stack always allocates memory in a sequential fashion. It can do so because it requires you to release the memory in the reverse order (First-In, Last-Out: FILO). This is the memory allocation technique for local variables in many programming languages. It is very, very fast because it requires minimal bookkeeping and the next address to allocate is implicit.
In C++, this is called automatic storage because the storage is claimed automatically at the end of scope. As soon as execution of current code block (delimited using {}
) is completed, memory for all variables in that block is automatically collected. This is also the moment where destructors are invoked to clean up resources.
The heap allows for a more flexible memory allocation mode. Bookkeeping is more complex and allocation is slower. Because there is no implicit release point, you must release the memory manually, using delete
or delete[]
(free
in C). However, the absence of an implicit release point is the key to the heap's flexibility.
Even if using the heap is slower and potentially leads to memory leaks or memory fragmentation, there are perfectly good use cases for dynamic allocation, as it's less limited.
Two key reasons to use dynamic allocation:
You don't know how much memory you need at compile time. For instance, when reading a text file into a string, you usually don't know what size the file has, so you can't decide how much memory to allocate until you run the program.
You want to allocate memory which will persist after leaving the current block. For instance, you may want to write a function string readfile(string path)
that returns the contents of a file. In this case, even if the stack could hold the entire file contents, you could not return from a function and keep the allocated memory block.
In C++ there's a neat construct called a destructor. This mechanism allows you to manage resources by aligning the lifetime of the resource with the lifetime of a variable. This technique is called RAII and is the distinguishing point of C++. It "wraps" resources into objects. std::string
is a perfect example. This snippet:
int main ( int argc, char* argv[] )
{
std::string program(argv[0]);
}
actually allocates a variable amount of memory. The std::string
object allocates memory using the heap and releases it in its destructor. In this case, you did not need to manually manage any resources and still got the benefits of dynamic memory allocation.
In particular, it implies that in this snippet:
int main ( int argc, char* argv[] )
{
std::string * program = new std::string(argv[0]); // Bad!
delete program;
}
there is unneeded dynamic memory allocation. The program requires more typing (!) and introduces the risk of forgetting to deallocate the memory. It does this with no apparent benefit.
Basically, the last paragraph sums it up. Using automatic storage as often as possible makes your programs:
In the referenced question, there are additional concerns. In particular, the following class:
class Line {
public:
Line();
~Line();
std::string* mString;
};
Line::Line() {
mString = new std::string("foo_bar");
}
Line::~Line() {
delete mString;
}
Is actually a lot more risky to use than the following one:
class Line {
public:
Line();
std::string mString;
};
Line::Line() {
mString = "foo_bar";
// note: there is a cleaner way to write this.
}
The reason is that std::string
properly defines a copy constructor. Consider the following program:
int main ()
{
Line l1;
Line l2 = l1;
}
Using the original version, this program will likely crash, as it uses delete
on the same string twice. Using the modified version, each Line
instance will own its own string instance, each with its own memory and both will be released at the end of the program.
Extensive use of RAII is considered a best practice in C++ because of all the reasons above. However, there is an additional benefit which is not immediately obvious. Basically, it's better than the sum of its parts. The whole mechanism composes. It scales.
If you use the Line
class as a building block:
class Table
{
Line borders[4];
};
Then
int main ()
{
Table table;
}
allocates four std::string
instances, four Line
instances, one Table
instance and all the string's contents and everything is freed automagically.
As far as I remember, this is controlled by browser settings. In other words: user can chose whether they would like to open new tab in the background or foreground. Also they can chose whether new popup should open in new tab or just... popup.
For example in firefox preferences:
Notice the last option.
You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory.
However, you can reliably determine the location of a module, since modules are always loaded from a file. If you create a module with the following code and put it in the same directory as your main script, then the main script can import the module and use that to locate itself.
some_path/module_locator.py:
def we_are_frozen():
# All of the modules are built-in to the interpreter, e.g., by py2exe
return hasattr(sys, "frozen")
def module_path():
encoding = sys.getfilesystemencoding()
if we_are_frozen():
return os.path.dirname(unicode(sys.executable, encoding))
return os.path.dirname(unicode(__file__, encoding))
some_path/main.py:
import module_locator
my_path = module_locator.module_path()
If you have several main scripts in different directories, you may need more than one copy of module_locator.
Of course, if your main script is loaded by some other tool that doesn't let you import modules that are co-located with your script, then you're out of luck. In cases like that, the information you're after simply doesn't exist anywhere in your program. Your best bet would be to file a bug with the authors of the tool.
Passing a parameter to gulp can mean a few things:
Here's an approach of passing parameters from the main gulpfile to a gulp task. By moving the task that needs the parameter to it's own module and wrapping it in a function (so a parameter can be passed).:
// ./gulp-tasks/my-neat-task.js file
module.exports = function(opts){
opts.gulp.task('my-neat-task', function(){
console.log( 'the value is ' + opts.value );
});
};
//main gulpfile.js file
//...do some work to figure out a value called val...
var val = 'some value';
//pass that value as a parameter to the 'my-neat-task' gulp task
require('./gulp-tasks/my-neat-task.js')({ gulp: gulp, value: val});
This can come in handy if you have a lot of gulp tasks and want to pass them some handy environmental configs. I'm not sure if it can work between one task and another.
<?php
header('Location: B.php');
exit();
?>
Suppose we want to route from A.php file to B.php than we have to take help of <button>
or <a>
. Lets see an example
<?php
if(isset($_GET['go_to_page_b'])) {
header('Location: B.php');
exit();
}
?>
<p>I am page A</p>
<button name='go_to_page_b'>Page B</button>
B.php
<p> I am Page B</p>
On localhost you should consider context path.
function wsURL(path) {
var protocol = (location.protocol === 'https:') ? 'wss://' : 'ws://';
var url = protocol + location.host;
if(location.hostname === 'localhost') {
url += '/' + location.pathname.split('/')[1]; // add context path
}
return url + path;
}
Also, when checking for the last image, you must compare with imgArray.length-1
because, for example, when array length is 2 then I will take the values 0 and 1, it won't reach the value 2, so you must compare with length-1 not with length, here is the fixed line:
if(i == imgArray.length-1)
Since the other posts say everything (and I stumbled upon this post while looking for the following).
Here is a way how to execute a python script from another python script:
Python 2:
execfile("somefile.py", global_vars, local_vars)
Python 3:
with open("somefile.py") as f:
code = compile(f.read(), "somefile.py", 'exec')
exec(code, global_vars, local_vars)
and you can supply args by providing some other sys.argv
In my case URI, as it was defined on FB, was fine, but I was using Spring Security and it was adding ;jsessionid=0B9A5E71DAA32A01A3CD351E6CA1FCDD to my URI so, it caused the mismatching.
https://m.facebook.com/v2.5/dialog/oauth?client_id=your-fb-id-code&response_type=code&redirect_uri=https://localizator.org/auth/facebook;jsessionid=0B9A5E71DAA32A01A3CD351E6CA1FCDD&scope=email&state=b180578a-007b-48bc-bd81-4b08c6989e18
In order to avoid the URL rewriting I added disable-url-rewriting="true" to Spring Security config, in this way:
<http auto-config="true" access-denied-page="/security/accessDenied" use-expressions="true"
disable-url-rewriting="true" entry-point-ref="authenticationEntryPoint"/>
And it fixed my problem.
I think you meant that you want to clear all the cells in the jTable and make it just like a new blank jTable. For an example, if your table is myTable, you can do following.
DefaultTableModel model = new DefaultTableModel();
myTable.setModel(model);
There is no such thing as a byte or short literal. You need to cast to short using (short)100
Building on Roland's answer, using tidyr
to reshape the data from wide to long:
library(tidyr)
library(ggplot2)
df <- read.table(text="Rank F1 F2 F3
1 500 250 50
2 400 100 30
3 300 155 100
4 200 90 10", header=TRUE)
df %>%
gather(variable, value, F1:F3) %>%
ggplot(aes(x = Rank, y = value, fill = variable)) +
geom_bar(stat = "identity")
There is another issue to be considered here. Some people expect that adding custom method to your repository will automatically expose them as REST services under '/search' link. This is unfortunately not the case. Spring doesn't support that currently.
This is 'by design' feature, spring data rest explicitly checks if method is a custom method and doesn't expose it as a REST search link:
private boolean isQueryMethodCandidate(Method method) {
return isQueryAnnotationPresentOn(method) || !isCustomMethod(method) && !isBaseClassMethod(method);
}
This is a qoute of Oliver Gierke:
This is by design. Custom repository methods are no query methods as they can effectively implement any behavior. Thus, it's currently impossible for us to decide about the HTTP method to expose the method under. POST would be the safest option but that's not in line with the generic query methods (which receive GET).
For more details see this issue: https://jira.spring.io/browse/DATAREST-206
To avoid problems with layout_* params not being properly used, you need to make sure that when you inflate your custom layout that you specify a correct ViewGroup as a parent.
Many examples pass null here, but instead you can pass the existing Toast ViewGroup as your parent.
val toast = Toast.makeText(this, "", Toast.LENGTH_LONG)
val layout = LayoutInflater.from(this).inflate(R.layout.view_custom_toast, toast.view.parent as? ViewGroup?)
toast.view = layout
toast.show()
Here we replace the existing Toast view with our custom view. Once you have a reference to your layout "layout" you can then update any images/text views that it may contain.
This solution also prevents any "View not attached to window manager" crashes from using null as a parent.
Also, avoid using ConstraintLayout as your custom layout root, this seems to not work when used inside a Toast.
UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id
That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read
As for running slow, how large are the tables? You should have indexes on tobeupdated.value
and original.value
EDIT: we can also simplify the query
UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id
USING
is shorthand when both tables of a join have an identical named key
such as id
. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join
TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.
If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.
As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT
header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/chainedcert.pem; # server certificate
ssl_certificate_key /path/to/key; # server key
ssl_client_certificate /path/to/ca.pem; # client CA
ssl_verify_client on;
proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;
location / {
proxy_pass http://localhost:3000;
}
}
maven-compiler-plugin it's already present in plugins hierarchy dependency in pom.xml. Check in Effective POM.
For short you can use properties like this:
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
I'm using Maven 3.2.5.
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
f = open(file_to_open)
print(f.read())
As best place and practice for external API calls is React Lifecycle method componentDidMount(), where after the execution of the API call you should update the local state to be triggered new render() method call, then the changes in the updated local state will be applied on the component view.
As other option for initial external data source call in React is pointed the constructor() method of the class. The constructor is the first method executed on initialization of the component object instance. You could see this approach in the documentation examples for Higher-Order Components.
The method componentWillMount() and UNSAFE_componentWillMount() should not be used for external API calls, because they are intended to be deprecated. Here you could see common reasons, why this method will be deprecated.
Anyway you must never use render() method or method directly called from render() as a point for external API call. If you do this your application will be blocked.
@joeshmo Or instead of writing a helper function, you could just urlencode the base64 encoded string. This would do the exact same thing as your helper function, but without the need of two extra functions.
$str = 'Some String';
$encoded = urlencode( base64_encode( $str ) );
$decoded = base64_decode( urldecode( $encoded ) );
I'm not sure exactly what you're trying to achieve (I've never used Emacs), but you can run commands in Vim by typing:
:! somecommand [ENTER]
And if you want to type in several commands, or play around in a shell for a while, you can always use:
:! bash (or your favourite shell) [ENTER]
Once the command or shell terminates, you'll be given the option to press Enter to return to your editor window
Vim is intentionally lightweight and lacking in the ability to do non-editorish type things, just as running a full-blown shell inside a Vim pane/tab, but as mentioned above there are third-party addons such as vim-shell that allow you to do that sort of thing.
Typically if I want to switch between Vim and my shell (Bash), I just hit CTRL+Z to pause the Vim process, play around in my shell, then type 'fg' when I want to go back to Vim - keeping my editor and my shell nice and separate.
If you're a macOS homebrew zsh user:
brew cask install google-cloud-sdk
Update your ~/.zshrc:
plugins=(
...
gcloud
)
Other methods were mentioned so let us please acknowledge that, at the time of writing, we are in the 21st century. Let's park the local bus browser opening, and fly with an XMLHTTP GET request (XHR GET for short).
XHR is an API in the form of an object whose methods transfer data between a web browser and a web server. The object is provided by the browser's JavaScript environment
It's a fast method for retrieving data that doesn't require opening a browser. The server response can be read into an HTMLDocument and the process of grabbing the table continued from there.
Note that javascript rendered/dynamically added content will not be retrieved as there is no javascript engine running (which there is in a browser).
In the below code, the table is grabbed by its id cr1
.
In the helper sub, WriteTable
, we loop the columns (td
tags) and then the table rows (tr
tags), and finally traverse the length of each table row, table cell by table cell. As we only want data from columns 1 and 8, a Select Case
statement is used specify what is written out to the sheet.
Sample webpage view:
Sample code output:
VBA:
Option Explicit
Public Sub GetRates()
Dim html As HTMLDocument, hTable As HTMLTable '<== Tools > References > Microsoft HTML Object Library
Set html = New HTMLDocument
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://uk.investing.com/rates-bonds/financial-futures", False
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" 'to deal with potential caching
.send
html.body.innerHTML = .responseText
End With
Application.ScreenUpdating = False
Set hTable = html.getElementById("cr1")
WriteTable hTable, 1, ThisWorkbook.Worksheets("Sheet1")
Application.ScreenUpdating = True
End Sub
Public Sub WriteTable(ByVal hTable As HTMLTable, Optional ByVal startRow As Long = 1, Optional ByVal ws As Worksheet)
Dim tSection As Object, tRow As Object, tCell As Object, tr As Object, td As Object, r As Long, C As Long, tBody As Object
r = startRow: If ws Is Nothing Then Set ws = ActiveSheet
With ws
Dim headers As Object, header As Object, columnCounter As Long
Set headers = hTable.getElementsByTagName("th")
For Each header In headers
columnCounter = columnCounter + 1
Select Case columnCounter
Case 2
.Cells(startRow, 1) = header.innerText
Case 8
.Cells(startRow, 2) = header.innerText
End Select
Next header
startRow = startRow + 1
Set tBody = hTable.getElementsByTagName("tbody")
For Each tSection In tBody
Set tRow = tSection.getElementsByTagName("tr")
For Each tr In tRow
r = r + 1
Set tCell = tr.getElementsByTagName("td")
C = 1
For Each td In tCell
Select Case C
Case 2
.Cells(r, 1).Value = td.innerText
Case 8
.Cells(r, 2).Value = td.innerText
End Select
C = C + 1
Next td
Next tr
Next tSection
End With
End Sub
I created a VB script and run it either from command line or from a Java process. I also tried to catch errors when creating the shortcut so I can have a better error handling.
Set oWS = WScript.CreateObject("WScript.Shell")
shortcutLocation = Wscript.Arguments(0)
'error handle shortcut creation
On Error Resume Next
Set oLink = oWS.CreateShortcut(shortcutLocation)
If Err Then WScript.Quit Err.Number
'error handle setting shortcut target
On Error Resume Next
oLink.TargetPath = Wscript.Arguments(1)
If Err Then WScript.Quit Err.Number
'error handle setting start in property
On Error Resume Next
oLink.WorkingDirectory = Wscript.Arguments(2)
If Err Then WScript.Quit Err.Number
'error handle saving shortcut
On Error Resume Next
oLink.Save
If Err Then WScript.Quit Err.Number
I run the script with the following commmand:
cscript /b script.vbs shortcutFuturePath targetPath startInProperty
It is possible to have it working even without setting the 'Start in' property in some cases.
function escapeHTML(string)
{
var pre = document.createElement('pre');
var text = document.createTextNode(string);
pre.appendChild(text);
return pre.innerHTML;
}//end escapeHTML
it will return the escaped Html
Many existing answers include human intervention at install time. This can be an error-prone process. If you have many executables wanted to be installed as services, the last thing you want to do is to do them manually at install time.
Towards the above described scenario, I created serman, a command line tool to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run
serman install <path_to_config_file>
will install the service. stdout
and stderr
are all logged. For more info, take a look at the project website.
A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env>
and <persistent_env>
below.
<service>
<id>hello</id>
<name>hello</name>
<description>This service runs the hello application</description>
<executable>node.exe</executable>
<!--
{{dir}} will be expanded to the containing directory of your
config file, which is normally where your executable locates
-->
<arguments>"{{dir}}\hello.js"</arguments>
<logmode>rotate</logmode>
<!-- OPTIONAL FEATURE:
NODE_ENV=production will be an environment variable
available to your application, but not visible outside
of your application
-->
<env name="NODE_ENV" value="production"/>
<!-- OPTIONAL FEATURE:
FOO_SERVICE_PORT=8989 will be persisted as an environment
variable to the system.
-->
<persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>
Just pass a callback as argument like this:
function getMeta(url, callback) {_x000D_
var img = new Image();_x000D_
img.src = url;_x000D_
img.onload = function() { callback(this.width, this.height); }_x000D_
}_x000D_
getMeta(_x000D_
"http://snook.ca/files/mootools_83_snookca.png",_x000D_
function(width, height) { alert(width + 'px ' + height + 'px') }_x000D_
);
_x000D_
As of July 25, 2011, the answer is no.
I have looked through their Javascript and it seems they don't want anyone directly accessing their api for +1 at the moment.
The Javascript that does all of the work for the +1 button is here:
https://apis.google.com/js/plusone.js
If you run it through a Javascript cleanup program you can tell that they have obfuscated their code with various functions that only start with letters and constantly refer back to themselves and do cryptic things.
I figure in the next couple of weeks or moths they will release a link based sharing api due to the fact that we will need this for sharing from flash and other web based formats that don't rely on pure html and js.
I had this problem yesterday. Before in the my solution, chek this settings.
git config --global user.email "[email protected]"
git config --global user.name "your_name"
Where "user" is the user of the laptop.
Example: dias@dias-hp-pavilion$ git config --global dias.email ...
So, confirm the informations add, doing:
dias@dias-hp-pavilion:/home/dias$ git config --global dias.email
[email protected]
dias@dias-hp-pavilion:/home/dias$ git config --global dias.name
my_name
or
nano /home/user_name/.gitconfig
and check this informations.
Doing it and the error persists, try another Git IDE (GUI Clients). I used git-cola and this error appeared, so I changed of IDE, and currently I use the CollabNet GitEye. Try you also!
I hope have helped!
You could use a css class too.
$('#hook').parent().parent().parent().siblings().addClass("class_name");
Good day!
I solved this problem instantiating a new Date object in node.js:...
In Javascript, send the Date().toISOString() to nodejs:...
var start_date = new Date(2012, 01, 03, 8, 30);
$.ajax({
type: 'POST',
data: { start_date: start_date.toISOString() },
url: '/queryScheduleCollection',
dataType: 'JSON'
}).done(function( response ) { ... });
Then use the ISOString to create a new Date object in nodejs:..
exports.queryScheduleCollection = function(db){
return function(req, res){
var start_date = new Date(req.body.start_date);
db.collection('schedule_collection').find(
{ start_date: { $gte: start_date } }
).toArray( function (err,d){
...
res.json(d)
})
}
};
Note: I'm using Express and Mongoskin.
I know this question has already been answered, but I came here looking for a way to filter elements in an Array based on some criteria. So here is my solution example: using select
, I find all constants in Class that start with "RUBY_"
Class.constants.select {|c| c.to_s =~ /^RUBY_/ }
UPDATE: In the meantime I have discovered that Array#grep works much better. For the above example,
Class.constants.grep /^RUBY_/
did the trick.
For those who don't have nor want to install wget, curl -O
(capital "o", not a zero) will do the same thing as wget
. E.g. my old netbook doesn't have wget, and is a 2.68 MB install that I don't need.
curl -O https://www.python.org/static/apple-touch-icon-144x144-precomposed.png
There is various way to define a function. It is totally based upon your requirement. Below are the few styles :-
var person = new Object();
person.name = "Anand",
person.getName = function(){
return this.name ;
};
var person = {
name : "Anand",
getName : function (){
return this.name
}
}
function Person(name){
this.name = name
this.getName = function(){
return this.name
}
}
function Person(){};
Person.prototype.name = "Anand";
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name
}
var person = new function(){
this.name = "Anand"
}
You can try it on console, if you have any confusion.
private static Node mergeLists(Node L1, Node L2) {
Node P1 = L1.val < L2.val ? L1 : L2;
Node P2 = L1.val < L2.val ? L2 : L1;
Node BigListHead = P1;
Node tempNode = null;
while (P1 != null && P2 != null) {
if (P1.next != null && P1.next.val >P2.val) {
tempNode = P1.next;
P1.next = P2;
P1 = P2;
P2 = tempNode;
} else if(P1.next != null)
P1 = P1.next;
else {
P1.next = P2;
break;
}
}
return BigListHead;
}
You could try with simple 3 dots. refer to the code in perl below
$a =~ m /.../ #where $a is your string
There is a method update
on BaseQuery object in SQLAlchemy, which is returned by filter_by
.
num_rows_updated = User.query.filter_by(username='admin').update(dict(email='[email protected]')))
db.session.commit()
The advantage of using update
over changing the entity comes when there are many objects to be updated.
If you want to give add_user
permission to all the admin
s,
rows_changed = User.query.filter_by(role='admin').update(dict(permission='add_user'))
db.session.commit()
Notice that filter_by
takes keyword arguments (use only one =
) as opposed to filter
which takes an expression.
There are all sorts of ways to get the Last Inserted ID but the easiest way I have found is by simply retrieving it from the TableAdapter in the DataSet like so:
<Your DataTable Class> tblData = new <Your DataTable Class>();
<Your Table Adapter Class> tblAdpt = new <Your Table Adapter Class>();
/*** Initialize and update Table Data Here ***/
/*** Make sure to call the EndEdit() method ***/
/*** of any Binding Sources before update ***/
<YourBindingSource>.EndEdit();
//Update the Dataset
tblAdpt.Update(tblData);
//Get the New ID from the Table Adapter
long newID = tblAdpt.Adapter.InsertCommand.LastInsertedId;
Hope this Helps ...
Write-Output
should be used when you want to send data on in the pipe line, but not necessarily want to display it on screen. The pipeline will eventually write it to out-default
if nothing else uses it first.
Write-Host
should be used when you want to do the opposite.
[console]::WriteLine
is essentially what Write-Host
is doing behind the scenes.
Run this demonstration code and examine the result.
function Test-Output {
Write-Output "Hello World"
}
function Test-Output2 {
Write-Host "Hello World" -foreground Green
}
function Receive-Output {
process { Write-Host $_ -foreground Yellow }
}
#Output piped to another function, not displayed in first.
Test-Output | Receive-Output
#Output not piped to 2nd function, only displayed in first.
Test-Output2 | Receive-Output
#Pipeline sends to Out-Default at the end.
Test-Output
You'll need to enclose the concatenation operation in parentheses, so that PowerShell processes the concatenation before tokenizing the parameter list for Write-Host
, or use string interpolation
write-host ("count=" + $count)
# or
write-host "count=$count"
BTW - Watch this video of Jeffrey Snover explaining how the pipeline works. Back when I started learning PowerShell I found this to be the most useful explanation of how the pipeline works.