Adding to the advice given in other answers (I have no rep to create replies)...
When combining -prune
with other expressions, there is a subtle difference in behavior depending on which other expressions are used.
@Laurence Gonsalves' example will find the "*.foo" files that aren't under ".snapshot" directories:-
find . -name .snapshot -prune -o -name '*.foo' -print
However, this slightly different short-hand will, perhaps inadvertently, also list the .snapshot
directory (and any nested .snapshot directories):-
find . -name .snapshot -prune -o -name '*.foo'
The reason is (according to the manpage on my system):-
If the given expression does not contain any of the primaries -exec, -ls, -ok, or -print, the given expression is effectively replaced by:
( given_expression ) -print
That is, the second example is the equivalent of entering the following, thereby modifying the grouping of terms:-
find . \( -name .snapshot -prune -o -name '*.foo' \) -print
This has at least been seen on Solaris 5.10. Having used various flavors of *nix for approx 10 years, I've only recently searched for a reason why this occurs.
$date = date('h:i:s A', strtotime($today . " +10 hours"));
anhdevit's suggestion in https://github.com/facebook/react-native/issues/24363#issuecomment-488547280 worked for me:
In your terminal, run:
defaults delete com.apple.dt.Xcode
Enable TextWrapping="Wrap"
and AcceptsReturn="True"
on your TextBox.
You might also wish to enable AcceptsTab
and SpellCheck.IsEnabled
too.
Copy the diff file to the root of your repository, and then do:
git apply yourcoworkers.diff
More information about the apply
command is available on its man page.
By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch
on the sender and then git am
on the receiver, because it also transfers the authorship info and the commit message.
If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3
option of apply
that tries to merge in the changes.
It also works with Unix pipe as follows:
git diff d892531 815a3b5 | git apply
First, make sure that the source page and the target page are both served through the file
URI scheme. You can't force an http
page to open a file
page (but it works the other way around).
Next, your script that calls window.open()
should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open()
won't work.
You can test this right here in this question page. Run these in Chrome's JavaScript console:
// Does nothing
window.open('http://google.com');
// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });
// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });
You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
</head>
<body>
<h5>Feel the presha</h5>
<h3>Come play my game, I'll test ya</h3>
<h1>Psycho- somatic- addict- insane!</h1>
</body>
</html>
Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.
With Java 8 you can do this without any third party library.
If you want to join a Collection of Strings you can use the new String.join() method:
List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"
If you have a Collection with another type than String you can use the Stream API with the joining Collector:
List<Person> list = Arrays.asList(
new Person("John", "Smith"),
new Person("Anna", "Martinez"),
new Person("Paul", "Watson ")
);
String joinedFirstNames = list.stream()
.map(Person::getFirstName)
.collect(Collectors.joining(", ")); // "John, Anna, Paul"
The StringJoiner
class may also be useful.
You can read files in raw/res using getResources().openRawResource(R.raw.myfilename)
.
BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt
or my_data.bin
will not be listed in R.
The existing answers solve most cases. However, I ran into a case where I needed the content of the grid-cell to be overflow: visible
. I solved it by absolutely positioning within a wrapper (not ideal, but the best I know), like this:
.month-grid {
display: grid;
grid-template: repeat(6, 1fr) / repeat(7, 1fr);
background: #fff;
grid-gap: 2px;
}
.day-item-wrapper {
position: relative;
}
.day-item {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
padding: 10px;
background: rgba(0,0,0,0.1);
}
This is the easiest one
You can define your modal behavior, defining data-keyboard and data-backdrop.
<div id="modal" class="modal hide fade in" data-keyboard="false" data-backdrop="static">
Variation on a theme. Handles single digit seconds a little differently
seconds2time(0) -> "0s"
seconds2time(59) -> "59s"
seconds2time(60) -> "1:00"
seconds2time(1000) -> "16:40"
seconds2time(4000) -> "1:06:40"
function seconds2time (seconds) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor((seconds - (hours * 3600)) / 60);
var seconds = seconds - (hours * 3600) - (minutes * 60);
var time = "";
if (hours != 0) {
time = hours+":";
}
if (minutes != 0 || time !== "") {
minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
time += minutes+":";
}
if (time === "") {
time = seconds+"s";
}
else {
time += (seconds < 10) ? "0"+seconds : String(seconds);
}
return time;
}
for n in range(6,0,-1):
print n
XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
xmlw.WriteStartDocument();
xmlw.WriteStartElement("examtimes");
xmlw.WriteStartElement("Starttime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Changetime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Endtime");
xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
xmlw.WriteEndElement();
xmlw.WriteEndElement();
xmlw.WriteEndDocument();
xmlw.Close();
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\WINDOWS\Temp\exm.xml");
XmlNode root = doc.DocumentElement["Starttime"];
root.FirstChild.InnerText = "First";
XmlNode root1 = doc.DocumentElement["Changetime"];
root1.FirstChild.InnerText = "Second";
doc.Save(@"C:\WINDOWS\Temp\exm.xml");
Try this. It's C# code.
Just to make a proper answer from the @Eddy Hernandez's comment and which is very correct since Alpine comes with ash not bash.
The question now referes to Starting a shell in the Docker Alpine container which implies using sh
or ash
or /bin/sh
or /bin/ash/
.
Based on the OP's question:
docker run image sh -c "cd /path/to/somewhere && python a.py"
For a different command I decided to change the network from public to work.
After trying to use the psexec command again it worked again.
So to get psexec to work try to change your network type from public to work or home.
Maybe these could be helpful?
What is the equivalent of memset in C#?
http://techmikael.blogspot.com/2009/12/filling-array-with-default-value.html
As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.
A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges
response. Chrome always sends a Range: bytes=0-
with its first GET request for a video, so it's something you can't dismiss.
Whenever a client includes Range:
in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:
Range: bytes=3744-
So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.
You can handle the type of 'range' you specified in your question in two ways:
First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:
Request:
GET /BigBuckBunny_320x180.mp4
Range: bytes=100-
Response:
206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927
Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:
Request:
GET /BigBuckBunny_320x180.mp4
Range: bytes=100-
Response:
206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*
Tips:
You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:
Request: Range: bytes=500-1000
Response: Content-Range: bytes 500-1000/123456
Remember that the range is zero-indexed, so Range: bytes=0-999
is actually requesting 1000 bytes, not 999, so respond with something like:
Content-Length: 1000
Content-Range: bytes 0-999/123456
Or:
Content-Length: 1000
Content-Range: bytes 0-999/*
But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:
X-Content-Duration: 63.23
This must be a floating point. Unlike Content-Length
, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:
X-Content-Duration: 7200.00
With some media types, such as webm, you must also include the content-type, such as:
Content-Type: video/webm
All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.
X-Content-Duration
is being phased out in favor of Content-Duration
, so I'd include that too. A basic, response to a "0-" request would include at least the following:
HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53
One more point: Chrome always starts its first video request with the following:
Range: bytes=0-
Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.
If you pass 0 as the port number to the constructor of ServerSocket, It will allocate a port for you.
Set: const [state, setState] = useState(1);
Toggle: setState(state*-1);
Use: state > 0 ? 'on' : 'off';
Your requirements are all over the place, but this is the solution to my understanding of them:
To group by Reference property:
var refGroupQuery = (from m in context.Measurements
group m by m.Reference into refGroup
select refGroup);
Now you say you want to limit results by "most recent numOfEntries" - I take this to mean you want to limit the returned Measurements... in that case:
var limitedQuery = from g in refGroupQuery
select new
{
Reference = g.Key,
RecentMeasurements = g.OrderByDescending( p => p.CreationTime ).Take( numOfEntries )
}
To order groups by first Measurement creation time (note you should order the measurements; if you want the earliest CreationTime value, substitue "g.SomeProperty" with "g.CreationTime"):
var refGroupsOrderedByFirstCreationTimeQuery = limitedQuery.OrderBy( lq => lq.RecentMeasurements.OrderBy( g => g.SomeProperty ).First().CreationTime );
To order groups by average CreationTime, use the Ticks property of the DateTime struct:
var refGroupsOrderedByAvgCreationTimeQuery = limitedQuery.OrderBy( lq => lq.RecentMeasurements.Average( g => g.CreationTime.Ticks ) );
Add it to your project/application/config/config.php file, and it will work on all over your site.
date_default_timezone_set('Asia/Kolkata');
There's also JustCode from Telerik.
Or perhaps you could use this class:
http://developer.android.com/reference/java/net/URLEncoder.html
Which is present in Android since API level 1.
Annoyingly however, it treats spaces specially (replacing them with + instead of %20). To get round this we simply use this fragment:
URLEncoder.encode(value, "UTF-8").replace("+", "%20");
In case if you don't have a fixed format for the address as mentioned above, I would use regex expression just to eliminate the symbols which are not used in the address (like specialized sybmols - &(%#$^). Result would be:
[A-Za-z0-9'\.\-\s\,]
You can use sed
:
sed -i 's/abc/XYZ/gi' /tmp/file.txt
You can use find
and sed
if you don't know your filename:
find ./ -type f -exec sed -i 's/abc/XYZ/gi' {} \;
Find and replace in all Python files:
find ./ -iname "*.py" -type f -exec sed -i 's/abc/XYZ/gi' {} \;
You can extract the scroll position using jQuery's .scrollTop()
method
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
// Do something
});
vim +21490go script.py
From the command line will open the file and take you to position 21490
in the buffer.
Triggering it from the command line like this allows you to automate a script to parse the exception message and open the file to the problem position.
Excerpt from man vim
:
+{command} -c {command}
{command}
will be executed after the first file has been read.{command}
is interpreted as an Ex command. If the{command}
contains spaces it must be enclosed in double quotes (this depends on the shell that is used).
I have recently discovered that minidlna doesn't update the database if the media file is a hardlink. If you want these files to show up in the database, a full rescan is necessary.
ex: If you have a file /home/movies/foo.mkv and a hardlink in /home/minidlna/video/foo.mkv, where '/home/minidlna' is your minidlna share, you will have to do a rescan till that file appears in the db (and subsequently your dlna client).
I'm still trying to find a way around this. If anyone has any input, it's most welcome.
A solution using java.util.regex.Pattern / java.util.regex.Matcher
String test = "foo bar baz ";
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(test);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
If you don't want to go back to all the activities on your application, you can use
android:launchMode="singleTask"
Learn more here: http://developer.android.com/guide/topics/manifest/activity-element.html
Use .val()
instead of .innerHTML
for getting value of selected option
Use .text()
for getting text of selected option
Thanks for correcting :)
You don't have to load the whole product. Magentos collections are very powerful and smart.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('entity_id', $product->getId());
$collection->addAttributeToSelect('manufacturer');
$product = $collection->getFirstItem();
$manufacturer = $product->getAttributeText('manufacturer');
At the moment you call getFirstItem() the query will be executed and the result product is very minimal:
[status] => 1
[entity_id] => 38901
[type_id] => configurable
[attribute_set_id] => 9
[manufacturer] => 492
[manufacturer_value] => JETTE
[is_salable] => 1
[stock_item (Varien_Object)] => Array
(
[is_in_stock] => 1
)
You can return an object of a Class in Java.
If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.
If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.
I came across the same problem, but I wasn't enamoured by any of the solutions I found here. So, I wrote one that iterates over the characters of the string using a matcher to find and replace the escape sequences. This solution assumes properly formatted input. That is, it happily skips over nonsensical escapes, and it decodes Unicode escapes for line feed and carriage return (which otherwise cannot appear in a character literal or a string literal, due to the definition of such literals and the order of translation phases for Java source). Apologies, the code is a bit packed for brevity.
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Decoder {
// The encoded character of each character escape.
// This array functions as the keys of a sorted map, from encoded characters to decoded characters.
static final char[] ENCODED_ESCAPES = { '\"', '\'', '\\', 'b', 'f', 'n', 'r', 't' };
// The decoded character of each character escape.
// This array functions as the values of a sorted map, from encoded characters to decoded characters.
static final char[] DECODED_ESCAPES = { '\"', '\'', '\\', '\b', '\f', '\n', '\r', '\t' };
// A pattern that matches an escape.
// What follows the escape indicator is captured by group 1=character 2=octal 3=Unicode.
static final Pattern PATTERN = Pattern.compile("\\\\(?:(b|t|n|f|r|\\\"|\\\'|\\\\)|((?:[0-3]?[0-7])?[0-7])|u+(\\p{XDigit}{4}))");
public static CharSequence decodeString(CharSequence encodedString) {
Matcher matcher = PATTERN.matcher(encodedString);
StringBuffer decodedString = new StringBuffer();
// Find each escape of the encoded string in succession.
while (matcher.find()) {
char ch;
if (matcher.start(1) >= 0) {
// Decode a character escape.
ch = DECODED_ESCAPES[Arrays.binarySearch(ENCODED_ESCAPES, matcher.group(1).charAt(0))];
} else if (matcher.start(2) >= 0) {
// Decode an octal escape.
ch = (char)(Integer.parseInt(matcher.group(2), 8));
} else /* if (matcher.start(3) >= 0) */ {
// Decode a Unicode escape.
ch = (char)(Integer.parseInt(matcher.group(3), 16));
}
// Replace the escape with the decoded character.
matcher.appendReplacement(decodedString, Matcher.quoteReplacement(String.valueOf(ch)));
}
// Append the remainder of the encoded string to the decoded string.
// The remainder is the longest suffix of the encoded string such that the suffix contains no escapes.
matcher.appendTail(decodedString);
return decodedString;
}
public static void main(String... args) {
System.out.println(decodeString(args[0]));
}
}
I should note that Apache Commons Lang3 doesn't seem to suffer the weaknesses indicated in the accepted solution. That is, StringEscapeUtils
seems to handle octal escapes and multiple u
characters of Unicode escapes. That means unless you have some burning reason to avoid Apache Commons, you should probably use it rather than my solution (or any other solution here).
Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.
You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\n
indicating one line.
So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n
, perform your operation on the line and proceed to read the next line into the buffer.
Note you will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...
EDIT
import serial
ser = serial.Serial(
port='COM5',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
#this will store the line
line = []
while True:
for c in ser.read():
line.append(c)
if c == '\n':
print("Line: " + ''.join(line))
line = []
break
ser.close()
Add tomcat in Eclipse
In Eclipse, as tomcat server, double click "Tomcat v7.0 Server at Localhost", Change the properties as shown in time out settings 45 to whatever sec you like
<asp:GridView ID="GridView1" runat="server">
<HeaderStyle Width="10%" />
<RowStyle Width="10%" />
<FooterStyle Width="10%" />
<Columns>
<asp:BoundField HeaderText="Name" DataField="LastName"
HeaderStyle-Width="10%" ItemStyle-Width="10%"
FooterStyle-Width="10%" />
</Columns>
</asp:GridView>
your $(this).val() has no scope in your ajax call, because its not in change event function scope
May be you implemented that ajax call in your change event itself first, in that case it works fine. but when u created a function and calling that funciton in change event, scope for $(this).val() is not valid.
simply get the value using id selector instead of
$(#CourseSelect).val()
whole code should be like this:
$(document).ready(function ()
{
$("#CourseSelect").change(loadTeachers);
loadTeachers();
});
function loadTeachers()
{
$.ajax({ type:'GET', url:'/Manage/getTeachers/' + $(#CourseSelect).val(), dataType:'json', cache:false,
success:function(data)
{
$('#TeacherSelect').get(0).options.length = 0;
$.each(data, function(i, teacher)
{
var option = $('<option />');
option.val(teacher.employeeId);
option.text(teacher.name);
$('#TeacherSelect').append(option);
});
}, error:function(){ alert("Error while getting results"); }
});
}
download InputSimulator from nuget package.
then write this:
var simu = new InputSimulator();
simu.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_E);
in my case to create new vertial desktop, 3 keys needed and code like this(windows key + ctrl + D):
simu.Keyboard.ModifiedKeyStroke(new[] { VirtualKeyCode.LWIN, VirtualKeyCode.CONTROL }, VirtualKeyCode.VK_D);
You will not be able to retrieve a plain text password from wordpress.
Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.
See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password
This is what worked for me:
import json
import requests
url = 'http://xxx.com'
payload = {'param': '1', 'data': '2', 'field': '4'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data = json.dumps(payload), headers = headers)
I have seen most of the people saying explicit parent to child casting is not possible, that actually is not true. Let's take a revised start and try proving it by examples.
As we know in .net all castings have two broad categories.
Reference type has further three main situational cases in which any scenario can lie.
Case 1. Child to any direct or indirect parent
Employee e = new Employee();
Person p = (Person)e; //Allowed
Case 2. Parent variable holding parent object (Not allowed)
Person p = new Person(); // p is true Person object
Employee e = (Employee)p; //Runtime err : InvalidCastException <-------- Yours issue
Case 3. Parent variable holding child object (Always Successful)
Note: Because objects has polymorphic nature, it is possible for a variable of a parent class type to hold a child type.
Person p = new Employee(); // p actually is Employee
Employee e = (Employee)p; // Casting allowed
Conclusion : After reading above all, hope it will make sense now like how parent to child conversion is possible(Case 3).
Answer To The Question :
Your answer is in case 2.Where you can see such casting is not allowed by OOP and you are trying to violate one of OOP's basic rule.So always choose safe path.
Further more, to avoid such exceptional situations .net has recommended using is/as operators those will help you to take informed decisions and provide safe casting.
I think things (location) have changed little bit. For: Android Studio 1.2.1.1 Build @AI-141.1903250 - built on May 5, 2015
Franco Rondinis answer should be
To track memory allocation of objects:
I used to do like,
if the activity is not in the foreground
getIntent()
will return null. :=P
Using String#gsub
with regular expression:
"((String1))".gsub(/^\(+|\)+$/, '')
# => "String1"
"(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
# => " parentheses "
This will remove surrounding parentheses only.
"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
# => " This (is) string "
$query_string = "";
if ($_POST) {
$kv = array();
foreach ($_POST as $key => $value) {
$kv[] = stripslashes($key) . "=" . stripslashes($value);
}
$query_string = join("&", $kv);
}
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$url = 'https://www.abcd.com/servlet/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$result = curl_exec($ch);
curl_close($ch);
Well, ["Title", "Ramones"]
is an array of strings. But [{"01":"Title", "02", "Ramones"}]
is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue;
in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[]
, so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({})
, or myArray.push({""})
.
This will push an empty object into myArray
which will have an index number 0
, so your exact object is now myArray[0]
Then push property
and value
into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
one kind of join a query in mongoDB, is ask at one collection for id that match , put ids in a list (idlist) , and do find using on other (or same) collection with $in : idlist
u = db.friends.find({"friends": something }).toArray()
idlist= []
u.forEach(function(myDoc) { idlist.push(myDoc.id ); } )
db.family.find({"id": {$in : idlist} } )
You have a selector ul
on line 252
which is setting list-style: square outside none
(a square bullet). You'll have to change it to list-style: none
or just remove the line.
If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:
ul#groups-list.items-list { list-style: none }
There is no platform-neutral way of doing this. In the 1.6 release of Java, a "Desktop" class was added the allows portable ways of browsing, editing, mailing, opening, and printing URI's. It is possible this class may someday be extended to support processes, but I doubt it.
If you are only curious in Java processes, you can use the java.lang.management api for getting thread/memory information on the JVM.
UPDATE for Django >= 1.7
Per Django 2.1 documentation: Serving files uploaded by a user during development
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
You no longer need if settings.DEBUG
as Django will handle ensuring this is only used in Debug mode.
ORIGINAL answer for Django <= 1.6
Try putting this into your urls.py
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
With this you can serve the static media from Django when DEBUG = True
(when you run on local computer) but you can let your web server configuration serve static media when you go to production and DEBUG = False
Some colleague of mine had good experience with Learn You a Haskell for Great Good!.
Tutorial aimed at people who have experience in imperative programming languages but haven't programmed in a functional language before.
And check the answers here too
chmod +x gradlew
Just run the above comment. that's all enjoy your coding...
to me, i just do this :
rm -rf ~/.ssh/known_hosts
then :
i just ssh to the target host and all will be okay. This only if you dont know, what permission and the default owner of "known_hosts" file.
Between dates Including end points can be written as
public static boolean isDateInBetweenIncludingEndPoints(final Date min, final Date max, final Date date){
return !(date.before(min) || date.after(max));
}
The angular2 way is to use listen
or listenGlobal
from Renderer
For example, if you want to add a click event to a Component, you have to use Renderer and ElementRef (this gives you as well the option to use ViewChild, or anything that retrieves the nativeElement
)
constructor(elementRef: ElementRef, renderer: Renderer) {
// Listen to click events in the component
renderer.listen(elementRef.nativeElement, 'click', (event) => {
// Do something with 'event'
})
);
You can use listenGlobal
that will give you access to document
, body
, etc.
renderer.listenGlobal('document', 'click', (event) => {
// Do something with 'event'
});
Note that since beta.2 both listen
and listenGlobal
return a function to remove the listener (see breaking changes section from changelog for beta.2). This is to avoid memory leaks in big applications (see #6686).
So to remove the listener we added dynamically we must assign listen
or listenGlobal
to a variable that will hold the function returned, and then we execute it.
// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;
// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;
constructor(elementRef: ElementRef, renderer: Renderer) {
// We cache the function "listen" returns
this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
// Do something with 'event'
});
// We cache the function "listenGlobal" returns
this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
// Do something with 'event'
});
}
ngOnDestroy() {
// We execute both functions to remove the respectives listeners
// Removes "listen" listener
this.listenFunc();
// Removs "listenGlobal" listener
this.globalListenFunc();
}
Here's a plnkr with an example working. The example contains the usage of listen
and listenGlobal
.
25/02/2017: Renderer
has been deprecated, now we should use (see line below). See the commit.RendererV2
10/03/2017: RendererV2
was renamed to Renderer2
. See the breaking changes.
RendererV2
has no more listenGlobal
function for global events (document, body, window). It only has a listen
function which achieves both functionalities.
For reference, I'm copy & pasting the source code of the DOM Renderer implementation since it may change (yes, it's angular!).
listen(target: 'window'|'document'|'body'|any, event: string, callback: (event: any) => boolean):
() => void {
if (typeof target === 'string') {
return <() => void>this.eventManager.addGlobalEventListener(
target, event, decoratePreventDefault(callback));
}
return <() => void>this.eventManager.addEventListener(
target, event, decoratePreventDefault(callback)) as() => void;
}
As you can see, now it verifies if we're passing a string (document, body or window), in which case it will use an internal addGlobalEventListener
function. In any other case, when we pass an element (nativeElement) it will use a simple addEventListener
To remove the listener it's the same as it was with Renderer
in angular 2.x. listen
returns a function, then call that function.
// Add listeners
let global = this.renderer.listen('document', 'click', (evt) => {
console.log('Clicking the document', evt);
})
let simple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
console.log('Clicking the button', evt);
});
// Remove listeners
global();
simple();
plnkr with Angular 4.0.0-rc.1 using RendererV2
plnkr with Angular 4.0.0-rc.3 using Renderer2
I tried almost all the possible suggestions mention here but for me problem got solved after changing "Access for less secure apps" to ENABLE in my Google account security settings tab. Hope this might useful for others !
HTML
<div id="container">
<div id="element">
some text
</div>
</div>
CSS
#container {
width: 50%; /* desired width */
}
#element {
height: 0;
padding-bottom: 100%;
}
The best way is surely just to check whether there are two program files directories, 'Program Files'and 'Program Files (x86)' The advantage of this method is you can do it when the o/s is not running, for instance if the machine has failed to start and you wish to reinstall the operating system
Below we use a boolean "first" argument to switch between first match and all matches (a default which is equivalent to "find . -name file"):
import os
def find(root, file, first=False):
for d, subD, f in os.walk(root):
if file in f:
print("{0} : {1}".format(file, d))
if first == True:
break
In my case, I was moving the component UserComponent
from one module appModule
to anotherdashboardModule
and forgot to remove the route definition from the routing of the previous moduleappModule
in AppRoutingModule file.
const routes = [
{ path: 'user', component: UserComponent, canActivate: [AuthGuard]},...]
After i removed the route definition it worked fine.
To call one constructor from another you need to use this()
and you need to put it first. In your case the default constructor needs to call the one which takes an argument, not the other ways around.
Here's my attempt with Javascript and CSS3 animation So the HTML:
<div id="handle">Fade</div>
<div id="slideSource">Whatever you want images or text here</div>
The CSS3 with transitions:
div#slideSource {
opacity:1;
-webkit-transition: opacity 3s;
-moz-transition: opacity 3s;
transition: opacity 3s;
}
div#slideSource.fade {
opacity:0;
}
The Javascript part. Check if the className exists, if it does then add the class and transitions.
document.getElementById('handle').onclick = function(){
if(slideSource.className){
document.getElementById('slideSource').className = '';
} else {
document.getElementById('slideSource').className = 'fade';
}
}
Just click and it will fade in and out. I would recommend using JQuery as Itai Sagi mentioned. I left out Opera and MS, so I would recommend using prefixr to add that in the css. This is my first time posting on stackoverflow but it should work fine.
this should do:
//Main Class
public class SomeClass {
//Sub-Class
public static class AnotherClass {
public enum MyEnum {
VALUE_A, VALUE_B
}
public MyEnum myEnum;
}
public void someMethod() {
AnotherClass.MyEnum enumExample = AnotherClass.MyEnum.VALUE_A; //...
switch (enumExample) {
case VALUE_A: { //<-- error on this line
//..
break;
}
}
}
}
First, it would be simpler if the onclick handler was set this way:
<a id="someLinkId"href="#">Select</a>
<script type="text/javascript">
document.getElementById("someLinkId").onClick =
function() {
SelectSurveyItem('<%itemid%>', '<%itemname%>'); return false;
};
</script>
Then itemid and itemname need to be escaped for JavaScript (that is, "
becomes \"
, etc.).
If you are using Java on the server side, you might take a look at the class StringEscapeUtils from jakarta's common-lang. Otherwise, it should not take too long to write your own 'escapeJavascript' method.
you can update all of the dependencies to their latest version by
npm update
Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class. So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.
As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a "struct" in C, consider making it static.
an additional note:
if you have already added a remote ($git remote add origin ... ) and need to change that particular remote then do a remote remove first ($ git remote rm origin), before re-adding the new and improved repo URL (where "origin" was the name for the remote repo).
so to use the original example :
$ git remote add origin https://github.com/WEMP/project-slideshow.git
$ git remote rm origin
$ git remote add origin https://[email protected]/WEMP/project-slideshow.git
It depends on the class you are using.
Dictionary<(Of <(TKey, TValue>)>) Class For Example Support This
The Dictionary<(Of <(TKey, TValue>)>) generic class provides a mapping from a set of keys to a set of values.
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<(Of <(TKey, TValue>)>) structure representing a value and its key. The order in which the items are returned is undefined.
foreach (KeyValuePair kvp in myDictionary) {...}
You can use PreferredSize
and flexibleSpace
for it:
appBar: PreferredSize(
preferredSize: Size.fromHeight(100.0),
child: AppBar(
automaticallyImplyLeading: false, // hides leading widget
flexibleSpace: SomeWidget(),
)
),
This way you can keep the elevation
of AppBar
for keeping its shadow visible and have custom height, which is what I was just looking for. You do have to set the spacing in SomeWidget
, though.
Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:
private void Calculate(int i)
{
double pow = Math.Pow(i, i);
}
public void DoWork(IProgress<int> progress)
{
// This method is executed in the context of
// another thread (different than the main UI thread),
// so use only thread-safe code
for (int j = 0; j < 100000; j++)
{
Calculate(j);
// Use progress to notify UI thread that progress has
// changed
if (progress != null)
progress.Report((j + 1) * 100 / 100000);
}
}
private async void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = 100;
progressBar1.Step = 1;
var progress = new Progress<int>(v =>
{
// This lambda is executed in context of UI thread,
// so it can safely update form controls
progressBar1.Value = v;
});
// Run operation in another thread
await Task.Run(() => DoWork(progress));
// TODO: Do something after all calculations
}
Tasks are currently the preferred way to implement what BackgroundWorker
does.
Tasks and
Progress
are explained in more detail here:
If you happens to change the columns and stumbled on
'Doctrine\DBAL\Driver\PDOMySql\Driver' not found
then just install
composer require doctrine/dbal
Here '~' refers to the root directory ,where Home is controller and Download_Excel_File is actionmethod
<a href="~/Home/Download_Excel_File" />
install json-loader
:
npm i json-loader --save
create data
folder in src
:
mkdir data
put your file(s) there
load your file
var data = require('json!../data/yourfile.json');
There are two ways to achieve this:
final PageRequest page1 = new PageRequest(
0, 20, Direction.ASC, "lastName", "salary"
);
final PageRequest page2 = new PageRequest(
0, 20, new Sort(
new Order(Direction.ASC, "lastName"),
new Order(Direction.DESC, "salary")
)
);
dao.findAll(page1);
As you can see the second form is more flexible as it allows to define different direction for every property (lastName ASC, salary DESC
).
Why not use a filter?
var thevalue = 'foo';
var exists = $('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length;
Loose comparisons work because exists > 0 is true, exists == 0 is false, so you can just use
if(exists){
// it is in the dropdown
}
Or combine it:
if($('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length){
// found
}
Or where each select dropdown has the select-boxes class this will give you a jquery object of the select(s) which contain the value:
var matched = $('.select-boxes option').filter(function(){ return $(this).val() == thevalue; }).parent();
This comes up high on Google, so I'd like to add some contextual information about the original question (emphasis mine):
Why does Node.js' fs.readFile() return a buffer instead of string?
Even if you as the programmer know it: Node has no idea what's in the file you're trying to read. It could be a text file, but it could just as well be a ZIP archive or a JPG image — Node doesn't know.
Even if Node knew it were to read a text file, it still would have no idea which character encoding is used (i.e. how the bytes in the file map to human-readable characters), because the character encoding itself is not stored in the file.
There are ways to guess the character encoding of text files with more or less confidence (that's what text editors do when opening a file), but you usually don't want your code to rely on guesses without your explicit instruction.
So, because it does not and can not know all these details, Node just reads the file byte for byte, without assuming anything about its contents.
And that's what the returned buffer is: an unopinionated container for raw binary content. How this content should be interpreted is up to you as the developer.
Java's String.format works like so:
if the final destination for this data is a stream (e.g. rendering a webpage or writing to a file), you can assemble the format chunks directly into your stream:
new PrintStream(outputStream, autoFlush, encoding).format("hello {0}", "world");
I speculate that the optimizer will optimize away the format string processing. If so, you're left with equivalent amortized performance to manually unrolling your String.format into a StringBuilder.
If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:
var myID = "xxx";
var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";
<script>
function initMap() {
//echo hiii;
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(8.5241, 76.9366),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('package');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
// var name = markerElem.getAttribute('name');
// var address = markerElem.getAttribute('address');
// var type = markerElem.getAttribute('type');
// var latitude = results[0].geometry.location.lat();
// var longitude = results[0].geometry.location.lng();
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('latitude')),
parseFloat(markerElem.getAttribute('longitude'))
);
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var package = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
package.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, package);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
I've added to /etc/sysconfig/jenkins (CentOS):
# Options to pass to java when running Jenkins.
#
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true -Xmx1024m -XX:MaxPermSize=512m"
For ubuntu the same config should be located in /etc/default
SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result
'And so on and so forth.
"The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios." Source
Try
webView.setBackgroundColor(0);
I had the same problem, this is the solution i came up with, which is much easier!
Make a little 1px x 1px transparent image and save it as a .png file.
In the CSS for your DIV, use this code:
background:transparent url('/images/trans-bg.png') repeat center top;
Remember to change the file path to your transparent image.
I think this solution works in all browsers, maybe except for IE 6, but I haven't tested.
I'm using rather specified charset (ISO-8859-2) because not every mail system (for example: http://10minutemail.com) can read UTF-8 mails. If you need this:
function utf8_to_latin2($str)
{
return iconv ( 'utf-8', 'ISO-8859-2' , $str );
}
function my_mail($to,$s,$text,$form, $reply)
{
mail($to,utf8_to_latin2($s),utf8_to_latin2($text),
"From: $form\r\n".
"Reply-To: $reply\r\n".
"X-Mailer: PHP/" . phpversion());
}
I have made another mailer function, because apple device could not read well the previous version.
function utf8mail($to,$s,$body,$from_name="x",$from_a = "[email protected]", $reply="[email protected]")
{
$s= "=?utf-8?b?".base64_encode($s)."?=";
$headers = "MIME-Version: 1.0\r\n";
$headers.= "From: =?utf-8?b?".base64_encode($from_name)."?= <".$from_a.">\r\n";
$headers.= "Content-Type: text/plain;charset=utf-8\r\n";
$headers.= "Reply-To: $reply\r\n";
$headers.= "X-Mailer: PHP/" . phpversion();
mail($to, $s, $body, $headers);
}
image_tag("/icons/icon.gif", height: '32', width: '32')
I need to set height: '50px', width: '50px' to image tag and this code works from first try note I tried all the above code but no luck so this one works and here is my code from my _nav.html.erb:
<%= image_tag("#{current_user.image}", height: '50px', width: '50px') %>
Make sure your git username and password is correct. In my case, it gave error when the username and password(especially the GIT TOKEN) was not correct.
The reason for this error is very simple. Your AJAX is trying to call over HTTP whereas your server is running over HTTPS, so your server is denying calling your AJAX. This can be fixed by adding the following line inside the head tag of your main HTML file:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
As simple as clone then delete the .git folder:
git clone url_of_your_repo path_to_export && rm -rf path_to_export/.git
well you are returning an array of items from the database. so you need something like this.
$dave= mysql_query("SELECT order_date, no_of_items, shipping_charge,
SUM(total_order_amount) as test FROM `orders`
WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)")
or die(mysql_error());
while ($row = mysql_fetch_assoc($dave)) {
echo $row['order_date'];
echo $row['no_of_items'];
echo $row['shipping_charge'];
echo $row['test '];
}
Question: Is there a simple way to do this in the current release of Python?
Answer: There is no simple (direct) way to do this in the current release of Python.
Reference: Please refer to docs.python.org/2/library/datetime.html, section 8.1.2. timedelta Objects. As we may understand from that, we cannot increment month directly since it is not a uniform time unit.
Plus: If you want first day -> first day and last day -> last day mapping you should handle that separately for different months.
This event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. At this stage you could programmatically optimize loading of images and css based on user device or bandwidth speed.
Executes after DOM is loaded (before img and css):
document.addEventListener("DOMContentLoaded", function(){
//....
});
Note: Synchronous JavaScript pauses parsing of the DOM. If you want the DOM to get parsed as fast as possible after the user requested the page, you could turn your JavaScript asynchronous and optimize loading of stylesheets
A very different event, load, should only be used to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
Exectues after everything is loaded and parsed:
window.addEventListener("load", function(){
// ....
});
MDN Resources:
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded https://developer.mozilla.org/en-US/docs/Web/Events/load
MDN list of all events:
int arr[5][4];
For the row subscript(4 raise to 2, include cmath to use pow):
sizeof(arr1)/pow(4,2)
Column subscript:
sizeof(*arr1)/4
4 means 4 bytes, size of int.
Fixed by adding crossorigin to the script tag.
From: https://code.jquery.com/
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org
If you use any full screen window (having its WindowState = WindowState.Maximized, WindowStyle = WindowStyle.None
), you can wrap its contents in System.Windows.Controls.Canvas
like this:
<Canvas Name="MyCanvas" Width="auto" Height="auto">
...
</Canvas>
Then you can use MyCanvas.ActualWidth
and MyCanvas.ActualHeight
to get the resolution of the current screen, with DPI settings taken into account and in device independent units.
It doesn't add any margins as the maximized window itself does.
(Canvas accepts UIElement
s as children, so you should be able to use it with any content.)
Do you mean unique
:
R> x = c(1,1,2,3,4,4,4)
R> x
[1] 1 1 2 3 4 4 4
R> unique(x)
[1] 1 2 3 4
TCP/IP is a stream-based protocol, not a message-based protocol. There's no guarantee that every send()
call by one peer results in a single recv()
call by the other peer receiving the exact data sent—it might receive the data piece-meal, split across multiple recv()
calls, due to packet fragmentation.
You need to define your own message-based protocol on top of TCP in order to differentiate message boundaries. Then, to read a message, you continue to call recv()
until you've read an entire message or an error occurs.
One simple way of sending a message is to prefix each message with its length. Then to read a message, you first read the length, then you read that many bytes. Here's how you might do that:
def send_msg(sock, msg):
# Prefix each message with a 4-byte length (network byte order)
msg = struct.pack('>I', len(msg)) + msg
sock.sendall(msg)
def recv_msg(sock):
# Read message length and unpack it into an integer
raw_msglen = recvall(sock, 4)
if not raw_msglen:
return None
msglen = struct.unpack('>I', raw_msglen)[0]
# Read the message data
return recvall(sock, msglen)
def recvall(sock, n):
# Helper function to recv n bytes or return None if EOF is hit
data = bytearray()
while len(data) < n:
packet = sock.recv(n - len(data))
if not packet:
return None
data.extend(packet)
return data
Then you can use the send_msg
and recv_msg
functions to send and receive whole messages, and they won't have any problems with packets being split or coalesced on the network level.
input()
by default takes the input in form of strings.
if (0<= vote <=24):
vote takes a string input (suppose 4
,5
,etc) and becomes uncomparable.
The correct way is: vote = int(input("Enter your message")
will convert the input to integer (4
to 4 or 5
to 5 depending on the input)
Update: December 2020 - I have updated the answer because previous one was not relevant.
Follow below steps to update your node version.
1. Install nvm For this run below command in your terminal
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
2. Install specific node version using nvm
For this run
Replace 12.14.1
with your node version
nvm install 12.14.1
Note: If you are getting error of NVM not recognised then run below command and then run above again
source ~/.nvm/nvm.sh
3. Make the installed version default
Note: Replace 12.14.1 with your installed version.
nvm alias default 12.14.1
4. Check node version
node -v
And that's it. Cheers!
Try this solution from http://social.technet.microsoft.com/Forums/en/w7itprosecurity/thread/e1ef04fa-6aea-47fe-9392-45929239bd68
Microsoft Support found the problem for us. Our domain accounts were locking when a Windows 7 computer was started. The Windows 7 computer had a hidden old password from that domain account. There are passwords that can be stored in the SYSTEM context that can't be seen in the normal Credential Manager view.
Download
PsExec.exe
from http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx and copy it toC:\Windows\System32
.From a command prompt run:
psexec -i -s -d cmd.exe
From the new DOS window run:
rundll32 keymgr.dll,KRShowKeyMgr
Remove any items that appear in the list of Stored User Names and Passwords. Restart the computer.
Don't put the DB::insert() inside of the Schema::create(), because the create method has to finish making the table before you can insert stuff. Try this instead:
public function up()
{
// Create the table
Schema::create('users', function($table){
$table->increments('id');
$table->string('email', 255);
$table->string('password', 64);
$table->boolean('verified');
$table->string('token', 255);
$table->timestamps();
});
// Insert some stuff
DB::table('users')->insert(
array(
'email' => '[email protected]',
'verified' => true
)
);
}
In format function your can use timestamp_format function. Example, if the format is YYYYMMDD you can do it :
select TIMESTAMP_FORMAT(yourcolumnchar, 'YYYYMMDD') as YouTimeStamp
from yourtable
you can then adapt then format with elements format foundable here
Do not use list as variable name. You can take a look at the following code too:
clist = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847', 'element5']
clist = [x[:x.index('\t')] if '\t' in x else x for x in clist]
Or in-place editing:
for i,x in enumerate(clist):
if '\t' in x:
clist[i] = x[:x.index('\t')]
A correct answer has already been supplied, but for you to learn how to help yourself I thought I'd throw in something helpful in a different way; if you can sum up what you're trying to achieve in one word, there's a mighty fine help feature on Linux.
man -k <your search term>
What that does is to list all commands that have your search term in the short description. There's usually a pretty good chance that you will find what you're after. ;)
That output can sometimes be somewhat overwhelming, and I'd recommend narrowing it down to the executables, rather than all available man-pages, like so:
man -k find | egrep '\(1\)'
or, if you also want to look for commands that require higher privilege levels, like this:
man -k find | egrep '\([18]\)'
Here's a solution, too:
int main()
{
QUuid uuid;
while ( (uuid = QUuid::createUuid()) != QUuid::createUuid() ) { }
std::cout << "Aha! I've found one! " << qPrintable( uuid.toString() ) << std::endl;
}
Note: requires Qt, but I guarantee that if you let it run long enough, it might find one.
(Note note: actually, now that I'm looking at it, there may be something about the generation algorithm that prevents two subsequently generated uuids that collide--but I kinda doubt it).
Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.
When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.
Words in italics are system calls.
Ref
while(node.firstChild) {
node.removeChild(node.firstChild);
}
Actually you are right: it runs another instance of make. A possible solution would be:
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : clean clearscr all
clearscr:
clear
By calling make fresh
you get first the clean
target, then the clearscreen
which runs clear
and finally all
which does the job.
EDIT Aug 4
What happens in the case of parallel builds with make’s -j
option?
There's a way of fixing the order. From the make manual, section 4.2:
Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites
The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).
Hence the makefile becomes
.PHONY : clearscr fresh clean all
all :
compile executable
clean :
rm -f *.o $(EXEC)
fresh : | clean clearscr all
clearscr:
clear
EDIT Dec 5
It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.
log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
install:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
command1 # this line will be a subshell
command2 # this line will be another subshell
@command3 # Use `@` to hide the command line
$(call log_error, "It works, yey!")
uninstall:
@[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
....
$(call log_error, "Nuked!")
To check for an empty QueryString you should use Request.QueryString.HasKeys
property.
To check if the key is present: Request.QueryString.AllKeys.Contains()
Then you can get ist's Value and do any other check you want, such as isNullOrEmpty, etc.
when new allocates an array, depending on the compiler (i use gnu c++), the word in front of the array contains information about the number of bytes allocated.
The test code:
#include <stdio.h>
#include <stdlib.h>
int
main ()
{
int arraySz;
char *a;
unsigned int *q;
for (arraySz = 5; arraySz <= 64; arraySz++) {
printf ("%02d - ", arraySz);
a = new char[arraySz];
unsigned char *p = (unsigned char *) a;
q = (unsigned int *) (a - 4);
printf ("%02d\n", (*q));
delete[] (a);
}
}
on my machine dumps out:
05 - 19
06 - 19
07 - 19
08 - 19
09 - 19
10 - 19
11 - 19
12 - 19
13 - 27
14 - 27
15 - 27
16 - 27
17 - 27
18 - 27
19 - 27
20 - 27
21 - 35
22 - 35
23 - 35
24 - 35
25 - 35
26 - 35
27 - 35
28 - 35
29 - 43
30 - 43
31 - 43
32 - 43
33 - 43
34 - 43
35 - 43
36 - 43
37 - 51
38 - 51
39 - 51
40 - 51
41 - 51
42 - 51
43 - 51
44 - 51
45 - 59
46 - 59
47 - 59
48 - 59
49 - 59
50 - 59
51 - 59
52 - 59
53 - 67
54 - 67
55 - 67
56 - 67
57 - 67
58 - 67
59 - 67
60 - 67
61 - 75
62 - 75
63 - 75
64 - 75
I would not recommend this solution (vector is better), but if you are really desperate, you could find a relationship and be able to conclude the number of bytes allocated from the heap.
Open the AVD Manager.
Click Edit Icon to edit the AVD.
Click Show Advanced settings.
Change the Internal Storage, Ram, SD Card size as necessary. Click Finish.
Confirm the popup by clicking yes.
Wipe Data on the AVD and confirm the popup by clicking yes.
Important: After increasing the size, if it doesn't automatically ask you to wipe data, you have to do it manually by opening the AVD's pull-down menu and choosing Wipe Data.
Now start and use your Emulator with increased storage.
This is my own plugin (will position the element in top of the the list. Specially for overflow-y : auto
. May not work with overflow-x
!):
NOTE: elem
is the HTML selector of an element which the page will be scrolled to. Anything supported by jQuery, like: #myid
, div.myclass
, $(jquery object)
, [dom object], etc.
jQuery.fn.scrollTo = function(elem, speed) {
$(this).animate({
scrollTop: $(this).scrollTop() - $(this).offset().top + $(elem).offset().top
}, speed == undefined ? 1000 : speed);
return this;
};
If you don't need it to be animated, then use:
jQuery.fn.scrollTo = function(elem) {
$(this).scrollTop($(this).scrollTop() - $(this).offset().top + $(elem).offset().top);
return this;
};
How to use:
$("#overflow_div").scrollTo("#innerItem");
$("#overflow_div").scrollTo("#innerItem", 2000); //custom animation speed
Note: #innerItem
can be anywhere inside #overflow_div
. It doesn't really have to be a direct child.
Tested in Firefox (23) and Chrome (28).
If you want to scroll the whole page, check this question.
assume you want one item to be clicked each time. Then this code works well. Let's take the listview name as stlist
stList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
// here i overide the onitemclick method in onitemclick listener
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//color change
//selected item colored
for(int i=0; i<stList.getAdapter().getCount();i++)
{
stList.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
parent.getChildAt(position).setBackgroundColor(Color.GRAY);
});
Use Shift+Del.
More info: Shift+Del combination key set a field to null when you filled a field by a value and you changed your decision and you want to make it null. It is useful and I amazed from the other answers that give strange solutions.
I ran into the same issue and the above answers didn't help. I need to debug and find it.
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.6.0-cdh5.13.1</version>
<exclusions>
<exclusion>
<artifactId>jsp-api</artifactId>
<groupId>javax.servlet.jsp</groupId>
</exclusion>
</exclusions>
</dependency>
After excluding the jsp-api, it worked for me.
There is a UDF that will do that described here:
User Defined Function to Strip HTML
CREATE FUNCTION [dbo].[udf_StripHTML] (@HTMLText VARCHAR(MAX))
RETURNS VARCHAR(MAX) AS
BEGIN
DECLARE @Start INT
DECLARE @End INT
DECLARE @Length INT
SET @Start = CHARINDEX('<',@HTMLText)
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
WHILE @Start > 0 AND @End > 0 AND @Length > 0
BEGIN
SET @HTMLText = STUFF(@HTMLText,@Start,@Length,'')
SET @Start = CHARINDEX('<',@HTMLText)
SET @End = CHARINDEX('>',@HTMLText,CHARINDEX('<',@HTMLText))
SET @Length = (@End - @Start) + 1
END
RETURN LTRIM(RTRIM(@HTMLText))
END
GO
Edit: note this is for SQL Server 2005, but if you change the keyword MAX to something like 4000, it will work in SQL Server 2000 as well.
Per this npm issue list, one work around could be done through npm config
name: 'foo'
config: { path: "baz" },
scripts: { start: "node ./$npm_package_config_path" }
Under windows, the scripts
could be { start: "node ./%npm_package_config_path%" }
Then run the command line as below
npm start --foo:path=myapp
Reset - On the commit-level, resetting is a way to move the tip of a branch to a different commit. This can be used to remove commits from the current branch.
Revert - Reverting undoes a commit by creating a new commit. This is a safe way to undo changes, as it has no chance of re-writing the commit history. Contrast this with git reset, which does alter the existing commit history. For this reason, git revert should be used to undo changes on a public branch, and git reset should be reserved for undoing changes on a private branch.
You can have a look on this link- Reset, Checkout and Revert
You can read it from Request
using Request.Form
, your dropdown name is ddlVendor
so pass ddlVendor
key in the formCollection to get its value that is posted by form:
string strDDLValue = Request.Form["ddlVendor"].ToString();
or Use FormCollection
:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{
string strDDLValue = form["ddlVendor"].ToString();
return View(MV);
}
If you want with Model binding then add a property in Model:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectedVendor {get;set;}
}
and in View:
@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
and in Action:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{
string SelectedValue = MV.SelectedVendor;
return View(MV);
}
If you want to post the text of selected item as well, you have to add a hidden field and on drop down selection change set selected item text in the hidden field:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectVendor {get;set;}
public string SelectedvendorText { get; set; }
}
use jquery to set hidden field:
<script type="text/javascript">
$(function(){
$("#SelectedVendor").on("change", function {
$("#SelectedvendorText").val($(this).text());
});
});
</script>
@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
@Html.HiddenFor(m=>m.SelectedvendorText)
Change your line
ws.Range(Rand, 1).EntireRow.Delete
to
ws.Cells(Rand, 1).EntireRow.Delete
As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have
So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).
There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see
Simply do (mouseenter)
attribute in Angular2+...
In your HTML do:
<div (mouseenter)="mouseHover($event)">Hover!</div>
and in your component do:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'component',
templateUrl: './component.html',
styleUrls: ['./component.scss']
})
export class MyComponent implements OnInit {
mouseHover(e) {
console.log('hovered', e);
}
}
Or you could use File.AppendAllLines(string, IEnumerable<string>)
File.AppendAllLines(@"C:\Path\file.txt", new[] { "my text content" });
I'm sitting at a computer with none of the relevant bits of software, but from memory that code looks wrong. You're executing the command but discarding the RecordSet
that objMyCommand.Execute
returns.
I'd do:
Set objMyRecordset = objMyCommand.Execute
...and then lose the "open recordset" part.
Do i need to modify the headers and just echo it or something?
exactly.
Send a header("content-type: image/your_image_type");
and the data afterwards.
You could use the below to take multiple inputs separated by a keyword
a,b,c=raw_input("Please enter the age of 3 people in one line using commas\n").split(',')
You also can try out this
final WebView webView = new WebView(this);
webView.loadDataWithBaseURL(null, content, "text/html", "UTF-8", null);
Note that most of XLConnect's functions are already vectorized. This means that you can read in all worksheets with one function call without having to do explicit vectorization:
require(XLConnect)
wb <- loadWorkbook(system.file("demoFiles/mtcars.xlsx", package = "XLConnect"))
lst = readWorksheet(wb, sheet = getSheets(wb))
With XLConnect 0.2-0 lst will already be a named list.
First install a pod :-
pod 'SwiftGifOrigin'
and import in your class
import SwiftGifOrigin
then write this code in viewDidiload method
yourImageView.image = UIImage.gif(name: "imageName")
Note:- plz do not include the file extension in the gif file name. Ex:-
//Don't Do this
yourImageView.image = UIImage.gif(name: "imageName.gif")
See source: https://github.com/swiftgif/SwiftGif
Your syntax is pretty screwy.
Change this:
input:not(disabled)not:[type="submit"]:focus{
to:
input:not(:disabled):not([type="submit"]):focus{
Seems that many people don't realize :enabled
and :disabled
are valid CSS selectors...
If you are working in Eclipse IDE, that could mean that you haven't close the file in the previous launch of the application. When I had the same error message at trying to delete a file, that was the reason. It seems, Eclipse IDE doesn't close all files after termination of an application.
Try using following command. I haven't tried it but I think it should work.
openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt
Is there an easy way to convert jQuery code to regular javascript?
No, especially if:
understanding the examples of javascript solutions written in jQuery [is] hard.
JQuery and all the frameworks tend to make understanding the code easier. If that's difficult to understand, then vanilla javascript will be torture :)
To fix this issue simply upgrade react-scripts package (check latest version with npm info react-scripts version
):
"react-scripts": "^3.x.x"
with "react-scripts": "^3.4.1"
(or the latest available version)npm install
or yarn install
Some people reported that this issue was caused by running npm audit fix
(avoid it!).
I removed your document.getElementById("Save").onclick =
before your functions, because it's an event already being called on your button. I also had to call the two functions separately by the onclick event.
<!DOCTYPE html>
<html>
<head>
<script>
function fun()
{
alert("hello");
//validation code to see State field is mandatory.
}
function f1()
{
alert("f1 called");
//form validation that recalls the page showing with supplied inputs.
}
</script>
</head>
<body>
<form name="form1" id="form1" method="post">
State:
<select id="state ID">
<option></option>
<option value="ap">ap</option>
<option value="bp">bp</option>
</select>
</form>
<table><tr><td id="Save" onclick="f1(); fun();">click</td></tr></table>
</body>
</html>
If you are using SQL server 2016 or higher and if your table is having partitions created based on column you are trying to delete(for example Timestamp column), then you could use this new command to delete data by partitions.
TRUNCATE TABLE WITH ( PARTITIONS ( { | } [ , ...n ] ) )
This will delete the data in selected partition(s) only and should be the most efficient way to delete data from part of table since it will not create transaction logs and will be done just as fast as regular truncate but without having all the data deleted from the table.
Drawback is if your table is not setup with partition, then you need to go old school and delete the data with regular approach and then recreate the table with partitions so that you can do this in future, which is what I did. I added the partition creation and deletion into insertion procedure itself. I had table with 500 million rows so this was the only option to reduce deletion time.
For more details refer to below links: https://docs.microsoft.com/en-us/sql/t-sql/statements/truncate-table-transact-sql?view=sql-server-2017
SQL server 2016 Truncate table with partitions
Below is what I did first to delete the data before I could recreate the table with partitions with required data in it. This query will run for days during specified time window until the data is deleted.
:connect <<ServerName>>
use <<DatabaseName>>
SET NOCOUNT ON;
DECLARE @Deleted_Rows INT;
DECLARE @loopnum INT;
DECLARE @msg varchar(100);
DECLARE @FlagDate datetime;
SET @FlagDate = getdate() - 31;
SET @Deleted_Rows = 1;
SET @loopnum = 1;
/*while (getdate() < convert(datetime,'2018-11-08 14:00:00.000',120))
BEGIN
RAISERROR( 'WAIT for START' ,0,1) WITH NOWAIT
WAITFOR DELAY '00:10:00'
END*/
RAISERROR( 'STARTING PURGE' ,0,1) WITH NOWAIT
WHILE (1=1)
BEGIN
WHILE (@Deleted_Rows > 0 AND (datepart(hh, getdate() ) >= 12 AND datepart(hh, getdate() ) <= 20)) -- (getdate() < convert(datetime,'2018-11-08 19:00:00.000',120) )
BEGIN
-- Delete some small number of rows at a time
DELETE TOP (500000) dbo.<<table_name>>
WHERE timestamp_column < convert(datetime, @FlagDate,102)
SET @Deleted_Rows = @@ROWCOUNT;
WAITFOR DELAY '00:00:01'
select @msg = 'ROWCOUNT' + convert(varchar,@Deleted_Rows);
set @loopnum = @loopnum + 1
if @loopnum > 1000
begin
begin try
DBCC SHRINKFILE (N'<<databasename>>_log' , 0, TRUNCATEONLY)
RAISERROR( @msg ,0,1) WITH NOWAIT
end try
begin catch
RAISERROR( 'DBCC SHRINK' ,0,1) WITH NOWAIT
end catch
set @loopnum = 1
end
END
WAITFOR DELAY '00:10:00'
END
select getdate()
Try this:
@keyframes animationName {
0% { opacity:0; }
50% { opacity:1; }
100% { opacity:0; }
}
@-o-keyframes animationName{
0% { opacity:0; }
50% { opacity:1; }
100% { opacity:0; }
}
@-moz-keyframes animationName{
0% { opacity:0; }
50% { opacity:1; }
100% { opacity:0; }
}
@-webkit-keyframes animationName{
0% { opacity:0; }
50% { opacity:1; }
100% { opacity:0; }
}
.elementToFadeInAndOut {
-webkit-animation: animationName 5s infinite;
-moz-animation: animationName 5s infinite;
-o-animation: animationName 5s infinite;
animation: animationName 5s infinite;
}
command line:
keytool -genseckey -alias aliasName -keystore truststore.bks -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath /path/to/jar/bcprov-jdk16-1.46.jar -storetype BKS
A few
x % 2 == 0; // Check if even
!(x & 1); // bitmask the value with 1 then invert.
((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value
~x&1; // flip the bits and bitmask
make sure you have mapped the y: drive, or copy all the files to local dir c:/local
c:/local> copy *.* c:/newfile.txt
Seek to the end of the file minus 100 bytes or so. Do a read and search for a newline. If here is no newline, seek back another 100 bytes or so. Lather, rinse, repeat. Eventually you'll find a newline. The last line begins immediately after that newline.
Best case scenario you only do one read of 100 bytes.
On Centos7, It is important to note that while you remove jenkins using following command: sudo yum remove jenkins
it will not remove your users and other information. For that you will have to do following: sudo rm -r /var/lib/jenkins
There's also str_pad
<?php
$input = "Alien";
echo str_pad($input, 10); // produces "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // produces "__Alien___"
echo str_pad($input, 6 , "___"); // produces "Alien_"
?>
This is what events are for.
HTMLInputElementObject.addEventListener('input', function (evt) {
something(this.value);
});
[Update]
While the solution under "old answer" will work for general problems, this section is to answer your specific question after clarification from your comment.
You should be able to set environment variables exactly like you specify in your question. As an example, I have a Heroku app that uses HTTP basic authentication.
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == ENV['HTTP_USER'] && password == ENV['HTTP_PASS']
end
end
end
# config/initializers/dev_environment.rb
unless Rails.env.production?
ENV['HTTP_USER'] = 'testuser'
ENV['HTTP_PASS'] = 'testpass'
end
So in your case you would use
unless Rails.env.production?
ENV['admin_password'] = "secret"
end
Don't forget to restart the server so the configuration is reloaded!
[Old Answer]
For app-wide configuration, you might consider a solution like the following:
Create a file config/application.yml
with a hash of options you want to be able to access:
admin_password: something_secret
allow_registration: true
facebook:
app_id: application_id_here
app_secret: application_secret_here
api_key: api_key_here
Now, create the file config/initializers/app_config.rb
and include the following:
require 'yaml'
yaml_data = YAML::load(ERB.new(IO.read(File.join(Rails.root, 'config', 'application.yml'))).result)
APP_CONFIG = HashWithIndifferentAccess.new(yaml_data)
Now, anywhere in your application, you can access APP_CONFIG[:admin_password]
, along with all your other data. (Note that since the initializer includes ERB.new
, your YAML file can contain ERB markup.)
I have tried a few of the answers above and note that some of them are version dependent and do not work in version 3.7.
I also note that since 3.6 all dictionaries are ordered by the sequence in which items are inserted.
Despite dictionaries being ordered since 3.6 some of the statements you expect to work with ordered structures don't seem to work.
The answer to the OP question that worked best for me.
itr = iter(dic.items())
lst = [next(itr) for i in range(3)]
Although your answer has many solutions I think this is a great way to save lines of code. Try using spans which is great for situations like yours.
span.bold(This name can be anything do not include parenthesis) { font-weight: bold; }
Everything except for point 2 is correct. There are many different notations for signed ints, some implementations use the first, others use the last and yet others use something completely different. That all depends on the platform you're working with.
$ pip install --user ipykernel
$ python -m ipykernel install --user --name=test2
Does this help?
http://www.quirksmode.org/js/iframe.html
I only tested this in firefox, but if you have something like this:
<iframe name='myframe' id='myframe' src='http://www.google.com'></iframe>
You can get its address by using:
document.getElementById('myframe').src
Not sure if I understood your question correctly but anyways :)
You can use this tool to create appropriate c# classes:
http://jsonclassgenerator.codeplex.com/
and when you will have classes created you can simply convert string to object:
public static T ParseJsonObject<T>(string json) where T : class, new()
{
JObject jobject = JObject.Parse(json);
return JsonConvert.DeserializeObject<T>(jobject.ToString());
}
Here that classes: http://ge.tt/2KGtbPT/v/0?c
Just fix namespaces.
const things = [
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"}
];
const filteredArr = things.reduce((thing, current) => {
const x = thing.find(item => item.place === current.place);
if (!x) {
return thing.concat([current]);
} else {
return thing;
}
}, []);
console.log(filteredArr)
_x000D_
Solution Via Set
Object | According to the data type
const seen = new Set();
const things = [
{place:"here",name:"stuff"},
{place:"there",name:"morestuff"},
{place:"there",name:"morestuff"}
];
const filteredArr = things.filter(el => {
const duplicate = seen.has(el.place);
seen.add(el.place);
return !duplicate;
});
console.log(filteredArr)
_x000D_
Set
Object Feature
Each value in the Set Object has to be unique, the value equality will be checked
The Purpose of Set object storing unique values according to the Data type , whether primitive values or object references.it has very useful four Instance methods add
, clear
, has
& delete
.
Unique & data Type feature:..
add
method
it's push unique data into collection by default also preserve data type .. that means it prevent to push duplicate item into collection also it will check data type by default...
has
method
sometime needs to check data item exist into the collection and . it's handy method for the collection to cheek unique id or item and data type..
delete
method
it will remove specific item from the collection by identifying data type..
clear
method
it will remove all collection items from one specific variable and set as empty object
Set
object has also Iteration methods & more feature..
Better Read from Here : Set - JavaScript | MDN
For those using (or planning to use) the accepted answer from Christian Varga, please be aware of the performance issues.
Cloning/manipulating the DOM in such a way causes DOM Reflow (see an explanation on DOM reflow here) which is extremely resource intensive.
Using Christian Varga's solution on 100+ elements on a page caused a 4 second reflow delay during which the JS thread is locked. Considering JS is single-threaded this means a significant UX delay to the end user.
Italo Borssatto's answer should be the accepted one, it was approximately 10 times quicker during my profiling.
Or, you could try changing the parameter type to string, then convert the string to an integer in the method. I am new to MVC, but I believe you need nullable objects in your parameter list, how else will the controller indicate that no such parameter was provided? So...
public ActionResult ViewNextItem(string id)...
Using ed:
ed -s infile <<<'16224,16482p'
-s
suppresses diagnostic output; the actual commands are in a here-string. Specifically, 16224,16482p
runs the p
(print) command on the desired line address range.
It seems that for full page reload $window.location.href
is the preferred way.
It does not cause a full page reload when the browser URL is changed. To reload the page after changing the URL, use the lower-level API, $window.location.href.
I had a similar issue, I was using the ViewBag and Element name as same. (Typing mistake)
There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.
By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler)
method call you are also able to register a signal handler, but probably not for signals like INT
or TERM
as they are used by the JVM.
To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.
What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid
system call.
I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.
In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before
css to match yours.
In case if it is IE10 then using below css3 it is possible
select::-ms-expand {
display: none;
}
However if you're interested in jQuery plugin, try Chosen.js
or you can create your own in js.
This BFS-like solution is pretty straightforward. Simply jumps levels one-by-one.
def getHeight(self,root, method='links'):
c_node = root
cur_lvl_nodes = [root]
nxt_lvl_nodes = []
height = {'links': -1, 'nodes': 0}[method]
while(cur_lvl_nodes or nxt_lvl_nodes):
for c_node in cur_lvl_nodes:
for n_node in filter(lambda x: x is not None, [c_node.left, c_node.right]):
nxt_lvl_nodes.append(n_node)
cur_lvl_nodes = nxt_lvl_nodes
nxt_lvl_nodes = []
height += 1
return height
Forgive me - I couldn't resist ;-)
def goto(linenum):
global line
line = linenum
line = 1
while True:
if line == 1:
response = raw_input("yes or no? ")
if response == "yes":
goto(2)
elif response == "no":
goto(3)
else:
goto(100)
elif line == 2:
print "Thank you for the yes!"
goto(20)
elif line == 3:
print "Thank you for the no!"
goto(20)
elif line == 20:
break
elif line == 100:
print "You're annoying me - answer the question!"
goto(1)
In at least in ubuntu 16.10, the default python3
is python3.5
. As such, all of the python3-X
packages will be installed for python3.5 and not for python3.6.
You can verify this by checking the shebang of pip3
:
$ head -n1 $(which pip3)
#!/usr/bin/python3
Fortunately, the pip installed by the python3-pip
package is installed into the "shared" /usr/lib/python3/dist-packages
such that python3.6 can also take advantage of it.
You can install packages for python3.6 by doing:
python3.6 -m pip install ...
For example:
$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py
Another way to refresh the current page using selenium in Java.
//first: get the current URL in a String variable
String currentURL = driver.getCurrentUrl();
//second: call the current URL
driver.get(currentURL);
Using this will refresh the current page like clicking the address bar of the browser and pressing enter.
If you add the boolean true to the reload
window.location.reload(true)
it will load from server.
It is not clear how supported this boolean is, W3Org mentions that NS used to support it
There MIGHT be a difference between the content of window.location.href and document.URL - there at least used to be a difference between location.href and the non-standard and deprecated document.location that had to do with redirection, but that is really last millennium.
For documentation purposes I would use window.location.reload() because that is what you want to do.
I'm assuming that you're trying to deal with Ajax navigation and not trying to prevent your users from using the back button, which violates just about every tenet of UI development ever.
Here's some possible solutions: JQuery History Salajax A Better Ajax Back Button
In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'
Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:
from matplotlib import pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]
color = [str(item/255.) for item in y]
plt.scatter(x, y, s=500, c=color)
plt.show()
Another option is doing the following:
public class UserList extends List<User>{
}
public <T> T magicalListGetter(Class<T> clazz) {
List<?> list = doMagicalVooDooHere();
return (T)list;
}
List<User> users = magicalListGetter(UserList.class);
`
Hide text on load and show on hover
.hide-text {
width: 70px;
display: inline-block;
white-space: nowrap;
overflow: hidden !important;
text-overflow: ellipsis;
}
span:hover {
white-space: unset;
text-overflow: unset;
}
_x000D_
<span class="hide-text"> How to hide text by dots and show text on hover</span>
_x000D_
Add style="width:100%; height:100%;"
to the div see what that does
not to the #map_canvas
but the main div
example
<body>
<div style="height:100%; width:100%;">
<div id="map-canvas"></div>
</div>
</body>
There are some other answers on here the explain why this is necessary
Here is the solution: You use Ctrl+Alt+Delete, open task manager and switch to tab services find VMWareHostd and right click to chose StopService. You can start xampp without error
Regarding @Suragch's Alternative to "Remove element of unknown index":
There is a more powerful version of "indexOf(element)" that will match on a predicate instead of the object itself. It goes by the same name but it called by myObjects.indexOf{$0.property = valueToMatch}. It returns the index of the first matching item found in myObjects array.
If the element is an object/struct, you may want to remove that element based on a value of one of its properties. Eg, you have a Car class having car.color property, and you want to remove the "red" car from your carsArray.
if let validIndex = (carsArray.indexOf{$0.color == UIColor.redColor()}) {
carsArray.removeAtIndex(validIndex)
}
Foreseeably, you could rework this to remove "all" red cars by embedding the above if statement within a repeat/while loop, and attaching an else block to set a flag to "break" out of the loop.
Here is just a reply from Richard Pickup on LinkedIn to a similar question of mine:
I've used cocos 2dx marmalade and unity on both iOS and android. For 2d games cocos2dx is the way to go every time. Unity is just too much overkill for 2d games and as already stated marmalade is just a thin abstraction layer not really a game engine. You can even run cocos2d on top of marmalade. My approach would be to use cocos2dx on iOS and android then in future run cocosd2dx code on top of marmalade as an easy way to port to bb10 and win phone 7
I would use Bootstrap's grid to achieve the desired result. The class="img-responsive" works nicely. Something like:
<div class="container-fluid">
<div class="row">
<div class="col-md-3"><img src="./pictures/placeholder.jpg" class="img-responsive" alt="Some picture" width="410" height="307"></div>
<div class="col-md-9"><h1>Heading</h1><p>Your Information.</p></div>
</div>
</div>
you can try to this , then you get a bitmap of selected image and then you can easily find it's native path from Device Default Gallery.
Bitmap roughBitmap= null;
try {
// Works with content://, file://, or android.resource:// URIs
InputStream inputStream =
getContentResolver().openInputStream(uri);
roughBitmap= BitmapFactory.decodeStream(inputStream);
// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.Width, roughBitmap.Height);
RectF outRect = new RectF(0, 0, dstWidth, dstHeight);
m.SetRectToRect(inRect, outRect, Matrix.ScaleToFit.Center);
float[] values = new float[9];
m.GetValues(values);
// resize bitmap if needed
Bitmap resizedBitmap = Bitmap.CreateScaledBitmap(roughBitmap, (int) (roughBitmap.Width * values[0]), (int) (roughBitmap.Height * values[4]), true);
string name = "IMG_" + new Java.Text.SimpleDateFormat("yyyyMMdd_HHmmss").Format(new Java.Util.Date()) + ".png";
var sdCardPath= Environment.GetExternalStoragePublicDirectory("DCIM").AbsolutePath;
Java.IO.File file = new Java.IO.File(sdCardPath);
if (!file.Exists())
{
file.Mkdir();
}
var filePath = System.IO.Path.Combine(sdCardPath, name);
} catch (FileNotFoundException e) {
// Inform the user that things have gone horribly wrong
}
Include this where the imports are on top:
import android.view.WindowManager;
Add this code on OnCreate part:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
if you also want to compare the order of the answer you can extend the answer to something like this:
Array.prototype.compareTo = function (array2){
var array1 = this;
var difference = [];
$.grep(array2, function(el) {
if ($.inArray(el, array1) == -1) difference.push(el);
});
if( difference.length === 0 ){
var $i = 0;
while($i < array1.length){
if(array1[$i] !== array2[$i]){
return false;
}
$i++;
}
return true;
}
return false;
}
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
C:\>start chrome "http://site1.com"
works on Windows Vista.
Hiding through CSS is achieved by using either the "visibility" or the "display" attributes. Though both achieve similar results, it's useful to know the differences.
If you only want to hide the element but retain the space occupied by it, you should use:
#mybox:hover {
visibility: hidden;
}
If you want to hide the element and remove the space occupied by it, so that other elements can take its space, then you should use:
#mybox:hover {
display: none;
}
Also remember that IE6 and below do not respond to :hover for anything except A tags. In which case, you'll need some Javascript to change the classname:
document.getElementById('mybox').className = 'hide';
and define the "hide" class in CSS:
.hide { display: none; }
Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.
location / {
root /path/to/root/of/static/files;
try_files $uri $uri/ @apachesite;
expires max;
access_log off;
}
location @apachesite {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files
. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.
Joshua Bloch's book has a whole chapter entitled "Item 10: Override Clone Judiciously" in which he goes into why overriding clone for the most part is a bad idea because the Java spec for it creates many problems.
He provides a few alternatives:
Use a factory pattern in place of a constructor:
public static Yum newInstance(Yum yum);
Use a copy constructor:
public Yum(Yum yum);
All of the collection classes in Java support the copy constructor (e.g. new ArrayList(l);)
Assume that the application folder is in your pen drive.
open eclipse, go to import,select Android,In Android select "existing android code into workspace"
next and finish.
Ramanand Bhat
What you do is called a projection. That's when you return only a scalar value that belongs to one entity. You can do this with JPA. See scalar value.
I think in this case, omitting the entity type altogether is possible:
Query query = em.createNativeQuery( "select id from users where username = ?");
query.setParameter(1, "lt");
BigDecimal val = (BigDecimal) query.getSingleResult();
Example taken from here.
final long usedMemInMB=(runtime.totalMemory() - runtime.freeMemory()) / 1048576L;
final long maxHeapSizeInMB=runtime.maxMemory() / 1048576L;
final long availHeapSizeInMB = maxHeapSizeInMB - usedMemInMB;
It is a strange code. It return MaxMemory - (totalMemory - freeMemory). If freeMemory equals 0, then the code will return MaxMemory - totalMemory, so it can more or equals 0. Why freeMemory not used?
I saw that no one had used the slice method, so here I put my 2 cents here.
df["<col_name>"].str.slice(stop=5)
df["<col_name>"].str.slice(start=6)
This method will create two new columns.
It is important to run your mongod command and keep the server running. If not, you will still be seeing this error.
I attach you my code:
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'task-manager'
MongoClient.connect(connectionURL, {useNewUrlParser: true, useUnifiedTopology: true}, (error, client) => {
if(error) {
return console.log('Error connecting to the server.')
}
console.log('Succesfully connected.')
})
_x000D_
i experience this error too. I think it was because I failed to supply a box_url..
vagrant init precise64 http://files.vagrantup.com/precise64.box
Set button visibility to GONE (button will be completely "removed" -- the buttons space will be available for another widgets) or INVISIBLE (button will became "transparent" -- its space will not be available for another widgets):
View b = findViewById(R.id.button);
b.setVisibility(View.GONE);
or in xml:
<Button ... android:visibility="gone"/>
This code might work for non-.NET Core MVC controllers:
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);
One more thing to consider is whether or not the class could be used in an array:
foo bar[400];
In this scenario, there is no advantage to using the default parameter.
This would certainly NOT work:
foo bar("david", 34)[400]; // NOPE
I was working with talend V7.3.1 and I had poi version "4.1.0" and including xml-beans from the list of dependencies didnt fix my problem (i.e: 2.3.0 and 2.6.0).
It was fixed by downloading the jar "xmlbeans-3.0.1.jar" and adding it to the project
using bitmask and bitwise and .
string int2bin(int n){
string x;
for(int i=0;i<32;i++){
if(n&1) {x+='1';}
else {x+='0';}
n>>=1;
}
reverse(x.begin(),x.end());
return x;
}
We Can override the blue color in to our custom color It works for Internet Explorer, Firefox and Chrome:
By using this below following CSS:
option: checked, option: hover {
Color: #ffffff;
background: #614767 repeat url("data:image/gif;base64,R0lGODlh8ACgAPAAAGFGZQAAACH5BAAAAAAALAAAAADwAKAAAAL+hI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC8fyTNf2jef6zvf+DwwKh8Si8YhMKpfMpvMJjUqn1Kr1is1qt9yu9wsOi8fksvmMTqvX7Lb7DY/L5/S6/Y7P6/f8vv8PGCg4SFhoeIiYqLjI2Oj4CBkpOUlZaXmJmam5ydnp+QkaKjpKWmp6ipqqusra6voKGys7S1tre4ubq7vL2+v7CxwsPExcbHyMnKy8zNzs/AwdLT1NXW19jZ2tvc3d7f0NHi4+Tl5ufo6err7O3u7+Dh8vP09fb3+Pn6+/z9/v/w8woMCBBAsaPIgwocKFDBs6fAgxosSJFCtavIhRVgEAOw");
}
download latest pytz file (pytz-2019.3.tar.gz) from:
https://pypi.org/simple/pytz/
copy and extract it to site_packages
directory on yor project
in cmd go to the extracted folder and run:
python setup.py install
TIME_ZONE = 'Etc/GMT+2'
or country name