If you're using .NET 3.5 or .NET 4, it's easy to create the dictionary using LINQ:
Dictionary<string, ArrayList> result = target.GetComponents()
.ToDictionary(x => x.Key, x => x.Value);
There's no such thing as an IEnumerable<T1, T2>
but a KeyValuePair<TKey, TValue>
is fine.
You can use the time()
method of datetime
objects to get the time of day, which you can use for comparison without taking the date into account:
>>> this_morning = datetime.datetime(2009, 12, 2, 9, 30)
>>> last_night = datetime.datetime(2009, 12, 1, 20, 0)
>>> this_morning.time() < last_night.time()
True
Two things are important for above solutions to work:
When applying bindings, you need to specify scope (element) !!
When clearing bindings, you must specify exactly same element used for scope.
Code is below
Markup
<div id="elt1" data-bind="with: data">
<input type="text" data-bind="value: text1" >
</form>
Binding view
var myViewModel = {
"data" : {
"text1" : "bla bla"
}
}:
Javascript
ko.applyBindings(myViewModel, document.getElementById('elt1'));
Clear bindings
ko.cleanNode(document.getElementById('elt1'));
I've found this css (scss) solution that works quite well. On webkit browsers it shows the ellipsis and on other browsers it just truncates the text. Which is fine for my intended use.
$font-size: 26px;
$line-height: 1.4;
$lines-to-show: 3;
h2 {
display: block; /* Fallback for non-webkit */
display: -webkit-box;
max-width: 400px;
height: $font-size*$line-height*$lines-to-show; /* Fallback for non-webkit */
margin: 0 auto;
font-size: $font-size;
line-height: $line-height;
-webkit-line-clamp: $lines-to-show;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
An example by the creator: http://codepen.io/martinwolf/pen/qlFdp
string mypath = @"..\folder1\folder2\folder2";
string[] directories = mypath.Split(Path.DirectorySeparatorChar);
Edit: This returns each individual folder in the directories array. You can get the number of folders returned like this:
int folderCount = directories.Length;
range()
can only work with integers, but dividing with the /
operator always results in a float value:
>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
Make the value an integer again:
for i in range(int(c / 10)):
or use the //
floor division operator:
for i in range(c // 10):
I'll answer this question via Simple Javascript that is supported in all browsers that I have tested so far (IE8 to IE11, Chrome, FF etc).
Here is the code.
function GetFileSizeNameAndType()_x000D_
{_x000D_
var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE._x000D_
_x000D_
var totalFileSize = 0;_x000D_
_x000D_
// VALIDATE OR CHECK IF ANY FILE IS SELECTED._x000D_
if (fi.files.length > 0)_x000D_
{_x000D_
// RUN A LOOP TO CHECK EACH SELECTED FILE._x000D_
for (var i = 0; i <= fi.files.length - 1; i++)_x000D_
{_x000D_
//ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE_x000D_
var fsize = fi.files.item(i).size;_x000D_
totalFileSize = totalFileSize + fsize;_x000D_
document.getElementById('fp').innerHTML =_x000D_
document.getElementById('fp').innerHTML_x000D_
+_x000D_
'<br /> ' + 'File Name is <b>' + fi.files.item(i).name_x000D_
+_x000D_
'</b> and Size is <b>' + Math.round((fsize / 1024)) //DEFAULT SIZE IS IN BYTES SO WE DIVIDING BY 1024 TO CONVERT IT IN KB_x000D_
+_x000D_
'</b> KB and File Type is <b>' + fi.files.item(i).type + "</b>.";_x000D_
}_x000D_
}_x000D_
document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is <b>" + Math.round(totalFileSize / 1024) + "</b> KB";_x000D_
}
_x000D_
<p>_x000D_
<input type="file" id="file" multiple onchange="GetFileSizeNameAndType()" />_x000D_
</p>_x000D_
_x000D_
<div id="fp"></div>_x000D_
<p>_x000D_
<div id="divTotalSize"></div>_x000D_
</p>
_x000D_
*Please note that we are displaying filesize in KB (Kilobytes). To get in MB divide it by 1024 * 1024 and so on*.
erm it does work? I've just tested it?
/****** Object: Table [dbo].[DateTest] Script Date: 09/26/2008 10:44:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DateTest](
[Date1] [datetime] NULL,
[Date2] [datetime] NOT NULL
) ON [PRIMARY]
GO
Insert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008')
Insert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008')
Go
SELECT * FROM DateTest WHERE Date1 is not NULL
GO
SELECT * FROM DateTest WHERE Date2 is not NULL
Well, I meant that I need to parse object like this: var jsonObj = {"first name" : "fname"}
. But, I don't actually. Because it's already an JSON.
Want something quick?
public static class StringExtensions
{
public static string ToAlphaNumeric(this string self, params char[] allowedCharacters)
{
return new string(Array.FindAll(self.ToCharArray(), c => char.IsLetterOrDigit(c) || allowedCharacters.Contains(c)));
}
}
This will allow you to specify which characters you want to allow as well.
For me the problem was that I was running the migration commands inside the wrong project. Running the commands inside the project that contained the Startup.cs rather than the project that contained the DbContext allowed me to move past this particular problem.
$(document).ready(function() {
$('#div_one').bind('click', function() {
$('#div_two').addClass('large');
});
});
If I understood your question.
Or you can modify css directly:
var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');
It's a bit more readable using literals:
self.navigationController.navigationBar.titleTextAttributes = @{
NSFontAttributeName:[UIFont fontWithName:@"mplus-1c-regular" size:21],
NSForegroundColorAttributeName: [UIColor whiteColor]
};
Using one line to convert the dates to preferred format:
nzd$date <- format(as.Date(nzd$date, format="%d/%m/%Y"),"%Y/%m/%d")
As Bhavik Shah says, you can do it in JAVA_OPTS, but the recommended way (as per catalina.sh) is to use CATALINA_OPTS:
# CATALINA_OPTS (Optional) Java runtime options used when the "start",
# "run" or "debug" command is executed.
# Include here and not in JAVA_OPTS all options, that should
# only be used by Tomcat itself, not by the stop process,
# the version command etc.
# Examples are heap size, GC logging, JMX ports etc.
# JAVA_OPTS (Optional) Java runtime options used when any command
# is executed.
# Include here and not in CATALINA_OPTS all options, that
# should be used by Tomcat and also by the stop process,
# the version command etc.
# Most options should go into CATALINA_OPTS.
Redirect the output to DEVNULL:
import os
import subprocess
FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'],
stdout=FNULL,
stderr=subprocess.STDOUT)
It is effectively the same as running this shell command:
retcode = os.system("echo 'foo' &> /dev/null")
Update: This answer applies to the original question relating to python 2.7. As of python >= 3.3 an official subprocess.DEVNULL
symbol was added.
retcode = subprocess.call(['echo', 'foo'],
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)
Regexes can also limit the number of characters.
r = re.compile("^[a-z]{1,15}$")
gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.
Deployment descriptor file "web.xml" : Through the proper use of the deployment descriptor file, web.xml, you can control many aspects of the Web application behavior, from preloading servlets, to restricting resource access, to controlling session time-outs.
web.xml : is used to control many facets of a Web application. Using web.xml, you can assign custom URLs for invoking servlets, specify initialization parameters for the entire application as well as for specific servlets, control session timeouts, declare filters, declare security roles, restrict access to Web resources based on declared security roles, and so on.
I recently solved this problem by using table-caption, though I cannot say if it is recommended. The other answers didn't seem to workout in my case.
h1 {
display: table-caption;
}
According to spark documentation "where()
is an alias for filter()
"
filter(condition)
Filters rows using the given condition.
where()
is an alias for filter()
.
Parameters: condition – a Column
of types.BooleanType
or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]
>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]
Right click and open SVN Repo-browser:
Right click on Trunk (working copy) and choose Copy to...:
Input the respective branch's name/path:
Click OK, type the respective log message, and click OK.
Using EntityManager em;
public User getUserById(Long id) {
return em.getReference(User.class, id);
}
No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.
XML has only one definition for a comment:
'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
XML forbids --
in comments to maintain compatibility with SGML.
Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:
var http = require('http')
var fs = require('fs')
fs.readFile('image.jpg', function(err, data) {
if (err) throw err // Fail if the file can't be read.
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'image/jpeg'})
res.end(data) // Send the file data to the browser.
}).listen(8124)
console.log('Server running at http://localhost:8124/')
})
Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg
.
[Edit] You could even embed the image in an HTML page directly by using an <img>
with a data URI source. For example:
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><body><img src="data:image/jpeg;base64,')
res.write(Buffer.from(data).toString('base64'));
res.end('"/></body></html>');
See ?order
. You just need the last index (or first, in decreasing order), so this should do the trick:
order(matrix[,2],decreasing=T)[1]
check this link. It has helped me with errno 150: http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/
On the top of my head two things come to mind.
I'm guessing the problem is with the set NULL on update (if my brains aren't on backwards today as they so often are...).
Edit: I missed the comments on your original post. Unsigned/not unsigned int columns maybe resolved your case. Hope my link helps someone in the future thought.
Hoho.. It should be very easy to use Gallery to implement this, using ViewPager is much harder. But i still encourage to use ViewPager since Gallery really have many problems and is deprecated since android 4.2.
In PagerAdapter there is a method getPageWidth() to control page size, but only by this you cannot achieve your target.
Try to read the following 2 articles for help.
To answer this question it's critical whether the Java VM is in CLIENT or SERVER mode. You can specify "-client" or "-server" options. Otherwise java uses internal rules; basically win32 is always client and Linux is always server, but see the table here:
http://docs.oracle.com/javase/6/docs/technotes/guides/vm/server-class.html
Sun/Oracle jre6u18 doc says re client: the VM gets 1/2 of physical memory if machine has <= 192MB; 1/4 of memory if machine has <= 1Gb; max 256Mb. In my test on a 32bit WindowsXP system with 2Gb phys mem, Java allocated 256Mb, which agrees with the doc.
Sun/Oracle jre6u18 doc says re server: same as client, then adds confusing language: for 32bit JVM the default max is 1Gb, and for 64 bit JVM the default is 32Gb. In my test on a 64bit linux machine with 8Gb physical, Java allocates 2Gb, which is 1/4 of physical; on a 64bit linux machine with 128Gb physical Java allocates 32Gb, again 1/4 of physical.
Thanks to this SO post for guiding me:
If you are manually making your entity's CoreDataClass and CoreDataProperties, make sure you go to your xcdatamodel and set the Codegen in the inspector tab to "Manual/None". Xcode will automatically create a duplicate class for you if this is set as "Class Definition".
use OTHER OPEN memorystream:
example for lauch pdf and send pdf in MVC4 C# Controller
public void ToPdf(string uco, int idAudit)
{
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment;filename= Document.pdf");
Response.Buffer = true;
Response.Clear();
//get the memorystream pdf
var bytes = new MisAuditoriasLogic().ToPdf(uco, idAudit).ToArray();
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.OutputStream.Flush();
}
public ActionResult ToMail(string uco, string filter, int? page, int idAudit, int? full)
{
//get the memorystream pdf
var bytes = new MisAuditoriasLogic().ToPdf(uco, idAudit).ToArray();
using (var stream = new MemoryStream(bytes))
using (var mailClient = new SmtpClient("**YOUR SERVER**", 25))
using (var message = new MailMessage("**SENDER**", "**RECEIVER**", "Just testing", "See attachment..."))
{
stream.Position = 0;
Attachment attach = new Attachment(stream, new System.Net.Mime.ContentType("application/pdf"));
attach.ContentDisposition.FileName = "test.pdf";
message.Attachments.Add(attach);
mailClient.Send(message);
}
ViewBag.errMsg = "Documento enviado.";
return Index(uco, filter, page, idAudit, full);
}
for a non-generic, simple solution to your exact problem:
homes.sort(
function(a, b) {
if (a.city === b.city) {
// Price is only important when cities are the same
return b.price - a.price;
}
return a.city > b.city ? 1 : -1;
});
Try filtering out the rows that contain strings with the delimiter and work on those only like:
SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM MyTable
WHERE CHARINDEX('/', myColumn) > 0
Or
SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM MyTable
WHERE myColumn LIKE '%/%'
I was able to handle this in Spring 2 as following
private boolean isInPath(ServletRequest request) {
String PATH_TO_VALIDATE = "/path/";
String path = ((HttpServletRequest) request).getRequestURI();
return path != null && path.toLowerCase().contains(PATH_TO_VALIDATE);
}
This solution works using Bootstrap v2, however in TBS3 the class INLINE. I haven't figured out what is the equivalent class (if there is one) in TBS3.
This gentleman had a pretty good article of the differences between v2 and v3.
http://mattduchek.com/differences-between-bootstrap-v2-3-and-v3-0/
EDIT - use CSS to target the li
elements to solve your problem as below
{ display: inline-block; }
In my situation I was targeting the UL, instead of the LI
nav ul li { display: inline-block; }
You must use
list.remove(indexYouWantToReplace);
first.
Your elements will become like this. [zero, one, three]
then add this
list.add(indexYouWantedToReplace, newElement)
Your elements will become like this. [zero, one, new, three]
In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]:
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
Universal apps seem to work a bit differently; it doesn't have all the power of full-featured XAML. What worked for me is:
Just for fun I whipped up a little templated class to help with this and published it to the MSDN Samples pages. The extra bits let me optionally override the names of the enums and to let me hide some of the enums. My code looks an awful like like Nick's (above), which I wish I had seen earlier.
I have used jQuery AJAX to make AJAX requests.
Check the following code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#call').click(function ()
{
$.ajax({
type: "post",
url: "testme", //this is my servlet
data: "input=" +$('#ip').val()+"&output="+$('#op').val(),
success: function(msg){
$('#output').append(msg);
}
});
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
input:<input id="ip" type="text" name="" value="" /><br></br>
output:<input id="op" type="text" name="" value="" /><br></br>
<input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
<div id="output"></div>
</body>
using Apache IO could be another option for copy the Stream
@RequestMapping(path = "/file/{fileId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> downloadFile(@PathVariable(value="fileId") String fileId,HttpServletResponse response) throws Exception {
InputStream yourInputStream = ...
IOUtils.copy(yourInputStream, response.getOutputStream());
response.flushBuffer();
return ResponseEntity.ok().build();
}
maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
I was facing the same issue with MSBuild for VS 17
I solved this by applying the following steps:
In my case the Microsoft.Cpp.Default.props
file was located at C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\VC\VCTargets
so I created VCTragetsPath
string in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0
with value
C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\Common7\IDE\VC\VCTargets
I also made my Jenkins run as an admin user
This solved my issue.
Are you using virtualenv?
if so, you need to notify PyCharm for every change in the location of the the desired python.exe (merely ./activate is not enough for PyCharm)
Make sure Pycharm points to the correct interpetor and packages: File -> Settings -> Project -> Project Interpreter. Click the gear and choose python.exe under virtualenv's Scripts folder
I created a little wrapper around the Screen from System.Windows.Forms, currently everything works... Not sure about the "device independent pixels", though.
public class WpfScreen
{
public static IEnumerable<WpfScreen> AllScreens()
{
foreach (Screen screen in System.Windows.Forms.Screen.AllScreens)
{
yield return new WpfScreen(screen);
}
}
public static WpfScreen GetScreenFrom(Window window)
{
WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window);
Screen screen = System.Windows.Forms.Screen.FromHandle(windowInteropHelper.Handle);
WpfScreen wpfScreen = new WpfScreen(screen);
return wpfScreen;
}
public static WpfScreen GetScreenFrom(Point point)
{
int x = (int) Math.Round(point.X);
int y = (int) Math.Round(point.Y);
// are x,y device-independent-pixels ??
System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
Screen screen = System.Windows.Forms.Screen.FromPoint(drawingPoint);
WpfScreen wpfScreen = new WpfScreen(screen);
return wpfScreen;
}
public static WpfScreen Primary
{
get { return new WpfScreen(System.Windows.Forms.Screen.PrimaryScreen); }
}
private readonly Screen screen;
internal WpfScreen(System.Windows.Forms.Screen screen)
{
this.screen = screen;
}
public Rect DeviceBounds
{
get { return this.GetRect(this.screen.Bounds); }
}
public Rect WorkingArea
{
get { return this.GetRect(this.screen.WorkingArea); }
}
private Rect GetRect(Rectangle value)
{
// should x, y, width, height be device-independent-pixels ??
return new Rect
{
X = value.X,
Y = value.Y,
Width = value.Width,
Height = value.Height
};
}
public bool IsPrimary
{
get { return this.screen.Primary; }
}
public string DeviceName
{
get { return this.screen.DeviceName; }
}
}
Percent encoding. Replace the hash with %23
.
html using Razor:
@Html.DropDownList("test1", Model.SelectOptionList, new { id = "test1", onchange = "myFunction()" })
JS Code:
function myFunction() {
var value = document.getElementById('test1').value;
console.log("it has been changed! to " + value );
}
You will first need to update the local formulas by doing
brew update
and then upgrade the package by doing
brew upgrade formula-name
An example would be if i wanted to upgrade mongodb, i would do something like this, assuming mongodb was already installed :
brew update && brew upgrade mongodb && brew cleanup mongodb
String UrlPath="android.resource://"+getPackageName()+"/"+R.raw.ur file name;
videocontainer.setVideoURI(Uri.parse(UrlPath));
videocontainer.start();
where videocontainer of type videoview.
To specify a directory to search for (binary) libraries, you just use -L
:
-L/data[...]/lib
To specify the actual library name, you use -l
:
-lfoo # (links libfoo.a or libfoo.so)
To specify a directory to search for include files (different from libraries!) you use -I
:
-I/data[...]/lib
So I think what you want is something like
g++ -g -Wall -I/data[...]/lib testing.cpp fileparameters.cpp main.cpp -o test
These compiler flags (amongst others) can also be found at the GNU GCC Command Options manual:
How about
sudo yum install php-mysql
or
sudo apt-get install php5-mysql
With pseudo elements.
HTML:
<div class="image-map-container">
<img src="https://upload.wikimedia.org/wikipedia/commons/8/83/FibonacciBlocks.png" alt="" usemap="#image-map" />
<div class="map-selector"></div>
</div>
<map name="image-map" id="image-map">
<area alt="" title="" href="#" shape="rect" coords="54,36,66,49" />
<area alt="" title="" href="#" shape="rect" coords="72,38,83,48" />
<area alt="" title="" href="#" shape="rect" coords="56,4,80,28" />
<area alt="" title="" href="#" shape="rect" coords="7,7,45,46" />
<area alt="" title="" href="#" shape="rect" coords="10,59,76,125" />
<area alt="" title="" href="#" shape="rect" coords="93,9,199,122" />
</map>
some CSS:
.image-map-container {
position: relative;
display:inline-block;
}
.image-map-container img {
display:block;
}
.image-map-container .map-selector {
left:0;top:0;right:0;bottom:0;
color:#546E7A00;
transition-duration: .3s;
transition-timing-function: ease-out;
transition-property: top, left, right, bottom, color;
}
.image-map-container .map-selector.hover {
color:#546E7A80;
}
.map-selector:after {
content: '';
position: absolute;
top: inherit;right: inherit;bottom: inherit;left: inherit;
background: currentColor;
transition-duration: .3s;
transition-timing-function: ease-out;
transition-property: top, left, right, bottom, background;
pointer-events: none;
}
JS:
$('#image-map area').hover(
function () {
var coords = $(this).attr('coords').split(','),
width = $('.image-map-container').width(),
height = $('.image-map-container').height();
$('.image-map-container .map-selector').addClass('hover').css({
'left': coords[0]+'px',
'top': coords[1] + 'px',
'right': width - coords[2],
'bottom': height - coords[3]
})
},
function () {
$('.image-map-container .map-selector').removeClass('hover').attr('style','');
}
)
In the latest version of JAVA this is how you do it:
nir.length //is the first dimension
nir[0].length //is the second dimension
You should get the value of the current date to get the date with (ms) and add (30 * 60 *1000) to it. Now you have (current date + 30 min) with ms
console.log('with ms', Date.now() + (30 * 60 * 1000))_x000D_
console.log('new Date', new Date(Date.now() + (30 * 60 * 1000)))
_x000D_
Simply just use an ImageButton.
Well I found the solution. It can be done one by passing a closure
function in with()
as second index of array like
Post::query()
->with(array('user' => function($query) {
$query->select('id','username');
}))
->get();
It will only select id
and username
from other table. I hope this will help others.
Remember that the primary key (id in this case) needs to be the first param in the
$query->select()
to actually retrieve the necessary results.*
You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN)
before you start your cleanup code.
This also would work:
export LD_LIBRARY_PATH=/usr/lib/hadoop/lib/native
The dot itself is not an operator, .^
is.
The .^
is a pointwise¹ (i.e. element-wise) power, as .*
is the pointwise product.
.^
Array power.A.^B
is the matrix with elementsA(i,j)
to theB(i,j)
power. The sizes ofA
andB
must be the same or be compatible.
C.f.
¹) Hence the dot.
And in addition to the above nice answers.
RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.
You can use Array.push()
for appending elements to an array.
For deleting, it is best to use this.$delete(array, index)
for reactive objects.
Vue.delete( target, key )
: Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.
I think your EmpID
column is string and you forget to use ' '
in your value.
Because when you write EmpID=" + id.Text
, your command looks like EmpID = 12345
instead of EmpID = '12345'
Change your SqlCommand
to
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID='" + id.Text +"'", con);
Or as a better way you can (and should) always use parameterized queries
. This kind of string concatenations are open for SQL Injection
attacks.
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);
I think your EmpID
column keeps your employee id's, so it's type should some numerical type instead of character.
Modern linear algebra libraries include optimized versions of the most common operations. Many of them include dynamic CPU dispatch, which chooses the best implementation for the hardware at program execution time (without compromising on portability).
This is commonly a better alternative to performing manual optimization of your functinos via vector extensions intrinsic functions. The latter will tie your implementation to a particular hardware vendor and model: if you decide to swap to a different vendor (e.g. Power, ARM) or to a newer vector extensions (e.g. AVX512), you will need to re-implement it again to get the most of them.
MKL transposition, for example, includes the BLAS extensions function imatcopy
. You can find it in other implementations such as OpenBLAS as well:
#include <mkl.h>
void transpose( float* a, int n, int m ) {
const char row_major = 'R';
const char transpose = 'T';
const float alpha = 1.0f;
mkl_simatcopy (row_major, transpose, n, m, alpha, a, n, n);
}
For a C++ project, you can make use of the Armadillo C++:
#include <armadillo>
void transpose( arma::mat &matrix ) {
arma::inplace_trans(matrix);
}
Another alternative way using get method with requests:
import requests
wjdata = requests.get('url').json()
print wjdata.get('data').get('current_condition')[0].get('temp_C')
The iPhone6/6s/6+ are NOT designed to read passive NFC tags (aka Discovery Mode). There's a lot of misinformation on this topic, so I thought to provide some tangible info for developers to consider. The lack of NFC tag read support is not because of software but because of hardware. To understand why, you need to understand how NFC works. NFC works by way of Load Modulation. That means that the interrogator (PCD) emits a carrier magnetic field that energizes the passive target (PICC). With the potential generated by this carrier field, the target then is able to demodulate data coming from the interrogator and respond by modulating data over top of this very same field. The key here is that the target never creates a field of its own.
If you look at the iPhone6 teardown and parts list you will see the presence of a very small NFC loop antenna as well as the use of the AS3923 booster IC. This design was intended for custom microSD or SIM cards to enable mobile phones of old to do payments. This is the type of application where the mobile phone presents a Card Emulated credential to a high power contactless POS terminal. The POS terminal acts as the reader, energizing the iPhone6 with help from the AS3923 chip. The AS3923 block diagram clearly shows how the RX and TX modulation is boosted from a signal presented by a reader device. In other words the iPhone6 is not meant to provide a field, only to react to one. That's why it's design is only meant for NFC Card Emulation and perhaps Peer-2-Peer, but definitely not tag Discovery.
There are some alternatives to achieving tag Discovery with an iPhone6 using HW accessories. I talk about these integrations and how developers can architect solutions in this blog post. Our low power reader designs open interesting opportunities for mobile engagement that few developers are thinking about.
Disclosure: I'm the founder of Flomio, Inc., a TechStars company that delivers proximity ID hardware, software, and services for applications ranging from access control to payments.
Update: This rumor, if true, would open up the possibility for the iPhone to practically support NFC tag Discovery mode. An all glass design would not interfere with the NFC antenna as does the metal back of the current iPhone. We've attempted this design approach --albeit with cheaper materials-- on some of our custom reader designs with success so looking forward to this improvement.
Update: iOS11 has announced support for "NFC reader mode" for iPhone7/7+. Details here. API only supports reading NDEF messages (no ISO7816 APDUs) while an app is in the foreground (no background detection). Due out in the Fall, 2017... check the screenshot from WWDC keynote:
\.jenkins\secrets\initialAdminPassword
Copy the password from the initialAdminPassword file and paste it into the Jenkins.
You can use a simple if
statement instead of continue. So instead of the way you have your code, you can try:
try(Stream<String> lines = Files.lines(path, StandardCharsets.ISO_8859_1)){
filteredLines = lines.filter(...).foreach(line -> {
...
if(!...) {
// Code you want to run
}
// Once the code runs, it will continue anyway
});
}
The predicate in the if statement will just be the opposite of the predicate in your if(pred) continue;
statement, so just use !
(logical not).
Erik Allik already gave very good reasons, why you will most likely not want to collect elements of a stream into an existing List.
Anyway, you can use the following one-liner, if you really need this functionality.
But as Stuart Marks explains in his answer, you should never do this, if the streams might be parallel streams - use at your own risk...
list.stream().collect(Collectors.toCollection(() -> myExistingList));
I would use specific user (and NOT Application user). Then I will enable impersonation in the application. Once you do that whatever account is set as the specific user, those credentials would used to access local resources on that server (Not for external resources).
Specific User setting is specifically meant for accessing local resources.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
How I solved this issue: 1. Be connected to the internet. 2. Open the Anaconda Prompt (looks like a regular command window). If you installed the .exe in your /name/user/ location you should be fine, if not navigate to it. Then start an environment.
conda info --envs
Then run
conda install -c anaconda anaconda-navigator
Press y when prompted (if prompted). It will being downloading the packages needed.
Then run your newly installed Anaconda Navigator
anaconda-navigator
It should start, and also appear in your regular windows 10 apps list.
If you are migrating to ASP.NET Core MVC from .Net Framework MVC like I was, things have changed slightly. The ajax call must be on the raw object using stringify so rather than passing data of { vals: arrayOfValues }
it should be JSON.stringify(arrayOfValues)
as follows:
$.ajax({
url: 'controller/myaction',
data: JSON.stringify(arrayOfValues),
success: function(data) { /* Whatever */ }
});
The other change that has been made in ASP.NET Core is to prevent cross-site request forgery so for calls to an MVC action from an ajax method the [FromBody]
atribute must be applied to the action parameter as follows:
public ActionResult MyAction([FromBody] IEnumerable<int> arrayOfValues )
This is GLUT installation instruction. Not free glut
First download this 118 KB GLUT package from Here
Extract the downloaded ZIP file and make sure you find the following
glut.h
glut32.lib
glut32.dll
If you have a 32 bits operating system, place glut32.dll to C:\Windows\System32\
, if your operating system is 64 bits, place it to 'C:\Windows\SysWOW64\' (to your system directory)
Place glut.h C:\Program Files\Microsoft Visual Studio 12\VC\include\GL\
(NOTE: 12 here refers to your VS version it may be 8 or 10)
If you do not find VC and following directories.. go on create it.
Place glut32.lib to C:\Program Files\Microsoft Visual Studio 12\VC\lib\
Now, open visual Studio and
now type
opengl32.lib
glu32.lib
glut32.lib
(NOTE: Each .lib in new line)
That's it... You have successfully installed OpenGL.. Go on and run your program.
Same installation instructions aplies to freeglut files with the header files in the GL folder, lib in the lib folder, and dll in the System32 folder.
Maven kept your files on cache, and don't retry to download them. You can simply manually 'help' him by deleting the .m2
directory, and then our friend will download everything over the old dependencies.
I just wrote this for another answer:
You would call it using the form using your example: appendTextToRange "[theRange]", ","
.
Sub testit()
appendTextToRange "A1:D4000", "hey there"
End Sub
Sub appendTextToRange(rngAddress As String, append As String)
Dim arr() As Variant, c As Variant
arr = Range(rngAddress).Formula
For x = LBound(arr, 1) To UBound(arr, 1)
For y = LBound(arr, 2) To UBound(arr, 2)
Debug.Print arr(x, y)
If arr(x, y) = "" Then
arr(x, y) = append
ElseIf Left(arr(x, y), 1) = "=" Then
arr(x, y) = arr(x, y) & " & "" " & append & """"
Else
arr(x, y) = arr(x, y) & " " & append
End If
Next
Next
Range(rngAddress).Formula = arr
End Sub
I'm also reading an exported file which contains french and German languages. I used Encoding.GetEncoding("iso-8859-1"), true which worked out without any challenges.
I was facing the same issue.
Commonly This kind of error occurs due to client has closed its connection and server still trying to write on that client.
So make sure that your client has its connection open until server done with its outputstream.
And one more thing, Don`t forgot to close input and output stream.
Hope this helps.
And if still facing issue than brief your problem here in details.
If you use the command
time /T
that will print the time. (without the /T, it will try to set the time)
date /T
is similar for the date.
If cmd's Command Extensions are enabled (they are enabled by default, but in this question they appear to be disabled), then the environment variables %DATE%
and %TIME%
will expand to the current date and time each time they are expanded. The format used is the same as the DATE
and TIME
commands.
To see the other dynamic environment variables that exist when Command Extensions are enabled, run set /?
.
Extract the table and pipe it directly to the target database:
pg_dump -t table_to_copy source_db | psql target_db
Note: If the other database already has the table set up, you should use the -a
flag to import data only, else you may see weird errors like "Out of memory":
pg_dump -a -t my_table my_db | psql target_db
$(this).find("select").each(function () {
$(this).find('option:selected').text();
});
This may help some one with same requirement
private String getDate(long time){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
String dateString = formatter.format(new Date(time));
String date = ""+dateString;
return date;
}
Search your code for unsafe
blocks or statements. These are only valid is compiled with /unsafe
.
Only if you open a new window using window.open() will the new window be able to close using code as I have mentioned above. This works perfectly for me :) Note : Never use href to open the page in a new tab. Window.close() does not work with "href" . Use window.open() instead.
The simplest solution is to add a :key attribute to :
<router-view :key="$route.fullPath"></router-view>
This is because Vue Router does not notice any change if the same component is being addressed. With the key, any change to the path will trigger a reload of the component with the new data.
I use seperate custom functions which gets all URL Parameters and URL parts . For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The above function will return an array consisting of url variables.
For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b I use a simple uri split,
function getUrlParams() {
var vars = {};
var parts = window.location.href.split('/' );
return parts;
}
You can even combine them both to be able to use with a single call in a page or in javascript.
You can also override onContentChanged()
which is among others fired when setContentView()
has been called.
Do the following on your linux box where java works (if u like the terminal way of doing things)
cd ~
mkdir decompiled_code && cd decompiled_code
wget https://bitbucket.org/mstrobel/procyon/downloads/procyon-decompiler-0.5.36.jar
java -jar procyon-decompiler-0.5.36.jar /Path/to/your/jar -o .
NOTE : as @Richard commented "this may be illegal depending on whether you own the copyright to the jar, the country you live in and your purpose for doing it."
The problem with just using dirname(__FILE__)
is that it doesn't follow symlinks. I had to use this for my script to follow the symlink to the actual file location.
use File::Basename;
my $script_dir = undef;
if(-l __FILE__) {
$script_dir = dirname(readlink(__FILE__));
}
else {
$script_dir = dirname(__FILE__);
}
You can also use a transparent color:
android:background="@android:color/transparent"
For some reason none of these solutions worked for me. I've had the best success using transforms.
transform: translateX(-5.8%) translateY(-5%) scale(0.884);
You can think of WORKDIR
like a cd
inside the container (it affects commands that come later in the Dockerfile, like the RUN
command). If you removed WORKDIR
in your example above, RUN npm install
wouldn't work because you would not be in the /usr/src/app
directory inside your container.
I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY
is a relative path, so if you move your Dockerfile you may need to update those COPY
commands.
I had this problem mysteriously crop up when I added some signal handling to my django app. In doing so I converted the app to use an AppConfig, meaning that instead of simply reading as 'booking
' in INSTALLED_APPS
, it read 'booking.app.BookingConfig'
.
Celery doesn't understand what that means, so I added, INSTALLED_APPS_WITH_APPCONFIGS = ('booking',)
to my django settings, and modified my celery.py
from
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
to
app.autodiscover_tasks(
lambda: settings.INSTALLED_APPS + settings.INSTALLED_APPS_WITH_APPCONFIGS
)
The LDF is the transaction log. It keeps a record of everything done to the database for rollback purposes.
You do not want to delete, but you can shrink it with the dbcc shrinkfile
command. You can also right-click on the database in SQL Server Management Studio and go to Tasks > Shrink.
The easiest way is to use lubridate:
library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)
This function automatically returns objects of class POSIXct
and will work with either factors or characters.
Are you calling the web service from client script or on the server side?
You may find sending a content type header to the server will help, e.g.
'application/json; charset=utf-8'
On the client side, I use prototype client side library and there is a contentType parameter when making an Ajax call where you can specify this. I think jQuery has a getJSON method.
I had similar requirements but I didn't want to use v-model
to have the state in the parent component. Then I got this to work:
<input
type="checkbox"
:checked="checked"
@input="checked = $event.target.checked"
/>
To pass down the value from the parent, I made a small change on this and it works.
<input
type="checkbox"
:checked="aPropFrom"
@input="$emit('update:aPropFrom', $event.target.checked)"
/>
Use Linq's Union:
using System.Linq;
var l1 = new List<int>() { 1,2,3,4,5 };
var l2 = new List<int>() { 3,5,6,7,8 };
var l3 = l1.Union(l2).ToList();
1: Create a custom attribute and override method like this:
public class CultureAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Retreive culture from GET
string currentCulture = filterContext.HttpContext.Request.QueryString["culture"];
// Also, you can retreive culture from Cookie like this :
//string currentCulture = filterContext.HttpContext.Request.Cookies["cookie"].Value;
// Set culture
Thread.CurrentThread.CurrentCulture = new CultureInfo(currentCulture);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(currentCulture);
}
}
2: In App_Start, find FilterConfig.cs, add this attribute. (this works for WHOLE application)
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// Add custom attribute here
filters.Add(new CultureAttribute());
}
}
That's it !
If you want to define culture for each controller/action in stead of whole application, you can use this attribute like this:
[Culture]
public class StudentsController : Controller
{
}
Or:
[Culture]
public ActionResult Index()
{
return View();
}
your link is generated when the page loads therefore it will always have the original value in it. You will need to set the link via javascript
You could also just wrap that in a form and have hidden fields for id
, productid
, and unitrate
Here's a sample for ya.
HTML
<input type="text" id="ss" value="1"/>
<br/>
<input type="submit" id="go" onClick="changeUrl()"/>
<br/>
<a id="imgUpdate" href="/someurl?quantity=1">click me</a>
JS
function changeUrl(){
var url = document.getElementById("imgUpdate").getAttribute('href');
var inputValue = document.getElementById('ss').value;
var currentQ = GiveMeTheQueryStringParameterValue("quantity",url);
url = url.replace("quantity=" + currentQ, "quantity=" + inputValue);
document.getElementById("imgUpdate").setAttribute('href',url)
}
function GiveMeTheQueryStringParameterValue(parameterName, input) {
parameterName = parameterName.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + parameterName + "=([^&#]*)");
var results = regex.exec(input);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
this could be cleaned up and expanded as you need it but the example works
Try this it will work...
<iframe src="Tmp.XLS" width="100%" height="500"></iframe>
But you can not save changes that you have done...It is used only for displaying purpose..
f = open('words.txt')
for word in f.read().split():
print(word)
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
I met the same error on Windows when I tried to install a package via pip3:
Traceback (most recent call last):
File "d:\anaconda\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "d:\anaconda\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\Anaconda\Scripts\pip3.6.exe\__main__.py", line 5, in <module>
ModuleNotFoundError: No module named 'pip._internal'
My python is installed via Anaconda. I solved this issue by reinstalling pip via conda:
conda install pip
After that, pip returns to normal.
You can also use the following syntax:-
INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO
From here
In .NET4.5
, MVC 5
no need for widgets.
Javascript:
object in JS:
mechanism that does post.
$('.button-green-large').click(function() {
$.ajax({
url: 'Quote',
type: "POST",
dataType: "json",
data: JSON.stringify(document.selectedProduct),
contentType: 'application/json; charset=utf-8',
});
});
C#
Objects:
public class WillsQuoteViewModel
{
public string Product { get; set; }
public List<ClaimedFee> ClaimedFees { get; set; }
}
public partial class ClaimedFee //Generated by EF6
{
public long Id { get; set; }
public long JourneyId { get; set; }
public string Title { get; set; }
public decimal Net { get; set; }
public decimal Vat { get; set; }
public string Type { get; set; }
public virtual Journey Journey { get; set; }
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}
Object received:
Hope this saves you some time.
If you use the DateTime.ParseExact()
-method that several people have suggested, you should carefully consider what you want to happen when the application runs in a non-English environment!
In Denmark, which of ParseExact("Januar", ...)
and ParseExact("January", ...)
should work and which should fail?
That will be the difference between CultureInfo.CurrentCulture
and CultureInfo.InvariantCulture
.
Replace 123 with number of commits your branch has diverged from origin.
git reset HEAD~123 && git reset && git checkout . && git clean -fd && git pull
There are actually two ways in which strings can be made in javascript.
var str = 'Javascript';
This creates a primitive string value.
var obj = new String('Javascript');
This creates a wrapper object
of type String
.
typeof str // string
typeof obj // object
So the best way to check for equality is using the ===
operator because it checks value as well as type of both operands.
If you want to check for equality between two objects then using String.prototype.valueOf
is the correct way.
new String('javascript').valueOf() == new String('javascript').valueOf()
In C# you can use the backslash to put special characters to your string. For example, to put ", you need to write \". There are a lot of characters that you write using the backslash: Backslash with a number:
Backslash with othe character
To use Windows SDK successfully you need not only make include files available to your projects but also library files and executables (tools). To set all these directories you should use WinSDK Configuration Tool.
Just add
xAxis: {
...
lineWidth: 0,
minorGridLineWidth: 0,
lineColor: 'transparent',
...
labels: {
enabled: false
},
minorTickLength: 0,
tickLength: 0
}
to the xAxis definition.
Since Version 4.1.9 you can simply use the axis attribute visible
:
xAxis: {
visible: false,
}
This is similar to the previous but works forward through the string instead of recursively backwards. Leaves errno with the right value for last failure. If there's a leading slash, there's an extra time through the loop which could have been avoided via one find_first_of() outside the loop or by detecting the leading / and setting pre to 1. The efficiency is the same whether we get set up by a first loop or a pre loop call, and the complexity would be (slightly) higher when using the pre-loop call.
#include <iostream>
#include <string>
#include <sys/stat.h>
int
mkpath(std::string s,mode_t mode)
{
size_t pos=0;
std::string dir;
int mdret;
if(s[s.size()-1]!='/'){
// force trailing / so we can handle everything in loop
s+='/';
}
while((pos=s.find_first_of('/',pos))!=std::string::npos){
dir=s.substr(0,pos++);
if(dir.size()==0) continue; // if leading / first time is 0 length
if((mdret=mkdir(dir.c_str(),mode)) && errno!=EEXIST){
return mdret;
}
}
return mdret;
}
int main()
{
int mkdirretval;
mkdirretval=mkpath("./foo/bar",0755);
std::cout << mkdirretval << '\n';
}
MainAxisAlignment
start - Place the children as close to the start of the main axis as possible.
end - Place the children as close to the end of the main axis as possible.
center - Place the children as close to the middle of the main axis as possible.
spaceBetween - Place the free space evenly between the children.
spaceAround - Place the free space evenly between the children as well as half of that space before and after the first and last child.
spaceEvenly - Place the free space evenly between the children as well as before and after the first and last child.
Example:
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('Row1'),
Text('Row2')
],
)
As the other answers said, the function you need is cv2.rectangle()
, but keep in mind that the coordinates for the bounding box vertices need to be integers if they are in a tuple, and they need to be in the order of (left, top)
and (right, bottom)
. Or, equivalently, (xmin, ymin)
and (xmax, ymax)
.
Use this:
$sheet->getStyle('A1:'.$sheet->getHighestColumn().'1')->getFont()->setBold(true);
In my case, we had several projects in one solution and had selected a different start project than in the package manager console when running the "Update-Database" Command with Code-First Migrations. Make sure to select the proper start project.
Go dependency management summary:
vgo
if your go version is: x >= go 1.11
dep
or vendor
if your go version is: go 1.6 >= x < go 1.11
x < go 1.6
Edit 3: Go 1.11 has a feature vgo
which will replace dep
.
To use vgo
, see Modules documentation. TLDR below:
export GO111MODULE=on
go mod init
go mod vendor # if you have vendor/ folder, will automatically integrate
go build
This method creates a file called go.mod
in your projects directory. You can then build your project with go build
. If GO111MODULE=auto
is set, then your project cannot be in $GOPATH
.
Edit 2: The vendoring method is still valid and works without issue. vendor
is largely a manual process, because of this dep
and vgo
were created.
Edit 1: While my old way works it's not longer the "correct" way to do it. You should be using vendor capabilities, vgo
, or dep
(for now) that are enabled by default in Go 1.6; see. You basically add your "external" or "dependent" packages within a vendor
directory; upon compilation the compiler will use these packages first.
Found. I was able import local package with GOPATH
by creating a subfolder of package1
and then importing with import "./package1"
in binary1.go
and binary2.go
scripts like this :
binary1.go
...
import (
"./package1"
)
...
So my current directory structure looks like this:
myproject/
+-- binary1.go
+-- binary2.go
+-- package1/
¦ +-- package1.go
+-- package2.go
I should also note that relative paths (at least in go 1.5) also work; for example:
import "../packageX"
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
You could create a mutable wrapper of the primitive int and create a Set of those:
class MutableInteger
{
private int value;
public int getValue()
{
return value;
}
public void setValue(int value)
{
this.value = value;
}
}
class Test
{
public static void main(String[] args)
{
Set<MutableInteger> mySet = new HashSet<MutableInteger>();
// populate the set
// ....
for (MutableInteger integer: mySet)
{
integer.setValue(integer.getValue() + 1);
}
}
}
Of course if you are using a HashSet you should implement the hash, equals method in your MutableInteger but that's outside the scope of this answer.
Found other similar question, but not the answer.
It would have been interesting to know, where you have found this question.
As far as I can remember and according com.jcraft.jsch.JSchException: Auth cancel
try to add to method .addIdentity()
a passphrase. You can use ""
in case you generated a keyfile without one.
Another source of error is the fingerprint string. If it doesn't match you will get an authentication failure either (depends from on the target server).
And at last here my working source code - after I could solve the ugly administration tasks:
public void connect(String host, int port,
String user, String pwd,
String privateKey, String fingerPrint,
String passPhrase
) throws JSchException{
JSch jsch = new JSch();
String absoluteFilePathPrivatekey = "./";
File tmpFileObject = new File(privateKey);
if (tmpFileObject.exists() && tmpFileObject.isFile())
{
absoluteFilePathPrivatekey = tmpFileObject.getAbsolutePath();
}
jsch.addIdentity(absoluteFilePathPrivatekey, passPhrase);
session = jsch.getSession(user, host, port);
//Password and fingerprint will be given via UserInfo interface.
UserInfo ui = new UserInfoImpl(pwd, fingerPrint);
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
c = (ChannelSftp) channel;
}
Using the Elastic search DSL API, you may hit the same error with
s = Search(using=client, index="my-index") \
.query("match", category.keyword="Musician")
You can solve it by doing:
s = Search(using=client, index="my-index") \
.query({"match": {"category.keyword":"Musician/Band"}})
There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.
Similarity::Similarity()
or Similarity::~Similarity()
are just missing and you have defined the others incorrectly,
void Similarity::readData(Scanner& inStream){
}
not
void readData(Scanner& inStream){
}
etc. etc.
The second one is a function called readData, only the first is the readData method of the Similarity class.
To be clear about this, in Similarity.h
void readData(Scanner& inStream);
but in Similarity.cpp
void Similarity::readData(Scanner& inStream){
}
If more than one test are needed be skipped
--gtest_filter=-TestName.*:TestName.*TestCase
Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:
$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);
Output:
Array
(
[0] => 4
)
Now:
$key = 4;
$value = $array[$key];
print $value;
Output:
Hello There
You can set triangle with position see this code for reference
.top-left-corner {
width: 0px;
height: 0px;
border-top: 0px solid transparent;
border-bottom: 55px solid transparent;
border-left: 55px solid #289006;
position: absolute;
left: 0px;
top: 0px;
}
publicPath is used by webpack for the replacing relative path defined in your css for refering image and font file.
Height and width are zero because view has not been created by the time you are requesting it's height and width . One simplest solution is
view.post(new Runnable() {
@Override
public void run() {
view.getHeight(); //height is ready
view.getWidth(); //width is ready
}
});
This method is good as compared to other methods as it is short and crisp.
I've used the base idea from @Jonathan. I've set the windows with: set JAVA_HOME=C:\Program Files\java\AdoptOpenJDK-11.0.8+10 call mvn clean package -DskipTests
Instead of building from the top-level directory, build from the output directory. You can access the source directories by setting the vpath. This option has the advantage that the built-in rules can be used.
build.sh
#!/bin/bash
mkdir -p obj
cp Makefile.template obj/Makefile
cd obj
make "$*"
.SUFFIXES:
.SUFFIXES: .c .o
CC=gcc
CPPFLAGS=-Wall
LDLIBS=-lhpdf
VPATH=%.c ../src
VPATH=%.h ../src
objects=kumain.o kudlx.o kusolvesk.o kugetpuz.o kuutils.o \
kurand.o kuASCboard.o kuPDFs.o kupuzstrings.o kugensud.o \
kushapes.o
ku : $(objects)
$(objects) : ku.h kudefines.h kuglobals.h kufns.h
.PHONY: clean
clean :
rm $(objects)
The disadvantage is that error messages do not match the CWD. This can be solved by skipping build.sh
and directly building from the obj
directory.
Another advantage of this approach is that it's somewhat popular. cmake
works in a similar fashion.
The following solution isn't nice in my opinion, as I really love the built-in rules. However, GNU make doesn't support something like vpath
for output directories. And the built-in rules cannot match, as the %
in %.o
would match obj/foo
of obj/foo.o
, leaving make
with a search in vpath %.c src/
for stuff like src/obj/foo.c
, but not src/foo.c
.
But this is as close to the built-in rules as you can get, and therefore to my best knowledge the nicest solution that's available.
$(OBJDIR)/%.o: %.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
Explanation: $(COMPILE.c) $(OUTPUT_OPTION) $<
actually is how .c.o
is implemented, see http://git.savannah.gnu.org/cgit/make.git/tree/default.c (and it's even mentioned in the manual)
Besides, if $(OBJDIR)
would only ever contain auto-gererated files, you could create it on-the-fly with an order-only prerequisite, making the clean rule slightly simpler:
$(OBJDIR):
mkdir -p $(OBJDIR)
$(OBJDIR)/%.o: %.c | $(OBJDIR)
$(COMPILE.c) $(OUTPUT_OPTION) $<
.PHONY: clean
clean:
$(RM) -r $(OBJDIR)
This requires that the feature order-only is available, which you can check using $(filter order-only, $(.FETAURES))
. I've checked on Kubuntu 14.04 GNU make 3.81 and OpenSUSE 13.1 GNU make 3.82. Both were built with order-only enabled, and am now left puzzled why Kubuntu 14.04 comes with an older version of GNU make than OpenSUSE 13.1. Anyways, gonna download make 4.1 now :)
I was also receiving such an exception, but the problem was in my Entity identifier. I am using UUID
and there are some problems in the way Spring works with them. So I just added this line to my entity identifier and it began working:
@Column(columnDefinition = "BINARY(16)")
Here you can find a little bit more information.
This could help: http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=EURUSD=X,GBPUSD=X It will return csv file:
"EUR",1.2972
"GBP",1.6034
Or if you need json: Yahoo csv parser
In Python, one can use statsmodels.iolib.foreign.genfromdta
to read Stata datasets. In addition, there is also a wrapper of the aforementioned function which can be used to read a Stata file directly from the web: statsmodels.datasets.webuse
.
Nevertheless, both of the above rely on the use of the pandas.io.stata.StataReader.data
, which is now a legacy function and has been deprecated. As such, the new pandas.read_stata
function should now always be used instead.
According to the source file of stata.py
, as of version 0.23.0
, the following are supported:
As others have noted, the pandas.to_csv
function can then be used to save the file into disk. A related function numpy.savetxt
can also save the data
as a text file.
EDIT:
The following details come from help dtaversion
in Stata 15.1:
Stata version .dta file format
----------------------------------------
1 102
2, 3 103
4 104
5 105
6 108
7 110 and 111
8, 9 112 and 113
10, 11 114
12 115
13 117
14 and 15 118 (# of variables <= 32,767)
15 119 (# of variables > 32,767, Stata/MP only)
----------------------------------------
file formats 103, 106, 107, 109, and 116
were never used in any official release.
wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -xzf Python-2.7.11.tgz
cd Python-2.7.11
Now read the README
file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.
./configure
make
sudo make install
For Python 3.5 use the following download address:
http://www.python.org/ftp/python/3.5.1/Python-3.5.1.tgz
For other versions and the most up to date download links:
http://www.python.org/getit/
There are already great answers about the advantages of using list initialization, however my personal rule of thumb is NOT to use curly braces whenever possible, but instead make it dependent on the conceptual meaning:
In my experience, this ruleset can be applied much more consistently than using curly braces by default, but having to explicitly remember all the exceptions when they can't be used or have a different meaning than the "normal" function-call syntax with parenthesis (calls a different overload).
It e.g. fits nicely with standard library-types like std::vector
:
vector<int> a{10,20}; //Curly braces -> fills the vector with the arguments
vector<int> b(10,20); //Parentheses -> uses arguments to parametrize some functionality,
vector<int> c(it1,it2); //like filling the vector with 10 integers or copying a range.
vector<int> d{}; //empty braces -> default constructs vector, which is equivalent
//to a vector that is filled with zero elements
Here's my solution
if [[ "${cms}" != +(wordpress|magento|typo3) ]]; then
After 10 days of trouble, I just deleted everything from C:\Android\.android\
and deleted all created AVDs. Now internet seems to work fine.
(The typical method would be to use plot
just once to set up the limits, possibly to include the range of all series combined, and then to use points
and lines
to add the separate series.) To use plot
multiple times with par(new=TRUE)
you need to make sure that your first plot has a proper ylim
to accept the all series (and in another situation, you may need to also use the same strategy for xlim):
# first plot
plot(x, y1, ylim=range(c(y1,y2)))
# second plot EDIT: needs to have same ylim
par(new = TRUE)
plot(x, y2, ylim=range(c(y1,y2)), axes = FALSE, xlab = "", ylab = "")
This next code will do the task more compactly, by default you get numbers as points but the second one gives you typical R-type-"points":
matplot(x, cbind(y1,y2))
matplot(x, cbind(y1,y2), pch=1)
You can do this dynamically - in case you encounter not only: HH:mm:ss, but also, mm:ss, or even ss alone.
var str = '12:99:07';
var times = str.split(":");
times.reverse();
var x = times.length, y = 0, z;
for (var i = 0; i < x; i++) {
z = times[i] * Math.pow(60, i);
y += z;
}
console.log(y);
This is preferred approach in most cases:
File.open(yourfile, 'w') { |file| file.write("your text") }
When a block is passed to File.open
, the File object will be automatically closed when the block terminates.
If you don't pass a block to File.open
, you have to make sure that file is correctly closed and the content was written to file.
begin
file = File.open("/tmp/some_file", "w")
file.write("your text")
rescue IOError => e
#some error occur, dir not writable etc.
ensure
file.close unless file.nil?
end
You can find it in documentation:
static VALUE rb_io_s_open(int argc, VALUE *argv, VALUE klass)
{
VALUE io = rb_class_new_instance(argc, argv, klass);
if (rb_block_given_p()) {
return rb_ensure(rb_yield, io, io_close, io);
}
return io;
}
To support the answer by @oberstet, if the cert is not trusted by the browser (for example you get a "this site is not secure, do you want to continue?") one solution is to open the browser options, navigate to the certificates settings and add the host and post that the websocket server is being served from to the certificate provider as an exception.
for example add 'example-wss-domain.org:6001' as an exception to 'Certificate Provider Ltd'.
In firefox, this can be done from 'about:preferences' and searching for 'Certificates'
find $HOME -name "hello.c" -print
This will search the whole $HOME
(i.e. /home/username/
) system for any files named “hello.c” and display their pathnames:
/Users/user/Downloads/hello.c
/Users/user/hello.c
However, it will not match HELLO.C
or HellO.C
. To match is case insensitive pass the -iname
option as follows:
find $HOME -iname "hello.c" -print
Sample outputs:
/Users/user/Downloads/hello.c
/Users/user/Downloads/Y/Hello.C
/Users/user/Downloads/Z/HELLO.c
/Users/user/hello.c
Pass the -type f
option to only search for files:
find /dir/to/search -type f -iname "fooBar.conf.sample" -print
find $HOME -type f -iname "fooBar.conf.sample" -print
The -iname
works either on GNU or BSD (including OS X) version find command. If your version of find command does not supports -iname
, try the following syntax using grep
command:
find $HOME | grep -i "hello.c"
find $HOME -name "*" -print | grep -i "hello.c"
OR try
find $HOME -name '[hH][eE][lL][lL][oO].[cC]' -print
Sample outputs:
/Users/user/Downloads/Z/HELLO.C
/Users/user/Downloads/Z/HEllO.c
/Users/user/Downloads/hello.c
/Users/user/hello.c
Sorry, but none of the previous solutions helped me. I need to check both sides: SecurityManager and SO permissions. I have learned a lot with Josh code and with iain answer, but I'm afraid I need to use Rakesh code (also thanks to him). Only one bug: I found that he only checks for Allow and not for Deny permissions. So my proposal is:
string folder;
AuthorizationRuleCollection rules;
try {
rules = Directory.GetAccessControl(folder)
.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
} catch(Exception ex) { //Posible UnauthorizedAccessException
throw new Exception("No permission", ex);
}
var rulesCast = rules.Cast<FileSystemAccessRule>();
if(rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Deny)
|| !rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Allow))
throw new Exception("No permission");
//Here I have permission, ole!
Solution 1 : You can do like this :
List<car> result = GetSomeOtherList().Except(GetTheList()).ToList();
But in some cases may this solution not work. if it is not work you can use my second solution .
Solution 2 :
List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();
we pretend that list1 is your main list and list2 is your secondry list and you want to get items of list1 without items of list2.
var result = list1.Where(p => !list2.Any(x => x.ID == p.ID && x.property1 == p.property1)).ToList();
In case you need to split a string from your JSON, the string has the \n special character replaced with \\n.
Split string by newline:
Result.split('\n');
Split string received in JSON, where special character \n was replaced with \\n during JSON.stringify(in javascript) or json.json_encode(in PHP). So, if you have your string in a AJAX response, it was processed for transportation. and if it is not decoded, it will sill have the \n replaced with \\n** and you need to use:
Result.split('\\n');
Note that the debugger tools from your browser might not show this aspect as you was expecting, but you can see that splitting by \\n resulted in 2 entries as I need in my case:
by_type_year_tag_filtered <- by_type_year_tag %>%
dplyr:: filter(tag_name %in% c("dplyr", "ggplot2"))
It seems you've found your answer already but since you mentioned the active form I'll contribute with one more, even if it differs only ever so slightly.
<?php
$form = ActiveForm::begin();
echo $form->field($model, 'attribute')
->dropDownList(
$items, // Flat array ('id'=>'label')
['prompt'=>''] // options
);
ActiveForm::end();
?>
If you need one single regex, try:
(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)
A short explanation:
(?=.*[a-z]) // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z]) // use positive look ahead to see if at least one upper case letter exists
(?=.*\d) // use positive look ahead to see if at least one digit exists
(?=.*\W]) // use positive look ahead to see if at least one non-word character exists
And I agree with SilentGhost, \W
might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?]
(feel free to add more of course!)
I'd prefer to use [:punct:]
for that. Also, a-zA-Z09-9
could be just [:alnum:]
:
[[ $TEST =~ ^[[:alnum:][:blank:][:punct:]]+$ ]]
you can also use append function
b = [ ]
for x in range(0, 5):
b.append(["O"] * 5)
def print_b(b):
for row in b:
print " ".join(row)
Here is, how I've handled this issue (Mac OS X 10.8.4):
1) Because I previously have installed Android Studio the sdk located here: Applications/Android Studio.app/sdk
You can dig into Android Studio.app folder by hitting "Show package contents" in context menu
2) Simply copy the "sdk" folder to another location and write it down to Eclipse preferences. Because I couldn't find how to properly add adress like "/Android Studio.app/sdk" (folder with .app extension) to Eclipse preferences.
I know that this solution is not smooth and best, but it works (at least for me). And I've tried all advices in this theme, and installed the ADT from http://dl-ssl.google.com/android/eclipse/ before, but the error window have kept appearing every time.
If you are hesitating between using ng-bind
or ng-model
, try to answer these questions:
Do you only need to display data?
Yes: ng-bind
(one-way binding)
No: ng-model
(two-way binding)
Do you need to bind text content (and not value)?
Yes: ng-bind
No: ng-model
(you should not use ng-bind where value is required)
Is your tag a HTML
<input>
?
Yes: ng-model
(you cannot use ng-bind with <input>
tag)
No: ng-bind
You can pass an access level to the @Getter
and @Setter
annotations. This is useful to make getters or setters protected or private. It can also be used to override the default.
With @Data
, you have public access to the accessors by default. You can now use the special access level NONE
to completely omit the accessor, like this:
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private int mySecret;
The app should contain a templatetags
directory, at the same level as models.py
, views.py
, etc. If this doesn’t already exist, create it - don’t forget the __init__.py
file to ensure the directory is treated as a Python package.
define_action.py
inside of the templatetags directory with the following code:from django import template
register = template.Library()
@register.simple_tag
def define(val=None):
return val
Note: Development server won’t automatically restart. After adding the templatetags
module, you will need to restart your server before you can use the tags or filters in templates.
{% load define_action %}
{% if item %}
{% define "Edit" as action %}
{% else %}
{% define "Create" as action %}
{% endif %}
Would you like to {{action}} this item?
Try to set up the correct target in Podfile
and then run pod update
or pod install
$(document).ready(function () {
setTimeout(function () {
$(".imgthumbnew").click(function () {
$("#divVideo video").attr({
"src": $(this).data("item"),
"autoplay": "autoplay",
})
})
}, 2000);
}
});
here ".imgthumbnew" is the class of images which are thumbs of videos, an extra attribute is given to them which have video url. u can change according to your convenient.
i would suggest you to give an ID to ur Video tag it would be easy to handle.
Make sure you image is a relative path such as:
@Url.Content("~/Content/images/myimage.png")
MVC4
<img src="~/Content/images/myimage.png" />
You could convert the byte[]
into a Base64
string
on the fly.
string base64String = Convert.ToBase64String(imageBytes);
<img src="@String.Format("data:image/png;base64,{0}", base64string)" />
Update (2017): The following two libraries have now become the most common drop-down libraries used with Javascript. While they are jQuery-native, they have been customized to work with everything from AngularJS 1.x to having custom CSS for Bootstrap. (Chosen JS, the original answer here, seems to have dropped to #3 in popularity.)
Obligatory screenshots below.
Original answer (2012): I think that the Chosen library might also be useful. Its available in jQuery, Prototype and MooTools versions.
Attached is a screenshot of how the multi-select functionality looks in Chosen.
You can use date.js to achieve this:
var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');
Alternatively, you can do it natively like this:
var dateAr = '2014-01-06'.split('-');_x000D_
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);_x000D_
_x000D_
console.log(newDate);
_x000D_
You can use javascript for this provblem. It's retrieve link from browser history.
<script>_x000D_
function goBack() {_x000D_
window.history.back();_x000D_
}_x000D_
</script>
_x000D_
<button onclick="goBack()">Go Back</button>
_x000D_
As of 2018,
use MiniCssExtractPlugin
for Webpack(> 4.0) will solve this problem.
https://github.com/webpack-contrib/mini-css-extract-plugin
Using extract-text-webpack-plugin
in the accepted answer is NOT recommended for Webpack 4.0+.
According to http://www.techotopia.com/index.php/Ruby_String_Concatenation_and_Comparison
Doing either
mystring == yourstring
or
mystring.eql? yourstring
Are equivalent.
Here is it with a loop for all files with some extension:
ll -ltr *.filename_extension > list.lst
for i in $(cat list.lst | awk '{ print $8 }') # validate if it is the 8 column on ls
do
echo $i
sed -i '/^#/d' $i
done
For me this was ad blocker installed on web browser. It was not letting load the style.css
If you'd rather copy the properties:
var json1 = { value1: '1', value2: '2' };
var json2 = { value2: '4', value3: '3' };
function jsonConcat(o1, o2) {
for (var key in o2) {
o1[key] = o2[key];
}
return o1;
}
var output = {};
output = jsonConcat(output, json1);
output = jsonConcat(output, json2);
Output of above code is{ value1: '1', value2: '4', value3: '3' }
You can use query string to pass value from one page to another..
1.pass the value using querystring
Response.Redirect("Default3.aspx?value=" + txt.Text + "& number="+n);
2.Retrive the value in the page u want by using any of these methods..
Method1:
string v = Request.QueryString["value"];
string n=Request.QueryString["number"];
Method2:
NameValueCollection v = Request.QueryString;
if (v.HasKeys())
{
string k = v.GetKey(0);
string n = v.Get(0);
if (k == "value")
{
lbltext.Text = n.ToString();
}
if (k == "value1")
{
lbltext.Text = "error occured";
}
}
NOTE:Method 2 is the fastest method.
\w\-
is probably the best but here just another alternative
Use [:alnum:]
if(!preg_match("/[^[:alnum:]\-_]/",$str)) echo "valid";
margin
to align images:Since we wanted the image
to be left-aligned
, we added:
img {
margin-right: auto;
}
Similarly for image
to be right-aligned
, we can add margin-right: auto;
. The snippet shows a demo for both types of alignment.
Good Luck...
div {_x000D_
display:flex; _x000D_
flex-direction:column;_x000D_
border: 2px black solid;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
text-align: center;_x000D_
}_x000D_
hr {_x000D_
border: 1px black solid;_x000D_
width: 100%_x000D_
}_x000D_
img.one {_x000D_
margin-right: auto;_x000D_
}_x000D_
_x000D_
img.two {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div>_x000D_
<h1>Flex Box</h1>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="one" _x000D_
/>_x000D_
_x000D_
_x000D_
<img src="https://via.placeholder.com/80x80" class="two" _x000D_
/>_x000D_
_x000D_
<hr />_x000D_
</div>
_x000D_
On June 26, 2014 AWS released proper Vary: Origin behavior on CloudFront so now you just
Set a CORS Configuration for your S3 bucket:
<AllowedOrigin>*</AllowedOrigin>
In CloudFront -> Distribution -> Behaviors for this origin, use the Forward Headers: Whitelist option and whitelist the 'Origin' header.
Wait for ~20 minutes while CloudFront propagates the new rule
Now your CloudFront distribution should cache different responses (with proper CORS headers) for different client Origin headers.
First of all, why would you need to output to console in a release mode build? Nobody will think to look there when there's a gui...
Second, qDebug is fancy :)
Third, you can try adding console
to your .pro
's CONFIG
, it might work.
select id,first_name,gender,age,
rank() over(partition by gender order by age) rank_g
from person
CREATE TABLE person (id int, first_name varchar(20), age int, gender char(1));
INSERT INTO person VALUES (1, 'Bob', 25, 'M');
INSERT INTO person VALUES (2, 'Jane', 20, 'F');
INSERT INTO person VALUES (3, 'Jack', 30, 'M');
INSERT INTO person VALUES (4, 'Bill', 32, 'M');
INSERT INTO person VALUES (5, 'Nick', 22, 'M');
INSERT INTO person VALUES (6, 'Kathy', 18, 'F');
INSERT INTO person VALUES (7, 'Steve', 36, 'M');
INSERT INTO person VALUES (8, 'Anne', 25, 'F');
INSERT INTO person VALUES (9,'AKSH',32,'M');
CharSequence
is an interface and String
implements it. You can instantiate a String
but you could not do that for CharSequence
since it is an interface. You can find other implementations in CharSequence
in the official Java website.
Time changes everything. I was looking to do the same recently and came up with this:
added 02/17/2021
Stable Portal Page thanks Palec
added 12/18/2017
As indicated by shadowbq, the DirectoryId and TenantId both equate to the GUID representing the ActiveDirectory Tenant. Depending on context, either term may be used by Microsoft documentation and products, which can be confusing.
The tenant ID is tied to ActiveDirectoy in Azure
Yes I used paint, don't judge me.
Try to get using:
var count = $("ul > li").size();
alert(count);
Here is a solution that has not been mentioned so far, using bitfields. The following program counts the set bits in an array of 100000000 16-bit integers using 4 different methods. Timing results are given in parentheses (on MacOSX, with gcc -O3
):
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 100000000
typedef struct {
unsigned char bit0 : 1;
unsigned char bit1 : 1;
unsigned char bit2 : 1;
unsigned char bit3 : 1;
unsigned char bit4 : 1;
unsigned char bit5 : 1;
unsigned char bit6 : 1;
unsigned char bit7 : 1;
} bits;
unsigned char sum_bits(const unsigned char x) {
const bits *b = (const bits*) &x;
return b->bit0 + b->bit1 + b->bit2 + b->bit3 \
+ b->bit4 + b->bit5 + b->bit6 + b->bit7;
}
int NumberOfSetBits(int i) {
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
#define out(s) \
printf("bits set: %lu\nbits counted: %lu\n", 8*LENGTH*sizeof(short)*3/4, s);
int main(int argc, char **argv) {
unsigned long i, s;
unsigned short *x = malloc(LENGTH*sizeof(short));
unsigned char lut[65536], *p;
unsigned short *ps;
int *pi;
/* set 3/4 of the bits */
for (i=0; i<LENGTH; ++i)
x[i] = 0xFFF0;
/* sum_bits (1.772s) */
for (i=LENGTH*sizeof(short), p=(unsigned char*) x, s=0; i--; s+=sum_bits(*p++));
out(s);
/* NumberOfSetBits (0.404s) */
for (i=LENGTH*sizeof(short)/sizeof(int), pi=(int*)x, s=0; i--; s+=NumberOfSetBits(*pi++));
out(s);
/* populate lookup table */
for (i=0, p=(unsigned char*) &i; i<sizeof(lut); ++i)
lut[i] = sum_bits(p[0]) + sum_bits(p[1]);
/* 256-bytes lookup table (0.317s) */
for (i=LENGTH*sizeof(short), p=(unsigned char*) x, s=0; i--; s+=lut[*p++]);
out(s);
/* 65536-bytes lookup table (0.250s) */
for (i=LENGTH, ps=x, s=0; i--; s+=lut[*ps++]);
out(s);
free(x);
return 0;
}
While the bitfield version is very readable, the timing results show that it is over 4x slower than NumberOfSetBits()
. The lookup-table based implementations are still quite a bit faster, in particular with a 65 kB table.
On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.
You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.
If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.
Always try to use parametrized sql query to keep safe from malicious occurrence, so you could rearrange you code as below:
Also make sure that your table has column name matches to Name
, PhoneNo
,Address
.
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
List<String> stringList = getMyListOfStrings();
StringJoiner sj = new StringJoiner(" ");
stringList.stream().forEach(e -> sj.add(e));
String spaceSeparated = sj.toString()
You pass to the new StringJoiner
the char sequence you want to be used as separator. If you want to do a CSV: new StringJoiner(", ");
Make sure you are logged in as root user in your terminal.
Steps to start mongodb server in your mac
sudo su
mongod
Hope it helps you. Thanks
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
echo "LOAD_SETTLED LOAD_INIT 2011-01-13 03:50:01" | awk -v var="test" 'BEGIN { FS = "[ \t]+" } ; { print $1 "\t" var "\t" $3 }'
Just only copy and paste this code it will get your page content.
<?php
$pageid = get_the_id();
$content_post = get_post($pageid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
?>
I hit this recently and remember where it comes from. It's a mismatch between the Xamarin.Android.* version and the installed Android SDK version.
The current VS2017 15.5.3
new project defaults for nuGet Xamarin.Android.*
are 25.4.0.2
and the default VS install for cross platform development are the following Android SDK packages:
7.1
- Nougat
25
If you upgraded you solution nuGet for Xamarin.Android.*
to 26.1.0.1
then you will need to install the follow in the Android SDK:
8.0
- Oreo
26
Check out your table index. If that field got index (e.g. B+ tree index.) At that time update or insert query throws these kinds of error.
Remove indexing and then try to fire same query.
If you have a Mac and TextMate - An easy alternative for formatting Javascript is:
OSX's Python binary (version 2) is located at /usr/bin/python
if you use which python
it will tell you where the python
command is being resolved to. Typically, what happens is third parties redefine things in /usr/local/bin
(which takes precedence, by default over /usr/bin
). To fix, you can either run /usr/bin/python
directly to use 2.x or find the errant redefinition (probably in /usr/local/bin
or somewhere else in your PATH
)
if I got your question correct...
main() method is defined in the class below...
public class ToBeCalledClass{
public static void main (String args[ ]) {
System.out.println("I am being called");
}
}
you want to call this main method in another class.
public class CallClass{
public void call(){
ToBeCalledClass.main(null);
}
}
SOLUTION NO. 1
//your variable
var data = "brightcherry";
//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id='"+product_id+"'");
SOLUTION NO. 2
//your variable
var data = "brightcherry";
//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id=" + product_id);
This error occurs when you're trying to target an element that is wrapped in a condition.
So, here if I use ngIf in place of [hidden], it will give me TypeError: Cannot read property 'nativeElement' of undefined
So use [hidden], class.show or class.hide in place of *ngIf.
<button (click)="displayMap()" class="btn btn-primary">Display Map</button>
<div [hidden]="!display">
<div #mapContainer id="map">Content to render when condition is true.</div>
</div>
I have tried changing the tnsnames.ora file putting the IP of the server instead of localhost or loopback address, it did not work. The firewall was blocking the requests. Please configure your firewall or turn it off(not recommended), it would work.
You should use setTimestamp instead, if you hardcode it:
$start_date = new DateTime();
$start_date->setTimestamp(1372622987);
in your case
$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);
In fact, xargs
can run commands in parallel for you. There is a special -P max_procs
command-line option for that. See man xargs
.
I wouldn't suggest overriding the drawRect due to causing a performance hit.
Instead, I would modify the properties of the class like below (in your custom uiview):
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.layer.borderWidth = 2.f;
self.layer.borderColor = [UIColor redColor].CGColor;
}
return self;
I didn't see any glitches when taking above approach - not sure why putting in the initWithFrame stops these ;-)
Inverse and default class name mention in Twitter Bootstrap cause them to be black and white color.
Better, you should not override that and add a class near that and write you particular style for that:
my_style{_x000D_
background-color: green;_x000D_
}
_x000D_
I'll offer an oddball alternative. Sometimes it's easier to use different encoding, especially if you're dealing with a variety of systems that don't all handle the details of URL encoding the same way. This isn't the most mainstream approach but can come in handy in certain situations.
Rather than URL-encoding the data, you can base64-encode it. The benefit of this is the encoded data is very generic, consisting only of alpha characters and sometimes trailing =
's. Example:
JSON array-of-strings:
["option", "Fred's dog", "Bill & Trudy", "param=3"]
That data, URL-encoded as the data
param:
"data=%5B%27option%27%2C+%22Fred%27s+dog%22%2C+%27Bill+%26+Trudy%27%2C+%27param%3D3%27%5D"
Same, base64-encoded:
"data=WyJvcHRpb24iLCAiRnJlZCdzIGRvZyIsICJCaWxsICYgVHJ1ZHkiLCAicGFyYW09MyJd"
The base64 approach can be a bit shorter, but more importantly it's simpler. I often have problems moving URL-encoded data between cURL, web browsers and other clients, usually due to quotes, embedded %
signs and so on. Base64 is very neutral because it doesn't use special characters.
select getdate()
O/P
----
2011-05-25 17:29:44.763
select convert(varchar(30),getdate(),131) >= '12/04/2011 12:00:00 AM'
O/P
---
22/06/1432 5:29:44:763PM
Use the new CSS filter
property.
Supported by webkit browsers, Firefox 34+ and Edge.
You can use this polyfill that will support FF < 34, IE6+.
You would use it like so:
/* Use -webkit- only if supporting: Chrome < 54, iOS < 9.3, Android < 4.4.4 */_x000D_
_x000D_
.shadow {_x000D_
-webkit-filter: drop-shadow( 3px 3px 2px rgba(0, 0, 0, .7));_x000D_
filter: drop-shadow( 3px 3px 2px rgba(0, 0, 0, .7));_x000D_
/* Similar syntax to box-shadow */_x000D_
}
_x000D_
<img src="https://upload.wikimedia.org/wikipedia/commons/c/ce/Star_wars2.svg" alt="" class="shadow" width="200">_x000D_
_x000D_
<!-- Or -->_x000D_
_x000D_
<svg class="shadow" ...>_x000D_
<rect x="10" y="10" width="200" height="100" fill="#bada55" />_x000D_
</svg>
_x000D_
This approach differs from the box-shadow
effect in that it accounts for opacity and does not apply the drop shadow effect to the box but rather to the corners of the svg element itself.
Please Note: This approach only works when the class is placed on the <svg>
element alone. You can NOT use this on an inline svg element such as <rect>
.
<!-- This will NOT work! -->
<svg><rect class="shadow" ... /></svg>
Read more about css filters on html5rocks.
Here's how to find whether today is between 2 months:
private boolean isTodayBetween(int from, int to) {
if (from < 0 || to < 0 || from > Calendar.DECEMBER || to > Calendar.DECEMBER) {
throw new IllegalArgumentException("Invalid month provided: from = " + from + " to = " + to);
}
Date now = new Date();
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(now);
int thisMonth = cal.get(Calendar.MONTH);
if (from > to) {
to = to + Calendar.DECEMBER;
thisMonth = thisMonth + Calendar.DECEMBER;
}
if (thisMonth >= from && thisMonth <= to) {
return true;
}
return false;
}
and call it like:
isTodayBetween(Calendar.OCTOBER, Calendar.MARCH)
If I understand correctly, you have a vector containing variable names and would like loop through each name and sort your data frame by them. If so, this example should illustrate a solution for you. The primary issue in yours (the full example isn't complete so I"m not sure what else you may be missing) is that it should be order(Q1_R1000[,parameter[X]])
instead of order(Q1_R1000$parameter[X])
, since parameter is an external object that contains a variable name opposed to a direct column of your data frame (which when the $
would be appropriate).
set.seed(1)
dat <- data.frame(var1=round(rnorm(10)),
var2=round(rnorm(10)),
var3=round(rnorm(10)))
param <- paste0("var",1:3)
dat
# var1 var2 var3
#1 -1 2 1
#2 0 0 1
#3 -1 -1 0
#4 2 -2 -2
#5 0 1 1
#6 -1 0 0
#7 0 0 0
#8 1 1 -1
#9 1 1 0
#10 0 1 0
for(p in rev(param)){
dat <- dat[order(dat[,p]),]
}
dat
# var1 var2 var3
#3 -1 -1 0
#6 -1 0 0
#1 -1 2 1
#7 0 0 0
#2 0 0 1
#10 0 1 0
#5 0 1 1
#8 1 1 -1
#9 1 1 0
#4 2 -2 -2
I believe buffer length needs to be specified, as memory is finite and you may run out of it
Example:
InputStream in = new FileInputStream(strFileName);
long length = fileFileName.length();
if (length > Integer.MAX_VALUE) {
throw new IOException("File is too large!");
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = in.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + fileFileName.getName());
}
in.close();
Since there is a lot of confusion about queries MongoDB collection with sub-documents, I thought its worth to explain the above answers with examples:
First I have inserted only two objects in the collection namely: message
as:
> db.messages.find().pretty()
{
"_id" : ObjectId("5cce8e417d2e7b3fe9c93c32"),
"headers" : {
"From" : "[email protected]"
}
}
{
"_id" : ObjectId("5cce8eb97d2e7b3fe9c93c33"),
"headers" : {
"From" : "[email protected]",
"To" : "[email protected]"
}
}
>
So what is the result of query:
db.messages.find({headers: {From: "[email protected]"} }).count()
It should be one because these queries for documents where headers
equal to the object {From: "[email protected]"}
, only i.e. contains no other fields or we should specify the entire sub-document as the value of a field.
So as per the answer from @Edmondo1984
Equality matches within sub-documents select documents if the subdocument matches exactly the specified sub-document, including the field order.
From the above statements, what is the below query result should be?
> db.messages.find({headers: {To: "[email protected]", From: "[email protected]"} }).count()
0
And what if we will change the order of From
and To
i.e same as sub-documents of second documents?
> db.messages.find({headers: {From: "[email protected]", To: "[email protected]"} }).count()
1
so, it matches exactly the specified sub-document, including the field order.
For using dot operator, I think it is very clear for every one. Let's see the result of below query:
> db.messages.find( { 'headers.From': "[email protected]" } ).count()
2
I hope these explanations with the above example will make someone more clarity on find query with sub-documents.