I was dealing with this running Artifactory version 5.8.4. The "Set Me Up" function would generate settings.xml as follows:
<servers>
<server>
<username>${security.getCurrentUsername()}</username>
<password>${security.getEscapedEncryptedPassword()!"AP56eMPz8L12T5u4J6rWdqWqyhQ"}</password>
<id>central</id>
</server>
<server>
<username>${security.getCurrentUsername()}</username>
<password>${security.getEscapedEncryptedPassword()!"AP56eMPz8L12T5u4J6rWdqWqyhQ"}</password>
<id>snapshots</id>
</server>
</servers>
After using the mvn deploy -e -X switch, I noticed the credentials were not accurate. I removed the ${security.getCurrentUsername()} and replaced it with my username and removed ${security.getEscapedEncryptedPassword()!""} and just put my encrypted password which worked for me:
<servers>
<server>
<username>username</username>
<password>AP56eMPz8L12T5u4J6rWdqWqyhQ</password>
<id>central</id>
</server>
<server>
<username>username</username>
<password>AP56eMPz8L12T5u4J6rWdqWqyhQ</password>
<id>snapshots</id>
</server>
</servers>
Hope this helps!
I don't know if this is the answer or not but it might lead you in the right direction...
The command install:install
is actually a goal on the maven-install-plugin. This is different than the install
maven lifecycle phase.
Maven lifecycle phases are steps in a build which certain plugins can bind themselves to. Many different goals from different plugins may execute when you invoke a single lifecycle phase.
What this boils down to is the command...
mvn clean install
is different from...
mvn clean install:install
The former will run all goals in every cycle leading up to and including the install (like compile, package, test, etc.). The latter will not even compile or package your code, it will just run that one goal. This kinda makes sense, looking at the exception; it talks about:
StarTeamCollisionUtil: The packaging for this project did not assign a file to the build artifact
Try the former and your error might just go away!
There's no need for a parent POM.
You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.
To do it on the build server, just pass to the mvn
command:
-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases
See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.
It's also possible to set this in your settings.xml
.
Just create a profile there which is enabled and contains the property.
Example settings.xml:
<settings>
[...]
<profiles>
<profile>
<id>nexus</id>
<properties>
<altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
<altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
</settings>
Make sure that credentials for "snapshots" and "releases" are in the <servers>
section of your settings.xml
The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message
Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter
To fix this, you can enforce a newer version of the plug-in:
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8</version>
</plugin>
</plugins>
</pluginManagement>
</build>
A SELECT
in SQL Server will place a shared lock on a table row - and a second SELECT
would also require a shared lock, and those are compatible with one another.
So no - one SELECT
cannot block another SELECT
.
What the WITH (NOLOCK)
query hint is used for is to be able to read data that's in the process of being inserted (by another connection) and that hasn't been committed yet.
Without that query hint, a SELECT
might be blocked reading a table by an ongoing INSERT
(or UPDATE
) statement that places an exclusive lock on rows (or possibly a whole table), until that operation's transaction has been committed (or rolled back).
Problem of the WITH (NOLOCK)
hint is: you might be reading data rows that aren't going to be inserted at all, in the end (if the INSERT
transaction is rolled back) - so your e.g. report might show data that's never really been committed to the database.
There's another query hint that might be useful - WITH (READPAST)
. This instructs the SELECT
command to just skip any rows that it attempts to read and that are locked exclusively. The SELECT
will not block, and it will not read any "dirty" un-committed data - but it might skip some rows, e.g. not show all your rows in the table.
If you want to print in the tabular form with, then you can use this:
echo "<tr> <td><h3> ".$cat['id']."</h3></td><td><h3> ".$cat['title']."<h3></</td><td> <h3>".$cat['desc']."</h3></td><td><h3> ".$cat['process']."%"."<a href='taskUpdate.php' >Update</a>"."</h3></td></tr>" ;
You need to either provide the absolute path to data.csv, or run your script in the same directory as data.csv.
The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash
:
git stash
git checkout other-branch
git stash pop
The first stash
hides away your changes (basically making a temporary commit), and the subsequent stash pop
re-applies them. This lets Git use its merge capabilities.
If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.
On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:
# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset
# Add the things you *do* want to commit here
git add -p # or maybe git add -i
git commit
# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop
# Add the changes meant for this branch
git add -p
git commit
# And throw away the rest
git reset --hard
Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:
git add -p
git commit
git stash
git checkout other-branch
git stash pop
And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1)
to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)
Yes, it's the right way. You can use images in the Resource file using a path:
<StackPanel Orientation="Horizontal">
<CheckBox Content="{Binding Nname}" IsChecked="{Binding IsChecked}"/>
<Image Source="E:\SWorking\SharePointSecurityApps\SharePointSecurityApps\SharePointSecurityApps.WPF\Images\sitepermission.png"/>
<TextBlock Text="{Binding Path=Title}"></TextBlock>
</StackPanel>
You can use .replace
. For example:
>>> df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
>>> di = {1: "A", 2: "B"}
>>> df
col1 col2
0 w a
1 1 2
2 2 NaN
>>> df.replace({"col1": di})
col1 col2
0 w a
1 A 2
2 B NaN
or directly on the Series
, i.e. df["col1"].replace(di, inplace=True)
.
SimpleDateFormat has a constructor which takes the locale, have you tried that?
http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Something like
new SimpleDateFormat("your-pattern-here", Locale.getDefault());
Try using a format file since your data file only has 4 columns. Otherwise, try OPENROWSET
or use a staging table.
myTestFormatFiles.Fmt
may look like:
9.0 4 1 SQLINT 0 3 "," 1 StudentNo "" 2 SQLCHAR 0 100 "," 2 FirstName SQL_Latin1_General_CP1_CI_AS 3 SQLCHAR 0 100 "," 3 LastName SQL_Latin1_General_CP1_CI_AS 4 SQLINT 0 4 "\r\n" 4 Year "
(source: microsoft.com)
This tutorial on skipping a column with BULK INSERT
may also help.
Your statement then would look like:
USE xta9354
GO
BULK INSERT xta9354.dbo.Students
FROM 'd:\userdata\xta9_Students.txt'
WITH (FORMATFILE = 'C:\myTestFormatFiles.Fmt')
String filepath="/tmp/employee.csv";
FileWriter sw = new FileWriter(new File(filepath));
CSVWriter writer = new CSVWriter(sw);
writer.writeAll(allRows);
String[] header= new String[]{"ErrorMessage"};
writer.writeNext(header);
List<String[]> errorData = new ArrayList<String[]>();
for(int i=0;i<1;i++){
String[] data = new String[]{"ErrorMessage"+i};
errorData.add(data);
}
writer.writeAll(errorData);
writer.close();
This is because of the combination of two things:
tsconfig
not having any files
section. From http://www.typescriptlang.org/docs/handbook/tsconfig-json.html
If no "files" property is present in a tsconfig.json, the compiler defaults to including all files in the containing directory and subdirectories. When a "files" property is specified, only those files are included.
Including typescript
as an npm dependency : node_modules/typescript/
This means that all of typescript
gets included .... there is an implicitly included lib.d.ts
in your project anyways (http://basarat.gitbook.io/typescript/content/docs/types/lib.d.ts.html) and its conflicting with the one that ships with the NPM version of typescript.
Either list files
or include
explicitly https://basarat.gitbook.io/typescript/docs/project/files.html
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
Try adding the following to your eclipse.ini file:
-vm
C:\Program Files\Java\jdk1.7.0_01\bin\java.exe
You might also have to change the Dosgi.requiredJavaVersion to 1.7 in the same file.
Just make the property !important
in your css file so that background color doesnot change on mouse over.This worked for me.
Example:
.fbColor {
background-color: #3b5998 !important;
color: white;
}
This was asked some time ago now, but based on the answer that @nacho_zona3 provided, and previous experience with fragments, the issue is that the views have not been created by the time you are trying to find them with the findViewById()
method in onCreate()
to fix this, move the following code:
// 1. get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);
// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// this is data fro recycler view
ItemData itemsData[] = { new ItemData("Indigo",R.drawable.circle),
new ItemData("Red",R.drawable.color_ic_launcher),
new ItemData("Blue",R.drawable.indigo),
new ItemData("Green",R.drawable.circle),
new ItemData("Amber",R.drawable.color_ic_launcher),
new ItemData("Deep Orange",R.drawable.indigo)};
// 3. create an adapter
MyAdapter mAdapter = new MyAdapter(itemsData);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
// 5. set item animator to DefaultAnimator
recyclerView.setItemAnimator(new DefaultItemAnimator());
to your fragment's onCreateView()
call. A small amount of refactoring is required because all variables and methods called from this method have to be static. The final code should look like:
public class ColorsFragment extends Fragment {
public ColorsFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_colors, container, false);
// 1. get a reference to recyclerView
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.list);
// 2. set layoutManger
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
// this is data fro recycler view
ItemData itemsData[] = {
new ItemData("Indigo", R.drawable.circle),
new ItemData("Red", R.drawable.color_ic_launcher),
new ItemData("Blue", R.drawable.indigo),
new ItemData("Green", R.drawable.circle),
new ItemData("Amber", R.drawable.color_ic_launcher),
new ItemData("Deep Orange", R.drawable.indigo)
};
// 3. create an adapter
MyAdapter mAdapter = new MyAdapter(itemsData);
// 4. set adapter
recyclerView.setAdapter(mAdapter);
// 5. set item animator to DefaultAnimator
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
}
So the main thing here is that anywhere you call findViewById()
you will need to use rootView.findViewById()
blog_development doesn't exist
You can see this in sql by the 0 rows affected
message
create it in mysql with
mysql> create database blog_development
However as you are using rails you should get used to using
$ rake db:create
to do the same task. It will use your database.yml file settings, which should include something like:
development:
adapter: mysql2
database: blog_development
pool: 5
Also become familiar with:
$ rake db:migrate # Run the database migration
$ rake db:seed # Run thew seeds file create statements
$ rake db:drop # Drop the database
I recently began replacing static keywords with anonymous namespaces in my code but immediately ran into a problem where the variables in the namespace were no longer available for inspection in my debugger. I was using VC60, so I don't know if that is a non-issue with other debuggers. My workaround was to define a 'module' namespace, where I gave it the name of my cpp file.
For example, in my XmlUtil.cpp file, I define a namespace XmlUtil_I { ... }
for all of my module variables and functions. That way I can apply the XmlUtil_I::
qualification in the debugger to access the variables. In this case, the _I
distinguishes it from a public namespace such as XmlUtil
that I may want to use elsewhere.
I suppose a potential disadvantage of this approach compared to a truly anonymous one is that someone could violate the desired static scope by using the namespace qualifier in other modules. I don't know if that is a major concern though.
Sounds like you should just use PostGIS, SpatialLite, SQLServer2008, or Oracle Spatial. They can all answer this question for you with spatial SQL.
You can take advantage of fschange. It’s a Linux filesystem change notification. The source code is downloadable from the above link, you can compile it yourself. fschange
can be used to keep track of file changes by reading data from a proc file (/proc/fschange). When data is written to a file, fschange reports the exact interval that has been modified instead of just saying that the file has been changed.
If you are looking for the more advanced solution, I would suggest checking Resilio Connect.
It is cross-platform, provides extended options for use and monitoring. Since it’s BitTorrent-based, it is faster than any other existing sync tool. It was written on their behalf.
You can use this bootstrap datepicker
$("your-selector").datepicker({
format: "yyyy",
viewMode: "years",
minViewMode: "years"
});
"your-selector" you can use id(#your-selector) OR class(.your-selector).
In my case, I found that a computed column had been added to the "included columns" of an index. Later, when an item in that table was updated, the merge
statement failed with that message. The merge was in a trigger, so this was hard to track down! Removing the computed column from the index fixed it.
To be on the safe side use
os.getenv('FOO') or 'bar'
A corner case with the above answers is when the environment variable is set but is empty
For this special case you get
print(os.getenv('FOO', 'bar'))
# prints new line - though you expected `bar`
or
if "FOO" in os.environ:
print("FOO is here")
# prints FOO is here - however its not
To avoid this just use or
os.getenv('FOO') or 'bar'
Then you get
print(os.getenv('FOO') or 'bar')
# bar
When do we have empty environment variables?
You forgot to set the value in the .env
file
# .env
FOO=
or exported as
$ export FOO=
or forgot to set it in settings.py
# settings.py
os.environ['FOO'] = ''
Update: if in doubt, check out these one-liners
>>> import os; os.environ['FOO'] = ''; print(os.getenv('FOO', 'bar'))
$ FOO= python -c "import os; print(os.getenv('FOO', 'bar'))"
When using Set-Content
instead of Out-File
, you can specify the encoding Byte
, which can be used to write a byte array to a file. This in combination with a custom UTF8 encoding which does not emit the BOM gives the desired result:
# This variable can be reused
$utf8 = New-Object System.Text.UTF8Encoding $false
$MyFile = Get-Content $MyPath -Raw
Set-Content -Value $utf8.GetBytes($MyFile) -Encoding Byte -Path $MyPath
The difference to using [IO.File]::WriteAllLines()
or similar is that it should work fine with any type of item and path, not only actual file paths.
When I tried Continue For
it Failed, I got a compiler error. While doing this, I discovered 'Resume':
For Each I As Item In Items
If I = x Then
'Move to next item
Resume Next
End If
'Do something
Next
Note: I am using VBA here.
In my case I had a float value expected where xml had a null value so be sure to search for float and int data type in your xsd map
On your XAMPP control panel, next to apache, select the "Config" option and select the first file (httpd.conf):
there, look for the "listen" line (you may use the find tool in the notepad) and there must be a line stating "Listen 80". Note: there are other lines with "listen" on them but they should be commented (start with a #), the one you need to change is the one saying exactly "listen 80". Now change it to "Listen 1337".
Start apache now.
If the error subsists, it's because there's another port that's already in use. So, select the config option again (next to apache in your xampp control panel) and select the second option this time (httpd-ssl.conf):
there, look for the line "Listen 443" and change it to "Listen 7331".
Start apache, it should be working now.
If you want to select a variable range containing all headers cells:
Dim sht as WorkSheet
Set sht = This Workbook.Sheets("Data")
'Range(Cells(1,1),Cells(1,Columns.Count).End(xlToLeft)).Select '<<< NOT ROBUST
sht.Range(sht.Cells(1,1),sht.Cells(1,Columns.Count).End(xlToLeft)).Select
...as long as there's no other content on that row.
EDIT: updated to stress that when using Range(Cells(...), Cells(...))
it's good practice to qualify both Range
and Cells
with a worksheet reference.
The above problem can be solved by adding the following dependencies in your project, as i was facing the same problem.For more detail answer to this solution please refer link SEVERE:MessageBodyWriter not found for media type=application/xml type=class java.util.HashMap
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.25</version>
</dependency>
try this one http://code.google.com/p/geckofx/ hope it ain't dupe or this one i think is better http://webkitdotnet.sourceforge.net/
The code is okay but you are in the wrong directory. You must run these commands inside your rails project-directory.
The normal way to get there from scratch is:
$ rails new PROJECT_NAME
$ cd PROJECT_NAME
$ rails generate model ad \
name:string \
description:text \
price:decimal \
seller_id:integer \
email:string img_url:string
I used the following:
import matplotlib.pyplot as plt
p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05), ncol=2, fancybox=True, shadow=True)
plt.savefig('data.png')
plt.show()
f.close()
plt.close()
I found very important to use plt.show after saving the figure, otherwise it won't work.figure exported in png
I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was
<?xmlversion="1.0"encoding="utf-8"?>
which was causing the error. When I removed that line, so that the stylesheet started with the line
<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:
<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8" />
<xsl:template match="/">
<xsl:text>From,To~</xsl:text>
<xsl:text>
</xsl:text>
<xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
<xsl:value-of select="@DTS:From"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="@DTS:To"/>
<xsl:text>~</xsl:text>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.
This is not intended to be "the good answer", as this question ask explicitly for ObjectiveC. As Apple introduced Swift at the WWDC14, I'd like to share the different ways to use block (or closures) in Swift.
You have many ways offered to pass a block equivalent to function in Swift.
I found three.
To understand this I suggest you to test in playground this little piece of code.
func test(function:String -> String) -> String
{
return function("test")
}
func funcStyle(s:String) -> String
{
return "FUNC__" + s + "__FUNC"
}
let resultFunc = test(funcStyle)
let blockStyle:(String) -> String = {s in return "BLOCK__" + s + "__BLOCK"}
let resultBlock = test(blockStyle)
let resultAnon = test({(s:String) -> String in return "ANON_" + s + "__ANON" })
println(resultFunc)
println(resultBlock)
println(resultAnon)
As Swift is optimized for asynchronous development, Apple worked more on closures. The first is that function signature can be inferred so you don't have to rewrite it.
let resultShortAnon = test({return "ANON_" + $0 + "__ANON" })
let resultShortAnon2 = test({myParam in return "ANON_" + myParam + "__ANON" })
This special case works only if the block is the last argument, it's called trailing closure
Here is an example (merged with inferred signature to show Swift power)
let resultTrailingClosure = test { return "TRAILCLOS_" + $0 + "__TRAILCLOS" }
Finally:
Using all this power what I'd do is mixing trailing closure and type inference (with naming for readability)
PFFacebookUtils.logInWithPermissions(permissions) {
user, error in
if (!user) {
println("Uh oh. The user cancelled the Facebook login.")
} else if (user.isNew) {
println("User signed up and logged in through Facebook!")
} else {
println("User logged in through Facebook!")
}
}
If you need to retrieve more columns other than columns which are in group by then you can consider below query. Check it once whether it is performing well or not.
SELECT
a.[CUSTOMER ID],
a.[NAME],
(select SUM(b.[AMOUNT]) from INV_DATA b
where b.[CUSTOMER ID] = a.[CUSTOMER ID]
GROUP BY b.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA a
To run the command without a shell, pass the command as a list and implement the redirection in Python using [subprocess]
:
#!/usr/bin/env python
import subprocess
with open('test.nt', 'wb', 0) as file:
subprocess.check_call("cwm --rdf test.rdf --ntriples".split(),
stdout=file)
Note: no > test.nt
at the end. stdout=file
implements the redirection.
To run the command using the shell in Python, pass the command as a string and enable shell=True
:
#!/usr/bin/env python
import subprocess
subprocess.check_call("cwm --rdf test.rdf --ntriples > test.nt",
shell=True)
Here's the shell is responsible for the output redirection (> test.nt
is in the command).
To run a bash command that uses bashisms, specify the bash executable explicitly e.g., to emulate bash process substitution:
#!/usr/bin/env python
import subprocess
subprocess.check_call('program <(command) <(another-command)',
shell=True, executable='/bin/bash')
select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
from table1
where IsCurrent = 1
Coming in a bit late here but Android Studio has a very handy icon asset wizard. Its very self explanatory but has a few handy effects and its built right in:
Simply add the bootstrap "row-fluid" class to the textarea. It will stretch to 100% width;
Update: For bootstrap 3.x use "col-xs-12" class for textarea;
Update II: Also if you want to extend the container to full width use: container-fluid class.
in your css use white-space:nowrap;
In the server, do something like this:
Suppose
String data = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...=='
Then:
String base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
Then you can do whatever you like with the bytes like:
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
The last-child
selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.
The other part of the compound selector (which is attached before the :last-child
) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.
.parent :last-child{ /* this will select all elements which are last child of .parent */_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/_x000D_
background: crimson;_x000D_
}_x000D_
_x000D_
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/_x000D_
color: beige;_x000D_
}
_x000D_
<div class='parent'>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child-2'>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<div class='child'>Child</div>_x000D_
<p>Child w/o class</p>_x000D_
</div>
_x000D_
To answer your question, the below would style the last child li
element with background color as red.
li:last-child{
background-color: red;
}
But the following selector would not work for your markup because the last-child
does not have the class='complete'
even though it is an li
.
li.complete:last-child{
background-color: green;
}
It would have worked if (and only if) the last li
in your markup also had class='complete'
.
To address your query in the comments:
@Harry I find it rather odd that: .complete:last-of-type does not work, yet .complete:first-of-type does work, regardless of it's position it's parents element. Thanks for your help.
The selector .complete:first-of-type
works in the fiddle because it (that is, the element with class='complete'
) is still the first element of type li
within the parent. Try to add <li>0</li>
as the first element under the ul
and you will find that first-of-type
also flops. This is because the first-of-type
and last-of-type
selectors select the first/last element of each type under the parent.
Refer to the answer posted by BoltClock, in this thread for more details about how the selector works. That is as comprehensive as it gets :)
What about:
datetime.now().strftime('%M:%S.%f')[:-4]
I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.
EDIT
If the %f
modifier doesn't work for you, you can try something like:
now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]
Again, I'm assuming you just want to truncate the precision.
There are three formats with a reasonable level of support: H.264 (MPEG-4 AVC), OGG Theora (VP3) and WebM (VP8). See the wiki linked by Sam for which browsers support which; you will typically need at least one of those plus Flash fallback.
Whilst most browsers won't touch AVI, there are some browser builds that expose all the multimedia capabilities of the underlying OS to <video>
. These browser will indeed be able to play AVI, as long as they have matching codecs installed (AVI can contain about a million different video and audio formats). In particular Safari on OS X with QuickTime, or Konqi with GStreamer.
Personally I think this is an absolutely disastrous idea, as it exposes a very large codec codebase to the net, a codebase that was mostly not written to be resistant to network attacks. One of the worst drawbacks of media player plugins was the huge number of security holes they made available to every web page exploit. Let's not make this mistake again.
Using API version 2, which is deprecated, the URL for uploads (of channel UCqAEtEr0A0Eo2IVcuWBfB9g) is:
https://gdata.youtube.com/feeds/users/UCqAEtEr0A0Eo2IVcuWBfB9g/uploads
There is an API version 3.
Use the backslash before db on the header and you can use it then typically as you wrote it before.
Here is the example:
Use \DB;
Then inside your controller class you can use as you did before, like that ie :
$item = DB::table('items')->get();
To answer the second part of your question - there are no pointers in PHP.
When working with objects, you generally pass by reference rather than by value - so in some ways this operates like a pointer, but is generally completely transparent.
This does depend on the version of PHP you are using.
Suppose ListView object is lv, do the following-
lv.setClickable(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = lv.getItemAtPosition(position);
/* write you handling code like...
String st = "sdcard/";
File f = new File(st+o.toString());
// do whatever u want to do with 'f' File object
*/
}
});
Use UploadStringAsync
method:
WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
if (e.Error != null)
{
//handle your error here
}
else
{
//post was successful, so do what you need to do here
}
};
webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);
An easy fix, which worked for me, is moving my files out of src and into the main folder of the project. It's not the best solution, but depending on the magnitude of the project and your time, it might be just perfect.
Piping to xargs is a dirty way of doing that which can be done inside of find.
find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;
You can be even more controlling with other options, such as:
find . -type d -user harry -exec chown daisy {} \;
You can do some very cool things with find and you can do some very dangerous things too. Have a look at "man find", it's long but is worth a quick read. And, as always remember:
In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".
This is an alternate implementation using function instead of class. Inspired by @Andrew Wilkins above.
Because wait is more accurate than sleep ( it takes function runtime into account ):
import threading
PING_ON = threading.Event()
def ping():
while not PING_ON.wait(1):
print("my thread %s" % str(threading.current_thread().ident))
t = threading.Thread(target=ping)
t.start()
sleep(5)
PING_ON.set()
Exporting the DISPLAY
variable is definitely the solution but depending on your setup you may have to do this in a slightly different way.
In my case, I have two different processes: the first one starts Xvfb, the other one launches the tests. So my shell scripting knowledge is a bit rusty but I figured out that exporting the DISPLAY
variable from the first process didn't make it available in the second process.
Fortunately, Selenium WebDriver allows you to 'redefine' your environment. This is my function for creating a driver for Chrome in JS. Pretty sure the equivalent exists for your programming language:
const caps = require('selenium-webdriver/lib/capabilities');
const chrome = require('selenium-webdriver/chrome');
const chromedriver = require('chromedriver');
module.exports = function (cfg) {
let serviceBuilder = new chrome.ServiceBuilder(chromedriver.path);
let options = chrome.Options.fromCapabilities(caps.Capabilities.chrome());
let service;
let myENV = new Map();
// 're-export' the `DISPLAY` variable
myENV.set('DISPLAY', ':1');
serviceBuilder.setEnvironment(myENV);
service = serviceBuilder.build();
options.addArguments('disable-setuid-sandbox');
options.addArguments('no-sandbox');
options.addArguments('allow-insecure-localhost');
options.excludeSwitches('test-type');
return chrome.Driver.createSession(options, service);
};
Here is a solution that will both vertically and horizontally align your img within a div without any stretching even if the image supplied is too small or too big to fit in the div.
The HTML content:
<div id="myDiv">
<img alt="Client Logo" title="Client Logo" src="Imagelocation" />
</div>
The CSS content:
#myDiv
{
height: 104px;
width: 140px;
}
#myDiv img
{
max-width: 100%;
max-height: 100%;
margin: auto;
display: block;
}
The jQuery part:
var logoHeight = $('#myDiv img').height();
if (logoHeight < 104) {
var margintop = (104 - logoHeight) / 2;
$('#myDiv img').css('margin-top', margintop);
}
If you're using it, the Underscore.js library has a clone method.
var newObject = _.clone(oldObject);
First create HashMap.
HashMap> mapList = new HashMap>();
Get value from HashMap against your input key.
ArrayList arrayList = mapList.get(key);
Add value to arraylist.
arrayList.add(addvalue);
Then again put arraylist against that key value. mapList.put(key,arrayList);
It will work.....
If you use android studio, this might be useful for you.
I had a similar problem and i solved it by changing the skd path from the default C:\Program Files (x86)\Android\android-studio\sdk to C:\Program Files (x86)\Android\android-sdk .
It seems the problem came from the compiler version (gradle sets it automatically to the highest one available in the sdk folder) which doesn't support this theme, and since android studio had only the api 7 in its sdk folder, it gave me this error.
For more information on how to change Android sdk path in Android Studio: Android Studio - How to Change Android SDK Path
Machines don't understand English or any other languages, they understand only byte code, which they have to be compiled (e.g., C/C++, Java) or interpreted (e.g., Ruby, Python), the .pyc is a cached version of the byte code. https://www.geeksforgeeks.org/difference-between-compiled-and-interpreted-language/ Here is a quick read on what is the difference between compiled language vs interpreted language, TLDR is interpreted language does not require you to compile all the code before run time and thus most of the time they are not strict on typing etc.
for horizontal lines you can use hr tag:
hr { width: 90%; }
but its not possible to limit border height. only element height.
//path to directory to scan
$directory = "../data/team/";
//get all text files with a .txt extension.
$texts = glob($directory . "*.txt");
//print each file name
foreach($texts as $text)
{
echo $text;
}
As Srdjan Pejic says, you can use
<%= f.submit 'name', :class => 'button' %>
or the new syntax which would be:
<%= f.submit 'name', class: 'button' %>
I had the same problem and found solution, placing NULL
instead of NOT NULL
on foreign key column. Here is a query:
ALTER TABLE `db`.`table1`
ADD COLUMN `col_table2_fk` INT UNSIGNED NULL,
ADD INDEX `col_table2_fk_idx` (`col_table2_fk` ASC),
ADD CONSTRAINT `col_table2_fk1`
FOREIGN KEY (`col_table2_fk`)
REFERENCES `db`.`table2` (`table2_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
MySQL has executed this query!
reshape()
takes a while to get used to, just as melt
/cast
. Here is a solution with reshape, assuming your data frame is called d
:
reshape(d,
direction = "long",
varying = list(names(d)[3:7]),
v.names = "Value",
idvar = c("Code", "Country"),
timevar = "Year",
times = 1950:1954)
You should check this MSDN article and download the .docx file and read it carefully , it was very helpful for me.
However this is a class which works fine for my case :
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SECURITY_ATTRIBUTES
{
public uint nLength;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
internal enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
internal enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
public static class ProcessAsUser
{
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool CreateProcessAsUser(
IntPtr hToken,
string lpApplicationName,
string lpCommandLine,
ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx", SetLastError = true)]
private static extern bool DuplicateTokenEx(
IntPtr hExistingToken,
uint dwDesiredAccess,
ref SECURITY_ATTRIBUTES lpThreadAttributes,
Int32 ImpersonationLevel,
Int32 dwTokenType,
ref IntPtr phNewToken);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(
IntPtr ProcessHandle,
UInt32 DesiredAccess,
ref IntPtr TokenHandle);
[DllImport("userenv.dll", SetLastError = true)]
private static extern bool CreateEnvironmentBlock(
ref IntPtr lpEnvironment,
IntPtr hToken,
bool bInherit);
[DllImport("userenv.dll", SetLastError = true)]
private static extern bool DestroyEnvironmentBlock(
IntPtr lpEnvironment);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(
IntPtr hObject);
private const short SW_SHOW = 5;
private const uint TOKEN_QUERY = 0x0008;
private const uint TOKEN_DUPLICATE = 0x0002;
private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;
private const int GENERIC_ALL_ACCESS = 0x10000000;
private const int STARTF_USESHOWWINDOW = 0x00000001;
private const int STARTF_FORCEONFEEDBACK = 0x00000040;
private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock)
{
bool result = false;
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
saThread.nLength = (uint)Marshal.SizeOf(saThread);
STARTUPINFO si = new STARTUPINFO();
si.cb = (uint)Marshal.SizeOf(si);
//if this member is NULL, the new process inherits the desktop
//and window station of its parent process. If this member is
//an empty string, the process does not inherit the desktop and
//window station of its parent process; instead, the system
//determines if a new desktop and window station need to be created.
//If the impersonated user already has a desktop, the system uses the
//existing desktop.
si.lpDesktop = @"WinSta0\Default"; //Modify as needed
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;
si.wShowWindow = SW_SHOW;
//Set other si properties as required.
result = CreateProcessAsUser(
token,
null,
cmdLine,
ref saProcess,
ref saThread,
false,
CREATE_UNICODE_ENVIRONMENT,
envBlock,
null,
ref si,
out pi);
if (result == false)
{
int error = Marshal.GetLastWin32Error();
string message = String.Format("CreateProcessAsUser Error: {0}", error);
FilesUtilities.WriteLog(message,FilesUtilities.ErrorType.Info);
}
return result;
}
private static IntPtr GetPrimaryToken(int processId)
{
IntPtr token = IntPtr.Zero;
IntPtr primaryToken = IntPtr.Zero;
bool retVal = false;
Process p = null;
try
{
p = Process.GetProcessById(processId);
}
catch (ArgumentException)
{
string details = String.Format("ProcessID {0} Not Available", processId);
FilesUtilities.WriteLog(details, FilesUtilities.ErrorType.Info);
throw;
}
//Gets impersonation token
retVal = OpenProcessToken(p.Handle, TOKEN_DUPLICATE, ref token);
if (retVal == true)
{
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.nLength = (uint)Marshal.SizeOf(sa);
//Convert the impersonation token into Primary token
retVal = DuplicateTokenEx(
token,
TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY,
ref sa,
(int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
(int)TOKEN_TYPE.TokenPrimary,
ref primaryToken);
//Close the Token that was previously opened.
CloseHandle(token);
if (retVal == false)
{
string message = String.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error());
FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);
}
}
else
{
string message = String.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error());
FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);
}
//We'll Close this token after it is used.
return primaryToken;
}
private static IntPtr GetEnvironmentBlock(IntPtr token)
{
IntPtr envBlock = IntPtr.Zero;
bool retVal = CreateEnvironmentBlock(ref envBlock, token, false);
if (retVal == false)
{
//Environment Block, things like common paths to My Documents etc.
//Will not be created if "false"
//It should not adversley affect CreateProcessAsUser.
string message = String.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error());
FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);
}
return envBlock;
}
public static bool Launch(string appCmdLine /*,int processId*/)
{
bool ret = false;
//Either specify the processID explicitly
//Or try to get it from a process owned by the user.
//In this case assuming there is only one explorer.exe
Process[] ps = Process.GetProcessesByName("explorer");
int processId = -1;//=processId
if (ps.Length > 0)
{
processId = ps[0].Id;
}
if (processId > 1)
{
IntPtr token = GetPrimaryToken(processId);
if (token != IntPtr.Zero)
{
IntPtr envBlock = GetEnvironmentBlock(token);
ret = LaunchProcessAsUser(appCmdLine, token, envBlock);
if (envBlock != IntPtr.Zero)
DestroyEnvironmentBlock(envBlock);
CloseHandle(token);
}
}
return ret;
}
}
And to execute , simply call like this :
string szCmdline = "AbsolutePathToYourExe\\ExeNameWithoutExtension";
ProcessAsUser.Launch(szCmdline);
In cross-platform, lowest-common-denominator sh
you use:
#!/bin/sh
value=`cat config.txt`
echo "$value"
In bash
or zsh
, to read a whole file into a variable without invoking cat
:
#!/bin/bash
value=$(<config.txt)
echo "$value"
Invoking cat
in bash
or zsh
to slurp a file would be considered a Useless Use of Cat.
Note that it is not necessary to quote the command substitution to preserve newlines.
See: Bash Hacker's Wiki - Command substitution - Specialities.
all(getattr(someTime,x)==getattr(today(),x) for x in ['year','month','day'])
One should compare using .date()
, but I leave this method as an example in case one wanted to, for example, compare things by month or by minute, etc.
Put file inside while True
like so
while True:
f = open('torecv.png','wb')
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
print "Receiving..."
l = c.recv(1024)
while (l):
print "Receiving..."
f.write(l)
l = c.recv(1024)
f.close()
print "Done Receiving"
c.send('Thank you for connecting')
c.close()
If you're using a jupyter notebook, I found this to be the simplest solution for one off cases. Basically convert the numpy array to a list and then to a string and then print. This has the benefit of keeping the comma separators in the array, whereas using numpyp.printoptions(threshold=np.inf)
does not:
import numpy as np
print(str(np.arange(10000).reshape(250,40).tolist()))
For the last name as in US standards (i.e., last word in the [Full Name] column) and considering first name to include a possible middle initial, middle name, etc.:
SELECT DISTINCT
[Full Name]
,REVERSE([Full Name]) -- to visualize what the formula is doing
,CHARINDEX(' ', REVERSE([Full Name])) -- finds the last space in the string
,[Last Name] = REVERSE(RTRIM(LTRIM(LEFT(REVERSE([Full Name]), CHARINDEX(' ', REVERSE([Full Name]))))))
,[First Name] = RTRIM(LTRIM(LEFT([Full Name], LEN([Full Name]) - CHARINDEX(' ', REVERSE([Full Name])))))
FROM ...
Note that this assumes [Full Name] has no spaces before or after the actual string. Otherwise, use RTRIM and LTRIM to remove these.
Right click on your project, select New -> Source Folder
Enter src as Folder name, then click finish.
Eclipse will then recognize the src folder as containing Java code, and you should be able to set up a run configuration
Yes, O3 is buggier. I'm a compiler developer and I've identified clear and obvious gcc bugs caused by O3 generating buggy SIMD assembly instructions when building my own software. From what I've seen, most production software ships with O2 which means O3 will get less attention wrt testing and bug fixes.
Think of it this way: O3 adds more transformations on top of O2, which adds more transformations on top of O1. Statistically speaking, more transformations means more bugs. That's true for any compiler.
Unless the variable k
is defined, that's probably what's causing your trouble. Something like this will do what you want:
var new_tweets = { };
new_tweets.k = { };
new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;
new_tweets.k.data = { };
new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';
// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);
You can also do it all at once:
var new_tweets = {
k: {
tweet_id: 98745521,
user_id: 54875,
data: {
in_reply_to_screen_name: 'other_user',
text: 'tweet_text'
}
}
}
From component
import { Component, OnInit, ViewChild} from '@angular/core';_x000D_
import { HttpClient } from '@angular/common/http';_x000D_
import { dataService } from "src/app/service/data.service";_x000D_
@Component( {_x000D_
selector: 'app-sideWidget',_x000D_
templateUrl: './sideWidget.html',_x000D_
styleUrls: ['./linked-widget.component.css']_x000D_
} )_x000D_
export class sideWidget{_x000D_
TableColumnNames: object[];_x000D_
SelectedtableName: string = "patient";_x000D_
constructor( private LWTableColumnNames: dataService ) { _x000D_
_x000D_
}_x000D_
_x000D_
ngOnInit() {_x000D_
this.http.post( 'getColumns', this.SelectedtableName )_x000D_
.subscribe(_x000D_
( data: object[] ) => {_x000D_
this.TableColumnNames = data;_x000D_
this.LWTableColumnNames.refLWTableColumnNames = this.TableColumnNames; //this line of code will pass the value through data service_x000D_
} );_x000D_
_x000D_
} _x000D_
}
_x000D_
DataService
import { Injectable } from '@angular/core';_x000D_
import { BehaviorSubject, Observable } from 'rxjs';_x000D_
_x000D_
@Injectable()_x000D_
export class dataService {_x000D_
refLWTableColumnNames: object;//creating an object for the data_x000D_
}
_x000D_
To Component
import { Component, OnInit } from '@angular/core';_x000D_
import { dataService } from "src/app/service/data.service";_x000D_
_x000D_
@Component( {_x000D_
selector: 'app-linked-widget',_x000D_
templateUrl: './linked-widget.component.html',_x000D_
styleUrls: ['./linked-widget.component.css']_x000D_
} )_x000D_
export class LinkedWidgetComponent implements OnInit {_x000D_
_x000D_
constructor(private LWTableColumnNames: dataService) { }_x000D_
_x000D_
ngOnInit() {_x000D_
console.log(this.LWTableColumnNames.refLWTableColumnNames);_x000D_
}_x000D_
createTable(){_x000D_
console.log(this.LWTableColumnNames.refLWTableColumnNames);// calling the object from another component_x000D_
}_x000D_
_x000D_
}
_x000D_
Stack trace is prserved if you wrap the catched excetion into an other exception (to provide more info) or if you just rethrow the catched excetion.
try{
...
}catch (FooException e){
throw new BarException("Some usefull info", e);
}
A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order.
You can use MemberwiseClone
obj myobj2 = (obj)myobj.MemberwiseClone();
The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj
are of value types.
If you own the source code, you can also implement ICloneable
Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer:
# d = Pandas Dataframe,
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ]
def chart(d,ys):
from itertools import cycle
fig, ax = plt.subplots()
axes = [ax]
for y in ys[1:]:
# Twin the x-axis twice to make independent y-axes.
axes.append(ax.twinx())
extra_ys = len(axes[2:])
# Make some space on the right side for the extra y-axes.
if extra_ys>0:
temp = 0.85
if extra_ys<=2:
temp = 0.75
elif extra_ys<=4:
temp = 0.6
if extra_ys>5:
print 'you are being ridiculous'
fig.subplots_adjust(right=temp)
right_additive = (0.98-temp)/float(extra_ys)
# Move the last y-axis spine over to the right by x% of the width of the axes
i = 1.
for ax in axes[2:]:
ax.spines['right'].set_position(('axes', 1.+right_additive*i))
ax.set_frame_on(True)
ax.patch.set_visible(False)
ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
i +=1.
# To make the border of the right-most axis visible, we need to turn the frame
# on. This hides the other plots, however, so we need to turn its fill off.
cols = []
lines = []
line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
'1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
colors = cycle(matplotlib.rcParams['axes.color_cycle'])
for ax,y in zip(axes,ys):
ls=line_styles.next()
if len(y)==1:
col = y[0]
cols.append(col)
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
ax.set_ylabel(col,color=color)
#ax.tick_params(axis='y', colors=color)
ax.spines['right'].set_color(color)
else:
for col in y:
color = colors.next()
lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
cols.append(col)
ax.set_ylabel(', '.join(y))
#ax.tick_params(axis='y')
axes[0].set_xlabel(d.index.name)
lns = lines[0]
for l in lines[1:]:
lns +=l
labs = [l.get_label() for l in lns]
axes[0].legend(lns, labs, loc=0)
plt.show()
You should not wrap JavaScript expressions in quotes.
<option data-img-src={this.props.imageUrl} value="1">{this.props.title}</option>
Take a look at the JavaScript Expressions docs for more info.
You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.
Simply adding the following line of code should fix your problems:
mainFrame.setLayout(new BorderLayout());
(Do this before adding components to the JFrame)
You should execute the next query:
GRANT ALL ON TABLE mytable TO myuser;
Or if your error is in a view then maybe the table does not have permission, so you should execute the next query:
GRANT ALL ON TABLE tbm_grupo TO myuser;
Properties prop = new Properties();
prop.load(...); // FileInputStream
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream
Read From Config:
You'll need to add a reference to the configuration:
Get Value with using following code:
string value = Properties.Settings.Default.keyname;
Save to the configuration:
Properties.Settings.Default.keyName = value;
Properties.Settings.Default.Save();
I just run into this problem too, with all the MySQL re-config mentioned above the error still appears. It turns out that I misspelled the database name.
So be sure you're connecting with the right database name especially the case.
Just make all users who log in subscribe to a specific topic, and then send a notification to that topic.
ASCII encoding is 7-bit, but in practice, characters encoded in ASCII are not stored in groups of 7 bits. Instead, one ASCII is stored in a byte, with the MSB usually set to 0 (yes, it's wasted in ASCII).
You can verify this by inputting a string in the ASCII character set in a text editor, setting the encoding to ASCII, and viewing the binary/hex:
Aside: the use of (strictly) ASCII encoding is now uncommon, in favor of UTF-8 (which does not waste the MSB mentioned above - in fact, an MSB of 1 indicates the code point is encoded with more than 1 byte).
If you do decide to have MySQL handle the update of timestamps, you can set up a trigger to update the field on insert.
CREATE TRIGGER <trigger_name> BEFORE INSERT ON <table_name> FOR EACH ROW SET NEW.<timestamp_field> = CURRENT_TIMESTAMP;
MySQL Reference: http://dev.mysql.com/doc/refman/5.0/en/triggers.html
I feel this can be easily solved using bottleneck
See basic sample below:
import numpy as np
import bottleneck as bn
a = np.random.randint(4, 1000, size=(5, 7))
mm = bn.move_mean(a, window=2, min_count=1)
This gives move mean along each axis.
"mm" is the moving mean for "a".
"window" is the max number of entries to consider for moving mean.
"min_count" is min number of entries to consider for moving mean (e.g. for first element or if the array has nan values).
The good part is Bottleneck helps to deal with nan values and it's also very efficient.
Python started as a scripting language for Linux like Perl but less cryptic. Now it is used for both web and desktop applications and is available on Windows too. Desktop GUI APIs like GTK have their Python implementations and Python based web frameworks like Django are preferred by many over PHP et al. for web applications.
And by the way,
Proxy support and the Host field:
HTTP 1.1 has a required Host header by spec.
HTTP 1.0 does not officially require a Host header, but it doesn't hurt to add one, and many applications (proxies) expect to see the Host header regardless of the protocol version.
Example:
GET / HTTP/1.1
Host: www.blahblahblahblah.com
This header is useful because it allows you to route a message through proxy servers, and also because your web server can distinguish between different sites on the same server.
So this means if you have blahblahlbah.com and helohelohelo.com both pointing to the same IP. Your web server can use the Host field to distinguish which site the client machine wants.
Persistent connections:
HTTP 1.1 also allows you to have persistent connections which means that you can have more than one request/response on the same HTTP connection.
In HTTP 1.0 you had to open a new connection for each request/response pair. And after each response the connection would be closed. This lead to some big efficiency problems because of TCP Slow Start.
OPTIONS method:
HTTP/1.1 introduces the OPTIONS method. An HTTP client can use this method to determine the abilities of the HTTP server. It's mostly used for Cross Origin Resource Sharing in web applications.
Caching:
HTTP 1.0 had support for caching via the header: If-Modified-Since.
HTTP 1.1 expands on the caching support a lot by using something called 'entity tag'. If 2 resources are the same, then they will have the same entity tags.
HTTP 1.1 also adds the If-Unmodified-Since, If-Match, If-None-Match conditional headers.
There are also further additions relating to caching like the Cache-Control header.
100 Continue status:
There is a new return code in HTTP/1.1 100 Continue. This is to prevent a client from sending a large request when that client is not even sure if the server can process the request, or is authorized to process the request. In this case the client sends only the headers, and the server will tell the client 100 Continue, go ahead with the body.
Much more:
Note this
function FollowMouse() {
for(var i=0; i< arguments.length; i++) {
arguments[i].style.top = event.clientY+"px";
arguments[i].style.left = event.clientX+"px";
}
};
//---------------------------
html page
<body onmousemove="FollowMouse(d1,d2,d3)">
<p><div id="d1" style="position: absolute;">Follow1</div></p>
<div id="d2" style="position: absolute;"><p>Follow2</p></div>
<div id="d3" style="position: absolute;"><p>Follow3</p></div>
</body>
can call function with any Args
<body onmousemove="FollowMouse(d1,d2)">
or
<body onmousemove="FollowMouse(d1)">
First you don't need to change anything yet.
Those nonstandard behaviors remain the default for TIMESTAMP but as of MySQL 5.6.6 are deprecated and this warning appears at startup
Now if you want to move to new behaviors you have to add this line in your my.cnf
in the [mysqld] section.
explicit_defaults_for_timestamp = 1
The location of my.cnf (or other config files) vary from one system to another. If you can't find it refer to https://dev.mysql.com/doc/refman/5.7/en/option-files.html
To activate virtualenv in env
directory and export envinroment variables stored in .env
use :
source env/bin/activate && set -a; source .env; set +a
By using os.system:
import os
os.system(r'"C:/Documents and Settings/flow_model/flow.exe"')
When constructing the usual MCV (a 3-tier architecture) one can decide to implement the MCV with double-deck interfaces, such that one can in fact replace a particular tier without having to modify even one line of code.
We often see the benefits of this, for instance in scenarios where you want to be able to use more than one database (in which case you have a double-interface between the control and data-layers).
When you put it on the View-layer (presentation), then you can (hold on!!) replace the USER interface with another machine, thereby automate REAL input (!!!) - and you can thereby run tedious usability tests thousands of times without any user having to tap and re-tap and re-re-tap the same things over and over again.
Some describe such 3-tier architecture with 1 or 2 double-interfaces as 4-tier or 5-tier architecture, implicitly implying the double-interfaces.
Other cases include (but are not limited to) the fact that you - in case of semi-or-fully replicated database-systems would practically be able to consider one of the databases as the "master", and thereby you would have a tier comprising of the master and another comprising of the slave database.
Mobile example
Therefore, multi-tier - or N-tier - indeed has a few interpretations, whereas I would surely stick to the 3-tier + extra tiers comprising of thin interface-disks wedged in between to enable said tier-swaps, and in terms of testing (particularly used on mobile devices), you can now run user tests on the real software, by simulating a users tapping in ways which the control logic cannot distinguish from a real user tapping. This is almost paramount in simulating real user tests, in that you can record all inputs from the users OTA, and then re-use the same input when doing regression tests.
You can't do it directly, you should provide your own way to check this. Eg.
class MyClass {
Object attr1, attr2, attr3;
public boolean isValid() {
return attr1 != null && attr2 != null && attr3 != null;
}
}
Or make all fields final and initialize them in constructors so that you can be sure that everything is initialized.
__repr__
is used everywhere, except by print
and str
methods (when a __str__
is defined !)
You can use jquery for create element on the fly
$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');
or other way
$('<input>').attr({
type: 'hidden',
id: 'fieldId',
name: 'fieldname'
}).appendTo('form')
Try using copy()
function instead of move_uploaded_file()
. It worked for me.
copy($_FILES['file']['tmp_name'], $path);
Late resurrection.
Your query seems very similar to the one at page 259 of the book Pro JPA 2: Mastering the Java Persistence API, which in JPQL reads:
SELECT e
FROM Employee e
WHERE e IN (SELECT emp
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Using EclipseLink + H2 database, I couldn't get neither the book's JPQL nor the respective criteria working. For this particular problem I have found that if you reference the id directly instead of letting the persistence provider figure it out everything works as expected:
SELECT e
FROM Employee e
WHERE e.id IN (SELECT emp.id
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Finally, in order to address your question, here is an equivalent strongly typed criteria query that works:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);
Subquery<Integer> sq = c.subquery(Integer.class);
Root<Project> project = sq.from(Project.class);
Join<Project, Employee> sqEmp = project.join(Project_.employees);
sq.select(sqEmp.get(Employee_.id)).where(
cb.equal(project.get(Project_.name),
cb.parameter(String.class, "project")));
c.select(emp).where(
cb.in(emp.get(Employee_.id)).value(sq));
TypedQuery<Employee> q = em.createQuery(c);
q.setParameter("project", projectName); // projectName is a String
List<Employee> employees = q.getResultList();
Since you have mysql on your local computer, you do not need to bother with the IP address of the machine. Just use localhost:
mysql -u user -p
or
mysql -hlocalhost -u user -p
If you cannot login with this, you must find out what usernames (user@host) exist in the MySQL Server locallly. Here is what you do:
Step 01) Startup mysql so that no passwords are require no passwords and denies TCP/IP connections
service mysql restart --skip-grant-tables --skip-networking
Keep in mind that standard SQL for adding users, granting and revoking privs are disabled.
Step 02) Show users and hosts
select concat(''',user,'''@''',host,'''') userhost,password from mysql.user;
Step 03) Check your password to make sure it works
select user,host from mysql.user where password=password('YourMySQLPassword');
If your password produces no output for this query, you have a bad password.
If your password produces output for this query, look at the users and hosts. If your host value is '%', your should be able to connect from anywhere. If your host is 'localhost', you should be able to connect locally.
Make user you have 'root'@'localhost' defined.
Once you have done what is needed, just restart mysql normally
service mysql restart
If you are able to connect successfully on the macbook, run this query:
SELECT USER(),CURRENT_USER();
USER() reports how you attempted to authenticate in MySQL
CURRENT_USER() reports how you were allowed to authenticate in MySQL
Let us know what happens !!!
UPDATE 2012-02-13 20:47 EDT
Login to the remote server and repeat Step 1-3
See if any user allows remote access (i.e, host in mysql.user is '%'). If you do not, then add 'user'@'%' to mysql.user.
Here is a basic approach - it sure can be improved - of what I understood to be your requirement.
This will display 2 columns, one with the groups name, and one with the list of items associated to the group.
The trick is simply to include a list within the items cell.
<table>
<thead>
<th>Groups Name</th>
<th>Groups Items</th>
</thead>
<tbody>
<tr *ngFor="let group of groups">
<td>{{group.name}}</td>
<td>
<ul>
<li *ngFor="let item of group.items">{{item}}</li>
</ul>
</td>
</tr>
</tbody>
</table>
Talking about static variables, this is a little bit like closure variant:
var once = function() {
if(once.done) return;
console.log('Doing this once!');
once.done = true;
};
once(); once();
You could then reset a function if you wish:
once.done = false;
I have Tried something Like this and it worked really fine with me
Socket Skt;
String host = "localhost";
int i = 8983; // port no.
try {
System.out.println("Looking for "+ i);
Skt = new Socket(host, i);
System.out.println("There is a Server on port "
+ i + " of " + host);
}
catch (UnknownHostException e) {
System.out.println("Exception occured"+ e);
}
catch (IOException e) {
System.out.println("port is not used");
}
<>
is equal to !=
i.e, both are used to represent the NOT EQUAL operation. For instance, email <> ''
and email != ''
are same.
From: Developer > reference - Application
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
change this {% if loop.counter == 1 %}
to {% if forloop.counter == 1 %} {#your code here#} {%endfor%}
and this from {{ user }} {{loop.counter}}
to {{ user }} {{forloop.counter}}
I think there are more solutions!
You can start the app, and here are 3 things you can do:
Settings
> Manage License...
> Remove License
, and that removes for all Jetbrains products*.File
> Close Project
, and follow the first step.Help
> Register...
> Remove license
.*In case you have a license for a pack of products. If not, you have to remove the license per product individually. Check the 3rd step.
git submodule deinit --all -f
worked for me.
I have struggled with a similar issue for one day... My Scenario:
I have a SpringBoot application and I use applicationContext.xml in scr/main/resources
to configure all my Spring Beans.
For testing(integration testing) I use another applicationContext.xml in test/resources
and things worked as I have expected: Spring/SpringBoot would override applicationContext.xml from scr/main/resources
and would use the one for Testing which contained the beans configured for testing.
However, just for one UnitTest I wanted yet another customization for the applicationContext.xml used in Testing, just for this Test I wanted to used some mockito beans, so I could mock
and verify
, and here started my one day head-ache!
The problem is that Spring/SpringBoot doesn't not override the applicationContext.xml from scr/main/resources
ONLY IF the file from test/resources
HAS the SAME NAME.
I tried for hours to use something like:
@RunWith(SpringJUnit4ClassRunner.class)
@OverrideAutoConfiguration(enabled=true)
@ContextConfiguration({"classpath:applicationContext-test.xml"})
it did not work, Spring was first loading the beans from applicationContext.xml in scr/main/resources
My solution based on the answers here by @myroch and @Stuart:
Define the main configuration of the application:
@Configuration
@ImportResource({"classpath:applicationContext.xml"})
public class MainAppConfig {
}
this is used in the application
@SpringBootApplication
@Import(MainAppConfig.class)
public class SuppressionMain implements CommandLineRunner
Define a TestConfiguration for the Test where you want to exclude the main configuration
@ComponentScan( basePackages = "com.mypackage", excludeFilters = { @ComponentScan.Filter(type = ASSIGNABLE_TYPE, value = {MainAppConfig.class}) }) @EnableAutoConfiguration public class TestConfig { }
By doing this, for this Test, Spring will not load applicationContext.xml and will load only the custom configuration specific for this Test.
You can only view the log on a local repository, however that can include the fetched branches of all remotes you have set-up.
So, if you clone a repo...
git clone git@gitserver:folder/repo.git
This will default to origin/master
.
You can add a remote to this repo, other than origin
let's add production
. From within the local clone folder:
git remote add production git@production-server:folder/repo.git
If we ever want to see the log of production
we will need to do:
git fetch --all
This fetches from ALL remotes (default fetch without --all
would fetch just from origin
)
After fetching we can look at the log on the production
remote, you'll have to specify the branch too.
git log production/master
All options will work as they do with log on local branches.
It leaves blank pages so that a new part or chapter start on the right-hand side. You can fix this with the "openany" option for the document class. ;)
And this is a Kotlin version:
editText.setOnEditorActionListener { v, actionId, event ->
if(actionId == EditorInfo.IME_ACTION_DONE){
//Put your action there
true
} else {
false
}
}
The question is 'What is the simplest SOAP example using Javascript?'
This answer is of an example in the Node.js environment, rather than a browser. (Let's name the script soap-node.js) And we will use the public SOAP web service from Europe PMC as an example to get the reference list of an article.
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const DOMParser = require('xmldom').DOMParser;
function parseXml(text) {
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(text, "text/xml");
Array.from(xmlDoc.getElementsByTagName("reference")).forEach(function (item) {
console.log('Title: ', item.childNodes[3].childNodes[0].nodeValue);
});
}
function soapRequest(url, payload) {
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', url, true);
// build SOAP request
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
parseXml(xmlhttp.responseText);
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(payload);
}
soapRequest('https://www.ebi.ac.uk/europepmc/webservices/soap',
`<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header />
<S:Body>
<ns4:getReferences xmlns:ns4="http://webservice.cdb.ebi.ac.uk/"
xmlns:ns2="http://www.scholix.org"
xmlns:ns3="https://www.europepmc.org/data">
<id>C7886</id>
<source>CTX</source>
<offSet>0</offSet>
<pageSize>25</pageSize>
<email>[email protected]</email>
</ns4:getReferences>
</S:Body>
</S:Envelope>`);
Before running the code, you need to install two packages:
npm install xmlhttprequest
npm install xmldom
Now you can run the code:
node soap-node.js
And you'll see the output as below:
Title: Perspective: Sustaining the big-data ecosystem.
Title: Making proteomics data accessible and reusable: current state of proteomics databases and repositories.
Title: ProteomeXchange provides globally coordinated proteomics data submission and dissemination.
Title: Toward effective software solutions for big biology.
Title: The NIH Big Data to Knowledge (BD2K) initiative.
Title: Database resources of the National Center for Biotechnology Information.
Title: Europe PMC: a full-text literature database for the life sciences and platform for innovation.
Title: Bio-ontologies-fast and furious.
Title: BioPortal: ontologies and integrated data resources at the click of a mouse.
Title: PubMed related articles: a probabilistic topic-based model for content similarity.
Title: High-Impact Articles-Citations, Downloads, and Altmetric Score.
For the record and Google search users, If you are a .NET Core developer, you should set the content-types manually, because their default value is null or empty:
var provider = new FileExtensionContentTypeProvider();
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider
});
File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml
, .yaml
or indeed anything else.
The (rather sparse) YAML FAQ recommends that you use .yaml
in preference to .yml
, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml
instead.
So, what really matters is what is inside the file, rather than what its extension is.
In the specific case of sed
, the -i
option that others have already mentioned is far and away the simplest and sanest one.
In the more general case, sponge
, from the moreutils
collection, does exactly what you want: it lets you replace a file with the result of processing it, in a way specifically designed to keep the processing step from tripping over itself by overwriting the very file it's working on. To quote the sponge
man page:
sponge reads standard input and writes it out to the specified file. Unlike a shell redirect, sponge soaks up all its input before writing the output file. This allows constructing pipelines that read from and write to the same file.
You can just go to the place where the screen session is housed and run:
screen -ls
which results in
There is a screen on:
26727.pts-0.devxxx (Attached)
1 Socket in /tmp/uscreens/S-xxx. <------ this is where the session is.
And just remove it:
cd /tmp/uscreens/S-xxx
ls
26727.pts-0.devxxx
rm 26727.pts-0.devxxx
ls
The uscreens
directory will not have the 26727.pts-0.devxxx
file in it anymore. Now to make sure just type this:
screen -ls
and you should get:
No Sockets found in /tmp/uscreens/S-xxx.
You can customize the standard Linkedin button like this, after the page load:
$(".IN-widget span:first-of-type").css({
'border': '2px solid #DCDCDC',
'-webkit-border-radius': '3px',
'-moz-border-radius': '3px',
'border-radius': '3px'
});
You can set the StartPosition in the constructor of the child form so that all new instances of the form get centered to it's parent:
public MyForm()
{
InitializeComponent();
this.StartPosition = FormStartPosition.CenterParent;
}
Of course, you could also set the StartPosition property in the Designer properties for your child form. When you want to display the child form as a modal dialog, just set the window owner in the parameter for the ShowDialog method:
private void buttonShowMyForm_Click(object sender, EventArgs e)
{
MyForm form = new MyForm();
form.ShowDialog(this);
}
You can change the selector and data attributes as you wish!
<select id="selectVehicle">
<option value="1" data-year="2011">Mazda</option>
<option value="2" data-year="2015">Honda</option>
<option value="3" data-year="2008">Mercedes</option>
<option value="4" data-year="2005">Toyota</option>
</select>
$("#selectVehicle").change(function () {
alert($(this).find(':selected').data("year"));
});
Here is the working example: https://jsfiddle.net/ed5axgvk/1/
I would suggest you read the appropriate sections in The Java Tutorial from Sun:
http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html
Below code works with Spring boot(kotlin):
val authReader = InputStreamReader(javaClass.getResourceAsStream("/file1.json"))
The CSS Tooltip allows you to format the popup as you like as any div
section! And no Javascript needed.
In Linux, I normally use this command to recursively grep for a particular text within a dir
grep -rni "string" *
where,
r = recursive i.e, search subdirectories within the current directory
n = to print the line numbers to stdout
i = case insensitive search
I have found this small library that encapsulates what you need.
npm install zip-a-folder
const zip-a-folder = require('zip-a-folder');
await zip-a-folder.zip('/path/to/the/folder', '/path/to/archive.zip');
To answer your question, you can explore the contents of the model's output by saving the model as a variable and clicking on it in the environment window. You can then click around to see what it contains and what is stored where.
Another way is to type yourmodelname$
and select the components of the model one by one to see what each contains. When you get to yourmodelname$coefficients
, you will see all of beta-, p, and t- values you desire.
Here's how to apply environment variables to template file (no backup need).
echo "Hello {{FOO}}" > foo.conf.tmpl
FOO="world" && sed -e "s/{{FOO}}/$FOO/g" foo.conf.tmpl > foo.conf
Working both macOS 10.12.4 and Ubuntu 14.04.5
I came across this question and inspired by other contributors. I need to append some content to a file once per line. Here is what I did.
class Doh {
def ln = System.getProperty('line.separator')
File file //assume it's initialized
void append(String content) {
file << "$content$ln"
}
}
Pretty neat I think :)
Set height and width parameters in CSS file
.ImageStyle{_x000D_
_x000D_
max-height: 17vw;_x000D_
min-height: 17vw;_x000D_
max-width:17vw;_x000D_
min-width: 17vw;_x000D_
_x000D_
}
_x000D_
Not possible to load static local files(eg:svg) without server. If you have NPM /YARN installed in your machine, you can setup simple http server using "http-server"
npm install http-server -g
http-server [path] [options]
Or open terminal in that project folder and type "hs". It will automaticaly start HTTP live server.
Use : $window.location.href = '/Home.html';
Using pyautogui
To install
pip install pyautogui
and to find the location of the mouse pointer
import pyautogui
print(pyautogui.position())
This will give the pixel location to which mouse pointer is at.
Here's an Ajax, asxh
handler and session variables approach:
Handler:
using System;
using System.Web;
public class windowSize : IHttpHandler , System.Web.SessionState.IRequiresSessionState {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
var json = new System.Web.Script.Serialization.JavaScriptSerializer();
var output = json.Serialize(new { isFirst = context.Session["BrowserWidth"] == null });
context.Response.Write(output);
context.Session["BrowserWidth"] = context.Request.QueryString["Width"];
context.Session["BrowserHeight"] = context.Request.QueryString["Height"];
}
public bool IsReusable
{
get { throw new NotImplementedException(); }
}
}
Javascript:
window.onresize = function (event) {
SetWidthHeight();
}
function SetWidthHeight() {
var height = $(window).height();
var width = $(window).width();
$.ajax({
url: "windowSize.ashx",
data: {
'Height': height,
'Width': width
},
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (data) {
if (data.isFirst) {
window.location.reload();
};
}).fail(function (xhr) {
alert("Problem to retrieve browser size.");
});
}
$(function () {
SetWidthHeight();
});
On aspx file:
...
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/BrowserWindowSize.js"></script>
...
<asp:Label ID="lblDim" runat="server" Text=""></asp:Label>
...
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["BrowserWidth"] != null)
{
// Do all code here to avoid double execution first time
// ....
lblDim.Text = "Width: " + Session["BrowserWidth"] + " Height: " + Session["BrowserHeight"];
}
}
Source: https://techbrij.com/browser-height-width-server-responsive-design-asp-net
As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:
TSKILL processName
or
TSKILL PID
Have on mind that processName
should not have the .exe
suffix and is limited to 18 characters.
Another option is WMIC
:
wmic Path win32_process Where "Caption Like 'MyProcess.exe'" Call Terminate
wmic offer even more flexibility than taskkill .With wmic Path win32_process get
you can see the available fileds you can filter.
The same way you make anything else negative: put a negative sign in front of it.
var positive = 6;
var negative = -positive;
I had this error and no meaningful message to tell me what was wrong. I finally removed this line from gradle.properties and got a meaningful error message.
android.enableAapt2=false
In my case somebody on the team had changed a .jpg extension to a .png and the file header didn't match the extension. Fun.
A bit late on this one but this worked perfectly for me when trying to hide the background for IE6 & 7
.myclass{
background-image: url("images/myimg.png");
background-position: right top;
background-repeat: no-repeat;
background-size: 22px auto;
padding-left: 48px;
height: 42px;
_background-image: none;
*background-image: none;
}
I got this hack via: http://briancray.com/posts/target-ie6-and-ie7-with-only-1-extra-character-in-your-css/
#myelement
{
color: #999; /* shows in all browsers */
*color: #999; /* notice the * before the property - shows in IE7 and below */
_color: #999; /* notice the _ before the property - shows in IE6 and below */
}
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
I did a small demo for you. Demonstrating how to display long text.
In this example there is a column Name which may contain very long text. The boundField will display all content in a table cell and therefore the cell will expand as needed (because of the content)
The TemplateField will also be rendered as a cell BUT it contains a div which limits the width of any contet to eg 40px. So this column will have some kind of max-width!
<asp:GridView ID="gvPersons" runat="server" AutoGenerateColumns="False" Width="100px">
<Columns>
<asp:BoundField HeaderText="ID" DataField="ID" />
<asp:BoundField HeaderText="Name (long)" DataField="Name">
<ItemStyle Width="40px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Name (short)">
<ItemTemplate>
<div style="width: 40px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis">
<%# Eval("Name") %>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my demo codeBehind
public partial class gridViewLongText : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
#region init and bind data
List<Person> list = new List<Person>();
list.Add(new Person(1, "Sam"));
list.Add(new Person(2, "Max"));
list.Add(new Person(3, "Dave"));
list.Add(new Person(4, "TabularasaVeryLongName"));
gvPersons.DataSource = list;
gvPersons.DataBind();
#endregion
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public Person(int _ID, string _Name)
{
ID = _ID;
Name = _Name;
}
}
I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.
Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.
You could use a macro, but it’s simpler to use styles. Define a character style that has the desired text color and assign a shortcut key to it, say Alt+R. In order to be able to switch color using just the keyboard, define another character style, say “normal”, that has no special feature—just for use to get normal text after switching to your colored style, and assign another shortcut to it, say Alt+N. Then you would just type text, press Alt+R to switch to colored text, type that text, press Alt+N to resume normal text color, etc.
The simplest way to do this is to use MATLAB's system function.
So basically, you would execute a Python function on MATLAB as you would do on the command prompt (Windows), or shell (Linux):
system('python pythonfile.py')
The above is for simply running a Python file. If you wanted to run a Python function (and give it some arguments), then you would need something like:
system('python pythonfile.py argument')
For a concrete example, take the Python code in Adrian's answer to this question, and save it to a Python file, that is test.py
. Then place this file in your MATLAB directory and run the following command on MATLAB:
system('python test.py 2')
And you will get as your output 4 or 2^2.
Note: MATLAB looks in the current MATLAB directory for whatever Python file you specify with the system
command.
This is probably the simplest way to solve your problem, as you simply use an existing function in MATLAB to do your bidding.
#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;
println("hello");
Ensure debug mode is on - either add APP_DEBUG=true
to .env file or set an environment variable
Log files are in storage/logs folder. laravel.log
is the default filename. If there is a permission issue with the log folder, Laravel just halts. So if your endpoint generally works - permissions are not an issue.
In case your calls don't even reach Laravel or aren't caused by code issues - check web server's log files (check your Apache/nginx config files to see the paths).
If you use PHP-FPM, check its log files as well (you can see the path to log file in PHP-FPM pool config).
After reading through the answers, I'm going to use:
(L[n:] or [somedefault])[0]
In the scikit-learn 'metrics' library there is a confusion_matrix method which gives you the desired output.
You can use any classifier that you want. Here I used the KNeighbors as example.
from sklearn import metrics, neighbors
clf = neighbors.KNeighborsClassifier()
X_test = ...
y_test = ...
expected = y_test
predicted = clf.predict(X_test)
conf_matrix = metrics.confusion_matrix(expected, predicted)
>>> print conf_matrix
>>> [[1403 87]
[ 56 3159]]
If you'd rather use xpath and that span is the only span below your div, use my example below. I'd recommend using CSS (see sircapsalot's post).
String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']//span)).getText();
css example:
String kk = wd.findElement(By.cssSelector("div[id='customSelect_3'] span[class='selectLabel clear']")).getText();
hi the fastest (but not prettiest way) i found is
while (cleantext.indexOf(" ") != -1)
cleantext = StringUtils.replace(cleantext, " ", " ");
this is running pretty fast on android in opposite to an regex
I'd like to write an extension method for EqualsIgnoreCase
public static class StringExtensions
{
public static bool? EqualsIgnoreCase(this string strA, string strB)
{
return strA?.Equals(strB, StringComparison.CurrentCultureIgnoreCase);
}
}
On CYGwin, you can install this as a typical package in the first screen. Look for
libssl-devel
The easiest way to do this is to open the database directly and use the .dump
command, rather than attaching it after invoking the SQLite 3 shell tool.
So... (assume your OS command line prompt is $) instead of $sqlite3
:
sqlite3> ATTACH database.sqlite as "attached"
From your OS command line, open the database directly:
$sqlite3 database.sqlite
sqlite3> .dump
Why not use a PdfPTable
object for this?
Create a fixed width table and use a float array to set the widths of the columns
PdfPTable table = new PdfPTable(10);
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f, 80f, 50f, 50f, 50f, 50f };
table.SetWidths(widths);
addCell(table, "SER.\nNO.", 2);
addCell(table, "TYPE OF SHIPPING", 1);
addCell(table, "ORDER NO.", 1);
addCell(table, "QTY.", 1);
addCell(table, "DISCHARGE PPORT", 1);
addCell(table, "DESCRIPTION OF GOODS", 2);
addCell(table, "LINE DOC. RECL DATE", 1);
addCell(table, "CLEARANCE DATE", 2);
addCell(table, "CUSTOM PERMIT NO.", 2);
addCell(table, "DISPATCH DATE", 2);
addCell(table, "AWB/BL NO.", 1);
addCell(table, "COMPLEX NAME", 1);
addCell(table, "G. W. Kgs.", 1);
addCell(table, "DESTINATION", 1);
addCell(table, "OWNER DOC. RECL DATE", 1);
....
private static void addCell(PdfPTable table, string text, int rowspan)
{
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
PdfPCell cell = new PdfPCell(new Phrase(text, times));
cell.Rowspan = rowspan;
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
table.AddCell(cell);
}
have a look at this tutorial too...
>>> range(6, 0, -1)
[6, 5, 4, 3, 2, 1]
You should issue HEAD requests, not GET one, because you don't need the URI contents at all. As Pies said above, you should check for status code (in 200-299 ranges, and you may optionally follow 3xx redirects).
The answers question contain a lot of code examples which may be helpful: PHP / Curl: HEAD Request takes a long time on some sites
Note: ||= does not exist. (logical or) You can use
y= y || expr; // expr is NOT evaluated if y==true
or
y = expr ? true : y; // expr is always evaluated.
False and 0 are conceptually similar, i.e. they are isomorphic. 0 is the initial value for the algebra of natural numbers, and False is the initial value for the Boolean algebra.
In other words, 0 can be defined as the number which, when added to some natural number, yields that same number:
x + 0 = x
Similarly, False is a value such that a disjunction of it and any other value is that same value:
x || False = x
Null is conceptually something totally different. Depending on the language, there are different semantics for it, but none of them describe an "initial value" as False and 0 are. There is no algebra for Null. It pertains to variables, usually to denote that the variable has no specific value in the current context. In most languages, there are no operations defined on Null, and it's an error to use Null as an operand. In some languages, there is a special value called "bottom" rather than "null", which is a placeholder for the value of a computation that does not terminate.
I've written more extensively about the implications of NULL elsewhere.
A one line solution would be:
item['key'] if 'key' in item else None
This is useful when trying to add dictionary values to a new list and want to provide a default:
eg.
row = [item['key'] if 'key' in item else 'default_value']
From the VIM Documentation
To clear the last used search pattern:
:let @/ = ""
This will not set the pattern to an empty string, because that would match everywhere. The pattern is really cleared, like when starting Vim.
Thank you. I ended up implementing your suggestions: curl -i + grep
curl -i http://google.com -L | egrep -A 10 '301 Moved Permanently|302 Found' | grep 'Location' | awk -F': ' '{print $2}' | tail -1
Returns blank if the website doesn't redirect, but that's good enough for me as it works on consecutive redirections.
Could be buggy, but at a glance it works ok.
Yaml and Json are the simplest and most commonly used file formats to store settings/config. PyYaml can be used to parse yaml. Json is already part of python from 2.5. Yaml is a superset of Json. Json will solve most uses cases except multi line strings where escaping is required. Yaml takes care of these cases too.
>>> import json
>>> config = {'handler' : 'adminhandler.py', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))
{u'handler': u'adminhandler.py', u'timeoutsec': 5}
http://phonegap.com/blog/2012/03/19/phonegap-cordova-and-whate28099s-in-a-name/
I think this url explains what you need. Phonegap is built on Apache Cordova nothing else. You can think of Apache Cordova as the engine that powers PhoneGap. Over time, the PhoneGap distribution may contain additional tools and thats why they differ in command But they do same thing.
EDIT: Extra info added as its about command difference and what phonegap can do while apache cordova can't or viceversa
First of command line option of PhoneGap
http://docs.phonegap.com/en/edge/guide_cli_index.md.html
Apache Cordova Options http://cordova.apache.org/docs/en/3.0.0/guide_cli_index.md.html#The%20Command-line%20Interface
As almost most of commands are similar. There are few differences (Note: No difference in Codebase)
Adobe can add additional features to PhoneGap so that will not be in Cordova ,Eg: Building applications remotely for that you need to have account on https://build.phonegap.com
Though For local builds phonegap cli uses cordova cli (Link to check: https://github.com/phonegap/phonegap-cli/blob/master/lib/phonegap/util/platform.js)
Platform Environment Names. Mapping:
'local' => cordova-cli
'remote' => PhoneGap/Build
Also from following repository: Modules which requires cordova are:
build
create
install
local install
local plugin add , list , remove
run
mode
platform update
run
Which dont include cordova:
remote build
remote install
remote login,logout
remote run
serve
To overcome the issue of Win7 32bit VB6, try copying from Windows Server 2003 C:\Windows\system32\
the files mscomctl.ocx
and mscomcctl.oba
.
How about this;
myImageView.image=UIImage(named: "image_1")
where image_1 is within the assets folder as image_1.png.
This worked for me since i'm using a switch case to display an image slide.
I had the same issue on my windows 10. This is what fixed my problem
bower_components
in your root folder.bowerrc
file in the root{"directory" : "public/bower_components"}
bower install
You should see bower_components folder in your public folder now
You just have to use your local (but real) IP address and port number like this:
String webServiceUrl = "http://192.168.X.X:your_virtual_server_port/your_service.php"
And make sure you did set the internet permission within the manifest
<uses-permission android:name="android.permission.INTERNET" />
I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:
This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.
Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".
So in your case the JSTL code should look like the following, note the capital 'P':
<c:if test = "${ansokanInfo.PSystem == 'NAT'}">
Excel 2003, doesn't included 1M row features, Introduced in 2007 onwards.
In Excel2007, save as "normal" Excel file, not a backwards compatible one.
You may have to close and re-open Excel to get the full 1M rows
Thilip
It is very important that AJAX requests retain session. The easiest example is when you try to do an AJAX request for the admin panel, let's say. Of course that you will protect the page that you make the request to, not to accessible by others who don't have the session you get after administrator login. Makes sense?
Please, see oficial encode()
and decode()
documentation from codecs
library. utf-8
is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1
or utf_32
.
To Update the backdrop state in Bootstrap 4.1.3 after the modal have been Display, We used the following line from Bootstrap-Modal-Wrapper plugin. Plugin Repository code reference.
$("#yourModalElement").data('bs.modal')._config.backdrop = (true : "static");
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:10];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];
Not tested in xcode though :)
I have found the answer... click on the installer and check the box "Add python to environment variables" DO NOT uninstall the old one rather click on modify....Click on link for picture...
struct point { int x, y; };
struct rect { point tl, br; }; // top left and bottom right points
// return true if rectangles overlap
bool overlap(const rect &a, const rect &b)
{
return a.tl.x <= b.br.x && a.br.x >= b.tl.x &&
a.tl.y >= b.br.y && a.br.y <= b.tl.y;
}
In elasticsearch 2.x :
vi /etc/sysconfig/elasticsearch
Go to the block of code
# Heap size defaults to 256m min, 1g max
# Set ES_HEAP_SIZE to 50% of available RAM, but no more than 31g
#ES_HEAP_SIZE=2g
Uncomment last line like
ES_HEAP_SIZE=2g
If above solutions are not working, try to change your remove git url.
git remote -v
git remote set-url origin
ssh -R youruniquesubdomain:80:localhost:3000 serveo.net
And your local environment can be accessed from https://youruniquesubdomain.serveo.net
I couldn't believe when I found this service. It offers everything and it is the easiest to use. If there would be such an easy and painless tool for every problem...
Ctrl + Break works, but only if the Build window is active. Also, interrupting the build will sometimes leave a corrupted .obj
file that will have to be manually deleted in order for the build to proceed.
writexl
, without Java requirement:
# install.packages("writexl")
library(writexl)
tempfile <- write_xlsx(iris)
Even Sebastian had given a good answer there 3 more years ago, I still would like to share a new experience here, in case you will face same problem as me in new ndk version.
I have compilation error such as:
fatal error: map: No such file or directory
fatal error: vector: No such file or directory
My environment is android-ndk-r9d and adt-bundle-linux-x86_64-20140702. I add Application.mk file in same jni folder and insert one (and only one) line:
APP_STL := stlport_static
But unfortunately, it doesn't solve my problem! I have to add these 3 lines into Android.mk to solve it:
ifndef NDK_ROOT
include external/stlport/libstlport.mk
endif
And I saw a good sharing from here that says "'stlport_shared' is preferred". So maybe it's a better solution to use stlport as a shared library instead of static. Just add the following lines into Android.mk and then no need to add file Application.mk.
ifndef NDK_ROOT
include external/stlport/libstlport.mk
endif
LOCAL_SHARED_LIBRARIES += libstlport
Hope this is helpful.
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
Another Update
Needing an answer to this question myself I looked up the node docs, seems you should not be using fs.exists, instead use fs.open and use outputted error to detect if a file does not exist:
from the docs:
fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.
In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.
Also WebClient doesn't have timeout property. And that's the problem, because dafault value is 100 seconds and that's too much to indicate if there's no Internet connection.
Workaround for that problem is here https://stackoverflow.com/a/3052637/1303422
var BlobBuilder = (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder);
can be used without the try catch.
Thankx to check_ca. Great work.
The above solution will modify the inf
s that are not in the target columns. To remedy that,
lst = [np.inf, -np.inf]
to_replace = {v: lst for v in ['col1', 'col2']}
df.replace(to_replace, np.nan)
I juste made this code, from some StackOverflow discussions. I didn't test on Linux environment yet. It is made in order to delete a file or a directory, completely :
function splRm(SplFileInfo $i)
{
$path = $i->getRealPath();
if ($i->isDir()) {
echo 'D - ' . $path . '<br />';
rmdir($path);
} elseif($i->isFile()) {
echo 'F - ' . $path . '<br />';
unlink($path);
}
}
function splRrm(SplFileInfo $j)
{
$path = $j->getRealPath();
if ($j->isDir()) {
$rdi = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
$rii = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($rii as $i) {
splRm($i);
}
}
splRm($j);
}
splRrm(new SplFileInfo(__DIR__.'/../dirOrFileName'));
In my case I mistakely imported Action into my combineEpics, rather than Epic...
Verify all the functions within combine Epics are epic funcitons
Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.
But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.
static {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
// ip address of the service URL(like.23.28.244.244)
if (hostname.equals("23.28.244.244"))
return true;
return false;
}
});
}
If you happen to be using Java 8, there is a much slicker way of achieving the same result:
static {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}
In this case a[4]
is the 5th
integer in the array a
, ap
is a pointer to integer, so you are assigning an integer to a pointer and that's the warning.
So ap
now holds 45
and when you try to de-reference it (by doing *ap
) you are trying to access a memory at address 45, which is an invalid address, so your program crashes.
You should do ap = &(a[4]);
or ap = a + 4;
In c
array names decays to pointer, so a
points to the 1st element of the array.
In this way, a
is equivalent to &(a[0])
.
How about treat the external script as a Java class? Based on this article: https://www.jmdawson.net/blog/2014/08/18/using-functions-from-one-groovy-script-in-another/
getThing.groovy The external script
def getThingList() {
return ["thing","thin2","thing3"]
}
printThing.groovy The main script
thing = new getThing() // new the class which represents the external script
println thing.getThingList()
Result
$ groovy printThing.groovy
[thing, thin2, thing3]
Try it:
int rc=dgvDataRc.CurrentCell.RowIndex;** //for find the row index number
MessageBox.Show("Current Row Index is = " + rc.ToString());
I hope it will help you.
These are few things which will help you in understanding everything... using iloc
In iloc, [initial row:ending row, initial column:ending column]
case 1: if you want only last column --- df.iloc[:,-1] & df.iloc[:,-1:]
this means that you want only the last column...
case 2: if you want all columns and all rows except the last column --- df.iloc[:,:-1]
this means that you want all columns and all rows except the last column...
case 3: if you want only last row --- df.iloc[-1:,:] & df.iloc[-1,:]
this means that you want only the last row...
case 4: if you want all columns and all rows except the last row --- df.iloc[:-1,:]
this means that you want all columns and all rows except the last column...
case 5: if you want all columns and all rows except the last row and last column --- df.iloc[:-1,:-1]
this means that you want all columns and all rows except the last column and last row...
In the AndroidManifest.xml, under the application tag, you can set the theme of your choice. To customize the theme, press Ctrl + Click
on android:theme = "@style/AppTheme"
in the Android manifest file. It will open styles.xml
file where you can change the parent attribute of the style tag.
At parent=
in styles.xml
you can browse all available styles by using auto-complete inside the ""
. E.g. try parent="Theme."
with your cursor right after the .
and then pressing Ctrl + Space
.
You can also preview themes in the preview window in Android Studio.
May be it helps.
You can
SET @somevar := '';
SELECT @somevar AS user_name FROM users WHERE (@somevar := `u_name`) = "john";
It works.
BUT MAKE SURE WHAT YOU DO!
But, may be it helps in some cases
If you are having trouble with fonts, use:
<FilesMatch "\.(ttf|ttc|otf|eot|woff)$">
<IfModule mod_headers>
Header set Access-Control-Allow-Origin "*"
</IfModule>
</FilesMatch>
My device is POSITIVO and my operational system is Ubuntu 14.04 LTS
So, my problem was in variable name
I create the file /etc/udev/rules.d/51-android.rules
and put SUBSYSTEM=="usb", SYSFS{idVendor}=="1662", MODE="0666"
I disconnected device and execute:
$ sudo udevadm control --reload-rules
$ sudo service udev restart
after this i connected the android device in developer mode again and
$ adb devices
List of devices attached
1A883XB1K device
just publish somewhere your instance of the logger. that way, the other modules and clients can use your API to get the logger without having to import multiprocessing
.
Since RxJava is a hammer and this kinda looks like a nail, you can do
Observable.from(iterable).toList().toBlocking().single();
Go to:
Settings -> Preferences You will see a dialog box. There click the Backup / Auto-completion tab where you can set the auto complete option :)
var ids = [];
$('input[id="find-table"]:checked').each(function() {
ids.push(this.value);
});
This one worked for me!
In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.
So to convert string limit="100"
to a number, you need to do
limit = int(limit) # will return new object (integer) and assign to "limit"
If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:
def int_in_place(mutable):
mutable[0] = int(mutable[0])
mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer
But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).