use Request.Form
to get the Data
Controller:
[HttpPost]
public ActionResult Index(int? id)
{
string jsonData= Request.Form[0]; // The data from the POST
}
I write this to try
View:
<input type="button" value="post" id="btnPost" />
<script type="text/javascript">
$(function () {
var test = {
number: 456,
name: "Ryu"
}
$("#btnPost").click(function () {
$.post('@Url.Action("Index", "Home")', JSON.stringify(test));
});
});
</script>
and write Request.Form[0]
or Request.Params[0]
in controller can get the data.
I don't write <form> tag
in view.
For anyone else struggling with this: Qwertie's comment worked well for me.
<Border Width="1" Margin="2" Background="#8888"/>
This creates a vertical seperator which you can talior to suit your needs.
there you go
date('d.m.Y',strtotime("-1 days"));
this will work also if month change
There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.
Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!
That's no struts related problem but rather plain HMTL/CSS.
I'm not HTML or CSS expert, but I guess you could use a div with a border on the left or right side only.
To check if WhatsApp is installed in device and initiate "click to chat" in WhatsApp:
Kotlin:
try {
// Check if whatsapp is installed
context?.packageManager?.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA)
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/$internationalPhoneNumber"))
startActivity(intent)
} catch (e: NameNotFoundException) {
Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT).show()
}
Java:
try {
// Check if whatsapp is installed
getPackageManager().getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
Intent intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://wa.me/" + internationalPhoneNumber));
startActivity(intent);
} catch (NameNotFoundException e) {
Toast.makeText(context, "WhatsApp not Installed", Toast.LENGTH_SHORT).show();
}
getPackageInfo()
throws NameNotFoundException
if WhatsApp is not installed.
The internationalPhoneNumber
variable is used to access the phone number.
Reference:
John Sansom and Ed Harper have great solutions. However, I was unable to get them to work when dealing with ID fields (i.e. Integers). I modified the split function below to CAST the values as integers so the table will join with primary key columns. I also commented the code and added a column for order, in case the delimited list order was significant.
CREATE FUNCTION [dbo].[fn_SplitInt]
(
@List nvarchar(4000),
@Delimiter char(1)= ','
)
RETURNS @Values TABLE
(
Position int IDENTITY PRIMARY KEY,
Number int
)
AS
BEGIN
-- set up working variables
DECLARE @Index INT
DECLARE @ItemValue nvarchar(100)
SELECT @Index = 1
-- iterate until we have no more characters to work with
WHILE @Index > 0
BEGIN
-- find first delimiter
SELECT @Index = CHARINDEX(@Delimiter,@List)
-- extract the item value
IF @Index > 0 -- if found, take the value left of the delimiter
SELECT @ItemValue = LEFT(@List,@Index - 1)
ELSE -- if none, take the remainder as the last value
SELECT @ItemValue = @List
-- insert the value into our new table
INSERT INTO @Values (Number) VALUES (CAST(@ItemValue AS int))
-- remove the found item from the working list
SELECT @List = RIGHT(@List,LEN(@List) - @Index)
-- if list is empty, we are done
IF LEN(@List) = 0 BREAK
END
RETURN
END
Use this function as previously noted with:
WHERE id IN (SELECT Number FROM dbo.fn_SplitInt(@sParameterString,','))
Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.
Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.
If you are comparing schemas on the same database then try:
select * from dba_objects
where schema_name = 'ASCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects
where schema_name = 'BSCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
and switch around the orders of ASCHEMA and BSCHEMA.
If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas
You can use set_printoptions
to set the precision of the output:
import numpy as np
x=np.random.random(10)
print(x)
# [ 0.07837821 0.48002108 0.41274116 0.82993414 0.77610352 0.1023732
# 0.51303098 0.4617183 0.33487207 0.71162095]
np.set_printoptions(precision=3)
print(x)
# [ 0.078 0.48 0.413 0.83 0.776 0.102 0.513 0.462 0.335 0.712]
And suppress
suppresses the use of scientific notation for small numbers:
y=np.array([1.5e-10,1.5,1500])
print(y)
# [ 1.500e-10 1.500e+00 1.500e+03]
np.set_printoptions(suppress=True)
print(y)
# [ 0. 1.5 1500. ]
See the docs for set_printoptions for other options.
To apply print options locally, using NumPy 1.15.0 or later, you could use the numpy.printoptions context manager.
For example, inside the with-suite
precision=3
and suppress=True
are set:
x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
But outside the with-suite
the print options are back to default settings:
print(x)
# [ 0.07334334 0.46132615 0.68935231 0.75379645 0.62424021 0.90115836
# 0.04879837 0.58207504 0.55694118 0.34768638]
If you are using an earlier version of NumPy, you can create the context manager yourself. For example,
import numpy as np
import contextlib
@contextlib.contextmanager
def printoptions(*args, **kwargs):
original = np.get_printoptions()
np.set_printoptions(*args, **kwargs)
try:
yield
finally:
np.set_printoptions(**original)
x = np.random.random(10)
with printoptions(precision=3, suppress=True):
print(x)
# [ 0.073 0.461 0.689 0.754 0.624 0.901 0.049 0.582 0.557 0.348]
To prevent zeros from being stripped from the end of floats:
np.set_printoptions
now has a formatter
parameter which allows you to specify a format function for each type.
np.set_printoptions(formatter={'float': '{: 0.3f}'.format})
print(x)
which prints
[ 0.078 0.480 0.413 0.830 0.776 0.102 0.513 0.462 0.335 0.712]
instead of
[ 0.078 0.48 0.413 0.83 0.776 0.102 0.513 0.462 0.335 0.712]
I used the display:inline-block property: the solution consist in use a wrapper with fixed width. Inside, the ul block with the inline-block for display. Using this, the ul just take the width for the real content! and finally margin: 0 auto, to center this inline-block =)
/*ul wrapper*/
.gallery_wrapper{
width: 958px;
margin: 0 auto;
}
/*ul list*/
ul.gallery_carrousel{
display: inline-block;
margin: 0 auto;
}
.contenido_secundario li{
float: left;
}
Use the echo
command:
var="text to append";
destdir=/some/directory/path/filename
if [ -f "$destdir" ]
then
echo "$var" > "$destdir"
fi
The if
tests that $destdir
represents a file.
The >
appends the text after truncating the file. If you only want to append the text in $var
to the file existing contents, then use >>
instead:
echo "$var" >> "$destdir"
The cp
command is used for copying files (to files), not for writing text to a file.
Gitlab has made their service available to run on your own server for free. https://about.gitlab.com/downloads/
The best way to accomplish this is by simply adding "href" to the link button like below.
<asp:LinkButton runat="server" id="SomeLinkButton" href="url" CssClass="btn btn-primary btn-sm">Button Text</asp:LinkButton>
Using javascript, or doing this programmatically in the page_load, will work as well but is not the best way to go about doing this.
You will get this result:
<a id="MainContent_ctl00_SomeLinkButton" class="btn btn-primary btn-sm" href="url" href="javascript:__doPostBack('ctl00$MainContent$ctl00$lSomeLinkButton','')">Button Text</a>
You can also get the same results by using using a regular
<a href="" class=""></a>
.
just clean and make project / rebuilt fixed my issue give a try :-)
If you want to retrieve multiple values of attributes from the source above, you can use findAll
and a list comprehension to get everything you need:
import urllib
f = urllib.urlopen("http://58.68.130.147")
s = f.read()
f.close()
from BeautifulSoup import BeautifulStoneSoup
soup = BeautifulStoneSoup(s)
inputTags = soup.findAll(attrs={"name" : "stainfo"})
### You may be able to do findAll("input", attrs={"name" : "stainfo"})
output = [x["stainfo"] for x in inputTags]
print output
### This will print a list of the values.
You can implement this by overwriting a line. Use \r
to go back to the beginning of the line without writing \n
to the terminal.
Write \n
when you're done to advance the line.
Use echo -ne
to:
\n
and\r
.Here's a demo:
echo -ne '##### (33%)\r'
sleep 1
echo -ne '############# (66%)\r'
sleep 1
echo -ne '####################### (100%)\r'
echo -ne '\n'
In a comment below, puk mentions this "fails" if you start with a long line and then want to write a short line: In this case, you'll need to overwrite the length of the long line (e.g., with spaces).
Had the same issue installing angular material CDK:
npm install --save @angular/material @angular/cdk @angular/animations
Adding -dev
like below worked for me:
npm install --save-dev @angular/material @angular/cdk @angular/animations
Encapsulation is a way to achieve "information hiding" so, following your example, you don't "need to know the internal working of the mobile phone to operate" with it. You have an interface to use the device behaviour without knowing implementation details.
Abstraction on the other side, can be explained as the capability to use the same interface for different objects. Different implementations of the same interface can exist. Details are hidden by encapsulation.
#ul_top_hypers li {
display: flex;
}
In Linux:
If you have already downloaded the android SDK but its not being found.
The problem might be that the file local.properties
needs to be inside the same directory as gradle
stuff for gradle
to find it when building and running adb.
For my react-native project using gradle
I needed to put the local.properties
file to Myprojectname/android/
folder.
As I had unzipped the SDK to Downloads so I just use that path in the file with a row like this:
sdk.dir=/home/USER/Downloads/android-sdk-linux
you'll need to switch to Scala to implement your own operators
Semicolon ;
on the end of command had caused the same error on me.
cmd.CommandText = "INSERT INTO U_USERS_TABLE (USERNAME, PASSWORD, FIRSTNAME, LASTNAME) VALUES ("
+ "'" + txtUsername.Text + "',"
+ "'" + txtPassword.Text + "',"
+ "'" + txtFirstname.Text + "',"
+ "'" + txtLastname.Text + "');"; <== Semicolon in "" is the cause.
Removing it will be fine.
Hope it helps.
psycopgs cursor class has the attribute rowcount.
This read-only attribute specifies the number of rows that the last execute*() produced (for DQL statements like SELECT) or affected (for DML statements like UPDATE or INSERT).
So you could try UPDATE first and INSERT only if rowcount is 0.
But depending on activity levels in your database you may hit a race condition between UPDATE and INSERT where another process may create that record in the interim.
In the Laravel 6 application the make:auth
command no longer exists.
Laravel UI is a new first-party package that extracts the UI portion of a Laravel project into a separate laravel/ui package. The separate package enables the Laravel team to iterate on the UI package separately from the main Laravel codebase.
You can install the laravel/ui
package via composer:
composer require laravel/ui
ui:auth
CommandBesides the new ui command, the laravel/ui
package comes with another command for generating the auth scaffolding:
php artisan ui:auth
If you run the ui:auth
command, it will generate the auth routes, a HomeController, auth views, and a app.blade.php layout file.
If you want to generate the views alone, type the following command instead:
php artisan ui:auth --views
If you want to generate the auth scaffolding at the same time:
php artisan ui vue --auth
php artisan ui react --auth
php artisan ui vue --auth
command will create all of the views you need for authentication and place them in the resources/views/auth
directory
The ui
command will also create a resources/views/layouts
directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.
More detail follow. laravel-news & documentation
composer require laravel/ui
php artisan ui:auth
You invoke the function with 2 parameters (@GenId and @Description):
EXEC etl.etl_M_Update_Promo @GenID, @Description
However you have declared the function to take 1 argument:
ALTER PROCEDURE [etl].[etl_M_Update_Promo]
@GenId bigint = 0
SQL Server is telling you that [etl_M_Update_Promo]
only takes 1 parameter (@GenId
)
You can alter the procedure to take two parameters by specifying @Description
.
ALTER PROCEDURE [etl].[etl_M_Update_Promo]
@GenId bigint = 0,
@Description NVARCHAR(50)
AS
.... Rest of your code.
OS / mysql version:
$ uname -a
Darwin Raphaels-MacBook-Pro.local 15.6.0 Darwin Kernel Version 15.6.0: Thu Jun 21 20:07:40 PDT 2018; root:xnu-3248.73.11~1/RELEASE_X86_64 x86_64
$ mysql --version
/usr/local/mysql/bin/mysql Ver 14.14 Distrib 5.6.23, for osx10.8 (x86_64) using EditLine wrapper
Adding logging (example, I don't think /var/log/...
is the best path on Mac OS but that worked:
sudo vi ./usr/local/mysql-5.6.23-osx10.8-x86_64/my.cnf
[mysqld]
general_log = on
general_log_file=/var/log/mysql/mysqld_general.log
Restarted Mysql
Result:
$ sudo tail -f /var/log/mysql/mysqld_general.log
181210 9:41:04 21 Connect root@localhost on employees
21 Query /* mysql-connector-java-5.1.47 ( Revision: fe1903b1ecb4a96a917f7ed3190d80c049b1de29 ) */SELECT @@session.auto_increment_increment AS auto_increment_increment, @@character_set_client AS character_set_client, @@character_set_connection AS character_set_connection, @@character_set_results AS character_set_results, @@character_set_server AS character_set_server, @@collation_server AS collation_server, @@collation_connection AS collation_connection, @@init_connect AS init_connect, @@interactive_timeout AS interactive_timeout, @@license AS license, @@lower_case_table_names AS lower_case_table_names, @@max_allowed_packet AS max_allowed_packet, @@net_buffer_length AS net_buffer_length, @@net_write_timeout AS net_write_timeout, @@query_cache_size AS query_cache_size, @@query_cache_type AS query_cache_type, @@sql_mode AS sql_mode, @@system_time_zone AS system_time_zone, @@time_zone AS time_zone, @@tx_isolation AS transaction_isolation, @@wait_timeout AS wait_timeout
21 Query SET NAMES latin1
21 Query SET character_set_results = NULL
21 Query SET autocommit=1
21 Query SELECT USER()
21 Query SELECT USER()
181210 9:41:10 21 Query show tables
181210 9:41:25 21 Query select count(*) from current_dept_emp
After debugging the code, i created my own function just like "blesh"'s answer. So this is what i did
MyModule = angular.module('FIT', [])
.run(function ($rootScope) {
// Custom $off function to un-register the listener.
$rootScope.$off = function (name, listener) {
var namedListeners = this.$$listeners[name];
if (namedListeners) {
// Loop through the array of named listeners and remove them from the array.
for (var i = 0; i < namedListeners.length; i++) {
if (namedListeners[i] === listener) {
return namedListeners.splice(i, 1);
}
}
}
}
});
so by attaching my function to $rootscope now it is available to all my controllers.
and in my code I am doing
$scope.$off("onViewUpdated", callMe);
Thanks
EDIT: The AngularJS way to do this is in @LiviuT's answer! But if you want to de-register the listener in another scope and at the same time want to stay away from creating local variables to keep references of de-registeration function. This is a possible solution.
The notion of multi-module projects is there to service the needs of codependent segments of a project. Such a client depends on the services which in turn depends on say EJBs or data-access routines. You could group your continuous integration (CI) tests in this manner. I would rationalize that by saying that the CI tests need to be in lock-step with application logic changes.
Suppose your project is structured as:
project-root
|
+ --- ci
|
+ --- client
|
+ --- server
The project-root/pom.xml
defines modules
<modules>
<module>ci</module>
<module>client</module>
<module>server</module>
</modules>
The ci/pom.xml
defines profiles such as:
...
<profiles>
<profile>
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</profile>
<profile>
<id>CI</id>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>false</skip>
</configuration>
</plugin>
</profile>
</profiles>
This will result in Maven skipping tests in this module except when the profile named CI
is active.
Your CI server must be instructed to execute mvn clean package -P CI
. The Maven web site has an in-depth explanation of the profiling mechanism.
The triple quotes answer is great for ASCII art, but for those wondering - what if my multiple lines are a tuple, list, or other iterable that returns strings (perhaps a list comprehension?), then how about:
print("\n".join(<*iterable*>))
For example:
print("\n".join(["{}={}".format(k, v) for k, v in os.environ.items() if 'PATH' in k]))
import {MatButtonModule} from '@angular/material/button';
My work around was that I opened the csv
file in a text editor, removed the excessive commas on the last value, then saved the file. For example for the following file
Test1,Test2,Test3
1,1,1
2,2,2
3,3,3
4,4,
5,5,
,6,,
Remove the commas after 6, then save the file.
Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.
Using GNU sed
:
sed -i '$ d' foo.txt
The -i
option does not exist in GNU sed
versions older than 3.95, so you have to use it as a filter with a temporary file:
cp foo.txt foo.txt.tmp
sed '$ d' foo.txt.tmp > foo.txt
rm -f foo.txt.tmp
Of course, in that case you could also use head -n -1
instead of sed
.
MacOS:
On Mac OS X (as of 10.7.4), the equivalent of the sed -i
command above is
sed -i '' -e '$ d' foo.txt
Or using regular expressions
"rmlike" <- function(...) {
names <- sapply(
match.call(expand.dots = FALSE)$..., as.character)
names = paste(names,collapse="|")
Vars <- ls(1)
r <- Vars[grep(paste("^(",names,").*",sep=""),Vars)]
rm(list=r,pos=1)
}
rmlike(temp)
If you use moment.js
the you need to load moment-with-locales.min.js
not moment.min.js
. Otherwise, your locale: 'ru'
will not work.
Here is a polyglot program for BASH and Windows CMD that runs a series of commands and quits out if any of them fail:
#!/bin/bash 2> nul
:; set -o errexit
:; function goto() { return $?; }
command 1 || goto :error
command 2 || goto :error
command 3 || goto :error
:; exit 0
exit /b 0
:error
exit /b %errorlevel%
I have used this type of thing in the past for a multiple platform continuous integration script.
This will work if your route looks like this: localhost:8888/p?tagid=1234
var tagId = req.query.tagid;
console.log(tagId); // outputs: 1234
console.log(req.query.tagid); // outputs: 1234
Otherwise use the following code if your route looks like this: localhost:8888/p/1234
var tagId = req.params.tagid;
console.log(tagId); // outputs: 1234
console.log(req.params.tagid); // outputs: 1234
Starting with SQL 2008, you should use sys.server_principals
instead of sys.syslogins
, which has been deprecated.
CheckBoxFor
takes a bool
, you're passing a List<CheckBoxes>
to it. You'd need to do:
@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
@Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i })
@Html.HiddenFor(m => m.EmploymentType[i].Text)
@Html.DisplayFor(m => m.EmploymentType[i].Text)
}
Notice I've added a HiddenFor
for the Text
property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.
Edit, as shown in your comments, your EmploymentType
list is null
when the view is served. You'll need to populate that too, by doing this in your action method:
public ActionResult YourActionMethod()
{
CareerForm model = new CareerForm();
model.EmploymentType = new List<CheckBox>
{
new CheckBox { Text = "Fulltime" },
new CheckBox { Text = "Partly" },
new CheckBox { Text = "Contract" }
};
return View(model);
}
Here you can read more about different HTML parsers in Python and their performance. Even though the article is a bit dated it still gives you a good overview.
Python HTML parser performance
I'd recommend BeautifulSoup even though it isn't built in. Just because it's so easy to work with for those kinds of tasks. Eg:
import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)
x = soup.body.find('div', attrs={'class' : 'container'}).text
As per this gist, the solution is to create a ~/.bash_profile
(in HOME
directory) that contains:
export SHELLOPTS
set -o igncr
Try something like this:
Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();
you need to mark your directory as source root (right click on the parent directory)
and then compile the plugin (it is important )
as result you will be able to add classes and more
I don't know of a command to do this, but you could do it in VBScript or something similar. Somthing like:
sNewName = "put new name here"
Set oShell = CreateObject ("WSCript.shell" )
sCCS = "HKLM\SYSTEM\CurrentControlSet\"
sTcpipParamsRegPath = sCCS & "Services\Tcpip\Parameters\"
sCompNameRegPath = sCCS & "Control\ComputerName\"
With oShell
.RegDelete sTcpipParamsRegPath & "Hostname"
.RegDelete sTcpipParamsRegPath & "NV Hostname"
.RegWrite sCompNameRegPath & "ComputerName\ComputerName", sNewName
.RegWrite sCompNameRegPath & "ActiveComputerName\ComputerName", sNewName
.RegWrite sTcpipParamsRegPath & "Hostname", sNewName
.RegWrite sTcpipParamsRegPath & "NV Hostname", sNewName
End With ' oShell
MsgBox "Computer name changed, please reboot your computer"
You can use onclick
to run some JavaScript or jQuery code before submitting the form like this:
<script type="text/javascript">
beforeSubmit = function(){
if (1 == 1){
//your before submit logic
}
$("#formid").submit();
}
</script>
<input type="button" value="Click" onclick="beforeSubmit();" />
In first statement you define variable, which common for all of the objects (class static field).
In the second statement you define variable, which belongs to each created object (a lot of copies).
In your case you should use the first one.
You can enter (for example) text from div into iFrame:
var $iframe = $('#iframe');
$iframe.ready(function() {
$iframe.contents().find("body").append($('#mytext'));
});
and divs:
<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>
and JSFiddle demo: link
with bash:
shopt -s globstar nullglob
rename _dbg.txt .txt **/*dbg*
In Javascript to assign multiple cases in a switch, we have to define different case without break inbetween
like given below:
<script>
function checkHere(varName){
switch (varName)
{
case "saeed":
case "larry":
case "afshin":
alert('Hey');
break;
case "ss":
alert('ss');
break;
default:
alert('Default case');
break;
}
}
</script>
Please see example click on link
I've had this problem myself and I've found the great wikipedia page on the subject (in "Common rotations" paragraph:
https://en.wikipedia.org/wiki/Rotation_matrix#Ambiguities
Then I wrote the following code, super verbose in order to have a clear understanding of what is going on.
I hope that you'll find it useful to dig more in the very beautiful and clever one-liner you've posted.
To quickly test it you can copy / paste it here:
http://www.codeskulptor.org/
triangle = [[0,0],[5,0],[5,2]]
coordinates_a = triangle[0]
coordinates_b = triangle[1]
coordinates_c = triangle[2]
def rotate90ccw(coordinates):
print "Start coordinates:"
print coordinates
old_x = coordinates[0]
old_y = coordinates[1]
# Here we apply the matrix coming from Wikipedia
# for 90 ccw it looks like:
# 0,-1
# 1,0
# What does this mean?
#
# Basically this is how the calculation of the new_x and new_y is happening:
# new_x = (0)(old_x)+(-1)(old_y)
# new_y = (1)(old_x)+(0)(old_y)
#
# If you check the lonely numbers between parenthesis the Wikipedia matrix's numbers
# finally start making sense.
# All the rest is standard formula, the same behaviour will apply to other rotations, just
# remember to use the other rotation matrix values available on Wiki for 180ccw and 170ccw
new_x = -old_y
new_y = old_x
print "End coordinates:"
print [new_x, new_y]
def rotate180ccw(coordinates):
print "Start coordinates:"
print coordinates
old_x = coordinates[0]
old_y = coordinates[1]
new_x = -old_x
new_y = -old_y
print "End coordinates:"
print [new_x, new_y]
def rotate270ccw(coordinates):
print "Start coordinates:"
print coordinates
old_x = coordinates[0]
old_y = coordinates[1]
new_x = -old_x
new_y = -old_y
print "End coordinates:"
print [new_x, new_y]
print "Let's rotate point A 90 degrees ccw:"
rotate90ccw(coordinates_a)
print "Let's rotate point B 90 degrees ccw:"
rotate90ccw(coordinates_b)
print "Let's rotate point C 90 degrees ccw:"
rotate90ccw(coordinates_c)
print "=== === === === === === === === === "
print "Let's rotate point A 180 degrees ccw:"
rotate180ccw(coordinates_a)
print "Let's rotate point B 180 degrees ccw:"
rotate180ccw(coordinates_b)
print "Let's rotate point C 180 degrees ccw:"
rotate180ccw(coordinates_c)
print "=== === === === === === === === === "
print "Let's rotate point A 270 degrees ccw:"
rotate270ccw(coordinates_a)
print "Let's rotate point B 270 degrees ccw:"
rotate270ccw(coordinates_b)
print "Let's rotate point C 270 degrees ccw:"
rotate270ccw(coordinates_c)
print "=== === === === === === === === === "
Flask-Restful
0.3.6
the Request Parsing recommend marshmallow
marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes.
A simple marshmallow example is showing below.
from marshmallow import Schema, fields
class UserSchema(Schema):
name = fields.Str()
email = fields.Email()
created_at = fields.DateTime()
from marshmallow import pprint
user = User(name="Monty", email="[email protected]")
schema = UserSchema()
result = schema.dump(user)
pprint(result)
# {"name": "Monty",
# "email": "[email protected]",
# "created_at": "2014-08-17T14:54:16.049594+00:00"}
The core features contain
Declaring Schemas
Serializing Objects (“Dumping”)
Deserializing Objects (“Loading”)
Handling Collections of Objects
Validation
Specifying Attribute Names
Specifying Serialization/Deserialization Keys
Refactoring: Implicit Field Creation
Ordering Output
“Read-only” and “Write-only” Fields
Specify Default Serialization/Deserialization Values
Nesting Schemas
Custom Fields
The main points I like about DVCS are those :
The main reason for a relatively big project is the improved communication created by the point 3. Others are nice bonuses.
Try Like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class UserController extends Controller
{
function index(){
$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}
}
}
?>
...a very small library of components which you can use to help organise your code. It comes packaged as a single JavaScript file. Excluding comments, it has less than 1000 lines of actual JavaScript. It's sensibly written and you can read the whole thing in a couple of hours.
It's a front-end library, you include it in your web page with a script tag. It only affects the browser, and says little about your server, except that it should ideally expose a restful API.
If you have an API, Backbone has a few helpful features that will help you talk to it, but you can use Backbone to add interactivity to any static HTML page.
...adding structure to JavaScript.
Because JavaScript doesn't enforce any particular patterns, JavaScript applications can become very messy very quickly. Anyone who has built something beyond trivial in JavaScript will have likely run up against questions such as:
Backbone seeks to answer these questions by giving you:
We call this an MV* pattern. Models, Views and optional extras.
Despite initial appearances, Backbone is fantastically light, it hardly does anything at all. What it does do is very helpful.
It gives you a set of little objects which you can create, and which can emit events and listen to each other. You might create a little object to represent a comment for example, and then a little commentView object to represent the display of the comment in a particular place in the browser.
You can tell the commentView to listen to the comment and redraw itself when the comment changes. Even if you have the same comment displayed in several places on your page all these views can listen to the same comment model and stay in sync.
This way of composing code helps to keep you from getting tangled even if your codebase becomes very large with many interactions.
When starting out, it's common to store your data either in a global variable, or in the DOM as data attributes. Both of these have issues. Global variables can conflict with each other, and are generally bad form. Data attributes stored in the DOM can only be strings, you will have to parse them in and out again. It's difficult to store things like arrays, dates or objects, and to parse your data in a structured form.
Data attributes look like this:
<p data-username="derek" data-age="42"></p>
Backbone solves this by providing a Model object to represent your data and associated methods. Say you have a todo list, you would have a model representing each item on that list.
When your model is updated, it fires an event. You might have a view tied to that particular object. The view listens for model change events and re-renders itself.
Backbone provides you with View objects that talk to the DOM. All functions that manipulate the DOM or listen for DOM events go here.
A View typically implements a render function which redraws the whole view, or possibly part of the view. There's no obligation to implement a render function, but it's a common convention.
Each view is bound to a particular part of the DOM, so you might have a searchFormView, that only listens to the search form, and a shoppingCartView, that only displays the shopping cart.
Views are typically also bound to specific Models or Collections. When the Model updates, it fires an event which the view listens to. The view might them call render to redraw itself.
Likewise, when you type into a form, your view can update a model object. Every other view listening to that model will then call its own render function.
This gives us a clean separation of concerns that keeps our code neat and tidy.
You can implement your render function in any way you see fit. You might just put some jQuery in here to update the DOM manually.
You might also compile a template and use that. A template is just a string with insertion points. You pass it to a compile function along with a JSON object and get back a compiled string which you can insert into your DOM.
You also have access to collections which store lists of models, so a todoCollection would be a list of todo models. When a collection gains or loses a model, changes its order, or a model in a collection updates, the whole collection fires an event.
A view can listen to a collection and update itself whenever the collection updates.
You could add sort and filter methods to your collection, and make it sort itself automatically for example.
As much as possible, application components are decoupled from each other. They communicate using events, so a shoppingCartView might listenTo a shoppingCart collection, and redraw itself when the cart is added to.
shoppingCartView.listenTo(shoppingCart, "add", shoppingCartView.render);
Of course, other objects might also be listening to the shoppingCart as well, and might do other things like update a total, or save the state in local storage.
Decoupling your objects like this and communicating using events means that you'll never get tangled in knots, and adding new components and behaviour is easy. Your new components just have to listen to the other objects already in the system.
Code written for Backbone follows a loose set of conventions. DOM code belongs in a View. Collection code belongs in a Collection. Business logic goes in a model. Another developer picking up your codebase will be able to hit the ground running.
Backbone is a lightweight library that lends structure to your code. Components are decoupled and communicate via events so you won't end up in a mess. You can extend your codebase easily, simply by creating a new object and having it listen to your existing objects appropriately. Your code will be cleaner, nicer, and more maintainable.
I liked Backbone so much that I wrote a little intro book about it. You can read it online here: http://nicholasjohnson.com/backbone-book/
I also broke the material down into a short online course, which you can find here: http://www.forwardadvance.com/course/backbone. You can complete the course in about a day.
Best solution is add this android:nestedScrollingEnabled="true"
attribute in child scrolling for example i have inserted this attribute in my ListView
that is child of ScrollView
. i hope this mathod works for you :-
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center_horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TextView"/>
<ListView
android:nestedScrollingEnabled="true" //add this only
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="300dp"/>
</LinearLayout>
</ScrollView>
Ajax.ActionLink only sends an ajax request to the server. What happens ahead really depends upon type of data returned and what your client side script does with it. You may send a partial view for ajax call or json, xml etc. Ajax.ActionLink however have different callbacks and parameters that allow you to write js code on different events. You can do something before request is sent or onComplete
. similarly you have an onSuccess callback. This is where you put your JS code for manipulating result returned by server. You may simply put it back in UpdateTargetID or you can do fancy stuff with this result using jQuery or some other JS library.
Here is the code
dialog.getWindow().getDecorView().setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent ev) {
if(MotionEvent.ACTION_DOWN == ev.getAction())
{
Rect dialogBounds = new Rect();
dialog. getWindow().getDecorView().getHitRect(dialogBounds);
if (!dialogBounds.contains((int) ev.getX(), (int) ev.getY())) {
// You have clicked the grey area
UiUtils.hideKeyboard2(getActivity());
return false; // stop activity closing
}
}
getActivity().dispatchTouchEvent(ev);
return false;
}
});
Try this one . you can hide the keyboard when you touch outside
I recommend Derek Bruening's bar graph generator Perl script. Available at http://www.burningcutlery.com/derek/bargraph/
I would override your Tuple with a proper GetHashCode, and just use it as the key.
As long as you overload the proper methods, you should see decent performance.
You can also try this for match string.
DECLARE @temp1 VARCHAR(1000)
SET @temp1 = '<li>Error in connecting server.</li>'
DECLARE @temp2 VARCHAR(1000)
SET @temp2 = '<li>Error in connecting server. connection timeout.</li>'
IF @temp1 like '%Error in connecting server.%' OR @temp1 like '%Error in connecting server. connection timeout.%'
SELECT 'yes'
ELSE
SELECT 'no'
Look at the MSDN blog which details out this error:
Removing Connections
The connection pooler removes a connection from the pool after it has been idle for a long time, or if the pooler detects that the connection with the server has been severed.
Note that a severed connection can be detected only after attempting to communicate with the server. If a connection is found that is no longer connected to the server, it is marked as invalid.
Invalid connections are removed from the connection pool only when they are closed or reclaimed.
If a connection exists to a server that has disappeared, this connection can be drawn from the pool even if the connection pooler has not detected the severed connection and marked it as invalid.
This is the case because the overhead of checking that the connection is still valid would eliminate the benefits of having a pooler by causing another round trip to the server to occur.
When this occurs, the first attempt to use the connection will detect that the connection has been severed, and an exception is thrown.
Basically what you are seeing is that exception in the last sentence.
A connection is taken from the connection pool, the application does not know that the physical connection is gone, an attempt to use it is done under the assumption that the physical connection is still there.
And you get your exception.
There are a few common reasons for this.
- The server has been restarted, this will close the existing connections.
In this case, have a look at the SQL Server log, usually found at: C:\Program Files\Microsoft SQL Server\\MSSQL\LOG
If the timestamp for startup is very recent, then we can suspect that this is what caused the error. Try to correlate this timestamp with the time of exception.
2009-04-16 11:32:15.62 Server Logging SQL Server messages in file ‘C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\ERRORLOG’.
- Someone or something has killed the SPID that is being used.
Again, take a look in the SQL Server log. If you find a kill, try to correlate this timestamp with the time of exception.
2009-04-16 11:34:09.57 spidXX Process ID XX was killed by hostname xxxxx, host process ID XXXX.
- There is a failover (in a mirror setup for example) again, take a look in the SQL Server log.
If there is a failover, try to correlate this timestamp with the time of exception.
2009-04-16 11:35:12.93 spidXX The mirrored database “” is changing roles from “PRINCIPAL” to “MIRROR” due to Failover.
You need to use background-size: 100% 100%;
Demo 2 (Won't stretch, this is what you are doing)
Explanation: You need to use 100% 100%
as it sets for X
AS WELL AS Y
, you are setting 100%
just for the X
parameter, thus the background doesn't stretch vertically.
Still, the image will stretch out, it won't be responsive, if you want to stretch the background
proportionately, you can look for background-size: cover;
but IE will create trouble for you here as it's CSS3 property, but yes, you can use CSS3 Pie as a polyfill. Also, using cover
will crop your image.
I had the same problem, so I solved in this way.
Step 1: Close Vb
.
Step 2: Just go to your project directory and delete Bin
folder.
Step 3: Open Vb
.
Interesting enough, this error also occurs, at time of opening when the .XLS?
file is incorrectly formed or require repairs.
A hard to find error is to many rows on a .xls (old excel) file.
Test it: manually open the affected file with excel desktop .
I use automation to process a few hundred files daily, when this error show up, I notify the owner via mail and save the unprocessed file on a temporary location.
Recursive function grouping 2-dimensional array by keys from first to last
Input:
$arr = array(
'0' => array(
'key0' => 'value0',
'key1' => 'value1',
'key2' => 'value02',
),
'2' => array(
'key0' => 'value0',
'key1' => 'value1',
'key2' => 'value12',
),
'3' => array(
'key0' => 'value0',
'key1' => 'value3',
'key2' => 'value22',
),
);
$keys = array('key0', 'key1', 'key2');
Output:
$arr = array(
'value0' => array(
'value1 => array(
'value02' => null,
'value12' => null,
),
'value3' => 'value22',
),
);
Code:
function array_group_by_keys(&$arr, $keys) {
if (count($arr) < 2){
$arr = array_shift($arr[0]);
return;
}
foreach ($arr as $k => $item) {
$fvalue = array_shift($item);
$arr[$fvalue][] = $item;
unset($arr[$k]);
}
array_shift($keys);
foreach ($arr as &$sub_arr) {
array_group_by_keys($sub_arr, $keys);
}
}
I think a solution is to put count in back ticks
.filter("`count` >= 2")
in case if someone using the codeigniter framework, the problem may be caused by the csrf protection config enabled.
This question is tagged with PHP. But many people are using Laravel framework now. It might help somebody in future. That's why I answering for Laravel. It's more easy to encrypt and decrypt with internal functions.
$string = 'c4ca4238a0b923820dcc';
$encrypted = \Illuminate\Support\Facades\Crypt::encrypt($string);
$decrypted_string = \Illuminate\Support\Facades\Crypt::decrypt($encrypted);
var_dump($string);
var_dump($encrypted);
var_dump($decrypted_string);
Note: Be sure to set a 16, 24, or 32 character random string in the key option of the config/app.php file. Otherwise, encrypted values will not be secure.
But you should not use encrypt and decrypt for authentication. Rather you should use hash make and check.
$password = Input::get('password_from_user');
$hashed = Hash::make($password); // save $hashed value
// $user is database object
// $inputs is Input from user
if( \Illuminate\Support\Facades\Hash::check( $inputs['password'], $user['password']) == false) {
// Password is not matching
} else {
// Password is matching
}
Since Java 8, it seems like the java.time
standard library is the way to go. From Joda time web page:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Back to your question. Were you to use Java 8, I think you want LocalDateTime
. Because it contains the date and time-of-the-day, but is unaware of time zone or any reference point in time such as the unix epoch.
In Android Studio v1.2, it tells you how to fix it:
make a class for that button lets say :
`<input type="button" value="+" class="b1" onclick="addRow()">`
your js should look like this :
$(document).ready(function(){
$('.b1').click(function(){
$('div').append('<input type="text"..etc ');
});
});
date +%s%N
returns the number of seconds + current nanoseconds.
Therefore, echo $(($(date +%s%N)/1000000))
is what you need.
Example:
$ echo $(($(date +%s%N)/1000000))
1535546718115
date +%s
returns the number of seconds since the epoch, if that's useful.
Run the below query against the database
select distinct local_net_address, local_tcp_port from sys.dm_exec_connections where local_net_address is not null
The above query shows the local IP as well as the listening Port number
Today I was checking some resources about the same question and I got an example very interesting.
It is possible to call the same method by GET and POST protocol, but you need to overload the parameters like that:
@using (Ajax.BeginForm("Index", "MyController", ajaxOptions, new { @id = "form-consulta" }))
{
//code
}
The action:
[ActionName("Index")]
public async Task<ActionResult> IndexAsync(MyModel model)
{
//code
}
By default a method without explicit protocol is GET, but in that case there is a declared parameter which allows the method works like a POST.
When GET is executed the parameter does not matter, but when POST is executed the parameter is required on your request.
I would like to add this, I used this in laravel to just index my table:
My Code:
@foreach($resultsPerCountry->first()->studies as $result)
<tr>
<td>{{ ++$loop->index}}</td>
</tr>
@endforeach
Here's a way you can request info about the browser being used, you can use this to do your if statement
System.Web.HttpBrowserCapabilities browser = Request.Browser;
string s = "Browser Capabilities\n"
+ "Type = " + browser.Type + "\n"
+ "Name = " + browser.Browser + "\n"
+ "Version = " + browser.Version + "\n"
+ "Major Version = " + browser.MajorVersion + "\n"
+ "Minor Version = " + browser.MinorVersion + "\n"
+ "Platform = " + browser.Platform + "\n"
+ "Is Beta = " + browser.Beta + "\n"
+ "Is Crawler = " + browser.Crawler + "\n"
+ "Is AOL = " + browser.AOL + "\n"
+ "Is Win16 = " + browser.Win16 + "\n"
+ "Is Win32 = " + browser.Win32 + "\n"
+ "Supports Frames = " + browser.Frames + "\n"
+ "Supports Tables = " + browser.Tables + "\n"
+ "Supports Cookies = " + browser.Cookies + "\n"
+ "Supports VBScript = " + browser.VBScript + "\n"
+ "Supports JavaScript = " +
browser.EcmaScriptVersion.ToString() + "\n"
+ "Supports Java Applets = " + browser.JavaApplets + "\n"
+ "Supports ActiveX Controls = " + browser.ActiveXControls
+ "\n";
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
For a string of length 1 you can simply perform isdigit()
or isalpha()
If your string length is greater than 1, you can make a function something like..
def isinteger(a):
try:
int(a)
return True
except ValueError:
return False
basically inline-table
is for element table, I guess what you really need here is inline-block
, if you have to use inline-table
anyway, try it this way:
<div style="width:50%; display:inline-table;">A</div><!--
--><div style="width:50%; display:inline-table;">B</div>
This introduces a new paradigm to HTML/CSS, but using an <input readonly="true">
would allow you to append an input:focus
selector to then alter the background-image
This of course would require applying specific CSS to the input
itself to override browser defaults but it does go to show that click actions can indeed be triggered without the use of Javascript.
Apart from using the importlib
one can also use exec
method to import a module from a string variable.
Here I am showing an example of importing the combinations
method from itertools
package using the exec
method:
MODULES = [
['itertools','combinations'],
]
for ITEM in MODULES:
import_str = "from {0} import {1}".format(ITEM[0],', '.join(str(i) for i in ITEM[1:]))
exec(import_str)
ar = list(combinations([1, 2, 3, 4], 2))
for elements in ar:
print(elements)
Output:
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
The error means that your are trying to look up JNDI name, that is not attached to any EJB component - the component with that name does not exist.
As far as dir structure is concerned: you have to create a JAR file with EJB components. As I understand you want to play with EJB 2.X components (at least the linked example suggests that) so the structure of the JAR file should be:
/com/mypackage/MyEJB.class /com/mypackage/MyEJBInterface.class /com/mypackage/etc... etc... java classes /META-INF/ejb-jar.xml /META-INF/jboss.xml
The JAR file is more or less ZIP file with file extension changed from ZIP to JAR.
BTW. If you use JBoss 5, you can work with EJB 3.0, which are much more easier to configure. The simplest component is
@Stateless(mappedName="MyComponentName")
@Remote(MyEJBInterface.class)
public class MyEJB implements MyEJBInterface{
public void bussinesMethod(){
}
}
No ejb-jar.xml, jboss.xml is needed, just EJB JAR with MyEJB and MyEJBInterface compiled classes.
Now in your client code you need to lookup "MyComponentName".
The chosen answer is a good answer, but be careful with the object returned.
string test = null;
string test2 = "";
if (test is string)
Console.WriteLine("This will never be hit.");
if (test2 is string)
Console.WriteLine("Always hit.");
Extrapolating...
string test = GetDefault(typeof(string));
if (test is string)
Console.WriteLine("This will never be hit.");
See my code which may help you. models.py
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
password = models.CharField(max_length=100)
instrument_purchase = models.CharField(max_length=100)
house_no = models.CharField(max_length=100)
address_line1 = models.CharField(max_length=100)
address_line2 = models.CharField(max_length=100)
telephone = models.CharField(max_length=100)
zip_code = models.CharField(max_length=20)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
def __str__(self):
return self.name
forms.py
from django import forms
from models import *
class CustomerForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = Customer
fields = ('name', 'email', 'password', 'instrument_purchase', 'house_no', 'address_line1', 'address_line2', 'telephone', 'zip_code', 'state', 'country')
WHERE dates BETWEEN (convert(datetime, '2012-12-12',110) AND (convert(datetime, '2012-12-12',110))
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
I'd like to add df.values.tolist()
. (as long as you don't mind to get a column of lists rather than tuples)
import pandas as pd
import numpy as np
size = int(1e+07)
df = pd.DataFrame({'a': np.random.rand(size), 'b': np.random.rand(size)})
%timeit df.values.tolist()
1.47 s ± 38.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit list(zip(df.a,df.b))
1.92 s ± 131 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
It's a linker problem. Include the static library path into your project.
For Qt Creator open the project file .pro
and add the following line:
LIBS += -L<path for boost libraries in the system> -lboost_system
In my case Ubuntu x86_64:
LIBS += -L/usr/lib/x86_64-linux-gnu -lboost_system
For Codeblocks, open up Settings->Compiler...->Linker
settings tab and add:
boost_system
to the Link libraries text widget and press OK button.
Why could you not just make a file structure on the Windows file system and populate it with your desired names, then use a screen grabber like HyperSnap (or the ubiquitous Alt-PrtScr) to capture a section of the Explorer window.
I did this when 'demoing' an internet application which would have collapsible sections, I just had to create files that looked like my desired entries.
HyperSnap gives JPGs at least (probably others but I've never bothered to investigate).
Or you could screen capture the icons +/- from Explorer and use them within MS Word Draw itself to do your picture, but I've never been able to get MS Word Draw to behave itself properly.
To install Python package from github, you need to clone that repository.
git clone https://github.com/jkbr/httpie.git
Then just run the setup.py file from that directory,
sudo python setup.py install
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
>>> a = [(1, u'abc'), (2, u'def')]
>>> [i[0] for i in a]
[1, 2]
I use these two commands and I can see the files to change.
First executing git fetch, it gives output like this (part of output):
... 72f8433..c8af041 develop -> origin/develop ...
This operation gives us two commit IDs, first is the old one, and second will be the new.
Then compare these two commits using git diff
git diff 72f8433..c8af041 | grep "diff --git"
This command will list the files that will be updated:
diff --git a/app/controller/xxxx.php b/app/controller/xxxx.php
diff --git a/app/view/yyyy.php b/app/view/yyyy.php
For example app/controller/xxxx.php and app/view/yyyy.php will be updated.
Comparing two commits using git diff prints all updated files with changed lines, but with grep it searches and gets only the lines contains diff --git from output.
I had to reinstall pdAdmin to resolve this issue
brew cask reinstall pgadmin4
I was getting nothing for any $_GET["..."]
(e.g print_r($_GET)
gave an empty array) yet $_SERVER['REQUEST_URI']
showed stuff should be there. In the end it turned out that I was only getting to the web page because my .htaccess was redirecting it there (my 404 handler was the same .php file, and I had made a typo in the browser when testing).
Simply changing the name meant the same php code worked once the 404 redirection wasn't kicking in!
So there are ways $_GET
can return nothing even though the php code may be correct.
The accepted answer will also list the files that exist in both directories, but have different content. To list ONLY the files that exist in dir1 you can use:
diff -r dir1 dir2 | grep 'Only in' | grep dir1 | awk '{print $4}' > difference1.txt
Explanation:
I've encountered this a couple times and keep forgetting what causes it. I ran into this when I renamed the namespace on my code behind file but not in my XAML.
So check if you've done the same.
The namespace and class names need to match since they are both part of a partial class
namespace ZZZ
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow
{
//...
}
}
<!-- XAML -->
<Window x:Class="ZZZ.MainWindow">
//start the program
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
// config for your database
var config = {
user: 'datapullman',
password: 'system',
server: 'localhost',
database: 'chat6'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query("select * From emp", function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
//create a table as emp in a database (i have created as chat6)
// programs ends here
//save it as app.js and run as node app.js //open in you browser as localhost:5000
If you have another file in same directory, you can either do:
bash another_script.sh
or
source another_script.sh
or
. another_script.sh
When you use bash
instead of source
, the script cannot alter environment of the parent script. The .
command is POSIX standard while source
command is a more readable bash synonym for .
(I prefer source
over .
). If your script resides elsewhere just provide path to that script. Both relative as well as full path should work.
To further jfriend00's answer (I dont't have enough points to comment) I have extended his/her answer to the following:
function log(args) {_x000D_
var str = "";_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
if (typeof arguments[i] === "object") {_x000D_
str += JSON.stringify(arguments[i]);_x000D_
} else {_x000D_
str += arguments[i];_x000D_
}_x000D_
}_x000D_
var div = document.createElement("div");_x000D_
div.innerHTML = str;_x000D_
document.body.appendChild(div);_x000D_
}_x000D_
_x000D_
Number.prototype.addCommas = function (str) {_x000D_
if (str === undefined) {_x000D_
str = this;_x000D_
}_x000D_
_x000D_
var parts = (str + "").split("."),_x000D_
main = parts[0],_x000D_
len = main.length,_x000D_
output = "",_x000D_
first = main.charAt(0),_x000D_
i;_x000D_
_x000D_
if (first === '-') {_x000D_
main = main.slice(1);_x000D_
len = main.length; _x000D_
} else {_x000D_
first = "";_x000D_
}_x000D_
i = len - 1;_x000D_
while(i >= 0) {_x000D_
output = main.charAt(i) + output;_x000D_
if ((len - i) % 3 === 0 && i > 0) {_x000D_
output = "," + output;_x000D_
}_x000D_
--i;_x000D_
}_x000D_
// put sign back_x000D_
output = first + output;_x000D_
// put decimal part back_x000D_
if (parts.length > 1) {_x000D_
output += "." + parts[1];_x000D_
}_x000D_
return output;_x000D_
}_x000D_
_x000D_
var testCases = [_x000D_
1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789,_x000D_
-1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1_x000D_
];_x000D_
_x000D_
for (var i = 0; i < testCases.length; i++) {_x000D_
log(testCases[i].addCommas());_x000D_
}_x000D_
_x000D_
/*for (var i = 0; i < testCases.length; i++) {_x000D_
log(Number.addCommas(testCases[i]));_x000D_
}*/
_x000D_
You need to change File > Settings > Builds,Execution,Deployment > Build Tools > Gradle >Gradle home path
On Mac OS, change the path in Android Studio > Preferences > Builds,Execution,Deployment > Build Tools > Gradle >Gradle home
Or set Use default gradle wrapper and edit Project\gradle\wrapper\gradle-wrapper.properties
files field distributionUrl
like this
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip
I will reproduce a good tutorial here, because I lost this article and take some time to find it again!
Adding syntax highlighting for new languages to Eclipse with the Colorer library
Say you have an HRC file containing the syntax and lexical structure of some programming language Eclipse does not support (for example D / Iptables or any other script language).
Using the EclipseColorer plugin, you can easily add support for it.
Go to Help -> Install New Software and click Add.. In the Name field write Colorer and in the Location field write http://colorer.sf.net/eclipsecolorer/
Select the entry you’ve just added in the work with: combo box, wait for the component list to populate and click Select All
Click Next and follow the instructions
Once the plugin is installed, close Eclipse.
Copy your HRC file to [EclipseFolder]\plugins\net.sf.colorer_0.9.9\colorer\hrc\auto\types
[EclipseFolder] = /home/myusername/.eclipse
Use your favorite text editor to open
[EclipseFolder]\plugins\net.sf.colorer_0.9.9\colorer\hrc\auto\empty.hrc
Add the appropriate prototype element. For example, if your HRC file is d.hrc, empty.hrc will look like this:
<?xml version="1.0" encoding='Windows-1251'?>
<!DOCTYPE hrc PUBLIC
"-//Cail Lomecb//DTD Colorer HRC take5//EN"
"http://colorer.sf.net/2003/hrc.dtd"
>
<hrc version="take5" xmlns="http://colorer.sf.net/2003/hrc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://colorer.sf.net/2003/hrc http://colorer.sf.net/2003/hrc.xsd"
><annotation><documentation>
'auto' is a place for include
to colorer your own HRCs
</documentation></annotation>
<prototype name="d" group="main" description="D">
<location link="types/d.hrc"/>
<filename>/\.(d)$/i</filename>
</prototype>
</hrc>
Save the changes and close the text editor
Open Eclipse and go to Window -> Preferences -> General -> Editors -> File Associations
In the file types section, click Add.. and fill in the appropriate filetype (for example .d)
Click OK and click your newly added entry in the list
In the associated editors section, click Add.., select Colorer Editor and press OK
ok, the hard part is you must learn about HCR syntax.
You can look in
[EclipseFolder]/net.sf.colorer_0.9.9/colorer/hrc/common.jar
to learn how do it and explore many other hcr's files. At this moment I didn't find any documentation.
My gift is a basic and incomplete iptables syntax highlight. If you improve please share with me.
<?xml version="1.0" encoding="Windows-1251"?>
<!DOCTYPE hrc PUBLIC "-//Cail Lomecb//DTD Colorer HRC take5//EN" "http://colorer.sf.net/2003/hrc.dtd">
<hrc version="take5" xmlns="http://colorer.sf.net/2003/hrc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://colorer.sf.net/2003/hrc http://colorer.sf.net/2003/hrc.xsd">
<type name="iptables">
<annotation>
<develby> Mario Moura - moura.mario gmail.com</develby>
<documentation>Support iptables EQL language</documentation>
<appinfo>
<prototype name="iptables" group="database" description="iptables">
<location link="iptables.hrc"/>
<filename>/\.epl$/i</filename>
</prototype>
</appinfo>
</annotation>
<region name="iptablesTable" parent="def:Keyword"/>
<region name="iptablesChainFilter" parent="def:Symbol"/>
<region name="iptablesChainNatMangle" parent="def:NumberDec"/>
<region name="iptablesCustomDefaultChains" parent="def:Keyword"/>
<region name="iptablesOptions" parent="def:String"/>
<region name="iptablesParameters" parent="def:Operator"/>
<region name="iptablesOtherOptions" parent="def:Comment"/>
<region name="iptablesMatchExtensions" parent="def:ParameterStrong"/>
<region name="iptablesTargetExtensions" parent="def:FunctionKeyword"/>
<region name="pyComment" parent="def:Comment"/>
<region name="pyOperator" parent="def:Operator"/>
<region name="pyDelimiter" parent="def:Symbol"/>
<scheme name="iptablesTable">
<keywords ignorecase="no" region="iptablesTable">
<word name="mangle"/>
<word name="filter"/>
<word name="nat"/>
<word name="as"/>
<word name="at"/>
<word name="asc"/>
<word name="avedev"/>
<word name="avg"/>
<word name="between"/>
<word name="by"/>
</keywords>
</scheme>
<scheme name="iptablesChainFilter">
<keywords ignorecase="no" region="iptablesChainFilter">
<word name="FORWARD"/>
<word name="INPUT"/>
<word name="OUTPUT"/>
</keywords>
</scheme>
<scheme name="iptablesChainNatMangle">
<keywords ignorecase="no" region="iptablesChainNatMangle">
<word name="PREROUTING"/>
<word name="POSTROUTING"/>
<word name="OUTPUT"/>
</keywords>
</scheme>
<scheme name="iptablesCustomDefaultChains">
<keywords ignorecase="no" region="iptablesCustomDefaultChains">
<word name="CHTTP"/>
<word name="CHTTPS"/>
<word name="CSSH"/>
<word name="CDNS"/>
<word name="CFTP"/>
<word name="CGERAL"/>
<word name="CICMP"/>
</keywords>
</scheme>
<scheme name="iptablesOptions">
<keywords ignorecase="no" region="iptablesOptions">
<word name="-A"/>
<word name="--append"/>
<word name="-D"/>
<word name="--delete"/>
<word name="-I"/>
<word name="--insert"/>
<word name="-R"/>
<word name="--replace"/>
<word name="-L"/>
<word name="--list"/>
<word name="-F"/>
<word name="--flush"/>
<word name="-Z"/>
<word name="--zero"/>
<word name="-N"/>
<word name="--new-chain"/>
<word name="-X"/>
<word name="--delete-chain"/>
<word name="-P"/>
<word name="--policy"/>
<word name="-E"/>
<word name="--rename-chain"/>
</keywords>
</scheme>
<scheme name="iptablesParameters">
<keywords ignorecase="no" region="iptablesParameters">
<word name="-p"/>
<word name="--protocol"/>
<word name="-s"/>
<word name="--source"/>
<word name="-d"/>
<word name="--destination"/>
<word name="-j"/>
<word name="--jump"/>
<word name="-g"/>
<word name="--goto"/>
<word name="-i"/>
<word name="--in-interface"/>
<word name="-o"/>
<word name="--out-interface"/>
<word name="-f"/>
<word name="--fragment"/>
<word name="-c"/>
<word name="--set-counters"/>
</keywords>
</scheme>
<scheme name="iptablesOtherOptions">
<keywords ignorecase="no" region="iptablesOtherOptions">
<word name="-v"/>
<word name="--verbose"/>
<word name="-n"/>
<word name="--numeric"/>
<word name="-x"/>
<word name="--exact"/>
<word name="--line-numbers"/>
<word name="--modprobe"/>
</keywords>
</scheme>
<scheme name="iptablesMatchExtensions">
<keywords ignorecase="no" region="iptablesMatchExtensions">
<word name="account"/>
<word name="addrtype"/>
<word name="childlevel"/>
<word name="comment"/>
<word name="connbytes"/>
<word name="connlimit"/>
<word name="connmark"/>
<word name="connrate"/>
<word name="conntrack"/>
<word name="dccp"/>
<word name="dscp"/>
<word name="dstlimit"/>
<word name="ecn"/>
<word name="esp"/>
<word name="hashlimit"/>
<word name="helper"/>
<word name="icmp"/>
<word name="ipv4options"/>
<word name="length"/>
<word name="limit"/>
<word name="mac"/>
<word name="mark"/>
<word name="mport"/>
<word name="multiport"/>
<word name="nth"/>
<word name="osf"/>
<word name="owner"/>
<word name="physdev"/>
<word name="pkttype"/>
<word name="policy"/>
<word name="psd"/>
<word name="quota"/>
<word name="realm"/>
<word name="recent"/>
<word name="sctp"/>
<word name="set"/>
<word name="state"/>
<word name="string"/>
<word name="tcp"/>
<word name="tcpmss"/>
<word name="tos"/>
<word name="u32"/>
<word name="udp"/>
</keywords>
</scheme>
<scheme name="iptablesTargetExtensions">
<keywords ignorecase="no" region="iptablesTargetExtensions">
<word name="BALANCE"/>
<word name="CLASSIFY"/>
<word name="CLUSTERIP"/>
<word name="CONNMARK"/>
<word name="DNAT"/>
<word name="DSCP"/>
<word name="ECN"/>
<word name="IPMARK"/>
<word name="IPV4OPTSSTRIP"/>
<word name="LOG"/>
<word name="MARK"/>
<word name="MASQUERADE"/>
<word name="MIRROR"/>
<word name="NETMAP"/>
<word name="NFQUEUE"/>
<word name="NOTRACK"/>
<word name="REDIRECT"/>
<word name="REJECT"/>
<word name="SAME"/>
<word name="SET"/>
<word name="SNAT"/>
<word name="TARPIT"/>
<word name="TCPMSS"/>
<word name="TOS"/>
<word name="TRACE"/>
<word name="TTL"/>
<word name="ULOG"/>
<word name="XOR"/>
</keywords>
</scheme>
<scheme name="iptables">
<inherit scheme="iptablesTable"/>
<inherit scheme="iptablesChainFilter"/>
<inherit scheme="iptablesChainNatMangle"/>
<inherit scheme="iptablesCustomDefaultChains"/>
<inherit scheme="iptablesOptions"/>
<inherit scheme="iptablesParameters"/>
<inherit scheme="iptablesOtherOptions"/>
<inherit scheme="iptablesMatchExtensions"/>
<inherit scheme="iptablesTargetExtensions"/>
<!-- python operators : http://docs.python.org/ref/keywords.html -->
<keywords region="pyOperator">
<symb name="+"/>
<symb name="-"/>
<symb name="*"/>
<symb name="**"/>
<symb name="/"/>
<symb name="//"/>
<symb name="%"/>
<symb name="<<"/>
<symb name=">>"/>
<symb name="&"/>
<symb name="|"/>
<symb name="^"/>
<symb name="~"/>
<symb name="<"/>
<symb name=">"/>
<symb name="<="/>
<symb name=">="/>
<symb name="=="/>
<symb name="!="/>
<symb name="<>"/>
</keywords>
<!-- basic python comment - consider it everything after # till the end of line -->
<block start="/#/" end="/$/" region="pyComment" scheme="def:Comment"/>
<block start="/(u|U)?(r|R)?("{3}|'{3})/" end="/\y3/"
region00="def:PairStart" region10="def:PairEnd"
scheme="def:Comment" region="pyComment" />
<!-- TODO: better scheme for multiline comments/docstrings -->
<!-- scheme="StringCommon" region="pyString" /> -->
<!-- python delimiters : http://docs.python.org/ref/delimiters.html -->
<keywords region="pyDelimiter">
<symb name="+"/>
<symb name="("/>
<symb name=")"/>
<symb name="["/>
<symb name="]"/>
<symb name="{"/>
<symb name="}"/>
<symb name="@"/>
<symb name=","/>
<symb name=":"/>
<symb name="."/>
<symb name="`"/>
<symb name="="/>
<symb name=";"/>
<symb name="+="/>
<symb name="-="/>
<symb name="*="/>
<symb name="/="/>
<symb name="//="/>
<symb name="%="/>
<symb name="&="/>
<symb name="|="/>
<symb name="^="/>
<symb name=">>="/>
<symb name="<<="/>
<symb name="**="/>
</keywords>
</scheme>
</type>
After this you must save the file as iptables.hcr and add inside the jar:
[EclipseFolder]/net.sf.colorer_0.9.9/colorer/hrc/common.jar
SELECT * FROM (SELECT *,(((acos(sin((43.6980168*pi()/180)) *
sin((latitude*pi()/180))+cos((43.6980168*pi()/180)) *
cos((latitude*pi()/180)) * cos(((7.266903899999988- longitude)*
pi()/180))))*180/pi())*60*1.1515 ) as distance
FROM wp_users WHERE 1 GROUP BY ID limit 0,10) as X
ORDER BY ID DESC
This is the distance calculation query between to points in MySQL, I have used it in a long database, it it working perfect! Note: do the changes (database name, table name, column etc) as per your requirements.
If you don't mind jQuery, I am using this:
<table id="metaConfigTable">
<caption>This is your target table</caption>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</table>
<script>
function tabelajzing(a){
// takes (key, value) pairs from and array and returns
// corresponding html, i.e. [ [1,2], [3,4], [5,6] ]
return [
"<tr>\n<th>",
a.map(function (e, i) {
return e.join("</th>\n<td>")
}).join("</td></tr>\n<tr>\n<th>"),
"</td>\n</tr>\n"
].join("")
}
$('#metaConfigTable').find("tr").after(
tabelajzing( [ [1,2],[3,4],[5,6] ])
);
</script>
function sendAjaxRequest(element,urlToSend) {
var clickedButton = element;
$.ajax({type: "POST",
url: urlToSend,
data: { id: clickedButton.val(), access_token: $("#access_token").val() },
success:function(result){
alert('ok');
},
error:function(result)
{
alert('error');
}
});
}
$(document).ready(function(){
$("#button_1").click(function(e){
e.preventDefault();
sendAjaxRequest($(this),'/pages/test/');
});
$("#button_2").click(function(e){
e.preventDefault();
sendAjaxRequest($(this),'/pages/test/');
});
});
$suborder['payment_date'] = Carbon::parse($item['created_at'])->format('M d Y');
You can just print the packages that are outdated:
pip freeze | cut -d = -f 1 | xargs -n 1 pip search | grep -B2 'LATEST:'
It is up to the browser but they behave in similar ways.
I have tested FF, IE7, Opera and Chrome.
F5 usually updates the page only if it is modified. The browser usually tries to use all types of cache as much as possible and adds an "If-modified-since" header to the request. Opera differs by sending a "Cache-Control: no-cache".
CTRL-F5 is used to force an update, disregarding any cache. IE7 adds an "Cache-Control: no-cache", as does FF, which also adds "Pragma: no-cache". Chrome does a normal "If-modified-since" and Opera ignores the key.
If I remember correctly it was Netscape which was the first browser to add support for cache-control by adding "Pragma: No-cache" when you pressed CTRL-F5.
Edit: Updated table
The table below is updated with information on what will happen when the browser's refresh-button is clicked (after a request by Joel Coehoorn), and the "max-age=0" Cache-control-header.
Updated table, 27 September 2010
+------------------------------------------------------------+
¦ UPDATED ¦ Firefox 3.x ¦
¦27 SEP 2010 ¦ +--------------------------------------------¦
¦ ¦ ¦ MSIE 8, 7 ¦
¦ Version 3 ¦ ¦ +-----------------------------------------¦
¦ ¦ ¦ ¦ Chrome 6.0 ¦
¦ ¦ ¦ ¦ +--------------------------------------¦
¦ ¦ ¦ ¦ ¦ Chrome 1.0 ¦
¦ ¦ ¦ ¦ ¦ +-----------------------------------¦
¦ ¦ ¦ ¦ ¦ ¦ Opera 10, 9 ¦
¦ ¦ ¦ ¦ ¦ ¦ +--------------------------------¦
¦ ¦ ¦ ¦ ¦ ¦ ¦ ¦
+------------+--+--+--+--+--+--------------------------------¦
¦ F5¦IM¦I ¦IM¦IM¦C ¦ ¦
¦ SHIFT-F5¦- ¦- ¦CP¦IM¦- ¦ Legend: ¦
¦ CTRL-F5¦CP¦C ¦CP¦IM¦- ¦ I = "If-Modified-Since" ¦
¦ ALT-F5¦- ¦- ¦- ¦- ¦*2¦ P = "Pragma: No-cache" ¦
¦ ALTGR-F5¦- ¦I ¦- ¦- ¦- ¦ C = "Cache-Control: no-cache" ¦
+------------+--+--+--+--+--¦ M = "Cache-Control: max-age=0" ¦
¦ CTRL-R¦IM¦I ¦IM¦IM¦C ¦ - = ignored ¦
¦CTRL-SHIFT-R¦CP¦- ¦CP¦- ¦- ¦ ¦
+------------+--+--+--+--+--¦ ¦
¦ Click¦IM¦I ¦IM¦IM¦C ¦ With 'click' I refer to a ¦
¦ Shift-Click¦CP¦I ¦CP¦IM¦C ¦ mouse click on the browsers ¦
¦ Ctrl-Click¦*1¦C ¦CP¦IM¦C ¦ refresh-icon. ¦
¦ Alt-Click¦IM¦I ¦IM¦IM¦C ¦ ¦
¦ AltGr-Click¦IM¦I ¦- ¦IM¦- ¦ ¦
+------------------------------------------------------------+
Versions tested:
Notes:
Version 3.0.6 sends I and C, but 3.1.6 opens the page in a new tab, making a normal request with only "I".
Version 10.62 does nothing. 9.61 might do C unless it was a typo in my old table.
Note about Chrome 6.0.472: If you do a forced reload (like CTRL-F5) it behaves like the url is internally marked to always do a forced reload. The flag is cleared if you go to the address bar and press enter.
"Core Java" is Oracle's definition and refers to subset of Java SE technologies.
This actually is not related to Java language itself but rather to set of some 'basic' packages. As a result it affects development approaches.
Currently Java Core is defined as a following set:
But as you probably understand even term 'basic technologies' is somewhat unclear ;-) so this is not so strict definition. Here is official page for this term:
Here is another picture illustrating Java Core API / technologies inside Java SE platform.
Try this:
SCRIPT:
function winOpen()
{
window.open("yourpage.jsp");
}
HTML:
<a href="javascript:;" onclick="winOpen()">Pop Up</a>
Read https://developer.mozilla.org/en/docs/DOM/window.open for window.open
The Separator
you are using is a UI component. You would be better using a simple String sep = ", "
.
Don't use sprintf.
It will overflow your String-Buffer and crash your Program.
Always use snprintf
It lets you handle Many to Many relationship. Example:
Table 1: post
post has following columns
____________________
| ID | DATE |
|_________|_________|
| | |
|_________|_________|
Table 2: user
user has the following columns:
____________________
| ID |NAME |
|_________|_________|
| | |
|_________|_________|
Join Table lets you create a mapping using:
@JoinTable(
name="USER_POST",
joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="ID"),
inverseJoinColumns=@JoinColumn(name="POST_ID", referencedColumnName="ID"))
will create a table:
____________________
| USER_ID| POST_ID |
|_________|_________|
| | |
|_________|_________|
On GitHub, you can use HTML directly instead of Markdown:
<a href="url"><img src="http://url.to/image.png" align="left" height="48" width="48" ></a>
This should make it.
If you have @oneToOne
mapping set to FetchType.LAZY
and you use second query (because you need Department objects to be loaded as part of Employee objects) what Hibernate will do is, it will issue queries to fetch Department objects for every individual Employee object it fetches from DB.
Later, in the code you might access Department objects via Employee to Department single-valued association and Hibernate will not issue any query to fetch Department object for the given Employee.
Remember, Hibernate still issues queries equal to the number of Employees it has fetched. Hibernate will issue same number of queries in both above queries, if you wish to access Department objects of all Employee objects
If you're creating redirections, test with curl to avoid browser caching issues. Use -I to fetch http headers only. Use -L to follow all redirections.
Whilst some of the answers are good, there is a major caveat.
The mysql queries may be prevented from being cached, but it won't prevent your underlying O.S caching disk accesses into memory. This can be a major slowdown for some queries especially if they need to pull data from spinning disks.
So whilst it's good to use the methods above, I would also try and test with a different set of data/range each time, that's likely not been pulled from disk into disk/memory cache.
Execution is not related to laravel go to the php.ini file In php.ini file set max_execution_time=360 (time may be variable depends on need) if you want to increase execution of a specific page then write ini_set('max_execution_time',360) at top of page
otherwise in htaccess php_value max_execution_time 360
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
The localStorage
can only store string content and you are trying to store a jQuery object since html(htmlString)
returns a jQuery object.
You need to set the string content instead of an object. And use the setItem
method to add data and getItem
to get data.
window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));
Make the area with your data and formulas a Table:
Then adding new information in the next line will copy all formulas in that table for the new line. Data validation will also be applied for the new row as it was for the whole column. This is indeed Excel being smarter with your data.
NO VBA required...
You can simplify your code down to
url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
json_obj = urllib2.urlopen(url).read
player_json_list = json.loads(json_obj)
for player in readable_json_list:
print player['firstName']
You were trying to access a list element using dictionary syntax. the equivalent of
foo = [1, 2, 3, 4]
foo["1"]
It can be confusing when you have lists of dictionaries and keeping the nesting in order.
A bit old, but I thought sharing how I'd do it, based on chubbsondubs' answer:
I use FrameLayout
(see Documentation), since it is used to contain a single view, and inflate into it the view from the xml.
Code following:
public class MyView extends FrameLayout {
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public MyView(Context context) {
super(context);
initView();
}
private void initView() {
inflate(getContext(), R.layout.my_view_layout, this);
}
}
Using seeds.rb
file or FactoryBot
is great, but these are respectively great for fixed data structures and testing.
The seedbank
gem might give you more control and modularity to your seeds. It inserts rake tasks and you can also define dependencies between your seeds. Your rake task list will have these additions (e.g.):
rake db:seed # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/ENVIRONMENT/*.seeds.rb. ENVIRONMENT is the current environment in Rails.env.
rake db:seed:bar # Load the seed data from db/seeds/bar.seeds.rb
rake db:seed:common # Load the seed data from db/seeds.rb and db/seeds/*.seeds.rb.
rake db:seed:development # Load the seed data from db/seeds.rb, db/seeds/*.seeds.rb and db/seeds/development/*.seeds.rb.
rake db:seed:development:users # Load the seed data from db/seeds/development/users.seeds.rb
rake db:seed:foo # Load the seed data from db/seeds/foo.seeds.rb
rake db:seed:original # Load the seed data from db/seeds.rb
I know this is old but I had a similar need for this and I did not want to do the find and replace version. It turns out that you can nest the substitute method like so:
=SUBSTITUTE(SUBSTITUTE(F149, "a", " AM"), "p", " PM")
In my case, I am using excel to view a DBF file and however it was populated has times like this:
9:16a
2:22p
So I just made a new column and put that formula in it to convert it to the excel time format.
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
.vue
files<script>
var mylib = require('./mylib');
export default {
....
mylib
exports.myfunc = () => {....}
import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js
was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack
but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib
in a .vue
component. However as soon as I use mylib
there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
d['a']
and d['b']
to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict
, list
, set
).d['a']
, d['b']
changes at same time because they both point to same object.Window -> Show View -> Other -> Studio/Remote
(Drag this tabbed window wherever)
Click the add FTP button (see below); #profit
SoftReference
is designed for caches. When it is found that a WeakReference
references an otherwise unreachable object, then it will get cleared immediately. SoftReference
may be left as is. Typically there is some algorithm relating to the amount of free memory and the time last used to determine whether it should be cleared. The current Sun algorithm is to clear the reference if it has not been used in as many seconds as there are megabytes of memory free on the Java heap (configurable, server HotSpot checks against maximum possible heap as set by -Xmx
). SoftReference
s will be cleared before OutOfMemoryError
is thrown, unless otherwise reachable.
There are multiple ways to get the last inserted ID after insert command.
@@IDENTITY
: It returns the last Identity value generated on a Connection in current session, regardless of Table and the scope of statement that produced the valueSCOPE_IDENTITY()
: It returns the last identity value generated by the insert statement in the current scope in the current connection regardless of the table.IDENT_CURRENT(‘TABLENAME’)
: It returns the last identity value generated on the specified table regardless of Any connection, session or scope. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. Now it seems more difficult to decide which one will be exact match for my requirement.
I mostly prefer SCOPE_IDENTITY().
If you use select SCOPE_IDENTITY() along with TableName in insert statement, you will get the exact result as per your expectation.
Source : CodoBee
You could use:
cordova plugins list | awk '{print $1}' | xargs cordova plugins rm
and use cordova plugins list
to verify if plugins are all removed.
In my case, the orderBy is determined by a select box. I prefer Ludwig's response because you can set the sort direction in the select options as such:
$scope.options = [
{ label: 'Title', value: 'title' },
{ label: 'Newest', value: '-publish_date' },
{ label: 'Featured', value: '-featured' }
];
markup:
<select ng-model="orderProp" ng-options="opt as opt.label for opt in options"></select>
<ul>
<li ng-repeat="item in items | orderBy:orderProp.value"></li>
</ul>
In my case, it was not only necessary add jenkins
user to docker
group, but make that group the primary group of the jenkins
user.
# usermod -g docker jenkins
# usermod -a -G jenkins jenkins
Don't forget to reconnect the jenkins slave node or restart the jenkins server, depend on your case.
After hours of finding ways on how to get the data from the row selected on a WPF DataGrid Control, as I was using MongoDB. I found this post and used Tony's answer. I revised the code to be relevant to my project. Maybe someone can use this to get an idea.
private void selectionChanged(object sender, SelectionChangedEventArgs e)
{
facultyData row = (facultyData)facultyDataGrid.SelectedItem;
facultyID_Textbox.Text = row.facultyID;
lastName_TextBox.Text = row.lastName;
firstName_TextBox.Text = row.firstName;
middleName_TextBox.Text = row.middleName;
age_TextBox.Text = row.age.ToString();
}
}
class facultyData
{
public ObjectId _id { get; set; }
public string facultyID { get; set; }
public string acadYear { get; set; }
public string program { get; set; }
}
Almost everything is mentioned here. I would like to share one question which I was asked by a senior manager on database. I found the question pretty interesting and if you think about it deeply, it sort of has lot of meaning in it.
Question was - How would you describe database to your 5 year old kid ?
If you are looking to create an instant messenger for Android, this code should get you started somewhere.
Excerpt from the source :
This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.
EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.
There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!
*UPDATE : * Scringo services will be closed down on 15 February, 2015.
I am using this script after I rename my iOS Project. It helps to change the directories name and make the names in sync.
NOTE: you will need to manually change the scheme's name.
There are three answers here, depending on the version of React you're (forced to) work(ing) with, and whether you want to use hooks.
It's important to understand how React works, so you can do things properly (protip: it's is super worth running through the React tutorial exercise on the React website. It's well written, and covers all the basics in a way that actually explains how to do things). "Properly" here means that you're writing an application interface that happens to be rendered in a browser; all the interface work happens in React, not in "what you're used to if you're writing a web page" (this is why React apps are "apps", not "web pages").
React applications are rendered based off of two things:
What you're expressly not doing when you use React is generating HTML elements and then using those: when you tell React to use an <input>
, for instance, you are not creating an HTML input element, you are telling React to create a React input object that happens to render as an HTML input element, and whose event handling looks at, but is not controlled by, the HTML element's input events.
When using React, what you're doing is generating application UI elements that present the user with (often manipulable) data, with user interaction changing the Component's state, which may cause a rerender of part of your application interface to reflect the new state. In this model, the state is always the final authority, not "whatever UI library is used to render it", which on the web is the browser's DOM. The DOM is almost an afterthought in this programming model: it's just the particular UI framework that React happens to be using.
So in the case of an input element, the logic is:
render
call after the update, but only if the state update changed the state.All of that happens in a matter of milliseconds, if not less, so it looks like you typed into the input element in the same way you're used to from "just using an input element on a page", but that's absolutely not what happened.
So, with that said, on to how to get values from elements in React:
To do things properly, your component has a state value, which is shown via an input field, and we can update it by making that UI element send change events back into the component:
var Component = React.createClass({
getInitialState: function() {
return {
inputValue: ''
};
},
render: function() {
return (
//...
<input value={this.state.inputValue} onChange={this.updateInputValue}/>
//...
);
},
updateInputValue: function(evt) {
this.setState({
inputValue: evt.target.value
});
}
});
So we tell React to use the updateInputValue
function to handle the user interaction, use setState
to schedule the state update, and the fact that render
taps into this.state.inputValue
means that when it rerenders after updating the state, the user will see the update text based on what they typed.
addendum based on comments
Given that UI inputs represent state values (consider what happens if a user closes their tab midway, and the tab is restored. Should all those values they filled in be restored? If so, that's state). That might make you feel like a large form needs tens or even a hundred input forms, but React is about modeling your UI in a maintainable way: you do not have 100 independent input fields, you have groups of related inputs, so you capture each group in a component and then build up your "master" form as a collection of groups.
MyForm:
render:
<PersonalData/>
<AppPreferences/>
<ThirdParty/>
...
This is also much easier to maintain than a giant single form component. Split up groups into Components with state maintenance, where each component is only responsible for tracking a few input fields at a time.
You may also feel like it's "a hassle" to write out all that code, but that's a false saving: developers-who-are-not-you, including future you, actually benefit greatly from seeing all those inputs hooked up explicitly, because it makes code paths much easier to trace. However, you can always optimize. For instance, you can write a state linker
MyComponent = React.createClass({
getInitialState() {
return {
firstName: this.props.firstName || "",
lastName: this.props.lastName || ""
...: ...
...
}
},
componentWillMount() {
Object.keys(this.state).forEach(n => {
let fn = n + 'Changed';
this[fn] = evt => {
let update = {};
update[n] = evt.target.value;
this.setState(update);
});
});
},
render: function() {
return Object.keys(this.state).map(n => {
<input
key={n}
type="text"
value={this.state[n]}
onChange={this[n + 'Changed']}/>
});
}
});
Of course, there are improved versions of this, so hit up https://npmjs.com and search for a React state linking solution that you like best. Open Source is mostly about finding what others have already done, and using that instead of writing everything yourself from scratch.
As of React 16 (and soft-starting with 15.5) the createClass
call is no longer supported, and class syntax needs to be used. This changes two things: the obvious class syntax, but also the this
context binding that createClass
can do "for free", so to ensure things still work make sure you're using "fat arrow" notation for this
context preserving anonymous functions in onWhatever
handlers, such as the onChange
we use in the code here:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
inputValue: ''
};
}
render() {
return (
//...
<input value={this.state.inputValue} onChange={evt => this.updateInputValue(evt)}/>
//...
);
},
updateInputValue(evt) {
this.setState({
inputValue: evt.target.value
});
}
});
You may also have seen people use bind
in their constructor for all their event handling functions, like this:
constructor(props) {
super(props);
this.handler = this.handler.bind(this);
...
}
render() {
return (
...
<element onclick={this.handler}/>
...
);
}
Don't do that.
Almost any time you're using bind
, the proverbial "you're doing it wrong" applies. Your class already defines the object prototype, and so already defines the instance context. Don't put bind
of top of that; use normal event forwarding instead of duplicating all your function calls in the constructor, because that duplication increases your bug surface, and makes it much harder to trace errors because the problem might be in your constructor instead of where you call your code. As well as placing a burden of maintenance on others that you (have or choose) to work with.
Yes, I know the react docs say it's fine. It's not, don't do it.
As of React 16.8 the function component (i.e. literally just a function that takes some props
as argument can be used as if it's an instance of a component class, without ever writing a class) can also be given state, through the use of hooks.
If you don't need full class code, and a single instance function will do, then you can now use the useState
hook to get yourself a single state variable, and its update function, which works roughly the same as the above examples, except without the setState
function call:
import { useState } from 'react';
function myFunctionalComponentFunction() {
const [input, setInput] = useState(''); // '' is the initial state value
return (
<div>
<label>Please specify:</label>
<input value={input} onInput={e => setInput(e.target.value)}/>
</div>
);
}
Previously the unofficial distinction between classes and function components was "function components don't have state", so we can't hide behind that one anymore: the difference between function components and classes components can be found spread over several pages in the very well-written react documentation (no shortcut one liner explanation to conveniently misinterpret for you!) which you should read so that you know what you're doing and can thus know whether you picked the best (whatever that means for you) solution to program yourself out of a problem you're having.
It exists now in the statsmodels package:
http://statsmodels.sourceforge.net/devel/generated/statsmodels.graphics.gofplots.qqplot.html
It is not possible in on step or you need to keep the reference to the array. If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
You should look into using the MAC address on the network card (if it exists). Those are usually unique but can be fabricated. I've used software that generates its license file based on your network adapter MAC address, so it's considered a fairly reliable way to distinguish between computers.
There are several tools which can import Excel to SQL Server.
I am using DbTransfer (http://www.dbtransfer.com/Products/DbTransfer) to do the job. It's primarily focused on transfering data between databases and excel, xml, etc...
I have tried the openrowset method and the SQL Server Import / Export Assitant before. But I found these methods to be unnecessary complicated and error prone in constrast to doing it with one of the available dedicated tools.
It's better to add "overrides" in your .eslintrc.js config file. For example if you wont to disable camelcase rule for all js files ending on Actions add this code after rules scope in .eslintrc.js.
"rules": {
...........
},
"overrides": [
{
"files": ["*Actions.js"],
"rules": {
"camelcase": "off"
}
}
]
An alternative to fsolve
is root
:
import numpy as np
from scipy.optimize import root
def your_funcs(X):
x, y = X
# all RHS have to be 0
f = [x + y**2 - 4,
np.exp(x) + x * y - 3]
return f
sol = root(your_funcs, [1.0, 1.0])
print(sol.x)
This will print
[0.62034452 1.83838393]
If you then check
print(your_funcs(sol.x))
you obtain
[4.4508396968012676e-11, -1.0512035686360832e-11]
confirming that the solution is correct.
if ([strpass isEqual:[NSNull null]] || strpass==nil || [strpass isEqualToString:@"<null>"] || [strpass isEqualToString:@"(null)"] || strpass.length==0 || [strpass isEqualToString:@""])
{
//string is blank
}
None of the above solutions worked for me on Windows 8
But the following command works fine
SHIFT + Q
Get input1 data to send them to input2 immediately
<div>
<label>Input1</label>
<input type="text" id="input1" value="">
</div>
</br>
<label>Input2</label>
<input type="text" id="input2" value="">
<script type="text/javascript">
$(document).ready(function () {
$("#input1").keyup(function () {
var value = $(this).val();
$("#input2").val(value);
});
});
</script>
Actually what Luis proposed did not work for me. I had to figure out another way. This is what helped me. Might help you too. Links:
*.getEncoded(): https://docs.oracle.com/javase/7/docs/api/java/security/Key.html
Encoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html
Decoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html
Code snippets: For encoding:
String temp = new String(Base64.getEncoder().encode(key.getEncoded()));
For decoding:
byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");
You can still use the ExcelFile class (and the sheet_names
attribute):
xl = pd.ExcelFile('foo.xls')
xl.sheet_names # see all sheet names
xl.parse(sheet_name) # read a specific sheet to DataFrame
see docs for parse for more options...
You shouldn't launch as an IIS server. check your launch setting, make sure it switched to your project name( change this name in your launchSettings.json
file ), not the IIS.
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
By injecting an instance of ActivatedRoute
one can subscribe to a variety of observables, including a queryParams
and a params
observable:
import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, Component} from '@angular/core';
@Component({...})
export class MyComponent implements OnInit {
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
// Note: Below 'queryParams' can be replaced with 'params' depending on your requirements
this.activatedRoute.queryParams.subscribe(params => {
const userId = params['userId'];
console.log(userId);
});
}
}
A NOTE REGARDING UNSUBSCRIBING
@Reto and @codef0rmer had quite rightly pointed out that, as per the official docs, an unsubscribe()
inside the components onDestroy()
method is unnecessary in this instance. This has been removed from my code sample. (see blue alert box in this tutorial)
There is no command to do it (like you would do it with MySQL for instance). The number of Redis databases is fixed, and set in the configuration file. By default, you have 16 databases. Each database is identified by a number (not a name).
You can use the following command to know the number of databases:
CONFIG GET databases
1) "databases"
2) "16"
You can use the following command to list the databases for which some keys are defined:
INFO keyspace
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0
Please note that you are supposed to use the "redis-cli" client to run these commands, not telnet. If you want to use telnet, then you need to run these commands formatted using the Redis protocol.
For instance:
*2
$4
INFO
$8
keyspace
$79
# Keyspace
db0:keys=10,expires=0
db1:keys=1,expires=0
db3:keys=1,expires=0
You can find the description of the Redis protocol here: http://redis.io/topics/protocol
To move a file you could also use Jakarta Commons IOs FileUtils.moveFile
On error it throws an IOException
, so when no exception is thrown you know that that the file was moved.
I think this is an excellent article on explaining the differences and when you should use one over the other: http://tag1consulting.com/MySQL_Engines_MyISAM_vs_InnoDB
There is also Mappa - http://mappatool.com/.
It only supports polygons, but they are definitely the hardest parts :)
Here's one suggestion:
public interface Service<T,U> {
T executeService(U... args);
}
public class MyService implements Service<String, Integer> {
@Override
public String executeService(Integer... args) {
// do stuff
return null;
}
}
Because of type erasure any class will only be able to implement one of these. This eliminates the redundant method at least.
It's not an unreasonable interface that you're proposing but I'm not 100% sure of what value it adds either. You might just want to use the standard Callable
interface. It doesn't support arguments but that part of the interface has the least value (imho).
In SQL Server 2012, 2014:
USE mydb
GO
ALTER ROLE db_datareader ADD MEMBER MYUSER
GO
ALTER ROLE db_datawriter ADD MEMBER MYUSER
GO
In SQL Server 2008:
use mydb
go
exec sp_addrolemember db_datareader, MYUSER
go
exec sp_addrolemember db_datawriter, MYUSER
go
To also assign the ability to execute all Stored Procedures for a Database:
GRANT EXECUTE TO MYUSER;
To assign the ability to execute specific stored procedures:
GRANT EXECUTE ON dbo.sp_mystoredprocedure TO MYUSER;
If you are in a directory where only root have access to write in system. Then you can directly use wget www.example.com/wget-test
using a standard user account. So it will hit the url but because of having no write permission file won't be saved..
This method is working fine for me as i am using this method for a cronjob.
Thanks.
sthx
System.out.println(String.format("%-20s= %s" , "label", "content" ));
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
use this, it won't effect height:
<input type="text" style="border:1px solid #ff0000" />
The accepted answer by @cope360 is good, but I wanted something a little more like Oracle's DBA_IND_COLUMNS, ALL_IND_COLUMNS, and USER_IND_COLUMNS (e.g., reports the table/index schema and the position of the index in a multicolumn index), so I adapted the accepted answer into this:
with
ind_cols as (
select
n.nspname as schema_name,
t.relname as table_name,
i.relname as index_name,
a.attname as column_name,
1 + array_position(ix.indkey, a.attnum) as column_position
from
pg_catalog.pg_class t
join pg_catalog.pg_attribute a on t.oid = a.attrelid
join pg_catalog.pg_index ix on t.oid = ix.indrelid
join pg_catalog.pg_class i on a.attnum = any(ix.indkey)
and i.oid = ix.indexrelid
join pg_catalog.pg_namespace n on n.oid = t.relnamespace
where t.relkind = 'r'
order by
t.relname,
i.relname,
array_position(ix.indkey, a.attnum)
)
select *
from ind_cols
where schema_name = 'test'
and table_name = 'indextest'
order by schema_name, table_name
;
This gives an output like:
schema_name | table_name | index_name | column_name | column_position
-------------+------------+------------+-------------+-----------------
test | indextest | testind1 | singleindex | 1
test | indextest | testind2 | firstoftwo | 1
test | indextest | testind2 | secondoftwo | 2
(3 rows)
#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
echo "Usage: $0 DIRECTORY" >&2
exit 1
fi
Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.
More friendly error reporting:
#!/bin/sh
if [ "$#" -ne 1 ]; then
echo "Usage: $0 DIRECTORY" >&2
exit 1
fi
if ! [ -e "$1" ]; then
echo "$1 not found" >&2
exit 1
fi
if ! [ -d "$1" ]; then
echo "$1 not a directory" >&2
exit 1
fi
keep you Project(not app) Build.gradle dependncies classpath version code is new
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0-beta01'
classpath 'com.novoda:bintray-release:0.8.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
Not an expert here, but this is what I did and it worked
<html>
<style>
/*Style your div container, must specify height*/
.content {width:1000px; height:210px; margin:20px auto; font-size:16px;}
/*Style the p tag inside your div container with half the with of your container, and float left*/
.content p {width:490px; margin-right:10px; float:left;}
</style>
<body>
<!--Put your text inside a div with a class-->
<div class="content">
<h1>Title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus gravida laoreet lectus. Pellentesque ultrices consequat placerat. Etiam luctus euismod tempus. In sed eros dignissim tortor faucibus dapibus ut non neque. Ut ante odio, luctus eu pharetra vitae, consequat sit amet nunc. Aenean dolor felis, fringilla sagittis hendrerit vel, egestas eget eros. Mauris suscipit bibendum massa, nec mattis lorem dignissim sit amet. </p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer eget dolor neque. Phasellus tellus odio, egestas ut blandit sed, egestas sit amet velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;</p>
</div>
</body>
</html>
Once the text inside the <p>
tags has reached the height of the container div, the other text will flow to the right of the container.
Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.
Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid())
(_getpid()
on Windows), but that still won't be random.
The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random
(Linux) or CryptGenRandom()
(Windows), or from a service like random.org
.
Remove the spaces before the autoplay=1:
src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&;enablejsapi=1"
var popupWindow=null;
function popup()
{
popupWindow = window.open('child_page.html','name','width=200,height=200');
}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
and then declare these functions in the body tag of parent window
<body onFocus="parent_disable();" onclick="parent_disable();">
As you requested here is the complete html code of the parent window
<html>
<head>
<script type="text/javascript">
var popupWindow=null;
function child_open()
{
popupWindow =window.open('new.jsp',"_blank","directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");
}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
</script>
</head>
<body onFocus="parent_disable();" onclick="parent_disable();">
<a href="javascript:child_open()">Click me</a>
</body>
</html>
Content of new.jsp below
<html>
<body>
I am child
</body>
</html>
I use it like this.
xcopy "$(TargetDir)$(TargetName).dll" "$(SolutionDir)Lib\TIRM\x86\" /F /Y
xcopy "$(TargetDir)$(TargetName).lib" "$(SolutionDir)Lib\TIRM\x86\" /F /Y
/F : Copy source is File
/Y : Overwrite and don't ask me
Note the use of this. $(TargetDir) has already '\' "D:\MyProject\bin\" = $(TargetDir)
You can find macro in Command editor
It is difficult to choose which one is better; lock or ReaderWriterLockSlim. You need real world statistics of read and write numbers and ratios etc.
But if you believe using "lock" is the correct way. Then here is a different solution for different needs. I also include the Allan Xu's solution in the code. Because both can be needed for different needs.
Here are the requirements, driving me to this solution:
Code:
using System;
using System.Runtime.Caching;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace CachePoc
{
class Program
{
static object everoneUseThisLockObject4CacheXYZ = new object();
const string CacheXYZ = "CacheXYZ";
static object everoneUseThisLockObject4CacheABC = new object();
const string CacheABC = "CacheABC";
static void Main(string[] args)
{
//Allan Xu's usage
string xyzData = MemoryCacheHelper.GetCachedDataOrAdd<string>(CacheXYZ, everoneUseThisLockObject4CacheXYZ, 20, SomeHeavyAndExpensiveXYZCalculation);
string abcData = MemoryCacheHelper.GetCachedDataOrAdd<string>(CacheABC, everoneUseThisLockObject4CacheXYZ, 20, SomeHeavyAndExpensiveXYZCalculation);
//My usage
string sessionId = System.Web.HttpContext.Current.Session["CurrentUser.SessionId"].ToString();
string yvz = MemoryCacheHelper.GetCachedData<string>(sessionId);
if (string.IsNullOrWhiteSpace(yvz))
{
object locker = MemoryCacheHelper.GetLocker(sessionId);
lock (locker)
{
yvz = MemoryCacheHelper.GetCachedData<string>(sessionId);
if (string.IsNullOrWhiteSpace(yvz))
{
DatabaseRepositoryWithHeavyConstructorOverHead dbRepo = new DatabaseRepositoryWithHeavyConstructorOverHead();
yvz = dbRepo.GetDataExpensiveDataForSession(sessionId);
MemoryCacheHelper.AddDataToCache(sessionId, yvz, 5);
}
}
}
}
private static string SomeHeavyAndExpensiveXYZCalculation() { return "Expensive"; }
private static string SomeHeavyAndExpensiveABCCalculation() { return "Expensive"; }
public static class MemoryCacheHelper
{
//Allan Xu's solution
public static T GetCachedDataOrAdd<T>(string cacheKey, object cacheLock, int minutesToExpire, Func<T> GetData) where T : class
{
//Returns null if the string does not exist, prevents a race condition where the cache invalidates between the contains check and the retreival.
T cachedData = MemoryCache.Default.Get(cacheKey, null) as T;
if (cachedData != null)
return cachedData;
lock (cacheLock)
{
//Check to see if anyone wrote to the cache while we where waiting our turn to write the new value.
cachedData = MemoryCache.Default.Get(cacheKey, null) as T;
if (cachedData != null)
return cachedData;
cachedData = GetData();
MemoryCache.Default.Set(cacheKey, cachedData, DateTime.Now.AddMinutes(minutesToExpire));
return cachedData;
}
}
#region "My Solution"
readonly static ConcurrentDictionary<string, object> Lockers = new ConcurrentDictionary<string, object>();
public static object GetLocker(string cacheKey)
{
CleanupLockers();
return Lockers.GetOrAdd(cacheKey, item => (cacheKey, new object()));
}
public static T GetCachedData<T>(string cacheKey) where T : class
{
CleanupLockers();
T cachedData = MemoryCache.Default.Get(cacheKey) as T;
return cachedData;
}
public static void AddDataToCache(string cacheKey, object value, int cacheTimePolicyMinutes)
{
CleanupLockers();
MemoryCache.Default.Add(cacheKey, value, DateTimeOffset.Now.AddMinutes(cacheTimePolicyMinutes));
}
static DateTimeOffset lastCleanUpTime = DateTimeOffset.MinValue;
static void CleanupLockers()
{
if (DateTimeOffset.Now.Subtract(lastCleanUpTime).TotalMinutes > 1)
{
lock (Lockers)//maybe a better locker is needed?
{
try//bypass exceptions
{
List<string> lockersToRemove = new List<string>();
foreach (var locker in Lockers)
{
if (!MemoryCache.Default.Contains(locker.Key))
lockersToRemove.Add(locker.Key);
}
object dummy;
foreach (string lockerKey in lockersToRemove)
Lockers.TryRemove(lockerKey, out dummy);
lastCleanUpTime = DateTimeOffset.Now;
}
catch (Exception)
{ }
}
}
}
#endregion
}
}
class DatabaseRepositoryWithHeavyConstructorOverHead
{
internal string GetDataExpensiveDataForSession(string sessionId)
{
return "Expensive data from database";
}
}
}
Too late but I want to share the way that I resolve it.
Having model
file which has two named export:
export { Schema, Model };
and having controller
file which has the default export:
export default Controller;
I exposed in the index
file in this way:
import { Schema, Model } from './model';
import Controller from './controller';
export { Schema, Model, Controller };
and assuming that I want import all of them:
import { Schema, Model, Controller } from '../../path/';
This answer didn't work for me, but I found the answer myself. No one, however, has posted my question. I'm too lazy to ask it and then answer it, so will just put it here.
This is for the following query:
data = Leaderboard.objects.filter(id=custom_user.id).values(
'value1',
'value2',
'value3')
In template:
{% for dictionary in data %}
{% for key, value in dictionary.items %}
<p>{{ key }} : {{ value }}</p>
{% endfor %}
{% endfor %}
Try an OUTER APPLY
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
OUTER APPLY
(
SELECT TOP 1 *
FROM tbl_Media M
WHERE M.Content_Id = C.Content_Id
) m
ORDER BY
C.Content_DatePublished ASC
Alternatively, you could GROUP BY
the results
SELECT
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id
GROUP BY
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
ORDER BY
C.Content_DatePublished ASC
The OUTER APPLY
selects a single row (or none) that matches each row from the left table.
The GROUP BY
performs the entire join, but then collapses the final result rows on the provided columns.
or just study /etc/groups (ok this does probably not work if it uses pam with ldap)
A .NET Core Class Library is built upon the .NET Standard. If you want to implement a library that is portable to the .NET Framework, .NET Core and Xamarin, choose a .NET Standard Library
.NET Core will ultimately implement .NET Standard 2 (as will Xamarin and .NET Framework)
.NET Core, Xamarin and .NET Framework can, therefore, be identified as flavours of .NET Standard
To future-proof your applications for code sharing and reuse, you would rather implement .NET Standard libraries.
Microsoft also recommends that you use .NET Standard instead of Portable Class Libraries.
To quote MSDN as an authoritative source, .NET Standard is intended to be One Library to Rule Them All. As pictures are worth a thousand words, the following will make things very clear:
1. Your current application scenario (fragmented)
Like most of us, you are probably in the situation below: (.NET Framework, Xamarin and now .NET Core flavoured applications)
2. What the .NET Standard Library will enable for you (cross-framework compatibility)
Implementing a .NET Standard Library allows code sharing across all these different flavours:
For the impatient:
For a table to help understand what the highest version of .NET Standard that you can target, based on which .NET platforms you intend to run on, head over here.
Sources: MSDN: Introducing .NET Standard
Goto your app info.plist
1) Set View controller-based status bar appearance
to NO
2) Set Status bar style
to UIStatusBarStyleLightContent
Then Goto your app delegate and paste the following code where you set your Windows's RootViewController.
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
view.backgroundColor=[UIColor blackColor];
[self.window.rootViewController.view addSubview:view];
}
Hope it helps.
For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group
from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.
# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
x .groups
<dbl> <fct>
1 0.891 1
2 -1.13 1
3 -0.500 1
4 -1.12 1
5 -0.0187 1
6 0.420 2
7 -0.449 2
8 0.365 2
9 0.526 2
10 0.466 2
# … with 17 more rows
There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z")
the grouping factor would be c(1,1,2,3,3)
.
You can set border
properties on a tr
element, but according to the CSS 2.1 specification, such properties have no effect in the separated borders model, which tends to be the default in browsers. Ref.: 17.6.1 The separated borders model. (The initial value of border-collapse
is separate
according to CSS 2.1, and some browsers also set it as default value for table
. The net effect anyway is that you get separated border on almost all browsers unless you explicitly specifi collapse
.)
Thus, you need to use collapsing borders. Example:
<style>
table { border-collapse: collapse; }
tr:nth-child(3) { border: solid thin; }
</style>
If you use numpy there's a neat way to do it:
items = np.array(["a","b","c","d"])
indices = np.arange(items.shape[0])
np.random.shuffle(indices)
print(indices)
print(items[indices])
This code returns:
[1 3 2 0]
['b' 'd' 'c' 'a']
Even though this solution might seem obvious, I just wanted to post it here so the next guy will google it faster.
If you still want to have the model as a parameter in the method, you can create a DelegatingHandler
to buffer the content.
internal sealed class BufferizingHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
await request.Content.LoadIntoBufferAsync();
var result = await base.SendAsync(request, cancellationToken);
return result;
}
}
And add it to the global message handlers:
configuration.MessageHandlers.Add(new BufferizingHandler());
This solution is based on the answer by Darrel Miller.
This way all the requests will be buffered.
for (Iterator<String> itr = someList.iterator(); itr.hasNext(); ) {
String item = itr.next();
System.out.println(item);
}
This is universal solution for conditions wiht more same results.
<?php
$your_name1_finded="somethnig searched"; //$your_name1_finded must be finded in previous select
$result = db_query("SELECT your_name1 FROM your_table WHERE your_name=your_condition ORDER BY your_name1, your_name2"); //Get all our ids
$i=0;
while($row = db_fetch_assoc($result)) { //Loop through our rows
$i++;
$current_row[$i]=$row['your_name1'];// field with results
if($row['your_name1'] == $your_name1_finded) {//If we haven't hit our current row yet
$yid=$i;
}
}
//buttons
if ($current_row[$yid-1]) $out_button.= "<a class='button' href='/$your_url/".$current_row[$yid-1]."'>BUTTON_PREVIOUS</a>";
if ($current_row[$yid+1]) $out_button.= "<a class='button' href='/$your_url/".$current_row[$yid+1]."'>BUTTON_NEXT</a>";
echo $out_button;//display buttons
?>
You might look into jwht-scrapper!
This is a complete scrapping framework that has all the features a developper could expect from a web scrapper:
It works with (jwht-htmltopojo)[https://github.com/whimtrip/jwht-htmltopojo) lib which itsef uses Jsoup mentionned by several other people here.
Together they will help you built awesome scrappers mapping directly HTML to POJOs and bypassing any classical scrapping problems in only a matter of minutes!
Hope this might help some people here!
Disclaimer, I am the one who developed it, feel free to let me know your remarks!
The other answers here clearly explained what does it mean.I like to explain its use.
You can select an element in the elements
tab and switch to console
tab in chrome. Just type $0 or $1
or whatever number and press enter and the element will be displayed in the console for your use.
You could try
httpResponseMessage.Content.Headers.Add("Content-Type", "application/octet-stream");
What do you even want the result to be? 888888? If so, just remove the spaces with str_replace
, then convert.
The logic in the "one-liner" works fine. From personal experience, what has helped me is to assign the statements to variables (in their "True" form) and then use logical operators for the result:
A = year % 4 == 0
B = year % 100 == 0
C = year % 400 == 0
I used '==' in the B statement instead of "!=" and applied 'not' logical operator in the calculation:
leap = A and (not B or C)
This comes in handy with a larger set of conditions, and to simplify the boolean operation where applicable before writing a whole bunch of if statements.
CD
returns an EXIT_FAILURE
when the specified directory does not exist. And you got conditional processing symbols, so you could do like the below for this.
SET cd_backup=%cd%
(CD "%~1" && CD %cd_backup%) || GOTO Error
:Error
CD %cd_backup%
I'd rather implement TaskExecuteAsync interface function for IHttpActionResult. Something like:
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
switch ((Int32)_respContent.Code)
{
case 1:
case 6:
case 7:
response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
break;
case 2:
case 3:
case 4:
response = _request.CreateResponse(HttpStatusCode.BadRequest, _respContent);
break;
}
return Task.FromResult(response);
}
, where _request is the HttpRequest and _respContent is the payload.
I made a simple (stupid or not) bash script, that extracts the longs from the adb shell, converts them to timestamps and shows it in red.
echo "Please set a search filter"
read search
adb shell dumpsys alarm | grep $search | (while read i; do echo $i; _DT=$(echo $i | grep -Eo 'when\s+([0-9]{10})' | tr -d '[[:alpha:][:space:]]'); if [ $_DT ]; then echo -e "\e[31m$(date -d @$_DT)\e[0m"; fi; done;)
try it ;)
Do somthing like this by adding these line to your view files;
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/path/to/your/javascript/file'); Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/path/to/css/file');
Package: System.IO.FileSystem
System.IO.File.ReadAllText("MyTextFile.txt"); ?
Why don't you create a function or class for this navigation and put there active page as a parameter? This way you'd call it as, for example:
$navigation = new Navigation( 1 );
or
$navigation = navigation( 1 );
sudo yum install nodejs npm --enablerepo=epel
works for Amazon Linux AMI
.
curl --silent --location https://rpm.nodesource.com/setup_6.x | bash -
yum -y install nodejs
works for RedHat.
Update for PHP 7 (thanks shock_gone_wild)
PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:
$var = $var ?? "default";
Before PHP 7
No, there is no special operator or special syntax for this. However, you could use the ternary operator:
$var = isset($var) ? $var : "default";
Or like this:
isset($var) ?: $var = 'default';
You can do it like this
new DirectoryInfo(path).GetFiles().Where(Current => Regex.IsMatch(Current.Extension, "\\.(aspx|ascx)", RegexOptions.IgnoreCase)
If you are using Swift, add the following code to viewDidLoad of the controller that manages the tableview:
override func viewDidLoad() {
super.viewDidLoad()
//...
// Remove extra separators
tableView.tableFooterView = UIView()
}
A good read on the matter.
Excerpt:
These are all valid email addresses!
"Abc\@def"@example.com
"Fred Bloggs"@example.com
"Joe\\Blow"@example.com
"Abc@def"@example.com
customer/[email protected]
\[email protected]
!def!xyz%[email protected]
[email protected]
If you are having a problem with the font working I have also had this in the past and the issue I found was down to the font-family: name. This had to match what font name was actually given.
The easiest way I found to find this out was to install the font and see what display name is given.
For example, I was using Gill Sans on one project, but the actual font was called Gill Sans MT. Spacing and capitlisation was also important to get right.
Hope that helps.
you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image
if not installed ARM EABI v7a System Image, you should install all.