Excellent answer simple and accurate.
I would add a code sample.
C:\oreyes\samples\java\breakcontinue>type BreakContinue.java
class BreakContinue {
public static void main( String [] args ) {
for( int i = 0 ; i < 10 ; i++ ) {
if( i % 2 == 0) { // if pair, will jump
continue; // don't go to "System.out.print" below.
}
System.out.println("The number is " + i );
if( i == 7 ) {
break; // will end the execution, 8,9 wont be processed
}
}
}
}
C:\oreyes\samples\java\breakcontinue>java BreakContinue
The number is 1
The number is 3
The number is 5
The number is 7
I think so.. it's possible to 'bind' custom events, like(from: http://docs.jquery.com/Events/bind#typedatafn):
$("p").bind("myCustomEvent", function(e, myName, myValue){
$(this).text(myName + ", hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent", [ "John" ]);
});
I created this function that will make your life easier:
/// <summary>
/// The ultimate Path combiner of all time
/// </summary>
/// <param name="IsURL">
/// true - if the paths are Internet URLs, false - if the paths are local URLs, this is very important as this will be used to decide which separator will be used.
/// </param>
/// <param name="IsRelative">Just adds the separator at the beginning</param>
/// <param name="IsFixInternal">Fix the paths from within (by removing duplicate separators and correcting the separators)</param>
/// <param name="parts">The paths to combine</param>
/// <returns>the combined path</returns>
public static string PathCombine(bool IsURL , bool IsRelative , bool IsFixInternal , params string[] parts)
{
if (parts == null || parts.Length == 0) return string.Empty;
char separator = IsURL ? '/' : '\\';
if (parts.Length == 1 && IsFixInternal)
{
string validsingle;
if (IsURL)
{
validsingle = parts[0].Replace('\\' , '/');
}
else
{
validsingle = parts[0].Replace('/' , '\\');
}
validsingle = validsingle.Trim(separator);
return (IsRelative ? separator.ToString() : string.Empty) + validsingle;
}
string final = parts
.Aggregate
(
(string first , string second) =>
{
string validfirst;
string validsecond;
if (IsURL)
{
validfirst = first.Replace('\\' , '/');
validsecond = second.Replace('\\' , '/');
}
else
{
validfirst = first.Replace('/' , '\\');
validsecond = second.Replace('/' , '\\');
}
var prefix = string.Empty;
if (IsFixInternal)
{
if (IsURL)
{
if (validfirst.Contains("://"))
{
var tofix = validfirst.Substring(validfirst.IndexOf("://") + 3);
prefix = validfirst.Replace(tofix , string.Empty).TrimStart(separator);
var tofixlist = tofix.Split(new[] { separator } , StringSplitOptions.RemoveEmptyEntries);
validfirst = separator + string.Join(separator.ToString() , tofixlist);
}
else
{
var firstlist = validfirst.Split(new[] { separator } , StringSplitOptions.RemoveEmptyEntries);
validfirst = string.Join(separator.ToString() , firstlist);
}
var secondlist = validsecond.Split(new[] { separator } , StringSplitOptions.RemoveEmptyEntries);
validsecond = string.Join(separator.ToString() , secondlist);
}
else
{
var firstlist = validfirst.Split(new[] { separator } , StringSplitOptions.RemoveEmptyEntries);
var secondlist = validsecond.Split(new[] { separator } , StringSplitOptions.RemoveEmptyEntries);
validfirst = string.Join(separator.ToString() , firstlist);
validsecond = string.Join(separator.ToString() , secondlist);
}
}
return prefix + validfirst.Trim(separator) + separator + validsecond.Trim(separator);
}
);
return (IsRelative ? separator.ToString() : string.Empty) + final;
}
It works for URLs as well as normal paths.
Usage:
// Fixes internal paths
Console.WriteLine(PathCombine(true , true , true , @"\/\/folder 1\/\/\/\\/\folder2\///folder3\\/" , @"/\somefile.ext\/\//\"));
// Result: /folder 1/folder2/folder3/somefile.ext
// Doesn't fix internal paths
Console.WriteLine(PathCombine(true , true , false , @"\/\/folder 1\/\/\/\\/\folder2\///folder3\\/" , @"/\somefile.ext\/\//\"));
//result : /folder 1//////////folder2////folder3/somefile.ext
// Don't worry about URL prefixes when fixing internal paths
Console.WriteLine(PathCombine(true , false , true , @"/\/\/https:/\/\/\lul.com\/\/\/\\/\folder2\///folder3\\/" , @"/\somefile.ext\/\//\"));
// Result: https://lul.com/folder2/folder3/somefile.ext
Console.WriteLine(PathCombine(false , true , true , @"../../../\\..\...\./../somepath" , @"anotherpath"));
// Result: \..\..\..\..\...\.\..\somepath\anotherpath
You can add simple white space with quotes sign: {" "}
Also you can use template literals, which allow to insert, embedd expressions (code inside curly braces):
`${2 * a + b}.?!=-` // Notice this sign " ` ",its not normal quotes.
This is an example with ChartJs - 2.9.4
var maximumPoints = 5;// with this variable you can decide how many points are display on the chart
function addData(chart, label, data) {
chart.data.labels.push(label);
chart.data.datasets.forEach((dataset) => {
var d = data[0];
dataset.data.push(d);
data.shift();
});
var canRemoveData = false;
chart.data.datasets.forEach((dataset) => {
if (dataset.data.length > maximumPoints) {
if (!canRemoveData) {
canRemoveData = true;
chart.data.labels.shift();
}
dataset.data.shift();
}
});
chart.update();
}
window.onload = function () {
var canvas = document.getElementById('elm-chart'),
ctx = canvas.getContext('2d');
var myLineChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [
{
data: [],
label: 'Dataset-1',
backgroundColor: "#36a2eb88",
borderColor: "#36a2eb",
},
{
data: [],
label: 'Dataset-2',
backgroundColor: "#ff638488",
borderColor: "#ff6384",
}
],
},
options: {
responsive: false,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
var index = 0;
setInterval(function () {
var data = [];
myLineChart.data.datasets.forEach((dataset) => {
data.push(Math.random() * 100);
});
addData(myLineChart, index, data);
index++;
}, 1000);
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="elm-chart" width="640" height="480"></canvas>
_x000D_
It's possible to run application specifying package name only using monkey tool by follow this pattern:
adb shell monkey -p your.app.package.name -c android.intent.category.LAUNCHER 1
Command is used to run app using monkey tool which generates random input for application. The last part of command is integer which specify the number of generated random input for app. In this case the number is 1, which in fact is used to launch the app (icon click).
To show line numbers in the current window, go to Options
and click Show Line Numbers
.
To show them automatically, go to Options
> Configure IDLE
> General
and check the Show line numbers in new windows
box.
Unfortunately there is not an option to display line numbers in IDLE although there is an enhancement request open for this.
However, there are a couple of ways to work around this:
Under the edit menu there is a go to line option (there is a default shortcut of Alt+G for this).
There is a display at the bottom right which tells you your current line number / position on the line:
I dug myself into a slight variant on this problem by mistakenly running the setfacl
command. I ran:
sudo setfacl -m user:nginx:r /home/foo/bar
I abandoned this route in favor of adding nginx
to the foo
group, but that custom ACL was foiling nginx's attempts to access the file. I cleared it by running:
sudo setfacl -b /home/foo/bar
And then nginx was able to access the files.
1- Login as default PostgreSQL user (postgres)
sudo -u postgres -i
2- As postgres user. Add a new database user using the createuser
command
[postgres]$ createuser --interactive
3-exit
[postgres]$ exit
yes....` from Xml
android:button="@drawable/yourdrawable"
and from Java
myRadioButton.setButtonDrawable(resourceId or Drawable);
`
If you are like me and you have the same application.properties
in src/main/resources
and src/test/resources
, and you are wondering why the application.properties
in your test folder is not overriding the application.properties
in your main resources, read on...
If you have application.properties
under src/main/resources
and the same application.properties
under src/test/resources
, which application.properties
gets picked up, depends on how you are running your tests. The folder structure src/main/resources
and src/test/resources
, is a Maven architectural convention, so if you run your test like mvnw test
or even gradlew test
, the application.properties
in src/test/resources
will get picked up, as test classpath will precede main classpath. But, if you run your test like Run as JUnit Test
in Eclipse/STS, the application.properties
in src/main/resources
will get picked up, as main classpath precedes test classpath.
You can check it out by opening the menu bar Run > Run Configurations > JUnit > *your_run_configuration* > Click on "Show Command Line"
.
You will see something like this:
XXXbin\javaw.exe -ea -Dfile.encoding=UTF-8 -classpath
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\main;
XXX\workspace-spring-tool-suite-4-4.5.1.RELEASE\project_name\bin\test;
Do you see that classpath xxx\main comes first, and then xxx\test? Right, it's all about classpath :-)
Side-note: Be mindful that properties overridden in the Launch Configuration(In Spring Tool Suite IDE, for example) takes priority over application.properties.
Try this. Click anywhere in your range of data and then use this macro:
Sub CombineColumns()
Dim rng As Range
Dim iCol As Integer
Dim lastCell As Integer
Set rng = ActiveCell.CurrentRegion
lastCell = rng.Columns(1).Rows.Count + 1
For iCol = 2 To rng.Columns.Count
Range(Cells(1, iCol), Cells(rng.Columns(iCol).Rows.Count, iCol)).Cut
ActiveSheet.Paste Destination:=Cells(lastCell, 1)
lastCell = lastCell + rng.Columns(iCol).Rows.Count
Next iCol
End Sub
You have an orphaned user and this can't be remapped with ALTER USER (yet) becauses there is no login to map to. So, you need run CREATE LOGIN first.
If the database level user is
Then run ALTER USER
Edit, after comments and updates
The sid from sys.database_principals is for a Windows login.
So trying to create and re-map to a SQL Login will fail
Run this to get the Windows login
SELECT SUSER_SNAME(0x0105000000000009030000001139F53436663A4CA5B9D5D067A02390)
sed works with unicode
IFS=$'\n'
for z in $(sed 's/./&\n/g' <(printf '???')); do
echo hello: "$z"
done
outputs
hello: ?
hello: ?
hello: ?
There is an ordered set (possible new link) recipe for this which is referred to from the Python 2 Documentation. This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal set, except that initialisation should be done with a list.
OrderedSet([1, 2, 3])
This is a MutableSet, so the signature for .union
doesn't match that of set, but since it includes __or__
something similar can easily be added:
@staticmethod
def union(*sets):
union = OrderedSet()
union.union(*sets)
return union
def union(self, *sets):
for set in sets:
self |= set
Either you set LDAP_DOMAIN variable or you misconfigured it. Jump inside of ldap machine/container and run:
slapcat > backup.ldif
If it fails, check punctuation, quotes etc while you assigned variable "LDAP_DOMAIN" Otherwise you will find answer inside on backup.ldif file.
Although they vary slightly as to how they retrieve a height value, i.e some would calculate the whole element including padding, margin, scrollbar, etc and others would just calculate the element in its raw form.
You can try these ones:
javascript:
var myDiv = document.getElementById("myDiv");
myDiv.clientHeight;
myDiv.scrollHeight;
myDiv.offsetHeight;
or in jquery:
$("#myDiv").height();
$("#myDiv").innerHeight();
$("#myDiv").outerHeight();
This works for me.
@Test
public void cloneTest() {
List<Part> parts = new ArrayList<Part>();
Part part1 = new Part(1);
parts.add(part1);
Part part2 = new Part(2);
parts.add(part2);
try {
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(parts);
List<Part> cloneParts = objectMapper.readValue(jsonStr, new TypeReference<ArrayList<Part>>() {});
} catch (Exception e) {
//fail("failed.");
e.printStackTrace();
}
//TODO: Assert: compare both list values.
}
Try this query.. It uses the Analytic function SUM:
SELECT * FROM
(
SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
FROM table1 a
WHERE s_ind ='Y'
)
WHERE cnt > 2
Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1
All you have to do is:
You will be able to see historical attributions (using git blame
) and full history of changes (using git log
) for both files.
Suppose you want to create a copy of file foo
called bar
. In that case the workflow you'd use would look like this:
git mv foo bar
git commit
SAVED=`git rev-parse HEAD`
git reset --hard HEAD^
git mv foo copy
git commit
git merge $SAVED # This will generate conflicts
git commit -a # Trivially resolved like this
git mv copy foo
git commit
After you execute the above commands, you end up with a revision history that looks like this:
( revision history ) ( files )
ORIG_HEAD foo
/ \ / \
SAVED ALTERNATE bar copy
\ / \ /
MERGED bar,copy
| |
RESTORED bar,foo
When you ask Git about the history of foo
, it will:
copy
between MERGED and RESTORED,copy
came from the ALTERNATE parent of MERGED, andfoo
between ORIG_HEAD and ALTERNATE.From there it will dig into the history of foo
.
When you ask Git about the history of bar
, it will:
bar
came from the SAVED parent of MERGED, and foo
between ORIG_HEAD and SAVED.From there it will dig into the history of foo
.
It's that simple. :)
You just need to force Git into a merge situation where you can accept two traceable copies of the file(s), and we do this with a parallel move of the original (which we soon revert).
sleep 6
will sleep for 6 seconds. For a longer duration, you can also use sleep(6.minutes)
or sleep(6.hours)
.
I got around this by finding the nuget.exe and moving to an easy to type path (c:\nuget\nuget) and then calling the nuget with this path. This seems to solve the problem. c:\nuget\nuget at the package manager console works as expected. I tried to find the path that the console was using and changing the environment path but was never able to get it to work in that way.
One-liner for your problem:
data = [json.loads(line) for line in open('tweets.json', 'r')]
UPDATE: This answer was originally written in 2008 when nth-of-type
support was unreliable at best. Today I'd say you could safely use something like .bar:nth-of-type(2)
, unless you have to support IE8 and older.
Original answer from 2008 follows (Note that I would not recommend this anymore!):
If you can use Prototype JS you can use this code to set some style values, or add another classname:
// set style:
$$('div.theclassname')[1].setStyle({ backgroundColor: '#900', fontSize: '1.2em' });
// OR add class name:
$$('div.theclassname')[1].addClassName('secondclass'); // pun intentded...
(I didn't test this code, and it doesn't check if there actually is a second div present, but something like this should work.)
But if you're generating the html serverside you might just as well add an extra class on the second item...
function fetch_comments($ticket_id){
$this->db->select('tbl_tickets_replies.comments,
tbl_users.username,tbl_roles.role_name');
$this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
$this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
$this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
return $this->db->get('tbl_tickets_replies');
}
As jeb noted, the rest of the loop is skipped but evaluated, which makes the FOR
solution too slow for this purpose. An alternative:
set F=1
:nextpart
if not exist "%F%" goto :EOF
echo %F%
set /a F=%F%+1
goto nextpart
You might need to use delayed expansion and call
subroutines when using this in loops.
The very simple answer:
++++iter
The long answer:
You really should get used to writing ++iter
instead of iter++
. The latter must return (a copy of) the old value, which is different from the new value; this takes time and space.
Note that prefix increment (++iter
) takes an lvalue and returns an lvalue, whereas postfix increment (iter++
) takes an lvalue and returns an rvalue.
You have 2 options
1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.
2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"]
is set.
You can use console.dir(object)
to write that objects properties to the console.
Use: $("<p>Test</p>").prependTo(".inner");
Check out the .prepend documentation on jquery.com
Use the below if you care about shell exit statuses:
branch-current
- the current branch's namebranch-names
- clean branch names (one per line)branch-name
- Ensure that only one branch is returned from branch-names
Both branch-name
and branch-names
accept a commit as the argument, and default to HEAD
if none is given.
branch-current = "symbolic-ref --short HEAD" # https://stackoverflow.com/a/19585361/5353461
branch-names = !"[ -z \"$1\" ] && git branch-current 2>/dev/null || git branch --format='%(refname:short)' --contains \"${1:-HEAD}\" #" # https://stackoverflow.com/a/19585361/5353461
branch-name = !"br=$(git branch-names \"$1\") && case \"$br\" in *$'\\n'*) printf \"Multiple branches:\\n%s\" \"$br\">&2; exit 1;; esac; echo \"$br\" #"
% git branch-name eae13ea
master
% echo $?
0
0
.% git branch-name 4bc6188
Multiple branches:
attempt-extract
master%
% echo $?
1
1
.Because of the exit status, these can be safely built upon. For example, to get the remote used for fetching:
remote-fetch = !"branch=$(git branch-name \"$1\") && git config branch.\"$branch\".remote || echo origin #"
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
Just go to your AndroidManifest.xml file and add like below
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
then save and run your android project.
Everyone else has posted some perfectly reasonable answers. I took a different direction. Without using split, substring, or indexOf. Works great on i.e. and firefox. Probably works on Netscape too.
Just a loop and two ifs.
function getAfterDash(str) {
var dashed = false;
var result = "";
for (var i = 0, len = str.length; i < len; i++) {
if (dashed) {
result = result + str[i];
}
if (str[i] === '-') {
dashed = true;
}
}
return result;
};
console.log(getAfterDash("adfjkl-o812347"));
My solution is performant and handles edge cases.
The point of the above code was to procrastinate work, please don't actually use it.
Read and remember each line
Identify the one you want to get rid of
Forget that one
Write the rest back over the top of the file
Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?):
select *
from calls c join users u
on c.assigned_to = u.user_id
or c.requestor_id = u.user_id
where u.dept = 4
put export { Home };
at the end of the Home.js file
I've used below two scripts to do similar operations before. The first is in awk which is a lot faster than the second which is in "pure" bash. You might be able to adapt it to your own application.
awk '
{
for (i = 1; i <= NF; i++) {
s[i] = s[i]?s[i] FS $i:$i
}
}
END {
for (i in s) {
print s[i]
}
}' file.txt
declare -a arr
while IFS= read -r line
do
i=0
for word in $line
do
[[ ${arr[$i]} ]] && arr[$i]="${arr[$i]} $word" || arr[$i]=$word
((i++))
done
done < file.txt
for ((i=0; i < ${#arr[@]}; i++))
do
echo ${arr[i]}
done
This is the easiest way I found:
exec-Sync: https://github.com/jeremyfa/node-exec-sync
(Not to be confused with execSync.)
Execute shell command synchronously. Use this for migration scripts, cli programs, but not for regular server code.Example:
var execSync = require('exec-sync');
var user = execSync('echo $USER');
console.log(user);
You can use .replaceWith()
$(function() {_x000D_
_x000D_
$(".region").click(function(e) {_x000D_
e.preventDefault();_x000D_
var content = $(this).html();_x000D_
$('#map').replaceWith('<div class="region">' + content + '</div>');_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="map">_x000D_
<div class="region"><a href="link1">region1</a></div>_x000D_
<div class="region"><a href="link2">region2</a></div>_x000D_
<div class="region"><a href="link3">region3</a></div>_x000D_
</div>
_x000D_
The 2 highest upvoted answers are correct. As of today, the only thing I needed to change (from default settings) was to enable generation using dot instead of the built-in generator.
Some important notes:
html/inherits.html
or (from the website navigation) classes => class hierarchy => "Go to the textual class hierarchy".T
.
foo
inherits from T
and the T
template type parameter has a default, such default will be assumed. If there is a type bar
which inherits from foo<U>
where U
is different than the default, bar
will have a foo<U>
parent. foo<>
and bar<U>
will not have a common parent.variant
instantiation will be displayed to inherit from variant<Ts...>
.<...>
string in their name representing type and non-type parameters which did not have defaults.try this
<c:forEach items="${list}" var="map">
<tr>
<c:forEach items="${map}" var="entry">
<td>${entry.value}</td>
</c:forEach>
</tr>
</c:forEach>
You get this error when a datasource attempts to bind to data but cannot because it cannot find the connection string. In my experience, this is not usually due to an error in the web.config (though I am not 100% sure of this).
If you are programmatically assigning a datasource (such as a SqlDataSource) or creating a query (i.e. using a SqlConnection/SqlCommand combination), make sure you assigned it a ConnectionString.
var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[nameOfString].ConnectionString);
If you are hooking up a databound element to a datasource (i.e. a GridView or ComboBox to a SqlDataSource), make sure the datasource is assigned to one of your connection strings.
Post your code (for the databound element and the web.config to be safe) and we can take a look at it.
EDIT: I think the problem is that you are trying to get the Connection String from the AppSettings area, and programmatically that is not where it exists. Try replacing that with ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString
(if ConnectionString is the name of your connection string.)
Convert string value into integer list
var myString = "010";
int myInt;
List<int> B = myString.ToCharArray().Where(x => int.TryParse(x.ToString(), out myInt)).Select(x => int.Parse(x.ToString())).ToList();
I'd recommend application/octet-stream
as RFC2046 says "The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data" and "The recommended action for an implementation that receives an "application/octet-stream" entity is to simply offer to put the data in a file[...]".
I think that way you will get better handling from arbitrary programs, that might barf when encountering your unknown mime type.
Add the following to add hover effect on disabled button:
.buttonDisabled:hover
{
/*your code goes here*/
}
you can get the entire table structure using following simple command.
DESC TableName
or you can use following query.
SHOW COLUMNS FROM TableName
You can use these functions to brutally remove everything Docker related:
removecontainers() {
docker stop $(docker ps -aq)
docker rm $(docker ps -aq)
}
armageddon() {
removecontainers
docker network prune -f
docker rmi -f $(docker images --filter dangling=true -qa)
docker volume rm $(docker volume ls --filter dangling=true -q)
docker rmi -f $(docker images -qa)
}
You can add those to your ~/Xrc
file, where X is your shell interpreter (~/.bashrc
if you're using bash) file and reload them via executing source ~/Xrc
. Also, you can just copy paste them to the console and afterwards (regardless the option you took before to get the functions ready) just run:
armageddon
It's also useful for just general Docker clean up. Have in mind that this will also remove your images, not only your containers (either running or not) and your volumes of any kind.
$ git branch -D <branch-name>
[NOTE]:
-D
is a shortcut for --delete --force
.
df[df$aged <= df$laclen, ]
Should do the trick. The square brackets allow you to index based on a logical expression.
You can also use dictionaries that allows you to have more control over the plots:
import matplotlib.pyplot as plt
# plot 0 plot 1 plot 2 plot 3
x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]
plots = zip(x,y)
def loop_plot(plots):
figs={}
axs={}
for idx,plot in enumerate(plots):
figs[idx]=plt.figure()
axs[idx]=figs[idx].add_subplot(111)
axs[idx].plot(plot[0],plot[1])
return figs, axs
figs, axs = loop_plot(plots)
Now you can select the plot that you want to modify easily:
axs[0].set_title("Now I can control it!")
Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx)
or show them plt.show()
. Use the argument block=False
only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot
function or in a separate loop using the dictionaries that the function provided.
this may be also possibly solution.It some times also occurs when you keep your Development project into too deep, means may be possible project directory may have too many directories so please don't make too many directories keep it in a simple folder inside the drives. For Example- I was also getting this error when my project was kept like this-
D:\Sharad\LatestWorkings\GenericSurveyApplication020120\GenericSurveyApplication\GenericSurveyApplication
then I simply Pasted my project inside
D:\Sharad\LatestWorkings\GenericSurveyApplication
And Problem was solved.
I encountered a similar problem. I am using WinNMP. When I started it, MariaDB was also not running and prompts "Can't connect to MySQL server on '127.0.0.1' (10061) (2003)" whenever I try to connect to a database.
Just want to help. For WinNMP users like me, this worked for me:
msyqld
installer located at "C:\WinNMP\bin\MariaDB\bin"
.Hope this helps someone! :D
For me flex-box worked perfect to center the image.
this is my html-code:
<div class="img-wrapper">
<img src="..." >
</div>
and this i used for css: I wanted the Image same wide as the wrapper-element, but if the height is greater than the height of the wrapper-element it should be "cropped"/not displayed.
.img-wrapper{
width: 100%;
height: 50%;
overflow: hidden;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
img {
height: auto;
width: 100%;
}
It happens when $ret
hasn't been defined. The solution is simple. Right above $tags = get_tags();
, add the following line:
$ret = array();
You don't need HttpServletResponse to set a header on the response. You can do it using javax.ws.rs.core.Response. Just make your method to return Response instead of entity:
return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()
If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:
@Path("/resource")
class MyResource {
// one way to get HttpServletResponse
@Context
private HttpServletResponse anotherServletResponse;
// another way
Response myMethod(@Context HttpServletResponse servletResponse) {
// ... code
}
}
In Typescript use the For Each like below.
selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
{
for (var childObj in obj )
{
value.checked = parentChecked;
}
}
}
I added a ticket to add an option of some sort here:
https://github.com/pydata/pandas/issues/1450
In the meantime, result.fillna('')
should do what you want
EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values
, empty strings will stay empty strings in the result
is
compares identity. A string will never be identical to a not-string.
==
is equality. But a string will never be equal to either True
or False
.
You want neither.
path = '/bla/bla/bla'
if path:
print "True"
else:
print "False"
I've been working kind of similar to this and I have some code that might help you. The live example is here and below, is the code I'm using for you to have it as reference.
create-page.php
<?php
// Session is started.
session_start();
// Name of the template file.
$template_file = 'couples-template.php';
// Root folder if working in subdirectory. Name is up to you ut must match with server's folder.
$base_path = '/couple/';
// Path to the directory where you store the "couples-template.php" file.
$template_path = '../template/';
// Path to the directory where php will store the auto-generated couple's pages.
$couples_path = '../couples/';
// Posted data.
$data['groom-name'] = str_replace(' ', '', $_POST['groom-name']);
$data['bride-name'] = str_replace(' ', '', $_POST['bride-name']);
// $data['groom-surname'] = $_POST['groom-surname'];
// $data['bride-surname'] = $_POST['bride-surname'];
$data['wedding-date'] = $_POST['wedding-date'];
$data['email'] = $_POST['email'];
$data['code'] = str_replace(array('/', '-', ' '), '', $_POST['wedding-date']).strtoupper(substr($data['groom-name'], 0, 1)).urlencode('&').strtoupper(substr($data['bride-name'], 0, 1));
// Data array (Should match with data above's order).
$placeholders = array('{groom-name}', '{bride-name}', '{wedding-date}', '{email}', '{code}');
// Get the couples-template.php as a string.
$template = file_get_contents($template_path.$template_file);
// Fills the template.
$new_file = str_replace($placeholders, $data, $template);
// Generates couple's URL and makes it frendly and lowercase.
$couples_url = str_replace(' ', '', strtolower($data['groom-name'].'-'.$data['bride-name'].'.php'));
// Save file into couples directory.
$fp = fopen($couples_path.$couples_url, 'w');
fwrite($fp, $new_file);
fclose($fp);
// Set the variables to pass them to success page.
$_SESSION['couples_url'] = $couples_url;
// If working in root directory.
$_SESSION['couples_path'] = str_replace('.', '', $couples_path);
// If working in a sub directory.
//$_SESSION['couples_path'] = substr_replace($base_path, '', -1).str_replace('.', '',$couples_path);
header('Location: success.php');
?>
Hope this file can help and work as reference to start and boost your project.
This is more a footnote to a number of the answers above which suggest the use of ON DUPLICATE KEY UPDATE
, BEWARE that this is NOT always replication safe, so if you ever plan on growing beyond a single server, you'll want to avoid this and use two queries, one to verify the existence, and then a second to either UPDATE
when a row exists, or INSERT
when it does not.
Using .innerText
should work.
document.getElementById('lbltipAddedComment').innerText = 'your tip has been submitted!';
Quick and easy with no external tools, works well as long as the two sheets you are comparing are similar:
=if(Sheet1!A1 <> Sheet2!A1, "X", "")
in the top left cell (or equivalent: click on the actual cells to automatically have the references inserted into the formula)If the sheets are similar, this spreadsheet will be empty except for a few cells with X in them, highlighting the differences. Unzoom to 40% to quickly see what is different.
A simple way to do it would be to just annotate the Quartz Jobs with @Component
annotation, and then Spring will do all the DI magic for you, as it is now recognized as a Spring bean. I had to do something similar for an AspectJ
aspect - it was not a Spring bean until I annotated it with the Spring @Component
stereotype.
Ten years later and I had the same problem. I solved it in the following way:
That is all :)
For Grunt and Browsersync use connect-modrewrite here
var modRewrite = require('connect-modrewrite');
browserSync: {
dev: {
bsFiles: {
src: [
'app/assets/css/*.css',
'app/*.js',
'app/controllers/*.js',
'**/*.php',
'*.html',
'app/jade/includes/*.jade',
'app/views/*.html',
],
},
options: {
watchTask: true,
debugInfo: true,
logConnections: true,
server: {
baseDir :'./',
middleware: [
modRewrite(['!\.html|\.js|\.jpg|\.mp4|\.mp3|\.gif|\.svg\|.css|\.png$ /index.html [L]'])
]
},
ghostMode: {
scroll: true,
links: true,
forms: true
}
}
}
},
in header
using System.Configuration;
in code
SqlConnection conn = new SqlConnection(*ConfigurationManager.ConnectionStrings["connstrname"].ConnectionString*);
This is what worked for me.
In the Project panel, right click on the project name, and
select Open Module Settings
from the popup menu.
then change the Compile SDK Version
to the minimum version available (the minimum sdk version you set in the project).
wait for android studio to load everything.
It will give you some errors, ignore those.
Now go to your java file and android studio will suggest you import
import android.support.v4.app.FragmentActivity;
Import it, then go back to Open Module Settings
and change the compile sdk version back to what it was before.
Wait for things to load and voila.
if you're using reactive forms then you can use the following way. consider the following example.
`<p class="mr-3"> Require Shipping:
<input type="radio" class="ml-2" value="true" name="requiresShipping"
id="requiresShipping" formControlName="requiresShipping">
Yes
<input type="radio" class="ml-2" value="false" name="requiresShipping"
id="requiresShipping" formControlName="requiresShipping">
No
</p>`
`
export class ClassName implements OnInit {
public yourForm: FormGroup
constructor(
private fromBuilder: FormBuilder
) {
this.yourForm= this.fromBuilder.group({
requiresShipping: this.fromBuilder.control('true'),
})
}
}
`
now you will get the default selected radio button.
The NSLocalizedString
exists also in the Swift's world.
func NSLocalizedString(
key: String,
tableName: String? = default,
bundle: NSBundle = default,
value: String = default,
#comment: String) -> String
The tableName
, bundle
, and value
parameters are marked with a default
keyword which means we can omit these parameters while calling the function. In this case, their default values will be used.
This leads to a conclusion that the method call can be simplified to:
NSLocalizedString("key", comment: "comment")
Swift 5 - no change, still works like that.
Ensure you set SmtpClient.Credentials
after calling SmtpClient.UseDefaultCredentials = false
.
The order is important as setting SmtpClient.UseDefaultCredentials = false
will reset SmtpClient.Credentials
to null.
If you need to resume an scp transfer from local to remote, try with rsync:
rsync --partial --progress --rsh=ssh local_file user@host:remote_file
Short version, as pointed out by @aurelijus-rozenas:
rsync -P -e ssh local_file user@host:remote_file
In general the order of args for rsync is
rsync [options] SRC DEST
No, it's simply a typo, the "list" at the end must be capitalized. You can nest loops over the same variable just fine (although there's rarely a good reason to).
However, there are other problems with the code. For starters, you're iterating through lists, so i
and j
will be items not indices. Furthermore, you can't change a collection while iterating over it (well, you "can" in that it runs, but madness lies that way - for instance, you'll propably skip over items). And then there's the complexity problem, your code is O(n^2). Either convert the list into a set
and back into a list
(simple, but shuffles the remaining list items) or do something like this:
seen = set()
new_x = []
for x in xs:
if x in seen:
continue
seen.add(x)
new_xs.append(x)
Both solutions require the items to be hashable. If that's not possible, you'll probably have to stick with your current approach sans the mentioned problems.
You can process any number of threads; there is no limit. I ran the following code while watching a movie and using NetBeans, and it worked properly/without halting the machine. I think you can keep even more threads than this program does.
class A extends Thread {
public void run() {
System.out.println("**************started***************");
for(double i = 0.0; i < 500000000000000000.0; i++) {
System.gc();
System.out.println(Thread.currentThread().getName());
}
System.out.println("************************finished********************************");
}
}
public class Manager {
public static void main(String[] args) {
for(double j = 0.0; j < 50000000000.0; j++) {
A a = new A();
a.start();
}
}
}
Happens mostly when you have multiple versions of pgadmin installed or while trying to upgrade. Even I tried everything from killing the "running PID on port 5432" to "changing the server mode". In my case I uninstall postgres and re-install it again on different port(5433). Later, I opened it through cmd(right click on cmd and select "run cmd as an Administrator").
How about just using str_replace
function, if you just want to "Add Classes":
<?php
echo str_replace( '<li class="', '<li class="myclass ',
wp_nav_menu(
array(
'theme_location' => 'main_menu',
'container' => false,
'items_wrap' => '<ul>%3$s</ul>',
'depth' => 1,
'echo' => false
)
)
);
?>
Tough it is a quick fix for one-level menus or the menus that you want to add Classes to all of <li>
elements and is not recommended for more complex menus
A module in Angular 2 is something which is made from components, directives, services etc. One or many modules combine to make an Application. Modules breakup application into logical pieces of code. Each module performs a single task.
Components in Angular 2 are classes where you write your logic for the page you want to display. Components control the view (html). Components communicate with other components and services.
If the content is loaded via ajax anyway, use javascript to manipulate the placeholder. Every css approach is hack-isch anyway.
E.g. with jQuery:
$('#myFieldId').attr('placeholder', 'Search for Stuff');
The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.
The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.
The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.
Edit: Also worth a look - kashif's comment about json-streamer
and Henrik Heino's comment about bigjson
.
If you have no option to use server-side programming, such as PHP, you could use the query string, or GET parameters.
In the form, add a method="GET"
attribute:
<form action="display.html" method="GET">
<input type="text" name="serialNumber" />
<input type="submit" value="Submit" />
</form>
When they submit this form, the user will be directed to an address which includes the serialNumber
value as a parameter. Something like:
http://www.example.com/display.html?serialNumber=XYZ
You should then be able to parse the query string - which will contain the serialNumber
parameter value - from JavaScript, using the window.location.search
value:
// from display.html
document.getElementById("write").innerHTML = window.location.search; // you will have to parse
// the query string to extract the
// parameter you need
See also JavaScript query string.
The alternative is to store the values in cookies when the form is submit and read them out of the cookies again once the display.html
page loads.
See also How to use JavaScript to fill a form on another page.
There is build in forEach loop for array in ECMAScript 5th Edition.
var buttons = document.getElementsByClassName("navButton");
Array.prototype.forEach.call(buttons,function(button) {
button.setAttribute("class", "active");
button.setAttribute("src", "images/arrows/top_o.png");
});
Go to Project>Build Path>Configure Build Path>Libraries>Remove Error libraries
After Refresh project and run again program.
Add the following code to the .htaccess file:
Options +SymLinksIfOwnerMatch
RewriteEngine On
RewriteCond %{SERVER_PORT} !=443
RewriteRule ^ https://[your domain name]%{REQUEST_URI} [R,L]
Where [your domain name] is your website's domain name.
You can also redirect specific folders off of your domain name by replacing the last line of the code above with:
RewriteRule ^ https://[your domain name]/[directory name]%{REQUEST_URI} [R,L]
You cannot assign NULL
or 0
to a C++ std::string
object, because the object is not a pointer. This is one key difference from C-style strings; a C-style string can either be NULL
or a valid string, whereas C++ std::string
s always store some value.
There is no easy fix to this. If you'd like to reserve a sentinel value (say, the empty string), then you could do something like
const std::string NOT_A_STRING = "";
mValue = NOT_A_STRING;
Alternatively, you could store a pointer to a string so that you can set it to null:
std::string* mValue = NULL;
if (value) {
mValue = new std::string(value);
}
Hope this helps!
I recently had to resolve this issue and here's what I did :
First of all, this solution is around tuning Apache server.
Second main think is that there's a bug in the IE9 which means that the meta tag will not work, instead of this solution try this
uncomment/or add the following line
LoadModule headers_module modules/mod_headers.so
add the following lines
<IfModule headers_module>
Header set X-UA-Compatible: IE=EmulateIE8
</IfModule>
save/restart your Apache server,
If you need a floating random number between 13 and 20
(20-13).*rand(1) + 13
If you need an integer random number between 13 and 20
floor((21-13).*rand(1) + 13)
Note: Fix problem mentioned in comment "This excludes 20" by replacing 20 with 21
Try Case
SELECT stock.name,
CASE
WHEN stock.quantity <20 THEN 'Buy urgent'
ELSE 'There is enough'
END
FROM stock
Late answer, but currently the accepted one is at least suboptimal.
Using quotes is ALWAYS better than using any other characters to enclose %1
.
Because when %1
contains spaces or special characters like &
, the IF [%1] ==
simply stops with a syntax error.
But for the case that %1
contains quotes, like in myBatch.bat "my file.txt"
, a simple IF "%1" == ""
would fail.
But as you can't know if quotes are used or not, there is the syntax %~1
, this removes enclosing quotes when necessary.
Therefore, the code should look like
set "file1=%~1"
IF "%~1"=="" set "file1=default file"
type "%file1%" --- always enclose your variables in quotes
If you have to handle stranger and nastier arguments like myBatch.bat "This & will "^&crash
Then take a look at SO:How to receive even the strangest command line parameters?
This category offers a neat way to compare NSDates:
#import <Foundation/Foundation.h>
@interface NSDate (Compare)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date;
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date;
-(BOOL) isLaterThan:(NSDate*)date;
-(BOOL) isEarlierThan:(NSDate*)date;
//- (BOOL)isEqualToDate:(NSDate *)date; already part of the NSDate API
@end
And the implementation:
#import "NSDate+Compare.h"
@implementation NSDate (Compare)
-(BOOL) isLaterThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedAscending);
}
-(BOOL) isEarlierThanOrEqualTo:(NSDate*)date {
return !([self compare:date] == NSOrderedDescending);
}
-(BOOL) isLaterThan:(NSDate*)date {
return ([self compare:date] == NSOrderedDescending);
}
-(BOOL) isEarlierThan:(NSDate*)date {
return ([self compare:date] == NSOrderedAscending);
}
@end
Simple to use:
if([aDateYouWantToCompare isEarlierThanOrEqualTo:[NSDate date]]) // [NSDate date] is now
{
// do your thing ...
}
Also check this answer from here: Cannot manually edit applicationhost.config
The answer is simple, if not that obvious: win2008 is 64bit, notepad++ is 32bit. When you navigate to Windows\System32\inetsrv\config using explorer you are using a 64bit program to find the file. When you open the file using using notepad++ you are trying to open it using a 32bit program. The confusion occurs because, rather than telling you that this is what you are doing, windows allows you to open the file but when you save it the file's path is transparently mapped to Windows\SysWOW64\inetsrv\Config.
So in practice what happens is you open applicationhost.config using notepad++, make a change, save the file; but rather than overwriting the original you are saving a 32bit copy of it in Windows\SysWOW64\inetsrv\Config, therefore you are not making changes to the version that is actually used by IIS. If you navigate to the Windows\SysWOW64\inetsrv\Config you will find the file you just saved.
How to get around this? Simple - use a 64bit text editor, such as the normal notepad that ships with windows.
Stealth Change in VS 2010 and .NET 4.0 and Later
No public installers with the RunInstallerAttribute.Yes attribute could be found
There is an alias change or compiler cleanup in .NET that may reveal this little tweak for your specific case.
If you have the following code …
RunInstaller(true) // old alias
You may need to update it to
RunInstallerAttribute(true) // new property spelling
It is like an alias changed under the covers at compile time or at runtime and you will get this error behavior. The above explicit change to RunInstallerAttribute(true) fixed it in all of our install scenarios on all machines.
After you add project or service installer then check for the “old” RunInstaller(true) and change it to the new RunInstallerAttribute(true)
I was looking for a inline editing solution and I found a plunker that seemed promising, but it didn't work for me out of the box. After some tinkering with the code I got it working. Kudos to the person who made the initial effort to code this piece.
The example is available here http://plnkr.co/edit/EsW7mV?p=preview
Here goes the code:
app.controller('MainCtrl', function($scope) {
$scope.updateTodo = function(indx) {
console.log(indx);
};
$scope.cancelEdit = function(value) {
console.log('Canceled editing', value);
};
$scope.todos = [
{id:123, title: 'Lord of the things'},
{id:321, title: 'Hoovering heights'},
{id:231, title: 'Watership brown'}
];
});
// On esc event
app.directive('onEsc', function() {
return function(scope, elm, attr) {
elm.bind('keydown', function(e) {
if (e.keyCode === 27) {
scope.$apply(attr.onEsc);
}
});
};
});
// On enter event
app.directive('onEnter', function() {
return function(scope, elm, attr) {
elm.bind('keypress', function(e) {
if (e.keyCode === 13) {
scope.$apply(attr.onEnter);
}
});
};
});
// Inline edit directive
app.directive('inlineEdit', function($timeout) {
return {
scope: {
model: '=inlineEdit',
handleSave: '&onSave',
handleCancel: '&onCancel'
},
link: function(scope, elm, attr) {
var previousValue;
scope.edit = function() {
scope.editMode = true;
previousValue = scope.model;
$timeout(function() {
elm.find('input')[0].focus();
}, 0, false);
};
scope.save = function() {
scope.editMode = false;
scope.handleSave({value: scope.model});
};
scope.cancel = function() {
scope.editMode = false;
scope.model = previousValue;
scope.handleCancel({value: scope.model});
};
},
templateUrl: 'inline-edit.html'
};
});
Directive template:
<div>
<input type="text" on-enter="save()" on-esc="cancel()" ng-model="model" ng-show="editMode">
<button ng-click="cancel()" ng-show="editMode">cancel</button>
<button ng-click="save()" ng-show="editMode">save</button>
<span ng-mouseenter="showEdit = true" ng-mouseleave="showEdit = false">
<span ng-hide="editMode" ng-click="edit()">{{model}}</span>
<a ng-show="showEdit" ng-click="edit()">edit</a>
</span>
</div>
To use it just add water:
<div ng-repeat="todo in todos"
inline-edit="todo.title"
on-save="updateTodo($index)"
on-cancel="cancelEdit(todo.title)"></div>
UPDATE:
Another option is to use the readymade Xeditable for AngularJS:
This question was answered well at Can you encode CR/LF in into CSV files?.
Consider also reverse engineering multiple lines in Excel. To embed a newline in an Excel cell, press Alt+Enter. Then save the file as a .csv. You'll see that the double-quotes start on one line and each new line in the file is considered an embedded newline in the cell.
The accepted answer is good, but has two limitations.
It drops empty lines and lines beginning with ;
To read lines of any content, you need the delayed expansion toggling technic.
@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ text.txt"`) do (
set "var=%%a"
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
echo(!var!
ENDLOCAL
)
Findstr is used to prefix each line with the line number and a colon, so empty lines aren't empty anymore.
DelayedExpansion needs to be disabled, when accessing the %%a
parameter, else exclamation marks !
and carets ^
will be lost, as they have special meanings in that mode.
But to remove the line number from the line, the delayed expansion needs to be enabled.
set "var=!var:*:=!"
removes all up to the first colon (using delims=:
would remove also all colons at the beginning of a line, not only the one from findstr).
The endlocal disables the delayed expansion again for the next line.
The only limitation is now the line length limit of ~8191, but there seems no way to overcome this.
Sample DF:
In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
In [80]: df
Out[80]:
a b c
0 6 11 11
1 14 7 8
2 13 5 11
3 13 7 11
4 13 5 9
5 5 11 9
6 9 8 6
7 5 11 10
8 8 10 14
9 7 14 13
present only those rows where b > 10
In [81]: df[df.b > 10]
Out[81]:
a b c
0 6 11 11
5 5 11 9
7 5 11 10
9 7 14 13
Minimums (for all columns) for the rows satisfying b > 10
condition
In [82]: df[df.b > 10].min()
Out[82]:
a 5
b 11
c 9
dtype: int32
Minimum (for the b
column) for the rows satisfying b > 10
condition
In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11
UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.
Try setting a default value in the css (to let it know where you want it to start out)
position: relative;
transition: all 2s ease 0s;
top: 0; /* start out at position 0 */
A4 size is 210x297mm
So you can set the HTML page to fit those sizes with CSS:
html,body{
height:297mm;
width:210mm;
}
It is not possible to programmatically open the permission screen. Instead, we can open the app settings screen.
Code
Intent i = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID));
startActivity(i);
Sample Output
I think that this should work:
.element {
-webkit-transition: all .3s;
-moz-transition: all .3s;
-o-transition: all .3s;
transition: all .3s;
}
This error is coming because existing value is getting updated immediately after getting initialized. So if you will update new value after existing value is rendered in DOM, Then it will work fine.Like mentioned in this article Angular Debugging "Expression has changed after it was checked"
for example you can use
ngOnInit() {
setTimeout(() => {
//code for your new value.
});
}
or
ngAfterViewInit() {
this.paginator.page
.pipe(
startWith(null),
delay(0),
tap(() => this.dataSource.loadLessons(...))
).subscribe();
}
As you can see i have not mentioned time in setTimeout method. As it is browser provided API, not a JavaScript API, So this will run seperately in browser stack and will wait till call stack items are finished.
How browser API envokes concept is explained by Philip Roberts in one of Youtube video(What the hack is event loop?).
That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.
This code (example) :
Chronology ch1 = GregorianChronology.getInstance(); Chronology ch2 = ISOChronology.getInstance(); DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1); DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2); System.out.println(dt); System.out.println(dt2); boolean b = dt.equals(dt2); System.out.println(b);
Will print :
2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false
You are probably comparing two DateTimes with same date but different Chronology.
There is a way to get count of runes without any packages by converting string to []rune as len([]rune(YOUR_STRING))
:
package main
import "fmt"
func main() {
russian := "??????? ? ??????"
english := "Sputnik & pogrom"
fmt.Println("count of bytes:",
len(russian),
len(english))
fmt.Println("count of runes:",
len([]rune(russian)),
len([]rune(english)))
}
count of bytes 30 16
count of runes 16 16
I'd like to extend the paulalexandru's answer and put here complete solution that works generally with bootstrap dropdowns and updating main button's content and also the value from selected option.
The bootstrap dropdown is defined this way:
<div class="btn-group" role="group">
<button type="button" data-toggle="dropdown" value="1" class="btn btn-default btn-sm dropdown-toggle">
Option 1 <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="#" data-value="1">Option 1</a></li>
<li><a href="#" data-value="2">Option 2</a></li>
<li><a href="#" data-value="3">Option 3</a></li>
</ul>
</div>
Additional to standard bootstrap dropdown code, there is data-value
attribute for storing the values in every dropdown option (in <a>
element).
Now the JS code. I crated function that handle the dropdowns:
function dropdownToggle() {
// select the main dropdown button element
var dropdown = $(this).parent().parent().prev();
// change the CONTENT of the button based on the content of selected option
dropdown.html($(this).html() + ' </i><span class="caret"></span>');
// change the VALUE of the button based on the data-value property of selected option
dropdown.val($(this).prop('data-value'));
}
And of course we need to add event listener:
$(document).ready(function(){
$('.dropdown-menu a').on('click', dropdownToggle);
}
You need to annotate your Customer class with @Named or @Model annotation:
package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
private String email;
private String password;
}
or create/modify beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
Just add box-sizing:
input[type="text"] {
box-sizing: border-box;
}
In the System.pas (which automatically gets used) the following is defined:
const
sLineBreak = {$IFDEF LINUX} AnsiChar(#10) {$ENDIF}
{$IFDEF MSWINDOWS} AnsiString(#13#10) {$ENDIF};
This is from Delphi 2009 (notice the use of AnsiChar and AnsiString). (Line wrap added by me.)
So if you want to make your TLabel wrap, make sure AutoSize is set to true, and then use the following code:
label1.Caption := 'Line one'+sLineBreak+'Line two';
Works in all versions of Delphi since sLineBreak was introduced, which I believe was Delphi 6.
this worked for me:
ProxyRequests Off
ProxyPreserveHost On
RewriteEngine On
<Proxy http://localhost:8123>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /node http://localhost:8123
ProxyPassReverse /node http://localhost:8123
You need to run Application.run()
because this method starts whole Spring Framework. Code below integrates your main()
with Spring Boot.
Application.java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
ReconTool.java
@Component
public class ReconTool implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
main(args);
}
public static void main(String[] args) {
// Recon Logic
}
}
SpringApplication.run(ReconTool.class, args)
Because this way spring is not fully configured (no component scan etc.). Only bean defined in run() is created (ReconTool).
Example project: https://github.com/mariuszs/spring-run-magic
window.oncontextmenu = function () {
return false;
}
might help you.
Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.
Based on my personal experience with this knowledge base software, I would also like to join 'Julien H.' in suggesting PHPKB from http://www.knowledgebase-script.com
Personally I believe its one of the best. Many features, continously developed, excellent support & the GUI is just simple & great.
Starx's solution was extremely helpful to me. But I had some problems when I tried to implement a vertical scrolling sidebar with it. Here was my initial code, based on what Starx wrote:
function fix_vertical_scroll(id) {
$(window).scroll(function(){
$(id).css({
'top': $(this).scrollTop() //Use it later
});
});
}
It's slightly different from Starx's solution, because I think his code is designed to allow a menu to float horizontally instead of vertically. But that's just an aside. The problem I had with the above code is that in a lot of browsers, or depending on the resource load of the computer, the menu movements would be choppy, whereas the initial css solution was nice and smooth. I attribute this to browsers being slower at firing javascript events than at implementing css.
My alternate solution to this choppiness problem is set the frame to fixed instead of absolute, then cancel out the horizontal movements using starx's method.
function float_horizontal_scroll(id) {
jQuery(window).scroll(function(){
jQuery(id).css({
'left': 0 - jQuery(this).scrollLeft()
});
});
}
#leftframe {
position:fixed;
width: 200;
}
You might say all I'm doing is trading vertical scrolling choppiness for horizontal scrolling choppiness. But the thing is, 99% of scrolling is vertical, and it's much more annoying when that is choppy than when horizontal scrolling is.
Here's my related post on this matter, if I haven't already exhausted everyone's patience: Fixing a menu in one direction in jquery
Please try CURRENT_TIME()
or now()
functions
"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"
OR
"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"
OR you could try with PHP date
function here:
$date = date("Y-m-d H:i:s");
No that would still produce the right value because you must define the array to be either all elements of a single type or pointers to a type. In either case the array size is known at compile time so sizeof(arr) / sizeof(arr[0]) always returns the element count.
Here is an example of how to use this correctly:
int nonDynamicArray[ 4 ];
#define nonDynamicArrayElementCount ( sizeof(nonDynamicArray) / sizeof(nonDynamicArray[ 0 ]) )
I'll go one further here to show when to use this properly. You won't use it very often. It is primarily useful when you want to define an array specifically so you can add elements to it without changing a lot of code later. It is a construct that is primarily useful for maintenance. The canonical example (when I think about it anyway ;-) is building a table of commands for some program that you intend to add more commands to later. In this example to maintain/improve your program all you need to do is add another command to the array and then add the command handler:
char *commands[] = { // <--- note intentional lack of explicit array size
"open",
"close",
"abort",
"crash"
};
#define kCommandsCount ( sizeof(commands) / sizeof(commands[ 0 ]) )
void processCommand( char *command ) {
int i;
for ( i = 0; i < kCommandsCount; ++i ) {
// if command == commands[ i ] do something (be sure to compare full string)
}
}
Using find
, xargs
and sed
:
find . -name "fgh*" -type f -print0 | xargs -0 -I {} sh -c 'mv "{}" "$(dirname "{}")/`echo $(basename "{}") | sed 's/^fgh/jkl/g'`"'
It's more complex than @nik's solution but it allows to rename files recursively. For instance, the structure,
.
+-- fghdir
¦ +-- fdhfilea
¦ +-- fghfilea
+-- fghfile\ e
+-- fghfilea
+-- fghfileb
+-- fghfilec
+-- other
+-- fghfile\ e
+-- fghfilea
+-- fghfileb
+-- fghfilec
would be transformed to this,
.
+-- fghdir
¦ +-- fdhfilea
¦ +-- jklfilea
+-- jklfile\ e
+-- jklfilea
+-- jklfileb
+-- jklfilec
+-- other
+-- jklfile\ e
+-- jklfilea
+-- jklfileb
+-- jklfilec
The key to make it work with xargs
is to invoke the shell from xargs.
In scala implicit works as:
Converter
Parameter value injector
Extension method
There are 3 types of use of Implicit
Implicitly type conversion : It converts the error producing assignment into intended type
val x :String = "1"
val y:Int = x
String is not the sub type of Int , so error happens in line 2. To resolve the error the compiler will look for such a method in the scope which has implicit keyword and takes a String as argument and returns an Int .
so
implicit def z(a:String):Int = 2
val x :String = "1"
val y:Int = x // compiler will use z here like val y:Int=z(x)
println(y) // result 2 & no error!
Implicitly receiver conversion: We generally by receiver call object's properties, eg. methods or variables . So to call any property by a receiver the property must be the member of that receiver's class/object.
class Mahadi{
val haveCar:String ="BMW"
}
class Johnny{
val haveTv:String = "Sony"
}
val mahadi = new Mahadi
mahadi.haveTv // Error happening
Here mahadi.haveTv will produce an error. Because scala compiler will first look for the haveTv property to mahadi receiver. It will not find. Second it will look for a method in scope having implicit keyword which take Mahadi object as argument and returns Johnny object. But it does not have here. So it will create error. But the following is okay.
class Mahadi{
val haveCar:String ="BMW"
}
class Johnny{
val haveTv:String = "Sony"
}
val mahadi = new Mahadi
implicit def z(a:Mahadi):Johnny = new Johnny
mahadi.haveTv // compiler will use z here like new Johnny().haveTv
println(mahadi.haveTv)// result Sony & no error
Implicitly parameter injection: If we call a method and do not pass its parameter value, it will cause an error. The scala compiler works like this - first will try to pass value, but it will get no direct value for the parameter.
def x(a:Int)= a
x // ERROR happening
Second if the parameter has any implicit keyword it will look for any val in the scope which have the same type of value. If not get it will cause error.
def x(implicit a:Int)= a
x // error happening here
To slove this problem compiler will look for a implicit val having the type of Int because the parameter a has implicit keyword.
def x(implicit a:Int)=a
implicit val z:Int =10
x // compiler will use implicit like this x(z)
println(x) // will result 10 & no error.
Another example:
def l(implicit b:Int)
def x(implicit a:Int)= l(a)
we can also write it like-
def x(implicit a:Int)= l
Because l has a implicit parameter and in scope of method x's body, there is an implicit local variable(parameters are local variables) a which is the parameter of x, so in the body of x method the method-signature l's implicit argument value is filed by the x method's local implicit variable(parameter) a
implicitly.
So
def x(implicit a:Int)= l
will be in compiler like this
def x(implicit a:Int)= l(a)
Another example:
def c(implicit k:Int):String = k.toString
def x(a:Int => String):String =a
x{
x => c
}
it will cause error, because c in x{x=>c} needs explicitly-value-passing in argument or implicit val in scope.
So we can make the function literal's parameter explicitly implicit when we call the method x
x{
implicit x => c // the compiler will set the parameter of c like this c(x)
}
This has been used in action method of Play-Framework
in view folder of app the template is declared like
@()(implicit requestHreader:RequestHeader)
in controller action is like
def index = Action{
implicit request =>
Ok(views.html.formpage())
}
if you do not mention request parameter as implicit explicitly then you must have been written-
def index = Action{
request =>
Ok(views.html.formpage()(request))
}
Think, we want to add new method with Integer object. The name of the method will be meterToCm,
> 1 .meterToCm
res0 100
to do this we need to create an implicit class within a object/class/trait . This class can not be a case class.
object Extensions{
implicit class MeterToCm(meter:Int){
def meterToCm={
meter*100
}
}
}
Note the implicit class will only take one constructor parameter.
Now import the implicit class in the scope you are wanting to use
import Extensions._
2.meterToCm // result 200
Another way is to use box-shadow
:
#mybox {
box-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
-moz-box-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
-webkit-shadow:
0 0 0 1px #CCC,
0 0 0 2px #888,
0 0 0 3px #444,
0 0 0 4px #000;
}
<div id="mybox">ABC</div>
See example here.
Modify your constructor to the following so that it calls the base class constructor properly:
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message, string extrainfo) : base(message)
{
//other stuff here
}
}
Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.
If you want to use the same library folder for several projects, you can reference it in gradle to an external location like this:
settings.gradle:
include 'app', ':volley'
project(':volley').projectDir = new File('../libraries/volley')
in your app build.gradle
dependencies {
...
compile project(':volley')
...}
echo
adds spaces between the arguments passed to it. $text
is subject to variable expansion and word splitting, so your echo
command is equivalent to:
echo -e "this" "is" "line" "one\n" "this" "is" "line" "two\n" ...
You can see that a space will be added before "this". You can either remove the newline characters, and quote $text
to preserve the newlines:
text="this is line one
this is line two
this is line three"
echo "$text" > filename
Or you could use printf
, which is more robust and portable than echo
:
printf "%s\n" "this is line one" "this is line two" "this is line three" > filename
In bash
, which supports brace expansion, you could even do:
printf "%s\n" "this is line "{one,two,three} > filename
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
It is also possible to use enumeration.
typedef enum {
typeNo1 = 1,
typeNo2,
typeNo3,
typeNo4,
NumOfTypes = typeNo4
} TypeOfSomething;
yes stale element error is thrown when (taking your scenario) you have defined locator strategy to click on 'Add Item' first and then when you close the pop up the page gets refreshed hence the reference defined for 'Add Item' is lost in the memory so to overcome this you have to redefine the locator strategy for 'Add Item' again
understand it with a dummy code
// clicking on view details
driver.findElement(By.id("")).click();
// closing the pop up
driver.findElement(By.id("")).click();
// and when you try to click on Add Item
driver.findElement(By.id("")).click();
// you get stale element exception as reference to add item is lost
// so to overcome this you have to re identify the locator strategy for add item
// Please note : this is one of the way to overcome stale element exception
// Step 1 please add a universal wait in your script like below
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // just after you have initiated browser
Modulus operator gives you the result in 'reduced residue system'. For example for mod 5 there are 5 integers counted: 0,1,2,3,4. In fact 19=12=5=-2=-9 (mod 7). The main difference that the answer is given by programming languages by 'reduced residue system'.
add this to ~/.bashrc:
function mkfile() {
mkdir -p "$1" && touch "$1"/"$2"
}
save and then to make it available without a reboot or logout execute: $ source ~/.bashrc
or you can just do:
$ mkdir folder && touch $_/file.txt
note that $_ = folder
If your other class inherits Form1 and if your textBox1 is declared public, then you can access that text box from your other class by simply calling:
otherClassInstance.textBox1.Text = "hello world";
I think it's worth pointing out that there can be some unexpected behaviour here if you don't thoroughly understand how PRIMARY KEY and UNIQUE interact.
As an example, if you want to insert a record only if the NAME field isn't currently taken, and if it is, you want a constraint exception to fire to tell you, then INSERT OR REPLACE will not throw and exception and instead will resolve the UNIQUE constraint itself by replacing the conflicting record (the existing record with the same NAME). Gaspard's demonstrates this really well in his answer above.
If you want a constraint exception to fire, you have to use an INSERT statement, and rely on a separate UPDATE command to update the record once you know the name isn't taken.
normaly is better image store in public folder (because it has write permission already that you can use when I upload images to it)
public
upload_media
photos
image.png
$image = public_path() . '/upload_media/photos/image.png'; // destination path
view PHP
<img src="<?= $image ?>">
View blade
<img src="{{ $image }}">
You can add Connection Timeout=180;
to your connection string
There is one little catch with the third approach. Since aggregate POMs (myproject/pom.xml) usually don't have parent at all, they do not share configuration. That means all those aggregate POMs will have only default repositories.
That is not a problem if you only use plugins from Central, however, this will fail if you run plugin using the plugin:goal format from your internal repository. For example, you can have foo-maven-plugin
with the groupId of org.example
providing goal generate-foo
. If you try to run it from the project root using command like mvn org.example:foo-maven-plugin:generate-foo
, it will fail to run on the aggregate modules (see compatibility note).
Several solutions are possible:
if you are using localhost database, try port 3306
Active and passive are the two modes that FTP can run in.
For background, FTP actually uses two channels between client and server, the command and data channels, which are actually separate TCP connections.
The command channel is for commands and responses while the data channel is for actually transferring files.
This separation of command information and data into separate channels a nifty way of being able to send commands to the server without having to wait for the current data transfer to finish. As per the RFC, this is only mandated for a subset of commands, such as quitting, aborting the current transfer, and getting the status.
In active mode, the client establishes the command channel but the server is responsible for establishing the data channel. This can actually be a problem if, for example, the client machine is protected by firewalls and will not allow unauthorised session requests from external parties.
In passive mode, the client establishes both channels. We already know it establishes the command channel in active mode and it does the same here.
However, it then requests the server (on the command channel) to start listening on a port (at the servers discretion) rather than trying to establish a connection back to the client.
As part of this, the server also returns to the client the port number it has selected to listen on, so that the client knows how to connect to it.
Once the client knows that, it can then successfully create the data channel and continue.
More details are available in the RFC: https://www.ietf.org/rfc/rfc959.txt
You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.
How do I wrap this line of text
- asked by Peter 2 days ago
If your example represents your real code, the problem is not in the push
, it's that your constructor doesn't do anything.
You need to declare and initialize the x
and y
members.
Explicitly:
export class Pixel {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
Or implicitly:
export class Pixel {
constructor(public x: number, public y: number) {}
}
When your second thread is non-Daemon, your application's primary main thread cannot quit because its exit criteria is being tied to the exit also of non-Daemon thread(s). Threads cannot be forcibly killed in python, therefore your app will have to really wait for the non-Daemon thread(s) to exit. If this behavior is not what you want, then set your second thread as daemon so that it won't hold back your application from exiting.
Some of you might find this useful. Just copy paste it to your page and you will get a sequence in which events are fired in the Chrome console (Ctrl + Shift + I).
$(document).on('pagebeforecreate',function(){console.log('pagebeforecreate');});
$(document).on('pagecreate',function(){console.log('pagecreate');});
$(document).on('pageinit',function(){console.log('pageinit');});
$(document).on('pagebeforehide',function(){console.log('pagebeforehide');});
$(document).on('pagebeforeshow',function(){console.log('pagebeforeshow');});
$(document).on('pageremove',function(){console.log('pageremove');});
$(document).on('pageshow',function(){console.log('pageshow');});
$(document).on('pagehide',function(){console.log('pagehide');});
$(window).load(function () {console.log("window loaded");});
$(window).unload(function () {console.log("window unloaded");});
$(function () {console.log('document ready');});
You are not going see unload in the console as it is fired when the page is being unloaded (when you move away from the page). Use it like this:
$(window).unload(function () { debugger; console.log("window unloaded");});
And you will see what I mean.
The RequestDispatcher
interface allows you to do a server side forward/include whereas sendRedirect()
does a client side redirect. In a client side redirect, the server will send back an HTTP status code of 302
(temporary redirect) which causes the web browser to issue a brand new HTTP GET
request for the content at the redirected location. In contrast, when using the RequestDispatcher
interface, the include/forward to the new resource is handled entirely on the server side.
Editted:
In order to flex only the center text, a different approach can be taken - Unflex the other views.
alignItems : 'center'
from containeralignSelf:'center'
to the textviews that you don't want to flexYou can wrap the Text component in a View component and give the View a flex of 1.
The flex will give :
100% width if the flexDirection:'row'
in styles.container
100% height if the flexDirection:'column'
in styles.container
It is a good practice to set where the access log should be in nginx configuring file . Using acces_log /path/ Like this.
keyval $remote_addr:$http_user_agent $seen zone=clients;
server { listen 443 ssl;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
if ($seen = "") {
set $seen 1;
set $logme 1;
}
access_log /tmp/sslparams.log sslparams if=$logme;
error_log /pathtolog/error.log;
# ...
}
function printResult() {
var DocumentContainer = document.getElementById('your_div_id');
var WindowObject = window.open('', "PrintWindow", "width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
Warning:
mysql_*
extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
Whenever possible, importing a file to MySQL should be delegated to MySQL client.
the answer from Raj is useful, but (because of file($filename)) it will fail if your mysql-dump not fits in memory
If you are on shared hosting and there are limitations like 30 MB and 12s Script runtime and you have to restore a x00MB mysql dump, you can use this script:
it will walk the dumpfile query for query, if the script execution deadline is near, it saves the current fileposition in a tmp file and a automatic browser reload will continue this process again and again ... If an error occurs, the reload will stop and an the error is shown ...
if you comeback from lunch your db will be restored ;-)
the noLimitDumpRestore.php:
// your config
$filename = 'yourGigaByteDump.sql';
$dbHost = 'localhost';
$dbUser = 'user';
$dbPass = '__pass__';
$dbName = 'dbname';
$maxRuntime = 8; // less then your max script execution limit
$deadline = time()+$maxRuntime;
$progressFilename = $filename.'_filepointer'; // tmp file for progress
$errorFilename = $filename.'_error'; // tmp file for erro
mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());
($fp = fopen($filename, 'r')) OR die('failed to open file:'.$filename);
// check for previous error
if( file_exists($errorFilename) ){
die('<pre> previous error: '.file_get_contents($errorFilename));
}
// activate automatic reload in browser
echo '<html><head> <meta http-equiv="refresh" content="'.($maxRuntime+2).'"><pre>';
// go to previous file position
$filePosition = 0;
if( file_exists($progressFilename) ){
$filePosition = file_get_contents($progressFilename);
fseek($fp, $filePosition);
}
$queryCount = 0;
$query = '';
while( $deadline>time() AND ($line=fgets($fp, 1024000)) ){
if(substr($line,0,2)=='--' OR trim($line)=='' ){
continue;
}
$query .= $line;
if( substr(trim($query),-1)==';' ){
if( !mysql_query($query) ){
$error = 'Error performing query \'<strong>' . $query . '\': ' . mysql_error();
file_put_contents($errorFilename, $error."\n");
exit;
}
$query = '';
file_put_contents($progressFilename, ftell($fp)); // save the current file position for
$queryCount++;
}
}
if( feof($fp) ){
echo 'dump successfully restored!';
}else{
echo ftell($fp).'/'.filesize($filename).' '.(round(ftell($fp)/filesize($filename), 2)*100).'%'."\n";
echo $queryCount.' queries processed! please reload or wait for automatic browser refresh!';
}
You don't need to give local path. just give cdn link of bootstrap datetimepicker. and it works.
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class='col-sm-6'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<script type="text/javascript">_x000D_
$(function () {_x000D_
$('#datetimepicker').datepicker();_x000D_
});_x000D_
</script>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
You will need to use reflection to get the type "TestRunner". Use the Assembly.GetType method.
class Program
{
static void Main(string[] args)
{
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
var obj = (TestRunner)Activator.CreateInstance(type);
obj.Run();
}
}
@S-Lott gives the right procedure, but expanding on the Unicode issues, the Python interpreter can provide more insights.
Jon Skeet is right (unusual) about the codecs
module - it contains byte strings:
>>> import codecs
>>> codecs.BOM
'\xff\xfe'
>>> codecs.BOM_UTF8
'\xef\xbb\xbf'
>>>
Picking another nit, the BOM
has a standard Unicode name, and it can be entered as:
>>> bom= u"\N{ZERO WIDTH NO-BREAK SPACE}"
>>> bom
u'\ufeff'
It is also accessible via unicodedata
:
>>> import unicodedata
>>> unicodedata.lookup('ZERO WIDTH NO-BREAK SPACE')
u'\ufeff'
>>>
One of the things that can bite you is if you are using .onmousedown
as your user interaction; when you do that, and then an attempt is immediately made to select a field, it won't happen, because the mouse is being held down on something else. So change to .onmouseup
and viola, now focus()
works, because the mouse is in an un-clicked state when the attempt to change focus is made.
You can use the a stringstream from the C++ standard libraray:
stringstream ss(str);
int x;
ss >> x;
if(ss) { // <-- error handling
// use x
} else {
// not a number
}
The stream state will be set to fail if a non-digit is encountered when trying to read an integer.
See Stream pitfalls for pitfalls of errorhandling and streams in C++.
You need to modify AndroidManifest.xml as Intrications (previously Ashton) mentioned and make sure the activity handles the onConfigurationChanged event as you want it handled. This is how it should look:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
<select id="ddlViewBy">
<option value="value">text</option>
</select>
JQuery
var txt = $("#ddlViewBy option:selected").text();
var val = $("#ddlViewBy option:selected").val();
You can add the following in your .bashrc
if [ "$TERM" = xterm ]; then TERM=xterm-256color; fi
You need to add annotations to the Junit class, telling it to use the SpringJunitRunner. The ones you want are:
@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)
This tells Junit to use the test-context.xml file in same directory as your test. This file should be similar to the real context.xml you're using for spring, but pointing to test resources, naturally.
You can't mix in stored procedures with ordinary SQL, whilst with stored function you can.
e.g. SELECT get_foo(myColumn) FROM mytable
is not valid if get_foo()
is a procedure, but you can do that if get_foo()
is a function. The price is that functions have more limitations than a procedure.
Error jet 4 oledb It Can be possible upgrade kb4041678 kb4041681
Eclipse wouldn't let me point to an existing (or add a new) source directory. Eclipse's configuration files can be wonky. In my case I should have started simple. Right click the project and click Refresh.
If you want to do it without a forked command:
tee <inputfile file2 file3 file4 ... >/dev/null
mysqlcheck -r -f -uroot -p --use_frm db_name
will normally do the trick
In XML 1.0, the XML Declaration is optional. See section 2.8 of the XML 1.0 Recommendation, where it says it "should" be used -- which means it is recommended, but not mandatory. In XML 1.1, however, the declaration is mandatory. See section 2.8 of the XML 1.1 Recommendation, where it says "MUST" be used. It even goes on to state that if the declaration is absent, that automatically implies the document is an XML 1.0 document.
Note that in an XML Declaration the encoding
and standalone
are both optional. Only the version
is mandatory. Also, these are not attributes, so if they are present they must be in that order: version
, followed by any encoding
, followed by any standalone
.
<?xml version="1.0"?>
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" standalone="yes"?>
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
If you don't specify the encoding in this way, XML parsers try to guess what encoding is being used. The XML 1.0 Recommendation describes one possible way character encoding can be autodetected. In practice, this is not much of a problem if the input is encoded as UTF-8, UTF-16 or US-ASCII. Autodetection doesn't work when it encounters 8-bit encodings that use characters outside the US-ASCII range (e.g. ISO 8859-1) -- avoid creating these if you can.
The standalone
indicates whether the XML document can be correctly processed without the DTD or not. People rarely use it. These days, it is a bad to design an XML format that is missing information without its DTD.
Update:
A "prolog error/invalid utf-8 encoding" error indicates that the actual data the parser found inside the file did not match the encoding that the XML declaration says it is. Or in some cases the data inside the file did not match the autodetected encoding.
Since your file contains a byte-order-mark (BOM) it should be in UTF-16 encoding. I suspect that your declaration says <?xml version="1.0" encoding="UTF-8"?>
which is obviously incorrect when the file has been changed into UTF-16 by NotePad. The simple solution is to remove the encoding
and simply say <?xml version="1.0"?>
. You could also edit it to say encoding="UTF-16"
but that would be wrong for the original file (which wasn't in UTF-16) or if the file somehow gets changed back to UTF-8 or some other encoding.
Don't bother trying to remove the BOM -- that's not the cause of the problem. Using NotePad or WordPad to edit XML is the real problem!
Use int()
on a boolean test:
x = int(x == 'true')
int()
turns the boolean into 1
or 0
. Note that any value not equal to 'true'
will result in 0
being returned.
I had to fix this problem with pulling from the remote repo and deal with the merge conflicts that arose, commit and then push. But I feel like there is a better way.
Finally, I got a solution for reloading page once after two months research.
It works fine on my clientside JS project.
I wrote a function that below reloading page only once.
1) First getting browser domloading time
2) Get current timestamp
3) Browser domloading time + 10 seconds
4) If Browser domloading time + 10 seconds bigger than current now timestamp then page is able to be refreshed via "reloadPage();"
But if it's not bigger than 10 seconds that means page is just reloaded thus It will not be reloaded repeatedly.
5) Therefore if you call "reloadPage();" function in somewhere in your js file page will only be reloaded once.
Hope that helps somebody
// Reload Page Function //
function reloadPage() {
var currentDocumentTimestamp = new Date(performance.timing.domLoading).getTime();
// Current Time //
var now = Date.now();
// Total Process Lenght as Minutes //
var tenSec = 10 * 1000;
// End Time of Process //
var plusTenSec = currentDocumentTimestamp + tenSec;
if (now > plusTenSec) {
location.reload();
}
}
// You can call it in somewhere //
reloadPage();
You never mention what object you are inspecting, and since you are rejecting ones that reference a given object, I will assume you mean a static one.
using System.Reflection;
public object GetPropValue(string prop)
{
int splitPoint = prop.LastIndexOf('.');
Type type = Assembly.GetEntryAssembly().GetType(prop.Substring(0, splitPoint));
object obj = null;
return type.GetProperty(prop.Substring(splitPoint + 1)).GetValue(obj, null);
}
Note that I marked the object that is being inspected with the local variable obj
. null
means static, otherwise set it to what you want. Also note that the GetEntryAssembly()
is one of a few available methods to get the "running" assembly, you may want to play around with it if you are having a hard time loading the type.
The accepted answer is correct, but there is a more clever/efficient way to do this if you need to convert a whole bunch of ASCII characters to their ASCII codes at once. Instead of doing:
for ch in mystr:
code = ord(ch)
or the slightly faster:
for code in map(ord, mystr):
you convert to Python native types that iterate the codes directly. On Python 3, it's trivial:
for code in mystr.encode('ascii'):
and on Python 2.6/2.7, it's only slightly more involved because it doesn't have a Py3 style bytes
object (bytes
is an alias for str
, which iterates by character), but they do have bytearray
:
# If mystr is definitely str, not unicode
for code in bytearray(mystr):
# If mystr could be either str or unicode
for code in bytearray(mystr, 'ascii'):
Encoding as a type that natively iterates by ordinal means the conversion goes much faster; in local tests on both Py2.7 and Py3.5, iterating a str
to get its ASCII codes using map(ord, mystr)
starts off taking about twice as long for a len
10 str
than using bytearray(mystr)
on Py2 or mystr.encode('ascii')
on Py3, and as the str
gets longer, the multiplier paid for map(ord, mystr)
rises to ~6.5x-7x.
The only downside is that the conversion is all at once, so your first result might take a little longer, and a truly enormous str
would have a proportionately large temporary bytes
/bytearray
, but unless this forces you into page thrashing, this isn't likely to matter.
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
this example, I am assuming that all your image files begin with "IMG" and you want to replace "IMG" with "VACATION"
solution : first identified all jpg files and then replace keyword
find . -name '*jpg' -exec bash -c 'echo mv $0 ${0/IMG/VACATION}' {} \;
Could you add z-index style to the two sections so that the one you want appears on top?
I wanted to have a predefined text("No Labs Available") to be displayed if the value was null or empty and my friend helped me with this:
StrengthInfo = CASE WHEN ((SELECT COUNT(UnitsOrdered) FROM [Data_Sub_orders].[dbo].[Snappy_Orders_Sub] WHERE IdPatient = @PatientId and IdDrugService = 226)> 0)
THEN cast((S.UnitsOrdered) as varchar(50))
ELSE 'No Labs Available'
END
1: Get Timings. Until you know where the slowdown is, the question is too broad to answer. A project I'm working on has this precise problem; There's no logging to even know how long certain things take; we can only guess as to the slow parts of the app until we add timings to the project.
2: If you have sequential operations, Don't be afraid to lightly multithread. ESPECIALLY if blocking operations are involved. PLINQ is your friend here.
3: Pregenerate your MVC Views when Publishing... That will help with some of the 'first page hit'
4: Some argue for the stored procedure/ADO advantages of speed. Others argue for speed of development of EF and a more clear seprataion of tiers and their purpose. I've seen really slow designs when SQL and the workarounds to use Sprocs/Views for data retrieval and storage. Also, your difficulty to test goes up. Our current codebase that we are converting from ADO to EF is not performing any worse (and in some cases better) than the old Hand-Rolled model.
5: That said, Think about application Warmup. Part of what we do to help eliminate most of our EF performance woes was to add a special warmup method. It doesn't precompile any queries or anything, but it helps with much of the metadata loading/generation. This can be even more important when dealing with Code First models.
6: As others have said, Don't use Session state or ViewState if possible. They are not necessarily performance optimizations that developers think about, but once you start writing more complex web applications, you want responsiveness. Session state precludes this. Imagine a long running query. You decide to open a new window and try a less complex one. Well, you may as well have waited with session state on, because the server will wait until the first request is done before moving to the next one for that session.
7: Minimize round trips to the database. Save stuff that you frequently use but will not realistically change to your .Net Cache. Try to batch your inserts/updates where possible.
7.1: Avoid Data Access code in your Razor views without a damn good reason. I wouldn't be saying this if I hadn't seen it. They were already accessing their data when putting the model together, why the hell weren't they including it in the model?
The MyKey class (@Embeddable) should not have any relationships like @ManyToOne
Many of these answers were too slow for my source files. My source files were SQL files between 10 MB and 800 MB that needed to split into files of roughly equal line counts.
I found some of the previous answers which use Add-Content to be quite slow. Waiting many hours for a split to finish wasn't uncommon.
I didn't try Typhlosaurus's answer, but it looks to only do splits by file size, not line count.
The following has suited my purposes.
$sw = new-object System.Diagnostics.Stopwatch
$sw.Start()
Write-Host "Reading source file..."
$lines = [System.IO.File]::ReadAllLines("C:\Temp\SplitTest\source.sql")
$totalLines = $lines.Length
Write-Host "Total Lines :" $totalLines
$skip = 0
$count = 100000; # Number of lines per file
# File counter, with sort friendly name
$fileNumber = 1
$fileNumberString = $filenumber.ToString("000")
while ($skip -le $totalLines) {
$upper = $skip + $count - 1
if ($upper -gt ($lines.Length - 1)) {
$upper = $lines.Length - 1
}
# Write the lines
[System.IO.File]::WriteAllLines("C:\Temp\SplitTest\result$fileNumberString.txt",$lines[($skip..$upper)])
# Increment counters
$skip += $count
$fileNumber++
$fileNumberString = $filenumber.ToString("000")
}
$sw.Stop()
Write-Host "Split complete in " $sw.Elapsed.TotalSeconds "seconds"
For a 54 MB file, I get the output...
Reading source file...
Total Lines : 910030
Split complete in 1.7056578 seconds
I hope others looking for a simple, line-based splitting script that matches my requirements will find this useful.
public static JSONArray GetJSONDataFromResultSet(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
int count = metaData.getColumnCount();
String[] columnName = new String[count];
JSONArray jsonArray = new JSONArray();
while(rs.next()) {
JSONObject jsonObject = new JSONObject();
for (int i = 1; i <= count; i++){
columnName[i-1] = metaData.getColumnLabel(i);
jsonObject.put(columnName[i-1], rs.getObject(i));
}
jsonArray.put(jsonObject);
}
return jsonArray;
}
@Bo Persson correctly states in his great answer here:
When passing an array as a parameter, this
void arraytest(int a[])
means exactly the same as
void arraytest(int *a)
However, let me add also that the above two forms also:
mean exactly the same as
void arraytest(int a[0])
which means exactly the same as
void arraytest(int a[1])
which means exactly the same as
void arraytest(int a[2])
which means exactly the same as
void arraytest(int a[1000])
etc.
In every single one of the array examples above, and as shown in the example calls in the code just below, the input parameter type decays to an int *
, and can be called with no warnings and no errors, even with build options -Wall -Wextra -Werror
turned on (see my repo here for details on these 3 build options), like this:
int array1[2];
int * array2 = array1;
// works fine because `array1` automatically decays from an array type
// to `int *`
arraytest(array1);
// works fine because `array2` is already an `int *`
arraytest(array2);
As a matter of fact, the "size" value ([0]
, [1]
, [2]
, [1000]
, etc.) inside the array parameter here is apparently just for aesthetic/self-documentation purposes, and can be any positive integer (size_t
type I think) you want!
In practice, however, you should use it to specify the minimum size of the array you expect the function to receive, so that when writing code it's easy for you to track and verify. The MISRA-C-2012 standard (buy/download the 236-pg 2012-version PDF of the standard for £15.00 here) goes so far as to state (emphasis added):
Rule 17.5 The function argument corresponding to a parameter declared to have an array type shall have an appropriate number of elements.
...
If a parameter is declared as an array with a specified size, the corresponding argument in each function call should point into an object that has at least as many elements as the array.
...
The use of an array declarator for a function parameter specifies the function interface more clearly than using a pointer. The minimum number of elements expected by the function is explicitly stated, whereas this is not possible with a pointer.
In other words, they recommend using the explicit size format, even though the C standard technically doesn't enforce it--it at least helps clarify to you as a developer, and to others using the code, what size array the function is expecting you to pass in.
(Not recommended, but possible. See my brief argument against doing this at the end.)
As @Winger Sendon points out in a comment below my answer, we can force C to treat an array type to be different based on the array size!
First, you must recognize that in my example just above, using the int array1[2];
like this: arraytest(array1);
causes array1
to automatically decay into an int *
. HOWEVER, if you take the address of array1
instead and call arraytest(&array1)
, you get completely different behavior! Now, it does NOT decay into an int *
! Instead, the type of &array1
is int (*)[2]
, which means "pointer to an array of size 2 of int", or "pointer to an array of size 2 of type int", or said also as "pointer to an array of 2 ints". So, you can FORCE C to check for type safety on an array, like this:
void arraytest(int (*a)[2])
{
// my function here
}
This syntax is hard to read, but similar to that of a function pointer. The online tool, cdecl, tells us that int (*a)[2]
means: "declare a as pointer to array 2 of int" (pointer to array of 2 int
s). Do NOT confuse this with the version withOUT parenthesis: int * a[2]
, which means: "declare a as array 2 of pointer to int" (AKA: array of 2 pointers to int
, AKA: array of 2 int*
s).
Now, this function REQUIRES you to call it with the address operator (&
) like this, using as an input parameter a POINTER TO AN ARRAY OF THE CORRECT SIZE!:
int array1[2];
// ok, since the type of `array1` is `int (*)[2]` (ptr to array of
// 2 ints)
arraytest(&array1); // you must use the & operator here to prevent
// `array1` from otherwise automatically decaying
// into `int *`, which is the WRONG input type here!
This, however, will produce a warning:
int array1[2];
// WARNING! Wrong type since the type of `array1` decays to `int *`:
// main.c:32:15: warning: passing argument 1 of ‘arraytest’ from
// incompatible pointer type [-Wincompatible-pointer-types]
// main.c:22:6: note: expected ‘int (*)[2]’ but argument is of type ‘int *’
arraytest(array1); // (missing & operator)
You may test this code here.
To force the C compiler to turn this warning into an error, so that you MUST always call arraytest(&array1);
using only an input array of the corrrect size and type (int array1[2];
in this case), add -Werror
to your build options. If running the test code above on onlinegdb.com, do this by clicking the gear icon in the top-right and click on "Extra Compiler Flags" to type this option in. Now, this warning:
main.c:34:15: warning: passing argument 1 of ‘arraytest’ from incompatible pointer type [-Wincompatible-pointer-types] main.c:24:6: note: expected ‘int (*)[2]’ but argument is of type ‘int *’
will turn into this build error:
main.c: In function ‘main’: main.c:34:15: error: passing argument 1 of ‘arraytest’ from incompatible pointer type [-Werror=incompatible-pointer-types] arraytest(array1); // warning! ^~~~~~ main.c:24:6: note: expected ‘int (*)[2]’ but argument is of type ‘int *’ void arraytest(int (*a)[2]) ^~~~~~~~~ cc1: all warnings being treated as errors
Note that you can also create "type safe" pointers to arrays of a given size, like this:
int array[2];
// "type safe" ptr to array of size 2 of int:
int (*array_p)[2] = &array;
...but I do NOT necessarily recommend this (using these "type safe" arrays in C), as it reminds me a lot of the C++ antics used to force type safety everywhere, at the exceptionally high cost of language syntax complexity, verbosity, and difficulty architecting code, and which I dislike and have ranted about many times before (ex: see "My Thoughts on C++" here).
For additional tests and experimentation, see also the link just below.
See links above. Also:
As @Vadzim said, in IntelliJ or Android Studio, you just have to do the following to get java code from kotlin:
Menu > Tools > Kotlin > Show Kotlin Bytecode
Decompile
buttonUpdate:
With a recent version (1.2+) of the Kotlin plugin you also can directly do Menu > Tools > Kotlin -> Decompile Kotlin to Java
.
How do I select by partial string from a pandas DataFrame?
This post is meant for readers who want to
isin
)...and would like to know more about what methods should be preferred over others.
(P.S.: I've seen a lot of questions on similar topics, I thought it would be good to leave this here.)
Friendly disclaimer, this is post is long.
# setup
df1 = pd.DataFrame({'col': ['foo', 'foobar', 'bar', 'baz']})
df1
col
0 foo
1 foobar
2 bar
3 baz
str.contains
can be used to perform either substring searches or regex based search. The search defaults to regex-based unless you explicitly disable it.
Here is an example of regex-based search,
# find rows in `df1` which contain "foo" followed by something
df1[df1['col'].str.contains(r'foo(?!$)')]
col
1 foobar
Sometimes regex search is not required, so specify regex=False
to disable it.
#select all rows containing "foo"
df1[df1['col'].str.contains('foo', regex=False)]
# same as df1[df1['col'].str.contains('foo')] but faster.
col
0 foo
1 foobar
Performance wise, regex search is slower than substring search:
df2 = pd.concat([df1] * 1000, ignore_index=True)
%timeit df2[df2['col'].str.contains('foo')]
%timeit df2[df2['col'].str.contains('foo', regex=False)]
6.31 ms ± 126 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.8 ms ± 241 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Avoid using regex-based search if you don't need it.
Addressing ValueError
s
Sometimes, performing a substring search and filtering on the result will result in
ValueError: cannot index with vector containing NA / NaN values
This is usually because of mixed data or NaNs in your object column,
s = pd.Series(['foo', 'foobar', np.nan, 'bar', 'baz', 123])
s.str.contains('foo|bar')
0 True
1 True
2 NaN
3 True
4 False
5 NaN
dtype: object
s[s.str.contains('foo|bar')]
# ---------------------------------------------------------------------------
# ValueError Traceback (most recent call last)
Anything that is not a string cannot have string methods applied on it, so the result is NaN (naturally). In this case, specify na=False
to ignore non-string data,
s.str.contains('foo|bar', na=False)
0 True
1 True
2 False
3 True
4 False
5 False
dtype: bool
How do I apply this to multiple columns at once?
The answer is in the question. Use DataFrame.apply
:
# `axis=1` tells `apply` to apply the lambda function column-wise.
df.apply(lambda col: col.str.contains('foo|bar', na=False), axis=1)
A B
0 True True
1 True False
2 False True
3 True False
4 False False
5 False False
All of the solutions below can be "applied" to multiple columns using the column-wise apply
method (which is OK in my book, as long as you don't have too many columns).
If you have a DataFrame with mixed columns and want to select only the object/string columns, take a look at select_dtypes
.
This is most easily achieved through a regex search using the regex OR pipe.
# Slightly modified example.
df4 = pd.DataFrame({'col': ['foo abc', 'foobar xyz', 'bar32', 'baz 45']})
df4
col
0 foo abc
1 foobar xyz
2 bar32
3 baz 45
df4[df4['col'].str.contains(r'foo|baz')]
col
0 foo abc
1 foobar xyz
3 baz 45
You can also create a list of terms, then join them:
terms = ['foo', 'baz']
df4[df4['col'].str.contains('|'.join(terms))]
col
0 foo abc
1 foobar xyz
3 baz 45
Sometimes, it is wise to escape your terms in case they have characters that can be interpreted as regex metacharacters. If your terms contain any of the following characters...
. ^ $ * + ? { } [ ] \ | ( )
Then, you'll need to use re.escape
to escape them:
import re
df4[df4['col'].str.contains('|'.join(map(re.escape, terms)))]
col
0 foo abc
1 foobar xyz
3 baz 45
re.escape
has the effect of escaping the special characters so they're treated literally.
re.escape(r'.foo^')
# '\\.foo\\^'
By default, the substring search searches for the specified substring/pattern regardless of whether it is full word or not. To only match full words, we will need to make use of regular expressions here—in particular, our pattern will need to specify word boundaries (\b
).
For example,
df3 = pd.DataFrame({'col': ['the sky is blue', 'bluejay by the window']})
df3
col
0 the sky is blue
1 bluejay by the window
Now consider,
df3[df3['col'].str.contains('blue')]
col
0 the sky is blue
1 bluejay by the window
v/s
df3[df3['col'].str.contains(r'\bblue\b')]
col
0 the sky is blue
Similar to the above, except we add a word boundary (\b
) to the joined pattern.
p = r'\b(?:{})\b'.format('|'.join(map(re.escape, terms)))
df4[df4['col'].str.contains(p)]
col
0 foo abc
3 baz 45
Where p
looks like this,
p
# '\\b(?:foo|baz)\\b'
Because you can! And you should! They are usually a little bit faster than string methods, because string methods are hard to vectorise and usually have loopy implementations.
Instead of,
df1[df1['col'].str.contains('foo', regex=False)]
Use the in
operator inside a list comp,
df1[['foo' in x for x in df1['col']]]
col
0 foo abc
1 foobar
Instead of,
regex_pattern = r'foo(?!$)'
df1[df1['col'].str.contains(regex_pattern)]
Use re.compile
(to cache your regex) + Pattern.search
inside a list comp,
p = re.compile(regex_pattern, flags=re.IGNORECASE)
df1[[bool(p.search(x)) for x in df1['col']]]
col
1 foobar
If "col" has NaNs, then instead of
df1[df1['col'].str.contains(regex_pattern, na=False)]
Use,
def try_search(p, x):
try:
return bool(p.search(x))
except TypeError:
return False
p = re.compile(regex_pattern)
df1[[try_search(p, x) for x in df1['col']]]
col
1 foobar
np.char.find
, np.vectorize
, DataFrame.query
.In addition to str.contains
and list comprehensions, you can also use the following alternatives.
np.char.find
Supports substring searches (read: no regex) only.
df4[np.char.find(df4['col'].values.astype(str), 'foo') > -1]
col
0 foo abc
1 foobar xyz
np.vectorize
This is a wrapper around a loop, but with lesser overhead than most pandas str
methods.
f = np.vectorize(lambda haystack, needle: needle in haystack)
f(df1['col'], 'foo')
# array([ True, True, False, False])
df1[f(df1['col'], 'foo')]
col
0 foo abc
1 foobar
Regex solutions possible:
regex_pattern = r'foo(?!$)'
p = re.compile(regex_pattern)
f = np.vectorize(lambda x: pd.notna(x) and bool(p.search(x)))
df1[f(df1['col'])]
col
1 foobar
DataFrame.query
Supports string methods through the python engine. This offers no visible performance benefits, but is nonetheless useful to know if you need to dynamically generate your queries.
df1.query('col.str.contains("foo")', engine='python')
col
0 foo
1 foobar
More information on query
and eval
family of methods can be found at Dynamic Expression Evaluation in pandas using pd.eval().
str.contains
, for its simplicity and ease handling NaNs and mixed datanp.vectorize
df.query
sort
sorts inplace so returns nothing:
In [54]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
a
Out[54]:
array([1, 2, 3, 6, 8], dtype=int64)
So you have to call print a
again after the call to sort
.
Eg.:
In [55]:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
a.sort()
print(a)
[1 2 3 6 8]
try
subtotal.value= 5 // some value
proc = async function(x,y) {_x000D_
let url = "https://server.test-cors.org/server?id=346169&enable=true&status=200&credentials=false&methods=GET&" // some url working in snippet_x000D_
_x000D_
let r= await(await fetch(url+'&prodid=' + x + '&qbuys=' + y)).json(); // return json-object_x000D_
console.log(r);_x000D_
_x000D_
subtotal.value= r.length; // example value from json_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<form name="yoh" method="get"> _x000D_
Product id: <input type="text" id="pid" value=""><br/>_x000D_
_x000D_
Quantity to buy:<input type="text" id="qtytobuy" value="" onkeyup="proc(pid.value, this.value);"></br>_x000D_
_x000D_
Subtotal:<input type="text" name="subtotal" id="subtotal" value=""></br>_x000D_
<div id="compz"></div>_x000D_
_x000D_
</form>
_x000D_
in Mac Remove Java Version using this 3 Commands
java -version
sudo rm -rf /Library/Java/*
sudo rm -rf /Library/PreferencePanes/Java*
sudo rm -rf /Library/Internet\ Plug-Ins/Java*
Run
java -version
//See java was successfully uninstalled.
java -version sudo rm -rf /Library/Java/* sudo rm -rf /Library/PreferencePanes/Java* sudo rm -rf /Library/Internet\ Plug-Ins/Java*
Run java -version
Download Package and click next next next
Completely nothing worked out for me from these answers. Had to create the project again by running cordova platform add ios
. What I've noticed, even freshly generated project with (in my case) Firebase pods caused the error message over and over again. In my opinion looks like a bug for some (Firebase, RestKit) pods in Xcode
or CocoaPods
. To have the pods included I could simply edit my config.xml
and run cordova platform add iOS
, which did everything for me automatically. Not sure if it will work in all scenarios though.
Edit: I had a Podfile
from previous iOS
/Xcode
, but the newest as of today have # DO NOT MODIFY -- auto-generated by Apache Cordova
in the Podfile
. This turned on a light in my head to try the approach. Looks a bit trivial, but works and my Firebase
features worked out.
IO manipulators are what you need. setw, in particular. Here's an example from the reference page:
// setw example
#include <iostream>
#include <iomanip>
using namespace std;
int main () {
cout << setw (10);
cout << 77 << endl;
return 0;
}
Justifying the field to the left and right is done with the left
and right
manipulators.
Also take a look at setfill. Here's a more complete tutorial on formatting C++ output with io manipulators.
I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:
Request.AddHeader "Content-Type", "application/json"
Here is the snippet of my code:
Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String
Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac
Set Response = Client.Execute(Request)
You could just lump all the characters you want to use as separators either singularly or collectively into a regular expression and pass them to the split function. For instance you could write:
console.log( "dasdnk asd, (naks) :d skldma".split(/[ \(,\)]+/) );
And the output will be:
["dasdnk", "asd", "naks", ":d", "skldma"]
Extending User1648825's nice simple answer (I can't comment and my edit was rejected):
@Value("${spring.profiles.active}")
private String activeProfile;
This may throw an IllegalArgumentException if no profiles are set (I get a null value). This may be a Good Thing if you need it to be set; if not use the 'default' syntax for @Value, ie:
@Value("${spring.profiles.active:Unknown}")
private String activeProfile;
...activeProfile now contains 'Unknown' if spring.profiles.active could not be resolved
I guess you may have this problem in Pycharm. If so, you may try this to your problem.
Go to File-Setting-Tools-Python Scientific
in Pycharm and remove the option of Show plots in tool window
.
C++ provides a good mechanism to manage the life time of an object though class/struct constructs. This is one of the best features of C++ over other languages.
When you have member variables exposed through ref or pointer it violates the encapsulation in principle. This idiom enables the consumer of the class to change the state of an object of A without it(A) having any knowledge or control of it. It also enables the consumer to hold on to a ref/pointer to A's internal state, beyond the life time of the object of A. This is bad design. Instead the class could be refactored to hold a ref/pointer to the shared object (not own it) and these could be set using the constructor (Mandate the life time rules). The shared object's class may be designed to support multithreading/concurrency as the case may apply.
The link below will demonstrate how I accomplished this. Not very hard - just have to use some clever front-end dev!!
<div style="position: fixed; bottom: 0%; top: 0%;">
<div style="overflow-y: scroll; height: 100%;">
Menu HTML goes in here
</div>
</div>
Frustratingly the Numpy package published to PyPI won't install on most Windows computers https://github.com/numpy/numpy/issues/5479
Instead:
pip install numpy-1.10.2+mkl-cp35-none-win_amd64.whl
CSS-Transforms are not possible to animate with jQuery, yet. You can do something like this:
function AnimateRotate(angle) {
// caching the object for performance reasons
var $elem = $('#MyDiv2');
// we use a pseudo object for the animation
// (starts from `0` to `angle`), you can name it as you want
$({deg: 0}).animate({deg: angle}, {
duration: 2000,
step: function(now) {
// in the step-callback (that is fired each step of the animation),
// you can use the `now` paramter which contains the current
// animation-position (`0` up to `angle`)
$elem.css({
transform: 'rotate(' + now + 'deg)'
});
}
});
}
You can read more about the step-callback here: http://api.jquery.com/animate/#step
And, btw: you don't need to prefix css3 transforms with jQuery 1.7+
You can wrap this in a jQuery-plugin to make your life a bit easier:
$.fn.animateRotate = function(angle, duration, easing, complete) {
return this.each(function() {
var $elem = $(this);
$({deg: 0}).animate({deg: angle}, {
duration: duration,
easing: easing,
step: function(now) {
$elem.css({
transform: 'rotate(' + now + 'deg)'
});
},
complete: complete || $.noop
});
});
};
$('#MyDiv2').animateRotate(90);
http://jsbin.com/ofagog/2/edit
I optimized it a bit to make the order of easing
, duration
and complete
insignificant.
$.fn.animateRotate = function(angle, duration, easing, complete) {
var args = $.speed(duration, easing, complete);
var step = args.step;
return this.each(function(i, e) {
args.complete = $.proxy(args.complete, e);
args.step = function(now) {
$.style(e, 'transform', 'rotate(' + now + 'deg)');
if (step) return step.apply(e, arguments);
};
$({deg: 0}).animate({deg: angle}, args);
});
};
Thanks to matteo who noted an issue with the this
-context in the complete-callback
. If fixed it by binding the callback with jQuery.proxy
on each node.
I've added the edition to the code before from Update 2.
This is a possible modification if you want to do something like toggle the rotation back and forth. I simply added a start parameter to the function and replaced this line:
$({deg: start}).animate({deg: angle}, args);
If anyone knows how to make this more generic for all use cases, whether or not they want to set a start degree, please make the appropriate edit.
Mainly you've two ways to reach the desired result. But at the first, let's take a look on the arguments:
jQuery.fn.animateRotate(angle, duration, easing, complete)
Except of "angle" are all of them optional and fallback to the default jQuery.fn.animate
-properties:
duration: 400
easing: "swing"
complete: function () {}
This way is the short one, but looks a bit unclear the more arguments we pass in.
$(node).animateRotate(90);
$(node).animateRotate(90, function () {});
$(node).animateRotate(90, 1337, 'linear', function () {});
I prefer to use objects if there are more than three arguments, so this syntax is my favorit:
$(node).animateRotate(90, {
duration: 1337,
easing: 'linear',
complete: function () {},
step: function () {}
});
For those who might be trying to create a Travis Build, the default path from which Django is installed from the requirements.txt
file points to a repo whose django_extensions
module has not been updated. The only workaround, for now, is to install from the master branch using pip. That is where the patch is made. But for now, we'll have to wait.
You can try this in the meantime, it might help
- pip install git+https://github.com/chibisov/drf-extensions.git@master
- pip install git+https://github.com/django-extensions/django-extensions.git@master
all:
echo ${PATH}
Or change PATH just for one command:
all:
PATH=/my/path:${PATH} cmd
Some basic differences can be written in short:
MVC:
Traditional MVC is where there is a
MVP:
Similar to traditional MVC but Controller is replaced by Presenter. But the Presenter, unlike Controller is responsible for changing the view as well. The view usually does not call the presenter.
MVVM
The difference here is the presence of View Model. It is kind of an implementation of Observer Design Pattern, where changes in the model are represented in the view as well, by the VM. Eg: If a slider is changed, not only the model is updated but the data which may be a text, that is displayed in the view is updated as well. So there is a two-way data binding.
If you are trying to move to 2nd view controller from 5th view controller (skipping 3rd and 4th), you would like to use [self.navigationController popToviewController:secondViewController]
.
You can obtain the secondViewController
from the navigation controller stack.
secondViewController = [self.navigationController.viewControllers objectAtIndex:yourViewControllerIndex];
One example of rawQuery - db.rawQuery("select * from table where column = ?",new String[]{"data"});
Here is a part of the response that tells you if an element is in the viewport. You may need to check if there is nothing on top of it using elementFromPoint, but it's a bit longer.
function isInViewport(element) {
var rect = element.getBoundingClientRect();
var windowHeight = window.innerHeight || document.documentElement.clientHeight;
var windowWidth = window.innerWidth || document.documentElement.clientWidth;
return rect.bottom > 0 && rect.top < windowHeight && rect.right > 0 && rect.left < windowWidth;
}
You can see Hive MetaStore tables,Partitions information in table of "PARTITIONS". You could use "TBLS" join "Partition" to query special table partitions.
I use Google Chart Tools https://developers.google.com/chart/ It's well documented and the charts look great. Being javascript, you can feed it json data via ajax.
Use Dictionary Items:
{% for key, value in my_dictionay.items %}
<li>{{ key }} : {{ value }}</li>
{% endfor %}
I'd use this approach:
String randomString(final int length) {
Random r = new Random(); // perhaps make it a class variable so you don't make a new one every time
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++) {
char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
sb.append(c);
}
return sb.toString();
}
If you want a byte[] you can do this:
byte[] randomByteString(final int length) {
Random r = new Random();
byte[] result = new byte[length];
for(int i = 0; i < length; i++) {
result[i] = r.nextByte();
}
return result;
}
Or you could do this
byte[] randomByteString(final int length) {
Random r = new Random();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < length; i++) {
char c = (char)(r.nextInt((int)(Character.MAX_VALUE)));
sb.append(c);
}
return sb.toString().getBytes();
}
Please try this, if you want to fetch first/last.
{{#each list}}
{{#if @first}}
<div class="active">
{{else}}
<div>
{{/if}}
{{/each}}
{{#each list}}
{{#if @last}}
<div class="last-element">
{{else}}
<div>
{{/if}}
{{/each}}