For run all lines of GridView don't use for
loop, use foreach
loop like:
foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
//if checked do something
}
}
}
I have done a very simple thing to enable or disable command button. Below is my grid
<asp:GridView ID="grdOrderProduct" runat="server" TabIndex="1" BackColor="White" BorderColor="#CEC9EF" CssClass="table table-striped dataTable table-bordered"
OnRowEditing="grdOrderProduct_RowEditing" OnRowUpdating="grdOrderProduct_RowUpdating" OnRowDeleting="grdOrderProduct_RowDeleting" OnRowDataBound="grdOrderProduct_RowDataBound"
Width="100%" CellPadding="3" CellSpacing="1" BorderWidth="0" AutoGenerateColumns="False">
<HeaderStyle />
<AlternatingRowStyle />
<Columns>
<asp:BoundField DataField="ProductSKU" ReadOnly="true" HeaderText="Product SKU" HeaderStyle-CssClass="headTb4" />
<asp:BoundField DataField="ProductName" ReadOnly="true" HeaderText="ProductName" HeaderStyle-CssClass="headTb4" />
<asp:BoundField DataField="QTY" HeaderText="QTY" HeaderStyle-CssClass="headTb4" />
<asp:BoundField DataField="Discount" HeaderText="Discount %" HeaderStyle-CssClass="headTb4" />
<asp:BoundField DataField="TPrice" HeaderText="MRP" ReadOnly="true" HeaderStyle-CssClass="headTb4" />
<asp:CommandField ShowEditButton="true" ButtonType="Image" EditImageUrl="~/Images/edit.png"
UpdateImageUrl="~/Images/gear.png" CancelText=" " HeaderStyle-CssClass="headTb4"
ShowDeleteButton="true" DeleteImageUrl="~/Images/delete.png"
HeaderText="Action" ItemStyle-HorizontalAlign="Center">
<HeaderStyle CssClass="headTb4" />
<ItemStyle HorizontalAlign="Center" />
</asp:CommandField>
</Columns>
<AlternatingRowStyle CssClass="odd" />
<PagerStyle HorizontalAlign="Center" VerticalAlign="Top" Wrap="False" />
In the following method i have done the changes
protected void grdOrderProduct_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (ImageButton button in e.Row.Cells[5].Controls.OfType<ImageButton>())
{
if (button.CommandName == "Delete")
{
button.Visible = false;
}
}
}
}
void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
Button b = (Button)e.CommandSource;
b.CommandArgument = ((GridViewRow)sender).RowIndex.ToString();
}
Try using sprintf
:
unsigned long x=1000000;
char buffer[21];
sprintf(buffer,"%lu", x);
Edit:
Notice that you have to allocate a buffer in advance, and have no idea how long the numbers will actually be when you do so. I'm assuming 32bit long
s, which can produce numbers as big as 10 digits.
See Carl Smotricz's answer for a better explanation of the issues involved.
This is how I would start to solve this:
Create a video writer:
import cv2.cv as cv
videowriter = cv.CreateVideoWriter( filename, fourcc, fps, frameSize)
Loop to retrieve[1] and write the frames:
cv.WriteFrame( videowriter, frame )
[1] zenpoy already pointed in the correct direction. You just need to know that you can retrieve images from a webcam or a file :-)
Hopefully I understood the requirements correct.
If you're using a scanner, in your scanner try to have it return the least number of qualifiers as possible. In fact, the qualifier(s) that you do return should be the smallest (in byte-size) as you have available. This will speed up your scan tremendously.
Unfortuneately this will only scale so far (millions-billions?). To take it further, you can do this in real time but you will first need to run a mapreduce job to count all rows.
Store the Mapreduce output in a cell in HBase. Every time you add a row, increment the counter by 1. Every time you delete a row, decrement the counter.
When you need to access the number of rows in real time, you read that field in HBase.
There is no fast way to count the rows otherwise in a way that scales. You can only count so fast.
Javascript's inheritance is prototype based, so you extend the prototypes of objects such as Date, Math, and even your own custom ones.
Date.prototype.lol = function() {
alert('hi');
};
( new Date ).lol() // alert message
In the snippet above, I define a method for all Date objects ( already existing ones and all new ones ).
extend
is usually a high level function that copies the prototype of a new subclass that you want to extend from the base class.
So you can do something like:
extend( Fighter, Human )
And the Fighter
constructor/object will inherit the prototype of Human
, so if you define methods such as live
and die
on Human
then Fighter
will also inherit those.
Updated Clarification:
"high level function" meaning .extend isn't built-in but often provided by a library such as jQuery or Prototype.
You can do the following:
private ToolStripMenuItem getToolStripMenuItemByName(string nameParam) { foreach (Control ctn in this.Controls) { if (ctn is ToolStripMenuItem) { if (ctn.Name = nameParam) { return ctn; } } } return null; }
If so is there a way to not load the unnecessary content on mobile browsers?
use <img src="" srcset="">
http://www.webdesignerdepot.com/2015/08/the-state-of-responsive-images/
There's a lot of verbosity in here, and I'm deeply against it, so, my conclusive answer would be:
/^\w+$/
\w
is equivalent to [A-Za-z0-9_]
, which is pretty much what you want. (unless we introduce unicode to the mix)
Using the +
quantifier you'll match one or more characters. If you want to accept an empty string too, use *
instead.
Just add not-null constraint
I had the same problem. I just added not-null constraint in xml mapping. It worked
<set name="phone" cascade="all" lazy="false" >
<key column="id" not-null="true" />
<one-to-many class="com.practice.phone"/>
</set>
This did the trick for me: I was able to find which macro called a particular query. Incidentally, the reason someone who does know how to code in VBA would want to write something like this is when they've inherited something macro-ish written by someone who doesn't know how to code in VBA.
Function utlFindQueryInMacro
( strMacroNameLike As String
, strQueryName As String
) As String
' (c) 2012 Doug Den Hoed
' NOTE: requires reference to Microsoft Scripting Library
Dim varItem As Variant
Dim strMacroName As String
Dim oFSO As New FileSystemObject
Dim oFS
Dim strFileContents As String
Dim strMacroNames As String
For Each varItem In CurrentProject.AllMacros
strMacroName = varItem.Name
If Len(strMacroName) = 0 _
Or InStr(strMacroName, strMacroNameLike) > 0 Then
'Debug.Print "*** MACRO *** "; strMacroName
Application.SaveAsText acMacro, strMacroName, "c:\temp.txt"
Set oFS = oFSO.OpenTextFile("c:\temp.txt")
strFileContents = ""
Do Until oFS.AtEndOfStream
strFileContents = strFileContents & oFS.ReadLine
Loop
Set oFS = Nothing
Set oFSO = Nothing
Kill "c:\temp.txt"
'Debug.Print strFileContents
If InStr(strFileContents, strQueryName) 0 Then
strMacroNames = strMacroNames & strMacroName & ", "
End If
End If
Next varItem
MsgBox strMacroNames
utlFindQueryInMacro = strMacroNames
End Function
(can't comment or I would just do that) I believe the suggestion to check locals above is not quite right. It should be:
foo = foo if 'foo' in locals() or 'foo' in globals() else 'default'
to be correct in all contexts.
However, despite its upvotes, I don't think even that is a good analog to the Ruby operator. Since the Ruby operator allows more than just a simple name on the left:
foo[12] ||= something
foo.bar ||= something
The exception method is probably closest analog.
First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.
I've had a lot of problems trying to get Eclipse to accept as much memory as I'd like it to be able to use (between 2 and 4 gigs for example).
Open eclipse.ini
in the Eclipse installation directory.
You should be able to change the memory sizes after -vmargs
up to 1024 without a problem up to some maximum value that's dependent on your system. Here's that section on my Linux box:
-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=512m
-Xms512m
-Xmx1024m
And here's that section on my Windows box:
-vmargs
-Xms256m
-Xmx1024m
But, I've failed at setting it higher than 1024 megs. If anybody knows how to make that work, I'd love to know.
EDIT: 32bit version of juno seems to not accept more than Xmx1024m where the 64 bit version accept 2048.
EDIT: Nick's post contains some great links that explain two different things:
I have 8 gigs of Ram and can't set -Xmx
to more than 1024 megs of ram, even when a minimal amount of programs are loaded and both windows/linux report between 4 and 5 gigs of free ram.
The second quote is correct, the size of a word varies from computer to computer. The ARM NEON architecture is an example of an architecture with 32-bit words, where 64-bit quantities are referred to as "doublewords" and 128-bit quantities are referred to as "quadwords":
A NEON operand can be a vector or a scalar. A NEON vector can be a 64-bit doubleword vector or a 128-bit quadword vector.
Normally speaking, 16-bit words are only found on 16-bit systems, like the Amiga 500.
It's because of the way NOT IN works.
To avoid these headaches (and for a faster query in many cases), I always prefer NOT EXISTS:
SELECT *
FROM Table1 t1
WHERE NOT EXISTS (
SELECT *
FROM Table2 t2
WHERE t1.MAKE = t2.MAKE
AND t1.MODEL = t2.MODEL
AND t1.[Serial Number] = t2.[serial number]);
For some reason the responsive table in particular doesn't behave as it should. You can patch it by getting rid of display:block;
.table-responsive {
display: table;
}
I may file a bug report.
Edit:
If you want to browse to a folder by default: For example "D:\Default_Folder" just initialise the "InitialFileName" attribute
Dim diaFolder As FileDialog
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.InitialFileName = "D:\Default_Folder"
diaFolder.Show
As you state in one of your comments that the table in question is in a different database, then ownership chaining applies. I suspect there is a break in the chain somewhere - check that link for full details.
This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:
PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf
Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.
After successfully running autogen.sh/configure, compile with:
PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make
The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.
I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.
Try this. It holds the color until another item is clicked.
<style type="text/css">
.activeElem{
background-color:lightblue
}
.desactiveElem{
background-color:none
}
}
</style>
<script type="text/javascript">
var activeElemId;
function activateItem(elemId) {
document.getElementById(elemId).className="activeElem";
if(null!=activeElemId) {
document.getElementById(activeElemId).className="desactiveElem";
}
activeElemId=elemId;
}
</script>
<li id="aaa"><a href="#" onclick="javascript:activateItem('aaa');">AAA</a>
<li id="bbb"><a href="#" onClick="javascript:activateItem('bbb');">BBB</a>
<li id="ccc"><a href="#" onClick="javascript:activateItem('ccc');">CCC</a>
Step 1: convert the string to an array using the str_split
function
$array = str_split($your_string);
Step 2: loop through the newly created array
foreach ($array as $char) {
echo $char;
}
You can check the PHP docs for more information: str_split
date('Y-m', strtotime('first day of last month'));
Appending a single scalar could be done a bit easier as already shown (and also without converting to float) by expanding the scalar to a python-list-type:
import numpy as np
a = np.array([[1,3,4],[1,2,3],[1,2,1]])
x = 10
b = np.hstack ((a, [[x]] * len (a) ))
returns b
as:
array([[ 1, 3, 4, 10],
[ 1, 2, 3, 10],
[ 1, 2, 1, 10]])
Appending a row could be done by:
c = np.vstack ((a, [x] * len (a[0]) ))
returns c
as:
array([[ 1, 3, 4],
[ 1, 2, 3],
[ 1, 2, 1],
[10, 10, 10]])
Also, eclipse offers the possibility to sort class members for you, if you for some reason mixed them up:
Open your class file, the go to "Source" in the main menu and select "Sort Members".
taken from here: Sorting methods in Eclipse
Structure types should, whenever practical, either have all of their state encapsulated in public fields which may independently be set to any values which are valid for their respective type, or else behave as a single unified value which can only bet set via constructor, factory, method, or else by passing an instance of the struct as an explicit ref
parameter to one of its public methods. Contrary to what some people claim, that there's nothing wrong with a struct having public fields, if it is supposed to represent a set of values which may sensibly be either manipulated individually or passed around as a group (e.g. the coordinates of a point). Historically, there have been problems with structures that had public property setters, and a desire to avoid public fields (implying that setters should be used instead) has led some people to suggest that mutable structures should be avoided altogether, but fields do not have the problems that properties had. Indeed, an exposed-field struct is the ideal representation for a loose collection of independent variables, since it is just a loose collection of variables.
In your particular example, however, it appears that the two fields of your struct are probably not supposed to be independent. There are three ways your struct could sensibly be designed:
You could have the only public field be the string, and then have a read-only "helper" property called length
which would report its length if the string is non-null, or return zero if the string is null.
You could have the struct not expose any public fields, property setters, or mutating methods, and have the contents of the only field--a private string--be specified in the object's constructor. As above, length
would be a property that would report the length of the stored string.
You could have the struct not expose any public fields, property setters, or mutating methods, and have two private fields: one for the string and one for the length, both of which would be set in a constructor that takes a string, stores it, measures its length, and stores that. Determining the length of a string is sufficiently fast that it probably wouldn't be worthwhile to compute and cache it, but it might be useful to have a structure that combined a string and its GetHashCode
value.
It's important to be aware of a detail with regard to the third design, however: if non-threadsafe code causes one instance of the structure to be read while another thread is writing to it, that may cause the accidental creation of a struct instance whose field values are inconsistent. The resulting behaviors may be a little different from those that occur when classes are used in non-threadsafe fashion. Any code having anything to do with security must be careful not to assume that structure fields will be in a consistent state, since malicious code--even in a "full trust" enviroment--can easily generate structs whose state is inconsistent if that's what it wants to do.
PS -- If you wish to allow your structure to be initialized using an assignment from a string, I would suggest using an implicit conversion operator and making Length
be a read-only property that returns the length of the underlying string if non-null, or zero if the string is null.
After I plotted all the lines, I was able to set the transparency of all of them as follows:
for l in fig_field.gca().lines:
l.set_alpha(.7)
EDIT: please see Joe's answer in the comments.
You can do that using CSS's background
propieties. There are few ways to do it:
HTML:
<div id="div-with-bg"></div>
CSS:
#div-with-bg
{
background: color url('path') others;
}
HTML:
<div class="div-with-bg"></div>
CSS:
.div-with-bg
{
background: color url('path') others;
}
HTML:
<div style="background: color url('path')"></div>
Where:
background
CSS Property is a connection of all background-xxx propieties in that syntax:
background: background-color background-image background-repeat background-attachment background-position;
Source: w3schools
This is the right CSS3 answer. Hope this helps you somehow now :D I really recommend you to read the book: https://www.amazon.com/Book-CSS3-Developers-Future-Design/dp/1593272863 Actually I have made this solution from reading this book now. :D
#wrapper{_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
border: 1px solid black;_x000D_
}_x000D_
#first{_x000D_
width: 300px;_x000D_
border: 1px solid red;_x000D_
}_x000D_
#second{_x000D_
border: 1px solid green;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>_x000D_
<div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>_x000D_
</div>
_x000D_
CASE
is more like a switch statement. It has two syntaxes you can use. The first lets you use any compare statements you want:
CASE
WHEN user_role = 'Manager' then 4
WHEN user_name = 'Tom' then 27
WHEN columnA <> columnB then 99
ELSE -1 --unknown
END
The second style is for when you are only examining one value, and is a little more succinct:
CASE user_role
WHEN 'Manager' then 4
WHEN 'Part Time' then 7
ELSE -1 --unknown
END
I'm working on Crud for my app. This is how I did it Got Reactstrap as my dependency.
import React, { useState, setState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import firebase from 'firebase';
// import { LifeCrud } from '../CRUD/Crud';
import { Row, Card, Col, Button } from 'reactstrap';
import InsuranceActionInput from '../CRUD/InsuranceActionInput';
const LifeActionCreate = () => {
let [newLifeActionLabel, setNewLifeActionLabel] = React.useState();
const onCreate = e => {
const db = firebase.firestore();
db.collection('actions').add({
label: newLifeActionLabel
});
alert('New Life Insurance Added');
setNewLifeActionLabel('');
};
return (
<Card style={{ padding: '15px' }}>
<form onSubmit={onCreate}>
<label>Name</label>
<input
value={newLifeActionLabel}
onChange={e => {
setNewLifeActionLabel(e.target.value);
}}
placeholder={'Name'}
/>
<Button onClick={onCreate}>Create</Button>
</form>
</Card>
);
};
Some React Hooks in there
If Bool1 And Bool2 Then
Evaluates both Bool1 and Bool2
If Bool1 AndAlso Bool2 Then
Evaluates Bool2 if and only if Bool1 is true.
I solved this problem through the following:
string userId="";
for example: in C#
userId= "5,44,72,81,126";
and Send to SQL-Server
SqlParameter param = cmd.Parameters.AddWithValue("@user_id_list",userId);
NVARCHAR(Max)
) to Table.CREATE FUNCTION dbo.SplitInts ( @List VARCHAR(MAX), @Delimiter VARCHAR(255) ) RETURNS TABLE AS RETURN ( SELECT Item = CONVERT(INT, Item) FROM ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)') FROM ( SELECT [XML] = CONVERT(XML, '<i>' + REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.') ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y WHERE Item IS NOT NULL );
SELECT user_id = Item FROM dbo.SplitInts(@user_id_list, ',');
The default argument allows you to call the function without passing an argument. If you don't pass the argument, then the default argument is supplied. So using your code, this...
test()
...is exactly the same as this:
test(nil)
If you leave out the default argument like this...
func test(firstThing: Int?) {
if firstThing != nil {
print(firstThing!)
}
print("done")
}
...then you can no longer do this...
test()
If you do, you will get the "missing argument" error that you described. You must pass an argument every time, even if that argument is just nil
:
test(nil) // this works
My solution to this was to write the script block dynamically with [scriptblock]:Create
:
# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.
$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not
# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script
Passing arguments was very frustrating, trying various methods, e.g.,
-arguments
, $using:p1
, etc. and this just worked as desired with no problems.
Since I control the contents and variable expansion of the string which creates the [scriptblock]
(or script file) this way, there is no real issue with the "invoke-command" incantation.
(It shouldn't be that hard. :) )
References
and do Add Reference
, then from Assemblies->Framework
select System.Web.Extensions
. using System.Web.Script.Serialization;
I am not certain about what precisely you are trying to do, but I think this SQL function will help you:
SELECT DATEADD(day,-1,'2013-04-01 16:25:00.250')
The above will give you 2013-03-31 16:25:00.250
.
It takes you back exactly one day and works on any standard date-time or date format.
Try running this command and see if it gives you what you are looking for:
SELECT DATEADD(day,-1,@CreatedDate)
try this code worked for me
SELECT user_display_image AS user_image,
user_display_name AS user_name,
invitee_phone,
(CASE WHEN invitee_status = 1 THEN "attending"
WHEN invitee_status = 2 THEN "unsure"
WHEN invitee_status = 3 THEN "declined"
WHEN invitee_status = 0 THEN "notreviwed"
END) AS invitee_status
FROM your_table
I wrapped the 'svg' tag in 'a' tag and put the onClick event in the 'a' tag
loop through all loaded assemblies, loop through all their types, and check if they implement the interface.
something like:
Type ti = typeof(IYourInterface);
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {
foreach (Type t in asm.GetTypes()) {
if (ti.IsAssignableFrom(t)) {
// here's your type in t
}
}
}
Make sure that you have valid cacerts in the JRE/security, otherwise you will not bypass the invalid empty trustAnchors error.
In my Amazon EC2 Opensuse12 installation, the problem was that the file pointed by the cacerts in the JRE security directory was invalid:
$ java -version
java version "1.7.0_09"
OpenJDK Runtime Environment (IcedTea7 2.3.4) (suse-3.20.1-x86_64)
OpenJDK 64-Bit Server VM (build 23.2-b09, mixed mode)
$ ls -l /var/lib/ca-certificates/
-rw-r--r-- 1 root 363 Feb 28 14:17 ca-bundle.pem
$ ls -l /usr/lib64/jvm/jre/lib/security/
lrwxrwxrwx 1 root 37 Mar 21 00:16 cacerts -> /var/lib/ca-certificates/java-cacerts
-rw-r--r-- 1 root 2254 Jan 18 16:50 java.policy
-rw-r--r-- 1 root 15374 Jan 18 16:50 java.security
-rw-r--r-- 1 root 88 Jan 18 17:34 nss.cfg
So I solved installing an old Opensuse 11 valid certificates. (sorry about that!!)
$ ll
total 616
-rw-r--r-- 1 root 220065 Jan 31 15:48 ca-bundle.pem
-rw-r--r-- 1 root 363 Feb 28 14:17 ca-bundle.pem.old
-rw-r--r-- 1 root 161555 Jan 31 15:48 java-cacerts
I understood that you could use the keytool to generate a new one (http://mail.openjdk.java.net/pipermail/distro-pkg-dev/2010-April/008961.html). I'll probably have to that soon.
regards lellis
Incase you you're like me and you landed here trying to find a way to tell if your PowerShell variable is this particular flavor of non-existent:
COM object that has been separated from its underlying RCW cannot be used.
Then here's some code that worked for me:
function Count-RCW([__ComObject]$ComObj){
try{$iuk = [System.Runtime.InteropServices.Marshal]::GetIUnknownForObject($ComObj)}
catch{return 0}
return [System.Runtime.InteropServices.Marshal]::Release($iuk)-1
}
example usage:
if((Count-RCW $ExcelApp) -gt 0){[System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($ExcelApp)}
mashed together from other peoples' better answers:
and some other cool things to know:
I believe the easiest way is to upload the file using MYSQL command line.
using the command from the terminal to access MySQL command line and run source
mysql --host=hostname -uuser -ppassword
source filename.sql
or directly from the terminal
mysql --host=hostname -uuser -ppassword < filename.sql
at the prompt
I found this link How to upload big sql dump files (memory, HTTP or timeout problems) in MYSQL. it give the outline of what to do to upload a large SQL. It helped me when I got face with a client 196mb sql dump. Something the PHPMySql couldn't handle.
require(ggplot2)
require(nlme)
set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)
mp <- within(mp,
{
wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
wow <- rnorm(N)*wav+rnorm(N)*wav^3
})
m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))
Get fitted values (the same as m01$fitted
)
fit <- predict(m01)
Normally we could use something like predict(...,se.fit=TRUE)
to get the confidence intervals on the prediction, but gls
doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :
V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
Put together a "prediction frame":
predframe <- with(mp,data.frame(year,wav,
wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))
Now plot with geom_ribbon
(p1 <- ggplot(mp, aes(year, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It's easier to see that we got the right answer if we plot against wav
rather than year
:
(p2 <- ggplot(mp, aes(wav, wow))+
geom_point()+
geom_line(data=predframe)+
geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))
It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly()
fits -- see ?makepredictcall
.
To get the value:
$query = $this->db->query("YOUR QUERY");
Then, for single row from(in controller):
$query1 = $query->row();
$data['product'] = $query1;
In view, you can use your own code (above code)
Ubuntu, which is a Debian derivative, follows a very precise structure when installing packages. In other words, all software installed through the packaging tools, such as apt-get or synaptic, will put the stuff in the same locations. If you become familiar with these locations, you'll always know where to find your stuff.
As a short cut, you can always open a tool like synaptic, find the installed package, and inspect the "properties". Under properties, you'll see a list of all installed files. Again, you can expect these to always follow the Debian/Ubuntu conventions; these are highly ordered Linux distributions. IN short, binaries will be in /usr/bin, or some other location on your path ( try 'echo $PATH' on the command line to see the possible locations ). Configuration is always in a subdirectory of /etc. And the "home" is typically in /usr/lib or /usr/share.
For instance, according to http://www.mkyong.com/maven/how-to-install-maven-in-ubuntu/, maven is installed like:
The Apt-get installation will install all the required files in the following folder structure
/usr/bin/mvn
/usr/share/maven2/
/etc/maven2
P.S The Maven configuration is store in /etc/maven2
Note, it's not just apt-get that will do this, it's any .deb package installer.
There is a method update
on BaseQuery object in SQLAlchemy, which is returned by filter_by
.
num_rows_updated = User.query.filter_by(username='admin').update(dict(email='[email protected]')))
db.session.commit()
The advantage of using update
over changing the entity comes when there are many objects to be updated.
If you want to give add_user
permission to all the admin
s,
rows_changed = User.query.filter_by(role='admin').update(dict(permission='add_user'))
db.session.commit()
Notice that filter_by
takes keyword arguments (use only one =
) as opposed to filter
which takes an expression.
Be careful, you're unwittingly asking "where the date is greater than one divided by nine, divided by two thousand and eight".
Put #
signs around the date, like this #1/09/2008#
Do you have a pointer to a vector because that's how you've coded it? You may want to reconsider this and use a (possibly const) reference. For example:
#include <iostream>
#include <vector>
using namespace std;
void foo(vector<int>* a)
{
cout << a->at(0) << a->at(1) << a->at(2) << endl;
// expected result is "123"
}
int main()
{
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
foo(&a);
}
While this is a valid program, the general C++ style is to pass a vector by reference rather than by pointer. This will be just as efficient, but then you don't have to deal with possibly null pointers and memory allocation/cleanup, etc. Use a const reference if you aren't going to modify the vector, and a non-const reference if you do need to make modifications.
Here's the references version of the above program:
#include <iostream>
#include <vector>
using namespace std;
void foo(const vector<int>& a)
{
cout << a[0] << a[1] << a[2] << endl;
// expected result is "123"
}
int main()
{
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
foo(a);
}
As you can see, all of the information contained within a will be passed to the function foo, but it will not copy an entirely new value, since it is being passed by reference. It is therefore just as efficient as passing by pointer, and you can use it as a normal value rather than having to figure out how to use it as a pointer or having to dereference it.
When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?
Scanner scanner = new Scanner("Student.txt");
String currentLine;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Perform logic
}
}
You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:
Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Do task
passedLine = true;
}
if(passedLine)
{
//Do other task after passing the line.
}
lineNumber++;
}
If you're in a Navigation Controller:
ViewController *viewController = [[ViewController alloc] init];
[self.navigationController pushViewController:viewController animated:YES];
or if you just want to present a new view:
ViewController *viewController = [[ViewController alloc] init];
[self presentViewController:viewController animated:YES completion:nil];
CMake produces Visual Studio Projects and Solutions seamlessly. You can even produce projects/solutions for different Visual Studio versions without making any changes to the CMake files.
Adding and removing source files is just a matter of modifying the CMakeLists.txt
which has the list of source files and regenerating the projects/solutions. There is even a globbing function to find all the sources in a directory (though it should be used with caution).
The following link explains CMake and Visual Studio specific behavior very well.
Neither of answers worked for me even though I had my resources put in resources folders and followed the above answers. What did make a trick was:
@Value("file:*/**/resources/**/schema/*.json")
private Resource[] resources;
In my world, we use the terms as follows:
functional testing: This is a verification activity; did we build a correctly working product? Does the software meet the business requirements?
For this type of testing we have test cases that cover all the possible scenarios we can think of, even if that scenario is unlikely to exist "in the real world". When doing this type of testing, we aim for maximum code coverage. We use any test environment we can grab at the time, it doesn't have to be "production" caliber, so long as it's usable.
acceptance testing: This is a validation activity; did we build the right thing? Is this what the customer really needs?
This is usually done in cooperation with the customer, or by an internal customer proxy (product owner). For this type of testing we use test cases that cover the typical scenarios under which we expect the software to be used. This test must be conducted in a "production-like" environment, on hardware that is the same as, or close to, what a customer will use. This is when we test our "ilities":
Reliability, Availability: Validated via a stress test.
Scalability: Validated via a load test.
Usability: Validated via an inspection and demonstration to the customer. Is the UI configured to their liking? Did we put the customer branding in all the right places? Do we have all the fields/screens they asked for?
Security (aka, Securability, just to fit in): Validated via demonstration. Sometimes a customer will hire an outside firm to do a security audit and/or intrusion testing.
Maintainability: Validated via demonstration of how we will deliver software updates/patches.
Configurability: Validated via demonstration of how the customer can modify the system to suit their needs.
This is by no means standard, and I don't think there is a "standard" definition, as the conflicting answers here demonstrate. The most important thing for your organization is that you define these terms precisely, and stick to them.
from sklearn.linear_model import LinearRegression
X, Y = x.reshape(-1,1), y.reshape(-1,1)
plt.plot( X, LinearRegression().fit(X, Y).predict(X) )
If you want or don't mind having all the leading and trailing whitespace from your string removed you can use the strip
method.
" hello ".strip #=> "hello"
"\tgoodbye\r\n".strip #=> "goodbye"
as mentioned here.
edit The original title for this question was different. My answer is for the original question.
Go to ~/.subversion/auth/svn.simple/*
, and you will see a list of files that contains the information about your svn user account. Just delete all others that you don't need.
After that, when you do anything that regards to SVN operation, such as commit, rm, etc,. You will be prompt again to enter username or passwords.
I see lots of confusion in the comments. Null
, IsNull()
and vbNull
are mainly used for database handling and normally not used in VBScript. If it is not explicitly stated in the documentation of the calling object/data, do not use it.
To test if a variable is uninitialized, use IsEmpty()
. To test if a variable is uninitialized or contains ""
, test on ""
or Empty
. To test if a variable is an object, use IsObject
and to see if this object has no reference test on Is Nothing
.
In your case, you first want to test if the variable is an object, and then see if that variable is Nothing
, because if it isn't an object, you get the "Object Required" error when you test on Nothing
.
snippet to mix and match in your code:
If IsObject(provider) Then
If Not provider Is Nothing Then
' Code to handle a NOT empty object / valid reference
Else
' Code to handle an empty object / null reference
End If
Else
If IsEmpty(provider) Then
' Code to handle a not initialized variable or a variable explicitly set to empty
ElseIf provider = "" Then
' Code to handle an empty variable (but initialized and set to "")
Else
' Code to handle handle a filled variable
End If
End If
How about .delay()
?
$("#test").animate({"top":"-=80px"},1500)
.delay(1000)
.animate({"opacity":"0"},500);
you can add
<fieldset class="fieldset">
and then you can call
$('.fieldset').prop('disabled', true);
When you have own struct
, you could have own convert-to-string function.
package main
import (
"fmt"
)
type Color struct {
Red int `json:"red"`
Green int `json:"green"`
Blue int `json:"blue"`
}
func (c Color) String() string {
return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}
func main() {
c := Color{Red: 123, Green: 11, Blue: 34}
fmt.Println(c) //[123, 11, 34]
}
Go to IIS, Select your application and Find MIME Types
Click on Add from Right panel
File Name Extension = .json
MIME Type = application/json
After adding .json file type in MIME Types, Restart IIS and try to access json file
Go to web.config of that application and add this lines in it
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
The input.files
attribute is an HTML5 feature. That's why some browsers din't return anything.
Simply add a fallback to the plain old input.value
(string) if files
doesn't exist.
reference: http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-apis.html#dom-input-files
One of the problem with this code is here :
name += contactName[];
This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.
Instead use this:
contactName[index] = name;
this instruction will store the variable name in the contactName array at the index index
.
The second problem you have is that you don't have the variable index
.
What you can do is a loop with 12 iterations to fill all your arrays. (and index
will be your iteration variable)
Warning: do not use the following command unless you want to lose uncommitted work!
Using git reset
has been explained, but you asked for an explanation of the piped commands as well, so here goes:
git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached
The command git ls-files
lists all files git knows about. The option -z
imposes a specific format on them, the format expected by xargs -0
, which then invokes rm -f
on them, which means to remove them without checking for your approval.
In other words, "list all files git knows about and remove your local copy".
Then we get to git diff
, which shows changes between different versions of items git knows about. Those can be changes between different trees, differences between local copies and remote copies, and so on.
As used here, it shows the unstaged changes; the files you have changed but haven't committed yet. The option --name-only
means you want the (full) file names only and --diff-filter=D
means you're interested in deleted files only. (Hey, didn't we just delete a bunch of stuff?)
This then gets piped into the xargs -0
we saw before, which invokes git rm --cached
on them, meaning that they get removed from the cache, while the working tree should be left alone — except that you've just removed all files from your working tree. Now they're removed from your index as well.
In other words, all changes, staged or unstaged, are gone, and your working tree is empty. Have a cry, checkout your files fresh from origin or remote, and redo your work. Curse the sadist who wrote these infernal lines; I have no clue whatsoever why anybody would want to do this.
TL;DR: you just hosed everything; start over and use git reset
from now on.
For small functions like this you could just count by hand how many hops it is to the target, from the instruction under the branch instruction. If it branches backwards make that hop number negative. if that number doesn't require all 16 bits, then for every number to the left of the most significant of your hop number, make them 1's, if the hop number is positive make them all 0's Since most branches are close to they're targets, this saves you a lot of extra arithmetic for most cases.
I just discovered a workaround: You can make your local machine accessible by using http://localtunnel.com . You'll need to (temporarily) change some URLs used in your app code / html so links point to the temporary domain, but at least facebook can reach your machine.
public class TypedProperty<T> : Property
{
public T TypedValue
{
get { return (T)(object)base.Value; }
set { base.Value = value.ToString();}
}
}
I using converting via an object. It is a little bit simpler.
>>> some_string='A,B,C,D,E'
>>> new_tuple= tuple(some_string.split(','))
>>> new_tuple
('A', 'B', 'C', 'D', 'E')
Apologies for my previously mixed up answer.
Here is how to do:
myTreeView.SelectedNode = myTreeNode;
I have tested the code below and it works:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
treeView1.Nodes.Add("1", "1");
treeView1.Nodes.Add("2", "2");
treeView1.Nodes[0].Nodes.Add("1-1", "1-1");
TreeNode treeNode = treeView1.Nodes[0].Nodes.Add("1-2", "1-3");
treeView1.SelectedNode = treeNode;
MessageBox.Show(treeNode.IsSelected.ToString());
}
}
If you're testing for all zeros to avoid a warning on another numpy function then wrapping the line in a try, except block will save having to do the test for zeros before the operation you're interested in i.e.
try: # removes output noise for empty slice
mean = np.mean(array)
except:
mean = 0
$("#t").text($("#cb").find(":checked").val())
There are multiple solutions for this. If you want the page to be refreshed you actually don't need JavaScript, the browser can do it for you if you add this meta
tag in your head
tag.
<meta http-equiv="refresh" content="30">
The browser will then refresh the page every 30 seconds.
If you really want to do it with JavaScript, then you can refresh the page every 30 seconds with location.reload()
(docs) inside a setTimeout()
:
window.setTimeout(function () {
window.location.reload();
}, 30000);
If you don't need to refresh the whole page but only a part of it, I guess an Ajax call would be the most efficient way.
You could use the <pre>
tag
<div class="text">_x000D_
<pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</pre>_x000D_
abc_x000D_
def_x000D_
ghi_x000D_
</div>
_x000D_
There's a much simpler way to convert your XmlDocument to a string; use the OuterXml property. The OuterXml property returns a string version of the xml.
public string GetXMLAsString(XmlDocument myxml)
{
return myxml.OuterXml;
}
Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want
x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)
WORD.C <- function(WORDS){
require(wordcloud)
L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))
# Takes a dataframe and the text you want to display
FUN <- function(X, text){
windows()
wordcloud(X[, 1], X[, 2], min.freq=1)
mtext(text, 3, padj=-4.5, col="red") #what I'm trying that isn't working
}
# Now creates the sequence 1,...,length(L2)
# Loops over that and then create an anonymous function
# to send in the information you want to use.
lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})
# Since you asked about loops
# you could use i in seq_along(L2)
# instead of 1:length(L2) if you wanted to
#for(i in 1:length(L2)){
# FUN(L2[[i]], names(L2)[i])
#}
}
WORD.C(list.xy)
In both cases your inner dimension may be dynamically specified (i.e. taken from a variable), but the difference is in the outer dimension.
This question is basically equivalent to the following:
Is
int* x = new int[4];
"better" thanint x[4]
?
The answer is: "no, unless you need to choose that array dimension dynamically."
Had the same problem (is not a method) with jQuery when working on autocomplete. It appeared the code was executed before the autocomplete.js was loaded. So make sure the ui.colorpicker.js is loaded before calling colorpicker.
If you're in an async function you can simply do it in one line:
console.log(1);
await new Promise(resolve => setTimeout(resolve, 3000)); // 3 sec
console.log(2);
FYI, if target is NodeJS you can use this if you want (it's a predefined promisified setTimeout function):
await setTimeout[Object.getOwnPropertySymbols(setTimeout)[0]](3000) // 3 sec
File 1
class ClassA {
public $name = 'A';
public function getName(){
return $this->name;
}
}
File 2
include("file1.php");
class ClassB {
public $name = 'B';
public function getName(){
return $this->name;
}
public function callA(){
$a = new ClassA();
return $a->getName();
}
public static function callAStatic(){
$a = new ClassA();
return $a->getName();
}
}
$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();
The following seemed to work well for me:
=DATEDIF(B2, Today(), "D")
First, have to check
SELECT * FROM university
WHERE course_name LIKE '%&%'
Next, have to update
UPDATE university SET course_name = REPLACE(course_name, '&', '&') WHERE id = 1
Results: Engineering & Technology => Engineering & Technology
Intent i= new Intent(context, NextActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PowerBI Embedded requires TLS 1.2.
The answer above by Etienne Faucher is your solution. quick link to above answer... quick link to above answer... ( https://stackoverflow.com/a/45442874 )
PowerBI Requires TLS 1.2 June 2020 - This Is your Answer - Consider Forcing your IIS runtime to get up to 4.6 to force the default TLS 1.2 behavior you are looking for from the framework. The above answer gives you a config change only solution.
Symptoms: Forced Closed Rejected TCP/IP Connection to Microsoft PowerBI Embedded that just shows up all of a sudden across your systems.
These PowerBI Calls just stop working with a Hard TCP/IP Close error like a firewall would block a connection. Usually the auth steps work - it is when you hit the service for specific workspace and report id's that it fails.
This is the 2020 note from Microsoft PowerBI about TLS 1.2 required
PowerBIClient
methods that show this problem
GetReportsInGroupAsync GetReportsInGroupAsAdminAsync GetReportsAsync GetReportsAsAdminAsync Microsoft.PowerBI.Api HttpClientHandler Force TLS 1.1 TLS 1.2
Search Error Terms to help people find this: System.Net.Http.HttpRequestException: An error occurred while sending the request System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
If you are looking for a professional alternative, have a look at JEB Decompiler from PNF Software.
There is a demo version that will let you decompile most code.
using sizeof()
char h[] = "hello";
printf("%d\n",sizeof(h)-1); //Output = 5
using string.h
#include <string.h>
char h[] = "hello";
printf("%d\n",strlen(h)); //Output = 5
using function (
strlen
implementation)
int strsize(const char* str);
int main(){
char h[] = "hello";
printf("%d\n",strsize(h)); //Output = 5
return 0;
}
int strsize(const char* str){
return (*str) ? strsize(++str) + 1 : 0;
}
You would use the command Mechanical snail listed. Notice the uppercase O. Full command line to use could be:
wget www.examplesite.com/textfile.txt --output-document=newfile.txt
or
wget www.examplesite.com/textfile.txt -O newfile.txt
Hope that helps.
the "title"
attribute will be used as the text for tooltip by the browser, if you want to apply style to it consider using some plugins
I also encountered that problem.Check if database name already exist in Mysql,and rename the old one.
You could use base64:
function randomString(length)
{
var rtn = "";
do {
rtn += btoa("" + Math.floor(Math.random() * 100000)).substring(0, length);
}
while(rtn.length < length);
return rtn;
}
You need to edit the environment variable named PATH
, and add ;c:\python27
to the end of that. The semicolon separates one pathname from another (you will already have several things in your PATH
).
Alternately, you can just type
c:\python27\python
at the command prompt without having to modify any environment variables at all.
What is your opinion to use express-generator it will generate skeleton project to start with, without deprecated messages
appeared in your log
run this command
npm install express-generator -g
Now, create new Express.js starter application by type this command in your Node projects folder
.
express node-express-app
That command tell express to generate new Node.js application with the name node-express-app
.
then Go to the newly created project directory
, install npm packages
and start the app
using the command
cd node-express-app && npm install && npm start
Atom currently does not have a built-in terminal(that I know of), so you would have to install an additional package such as platformio-ide-terminal
.
The following screenshots were taken on a mac.
+
to Install a new packageSomething like this perhaps...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
#container
{
width:600px;
}
#head, #sub-title
{
width:100%;
}
#sub-left, #sub-right
{
width:50%;
float:left;
}
</style>
</head>
<body>
<div id="container">
<div id="head">
#head
</div>
<div id="sub-title">
#sub-title
<div id="sub-left">
#sub-left
</div>
<div id="sub-right">
#sub-right
</div>
</div>
</div>
</body>
</html>
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
It is totally possible, i did something similar based on the example of Mike Sav. That's the html page and ther shoul be an external test.js file in the same folder
example.html:
<html>
<button type="button" value="Submit" onclick="myclick()" >
Click here~!
<div id='mylink'></div>
</button>
<script type="text/javascript">
function myclick(){
var myLink = document.getElementById('mylink');
myLink.onclick = function(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "./test.js";
document.getElementsByTagName("head")[0].appendChild(script);
return false;
}
document.getElementById('mylink').click();
}
</script>
</html>
test.js:
alert('hello world')
First check if mingw32-make is installed on your system. Use mingw32-make.exe command in windows terminal or cmd to check, else install the package mingw32-make-bin.
then go to bin directory default ( C:\MinGW\bin) create new file make.bat
@echo off
"%~dp0mingw32-make.exe" %*
add the above content and save it
set the env variable in powershell
$Env:CC="gcc"
then compile the file
make hello
where hello.c is the name of source code
In my case:
<html>
<head>
<script type="text/javascript">
function changeFunction(val) {
//Show option value
console.log(val.value);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunction(this)">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
Prism 5 implementation:
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual bool SetProperty<T>(ref T storage,
T value,
[CallerMemberName] string propertyName = null)
{
if (object.Equals(storage, value)) return false;
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged(string propertyName)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
protected void OnPropertyChanged<T>(Expression<Func<T>> propertyExpression)
{
var propertyName = PropertySupport.ExtractPropertyName(propertyExpression);
this.OnPropertyChanged(propertyName);
}
}
public static class PropertySupport
{
public static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)
{
if (propertyExpression == null)
{
throw new ArgumentNullException("propertyExpression");
}
var memberExpression = propertyExpression.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("The expression is not a member access expression.", "propertyExpression");
}
var property = memberExpression.Member as PropertyInfo;
if (property == null)
{
throw new ArgumentException("The member access expression does not access a property.", "propertyExpression");
}
var getMethod = property.GetMethod;
if (getMethod.IsStatic)
{
throw new ArgumentException("The referenced property is a static property.", "propertyExpression");
}
return memberExpression.Member.Name;
}
}
I posted this answer because I have tried with most of the sed
commend example provided above which does not work for me in my Unix box and giving me error message Label too long: {:q;N;s/\n/ /g;t q}
. Finally I made my requirement and hence shared here which works in all Unix/Linux environment:-
line=$(while read line; do echo -n "$line "; done < yoursourcefile.txt)
echo $line |sed 's/ //g' > sortedoutput.txt
The first line will remove all the new line from file yoursourcefile.txt
and will produce a single line. And second sed
command will remove all the spaces from it.
CoreUtils referred to in other posts does NOT show the real implementation of most of the functionality which I think you seek. In most cases it provides front-ends for the actual functions that retrieve the data, which can be found here:
It is build upon Gnulib with the actual source code in the lib-subdirectory
I believe you can also accomplish this quite simply as follows:
e.g. #1:
# Libraries to import
import pandas as pd
import nump as np
#N x N numpy array (dimensions dont matter)
corr_mat #your numpy array
my_df = pd.DataFrame(corr_mat) #converting it to a pandas dataframe
e.g. #2:
#save as csv
my_df.to_csv('foo.csv', index=False) # "foo" is the name you want to give
# to csv file. Make sure to add ".csv"
# after whatever name like in the code
For Windows there are 2 installers. Did you use the bundle containing VirtualBox installer? It is call Windows 32/64 bits (with VirtualBox).
Enter the command
which python
//output:
/usr/bin/python
cd /usr/bin
ls -l
Here you can see something like this
lrwxrwxrwx 1 root root 9 Mar 7 17:04 python -> python2.7
your default python2.7 is soft linked to the text 'python'
So remove the softlink python
sudo rm -r python
then retry the above command
ls -l
you can see the softlink is removed
-rwxr-xr-x 1 root root 3670448 Nov 12 20:01 python2.7
Then create a new softlink for python3.6
ln -s /usr/bin/python3.6 python
Then try the command python
in terminal
//output:
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type help
, copyright
, credits
or license
for more information.
The below command worked for me :
conda install -c anaconda numpy
Wrap them around a div with the following CSS
.div_wrapper{
white-space: nowrap;
}
This is an example using the Expr() Class - I needed this too some days ago and it took me some time to find out what is the exact syntax and way of usage:
/**
* fetches Products that are more expansive than the given price
*
* @param int $price
* @return array
*/
public function findProductsExpensiveThan($price)
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$q = $qb->select(array('p'))
->from('YourProductBundle:Product', 'p')
->where(
$qb->expr()->gt('p.price', $price)
)
->orderBy('p.price', 'DESC')
->getQuery();
return $q->getResult();
}
Factory
and Service
is a just wrapper of a provider
.
Factory
Factory
can return anything which can be a class(constructor function)
, instance of class
, string
, number
or boolean
. If you return a constructor
function, you can instantiate in your controller.
myApp.factory('myFactory', function () {
// any logic here..
// Return any thing. Here it is object
return {
name: 'Joe'
}
}
Service
Service does not need to return anything. But you have to assign everything in this
variable. Because service will create instance by default and use that as a base object.
myApp.service('myService', function () {
// any logic here..
this.name = 'Joe';
}
Actual angularjs code behind the service
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
It just a wrapper around the factory
. If you return something from service
, then it will behave like Factory
.
IMPORTANT
: The return result from Factory and Service will be cache and same will be returned for all controllers.
When should i use them?
Factory
is mostly preferable in all cases. It can be used when you have constructor
function which needs to be instantiated in different controllers.
Service
is a kind of Singleton
Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application.
Eg: Authenticated user details.
For further understanding, read
http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html
http://viralpatel.net/blogs/angularjs-service-factory-tutorial/
XML has a much wider application than f.ex. HTML. It doesn't have an intrinsic, or default "application". So, while you might not really care that web pages are also governed by what's allowed, from the author's side, you'll probably want to precisely define what an XML document may and may not contain.
It's like designing a database.
The thing about XML technologies is that they are textual in nature. With XSD, it means you have a data structure definition framework that can be "plugged in" to text processing tools like PHP. So not only can you manipulate the data itself, but also very easily change and document the structure, and even auto-generate front-ends.
Viewed like this, XSD is the "glue" or "middleware" between data (XML) and data-processing tools.
Your code will count the number of tabs and not the number of spaces. Also, the number of tabs will be one less than arr.length
.
Swift 3:
self.btn.sendActions(for: .touchUpInside)
There are many way you can do this. Based on your requirement choose anything from below.
1. By REVERTing commit:
If you want to REVERT all the changes from you last COMMIT that means If you ADD something in your file that will be REMOVED after revert has been done. If you REMOVE something in your file the revert process will ADD those file.
You can REVERT the very last COMMIT. Like:
1.git revert head^
2.git push origin <Branch-Name>
Or you can revert to any previous commit using the hash of that commit.Like:
1.git revert <SHA>
2.git push origin <Branch-Name>
2. By RESETing previous Head
If you want to just point to any previous commit use reset; it points your local environment back to a previous commit. You can reset your head to previous commit or reset your head to previous any commit.
Reset to previous commit.
1.git reset head^
2.git push -f origin <Branch-name>
Reset to any previous commit:
1.git reset <SHA>
2.git push -f origin <Branch-name>
Trade of between REVERT & RESET:
Why would you choose to do a revert over a reset operation? If you have already pushed your chain of commits to the remote repository (where others may have pulled your code and started working with it), a revert is a nicer way to cancel out changes for them. This is because the Git workflow works well for picking up additional commits at the end of a branch, but it can be challenging if a set of commits is no longer seen in the chain when someone resets the branch pointer back.
The question is old, but I managed to figure out a simple way to have this in my app. You can create a C/C++ macro as shown below use it:
#ifndef MACROS_H
#define MACROS_H
#include <unistd.h>
#define msleep(X) usleep(X * 1000)
#endif // MACROS_H
<button type="button">my button</button>
we have to add attribute above in our button element
For anyone trying the answers to this question to get the stdout from a Python script note that Python buffers its stdout, and therefore it may take a while to see the stdout.
This can be rectified by adding the following after each stdout write in the target script:
sys.stdout.flush()
You could also use the verbatim environment
\begin{verbatim}
your
code
example
\end{verbatim}
first create file name it as footer.xml
put this code inside it.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="78dp"
android:layout_gravity="bottom"
android:gravity="bottom"
android:layout_weight=".15"
android:orientation="horizontal"
android:background="@drawable/actionbar_dark_background_tile" >
<ImageView
android:id="@+id/lborder"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/overlay" />
<ImageView
android:id="@+id/unknown"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/notcolor" />
<ImageView
android:id="@+id/open"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/openit"
/>
<ImageView
android:id="@+id/color"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/colored" />
<ImageView
android:id="@+id/rborder"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/frames"
android:layout_weight=".14" />
</LinearLayout>
then create header.xml and put this code inside it.:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="@dimen/action_bar_height"
android:layout_gravity="top"
android:baselineAligned="true"
android:orientation="horizontal"
android:background="@drawable/actionbar_dark_background_tile" >
<ImageView
android:id="@+id/contact"
android:layout_width="37dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight=".18"
android:scaleType="fitCenter"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/logo"/>
<ImageView
android:id="@+id/share"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/share" />
<ImageView
android:id="@+id/save"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/save" />
<ImageView
android:id="@+id/set"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/set" />
<ImageView
android:id="@+id/fix"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/light" />
<ImageView
android:id="@+id/rotate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/ic_menu_rotate" />
<ImageView
android:id="@+id/stock"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".14"
android:background="@drawable/action_bar_left_button"
android:src="@drawable/stock" />
</LinearLayout>
and then in your main_activity.xml
and put this code inside it :-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:id="@+id/relt"
android:background="@drawable/background" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="78dp"
android:id="@+id/down"
android:layout_alignParentBottom="true" >
<include
android:layout_width="fill_parent"
android:layout_height="78dp"
layout="@layout/footer" >
</include>
</LinearLayout>
<ImageView
android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/down"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/inc"
>
</ImageView>
<include layout="@layout/header"
android:id="@+id/inc"
android:layout_width="fill_parent"
android:layout_height="50dp"></include>
happy coding :)
My script to delete files older than a specific year :
@REM _______ GENERATE A CMD TO DELETE FILES OLDER THAN A GIVEN YEAR
@REM _______ (given in _olderthanyear variable)
@REM _______ (you must LOCALIZE the script depending on the dir cmd console output)
@REM _______ (we assume here the following line's format "11/06/2017 15:04 58 389 SpeechToText.zip")
@set _targetdir=c:\temp
@set _olderthanyear=2017
@set _outfile1="%temp%\deleteoldfiles.1.tmp.txt"
@set _outfile2="%temp%\deleteoldfiles.2.tmp.txt"
@if not exist "%_targetdir%" (call :process_error 1 DIR_NOT_FOUND "%_targetdir%") & (goto :end)
:main
@dir /a-d-h-s /s /b %_targetdir%\*>%_outfile1%
@for /F "tokens=*" %%F in ('type %_outfile1%') do @call :process_file_path "%%F" %_outfile2%
@goto :end
:end
@rem ___ cleanup and exit
@if exist %_outfile1% del %_outfile1%
@if exist %_outfile2% del %_outfile2%
@goto :eof
:process_file_path %1 %2
@rem ___ get date info of the %1 file path
@dir %1 | find "/" | find ":" > %2
@for /F "tokens=*" %%L in ('type %2') do @call :process_line "%%L" %1
@goto :eof
:process_line %1 %2
@rem ___ generate a del command for each file older than %_olderthanyear%
@set _var=%1
@rem LOCALIZE HERE (char-offset,string-length)
@set _fileyear=%_var:~0,4%
@set _fileyear=%_var:~7,4%
@set _filepath=%2
@if %_fileyear% LSS %_olderthanyear% echo @REM %_fileyear%
@if %_fileyear% LSS %_olderthanyear% echo @del %_filepath%
@goto :eof
:process_error %1 %2
@echo RC=%1 MSG=%2 %3
@goto :eof
Use this line of code:
moment.utc(moment.duration(4500, "seconds").asMilliseconds()).format("HH:mm:ss")
WHERE NULLIF(your_column, '') IS NOT NULL
Nowadays (4.5 years on), to make it easier for a human to read, I would just use
WHERE your_column <> ''
While there is a temptation to make the null check explicit...
WHERE your_column <> ''
AND your_column IS NOT NULL
...as @Martin Smith demonstrates in the accepted answer, it doesn't really add anything (and I personally shun SQL nulls entirely nowadays, so it wouldn't apply to me anyway!).
I took a few answers mentioned above and compiled this one, which can also generate a nice description for each target and it works for targets with variables too.
Example Makefile:
APPS?=app1 app2
bin: $(APPS:%=%.bin)
@# Help: A composite target that relies only on other targets
$(APPS:%=%.bin): %.bin:
echo "build binary"
@# Help: A target with variable name, value = $*
test:
echo $(MAKEFLAGS)
echo "starting test"
@# Help: A normal target without variables
# A target without any help description
clean:
echo $(MAKEFLAGS)
echo "Cleaning..."
MAKEOVERRIDES =
help:
@printf "%-20s %s\n" "Target" "Description"
@printf "%-20s %s\n" "------" "-----------"
@make -pqR : 2>/dev/null \
| awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' \
| sort \
| egrep -v -e '^[^[:alnum:]]' -e '^$@$$' \
| xargs -I _ sh -c 'printf "%-20s " _; make _ -nB | (grep -i "^# Help:" || echo "") | tail -1 | sed "s/^# Help: //g"'
Example output:
$ make help
Target Description
------ -----------
app1.bin A target with variable name, value = app1
app2.bin A target with variable name, value = app2
bin A composite target that relies only on other targets
clean
test A normal target without variables
How does it work:
The top part of the make help
target works exactly as posted by mklement0 here - How do you get the list of targets in a makefile?.
After getting the list of targets, it runs make <target> -nB
as a dry run for each target and parses the last line that starts with @# Help:
for the description of the target. And that or an empty string is printed in a nicely formatted table.
As you can see, the variables are even expanded within the description as well, which is a huge bonus in my book :).
Make sure ["key" : "type", "value" : "json"] & ["key":"Content-Type", "value":"application/x-www-form-urlencoded"] is in your postman request headers
I'm using XAMPP with Apache2.4, I had this same issue. I wanted to leave the default xampp/htdocs folder in place, be able to access it from locahost and have a Virtual Host to point to my dev area...
The full contents of my C:\xampp\apache\conf\extra\http-vhosts.conf
file is below...
# Virtual Hosts
#
# Required modules: mod_log_config
# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.
#
# Use name-based virtual hosting.
#
##NameVirtualHost *:80
#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ##ServerName or ##ServerAlias in any <VirtualHost> block.
#
##<VirtualHost *:80>
##ServerAdmin [email protected]
##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
##ServerName dummy-host.example.com
##ServerAlias www.dummy-host.example.com
##ErrorLog "logs/dummy-host.example.com-error.log"
##CustomLog "logs/dummy-host.example.com-access.log" common
##</VirtualHost>
##<VirtualHost *:80>
##ServerAdmin [email protected]
##DocumentRoot "C:/xampp/htdocs/dummy-host2.example.com"
##ServerName dummy-host2.example.com
##ErrorLog "logs/dummy-host2.example.com-error.log"
##CustomLog "logs/dummy-host2.example.com-access.log" common
##</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:\xampp\htdocs"
ServerName localhost
</VirtualHost>
<VirtualHost *:80>
DocumentRoot "C:\nick\static"
ServerName dev.middleweek.co.uk
<Directory "C:\nick\static">
Allow from all
Require all granted
</Directory>
</VirtualHost>
I then updated my C:\windows\System32\drivers\etc\hosts
file like this...
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com # x client host
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 dev.middleweek.co.uk
127.0.0.1 localhost
Restart your machine for good measure, open the XAMPP Control Panel and start Apache.
Now open your custom domain in your browser, in the above example, it'll be http://dev.middleweek.co.uk
Hope that helps someone!
And if you want to be able to view directory listings under your new Virtual host, then edit your VirtualHost block in C:\xampp\apache\conf\extra\http-vhosts.conf
to include "Options Indexes" like this...
<VirtualHost *:80>
DocumentRoot "C:\nick\static"
ServerName dev.middleweek.co.uk
<Directory "C:\nick\static">
Allow from all
Require all granted
Options Indexes
</Directory>
</VirtualHost>
Cheers, Nick
[edit based on this now being possible in recent versions]
[Updated Answer] You can query the following way to get back the name of class and the student id only if they are already enrolled.
db.student.find({},
{_id:0, name:1, students:{$elemMatch:{$eq:ObjectId("51780f796ec4051a536015cf")}}})
and you will get back what you expected:
{ "name" : "CS 101", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
{ "name" : "Literature" }
{ "name" : "Physics", "students" : [ ObjectId("51780f796ec4051a536015cf") ] }
[Original Answer] It's not possible to do what you want to do currently. This is unfortunate because you would be able to do this if the student was stored in the array as an object. In fact, I'm a little surprised you are using just ObjectId() as that will always require you to look up the students if you want to display a list of students enrolled in a particular course (look up list of Id's first then look up names in the students collection - two queries instead of one!)
If you were storing (as an example) an Id and name in the course array like this:
{
"_id" : ObjectId("51780fb5c9c41825e3e21fc6"),
"name" : "Physics",
"students" : [
{id: ObjectId("51780f796ec4051a536015cf"), name: "John"},
{id: ObjectId("51780f796ec4051a536015d0"), name: "Sam"}
]
}
Your query then would simply be:
db.course.find( { },
{ students :
{ $elemMatch :
{ id : ObjectId("51780f796ec4051a536015d0"),
name : "Sam"
}
}
}
);
If that student was only enrolled in CS 101 you'd get back:
{ "name" : "Literature" }
{ "name" : "Physics" }
{
"name" : "CS 101",
"students" : [
{
"id" : ObjectId("51780f796ec4051a536015cf"),
"name" : "John"
}
]
}
string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");
if (indexOfHyphen >= 0)
{
string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
Console.WriteLine(contentAfterLastHyphen );
}
I know the question is about Macs, but I got here searching the answer for Ubuntu, so I guess my answer could be useful to someone.
Easy way to do it: AltF3.
I am seeing starkly different runtimes when I take a for loop in g++ 4.7.0 and using
std::vector<double> x;
std::vector<double> y;
std::vector<double> prod;
for (int i = 0; i < 5000000; i++)
{
double r1 = ((double)rand() / double(RAND_MAX)) * 5;
double r2 = ((double)rand() / double(RAND_MAX)) * 5;
x.push_back(r1);
y.push_back(r2);
}
int sz = x.size();
#pragma omp parallel for
for (int i = 0; i< sz; i++)
prod[i] = x[i] * y[i];
the serial code (no openmp
) runs in 79 ms.
the "parallel for" code runs in 29 ms.
If I omit the for
and use #pragma omp parallel
, the runtime shoots up to 179ms,
which is slower than serial code. (the machine has hw concurrency of 8)
the code links to libgomp
It's pretty simple, just use Android:CenterInParent="true"
to center both in horizontal and vertical, or use Android:Horizontal="true"
to center in horizontal and Android:Vertical="true"
And make sure you write all this in RelaytiveLayout
Regex for password:
/^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[a-zA-Z!#$%&? "])[a-zA-Z0-9!#$%&?]{8,20}$/
Took me a while to figure out the restrictions, but I did it!
Restrictions: (Note: I have used >> and << to show the important characters)
{>>8,20}
{8,>>20}
(?=.*[A-Z])
(?=.*[a-z])
(?=.*\d)
(?=.*[a-zA-Z >>!#$%&? "<<])[a-zA-Z0-9 >>!#$%&?<< ]
A LITTLE NOTE: Be careful about loaders and minimize (Rails env.):
After seeing this error and trying every solution out there, i realised there was something wrong with my html loader.
I've set my Rails environment up to import HTML paths for my components successfully with this loader (config/loaders/html.js.
):
module.exports = {
test: /\.html$/,
use: [ {
loader: 'html-loader?exportAsEs6Default',
options: {
minimize: true
}
}]
}
After some hours efforts and countless of ReactiveFormsModule imports i saw that my formGroup
was small letters: formgroup
.
This led me to the loader and the fact that it downcased my HTML on minimize.
After changing the options, everything worked as it should, and i could go back to crying again.
I know that this is not an answer to the question, but for future Rails visitors (and other with custom loaders) i think this could be helpfull.
I guess you could use curl
and wget
, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.
Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx
, a text based browser.
Using case
#!/bin/bash
fun1 () {
echo "run function1"
[[ "$@" ]] && echo "options: $@"
}
fun2 () {
echo "run function2"
[[ "$@" ]] && echo "options: $@"
}
case $1 in
fun1) "$@"; exit;;
fun2) "$@"; exit;;
esac
fun1
fun2
This script will run functions fun1 and fun2 but if you start it with option fun1 or fun2 it'll only run given function with args(if provided) and exit. Usage
$ ./test
run function1
run function2
$ ./test fun2 a b c
run function2
options: a b c
There's no need for hacks or overflow. There's a pseudo-element for the dropdown arrow on IE:
select::-ms-expand {
display: none;
}
At the moment I am working "like" you, just on a lower scale, which is why I don't have a PoC for my suggestion.
However, I seem to find success in using pickle as caching system and outsourcing execution of various functions into files - executing these files from my commando / main file; For example i use a prepare_use.py to convert object types, split a data set into test, validating and prediction data set.
How does your caching with pickle work? I use strings in order to access pickle-files that are dynamically created, depending on which parameters and data sets were passed (with that i try to capture and determine if the program was already run, using .shape for data set, dict for passed parameters). Respecting these measures, i get a String to try to find and read a .pickle-file and can, if found, skip processing time in order to jump to the execution i am working on right now.
Using databases I encountered similar problems, which is why i found joy in using this solution, however - there are many constraints for sure - for example storing huge pickle sets due to redundancy. Updating a table from before to after a transformation can be done with proper indexing - validating information opens up a whole other book (I tried consolidating crawled rent data and stopped using a database after 2 hours basically - as I would have liked to jump back after every transformation process)
I hope my 2 cents help you in some way.
Greetings.
We can simply use
async: false
This will do your need.
To me, the solution that makes the most sense is to define a Callback
interface :
interface Callback {
void call();
}
and then to use it as parameter in the function you want to call :
void somewhereInYourCode() {
method(() -> {
// You've passed a lambda!
// method() is done, do whatever you want here.
});
}
void method(Callback callback) {
// Do what you have to do
// ...
// Don't forget to notify the caller once you're done
callback.call();
}
A lambda is not a special interface, class or anything else you could declare by yourself. Lambda
is just the name given to the () -> {}
special syntax, which allows better readability when passing single-method interfaces as parameter. It was designed to replace this :
method(new Callback() {
@Override
public void call() {
// Classic interface implementation, lot of useless boilerplate code.
// method() is done, do whatever you want here.
}
});
So in the example above, Callback
is not a lambda, it's just a regular interface ; lambda
is the name of the shortcut syntax you can use to implement it.
Go to C drive root in cmd Type dir /x This will list down the directories name with ~.use that instead of Program Files in your jdk path
File size by MySQL type:
Mike; Everytime I need to modify an XML document I work it this way:
//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");
node.Attributes[0].Value = newValue;
xmlDoc.Save(xmlFile);
//xmlFile is the path of your file to be modified
I hope you find it useful
In general, one doesn't expand out log(a + b)
; you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:
log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)
(In fact, this identity is often used when implementing log
in math libraries).
You need to use a pointer or a reference as the proper type is not known at this time the compiler can not instantiate it.
Instead try:
void action(const typename Subclass::mytype &var) {
(static_cast<Subclass*>(this))->do_action();
}
Just implemented my OWIN Service with Bearer (called access_token in the following) and Refresh Tokens. My insight into this is that you can use different flows. So it depends on the flow you want to use how you set your access_token and refresh_token expiration times.
I will describe two flows A and B in the follwing (I suggest what you want to have is flow B):
A) expiration time of access_token and refresh_token are the same as it is per default 1200 seconds or 20 minutes. This flow needs your client first to send client_id and client_secret with login data to get an access_token, refresh_token and expiration_time. With the refresh_token it is now possible to get a new access_token for 20 minutes (or whatever you set the AccessTokenExpireTimeSpan in the OAuthAuthorizationServerOptions to). For the reason that the expiration time of access_token and refresh_token are the same, your client is responsible to get a new access_token before the expiration time! E.g. your client could send a refresh POST call to your token endpoint with the body (remark: you should use https in production)
grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxx
to get a new token after e.g. 19 minutes to prevent the tokens from expiration.
B) in this flow you want to have a short term expiration for your access_token and a long term expiration for your refresh_token. Lets assume for test purpose you set the access_token to expire in 10 seconds (AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(10)
) and the refresh_token to 5 Minutes. Now it comes to the interesting part setting the expiration time of refresh_token: You do this in your createAsync function in SimpleRefreshTokenProvider class like this:
var guid = Guid.NewGuid().ToString();
//copy properties and set the desired lifetime of refresh token
var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
{
IssuedUtc = context.Ticket.Properties.IssuedUtc,
ExpiresUtc = DateTime.UtcNow.AddMinutes(5) //SET DATETIME to 5 Minutes
//ExpiresUtc = DateTime.UtcNow.AddMonths(3)
};
/*CREATE A NEW TICKET WITH EXPIRATION TIME OF 5 MINUTES
*INCLUDING THE VALUES OF THE CONTEXT TICKET: SO ALL WE
*DO HERE IS TO ADD THE PROPERTIES IssuedUtc and
*ExpiredUtc to the TICKET*/
var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);
//saving the new refreshTokenTicket to a local var of Type ConcurrentDictionary<string,AuthenticationTicket>
// consider storing only the hash of the handle
RefreshTokens.TryAdd(guid, refreshTokenTicket);
context.SetToken(guid);
Now your client is able to send a POST call with a refresh_token to your token endpoint when the access_token
is expired. The body part of the call may look like this: grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xx
One important thing is that you may want to use this code not only in your CreateAsync function but also in your Create function. So you should consider to use your own function (e.g. called CreateTokenInternal) for the above code. Here you can find implementations of different flows including refresh_token flow(but without setting the expiration time of the refresh_token)
Here is one sample implementation of IAuthenticationTokenProvider on github (with setting the expiration time of the refresh_token)
I am sorry that I can't help out with further materials than the OAuth Specs and the Microsoft API Documentation. I would post the links here but my reputation doesn't let me post more than 2 links....
I hope this may help some others to spare time when trying to implement OAuth2.0 with refresh_token expiration time different to access_token expiration time. I couldn't find an example implementation on the web (except the one of thinktecture linked above) and it took me some hours of investigation until it worked for me.
New info: In my case I have two different possibilities to receive tokens. One is to receive a valid access_token. There I have to send a POST call with a String body in format application/x-www-form-urlencoded with the following data
client_id=YOURCLIENTID&grant_type=password&username=YOURUSERNAME&password=YOURPASSWORD
Second is if access_token is not valid anymore we can try the refresh_token by sending a POST call with a String body in format application/x-www-form-urlencoded
with the following data grant_type=refresh_token&client_id=YOURCLIENTID&refresh_token=YOURREFRESHTOKENGUID
You don't use ls to get a file's permission information. You use the stat command. It will give you the numerical values you want. The "Unix Way" says that you should invent your own script using ls (or 'echo *') and stat and whatever else you like to give the information in the format you desire.
change the call to ereg_replace to use preg_replace instead
How about this...?
TextReader tr = new StringReader("<Root>Content</Root>");
XDocument doc = XDocument.Load(tr);
Console.WriteLine(doc);
This was taken from the MSDN docs for XDocument.Load, found here...
you have to create a instance of the class for calling the method..
You could decorate your view model property with the [DisplayFormat]
attribute:
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
ApplyFormatInEditMode = true)]
public DateTime MyDateTime { get; set; }
and in your view:
@Html.EditorFor(x => x.MyDate)
or, for displaying the value,
@Html.DisplayFor(x => x.MyDate)
Another possibility, which I don't recommend, is to use a weakly typed helper:
@Html.TextBox("MyDate", Model.MyDate.ToLongDateString())
You can do:
flask.jsonify(**data)
or
flask.jsonify(id=str(album.id), title=album.title)
Most of bootstrap datepickers as I write this answer are rather buggy when included in Bootstrap 4. In my view the least code adding solution is a jQuery plugin. I used this one https://plugins.jquery.com/datetimepicker/ - you can see its usage here: https://xdsoft.net/jqplugins/datetimepicker/ It sure is not as smooth as the whole BS interface, but it only requires its css and js files along with jQuery which is already included in bootstrap.
Going with Marcel's solution above to secure Forms Authentication cookie you should also update "authentication" config element to use SSL
<authentication mode="Forms">
<forms ... requireSSL="true" />
</authentication>
Other wise authentication cookie will not be https
See: http://msdn.microsoft.com/en-us/library/vstudio/1d3t3c61(v=vs.100).aspx
#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;
println("hello");
Your class Delivery
has no access modifier, which means it defaults to internal
. If you then try to expose a property of that type as public
, it won't work. Your type (class) needs to have the same, or higher access as your property.
More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx
Just add two lines of code to make orientation of recyclerview as horizontal. So add these lines when Initializing Recyclerview.
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
my_recycler.setLayoutManager(linearLayoutManager);
This works:
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
It will produce:
'abcdgxre'
You can also use a delimiter like a comma to produce:
'a,b,c,d,g,x,r,e'
By using:
','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
<context:annotation-config>
activates many different annotations in beans, whether they are defined in XML or through component scanning.
<context:component-scan>
is for defining beans without using XML
For further information, read:
Hi! In order to use percentage(%), you must define the % of it parent element. If you use body{height: 100%} it will not work because it parent have no percentage in height. In that case in order to work that body height you must add this in html{height:100%}
In other case to get rid of that defining parent percentage you can use
body{height:100vh}
vh stands for viewport height
I think it help
You can use the following endpoint to get the image.jfif instead of jpg:
https://graph.facebook.com/v3.2/{user-id}/picture
Note that you won't be able to see the image, only download it.
If you want to replace space below code worked for me in C#
Regex.Replace(Line,"\\\s","");
For Tab
Regex.Replace(Line,"\\\s\\\s","");
In Windows platform, these file types are used for certificate information. Normally used for SSL certificate and Public Key Infrastructure (X.509).
for more information visit:Certificate Files: .Cer x .Pvk x .Pfx
First you go to ova inside the folder and delete all files
C:\Users\UserName\AppData\Local\Genymobile\Genymotion\ova
After you uninstall the genymotion and virtual box. next you can do for install of genymotion and virtual box as check your support your OS(windows) capability version install then work fine.
Now you can create virtual device.
This way for work my windows 10 OS.
It is important to note that each jQuery()
call must actually return. If an exception is thrown in one, subsequent (unrelated) calls will never be executed.
This applies regardless of syntax. You can use jQuery()
, jQuery(function() {})
, $(document).ready()
, whatever you like, the behavior is the same. If an early one fails, subsequent blocks will never be run.
This was a problem for me when using 3rd-party libraries. One library was throwing an exception, and subsequent libraries never initialized anything.
try this
$('#div_id').animate({scrollTop:0}, '500', 'swing');
What I do when it happens is Disable the COM port into the Device Manager and Enable it again.
It stop the communications with another program or thread and become free for you.
I hope this works for you. Regards.
I use this method )
public delegate bool CompareValue<in T1, in T2>(T1 val1, T2 val2);
public static bool CompareTwoArrays<T1, T2>(this IEnumerable<T1> array1, IEnumerable<T2> array2, CompareValue<T1, T2> compareValue)
{
return array1.Select(item1 => array2.Any(item2 => compareValue(item1, item2))).All(search => search)
&& array2.Select(item2 => array1.Any(item1 => compareValue(item1, item2))).All(search => search);
}
You can access the same environment variables from groovy using the same names (e.g. JOB_NAME
or env.JOB_NAME
).
From the documentation:
Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):
env.MYTOOL_VERSION = '1.33' node { sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start' }
These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.
For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job
This will disable/enable the options when you select/remove them, respectively.
$("#theSelect").change(function(){
var value = $(this).val();
if (value === '') return;
var theDiv = $(".is" + value);
var option = $("option[value='" + value + "']", this);
option.attr("disabled","disabled");
theDiv.slideDown().removeClass("hidden");
theDiv.find('a').data("option",option);
});
$("div a.remove").click(function () {
$(this).parent().slideUp(function() { $(this).addClass("hidden"); });
$(this).data("option").removeAttr('disabled');
});
At first I was stuck trying to figure out out to "insert" the Guest Additions CD image in Windows because I presumed it was a separate download that I would have to mount or somehow attach to the virtual CD drive. But just going through the Mac VirtualBox Devices menu and picking "Insert Guest Additions CD Image..." seemed to do the trick. Nothing to mount, nothing to "insert".
Elsewhere I found that the Guest Additions update was part of the update package, so I guess the new VB found the new GA CD automatically when Windows went looking. I wish I had known that to start.
Also, it appears that when I installed the Guest Additions on my Linked Base machine, it propagated to the other machines that were based on it. Sweet. Only one installation for multiple "machines".
I still haven't found that documented, but it appears to be the case (probably I'm not looking for the right explanation terms because I don't already know the explanation). How that works should probably be a different thread.
Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit
<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
{{$index}} - {{day.iso}} - {{day.name}}
Temperature: {{f.temperature}}<br>
Humidity: {{f.humidity}}<br>
...
</div>
Example: http://jsfiddle.net/coma/UV4qF/
Criteria / factors | Sessions | Cookies |
---|---|---|
Epoch (start of existence) | Created BEFORE an HTTP response | Created AFTER an HTTP response |
Availability during the first HTTP request | YES | NO |
Availability during the succeeding HTTP requests | YES | YES |
Ultimate control for the data and expiration | Server administrator | End-user |
Default expiration | Expires earlier than cookies | Lasts longer than sessions |
Server costs | Memory | Memory |
Network costs | None | Unnecessary extra bytes |
Browser costs | None | Memory |
Security | Difficult to hijack | Easy to hijack |
Deprecation | None | Now discouraged in favor of the JavaScript "Web Storage" |
Advantages and disadvantages are subjective. They can result in a dichotomy (an advantage for some, but considered disadvantage for others). Instead, I laid out above the factors that can help you decide which one to pick.
Let's just say you are a server-side person who wants to process both the session and cookie. The first HTTP handshake will go like so:
In step 1, the browser have no idea of the contents of both sessions and cookies. In step 4, the server can have the opportunity to set the values of the session and cookies.
Let's say in a single web page you are loading 20 resources hosted by example.com
, those 20 resources will carry extra bytes of information about the cookies. Even if it's just a resource request for CSS or a JPG image, it would still carry cookies in their headers on the way to the server. Should an HTTP request to a JPG resource carry a bunch of unnecessary cookies?
There is no replacement for sessions. For cookies, there are many other options in storing data in the browser rather than the old school cookies.
Session is safer for storing user data because it can not be modified by the end-user and can only be set on the server-side. Cookies on the other hand can be hijacked because they are just stored on the browser.
If it's errors you want to hide you can do it like this
$ErrorActionPreference = "SilentlyContinue"; #This will hide errors
$someObject.SomeFunction();
$ErrorActionPreference = "Continue"; #Turning errors back on
I think you put the function in the $(document).ready....... The functions are always provided out the $(document).ready.......
That header file is not part of the C++ standard, is therefore non-portable, and should be avoided.
Moreover, even if there were some catch-all header in the standard, you would want to avoid it in lieu of specific headers, since the compiler has to actually read in and parse every included header (including recursively included headers) every single time that translation unit is compiled.
Enable:
private void enableEditText() {
mEditText.setFocusableInTouchMode(true);
mEditText.setFocusable(true);
mEditText.setEnabled(true);
}
Disable:
private void disableEditText() {
mEditText.setEnabled(false);
mEditText.setFocusable(false);
mEditText.setFocusableInTouchMode(false);
}
Refining upon the answers found here:
getCurrentScript and getCurrentScriptPath
I came up with the following:
//Thanks to https://stackoverflow.com/a/27369985/5175935
var getCurrentScript = function () {
if ( document.currentScript && ( document.currentScript.src !== '' ) )
return document.currentScript.src;
var scripts = document.getElementsByTagName( 'script' ),
str = scripts[scripts.length - 1].src;
if ( str !== '' )
return src;
//Thanks to https://stackoverflow.com/a/42594856/5175935
return new Error().stack.match(/(https?:[^:]*)/)[0];
};
//Thanks to https://stackoverflow.com/a/27369985/5175935
var getCurrentScriptPath = function () {
var script = getCurrentScript(),
path = script.substring( 0, script.lastIndexOf( '/' ) );
return path;
};
Use this command to update react npm install --save [email protected]
Don't forget to change 16.12.0 to the latest version or the version you need to setup.
For one, you can't modify string literals. It's undefined behavior.
To fix that you can make str
a local array:
char str[] = "First string";
Now, you will have a second problem, is that str
isn't large enough to hold str2
. So you will need to increase the length of it. Otherwise, you will overrun str
- which is also undefined behavior.
To get around this second problem, you either need to make str
at least as long as str2
. Or allocate it dynamically:
char *str2 = "Second string";
char *str = malloc(strlen(str2) + 1); // Allocate memory
// Maybe check for NULL.
strcpy(str, str2);
// Always remember to free it.
free(str);
There are other more elegant ways to do this involving VLAs (in C99) and stack allocation, but I won't go into those as their use is somewhat questionable.
As @SangeethSaravanaraj pointed out in the comments, everyone missed the #import
. It should be #include
:
#include <stdio.h>
#include <string.h>
Try gnuplot. It has very powerful graphing possibilities.
It can output to your terminal in the following way:
gnuplot> set terminal dumb
Terminal type set to 'dumb'
Options are 'feed 79 24'
gnuplot> plot sin(x)
1 ++----------------**---------------+----**-----------+--------**-----++
+ *+ * + * * + sin(x) ****** +
0.8 ++ * * * * * * ++
| * * * * * * |
0.6 ++ * * * * * * ++
* * * * * * * |
0.4 +* * * * * * * ++
|* * * * * * * |
0.2 +* * * * * * * ++
| * * * * * * * |
0 ++* * * * * * *++
| * * * * * * *|
-0.2 ++ * * * * * * *+
| * * * * * * *|
-0.4 ++ * * * * * * *+
| * * * * * * *
-0.6 ++ * * * * * * ++
| * * * * * * |
-0.8 ++ * * * * * * ++
+ * * + * * + * * +
-1 ++-----**---------+----------**----+---------------**+---------------++
-10 -5 0 5 10
Here's another option:
df.replace(to_replace=[None], value=np.nan, inplace=True)
As mentioned in other answer, best solution is using
parse_url()
You need to use combination of parse_url()
and parse_str()
.
The parse_url()
parse URL and return its components that you can get query string using query
key. Then you should use parse_str()
that parse query string and return
values into variable.
$url = "https://example.com/test/1234?basic=2&[email protected]";
parse_str(parse_url($url)['query'], $params);
echo $params['email']; // [email protected]
Also you can do this work using regex.
preg_match()
You can use preg_match()
to get specific value of query string from URL.
preg_match("/&?email=([^&]+)/", $url, $matches);
echo $matches[1]; // [email protected]
preg_replace()
Also you can use preg_replace()
to do this work in one line!
$email = preg_replace("/^https?:\/\/.*\?.*email=([^&]+).*$/", "$1", $url);
// [email protected]
Simply with command line:
javac MyApp.java
jar -cf myJar.jar MyApp.class
Sure IDEs avoid using command line terminal
The simplest solution is to go to your XML layout containing your webview. Change your android:layout_width and android:layout_height from "wrap_content" to "match_parent".
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"/>
When you use Apache with mod_php apache is enforced in prefork
mode, and not worker
. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).
So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :
StartServers 20
MinSpareServers 5
MaxSpareServers 10
MaxClients 1024
MaxRequestsPerChild 0
This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.
See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.
Now you set 1024
MaxClients
. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.
So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:
<IfModule prefork.c>
StartServers 12
MinSpareServers 12
MaxSpareServers 12
MaxClients 12
MaxRequestsPerChild 300
</IfModule>
That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300
means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).ListenBacklog
queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe
And yes, that means you cannot handle more than 12 parallel requests.
If you want to handle more requests:
If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?
And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.
Update: About internal dummy connections (if it's your problem, but maybe not).
Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.
If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]
Update:
Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.
Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l
or apache2 -l
on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:
<IfModule worker.c>
StartServers 3
MaxClients 500
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestsPerChild 300
</IfModule>
You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:
<IfModule worker.c>
StartServers 2
MaxClients 250
MinSpareThreads 50
MaxSpareThreads 150
ThreadsPerChild 25
MaxRequestsPerChild 300
</IfModule>
Java projects are exported as Jar executables. When you wanna do a .exe file of a java project, what you can do is 'convert' the JAR to EXE (i remark that i putted between quotes convert because isn't exactly this).
From intelij you gonna be able to generate only the jar
Try following the next example : https://www.genuinecoder.com/convert-java-jar-to-exe/
I am assuming that test.html is a static file.To render static files use the static middleware like so.
app.use(express.static(path.join(__dirname, 'public')));
This tells express to look for static files in the public directory of the application.
Once you have specified this simply point your browser to the location of the file and it should display.
If however you want to render the views then you have to use the appropriate renderer for it.The list of renderes is defined in consolidate.Once you have decided which library to use just install it.I use mustache so here is a snippet of my config file
var engines = require('consolidate');
app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');
What this does is tell express to
look for files to render in views directory
Render the files using mustache
The extension of the file is .html(you can use .mustache too)
you can't call sendRedirect(), after you have already used forward(). So, you get that exception.
I've encountered the same problem in OSX.
I've tried to replace the things like
$cfg['Servers'][$i]['usergroups'] to $cfg['Servers'][$i]['pma__usergroups']
...
It works in safari but still fails in chrome.
But the so called 'work' in safari can get the message that the features which have been modified are not in effect at all.
However, the 'work' means that I can access the dbs listed left.
I think this problem maybe a bug in the new version of XAMPP, since the #1932 problems in google is new and boomed.
You can have a try at an older version of XAMPP instead until the bug is solved.
http://sourceforge.net/projects/xampp/files/XAMPP%20Linux/5.6.12/
Hope it can help you.
No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.
I found the solution : it's the 9th byte of this key :
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections] "DefaultConnectionSettings"=hex:3c,00,00,00,1f,00,00,00,05,00,00,00,00,00,00, 00,00,00,00,00,00,00,00,00,01,00,00,00,1f,00,00,00,68,74,74,70,3a,2f,2f,31, 34,34,2e,31,33,31,2e,32,32,32,2e,31,36,37,2f,77,70,61,64,2e,64,61,74,90,0e, 1e,66,d3,88,c5,01,01,00,00,00,8d,a8,4e,9e,00,00,00,00,00,00,00,00
It's a bitfield:
Mask 0x8 to turn it off, i.e., subtract 8 if it's higher than 8.
Thanks to Jamie on google groups.
Update
Based on the VBScript by WhoIsRich combined with details in this answer, here's a PowerShell script to amend these & related settings:
function Set-ProxySettings {
[CmdletBinding()]
param ( #could improve with parameter sets
[Parameter(Mandatory = $false)]
[bool]$AutomaticDetect = $true
,
[Parameter(Mandatory = $false)]
[bool]$UseProxyForLAN = $false
,
[Parameter(Mandatory = $false)]
[AllowNull()][AllowEmptyString()]
[string]$ProxyAddress = $null
,
[Parameter(Mandatory = $false)]
[int]$ProxyPort = 8080 #closest we have to a default port for proxies
,
[AllowNull()][AllowEmptyString()]
[bool]$UseAutomaticConfigurationScript = $false
)
begin {
[string]$ProxyRegRoot = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
[string]$DefaultConnectionSettingsPath = (Join-Path $ProxyRegRoot 'Connections')
[byte]$MaskProxyEnabled = 2
[byte]$MaskUseAutomaticConfigurationScript = 4
[byte]$MaskAutomaticDetect = 8
[int]$ProxyConnectionSettingIndex = 8
}
process {
#this setting is affected by multiple options, so fetch once here
[byte[]]$DefaultConnectionSettings = Get-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' | Select-Object -ExpandProperty 'DefaultConnectionSettings'
#region auto detect
if($AutomaticDetect) {
Set-ItemProperty -Path $ProxyRegRoot -Name AutoDetect -Value 1
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskAutomaticDetect
} else {
Set-ItemProperty -Path $ProxyRegRoot -Name AutoDetect -Value 0
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskAutomaticDetect)
}
#endregion
#region defined proxy
if($UseProxyForLAN) {
if(-not ([string]::IsNullOrWhiteSpace($ProxyAddress))) {
Set-ItemProperty -Path $ProxyRegRoot -Name ProxyServer -Value ("{0}:{1}" -f $ProxyAddress,$ProxyPort)
}
Set-ItemProperty -Path $ProxyRegRoot -Name ProxyEnable -Value 1
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskProxyEnabled
} else {
Set-ItemProperty -Path $ProxyRegRoot -Name ProxyEnable -Value 0
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskProxyEnabled)
}
#endregion
#region config script
if($UseAutomaticConfigurationScript){
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -bor $MaskUseAutomaticConfigurationScript
}else{
$DefaultConnectionSettings[$ProxyConnectionSettingIndex] = $DefaultConnectionSettings[$ProxyConnectionSettingIndex] -band (-bnot $MaskUseAutomaticConfigurationScript)
}
#endregion
#persist the updates made above
Set-ItemProperty -Path $DefaultConnectionSettingsPath -Name 'DefaultConnectionSettings' -Value $DefaultConnectionSettings
}
}
If anyone getting this in unit/instrumentation testing, make sure you call getFilesDir()
on the app context, not the test context. i.e. use:
Context appContext = getInstrumentation().getTargetContext().getApplicationContext();
not
Context appContext = InstrumentationRegistry.getContext;
For fields where NULL
is acceptable, you could use var_export($var, true)
to output the string
, integer
, or NULL
literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.
For example:
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");
In my case the program (elinks) returned lines that looked empty, but in fact had special terminal characters, color control codes and backspace, so grep
options presented in other answers did not work for me. So I wrote this small script in Node.js. I called the file tight
, but that's just a random name.
#!/usr/bin/env node
function visible(a) {
var R = ''
for (var i = 0; i < a.length; i++) {
if (a[i] == '\b') { R -= 1; continue; }
if (a[i] == '\u001b') {
while (a[i] != 'm' && i < a.length) i++
if (a[i] == undefined) break
}
else R += a[i]
}
return R
}
function empty(a) {
a = visible(a)
for (var i = 0; i < a.length; i++) {
if (a[i] != ' ') return false
}
return true
}
var readline = require('readline')
var rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false })
rl.on('line', function(line) {
if (!empty(line)) console.log(line)
})
@ivelin: UUID can have capitals. So you'll either need to toLowerCase() the string or use:
[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}
Would have just commented this but not enough rep :)
Just in case, if someone is looking for a similar problem...
Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code). Instead, you can use a simple list comprehension.
[print(i) for i in x]
BTW, the return values will be a list on None s.
I had a requirement to take values from text file and use as key value pair. i have content in text file as key = value, so i have used split method with separator as "=" and wrote below code
d = {}
file = open("filename.txt")
for x in file:
f = x.split("=")
d.update({f[0].strip(): f[1].strip()})
By using strip method any spaces before or after the "=" separator are removed and you will have the expected data in dictionary format
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
A more Git based approach would be to make the changes to your local copy using cd
or copy and pasting and then pushing these changes from local to remote repository.
If you try checking status of your local repo, it may show "untracked changes" which are actually the relocated files. To push these changes forcefully, you need to stage these files/directories by using
$ git add -A
#And commiting them
$ git commit -m "Relocating image demo files"
#And finally, push
$ git push -u local_repo -f HEAD:master
Hope it helps.
Ctrl+Shift+Space shows the Edit.ParameterInfo
for the selected method, and by selected method I mean the caret must be within the method parentheses.
Here is the Visual Studio 2010 Keybinding Poster.
And for those still using 2008.
I solve this problem by adding extension method to IEnumerable.
public static class DataTableEnumerate
{
public static void Fill<T> (this IEnumerable<T> Ts, ref DataTable dt) where T : class
{
//Get Enumerable Type
Type tT = typeof(T);
//Get Collection of NoVirtual properties
var T_props = tT.GetProperties().Where(p => !p.GetGetMethod().IsVirtual).ToArray();
//Fill Schema
foreach (PropertyInfo p in T_props)
dt.Columns.Add(p.Name, p.GetMethod.ReturnParameter.ParameterType.BaseType);
//Fill Data
foreach (T t in Ts)
{
DataRow row = dt.NewRow();
foreach (PropertyInfo p in T_props)
row[p.Name] = p.GetValue(t);
dt.Rows.Add(row);
}
}
}
Explanation with an example:
Consider you have a game (iso) image in your computer.
When you run
(mount your image as a virtual drive), a virtual drive is created with all the game contents in the virtual drive and the game installation file is automatically launched. [Running your docker image - creating a container and then starting it.]
But when you stop
(similar to docker stop) it, the virtual drive still exists but stopping all the processes. [As the container exists till it is not deleted]
And when you do start
(similar to docker start), from the virtual drive the games files start its execution. [starting the existing container]
In this example - The game image is your Docker image and virtual drive is your container.
Remapped to in my .vimrc.local file, quick and dirty but very functional:
" Clear last search highlighting
map <Space> :noh<cr>