Select the Text
From the menu, go to Plugins > NPPExport > Copy RTF to clipboard
In MS Word go to Edit > Paste Special
This will open the Paste Special dialog box. Select the Paste radio button and from the list select Formatted Text (RTF)
You should be able to see the Formatted Text.
Note that for "Untitled" editor ("Untitled-1
", "Untitled-2
"), you now can set the language in the settings.
The previous setting was:
"files.associations": {
"untitled-*": "javascript"
}
This will not always work anymore, because with VSCode 1.42 (Q1 2020) will change the title of those untitled editors.
The title will now be the first line of the document for the editor title, along the generic name as part of the description.
It won't start anymore with "untitled-
"
See "Untitled editor improvements"
Regarding the associated language for those "Untitled" editors:
By default, untitled files do not have a specific language mode configured.
VS Code has a setting,
files.defaultLanguage
, to configure a default language for untitled files.With this release, the setting can take a new value
{activeEditorLanguage}
that will dynamically use the language mode of the currently active editor instead of a fixed default.In addition, when you copy and paste text into an untitled editor, VS Code will now automatically change the language mode of the untitled editor if the text was copied from a VS Code editor:
And see workbench.editor.untitled.labelFormat
in VSCode 1.43.
You can also add your own suggestion.
Open this path:
C:\Program Files\Notepad++\plugins\APIs
And open the XML file of the language, such as php.xml. Here suppose, you would like to add addcslashes, so just add this XML code.
<KeyWord name="addcslashes" func="yes">
<Overload retVal="void">
<Param name="void"/>
</Overload>
</KeyWord>
An on-line syntax highlighter:
or
Just copy and paste into your document.
In Sublime Text (confirmed in both v2.x and v3.x) there is a menu command:
View -> Syntax -> Open all with current extension as ...
The "this" is already coloured in Javascript.
View->Syntax-> and choose your language to highlight.
use:
NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;
You can add it programmatically or in the markup, but if you add it programmatically, rather than Add
the item, you should Insert
it as position zero so that it is the first item:
ddlColor.DataSource = from p in db.ProductTypes
where p.ProductID == pID
orderby p.Color
select new { p.Color };
ddlColor.DataTextField = "Color";
ddlColor.DataBind();
ddlColor.Items.Insert(0, new ListItem("Select Color", "");
The default item is expected to be the first item in the list. If you just Add
it, it will be on the bottom and will not be selected by default.
The best way is to use source generation, so that you could use
if (hash(str) == HASH("some string") ..
in your main source, and an pre-build step would convert the HASH(const char*)
expression to an integer value.
The biggest problem is probably that one can't ensure immutability on A and B (see How to ensure that type parameters are immutable) so hashCode()
may give inconsistent results for the same Pair after is inserted in a collection for instance (this would give undefined behavior, see Defining equals in terms of mutable fields). For a particular (non generic) Pair class the programmer may ensure immutability by carefully choosing A and B to be immutable.
Anyway, clearing generic's warnings from @PeterLawrey's answer (java 1.7) :
public class Pair<A extends Comparable<? super A>,
B extends Comparable<? super B>>
implements Comparable<Pair<A, B>> {
public final A first;
public final B second;
private Pair(A first, B second) {
this.first = first;
this.second = second;
}
public static <A extends Comparable<? super A>,
B extends Comparable<? super B>>
Pair<A, B> of(A first, B second) {
return new Pair<A, B>(first, second);
}
@Override
public int compareTo(Pair<A, B> o) {
int cmp = o == null ? 1 : (this.first).compareTo(o.first);
return cmp == 0 ? (this.second).compareTo(o.second) : cmp;
}
@Override
public int hashCode() {
return 31 * hashcode(first) + hashcode(second);
}
// TODO : move this to a helper class.
private static int hashcode(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
if (this == obj)
return true;
return equal(first, ((Pair<?, ?>) obj).first)
&& equal(second, ((Pair<?, ?>) obj).second);
}
// TODO : move this to a helper class.
private boolean equal(Object o1, Object o2) {
return o1 == o2 || (o1 != null && o1.equals(o2));
}
@Override
public String toString() {
return "(" + first + ", " + second + ')';
}
}
Additions/corrections much welcome :) In particular I am not quite sure about my use of Pair<?, ?>
.
For more info on why this syntax see Ensure that objects implement Comparable and for a detailed explanation How to implement a generic max(Comparable a, Comparable b)
function in Java?
I had the same issue and it appears that the Node.js version was the problem.
I installed the previous version of Node.js (10.14.2) and everything was ok using nvm (allow you to install several version of Node.js and quickly switch from a version to another).
It is not a "clean" solution, but it can serve you temporarly.
You need to convert the date field to varchar to strip out the time, then convert it back to datetime, this will reset the time to '00:00:00.000'.
SELECT *
FROM [TableName]
WHERE
(
convert(datetime,convert(varchar,GETDATE(),1))
between
convert(datetime,convert(varchar,[StartDate],1))
and
convert(datetime,convert(varchar,[EndDate],1))
)
You probably want
SELECT sum(bytes)
FROM dba_segments
WHERE owner = <<owner of schema>>
If you are logged in as the schema owner, you can also
SELECT SUM(bytes)
FROM user_segments
That will give you the space allocated to the objects owned by the user in whatever tablespaces they are in. There may be empty space allocated to the tables that is counted as allocated by these queries.
Java, unlike languages like C and C++, treats boolean
as a completely separate data type which has 2 distinct values: true and false. The values 1 and 0 are of type int and are not implicitly convertible to boolean
.
I'm a total noob, I came here to figure out VB's 'not equal to' syntax, so I figured I'd throw it in here in case someone else needed it:
<%If Not boolean_variable%>Do this if boolean_variable is false<%End If%>
I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:
foreach (var mc in list.Where(x => x.Name == "height"))
mc.Value = 30;
Try this:
SELECT Locations.Name, Schools.Name
FROM Locations
INNER JOIN School_Locations ON School_Locations.Locations_Id = Locations.Id
INNER JOIN Schools ON School.Id = Schools_Locations.School_Id
WHERE Locations.Type = "coun"
You can join Locations to School_Locations and then School_Locations to School. This forms a set of all related Locations and Schools, which you can then widdle down using the WHERE clause to those whose Location is of type "coun."
I've seen this style being used:
if (when || who || format || data || len);
Use \overleftarrow
to create a long arrow to the left.
\overleftarrow{blahblahblah}
The safest thing is have some clean virtual machine, on which you can test your program. On every version you'd like to test, restore the VM to its initial clean value. Then install your program using its setup, and see if it works.
Dll problems have different faces. If you use Visual Studio and dynamically link to the CRT, you have to distribute the CRT DLLs. Update your VS, and you have to distribute another version of the CRT. Just checking dependencies is not enough, as you might miss those. Doing a full install on a clean machine is the only safe solution, IMO.
If you don't want to setup a full-blown test environment and have Windows 7, you can use XP-Mode as the initial clean machine, and XP-More to duplicate the VM.
Using zip function we can get both element and index.
countries = ['Pakistan','India','China','Russia','USA']
for index, element zip(range(0,countries),countries):
print('Index : ',index)
print(' Element : ', element,'\n')
output : Index : 0 Element : Pakistan ...
See also :
To be short, use:
write-output "your text" | out-file -append -encoding utf8 "filename"
suptitle
seems the way to go, but for what it's worth, the figure
has a transFigure
property that you can use:
fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')
I deal with this issue for some hours. Let's consider the request is Reactjs (javascript) and backend (API) is Asp .Net Core.
in the request, you must set in header Content-Type:
Axios({
method: 'post',
headers: { 'Content-Type': 'application/json'},
url: 'https://localhost:44346/Order/Order/GiveOrder',
data: order,
}).then(function (response) {
console.log(response);
});
and in backend (Asp .net core API) u must have some setting:
1. in Startup --> ConfigureServices:
#region Allow-Orgin
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
});
#endregion
2. in Startup --> Configure before app.UseMvc() :
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
3. in controller before action:
[EnableCors("AllowOrigin")]
For older versions of windows (2k, 2k3, xp)
"%Userprofile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions"
You can also read lines w/o loop. Works in python3.6.
import os
import subprocess
process = subprocess.Popen(command, stdout=subprocess.PIPE)
list_of_byte_strings = process.stdout.readlines()
A simple and nice way is:
$time = (Get-Date).ToString("yyyy:MM:dd")
Indeed there is.
chmod a+x
is relative to the current state and just sets the x
flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.
chmod 755
, however, sets the mask as written: rwxr-xr-x
, no matter how it was before. It is equivalent to chmod u=rwx,go=rx
.
You can create a trigger which updates NoofUses
column in Coupon
table whenever
couponid
is used in CouponUse
table
query :
CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end
All you have to do is:
<a href="" style="text-decoration:#none; letter-spacing: -999px;">
Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.
I would recommend that you use Joda Time, which is a much better API than Date
/Calendar
. It sounds like you should use the LocalDate
type in this case. You can then use:
int days = Days.daysBetween(date1, date2).getDays();
It is completely acceptable to use a DIV inside a <form>
tag.
If you look at the default CSS 2.1 stylesheet, div
and p
are both in the display: block
category. Then looking at the HTML 4.01 specification for the form element, they include not only <p>
tags, but <table>
tags, so of course <div>
would meet the same criteria. There is also a <legend>
tag inside the form in the documentation.
For instance, the following passes HTML4 validation in strict mode:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
</head>
<body>
<form id="test" action="test.php">
<div>
Test: <input name="blah" value="test" type="text">
</div>
</form>
</body>
</html>
The text inside $type is substituted directly into the insert string, therefore MySQL gets this:
... VALUES(testing, 'john', 'whatever')
Notice that there are no quotes around testing, you need to put these in like so:
$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES('$type', 'john', 'whatever')");
I also recommend you read up on SQL injection, as this sort of parameter passing is prone to hacking attempts if you do not sanitize the data being used:
I found a solution for this problem try to run this command in terminal
ps -ef | grep postgres
kill process by this command
sudo kill -9 PID
Here is a detailed explanation & solution for this problem from ibm.
Problem(Abstract)
Request to HTTP Server fails with Response code 400.
Symptom
Response from the browser could be shown like this:
Bad Request Your browser sent a request that this server could not understand. Size of a request header field exceeds server limit.
HTTP Server Error.log shows the following message: "request failed: error reading the headers"
Cause
This is normally caused by having a very large Cookie, so a request header field exceeded the limit set for Web Server.
Diagnosing the problem
To assist with diagnose of the problem you can add the following to the LogFormat directive in the httpd.conf: error-note: %{error-notes}n
Resolving the problem
For server side: Increase the value for the directive LimitRequestFieldSize in the httpd.conf: LimitRequestFieldSize 12288 or 16384 For How to set the LimitRequestFieldSize, check Increase the value of LimitRequestFieldSize in Apache
For client side: Clear the cache of your web browser should be fine.
Giving width to Label is not a proper way. you should take one div or table structure to manage this. but still if you don't want to change your whole code then you can use following code.
label {
width:200px;
float: left;
}
You can simply hide the <td>
tag content by just including a style attribute: style = "display:none"
For e.g
<td style = "display:none" >
<p> I'm invisible </p>
</td>
def _GetHtmlPage(self, addr):
headers = { 'User-Agent' : self.userAgent,
' Cookie' : self.cookies}
req = urllib2.Request(addr)
response = urllib2.urlopen(req)
print "ResponseInfo="
print response.info()
resultsHtml = unicode(response.read(), self.encoding)
return resultsHtml
You can try:
<?php
$this_page = basename($_SERVER['REQUEST_URI']);
if (strpos($this_page, "?") !== false) $this_page = reset(explode("?", $this_page));
?>
You can put a UIButton
with a transparent background over top of the UIImageView
, and listen for a tap on the button before loading the image
i = ++a + ++a + a++;
is
i = 6 + 7 + 7
Working: increment a to 6 (current value 6) + increment a to 7 (current value 7). Sum is 13 now add it to current value of a (=7) and then increment a to 8. Sum is 20 and value of a after the assignment completes is 8.
i = a++ + ++a + ++a;
is
i = 5 + 7 + 8
Working: At the start value of a is 5. Use it in the addition and then increment it to 6 (current value 6). Increment a from current value 6 to 7 to get other operand of +. Sum is 12 and current value of a is 7. Next increment a from 7 to 8 (current value = 8) and add it to previous sum 12 to get 20.
you could use the last-child psuedo class
table tr td:last-child {
border: none;
}
This will style the last td only. It's not fully supported yet so it may be unsuitable
If you are using the free software R, you can open the matlab files in Rstudio. Very easy!
For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.
-- If no parameters need to be passed to a procedure, simply:
BEGIN
MY_PACKAGE_NAME.MY_PROCEDURE_NAME
END;
Just simple modification of @silgon answer:
while true; do
inotifywait -r -e modify,create,delete /directory
rsync -avz /directory /target
done
(@silgon version sometimes crashes on Ubuntu 16 if you run it in cron)
TAB has a specific meaning in PowerShell. It's for command completion. So if you enter "getch" and then type a TAB. It changes what you typed into "GetChildItem" (it corrects the case, even though that's unnecessary).
From your question, it looks like TAB completion and command completion would overload the TAB key. I'm pretty sure the PowerShell designers didn't want that.
Typically, to troubleshoot this, you go to SQL Server Configuration Manager (SSCM) and:
Maybe it can help: Could not open a connection to SQL Server
Try this.
using System.Xml.Linq;
void Main()
{
StringBuilder result = new StringBuilder();
//Load xml
XDocument xdoc = XDocument.Load("data.xml");
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new {
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
//Loop through results
foreach (var lv1 in lv1s){
result.AppendLine(lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result);
}
The Esentutl /y option allows copyng (single) file files with progress bar like this :
the command should look like :
esentutl /y "FILE.EXT" /d "DEST.EXT" /o
The command is available on every windows machine but the y
option is presented in windows vista.
As it works only with single files does not look very useful for a small ones.
Other limitation is that the command cannot overwrite files. Here's a wrapper script that checks the destination and if needed could delete it (help can be seen by passing /h
).
I think you should add style="background:white;" to make looks like it is writable
<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly" style="background:white;"/>
Do this to use a profile with name 'dev':
session = boto3.session.Session(profile_name='dev')
s3 = session.resource('s3')
for bucket in s3.buckets.all():
print(bucket.name)
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java" The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input. Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Try surrounding the path in quotes. i.e "C:\Program Files\Appname\config.file"
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
The way Facebook does this is pretty interesting.
A common method of doing such notifications is to poll a script on the server (using AJAX) on a given interval (perhaps every few seconds), to check if something has happened. However, this can be pretty network intensive, and you often make pointless requests, because nothing has happened.
The way Facebook does it is using the comet approach, rather than polling on an interval, as soon as one poll completes, it issues another one. However, each request to the script on the server has an extremely long timeout, and the server only responds to the request once something has happened. You can see this happening if you bring up Firebug's Console tab while on Facebook, with requests to a script possibly taking minutes. It is quite ingenious really, since this method cuts down immediately on both the number of requests, and how often you have to send them. You effectively now have an event framework that allows the server to 'fire' events.
Behind this, in terms of the actual content returned from those polls, it's a JSON response, with what appears to be a list of events, and info about them. It's minified though, so is a bit hard to read.
In terms of the actual technology, AJAX is the way to go here, because you can control request timeouts, and many other things. I'd recommend (Stack overflow cliche here) using jQuery to do the AJAX, it'll take a lot of the cross-compability problems away. In terms of PHP, you could simply poll an event log database table in your PHP script, and only return to the client when something happens? There are, I expect, many ways of implementing this.
Implementing:
Server Side:
There appear to be a few implementations of comet libraries in PHP, but to be honest, it really is very simple, something perhaps like the following pseudocode:
while(!has_event_happened()) {
sleep(5);
}
echo json_encode(get_events());
The has_event_happened function would just check if anything had happened in an events table or something, and then the get_events function would return a list of the new rows in the table? Depends on the context of the problem really.
Don't forget to change your PHP max execution time, otherwise it will timeout early!
Client Side:
Take a look at the jQuery plugin for doing Comet interaction:
That said, the plugin seems to add a fair bit of complexity, it really is very simple on the client, perhaps (with jQuery) something like:
function doPoll() {
$.get("events.php", {}, function(result) {
$.each(result.events, function(event) { //iterate over the events
//do something with your event
});
doPoll();
//this effectively causes the poll to run again as
//soon as the response comes back
}, 'json');
}
$(document).ready(function() {
$.ajaxSetup({
timeout: 1000*60//set a global AJAX timeout of a minute
});
doPoll(); // do the first poll
});
The whole thing depends a lot on how your existing architecture is put together.
We will consider first List type is String and want to convert it to Integer type of List.
List<String> origList = new ArrayList<>(); // assume populated
Add values in the original List.
origList.add("1");
origList.add("2");
origList.add("3");
origList.add("4");
origList.add("8");
Create target List of Integer Type
List<Integer> targetLambdaList = new ArrayList<Integer>();
targetLambdaList=origList.stream().map(Integer::valueOf).collect(Collectors.toList());
Print List values using forEach:
targetLambdaList.forEach(System.out::println);
You can do something like what i did with my List< Future< String > > or any other Arraylist, Type returned from other class called PingScan that returns List> because it implements service executor. Anyway the code down note that you can use foreach and retrieve data from the List.
PingScan p = new PingScan();
List<Future<String>> scanResult = p.checkThisIP(jFormattedTextField1.getText(), jFormattedTextField2.getText());
for (final Future<String> f : scanResult) {
try {
if (f.get() instanceof String) {
String ip = f.get();
Object[] data = {ip};
tableModel.addRow(data);
}
} catch (InterruptedException | ExecutionException ex) {
Logger.getLogger(gui.class.getName()).log(Level.SEVERE, null, ex);
}
}
You could try to extract columns as list, massage this as you want, and reindex your dataframe:
>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...
>>> df.reindex(columns=['n']+df.columns[:-1].tolist())
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
In case you did what the questioner hinted at (forgot to fork and just locally cloned a repo, made changes and now need to issue a pull request) you can get back on track:
You can use the call
command...
Type: call /?
Usage: call [drive:][path]filename [batch-parameters]
For example call "Example File/Input File/My Program.bat"
[This is also capable with calling files that have a .exe, .cmd, .txt, etc.
NOTE: THIS COMMAND DOES NOT ALWAYS WORK!!!
Not all computers are capable to run this command, but if it does work than it is very useful, and you won't have to open a brand new window...
From a Spring point of view, none of the HttpMessageConverter
instances registered with the RestTemplate
can convert text/html
content to a ProductList
object. The method of interest is HttpMessageConverter#canRead(Class, MediaType)
. The implementation for all of the above returns false
, including Jaxb2RootElementHttpMessageConverter
.
Since no HttpMessageConverter
can read your HTTP response, processing fails with an exception.
If you can control the server response, modify it to set the Content-type
to application/xml
, text/xml
, or something matching application/*+xml
.
If you don't control the server response, you'll need to write and register your own HttpMessageConverter
(which can extend the Spring classes, see AbstractXmlHttpMessageConverter
and its sub classes) that can read and convert text/html
.
To blank it:
myObject["myVar"]=null;
To remove it:
delete myObject["myVar"]
as you can see in duplicate answers
Check out this question: Is there a good Valgrind substitute for Windows? . Though general substitute for valgrind is asked, it mainly discusses memory leak detectors and not race conditions detections.
Assuming your code is inside an MVC controller:
public class MyController : Microsoft.AspNetCore.Mvc.Controller
From the Controller
base class, you can get the IClaimsPrincipal
from the User
property
System.Security.Claims.ClaimsPrincipal currentUser = this.User;
You can check the claims directly (without a round trip to the database):
bool IsAdmin = currentUser.IsInRole("Admin");
var id = _userManager.GetUserId(User); // Get user id:
Other fields can be fetched from the database's User entity:
Get the user manager using dependency injection
private UserManager<ApplicationUser> _userManager;
//class constructor
public MyController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
And use it:
var user = await _userManager.GetUserAsync(User);
var email = user.Email;
If the user cancel the request, the data will be returned as NULL
. The thread will throw a nullPointerException
when you call data.getExtras().get("data");
. I think you just need to add a conditional to check if the data returned is null.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
if (data != null)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
Like most form controls in HTML, the results of applying CSS to <select>
and <option>
elements vary a lot between browsers. Chrome, as you've found, won't let you apply and font styles to an <option>
element directly --- if you do Inspect Element on it, you'll see the font-size: 14px
declaration is crossed through as if it's been overridden by the cascade, but it's actually because Chrome is ignoring it.
However, Chrome will let you apply font styles to the <optgroup>
element, so to achieve the result you want you can wrap all the <option>
s in an <optgroup>
and then apply your font styles to a .styled-select optgroup
selector. If you want the optgroup sans-label, you may have to do some clever CSS with positioning or something to hide the white area at the top where the label would be shown, but that should be possible.
Forked to a new JSFiddle to show you what I mean:
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:
When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.
Even adding responseType, I dealt with it for days with no success. Finally I got it. Make sure that in your backend script you don't define header as -("Content-Type: application/json);
Becuase if you turn it to text but backend asks for json, it will return an error...
They're used in different places. group by
modifies the entire query, like:
select customerId, count(*) as orderCount
from Orders
group by customerId
But partition by
just works on a window function, like row_number
:
select row_number() over (partition by customerId order by orderId)
as OrderNumberForThisCustomer
from Orders
A group by
normally reduces the number of rows returned by rolling them up and calculating averages or sums for each row. partition by
does not affect the number of rows returned, but it changes how a window function's result is calculated.
I prefered to use an expression. This lets me do stuff like focus on a button when a field is valid, reaches a certain length, and of course after load.
<button type="button" moo-focus-expression="form.phone.$valid">
<button type="submit" moo-focus-expression="smsconfirm.length == 6">
<input type="text" moo-focus-expression="true">
On a complex form this also reduces need to create additional scope variables for the purposes of focusing.
I recently posted a free software library for this: "html5csv.js" -- GitHub
It is intended to help streamline the creation of small simulator apps in Javascript that might need to import or export csv files, manipulate, display, edit the data, perform various mathematical procedures like fitting, etc.
After loading "html5csv.js" the problem of scanning a table and creating a CSV is a one-liner:
CSV.begin('#PrintDiv').download('MyData.csv').go();
Here is a JSFiddle demo of your example with this code.
Internally, for Firefox/Chrome this is a data URL oriented solution, similar to that proposed by @italo, @lepe, and @adeneo (on another question). For IE
The CSV.begin()
call sets up the system to read the data into an internal array. That fetch then occurs. Then the .download()
generates a data URL link internally and clicks it with a link-clicker. This pushes a file to the end user.
According to caniuse IE10 doesn't support <a download=...>
. So for IE my library calls navigator.msSaveBlob()
internally, as suggested by @Manu Sharma
You can just use the TimeOfDay property of date time, which is TimeSpan type:
DateTime.TimeOfDay
This property has been around since .NET 1.1
More information: http://msdn.microsoft.com/en-us/library/system.datetime.timeofday(v=vs.110).aspx
Unfortunately, all of these solutions rely on specifying a fixed width. Since the tables are generated dynamically (statistical results pulled from a database), the width can not be known in advance.
The desired result can be achieved by wrapping the two tables within another table:
<table align="center"><tr><td>
//code for table on the left
</td><td>
//code for table on the right
</td></tr></table>
and the result is a perfectly centered pair of tables that responds fluidly to arbitrary widths and page (re)sizes (and the align="center" table attribute could be hoisted out into an outer div with margin autos).
I conclude that there are some layouts that can only be achieved with tables.
Lets say we have existing list, and gonna use java 8 for this activity `
import java.util.*;
import java.util.stream.Collectors;
public class AddingArray {
public void addArrayInList(){
List<Integer> list = Arrays.asList(3, 7, 9);
// And we have an array of Integer type
int nums[] = {4, 6, 7};
//Now lets add them all in list
// converting array to a list through stream and adding that list to previous list
list.addAll(Arrays.stream(nums).map(num ->
num).boxed().collect(Collectors.toList()));
}
}
`
--SUBSTITUTION VARIABLES
-- these variables are used to store values TEMPorarily.
-- The values can be stored temporarily through
-- Single Ampersand (&)
-- Double Ampersand(&&)
-- The single ampersand substitution variable applies for each instance when the
--SQL statement is created or executed.
-- The double ampersand substitution variable is applied for all instances until
--that SQL statement is existing.
INSERT INTO Student (Stud_id, First_Name, Last_Name, Dob, Fees, Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &fees, '&Gender');
--Using double ampersand substitution variable
INSERT INTO Student (Stud_id,First_Name, Last_Name,Dob,Fees,Gender)
VALUES (&stud_Id, '&First_Name' ,'&Last_Name', '&Dob', &&fees,'&gender');
Let's solve that using recursion...
ArrayList<Integer> al = new ArrayList<>();
void intToArray(int num){
if( num != 0){
int temp = num %10;
num /= 10;
intToArray(num);
al.add(temp);
}
}
Explanation:
Suppose the value of num
is 12345.
During the first call of the function, temp
holds the value 5 and a value of num
= 1234. It is again passed to the function, and now temp
holds the value 4 and the value of num
is 123... This function calls itself till the value of num
is not equal to 0.
Stack trace:
temp - 5 | num - 1234
temp - 4 | num - 123
temp - 3 | num - 12
temp - 2 | num - 1
temp - 1 | num - 0
And then it calls the add method of ArrayList and the value of temp
is added to it, so the value of list is:
ArrayList - 1
ArrayList - 1,2
ArrayList - 1,2,3
ArrayList - 1,2,3,4
ArrayList - 1,2,3,4,5
Reverse the items in a sub-list
int[] l = {0, 1, 2, 3, 4, 5, 6};
var res = new List<int>();
res.AddRange(l.Where((n, i) => i < 2));
res.AddRange(l.Where((n, i) => i >= 2 && i <= 4).Reverse());
res.AddRange(l.Where((n, i) => i > 4));
Gives 0,1,4,3,2,5,6
PHP has a built in function called bool chmod(string $filename, int $mode )
private function writeFileContent($file, $content){
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
chmod($file, 0777); //changed to add the zero
return true;
}
Use this little Windows command-line app that gets the CREATE TABLE
script (with constraints) for any table. I've written it in C#. Just compile it and carry it on a memory stick. Perhaps someone can port it to Powershell.
using System;
using System.Linq;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ViewSource
{
public class ViewSource
{
public static void Main(string[] args)
{
if (args.Length != 6)
{
Console.Error.WriteLine("Syntax: ViewSource.exe <server>" +
" <user> <password> <database> <schema> <table>");
}
Script(args[0], args[1], args[2], args[3], args[4], args[5]);
}
private static void Script(string server, string user,
string password, string database, string schema, string table)
{
new Server(new ServerConnection(server, user, password))
.Databases[database]
.Tables[table, schema]
.Script(new ScriptingOptions { SchemaQualify = true,
DriAll = true })
.Cast<string>()
.Select(s => s + "\n" + "GO")
.ToList()
.ForEach(Console.WriteLine);
}
}
}
in my case it was just to put return ; at the end of function where i have set session
It is a comment but should probably be an answer.
Make sure that your app name is in settings.py INSTALLED_APPS
otherwise no matter what you do it will not run the migrations.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
Then run:
./manage.py makemigrations blog
The only real difference between RPC and RMI is that there is objects involved in RMI: instead of invoking functions through a proxy function, we invoke methods through a proxy.
First off all I would like to thanks @MaximShoustin.
Thanks of you I have really nice table.
I provide some small modification in $scope.range
and $scope.setPage
.
In this way I have now possibility to go to the last page or come back to the first page.
Also when I'm going to next or prev page the navigation is changing when $scope.gap
is crossing. And the current page is not always on first position. For me it's looking more nicer.
Here is the new fiddle example: http://jsfiddle.net/qLBRZ/3/
Other answers have given clear enough examples of a record referencing another record in the same table.
There are even valid use cases for a record referencing itself in the same table. For example, a point of sale system accepting many tenders may need to know which tender to use for change when the payment is not the exact value of the sale. For many tenders that's the same tender, for others that's domestic cash, for yet other tenders, no form of change is allowed.
All this can be pretty elegantly represented with a single tender attribute which is a foreign key referencing the primary key of the same table, and whose values sometimes match the respective primary key of same record. In this example, the absence of value (also known as NULL value) might be needed to represent an unrelated meaning: this tender can only be used at its full value.
Popular relational database management systems support this use case smoothly.
Take-aways:
When inserting a record, the foreign key reference is verified to be present after the insert, rather than before the insert.
When inserting multiple records with a single statement, the order in which the records are inserted matters. The constraints are checked for each record separately.
Certain other data patterns, such as those involving circular dependences on record level going through two or more tables, cannot be purely inserted at all, or at least not with all the foreign keys enabled, and they have to be established using a combination of inserts and updates (if they are truly necessary).
I find this more elegant than the two top answers:
from urllib.parse import urlencode, urlparse, parse_qs
def merge_url_query_params(url: str, additional_params: dict) -> str:
url_components = urlparse(url)
original_params = parse_qs(url_components.query)
# Before Python 3.5 you could update original_params with
# additional_params, but here all the variables are immutable.
merged_params = {**original_params, **additional_params}
updated_query = urlencode(merged_params, doseq=True)
# _replace() is how you can create a new NamedTuple with a changed field
return url_components._replace(query=updated_query).geturl()
assert merge_url_query_params(
'http://example.com/search?q=question',
{'lang':'en','tag':'python'},
) == 'http://example.com/search?q=question&lang=en&tag=python'
The most important things I dislike in the top answers (they are nevertheless good):
query
is in the URL componentsParseResult
What's bad about my response is the magically looking dict
merge using unpacking, but I prefer that to updating an already existing dictionary because of my prejudice against mutability.
self.class.default_make
This problem consists of two very different sub-problems:
While randomness is quite easily achieved, the uniqueness without a retry loop is not. This brings us to concentrate on the uniqueness first. Non-random uniqueness can trivially be achieved with AUTO_INCREMENT
. So using a uniqueness-preserving, pseudo-random transformation would be fine:
RAND(N)
itself!A sequence of random numbers created by the same seed is guaranteed to be
INT32
So we use @AndreyVolk's or @GordonLinoff's approach, but with a seeded RAND
:
e.g. Assumin id
is an AUTO_INCREMENT
column:
INSERT INTO vehicles VALUES (blah); -- leaving out the number plate
SELECT @lid:=LAST_INSERT_ID();
UPDATE vehicles SET numberplate=concat(
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@lid)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed:=round(rand(@seed)*4294967296))*36+1, 1),
substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(@seed)*36+1, 1)
)
WHERE id=@lid;
GetThreadId
returns the ID of a given native thread. There are ways to make it work with managed threads, I'm sure, all you need to find is the thread handle and pass it to that function.
GetCurrentThreadId
returns the ID of the current thread.
GetCurrentThreadId
has been deprecated as of .NET 2.0: the recommended way is the Thread.CurrentThread.ManagedThreadId
property.
For very simple pseudorandom-looking stuff, I use this oneliner that I found on the internet somewhere:
float rand(vec2 co){
return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}
You can also generate a noise texture using whatever PRNG you like, then upload this in the normal fashion and sample the values in your shader; I can dig up a code sample later if you'd like.
Also, check out this file for GLSL implementations of Perlin and Simplex noise, by Stefan Gustavson.
Here is the answer with blue box-shadow,border,outline removed with file name fix in custom-file input of bootstrap appear on choose filename and if you not choose any file then show No file chosen.
$(document).on('change', 'input[type="file"]', function (event) { _x000D_
var filename = $(this).val();_x000D_
if (filename == undefined || filename == ""){_x000D_
$(this).next('.custom-file-label').html('No file chosen');_x000D_
}_x000D_
else _x000D_
{ $(this).next('.custom-file-label').html(event.target.files[0].name); }_x000D_
});
_x000D_
input[type=file]:focus,.custom-file-input:focus~.custom-file-label {_x000D_
outline:none!important;_x000D_
border-color: transparent;_x000D_
box-shadow: none!important;_x000D_
}_x000D_
.custom-file,_x000D_
.custom-file-label,_x000D_
.custom-file-input {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="container py-5">_x000D_
<div class="input-group mb-3">_x000D_
<div class="input-group-prepend">_x000D_
<span class="input-group-text">Upload</span>_x000D_
</div>_x000D_
<div class="custom-file">_x000D_
<input type="file" class="custom-file-input" id="inputGroupFile01">_x000D_
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
For php 7 on Ubuntu:
sudo apt-get install php7.0-gd
If you want to dubbel check the amount of cores you have on your machine to the number your java program is giving you.
In Linux terminal: lscpu
In Windows terminal (cmd): echo %NUMBER_OF_PROCESSORS%
In Mac terminal: sysctl -n hw.ncpu
The error message is saying that there's already a record with null
as the email. In other words, you already have a user without an email address.
The relevant documentation for this:
If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.
You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.
Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.
In other words, a sparse index is ok with multiple documents all having null
values.
From comments:
Your error says that the key is named mydb.users.$email_1
which makes me suspect that you have an index on both users.email
and users.local.email
(The former being old and unused at the moment). Removing a field from a Mongoose model doesn't affect the database. Check with mydb.users.getIndexes()
if this is the case and manually remove the unwanted index with mydb.users.dropIndex(<name>)
.
Because you rebased feature
on top of the new master
, your local feature
is not a fast-forward of origin/feature
anymore. So, I think, it's perfectly fine in this case to override the fast-forward check by doing git push origin +feature
. You can also specify this in your config
git config remote.origin.push +refs/heads/feature:refs/heads/feature
If other people work on top of origin/feature
, they will be disturbed by this forced update. You can avoid that by merging in the new master
into feature
instead of rebasing. The result will indeed be a fast-forward.
All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE
.
Reference: https://www.postgresql.org/docs/current/functions-matching.html
In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!
T1 and T2 are dataframes that have the same indices
import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')
P.S. I had to use merge because append would fill NaNs in unnecessarily.
This code is working fine for me,
var a = serializer.Deserialize<List<Entity>>(json);
Change your onCreate to
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for me this update worked
You can use the sort
command:
sort -k2 -n yourfile
-n
,--numeric-sort
compare according to string numerical value
For example:
$ cat ages.txt
Bob 12
Jane 48
Mark 3
Tashi 54
$ sort -k2 -n ages.txt
Mark 3
Bob 12
Jane 48
Tashi 54
We just released an experimental GitHub repository which should ease the process of using NVIDIA GPUs inside Docker containers.
Here are some useful links:
The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.
Basically you need following things to make location detector android app
Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.
Using all these resources, you will be able to create an flawless android location detection app.
You will first need to listen for current location of user. You can use any of below libraries to quick start.
This library provide last known location, location updates
With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.
Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.
Google Maps Android API utility library
If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.
Simple, smooth animation for route / polylines on google maps using projections. (WIP)
This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.
Building upon Anthony and Anton's answers I incorporated the ability to rotate the generated circle without affecting it's overall appearance. This is useful if you're using the path for an animation and you need to control where it begins.
function(cx, cy, r, deg){
var theta = deg*Math.PI/180,
dx = r*Math.cos(theta),
dy = -r*Math.sin(theta);
return "M "+cx+" "+cy+"m "+dx+","+dy+"a "+r+","+r+" 0 1,0 "+-2*dx+","+-2*dy+"a "+r+","+r+" 0 1,0 "+2*dx+","+2*dy;
}
Apache Commons
for (String code: ListUtils.emptyIfNull(codes)) {
}
Google Guava
for (String code: Optional.of(codes).get()) {
}
Quick answer for single line span
Make the child (in this case a span) the same line-height
as the parent <div>
's height
<div class="parent">
<span class="child">Yes mom, I did my homework lol</span>
</div>
You should then add the CSS rules
.parent { height: 20px; }
.child { line-height: 20px; vertical-align: middle; }
Or you can target it with a child selector
.parent { height: 20px; }
.parent > span { line-height: 20px; vertical-align: middle; }
Background on my own use of this
I ran into this similar issue where I needed to vertically center items in a mobile menu. I made the div and spans inside the same line height. Note that this is for a meteor project and therefore not using inline css ;)
HTML
<div class="international">
<span class="intlFlag">
{{flag}}
</span>
<span class="intlCurrent">
{{country}}
</span>
<span class="intlButton">
<i class="fa fa-globe"></i>
</span>
</div>
CSS (option for multiple spans in a div)
.international {
height: 42px;
}
.international > span {
line-height: 42px;
}
In this case if I just had one span I could have added the CSS rule directly to that span.
CSS (option for one specific span)
.intlFlag { line-height: 42px; }
Here is how it displayed for me
First install php-mysql
sudo apt-get install php7.0-mysql
//change the version number based on the php version
then enable the module
sudo phpenmod pdo_mysql
and restart apache
sudo service apache2 restart
You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include
directive. Then you may call the other function.
void MyFunc();
#include "other.h"
int main() {
MyFunc();
}
#include "other.h"
#include <iostream>
void MyFunc() {
std::cout << "Ohai from another .cpp file!";
std::cin.get();
}
They have one for free as a sample at http://www.xamltemplates.net/
Type the following command in Python shell
import django
django.get_version()
Put the data into a Pivot Table and do a top n filter on it
As @bodi0 correctly said, it is not possible. You either have to extent Bootstrap's grid system (you can search and find various solutions, here is a 7-column example) or use nested rows e.g. http://bootply.com/dd50he9tGe.
In the case of nested rows you might not always get the exact result but a similar one
<div class="row">
<div class="col-lg-5">
<div class="row">
<div class="col-lg-4">1.67 (close to 1.5)</div>
<div class="col-lg-8">3.33 (close to 3.5)</div>
</div>
</div>
<div class="col-lg-7">
<div class="row">
<div class="col-lg-6">3.5</div>
<div class="col-lg-6">3.5</div>
</div>
</div>
</div>
worked for me Thanks
Versions for reference
jquery-3.3.1.js
/1.10.19/js/jquery.dataTables.min.js
/buttons/1.5.2/js/dataTables.buttons.min.js
There is also a POSIX library for POSIX operating systems. Check for compatability
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>
void *task(void *argument){
char* msg;
msg = (char*)argument;
std::cout<<msg<<std::endl;
}
int main(){
pthread_t thread1, thread2;
int i1,i2;
i1 = pthread_create( &thread1, NULL, task, (void*) "thread 1");
i2 = pthread_create( &thread2, NULL, task, (void*) "thread 2");
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
compile with -lpthread
You could achieve this quite easily with jQuery by registering for the click event of the anchors (with class="movie") and using the .load()
method to send an AJAX request and replace the contents of the summary div:
$(function() {
$('.movie').click(function() {
$('#summary').load(this.href);
// it's important to return false from the click
// handler in order to cancel the default action
// of the link which is to redirect to the url and
// execute the AJAX request
return false;
});
});
if you want to list all the containers name with the relevant volumes that attached to each container you can try this:
docker ps -q | xargs docker container inspect -f '{{ .Name }} {{ .HostConfig.Binds }}'
example output:
/opt_rundeck_1 [/opt/var/lib/mysql:/var/lib/mysql:rw /var/lib/rundeck/var/storage:/var/lib/rundeck/var/storage:rw /opt/var/rundeck/.ssh:/var/lib/rundeck/.ssh:rw /opt/etc/rundeck:/etc/rundeck:rw /var/log/rundeck:/var/log/rundeck:rw /opt/rundeck-plugins:/opt/rundeck-plugins:rw /opt/var/rundeck:/var/rundeck:rw]
/opt_rundeck_1 - container name
[..] - volumes attached to the conatiner
You can do it using string.indexOf("{item}")
. If the result is greater than -1 {item}
is in the string
SELECT * FROM table ORDER BY id DESC,datechat desc LIMIT 50
If you have a date field that is storing the date(and time) on which the chat was sent or any field that is filled with incrementally(order by DESC) or desinscrementally( order by ASC) data per row put it as second column on which the data should be order.
That's what worked for me!!!! hope it will help!!!!
I doubt this is good practice but it's working locally. I'll update this if it fails when I publish/deploy (to an IIS web service).
Step 1 - Add this assembly to the top of your class (in my case, controller class):
using Microsoft.Extensions.Configuration;
Step 2 - Add this or something like it:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json").Build();
Step 3 - Call your key's value by doing this (returns string):
config["NameOfYourKey"]
According to Flexbugs:
In IE 10-11,
min-height
declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.
Here are a couple of workarounds:
<aside>
and <section>
:html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1;
display: flex;
}
aside, section {
overflow: auto;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1 0 auto;
display: flex;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
Try this:
net use * /delete /y
The /y
key makes it select Yes in prompt silently
Go into Terminal and type man mail
for help.
You will need to set SMTP
up:
http://hints.macworld.com/article.php?story=20081217161612647
See also:
http://www.mactricksandtips.com/2008/09/send-mail-over-your-network.html
Eg:
mail -s "hello" "[email protected]" <<EOF
hello
world
EOF
This will send an email to [email protected]
with the subject hello
and the message
Hello
World
Add this to your css:
.row-centered {
text-align:center;
}
.col-centered {
display:inline-block;
float:none;
/* reset the text-align */
text-align:left;
/* inline-block space fix */
margin-right:-4px;
}
Then, in your HTML code:
<div class=" row row-centered">
<div class="col-*-* col-centered>
Your content
</div>
</div>
here, Use explode() function to convert string into array, by a string
click here to know more about explode()
$str = "this is string";
$delimiter = ' '; // use any string / character by which, need to split string into Array
$resultArr = explode($delimiter, $str);
var_dump($resultArr);
Output :
Array
(
[0] => "this",
[1] => "is",
[2] => "string "
)
it is same as the requirements:
arr[0]="this";
arr[1]="is";
arr[2]="string";
this.WindowState = FormWindowState.Minimized;
If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,
RewriteCond %{REQUEST_FILENAME} !-d
and if the requested filename is not a regular file that exists,
RewriteCond %{REQUEST_FILENAME} !-f
and if the requested filename is not a symbolic link,
RewriteCond %{REQUEST_FILENAME} !-l
then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
Another Example:
RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]
With the [QSA] flag, a request for
/pages/123?one=two
will be mapped to
/page.php?page=123&one=two
April 11, 2019
None of the answers above solved my problem so I wanted to include a current solution (as of April 2019) for people using Ubuntu 18.04. This is how I solved the question above...
/usr/lib/Android/
Search for where the SDK is installed and the version. In my case it was here:
/usr/lib/Android/Sdk/build-tools/28.0.3
Note: that I am using version 28.0.3, your version may differ.
Add ANDROID_HOME
to the environment path. To do this, open /etc/environment with a text editor:
sudo nano /etc/environment
Add a line for ANDROID_HOME
for your specific version and path. In my case it was:
ANDROID_HOME="/usr/lib/Android/Sdk/build-tools/28.0.3"
Finally, source the updated environment with: source /etc/environment
Confirm this by trying: echo $ANDROID_HOME
in the terminal. You should get the path of your newly created variable.
One additionally note about sourcing, I did have to restart my computer for the VScode terminal to recognize my changes. After the restart, the environment was set and I haven't had any issues since.
It is possible to parse dynamic values in a couple of way.
Interpolation with double-curly braces:
ng-style="{'background-image':'url({{myBackgroundUrl}})'}"
String concatenation:
ng-style="{'background-image': 'url(' + myBackgroundUrl + ')'}"
ES6 template literals:
ng-style="{'background-image': `url(${myBackgroundUrl})`}"
I think a better way to solve this would be to use the datetime callable:
from datetime import datetime
date = models.DateField(default=datetime.now)
Note that no parenthesis were used. If you used parenthesis you would invoke the now()
function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.
Credit to Django Musings. I've used it and works fine.
I know it's "a bit late" but just in case if anybody needs to do this in LINQ Method syntax (which is why I found this post initially), this would be how to do that:
var results = context.Periods
.GroupJoin(
context.Facts,
period => period.id,
fk => fk.periodid,
(period, fact) => fact.Where(f => f.otherid == 17)
.Select(fact.Value)
.DefaultIfEmpty()
)
.Where(period.companyid==100)
.SelectMany(fact=>fact).ToList();
The first error you're getting - permissions - is the most indicative. Bump wp-content and wp-admin to 777 and try it, and if it works, then change them both back to 755 and see if it still works. What are you using to change folder permissions? An FTP client?
There is no best IDE. You make it as good as you get used using it.
Here's a LESS mixin for transitioning two properties at once:
.transition-two(@transition1, @transition1-duration, @transition2, @transition2-duration) {
-webkit-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
-moz-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
-o-transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
transition: @transition1 @transition1-duration, @transition2 @transition2-duration;
}
use the following code to apply some margin
$(".button").click(function() {
$('html, body').animate({
scrollTop: $(".scrolltothis").offset().top + 50;
}, 500);
});
See this ans: Scroll down to div + a certain margin
It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.
those are miliseconds, just divide them by 1000, since gmtime expects seconds ...
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0))
Without commit messages, only the hash:
git log --pretty=oneline | awk '{print $1}'
The question is how to create a new virtual environment in VSCode, that is why telling the following Anaconda solution might not the needed answer to the question. It is just relevant for Anaconda users.
Just create a venv using conda, see here. Afterwards open VSCode and left-click on the VSCode interpreter shown in VSCode at the bottom left:
Choose a virtual environment that pops up in a dropdown of the settings window, and you are done. Mind the answer of @RamiMa.
This link will help you out completely(the Shortest and Most Elegant way):
PdfPTable tbheader = new PdfPTable(3);
tbheader.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
tbheader.DefaultCell.Border = 0;
tbheader.AddCell(new Paragraph());
tbheader.AddCell(new Paragraph());
var _cell2 = new PdfPCell(new Paragraph("This is my header", arial_italic));
_cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
_cell2.Border = 0;
tbheader.AddCell(_cell2);
float[] widths = new float[] { 20f, 20f, 60f };
tbheader.SetWidths(widths);
tbheader.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin), writer.DirectContent);
PdfPTable tbfooter = new PdfPTable(3);
tbfooter.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
tbfooter.DefaultCell.Border = 0;
tbfooter.AddCell(new Paragraph());
tbfooter.AddCell(new Paragraph());
var _cell2 = new PdfPCell(new Paragraph("This is my footer", arial_italic));
_cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
_cell2.Border = 0;
tbfooter.AddCell(_cell2);
tbfooter.AddCell(new Paragraph());
tbfooter.AddCell(new Paragraph());
var _celly = new PdfPCell(new Paragraph(writer.PageNumber.ToString()));//For page no.
_celly.HorizontalAlignment = Element.ALIGN_RIGHT;
_celly.Border = 0;
tbfooter.AddCell(_celly);
float[] widths1 = new float[] { 20f, 20f, 60f };
tbfooter.SetWidths(widths1);
tbfooter.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);
I would like to correct the @Neal answer which was pretty good for integers, but the number 1 would return a length of 0 in the previous case.
function Longueur(numberlen)
{
var length = 0, i; //define `i` with `var` as not to clutter the global scope
numberlen = parseInt(numberlen);
for(i = numberlen; i >= 1; i)
{
++length;
i = Math.floor(i/10);
}
return length;
}
To expand on the answer given by Chris
if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know
>>> from datetime import date, timedelta
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'
If you want it as an integer (which can be useful)
>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817
select
(select count(*) from foo) as foo
, (select count(*) from bar) as bar
, ...
The question is quite old so I feel like I need to give a more up to date response to this question.
Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is http://xamarin.com/
You can use the open event handler to apply additional styling:
open: function(event) {
$('.ui-dialog-buttonpane').find('button:contains("Cancel")').addClass('cancelButton');
}
Using IDE configuration:
Open Visual Studio 2012, click on Tools from the file menu bar and then click Options,
From the Options window, expand the Source Control option, click on Plug-in Selection and make sure that the Current source control plug-in is set to Visual Studio Team Foundation Server.
Next, click on the Visual Studio Team Foundation Server option under Source Control and perform the following steps: Check Use proxy server for file downloads. Enter the host name of your preferred Team Foundation Server 2010 Proxy server. Set the port to 443. Check Use SSL encryption (https) to connect.
Click the OK button.
Using exe.config:
Modify the devenv.exe.config where IDE executable is like this:
<system.net>
<defaultProxy>
<proxy proxyaddress=”http://proxy:3128”
bypassonlocal=”True” autoDetect=”True” />
<bypasslist>
<add address=”http://URL”/>
</bypasslist>
</defaultProxy>
Declare your proxy at proxyaddress and remember bypasslist urls and ip addresses will be excluded from proxy traffic.
Then restart visual studio to update changes.
Put this bean in your configuration class.
@Bean
public Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
and then You can use
<T> BindingResult validate(T t) {
DataBinder binder = new DataBinder(t);
binder.setValidator(validator);
binder.validate();
return binder.getBindingResult();
}
for validating a bean manually. Then You will get all result in BindingResult and you can retrieve from there.
df.index
Index
object. list(df.index)
df.index['Row 2':'Row 5']
The list of encodings that node supports natively is rather short:
If you are using an older version than 6.4.0, or don't want to deal with non-Unicode encodings, you can recode the string:
Use iconv-lite to recode files:
var iconvlite = require('iconv-lite');
var fs = require('fs');
function readFileSync_encoding(filename, encoding) {
var content = fs.readFileSync(filename);
return iconvlite.decode(content, encoding);
}
Alternatively, use iconv:
var Iconv = require('iconv').Iconv;
var fs = require('fs');
function readFileSync_encoding(filename, encoding) {
var content = fs.readFileSync(filename);
var iconv = new Iconv(encoding, 'UTF-8');
var buffer = iconv.convert(content);
return buffer.toString('utf8');
}
If someone is using bootstrap sass note the code is on the _reboot.scss file like this:
button:focus {
outline: 1px dotted;
outline: 5px auto -webkit-focus-ring-color;
}
So if you want to keep the _reboot file I guess feel free to override with plain css instead of trying to look for a variable to change.
This will automatically enable autocomplete and save password in browsers.
autocomplete="on"
(form)autocomplete="username"
(input, email/username)autocomplete="current-password"
(input, password)<form autocomplete="on">
<input id="user-text-field" type="email" autocomplete="username"/>
<input id="password-text-field" type="password" autocomplete="current-password"/>
</form>
Check out more at Apple's documentation: Enabling Password AutoFill on an HTML Input Element
You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -
, like script.ps1 -server http://devserver
Then you handle them in param
section in the beginning of the file.
You can also assign default values to your params, read them from console if not available or stop script execution:
param (
[string]$server = "http://defaultserver",
[Parameter(Mandatory=$true)][string]$username,
[string]$password = $( Read-Host "Input password, please" )
)
Inside the script you can simply
write-output $server
since all parameters become variables available in script scope.
In this example, the $server
gets a default value if the script is called without it, script stops if you omit the -username
parameter and asks for terminal input if -password
is omitted.
Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.
The keyword for that is [switch]
parameter type:
param (
[string]$server = "http://defaultserver",
[string]$password = $( Read-Host "Input password, please" ),
[switch]$force = $false
)
Inside the script then you would work with it like this:
if ($force) {
//deletes a file or does something "bad"
}
Now, when calling the script you'd set the switch/flag parameter like this:
.\yourscript.ps1 -server "http://otherserver" -force
If you explicitly want to state that the flag is not set, there is a special syntax for that
.\yourscript.ps1 -server "http://otherserver" -force:$false
Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):
I had the same problem... I had to run it as a user.
00 * * * * root /usr/bin/php /var/virtual/hostname.nz/public_html/cronjob.php
The .length
property only tracks properties with numeric indexes (keys). You're using strings for keys.
You can do this:
var arr_jq_TabContents = {}; // no need for an array
arr_jq_TabContents["Main"] = jq_TabContents_Main;
arr_jq_TabContents["Guide"] = jq_TabContents_Guide;
arr_jq_TabContents["Articles"] = jq_TabContents_Articles;
arr_jq_TabContents["Forum"] = jq_TabContents_Forum;
for (var key in arr_jq_TabContents) {
console.log(arr_jq_TabContents[key]);
}
To be safe, it's a good idea in loops like that to make sure that none of the properties are unexpected results of inheritance:
for (var key in arr_jq_TabContents) {
if (arr_jq_TabContents.hasOwnProperty(key))
console.log(arr_jq_TabContents[key]);
}
edit — it's probably a good idea now to note that the Object.keys()
function is available on modern browsers and in Node etc. That function returns the "own" keys of an object, as an array:
Object.keys(arr_jq_TabContents).forEach(function(key, index) {
console.log(this[key]);
}, arr_jq_TabContents);
The callback function passed to .forEach()
is called with each key and the key's index in the array returned by Object.keys()
. It's also passed the array through which the function is iterating, but that array is not really useful to us; we need the original object. That can be accessed directly by name, but (in my opinion) it's a little nicer to pass it explicitly, which is done by passing a second argument to .forEach()
— the original object — which will be bound as this
inside the callback. (Just saw that this was noted in a comment below.)
Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.
You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.
I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.
Angular-cli includes the assets folder in the build options by default. I got this issue when the name of my images had spaces or dashes. For example :
If you put the image in the assets/img folder, then this line of code should work in your templates :
<img alt="My image name" src="./assets/img/myImageName.png">
If the issue persist just check if your Angular-cli config file and be sure that your assets folder is added in the build options.
ALTER TABLE [Employee]
ALTER COLUMN [Salary] NUMERIC(22,5) NOT NULL
Currently, and with the new versions of Mysql can insert the current date automatically without adding a code in your PHP file. You can achieve that from Mysql while setting up your database as follows:
Now, any new post will automatically get a unique date and time. Hope this can help.
Because timedelta is defined like:
class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])
All arguments are optional and default to 0.
You can easily say "Three days and four milliseconds" with optional arguments that way.
>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)
And for str casting, it returns a nice formatted value instead of __repr__
to improve readability. From docs:
str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)
>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'
Checkout documentation:
http://docs.python.org/library/datetime.html#timedelta-objects
2019
Using fetch
<script>
fetch('page.html')
.then(data => data.text())
.then(html => document.getElementById('elementID').innerHTML = html);
</script>
<div id='elementID'> </div>
fetch needs to receive a http or https link, this means that it won't work locally.
Note: As Altimus Prime said, it is a feature for modern browsers
If you have declare a bitmap object and you want to display it or store this bitmap object. but first you have to assign any image , and you may use the button click event, this code will only demonstrate that how to store the drawable image in bitmap Object.
Bitmap contact_pic = BitmapFactory.decodeResource(
v.getContext().getResources(),
R.drawable.android_logo
);
Now you can use this bitmap object, whether you want to store it, or to use it in google maps while drawing a pic on fixed latitude and longitude, or to use some where else
The most straightforward way to list all tables at command line is, for my taste :
psql -a -U <user> -p <port> -h <server> -c "\dt"
For a given database just add the database name :
psql -a -U <user> -p <port> -h <server> -c "\dt" <database_name>
It works on both Linux and Windows.
If I understand your question correctly, you need %p
to show the address that a pointer is using, for example:
int main() {
int a = 5;
int *p = &a;
printf("%d, %u, %p", p, p, p);
return 0;
}
will output something like:
-1083791044, 3211176252, 0xbf66a93c
Why fight it? Why not simply control your table width using the bootstrap grid?
<div class="row">
<div class="col-sm-6">
<table></table>
</div>
</div>
This will create a table that is half (6 out of 12) of the width of the containing element.
I sometimes use inline styles as per the other answers, but it is discouraged.
Bootstrap 4 has some nice helper classes for width like w-25
, w-50
, w-75
, w-100
, and w-auto
. This will make the table 50% width:
<table class="w-50"></table>
Here's the doc: https://getbootstrap.com/docs/4.0/utilities/sizing/
Very simple, this worked for me (title and icon white):
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="@color/PrimaryColor"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:elevation="4dp" />
for line in f
reads all file to a memory, and that can be a problem.
My offer is to change the original source by replacing stripping and checking for empty line. Because if it is not last line - You will receive at least newline character in it ('\n'). And '.strip()' removes it. But in last line of a file You will receive truely empty line, without any characters. So the following loop will not give You false EOF, and You do not waste a memory:
with open("blablabla.txt", "r") as fl_in:
while True:
line = fl_in.readline()
if not line:
break
line = line.strip()
# do what You want
look at it is informative [Qualified identifiers
A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a sequence of enumeration, (since C++11)class or namespace names or decltype expressions (since C++11) separated by scope resolution operators. For example, the expression std::string::npos is an expression that names the static member npos in the class string in namespace std. The expression ::tolower names the function tolower in the global namespace. The expression ::std::cout names the global variable cout in namespace std, which is a top-level namespace. The expression boost::signals2::connection names the type connection declared in namespace signals2, which is declared in namespace boost.
The keyword template may appear in qualified identifiers as necessary to disambiguate dependent template names]1
Getting the next 5 days:
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}
Here is one way to test which YAML implementation the user has selected on the virtualenv (or the system) and then define load_yaml_file
appropriately:
load_yaml_file = None
if not load_yaml_file:
try:
import yaml
load_yaml_file = lambda fn: yaml.load(open(fn))
except:
pass
if not load_yaml_file:
import commands, json
if commands.getstatusoutput('ruby --version')[0] == 0:
def load_yaml_file(fn):
ruby = "puts YAML.load_file('%s').to_json" % fn
j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
return json.loads(j[1])
if not load_yaml_file:
import os, sys
print """
ERROR: %s requires ruby or python-yaml to be installed.
apt-get install ruby
OR
apt-get install python-yaml
OR
Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
apt-get install epel-release
apt-get install python-pip
apt-get install libyaml-cpp-dev
python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
Pip might not play by all the rules.
Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
https://stackoverflow.com/questions/46326059/
https://stackoverflow.com/questions/36410756/
https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.
""" % sys.argv[0]
os._exit(4)
# test
import sys
print load_yaml_file(sys.argv[1])
...
vowels = "aioue"
text = input("Please enter your text: ")
count = 0
for i in text:
if i in vowels:
count += 1
print("There are", count, "vowels in your text")
...
After Xcode 7, the bitcode option will be enabled by default. If your library was compiled without bitcode, but the bitcode option is enabled in your project settings, you can:
And the Library Build Settings to remove the warnings.
For more information, go to documentation of bitcode in developer library.
And WWDC 2015 Session 102: "Platforms State of the Union"
It looks like the phoneGap plugin will allow you to get the device's uid.
http://docs.phonegap.com/en/3.0.0/cordova_device_device.md.html#device.uuid
Update: This is dependent on running native code. We used this solution writing javascript that was being compiled to native code for a native phone application we were creating.
To have access to stuff provided by math
module, like pi
. You need to import the module first:
import math
print (math.pi)
This happens to me every time I add a pod to the podfile.
I constantly try and find the problem but I just go round in circles again and again!
The error messages range, however the way to fix it is the same every time!
Comment out(#) ALL of the pods in the podfile and run pod install in terminal.
Then...
Uncomment out all of the pods in the podfile and run pod install again.
This has worked for me every single time!
You can change the code by using class definition for the i
element:
<a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
Then you can switch the classes rapresenting the plus/minus state using toggleClass
with multiple classes:
$('#category-tabs li a').click(function(){
$(this).next('ul').slideToggle('500');
$(this).find('i').toggleClass('fa-plus-circle fa-minus-circle');
});
Use the Backstretch plugin. One could even have several images slide. It also works within containers. This way for example one could have only a portion of the background been covered with an background image.
Since even I could get it to work proves it to be an easy to use plugin :).
I know this question has been asked years ago but still wanted to share how I usually compile multiple c++ files.
g++ -c *.cpp -o myprogram
. "myprogram"
./myprogram
that's all!!
The reason I'm using * is that what if you have 30 cpp files would you type all of them? or just use the * sign and save time :)
p.s Use this method only if you don't care about makefile.
For example if you use this code , you can load image from db (mysql) and display it in php5 ;)
<?php
$con =mysql_connect("localhost", "root" , "");
$sdb= mysql_select_db("my_database",$con);
$sql = "SELECT * FROM `news` WHERE 1";
$mq = mysql_query($sql) or die ("not working query");
$row = mysql_fetch_array($mq) or die("line 44 not working");
$s=$row['photo'];
echo $row['photo'];
echo '<img src="'.$s.'" alt="HTML5 Icon" style="width:128px;height:128px">';
?>
The string representation of a DateTime can be parsed by the Time class.
> Time.parse(DateTime.now.to_s).utc
=> 2015-10-06 14:53:51 UTC
I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
it simple, select columns want to insert primary key and click on Key icon on header and save table
happy coding..,
To count the columns of your table precisely, you can get form information_schema.columns
with passing your desired Database(Schema) Name and Table Name.
Reference the following Code:
SELECT count(*)
FROM information_schema.columns
WHERE table_schema = 'myDB'
AND table_name = 'table1';
This is a user-defined function to iterate through a dictionary:
func findDic(dict: [String: String]){
for (key, value) in dict{
print("\(key) : \(value)")
}
}
findDic(dict: ["Animal":"Lion", "Bird":"Sparrow"])
//prints Animal : Lion
Bird : Sparrow
This whole answer is in the context of spec compliance, not what any engine does at a particular moment or historically.
The actual question is very vague.
will the properties be in the same order that I added them
In what context?
The answer is: it depends on a number of factors. In general, no.
Here is where you can count on property key order for plain Objects
:
Object.getOwnPropertyNames()
, Reflect.ownKeys()
, Object.getOwnPropertySymbols(O)
In all cases these methods include non-enumerable property keys and order keys as specified by [[OwnPropertyKeys]]
(see below). They differ in the type of key values they include (String
and / or Symbol
). In this context String
includes integer values.
Object.getOwnPropertyNames(O)
Returns O
's own String
-keyed properties (property names).
Reflect.ownKeys(O)
Returns O
's own String
- and Symbol
-keyed properties.
Object.getOwnPropertySymbols(O)
Returns O
's own Symbol
-keyed properties.
[[OwnPropertyKeys]]
The order is essentially: integer-like Strings
in ascending order, non-integer-like Strings
in creation order, Symbols in creation order. Depending which function invokes this, some of these types may not be included.
The specific language is that keys are returned in the following order:
... each own property key
P
ofO
[the object being iterated] that is an integer index, in ascending numeric index order... each own property key
P
ofO
that is a String but is not an integer index, in property creation order... each own property key
P
ofO
that is a Symbol, in property creation order
Map
If you're interested in ordered maps you should consider using the Map
type introduced in ES2015 instead of plain Objects
.
getResource by example:
package szb.testGetResource;
public class TestGetResource {
private void testIt() {
System.out.println("test1: "+TestGetResource.class.getResource("test.css"));
System.out.println("test2: "+getClass().getResource("test.css"));
}
public static void main(String[] args) {
new TestGetResource().testIt();
}
}
output:
test1: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
test2: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
you can have a variable
DEBUG = 0
then you can use a conditional statement
ifeq ($(DEBUG),1)
else
endif
This worked perfectly for me, although fetching all branches could be a bit too much:
git init
git remote add origin https://github.com/Vitosh/VBA_personal.git
git fetch --all
git checkout develop
Initially I was just trying the method:
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
but after using this along with:
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
problem was solved. Sample Program-
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 30.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *sampleView = [[UIView alloc] init];
sampleView.frame = CGRectMake(SCREEN_WIDTH/2, 5, 60, 4);
sampleView.backgroundColor = [UIColor blackColor];
return sampleView;
}
and include UITableViewDelegate protocol.
@interface TestViewController : UIViewController <UITableViewDelegate>
you can use line.seperator
for appending new line in
Your error on the snippet of data you posted is a little cryptic, in that because there are no common values, the join operation fails because the values don't overlap it requires you to supply a suffix for the left and right hand side:
In [173]:
df_a.join(df_b, on='mukey', how='left', lsuffix='_left', rsuffix='_right')
Out[173]:
mukey_left DI PI mukey_right niccdcd
index
0 100000 35 14 NaN NaN
1 1000005 44 14 NaN NaN
2 1000006 44 14 NaN NaN
3 1000007 43 13 NaN NaN
4 1000008 43 13 NaN NaN
merge
works because it doesn't have this restriction:
In [176]:
df_a.merge(df_b, on='mukey', how='left')
Out[176]:
mukey DI PI niccdcd
0 100000 35 14 NaN
1 1000005 44 14 NaN
2 1000006 44 14 NaN
3 1000007 43 13 NaN
4 1000008 43 13 NaN
Just change the port to 8081
and following virtual host will work:
<VirtualHost *:8081>
ServerName comm-app.local
DocumentRoot "C:/xampp/htdocs/CommunicationApp/public"
SetEnv APPLICATION_ENV "development"
<Directory "C:/xampp/htdocs/CommunicationApp/public">
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
One way is to upload it to your own Maven repository manager (such as Nexus). It's good practice to have an own repository manager anyway.
Another nice way I've recently seen is to include the Maven Install Plugin in your build lifecycle: You declare in the POM to install the files to the local repository. It's a little but small overhead and no manual step involved.
http://maven.apache.org/plugins/maven-install-plugin/install-file-mojo.html
div.classList.add("foo");
div.classList.remove("foo");
More at https://developer.mozilla.org/en-US/docs/Web/API/element.classList
Simply, you can use FormCollection
like:
[HttpPost]
public ActionResult SubmitAction(FormCollection collection)
{
// Get Post Params Here
string var1 = collection["var1"];
}
You can also use a class, that is mapped with Form values, and asp.net mvc engine automagically fills it:
//Defined in another file
class MyForm
{
public string var1 { get; set; }
}
[HttpPost]
public ActionResult SubmitAction(MyForm form)
{
string var1 = form1.Var1;
}
I ended up doing the following and it works.
public static string Serialize(object obj)
{
using (MemoryStream memoryStream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(memoryStream, obj);
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
public static object Deserialize(string xml, Type toType)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
DataContractSerializer serializer = new DataContractSerializer(toType);
return serializer.ReadObject(reader);
}
}
It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.
@DanielChapman gives a good explanation of serialVersionUID, but no solution. the solution is this: run the serialver
program on all your old classes. put these serialVersionUID
values in your current versions of the classes. as long as the current classes are serial compatible with the old versions, you should be fine. (note for future code: you should always have a serialVersionUID
on all Serializable
classes)
if the new versions are not serial compatible, then you need to do some magic with a custom readObject
implementation (you would only need a custom writeObject
if you were trying to write new class data which would be compatible with old code). generally speaking adding or removing class fields does not make a class serial incompatible. changing the type of existing fields usually will.
Of course, even if the new class is serial compatible, you may still want a custom readObject
implementation. you may want this if you want to fill in any new fields which are missing from data saved from old versions of the class (e.g. you have a new List field which you want to initialize to an empty list when loading old class data).
If you have GNU find
, then there are a legion of relevant options. The only snag is that the interface to them is less than stellar:
-mmin n
(modification time in minutes)-mtime n
(modification time in days)-newer file
(modification time newer than modification time of file)-daystart
(adjust start time from current time to start of day)The hard part is determining the number of minutes since a time.
One option worth considering: use touch
to create a file with the required modification time stamp; then use find
with -newer
.
touch -t 200901031231.43 /tmp/wotsit
find . -newer /tmp/wotsit -print
rm -f /tmp/wotsit
This looks for files newer than 2009-01-03T12:31:43. Clearly, in a script, /tmp/wotsit
would be a name with the PID or other value to make it unique; and there'd be a trap
to ensure it gets removed even if the user interrupts, and so on and so forth.
Go to "app manager", then go to "all", then click on "Google Services Framework" and then "Clear Data". Reboot and it is done.
Checkbox only offer you 2 values (true, false). Nullable boolean has 3 values (true, false, null) so it's impossible to do it with a checkbox.
A good option is to use a drop down instead.
Model
public bool? myValue;
public List<SelectListItem> valueList;
Controller
model.valueList = new List<SelectListItem>();
model.valueList.Add(new SelectListItem() { Text = "", Value = "" });
model.valueList.Add(new SelectListItem() { Text = "Yes", Value = "true" });
model.valueList.Add(new SelectListItem() { Text = "No", Value = "false" });
View
@Html.DropDownListFor(m => m.myValue, valueList)
if you want to select column with specific name then just do
A=mtcars[,which(conames(mtcars)==cols[1])]
#and then
colnames(mtcars)[A]=cols[1]
you can run it in loop as well reverse way to add dynamic name eg if A is data frame and xyz is column to be named as x then I do like this
A$tmp=xyz
colnames(A)[colnames(A)=="tmp"]=x
again this can also be added in loop