Check Yasea library
Yasea is an Android streaming client. It encodes YUV and PCM data from camera and microphone to H.264/AAC, encapsulates in FLV and transmits over RTMP.
Feature:
If you want a "capture/streamer in a box" component, there are several out there as others have mentioned.
If you want to get down to the low-level control over it all, you'll need to use DirectShow as thealliedhacker points out. The best way to use DirectShow in C# is through the DirectShow.Net library - it wraps all of the DirectShow COM APIs and includes many useful shortcut functions for you.
In addition to capturing and streaming, you can also do recording, audio and video format conversions, audio and video live filters, and a whole lot of stuff.
Microsoft claims DirectShow is going away, but they have yet to release a new library or API that does everything that DirectShow provides. I suspect many of the latest things they have released are still DirectShow under the hood. Because of its status at Microsoft, there aren't a whole lot of books or references on it other than MSDN and what you can find on forums. Last year when we started a project using it, the best book on the subject - Programming Microsoft DirectShow - was out of print and going for around $350 for a used copy!
Reload Visual Studio with Administrator privileges. Windows Sockets (WinSock) will not allow you to create a SocketType.RAW Socket without Local Admin. And remember that your Solution will need elevated privileges to run as expected!
Simple way to initiate the message on startup:
bot.on('ready', () => {
bot.user.setStatus('available')
bot.user.setPresence({
game: {
name: 'with depression',
type: "STREAMING",
url: "https://www.twitch.tv/monstercat"
}
});
});
You can also just declare it elsewhere after startup, to change the message as needed:
bot.user.setPresence({ game: { name: 'with depression', type: "streaming", url: "https://www.twitch.tv/monstercat"}});
With VLC i'm able to transcode a live RTSP stream (mpeg4) to an HTTP stream in a OGG format (Vorbis/Theora). The quality is poor but the video work in Chrome 9. I have also tested with a trancoding in WEBM (VP8) but it's don't seem to work (VLC have the option but i don't know if it's really implemented for now..)
The first to have a doc on this should notify us ;)
I am not saying that you have to abandon PHP, but you need different technologies here.
Let's start off simple (without Akamai :-)) and think about the implications here. Video, chat, etc. - it's all client-side in the beginning. The user has a webcam, you want to grab the signal somehow and send it to the server. There is no PHP so far.
I know that Flash supports this though (check this tutorial on webcams and flash) so you could use Flash to transport the content to the server. I think if you'll stay with Flash, then Flex (flex and webcam tutorial) is probably a good idea to look into.
So those are just the basics, maybe it gives you an idea of where you need to research because obviously this won't give you a full video chat inside your app yet. For starters, you will need some sort of way to record the streams and re-publish them so others see other people from the chat, etc..
I'm also not sure how much traffic and bandwidth this is gonna consume though and generally, you will need way more than a Stackoverflow question to solve this issue. Best would be to do a full spec of your app and then hire some people to help you build it.
HTH!
private static void DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}
(For future reference.)
Quite possibly the fastest way to do this would be to use memory mapped files (so primarily copying memory, and the OS handling the file reads/writes via its paging/memory management).
Memory Mapped files are supported in managed code in .NET 4.0.
But as noted, you need to profile, and expect to switch to native code for maximum performance.
I had the same problem but finally I found the way.
Here is the walk through:
1- Install VLC on your computer (SERVER) and go to Media->Streaming (Ctrl+S)
2- Select a file to stream or if you want to stream your webcam or... click on "Capture Device" tab and do the configuration and finally click on "Stream" button.
3- Here you should do the streaming server configuration, just go to "Option" tab and paste the following command:
:sout=#transcode{vcodec=mp4v,vb=400,fps=10,width=176,height=144,acodec=mp4a,ab=32,channels=1,samplerate=22050}:rtp{sdp=rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/}
NOTE: Replace YOURCOMPUTER_SERVER_IP_ADDR with your computer IP address or any server which is running VLC...
NOTE: You can see, the video codec is MP4V which is supported by android.
4- go to eclipse and create a new project for media playbak. create a VideoView object and in the OnCreate() function write some code like this:
mVideoView = (VideoView) findViewById(R.id.surface_view);
mVideoView.setVideoPath("rtsp://YOURCOMPUTER_SERVER_IP_ADDR:5544/");
mVideoView.setMediaController(new MediaController(this));
5- run the apk on the device (not simulator, i did not check it) and wait for the playback to be started. please consider the buffering process will take about 10 seconds...
Question: Anybody know how to reduce buffering time and play video almost live ?
For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);
If you want it to download and install from your own server then use the following code
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
startActivity(intent);
I do this quite a bit and thought I could add a simpler answer. I set it up as a simple class here, but I run this every evening to collect financial data on companies I'm following.
class WebPage
{
public static string Get(string uri)
{
string results = "N/A";
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
results = sr.ReadToEnd();
sr.Close();
}
catch (Exception ex)
{
results = ex.Message;
}
return results;
}
}
In this case I pass in a url and it returns the page as HTML. If you want to do something different with the stream instead you can easily change this.
You use it like this:
string page = WebPage.Get("http://finance.yahoo.com/q?s=yhoo");
You can use IP Webcam, or perhaps use DLNA. For example Samsung devices come with an app called AllShare which can share and access DLNA enabled devices on the network. I think IP Webcam is your best bet, though. You should be able to open the stream it creates using MX Video player or something like that.
AFAIK, RTSP does not transmit streams at all, it is just an out-of-band control protocol with functions like PLAY and STOP.
Raw UDP or RTP over UDP are transmission protocols for streams just like raw TCP or HTTP over TCP.
To be able to stream a certain program over the given transmission protocol, an encapsulation method has to be defined for your container format. For example TS container can be transmitted over UDP but Matroska can not.
Pretty much everything can be transported through TCP though.
(The fact that which codec do you use also matters indirectly as it restricts the container formats you can use.)
Our first thought is that the site is down or the like, but the truth is that this is not the problem or disability. Nor is it a problem because a simple connection when tested under Firefox, Opera or services Explorer open as normal.
The error in Chrome displays a sign that says "This site is not available" and clarification with the legend "Error 15 (net :: ERR_SOCKET_NOT_CONNECTED): Unknown error". The error is quite usual in Google Chrome, more precisely in its updates, and its workaround is to restart the computer.
As partial solutions are not much we offer a tutorial for you solve the fault in less than a minute. To avoid this problem and ensure that services are normally open in Google Chrome should insert the following into the address bar: chrome: // net-internals (then give "Enter"). They then have to go to the "Socket" in the left menu and choose "Flush Socket Pools" (look at the following screenshots to guide http://www.fixotip.com/how-to-fix-error-waiting-for-available-sockets-in-google-chrome/) This has the problem solved and no longer will experience problems accessing Gmail, Google or any of the services of the Mountain View giant. I hope you found it useful and share the tutorial with whom they need or social networks: Facebook, Twitter or Google+.
You can use video js library for easily play HLS video's. It allows to directly play videos
<!-- CSS -->
<link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">
<!-- HTML -->
<video id='hls-example' class="video-js vjs-default-skin" width="400" height="300" controls>
<source type="application/x-mpegURL" src="http://www.streambox.fr/playlists/test_001/stream.m3u8">
</video>
<!-- JS code -->
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/ie8-version/videojs-ie8.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.14.1/videojs-contrib-hls.js"></script>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>
<script>
var player = videojs('hls-example');
player.play();
</script>
I wrote an HTML5 video player around broadway h264 codec (emscripten) that can play live (no delay) h264 video on all browsers (desktop, iOS, ...).
Video stream is sent through websocket to the client, decoded frame per frame and displayed in a canva (using webgl for acceleration)
Check out https://github.com/131/h264-live-player on github.
-mmin is for minutes.
Try looking at the man page.
man find
for more types.
replace it with index of the array.
array[index] = new_value;
When your Android stuio/jre uses a differ version of java, you will receive this error. to solve it, just set Android studio/jre to your JAVA_HOME. and uninstall your own java.
.PHONY: install
Swift version of new implementation is :
let alert = UIAlertController(title: "Oops!", message:"your message", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Okay.", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
Ok i'm going to extend on the answers here since a lot of the people who come here want to split the string by a whitespace. This is how it's done:
List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));
If the path you want is the one to the workbook running the macro, and that workbook has been saved, then
ThisWorkbook.Path
is what you would use.
Something like:
clients.stream.filter(c->{
users.stream.filter(u->u.getName().equals(c.getName()).count()>0
}).collect(Collectors.toList());
This is however not an awfully efficient way to do it. Unless the collections are very small, you will be better of building a set of user names and using that in the condition.
According to the latest doc you can do the following-
Add a day
moment().add(1, 'days').calendar();
Add Year
moment().add(1, 'years').calendar();
Add Month
moment().add(1, 'months').calendar();
Try format
function:
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"
Useful topic thanks.
If you want like me remove leadings zero you can use that :
DECLARE @MyFloat [float];
SET @MyFloat = 1000109360.050;
SELECT REPLACE(RTRIM(REPLACE(REPLACE(RTRIM(LTRIM(REPLACE(STR(@MyFloat, 38, 16), '0', ' '))), ' ', '0'),'.',' ')),' ',',')
There are plenty of examples of using JQuery to retrieve the mouse coordinates, but none fixed my issue.
The Body of my webpage is 1000 pixels wide, and I centre it in the middle of the user's browser window.
body {
position:absolute;
width:1000px;
left: 50%;
margin-left:-500px;
}
Now, in my JavaScript code, when the user right-clicked on my page, I wanted a div to appear at the mouse position.
Problem is, just using e.pageX value wasn't quite right. It'd work fine if I resized my browser window to be about 1000 pixels wide. Then, the pop div would appear at the correct position.
But if increased the size of my browser window to, say, 1200 pixels wide, then the div would appear about 100 pixels to the right of where the user had clicked.
The solution is to combine e.pageX with the bounding rectangle of the body element. When the user changes the size of their browser window, the "left" value of body element changes, and we need to take this into account:
// Temporary variables to hold the mouse x and y position
var tempX = 0;
var tempY = 0;
jQuery(document).ready(function () {
$(document).mousemove(function (e) {
var bodyOffsets = document.body.getBoundingClientRect();
tempX = e.pageX - bodyOffsets.left;
tempY = e.pageY;
});
})
Phew. That took me a while to fix ! I hope this is useful to other developers !
public class SecureSocket {
static {
// System.setProperty("javax.net.debug", "all");
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
}
public static void main(String[] args) {
String GhitHubSSLFile = "https://raw.githubusercontent.com/Yash-777/SeleniumWebDrivers/master/pom.xml";
try {
String str = readCloudFileAsString(GhitHubSSLFile);
// new String(Files.readAllBytes(Paths.get( "D:/Sample.file" )));
System.out.println("Cloud File Data : "+ str);
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readCloudFileAsString( String urlStr ) throws java.io.IOException {
if( urlStr != null && urlStr != "" ) {
java.io.InputStream s = null;
String content = null;
try {
URL url = new URL( urlStr );
s = (java.io.InputStream) url.getContent();
content = IOUtils.toString(s, "UTF-8");
}
}
return content.toString();
}
return null;
}
I found these two links which might help you:
https://www.reddit.com/r/csharp/comments/2agecc/why_must_visual_studio_be_installed_on_my_system/
http://www.placona.co.uk/1196/dotnet/installing-visual-studio-on-a-different-drive/
Basically, at least a portion needs to be installed on a system drive. I'm not sure if your D:\ corresponds to some external drive or an actual system drive but the symlink solution might help.
Good luck
For those that may be running Oracle in a VM (like me) I saw this issue because my VM was running out of memory, which seems to have prevented OracleDB from starting up/running correctly. Increasing my VM memory and restarting fixed the issue.
It appears that the correct answer varies in different JS engines. Here are the results I got from the test suite linked in ninjagecko's answer:
[].concat.apply
is fastest in Chrome 83 on Windows and Android, followed by reduce
(~56% slower);concat
is fastest in Safari 13 on Mac, followed by reduce
(~13% slower);reduce
is fastest in Safari 12 on iOS, followed by looped concat
(~40% slower);push
is fastest in Firefox 70 on Windows, followed by [].concat.apply
(~30% slower).Getting
java.nio.file.AccessDeniedException
when trying to write to a folder
Unobviously, Comodo antivirus has an "Auto-Containment" setting that can cause this exact error as well. (e.g. the user can write to a location, but the java.exe
and javaw.exe
processes cannot).
In this edge-case scenario, adding an exception for the process and/or folder should help.
Temporarily disabling the antivirus feature will help understand if Comodo AV is the culprit.
I post this not because I use or prefer Comodo, but because it's a tremendously unobvious symptom to an otherwise functioning Java application and can cost many hours of troubleshooting file permissions that are sane and correct, but being blocked by a 3rd-party application.
Math.Floor()
rounds
"toward negative infinity" in compliance to IEEE Standard 754 section 4.
Math.Truncate()
rounds " to the nearest integer towards zero."
That's a half-open interval.
[a,b]
includes the end points.(a,b)
excludes them.In your case the end-point at the start of the interval is included, but the end is excluded. So it means the interval "first1 <= x < last1".
Half-open intervals are useful in programming because they correspond to the common idiom for looping:
for (int i = 0; i < n; ++i) { ... }
Here i is in the range [0, n).
On the event of onClick
this.state={
title:''
}
sendthru=()=>{
document.getElementByid('inputname').value = '';
this.setState({
title:''
})
}
<input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />
<button className="btn btn-info" onClick={this.sendthru}>Add</button>
These are two different modes in which your computer can operate. Prior to this, when computers were like a big room, if something crashes – it halts the whole computer. So computer architects decide to change it. Modern microprocessors implement in hardware at least 2 different states.
User mode:
Kernel mode:
How the switch occurs.
The switch from user mode to kernel mode is not done automatically by CPU. CPU is interrupted by interrupts (timers, keyboard, I/O). When interrupt occurs, CPU stops executing the current running program, switch to kernel mode, executes interrupt handler. This handler saves the state of CPU, performs its operations, restore the state and returns to user mode.
http://en.wikibooks.org/wiki/Windows_Programming/User_Mode_vs_Kernel_Mode
http://tldp.org/HOWTO/KernelAnalysis-HOWTO-3.html
Python has a built-in datatype for an unordered collection of (hashable) things, called a set
. If you convert both lists to sets, the comparison will be unordered.
set(x) == set(y)
EDIT: @mdwhatcott points out that you want to check for duplicates. set
ignores these, so you need a similar data structure that also keeps track of the number of items in each list. This is called a multiset; the best approximation in the standard library is a collections.Counter
:
>>> import collections
>>> compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
>>>
>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3,3], [1,2,2,3])
False
>>>
Thanks for the info, think I see the problem. This is a bug in hive-go
that only shows up when you add a host. The last lines of it are:
app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);
When you add the host on the first line, it is crashing when it calls app.address().port
.
The problem is the potentially asynchronous nature of .listen()
. Really it should be doing that console.log
call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.
Try this:
app.listen(3001, 'localhost', function() {
console.log("... port %d in %s mode", app.address().port, app.settings.env);
});
If you really want to cover the case that a script is called via execfile(...)
, you can use the inspect
module to deduce the filename (including the path). As far as I am aware, this will work for all cases you listed:
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))
The problem is in your JSP, most likely you are calling a method on an object that is null at runtime.
It is happening in the _jspInit() call, which is a little more unusual... the problem code is probably a method declaration like <%! %>
Update: I've only reproduced this by overriding the _jspInit() method. Is that what you're doing? If so, it's not recommended - that's why it starts with an _.
You could use VB to write something that will output to a file row by row adding in the appropriate sql statements around your data. I have done this before.
I can't reproduce the @SilentGhost-beating performance quoted by @martineau. Here's my effort with comparisons:
=== maxelements.py ===
a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
35, 41, 49, 37, 19, 40, 41, 31]
b = range(10000)
c = range(10000 - 1, -1, -1)
d = b + c
def maxelements_s(seq): # @SilentGhost
''' Return list of position(s) of largest element '''
m = max(seq)
return [i for i, j in enumerate(seq) if j == m]
def maxelements_m(seq): # @martineau
''' Return list of position(s) of largest element '''
max_indices = []
if len(seq):
max_val = seq[0]
for i, val in ((i, val) for i, val in enumerate(seq) if val >= max_val):
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
def maxelements_j(seq): # @John Machin
''' Return list of position(s) of largest element '''
if not seq: return []
max_val = seq[0] if seq[0] >= seq[-1] else seq[-1]
max_indices = []
for i, val in enumerate(seq):
if val < max_val: continue
if val == max_val:
max_indices.append(i)
else:
max_val = val
max_indices = [i]
return max_indices
Results from a beat-up old laptop running Python 2.7 on Windows XP SP3:
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_s(me.a)"
100000 loops, best of 3: 6.88 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_m(me.a)"
100000 loops, best of 3: 11.1 usec per loop
>\python27\python -mtimeit -s"import maxelements as me" "me.maxelements_j(me.a)"
100000 loops, best of 3: 8.51 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_s(a100)"
1000 loops, best of 3: 535 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_m(a100)"
1000 loops, best of 3: 558 usec per loop
>\python27\python -mtimeit -s"import maxelements as me;a100=me.a*100" "me.maxelements_j(a100)"
1000 loops, best of 3: 489 usec per loop
I hope you were joking about writing your own parser. :-)
For such a simple mapping, most tools from http://json.org (section java) would work. For one of them (Jackson https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator), you'd do:
Map<String,Object> result =
new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
(where JSON_SOURCE is a File, input stream, reader, or json content String)
It's identical to commenting out the block, except with one important difference: Nesting is not a problem. Consider this code:
foo();
bar(x, y); /* x must not be NULL */
baz();
If I want to comment it out, I might try:
/*
foo();
bar(x, y); /* x must not be NULL */
baz();
*/
Bzzt. Syntax error! Why? Because block comments do not nest, and so (as you can see from SO's syntax highlighting) the */
after the word "NULL" terminates the comment, making the baz
call not commented out, and the */
after baz
a syntax error. On the other hand:
#if 0
foo();
bar(x, y); /* x must not be NULL */
baz();
#endif
Works to comment out the entire thing. And the #if 0
s will nest with each other, like so:
#if 0
pre_foo();
#if 0
foo();
bar(x, y); /* x must not be NULL */
baz();
#endif
quux();
#endif
Although of course this can get a bit confusing and become a maintenance headache if not commented properly.
Since hours are always positive, and always 2 digits, you can set a 1 in front of it and subtract 100:
echo $((1$hour+1-100))
which is equivalent to
echo $((1$hour-99))
Be sure to comment such gymnastics. :)
If you are using v2.2.0 then there is one more option available to detect changes in $routes.
To react to params changes in the same component, you can watch the $route object:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// react to route changes...
}
}
}
Or, use the beforeRouteUpdate guard introduced in 2.2:
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
Reference: https://router.vuejs.org/en/essentials/dynamic-matching.html
document.ready
is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all content.window.onload
fires later (or at the same time in the worst/failing cases) when images and such are loaded, so if you're using image dimensions for example, you often want to use this instead.A lot of answers here, nothing really simple. It's important that the ScrollView's lauout_height
is set to match_parent
while the layout_height
of the ContraintLayout is wrap_content
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
...
Define "stretch and scale"...
If you've got a bitmap format, it's generally not great (graphically speaking) to stretch it and pull it about. You can use repeatable patterns to give the illusion of the same effect. For instance if you have a gradient that gets lighter towards the bottom of the page, then you would use a graphic that's a single pixel wide and the same height as your container (or preferably larger to account for scaling) and then tile it across the page. Likewise, if the gradient ran across the page, it would be one pixel high and wider than your container and repeated down the page.
Normally to give the illusion of it stretching to fill the container when the container grows or shrinks, you make the image larger than the container. Any overlap would not be displayed outside the bounds of the container.
If you want an effect that relies on something like a box with curved edges, then you would stick the left side of your box to the left side of your container with enough overlap that (within reason) no matter how large the container, it never runs out of background and then you layer an image of the right side of the box with curved edges and position it on the right of the container. Thus as the container shrinks or grows, the curved box effect appears to shrink or grow with it - it doesn't in fact, but it gives the illusion that is what's happening.
As for really making the image shrink and grow with the container, you would need to use some layering tricks to make the image appear to function as a background and some javascript to resize it with the container. There's no current way of doing this with CSS...
If you're using vector graphics, you're way outside my realm of expertise I'm afraid.
Whenever you use
export someobject
and someobject is
{
"prop1":"Property1",
"prop2":"Property2",
}
the above you can import anywhere using import
or module.js
and there you can use someobject. This is not a restriction that someobject will be an object only it can be a function too, a class or an object.
When you say
new Object()
like you said
new Vue({
el: '#app',
data: []
)}
Here you are initiating an object of class Vue.
I hope my answer explains your query in general and more explicitly.
The current "pipable" variant of this operator is called finalize()
(since RxJS 6). The older and now deprecated "patch" operator was called finally()
(until RxJS 5.5).
I think finalize()
operator is actually correct. You say:
do that logic only when I subscribe, and after the stream has ended
which is not a problem I think. You can have a single source
and use finalize()
before subscribing to it if you want. This way you're not required to always use finalize()
:
let source = new Observable(observer => {
observer.next(1);
observer.error('error message');
observer.next(3);
observer.complete();
}).pipe(
publish(),
);
source.pipe(
finalize(() => console.log('Finally callback')),
).subscribe(
value => console.log('#1 Next:', value),
error => console.log('#1 Error:', error),
() => console.log('#1 Complete')
);
source.subscribe(
value => console.log('#2 Next:', value),
error => console.log('#2 Error:', error),
() => console.log('#2 Complete')
);
source.connect();
This prints to console:
#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message
Jan 2019: Updated for RxJS 6
It depends on the size of your database.
SQL is based on the SET theory: there is no order inherently used when querying a table.
So if you were to run the first query, it would first order by product price and then product name, IF there were any duplicates in the price category, say $20 for example, it would then order those duplicates by their names, therefore always maintaining that when you run your query it will always return the same set of result in the same order.
If you were to run the second query, it would only order by the name, so if there were two products with the same name (for some odd reason) then they wouldn't have a guaranteed order after you run the query.
Using writing-mode
and transform
.
.rotate {
writing-mode: vertical-lr;
-webkit-transform: rotate(-180deg);
-moz-transform: rotate(-180deg);
}
<span class="rotate">Hello</span>
<input type="text" disabled="disabled" />
See the W3C HTML Specification on the input tag for more information.
create example script as resp :
#!/bin/bash
http_code=200
mime=text/html
echo -e "HTTP/1.1 $http_code OK\r"
echo "Content-type: $mime"
echo
echo "Set-Cookie: name=F"
then make executable and execute like this.
./resp | nc -l -p 12346
open browser and browse URL: http://localhost:1236 you will see Cookie value which is sent by Browser
[aaa@bbbbbbbb ]$ ./resp | nc -l -p 12346 GET / HTTP/1.1 Host: xxx.xxx.xxx.xxx:12346 Connection: keep-alive Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36 Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8,ru;q=0.6 Cookie: name=F
In spring boot 2.x you need to reference provider specific properties.
The default, hikari can be set with spring.datasource.hikari.maximum-pool-size
.
Simple Steps:
-Open Eclipse.
You have to initialize variables before using them.?
If you try to evaluate the variables before initializing them you'll run into:
FailedPreconditionError: Attempting to use uninitialized value tensor.
The easiest way is initializing all variables at once using: tf.global_variables_initializer()
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
You use sess.run(init)
to run the initializer, without fetching any value.
To initialize only a subset of variables, you use tf.variables_initializer()
listing the variables:
var_ab = tf.variables_initializer([a, b], name="a_and_b")
with tf.Session() as sess:
sess.run(var_ab)
You can also initialize each variable separately using tf.Variable.initializer
# create variable W as 784 x 10 tensor, filled with zeros
W = tf.Variable(tf.zeros([784,10])) with tf.Session() as sess:
sess.run(W.initializer)
Since Swift 3, many of the NS prefixes have been dropped.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
/* date format string rules
* http://userguide.icu-project.org/formatparse/datetime
*/
let date = dateFormatter.date(from: dateString)
setVertical* helped to make vertical scrollbar always visible programmatically
scrollView.setScrollbarFadingEnabled(false);
scrollView.setVerticalScrollBarEnabled(true);
scrollView.setVerticalFadingEdgeEnabled(false);
http://www.asoft.be/prod_netver.html
Use this "good, lightweight, no-install-required program"
Update August 2019
In Android Studio 3.5 Instant Run was replaced with Apply Changes. And it works in different way: APK is not modified on the fly anymore but instead runtime instrumentation is used to redefine classes on the fly (more info). So since Android Studio 3.5 instant run settings are replaced with Deployment (Settings -> Build, Execution, Deployment -> Deployment):
The long must be at least the same size as an int, and possibly, but not necessarily, longer.
On common 32-bit systems, both int and long are 4-bytes/32-bits, and this is valid according to the C++ spec.
On other systems, both int and long long may be a different size. I used to work on a platform where int was 2-bytes, and long was 4-bytes.
The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize queue
to null when you declare it.
Queue queue = null;
SELECT CUSTOMER, COUNT(*) as PETS
FROM table_name
GROUP BY CUSTOMER;
This just worked for me on Ubuntu 16:
Download ('instantclient-basic-linux.x64-12.2.0.1.0.zip' and 'instantclient-sdk-linux.x64-12.2.0.1.0.zip') from Oracle web site and then do following script (you can do piece by piece and I did as a ROOT):
apt-get install -y python-dev build-essential libaio1
mkdir -p /opt/ora/
cd /opt/ora/
## Now put 2 ZIP files:
# ('instantclient-basic-linux.x64-12.2.0.1.0.zip' and 'instantclient-sdk-linux.x64-12.2.0.1.0.zip')
# into /opt/ora/ and unzip them -> both will be unzipped into 1 directory: /opt/ora/instantclient_12_2
rm -rf /etc/profile.d/oracle.sh
echo "export ORACLE_HOME=/opt/ora/instantclient_12_2" >> /etc/profile.d/oracle.sh
echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME" >> /etc/profile.d/oracle.sh
chmod 777 /etc/profile.d/oracle.sh
source /etc/profile.d/oracle.sh
env | grep -i ora # This will check current ENVIRONMENT settings for Oracle
rm -rf /etc/ld.so.conf.d/oracle.conf
echo "/opt/ora/instantclient_12_2" >> /etc/ld.so.conf.d/oracle.conf
ldconfig
cd $ORACLE_HOME
ls -lrth libclntsh* # This will show which version of 'libclntsh' you have... --> needed for following line:
ln -s libclntsh.so.12.1 libclntsh.so
pip install cx_Oracle # Maybe not needed but I did it anyway (only pip install cx_Oracle without above steps did not work for me...)
Your python scripts are now ready to use 'cx_Oracle'... Enjoy!
C99 defines bool, true
and false
in stdbool.h
.
I know the question specified dplyr
. But, since others already posted solutions using other packages, I decided to have a go using other packages too:
Base package:
df <- df[with(df, order(id, stopSequence, stopId)), ]
merge(df[!duplicated(df$id), ],
df[!duplicated(df$id, fromLast = TRUE), ],
all = TRUE)
data.table:
df <- setDT(df)
df[order(id, stopSequence)][, .SD[c(1,.N)], by=id]
sqldf:
library(sqldf)
min <- sqldf("SELECT id, stopId, min(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId")
max <- sqldf("SELECT id, stopId, max(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId")
sqldf("SELECT * FROM min
UNION
SELECT * FROM max")
In one query:
sqldf("SELECT *
FROM (SELECT id, stopId, min(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId)
UNION
SELECT *
FROM (SELECT id, stopId, max(stopSequence) AS StopSequence
FROM df GROUP BY id
ORDER BY id, StopSequence, stopId)")
Output:
id stopId StopSequence
1 1 a 1
2 1 c 3
3 2 b 1
4 2 c 4
5 3 a 3
6 3 b 1
To answer the question literally (since GitHub is not in the question title), also be aware of this post over on superuser. EDIT: Answer copied here in relevant part, slightly modified for clarity in square brackets:
You're getting rejected because you're trying to delete the branch that your origin has currently "checked out".
If you have direct access to the repo, you can just open up a shell [in the bare repo] directory and use good old
git branch
to see what branch origin is currently on. To change it to another branch, you have to usegit symbolic-ref HEAD refs/heads/another-branch
.
It depends why the something is on the same line in the first place.
clear
in the case of floats, display: block
in the case of inline content naturally flowing, nothing will defeat position: absolute
as the previous element will be taken out of the normal flow by it.
v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.
So, you should override it with display: flex
in your HTML or CSS to make it work with justify-content.
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
Just do myFunction.foo = "bar"
and it will add it. myFunction
is the name of the object in this case.
You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:
var rockets = [_x000D_
{ country:'Russia', launches:32 },_x000D_
{ country:'US', launches:23 },_x000D_
{ country:'China', launches:16 },_x000D_
{ country:'Europe(ESA)', launches:7 },_x000D_
{ country:'India', launches:4 },_x000D_
{ country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
var launchOptimistic = rockets.map(function(elem) {_x000D_
return {_x000D_
country: elem.country,_x000D_
launches: elem.launches+10,_x000D_
} _x000D_
});_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
numpy.binary_repr(num, width=None)
has a magic width argumentRelevant examples from the documentation linked above:
>>> np.binary_repr(3, width=4) '0011'
The two’s complement is returned when the input number is negative and width is specified:
>>> np.binary_repr(-3, width=5) '11101'
The posttitle part of the URL is after your index.php
file, which is a common way of providing friendly URLs without using mod_rewrite. The posttitle is actually therefore part of the query string, so you should be able to get it using $_SERVER['QUERY_STRING']
Edit 2
I finally found a solution by implementing my forward action like that:
private void applyForward() {
FacesContext facesContext = FacesContext.getCurrentInstance();
// Find where to redirect the user.
String redirect = getTheFromOutCome();
// Change the Navigation context.
NavigationHandler myNav = facesContext.getApplication().getNavigationHandler();
myNav.handleNavigation(facesContext, null, redirect);
// Update the view root
UIViewRoot vr = facesContext.getViewRoot();
if (vr != null) {
// Get the URL where to redirect the user
String url = facesContext.getExternalContext().getRequestContextPath();
url = url + "/" + vr.getViewId().replace(".xhtml", ".jsf");
Object obj = facesContext.getExternalContext().getResponse();
if (obj instanceof HttpServletResponse) {
HttpServletResponse response = (HttpServletResponse) obj;
try {
// Redirect the user now.
response.sendRedirect(response.encodeURL(url));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
It works (at least regarding my first tests), but I still don't like the way it is implemented... Any better idea?
Edit This solution does not work. Indeed, when the doForward()
function is called, the JSF lifecycle has already been started, and then recreate a new request is not possible.
One idea to solve this issue, but I don't really like it, is to force the doForward()
action during one of the setBindedInputHidden()
method:
private boolean actionDefined = false;
private boolean actionParamDefined = false;
public void setHiddenActionParam(HtmlInputHidden hiddenActionParam) {
this.hiddenActionParam = hiddenActionParam;
String actionParam = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("actionParam");
this.hiddenActionParam.setValue(actionParam);
actionParamDefined = true;
forwardAction();
}
public void setHiddenAction(HtmlInputHidden hiddenAction) {
this.hiddenAction = hiddenAction;
String action = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("action");
this.hiddenAction.setValue(action);
actionDefined = true;
forwardAction();
}
private void forwardAction() {
if (!actionDefined || !actionParamDefined) {
// As one of the inputHidden was not binded yet, we do nothing...
return;
}
// Now, both action and actionParam inputHidden are binded, we can execute the forward...
doForward(null);
}
This solution does not involve any Javascript call, and works does not work.
I don't think there's a good "jQuery " way to do this, but if you need efficiency, map one of the arrays by a certain key (one of the unique object fields), and then do comparison by looping through the other array and comparing against the map, or associative array, you just built.
If efficiency is not an issue, just compare every object in A to every object in B. As long as |A| and |B| are small, you should be okay.
better use quoted `data`
and `date`
. AFAIR these may be reserved words
my version is:
INSERT INTO `table` ( `data` , `date` ) VALUES('".$date."',NOW()+INTERVAL 1 DAY);
Using the -u
command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the -u
option. I usually use a custom stdout
, like this:
class flushfile:
def __init__(self, f):
self.f = f
def write(self, x):
self.f.write(x)
self.f.flush()
import sys
sys.stdout = flushfile(sys.stdout)
... Now all your print
calls (which use sys.stdout
implicitly), will be automatically flush
ed.
This is the correct and tested solution
if (myReader.Read())
{
ltlAdditional.Text = "Contains data";
}
else
{
ltlAdditional.Text = "Is null";
}
Just put your images in the assets folder refer them in your html
pages or ts
files with that link.
You don't need ANY of these other fancy answers. Below is a simplistic example that doesn't have all the Margin
, Height
, Width
properties set in the XAML, but should be enough to show how to get this done at a basic level.
XAML
Build a Window
page like you would normally and add your fields to it, say a Label
and TextBox
control inside a StackPanel
:
<StackPanel Orientation="Horizontal">
<Label Name="lblUser" Content="User Name:" />
<TextBox Name="txtUser" />
</StackPanel>
Then create a standard Button
for Submission ("OK" or "Submit") and a "Cancel" button if you like:
<StackPanel Orientation="Horizontal">
<Button Name="btnSubmit" Click="btnSubmit_Click" Content="Submit" />
<Button Name="btnCancel" Click="btnCancel_Click" Content="Cancel" />
</StackPanel>
Code-Behind
You'll add the Click
event handler functions in the code-behind, but when you go there, first, declare a public variable where you will store your textbox value:
public static string strUserName = String.Empty;
Then, for the event handler functions (right-click the Click
function on the button XAML, select "Go To Definition", it will create it for you), you need a check to see if your box is empty. You store it in your variable if it is not, and close your window:
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(txtUser.Text))
{
strUserName = txtUser.Text;
this.Close();
}
else
MessageBox.Show("Must provide a user name in the textbox.");
}
Calling It From Another Page
You're thinking, if I close my window with that this.Close()
up there, my value is gone, right? NO!! I found this out from another site: http://www.dreamincode.net/forums/topic/359208-wpf-how-to-make-simple-popup-window-for-input/
They had a similar example to this (I cleaned it up a bit) of how to open your Window
from another and retrieve the values:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
MyPopupWindow popup = new MyPopupWindow(); // this is the class of your other page
//ShowDialog means you can't focus the parent window, only the popup
popup.ShowDialog(); //execution will block here in this method until the popup closes
string result = popup.strUserName;
UserNameTextBlock.Text = result; // should show what was input on the other page
}
}
Cancel Button
You're thinking, well what about that Cancel button, though? So we just add another public variable back in our pop-up window code-behind:
public static bool cancelled = false;
And let's include our btnCancel_Click
event handler, and make one change to btnSubmit_Click
:
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
cancelled = true;
strUserName = String.Empty;
this.Close();
}
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(txtUser.Text))
{
strUserName = txtUser.Text;
cancelled = false; // <-- I add this in here, just in case
this.Close();
}
else
MessageBox.Show("Must provide a user name in the textbox.");
}
And then we just read that variable in our MainWindow
btnOpenPopup_Click
event:
private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
MyPopupWindow popup = new MyPopupWindow(); // this is the class of your other page
//ShowDialog means you can't focus the parent window, only the popup
popup.ShowDialog(); //execution will block here in this method until the popup closes
// **Here we find out if we cancelled or not**
if (popup.cancelled == true)
return;
else
{
string result = popup.strUserName;
UserNameTextBlock.Text = result; // should show what was input on the other page
}
}
Long response, but I wanted to show how easy this is using public static
variables. No DialogResult
, no returning values, nothing. Just open the window, store your values with the button events in the pop-up window, then retrieve them afterwards in the main window function.
update
If you use the router you can use lifecycle hooks or resolvers to delay navigation until the data arrived. https://angular.io/guide/router#milestone-5-route-guards
To load data before the initial rendering of the root component APP_INITIALIZER
can be used How to pass parameters rendered from backend to angular2 bootstrap method
original
When console.log(this.ev)
is executed after this.fetchEvent();
, this doesn't mean the fetchEvent()
call is done, this only means that it is scheduled. When console.log(this.ev)
is executed, the call to the server is not even made and of course has not yet returned a value.
Change fetchEvent()
to return a Promise
fetchEvent(){
return this._apiService.get.event(this.eventId).then(event => {
this.ev = event;
console.log(event); // Has a value
console.log(this.ev); // Has a value
});
}
change ngOnInit()
to wait for the Promise
to complete
ngOnInit() {
this.fetchEvent().then(() =>
console.log(this.ev)); // Now has value;
}
This actually won't buy you much for your use case.
My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>
and in ngOnInit()
isDataAvailable:boolean = false;
ngOnInit() {
this.fetchEvent().then(() =>
this.isDataAvailable = true); // Now has value;
}
If you are building with Eclipse, make sure your project's build target is set to Honeycomb too.
Here's one xmlstarlet use case to extract data from nested elements elem1, elem2 to one line of text from this type of XML (also showing how to handle namespaces):
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<mydoctype xmlns="http://xml-namespace-uri" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xml-namespace-uri http://xsd-uri" format="20171221A" date="2018-05-15">
<elem1 time="0.586" length="10.586">
<elem2 value="cue-in" type="outro" />
</elem1>
</mydoctype>
The output will be
0.586 10.586 cue-in outro
In this snippet, -m matches the nested elem2, -v outputs attribute values (with expressions and relative addressing), -o literal text, -n adds a newline:
xml sel -N ns="http://xml-namespace-uri" -t -m '//ns:elem1/ns:elem2' \
-v ../@time -o " " -v '../@time + ../@length' -o " " -v @value -o " " -v @type -n file.xml
If more attributes are needed from elem1, one can do it like this (also showing the concat() function):
xml sel -N ns="http://xml-namespace-uri" -t -m '//ns:elem1/ns:elem2/..' \
-v 'concat(@time, " ", @time + @length, " ", ns:elem2/@value, " ", ns:elem2/@type)' -n file.xml
Note the (IMO unnecessary) complication with namespaces (ns, declared with -N), that had me almost giving up on xpath and xmlstarlet, and writing a quick ad-hoc converter.
I use the following code to change the endpoint address in the App.Config file. You may want to modify or remove the namespace before usage.
using System;
using System.Xml;
using System.Configuration;
using System.Reflection;
//...
namespace Glenlough.Generations.SupervisorII
{
public class ConfigSettings
{
private static string NodePath = "//system.serviceModel//client//endpoint";
private ConfigSettings() { }
public static string GetEndpointAddress()
{
return ConfigSettings.loadConfigDocument().SelectSingleNode(NodePath).Attributes["address"].Value;
}
public static void SaveEndpointAddress(string endpointAddress)
{
// load config document for current assembly
XmlDocument doc = loadConfigDocument();
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode(NodePath);
if (node == null)
throw new InvalidOperationException("Error. Could not find endpoint node in config file.");
try
{
// select the 'add' element that contains the key
//XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
node.Attributes["address"].Value = endpointAddress;
doc.Save(getConfigFilePath());
}
catch( Exception e )
{
throw e;
}
}
public static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
}
private static string getConfigFilePath()
{
return Assembly.GetExecutingAssembly().Location + ".config";
}
}
}
Use can use a String[]
instead of an ArrayList<String>
:
It will reduce the memory overhead that an ArrayList has
Hope it helps!
String[] stringsArray = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length; i++) {
parametersArray[i] = parametersJSONArray.getString(i);
}
In my copy, Shift + Tab does this, as long as I have a code selection, and am in a code window.
It is not possible to directly make a 3d surface using your data. I would recommend you to build an interpolation model using some tools like pykridge. The process will include three steps:
pykridge
X
and Y
using meshgrid
Z
Having created your grid and the corresponding Z
values, now you're ready to go with plot_surface
. Note that depending on the size of your data, the meshgrid
function can run for a while. The workaround is to create evenly spaced samples using np.linspace
for X
and Y
axes, then apply interpolation to infer the necessary Z
values. If so, the interpolated values might different from the original Z
because X
and Y
have changed.
iOS Status bar has only 2 options (black and white). You can try this in AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleLightContent];
}
You can use Web SQL API which is an ordinary SQLite database in your browser and you can open/modify it like any other SQLite databases for example with Lita.
Chrome locates databases automatically according to domain names or extension id. A few months ago I posted on my blog short article on how to delete Chrome's database because when you're testing some functionality it's quite useful.
Here is the solution that worked for me
=IF(H14<>"",NOW(),"")
this solution also considered the case that url is empty and disabled(gray) the empty link.
$(function() {_x000D_
changeAnchor();_x000D_
});_x000D_
_x000D_
function changeAnchor() {_x000D_
$("a[name$='aWebsiteUrl']").each(function() { // you can write your selector here_x000D_
$(this).css("background", "none");_x000D_
$(this).css("font-weight", "normal");_x000D_
_x000D_
var url = $(this).attr('href').trim();_x000D_
if (url == " " || url == "") { //disable empty link_x000D_
$(this).attr("class", "disabled");_x000D_
$(this).attr("href", "javascript:void(0)");_x000D_
} else {_x000D_
$(this).attr("target", "_blank");// HERE set the non-empty links, open in new window_x000D_
}_x000D_
});_x000D_
}
_x000D_
a.disabled {_x000D_
text-decoration: none;_x000D_
pointer-events: none;_x000D_
cursor: default;_x000D_
color: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<a name="aWebsiteUrl" href="http://www.baidu.com" class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href=" " class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href="http://www.alibaba.com" class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href="http://www.qq.com" class='#'>[website]</a>
_x000D_
Try
CAST(STR(DATEPART(year, DATE))+'-'+ STR(DATEPART(month, DATE)) +'-'+ STR(DATEPART(day, DATE)) AS DATETIME)
Since the count is the intended final value, in your query pass
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get()->result_array();
return count($query);
The count the retuned value
The accepted answer here is problematic, because there is no guarantee that an image will have any sort of interactive shell. For example, the drone/drone image contains on a single command /drone
, and it has an ENTRYPOINT
as well, so this will fail:
$ docker run -it drone/drone sh
FATA[0000] DRONE_HOST is not properly configured
And this will fail:
$ docker run --rm -it --entrypoint sh drone/drone
docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "exec: \"sh\": executable file not found in $PATH".
This is not an uncommon configuration; many minimal images contain only the binaries necessary to support the target service. Fortunately, there are mechanisms for exploring an image filesystem that do not depend on the contents of the image. The easiest is probably the docker export
command, which will export a container filesystem as a tar archive. So, start a container (it does not matter if it fails or not):
$ docker run -it drone/drone sh
FATA[0000] DRONE_HOST is not properly configured
Then use docker export
to export the filesystem to tar
:
$ docker export $(docker ps -lq) | tar tf -
The docker ps -lq
there means "give me the id of the most recent docker container". You could replace that with an explicit container name or id.
You have to call 2 functions for this:
First: for excuting the commands you have implemented in onNavigationItemSelected
listener:
onNavigationItemSelected(navigationView.getMenu().getItem(R.id.nav_camera));
Second: for changing the state of the navigation drawer menu item to selected (or checked):
navigationView.setCheckedItem(R.id.nav_camera);
I called both functions and it worked for me.
This is due to the series df[cat]
containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna
operation.
In other words
pandas data type 'Object' indicates mixed types rather than str type
so using the following line:
df[cat] = le.fit_transform(df[cat].astype(str))
should help
stopPropagation
prevents further propagation of the current event in the capturing and bubbling phases.
preventDefault
prevents the default action the browser makes on that event.
preventDefault
$("#but").click(function (event) {
event.preventDefault()
})
$("#foo").click(function () {
alert("parent click event fired!")
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div>
_x000D_
stopPropagation
$("#but").click(function (event) {
event.stopPropagation()
})
$("#foo").click(function () {
alert("parent click event fired!")
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
<button id="but">button</button>
</div>
_x000D_
With stopPropagation
, only the button
's click handler is called while the div
's click handler never fires.
Where as if you use preventDefault
, only the browser's default action is stopped but the div's click handler still fires.
Below are some docs on the DOM event properties and methods from MDN:
For IE9 and FF you can just use preventDefault & stopPropagation.
To support IE8 and lower replace stopPropagation
with cancelBubble
and replace preventDefault
with returnValue
The value disappears since the read command is run in a separate subshell: Bash FAQ 24
Try git checkout -f master
.
-f
or --force
Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html
When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.
When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.
Update: check for existence using TryGetValue
to do only one lookup in the case where you have the list:
List<int> list;
if (!dictionary.TryGetValue("foo", out list))
{
list = new List<int>();
dictionary.Add("foo", list);
}
list.Add(2);
var dictionary = new Dictionary<string, List<int>>();
if (!dictionary.ContainsKey("foo"))
dictionary.Add("foo", new List<int>());
dictionary["foo"].Add(42);
dictionary["foo"].AddRange(oneHundredInts);
Or List<string>
as in your case.
As an aside, if you know how many items you are going to add to a dynamic collection such as List<T>
, favour the constructor that takes the initial list capacity: new List<int>(100);
.
This will grab the memory required to satisfy the specified capacity upfront, instead of grabbing small chunks every time it starts to fill up. You can do the same with dictionaries if you know you have 100 keys.
A browser isn't going to show you white space reliably. I recommend the Linux 'od' command to see what's really in there. Comforming XML parsers will respect all of the methods you listed.
And also
library(dplyr)
data %>% filter(!v1 %in% c("b", "d", "e"))
or
data %>% filter(v1 != "b" & v1 != "d" & v1 != "e")
or
data %>% filter(v1 != "b", v1 != "d", v1 != "e")
Since the &
operator is implied by the comma.
The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:
underscores_in_headers on;
This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997
I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.
Do not edit the plist. These instructions worked for me the first time I installed Android Studio a few months ago as well as just today. (1/21/2015)
All you need to do is a few simple things, although they aren't really listed on Google's website.
Append the following script to the following file (on the SSRS Server)
C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js
function pageLoad() {
var element = document.getElementById("ctl31_ctl10");
if (element)
{
element.style.overflow = "visible";
}
}
Note: As azzlak noted, the div's name isn't always ctl31_ctl10
. For SQL 2012 tryctl32_ctl09
and for 2008 R2 try ctl31_ctl09
. If this solution doesn't work, look at the HTML from your browser to see if the script has worked properly changing the overflow:auto
property to overflow:visible
.
Insert into .aspx
page (or into a linked .css
file, if available) this style line
#reportViewer_ctl09 {
overflow:visible !important;
}
Chrome and Safari render overflow:auto
in different way respect to IE.
SSRS HTML is QuirksMode HTML and depends on IE 5.5 bugs. Non-IE browsers don't have the IE quirksmode and therefore render the HTML correctly
The HTML page produced by SSRS 2008 R2 reports contain a div
which has overflow:auto
style, and it turns report into an invisible report.
<div id="ctl31_ctl10" style="height:100%;width:100%;overflow:auto;position:relative;">
I can see reports on Chrome by manually changing overflow:auto
to overflow:visible
in the produced webpage using Chrome's Dev Tools (F12).
I love Tim's solution, it's easy and working.
But there is still a problem: any time the user change parameters (my reports use parameters!) AJAX refreshes the div, the overflow:auto tag is rewritten, and no script changes it.
This technote detail explains what is the problem:
This happens because in a page built with AJAX panels, only the AJAX panels change their state, without refreshing the whole page. Consequently, the
OnLoad
events you applied on the<body>
tag are only fired once: the first time your page loads. After that, changing any of the AJAX panels will not trigger these events anymore.
User einarq suggested this solution:
Another option is to rename your function to pageLoad. Any functions with this name will be called automatically by asp.net ajax if it exists on the page, also after each partial update. If you do this you can also remove the onload attribute from the body tag
So wrote the improved script that is shown in the solution.
Here's some more detailed information on what Client, Resource, and Session are all about.
Client:
Here's an example of client-level access to an S3 bucket's objects (at most 1000**):
import boto3
client = boto3.client('s3')
response = client.list_objects_v2(Bucket='mybucket')
for content in response['Contents']:
obj_dict = client.get_object(Bucket='mybucket', Key=content['Key'])
print(content['Key'], obj_dict['LastModified'])
** you would have to use a paginator, or implement your own loop, calling list_objects() repeatedly with a continuation marker if there were more than 1000.
Resource:
Here's the equivalent example using resource-level access to an S3 bucket's objects (all):
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('mybucket')
for obj in bucket.objects.all():
print(obj.key, obj.last_modified)
Note that in this case you do not have to make a second API call to get the objects; they're available to you as a collection on the bucket. These collections of subresources are lazily-loaded.
You can see that the Resource
version of the code is much simpler, more compact, and has more capability (it does pagination for you). The Client
version of the code would actually be more complicated than shown above if you wanted to include pagination.
Session:
A useful resource to learn more about these boto3 concepts is the introductory re:Invent video.
You also can check input mask formatter.
This is a directive and it's called ui-mask
and also it's a part of angular-ui.utils
library.
Here is working: Live example
For the time of writing this post there aren't any examples of using this directive, so I've made a very simple example to demonstrate how this thing works in practice.
Tried to specify dll path in different ways (proposed by @markm), but nothing has worked for me. Fixed the problem by copying dll into script folder. It's not a good solution, but ok for my purposes.
A generic answer that may or not apply to this specific case:
As the error message hint at, aclocal-1.15 should only be required if you modified files that were used to generate aclocal.m4
If you don't modify any of those files (including configure.ac) then you should not need to have aclocal-1.15.
In my case, the problem was not that any of those files was modified but somehow the timestamp on configure.ac was 6 minutes later compared to aclocal.m4.
I haven't figured out why, but a clean clone of my git repo solved the issue for me. Maybe something linked to git and how it created files in the first place.
Rather than rerunning autoconf and friends, I would just try to get a clean clone and try again.
It's also possible that somebody committed a change to configure.ac but didn't regenerate the aclocal.m4, in which case you indeed have to rerun automake and friends.
In general, you can't do this. UTF-8 is capable of encoding any Unicode code point. ISO-8859-1 can handle only a tiny fraction of them. So, transcoding from ISO-8859-1 to UTF-8 is no problem. Going backwards from UTF-8 to ISO-8859-1 will cause "replacement characters" (�) to appear in your text when unsupported characters are found.
To transcode text:
byte[] latin1 = ...
byte[] utf8 = new String(latin1, "ISO-8859-1").getBytes("UTF-8");
or
byte[] utf8 = ...
byte[] latin1 = new String(utf8, "UTF-8").getBytes("ISO-8859-1");
You can exercise more control by using the lower-level Charset
APIs. For example, you can raise an exception when an un-encodable character is found, or use a different character for replacement text.
If you only need to execute only one command all by itself and no wait needed, you should try "cmd /c", this works for me!
cmd /c start iexplore "http://your/url.html"
cmd /c means executing a command and then exit.
You can learn the functions of your switches by typing in your command prompt
anycmd /?
Although this isn't going to be a problem for the person who asked the question, because they ran the program that was to produce the core file in a script with the ulimit command, I'd like to document that the ulimit command is specific to the shell in which you run it (like environment variables). I spent way too much time running ulimit and sysctl and stuff in one shell, and the command that I wanted to dump core in the other shell, and wondering why the core file was not produced.
I will be adding it to my bashrc. The sysctl works for all processes once it is issued, but the ulimit only works for the shell in which it is issued (maybe also the descendents too) - but not for other shells that happen to be running.
You could use random.sample
to generate the list with one call:
import random
my_randoms = random.sample(range(100), 10)
That generates numbers in the (inclusive) range from 0 to 99. If you want 1 to 100, you could use this (thanks to @martineau for pointing out my convoluted solution):
my_randoms = random.sample(range(1, 101), 10)
For python 2 i did this
print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1])
it prints time "%H:%M:%S" , splits the time.time() to two substrings (before and after the .) xxxxxxx.xx and since .xx are my milliseconds i add the second substring to my "%H:%M:%S"
hope that makes sense :) Example output:
13:31:21.72 Blink 01
13:31:21.81 END OF BLINK 01
13:31:26.3 Blink 01
13:31:26.39 END OF BLINK 01
13:31:34.65 Starting Lane 01
Another working example:
var zlib = require('zlib');
var tar = require('tar');
var ftp = require('ftp');
var files = [];
var conn = new ftp();
conn.on('connect', function(e)
{
conn.auth(function(e)
{
if (e)
{
throw e;
}
conn.get('/tz/tzdata-latest.tar.gz', function(e, stream)
{
stream.on('success', function()
{
conn.end();
console.log("Processing files ...");
for (var name in files)
{
var file = files[name];
console.log("filename: " + name);
console.log(file);
}
console.log("OK")
});
stream.on('error', function(e)
{
console.log('ERROR during get(): ' + e);
conn.end();
});
console.log("Reading ...");
stream
.pipe(zlib.createGunzip())
.pipe(tar.Parse())
.on("entry", function (e)
{
var filename = e.props["path"];
console.log("filename:" + filename);
if( files[filename] == null )
{
files[filename] = "";
}
e.on("data", function (c)
{
files[filename] += c.toString();
})
});
});
});
})
.connect(21, "ftp.iana.org");
the best way to find out all the combinations for large number of lists is:
import itertools
from pprint import pprint
inputdata = [
['a', 'b', 'c'],
['d'],
['e', 'f'],
]
result = list(itertools.product(*inputdata))
pprint(result)
the result will be:
[('a', 'd', 'e'),
('a', 'd', 'f'),
('b', 'd', 'e'),
('b', 'd', 'f'),
('c', 'd', 'e'),
('c', 'd', 'f')]
I was getting this error : javax.faces.application.ViewExpiredException.When I using different requests, I found those having same JsessionId, even after restarting the server. So this is due to the browser cache. Just close the browser and try, it will work.
Another way to do this would be to respond to the UITableViewDelegate
method willDisplayHeaderView
. The passed view is actually an instance of a UITableViewHeaderFooterView
.
The example below changes the font, and also centers the title text vertically and horizontally within the cell. Note that you should also respond to heightForHeaderInSection
to have any changes to your header's height accounted for in the layout of the table view. (That is, if you decide to change the header height in this willDisplayHeaderView
method.)
You could then respond to the titleForHeaderInSection
method to reuse this configured header with different section titles.
Objective-C
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.textLabel.textColor = [UIColor redColor];
header.textLabel.font = [UIFont boldSystemFontOfSize:18];
CGRect headerFrame = header.frame;
header.textLabel.frame = headerFrame;
header.textLabel.textAlignment = NSTextAlignmentCenter;
}
Swift 1.2
(Note: if your view controller is a descendant of a UITableViewController
, this would need to be declared as override func
.)
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel.textColor = UIColor.redColor()
header.textLabel.font = UIFont.boldSystemFontOfSize(18)
header.textLabel.frame = header.frame
header.textLabel.textAlignment = NSTextAlignment.Center
}
Swift 3.0
This code also ensures that the app doesn't crash if your header view is something other than a UITableViewHeaderFooterView:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView else { return }
header.textLabel?.textColor = UIColor.red
header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
header.textLabel?.frame = header.frame
header.textLabel?.textAlignment = .center
}
not bad .. but try this one ... (should works for all but ist just -webkit included)
<br>
<input type="text" style="
background: transparent;
border-bottom: 1px solid #B5D5FF;
border-left: 1px solid;
border-right: 1px solid;
border-left-color: #B5D5FF;
border-image: -webkit-linear-gradient(top, #fff 50%, #B5D5FF 0%) 1 repeat;
">
//Feel free to edit and add all other browser..
I got the "hunks failed" message when I wasn't applying the patch in the top directory of the associated git project. I was applying the patch (where I created it) in a subdirectory.
It seems patches can be created from subdirectories within a git project, but not applied.
Just adding to all the fine answers, my version with decoration:
from __future__ import print_function
import six
def classrep(rep):
def decorate(cls):
class RepMetaclass(type):
def __repr__(self):
return rep
class Decorated(six.with_metaclass(RepMetaclass, cls)):
pass
return Decorated
return decorate
@classrep("Wahaha!")
class C(object):
pass
print(C)
stdout:
Wahaha!
The down sides:
C
without a super class (no class C:
)C
instances will be instances of some strange derivation, so it's probably a good idea to add a __repr__
for the instances as well.If you are on windows, try Visual Studio Code with MySQL plugins, an easy and integrated way to access MySQL data on a windows machine. And the database tables listed and can execute any custom queries.
This is due to a security vulnerability that has been addressed in Ghostscript 9.24 (source). If you have a newer version, you don't need this workaround anymore. On Ubuntu 19.10 with Ghostscript 6, this means:
Make sure you have Ghostscript =9.24:
gs --version
If yes, just remove this whole following section from /etc/ImageMagick-6/policy.xml
:
<!-- disable ghostscript format types -->
<policy domain="coder" rights="none" pattern="PS" />
<policy domain="coder" rights="none" pattern="PS2" />
<policy domain="coder" rights="none" pattern="PS3" />
<policy domain="coder" rights="none" pattern="EPS" />
<policy domain="coder" rights="none" pattern="PDF" />
<policy domain="coder" rights="none" pattern="XPS" />
Named exports:
Let's say you create a file called utils.js
, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:
export function add(x, y) {
return x + y
}
export function mutiply(x, y) {
return x * y
}
Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:
import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.
Or if you prefer, place the entire module's contents under a common namespace:
import * as utils from './utils.js';
...
utils.multiply(2,3)
Default exports:
If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js
, with only one function that logs out whatever argument it's called with:
export default function log(message) {
console.log(message);
}
This can now be used like this:
import log from './log.js';
...
log('test') // Would print 'test' in the console.
You don't have to call it log
when you import it, you could actually call it whatever you want:
import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.
Combined:
A module can have both a default export (max 1), and named exports (imported either one by one, or using *
with an alias). React actually has this, consider:
import React, { Component, PropTypes } from 'react';
I'm not sure what you mean by "then again by the parser". After the splitting has been done, there's no further traversal of the string, only a traversal of the list of split strings. This will probably actually be the fastest way to accomplish this, so long as the size of your string isn't absolutely huge. The fact that python uses immutable strings means that you must always create a new string, so this has to be done at some point anyway.
If your string is very large, the disadvantage is in memory usage: you'll have the original string and a list of split strings in memory at the same time, doubling the memory required. An iterator approach can save you this, building a string as needed, though it still pays the "splitting" penalty. However, if your string is that large, you generally want to avoid even the unsplit string being in memory. It would be better just to read the string from a file, which already allows you to iterate through it as lines.
However if you do have a huge string in memory already, one approach would be to use StringIO, which presents a file-like interface to a string, including allowing iterating by line (internally using .find to find the next newline). You then get:
import StringIO
s = StringIO.StringIO(myString)
for line in s:
do_something_with(line)
Regarding @Cherian's answer, the following lines can be removed:
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ANSI';
...
SET SQL_MODE=@OLD_SQL_MODE;
...
This was a bug pre 5.1.23. After that version these are no longer required. So, for copy/paste convenience, here is the same with the above lines removed. Again, for example purposes "test" is the user and "databaseName" is the database; and this was from this bug.
DROP PROCEDURE IF EXISTS databaseName.drop_user_if_exists ;
DELIMITER $$
CREATE PROCEDURE databaseName.drop_user_if_exists()
BEGIN
DECLARE foo BIGINT DEFAULT 0 ;
SELECT COUNT(*)
INTO foo
FROM mysql.user
WHERE User = 'test' and Host = 'localhost';
IF foo > 0 THEN
DROP USER 'test'@'localhost' ;
END IF;
END ;$$
DELIMITER ;
CALL databaseName.drop_user_if_exists() ;
DROP PROCEDURE IF EXISTS databaseName.drop_users_if_exists ;
CREATE USER 'test'@'localhost' IDENTIFIED BY 'a';
GRANT ALL PRIVILEGES ON databaseName.* TO 'test'@'localhost'
WITH GRANT OPTION
If I understand your question correctly, then you probably want a density estimate along with the histogram:
X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE) # prob=TRUE for probabilities not counts
lines(density(X)) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted") # add another "smoother" density
Edit a long while later:
Here is a slightly more dressed-up version:
X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2)
along with the graph it produces:
I have now come up with an own solution to this:
1. Created a general function to extract specific attributes from arrays
The function below extract only specific attributes from an associative array, or an array of associative arrays (the last is what you get when doing $collection->toArray() in Laravel).
It can be used like this:
$data = array_extract( $collection->toArray(), ['id','url'] );
I am using the following functions:
function array_is_assoc( $array )
{
return is_array( $array ) && array_diff_key( $array, array_keys(array_keys($array)) );
}
function array_extract( $array, $attributes )
{
$data = [];
if ( array_is_assoc( $array ) )
{
foreach ( $attributes as $attribute )
{
$data[ $attribute ] = $array[ $attribute ];
}
}
else
{
foreach ( $array as $key => $values )
{
$data[ $key ] = [];
foreach ( $attributes as $attribute )
{
$data[ $key ][ $attribute ] = $values[ $attribute ];
}
}
}
return $data;
}
This solution does not focus on performance implications on looping through the collections in large datasets.
2. Implement the above via a custom collection i Laravel
Since I would like to be able to simply do $collection->extract('id','url');
on any collection object, I have implemented a custom collection class.
First I created a general Model, which extends the Eloquent model, but uses a different collection class. All you models need to extend this custom model, and not the Eloquent Model then.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Lib\Collection;
class Model extends EloquentModel
{
public function newCollection(array $models = [])
{
return new Collection( $models );
}
}
?>
Secondly I created the following custom collection class:
<?php
namespace Lib;
use Illuminate\Support\Collection as EloquentCollection;
class Collection extends EloquentCollection
{
public function extract()
{
$attributes = func_get_args();
return array_extract( $this->toArray(), $attributes );
}
}
?>
Lastly, all models should then extend your custom model instead, like such:
<?php
namespace App\Models;
class Article extends Model
{
...
Now the functions from no. 1 above are neatly used by the collection to make the $collection->extract()
method available.
You mentioned you're using Ruby on Rails as a backend. You didn't post the code for the relevant method, but my guess is that it looks something like this:
def create
post = Post.create params[:post]
respond_to do |format|
format.json { render :json => post }
end
end
Change it to:
def create
post = Post.create params[:post])
render :json => post
end
And it will solve your problem. It worked for me :)
Create a Virtual Machine with Windows running on it and download the file to a shared folder. :-D
NOTE: This answer has gotten so much attention, that I need to update it. Since the original answer was posted, the comment from @dzeikei has gotten almost as much attention as the original answer. So here are 2 possible solutions:
1. If your background thread has a reference to a Context
object:
Make sure that your background worker threads have access to a Context object (can be the Application context or the Service context). Then just do this in the background worker thread:
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {....} // This is your code
};
mainHandler.post(myRunnable);
2. If your background thread does not have (or need) a Context
object
(suggested by @dzeikei):
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {....} // This is your code
};
mainHandler.post(myRunnable);
Actually an other way to solve this could be, overwriting the CSS with insertRule
.
It gives the ability to inject CSS rules to an existing/new stylesheet. In my concrete example it would look like this:
//creates a new `style` element in the document
var sheet = (function(){
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
//add the actual rules to it
sheet.insertRule(
"ul#mainFilter a:hover { color: #0000EE }" , 0
);
Demo with my 4 years old original example: http://jsfiddle.net/raPeX/21/
To your question whether the map was like a bucket: no.
It's like a list with name=value
pairs whereas name
doesn't need to be a String (it can, though).
To get an element, you pass your key to the get()-method which gives you the assigned object in return.
And a Hashmap means that if you're trying to retrieve your object using the get-method, it won't compare the real object to the one you provided, because it would need to iterate through its list and compare() the key you provided with the current element.
This would be inefficient. Instead, no matter what your object consists of, it calculates a so called hashcode from both objects and compares those. It's easier to compare two int
s instead of two entire (possibly deeply complex) objects. You can imagine the hashcode like a summary having a predefined length (int), therefore it's not unique and has collisions. You find the rules for the hashcode in the documentation to which I've inserted the link.
If you want to know more about this, you might wanna take a look at articles on javapractices.com and technofundo.com
regards
I have created Django Simple Mail to have a simple, customizable and reusable template for every transactional email you would like to send.
Emails contents and templates can be edited directly from django's admin.
With your example, you would register your email :
from simple_mail.mailer import BaseSimpleMail, simple_mailer
class WelcomeMail(BaseSimpleMail):
email_key = 'welcome'
def set_context(self, user_id, welcome_link):
user = User.objects.get(id=user_id)
return {
'user': user,
'welcome_link': welcome_link
}
simple_mailer.register(WelcomeMail)
And send it this way :
welcome_mail = WelcomeMail()
welcome_mail.set_context(user_id, welcome_link)
welcome_mail.send(to, from_email=None, bcc=[], connection=None, attachments=[],
headers={}, cc=[], reply_to=[], fail_silently=False)
I would love to get any feedback.
You should be using iostream
without the .h
.
Early implementations used the .h
variants but the standard mandates the more modern style.
break x if ((int)strcmp(y, "hello")) == 0
On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!
The exception you get is telling you filedialog
is not in your namespace.
filedialog
(and btw messagebox
) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *
>>> filedialog
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'filedialog' is not defined
>>>
you should use for example:
>>> from tkinter import filedialog
>>> filedialog
<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>
>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
class MyFrame(Frame):
def __init__(self):
Frame.__init__(self)
self.master.title("Example")
self.master.rowconfigure(5, weight=1)
self.master.columnconfigure(5, weight=1)
self.grid(sticky=W+E+N+S)
self.button = Button(self, text="Browse", command=self.load_file, width=10)
self.button.grid(row=1, column=0, sticky=W)
def load_file(self):
fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
("HTML files", "*.html;*.htm"),
("All files", "*.*") ))
if fname:
try:
print("""here it comes: self.settings["template"].set(fname)""")
except: # <- naked except is a bad idea
showerror("Open Source File", "Failed to read file\n'%s'" % fname)
return
if __name__ == "__main__":
MyFrame().mainloop()
Here is my version of Mattrs solution in Swift for injecting all cookies from HTTPCookieStorage. This was done mainly to inject an authentication cookie to create a user session.
public func setupWebView() {
let userContentController = WKUserContentController()
if let cookies = HTTPCookieStorage.shared.cookies {
let script = getJSCookiesString(for: cookies)
let cookieScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: false)
userContentController.addUserScript(cookieScript)
}
let webViewConfig = WKWebViewConfiguration()
webViewConfig.userContentController = userContentController
self.webView = WKWebView(frame: self.webViewContainer.bounds, configuration: webViewConfig)
}
///Generates script to create given cookies
public func getJSCookiesString(for cookies: [HTTPCookie]) -> String {
var result = ""
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
for cookie in cookies {
result += "document.cookie='\(cookie.name)=\(cookie.value); domain=\(cookie.domain); path=\(cookie.path); "
if let date = cookie.expiresDate {
result += "expires=\(dateFormatter.stringFromDate(date)); "
}
if (cookie.secure) {
result += "secure; "
}
result += "'; "
}
return result
}
Do this: Step 1: Your String
String str = ";;;;;;\n" +
"Name, number, address;;;;;;\n" +
"01.01.12-16.02.12;;;;;;\n" +
";;;;;;\n" +
";;;;;;";
Step 2: Just replace all "\n" with "%n" the result looks like this
String str = ";;;;;;%n" +
"Name, number, address;;;;;;%n" +
"01.01.12-16.02.12;;;;;;%n" +
";;;;;;%n" +
";;;;;;";
Notice I've just put "%n" in place of "\n"
Step 3: Now simply call format()
str=String.format(str);
That's all you have to do.
You have to use Objective C to interface with the Cocoa API, so there is no choice. Of course, you can use as much C++ as you like behind the scenes (Objective C++ makes this easy).
It is an insane language indeed, but it's also... kind of fun to use once you're a bit used to it. :-)
Casting int to char is done simply by assigning with the type in parenthesis:
int i = 65535;
char c = (char)i;
Note: I thought that you might be losing data (as in the example), because the type sizes are different.
Appending characters to characters cannot be done (unless you mean arithmetics, then it's simple operators). You need to use strings, AKA arrays of characters, and <string.h>
functions like strcat
or sprintf
.
Maybe std::ostream_iterator
and std::ostringstream
:
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>
int main()
{
std::vector<int> vec;
vec.push_back(1);
vec.push_back(4);
vec.push_back(7);
vec.push_back(4);
vec.push_back(9);
vec.push_back(7);
std::ostringstream oss;
if (!vec.empty())
{
// Convert all but the last element to avoid a trailing ","
std::copy(vec.begin(), vec.end()-1,
std::ostream_iterator<int>(oss, ","));
// Now add the last element with no delimiter
oss << vec.back();
}
std::cout << oss.str() << std::endl;
}
Just use var = var1 var2
and it will automatically concatenate the vars var1
and var2
:
awk '{new_var=$1$2; print new_var}' file
You can put an space in between with:
awk '{new_var=$1" "$2; print new_var}' file
Which in fact is the same as using FS
, because it defaults to the space:
awk '{new_var=$1 FS $2; print new_var}' file
$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
hellohow
iam
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am
You can play around with it in ideone: http://ideone.com/4u2Aip
C#
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
...
[ValidateModel]
public HttpResponseMessage Post([FromBody]AnyModel model)
{
Javascript
$.ajax({
type: "POST",
url: "/api/xxxxx",
async: 'false',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
error: function (xhr, status, err) {
if (xhr.status == 400) {
DisplayModelStateErrors(xhr.responseJSON.ModelState);
}
},
....
function DisplayModelStateErrors(modelState) {
var message = "";
var propStrings = Object.keys(modelState);
$.each(propStrings, function (i, propString) {
var propErrors = modelState[propString];
$.each(propErrors, function (j, propError) {
message += propError;
});
message += "\n";
});
alert(message);
};
Use the matplotlib savefig
function with the keyword argument transparent=True
to save the image as a png file.
In [30]: x = np.linspace(0,6,31)
In [31]: y = np.exp(-0.5*x) * np.sin(x)
In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]
In [33]: savefig('demo.png', transparent=True)
Result:
Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display
command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.
In my case, I had an already removed SDCard still registered in Android. So I longpressed the entry for my old SDCard under:
Settings | Storage & USB
and selected "Forget".
Afterwards a normal
adb push myfile.zip /sdcard/
worked fine.
I found a caveat that no one so far has mentioned. I don't know if it will come up often in practical situations, but here it is for the sake of completeness.
Usually, calculating a number modulo infinity returns itself as a float, but a fraction modulo infinity returns nan
(not a number). Here is an example:
>>> from fractions import Fraction
>>> from math import inf
>>> 3 % inf
3.0
>>> 3.5 % inf
3.5
>>> Fraction('1/3') % inf
nan
I filed an issue on the Python bug tracker. It can be seen at https://bugs.python.org/issue32968.
Update: this will be fixed in Python 3.8.
As stated in an article by Slicehost:
User setup
So let's start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
groups ... # demo www-data
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let's set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the 'www-data' group.
The first command will change the permissions for the public_html directory to include the "setgid" bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
The total columns in a row has to add up to 12. So you can do col-md-4 col-md-offset-4. So your breaking up your columns into 3 groups of 4 columns each. Right now you have a 4 column form with an offset by 6 so you are only getting 2 columns to the right side of your form. You can also do col-md-8 col-md-offset-2 which would give you a 8 column form with 2 columns each of space left and right or col-md-6 col-md-offset-3 (6 column form with 3 columns space on each side), etc.
I found a simple difference that hasn't been addressed in this thread.
If you're doing all the ScrollToCarat()
calls as part of your form's Load()
event, it doesn't work. I just added my ScrollToCarat()
call to my form's Activated()
event, and it works fine.
Edit
It's important to only do this scrolling the first time form's Activated
event is fired (not on subsequent activations), or it will scroll every time your form is activated, which is something you probably don't want.
So if you're only trapping the Activated()
event to scroll your text when your program loads, then you can just unsubscribe to the event inside the event handler itself, thusly:
Activated -= new System.EventHandler(this.Form1_Activated);
If you have other things you need to do each time your form is activated, you can set a bool
to true the first time your Activated()
event is fired, so you don't scroll on subsequent activations, but can still do the other things you need to do.
Also, if your TextBox
is on a tab that isn't the SelectedTab
, ScrollToCarat()
will have no effect. So you need at least make it the selected tab while you're scrolling. You can wrap the code in a YourTab.SuspendLayout();
and YourTab.ResumeLayout(false);
pair if your form flickers when you do this.
End of edit
Hope this helps!
FYI, this is not an answer to the post. But it may help future users who may get the error with the message:
TypeError: 'builtin_function_or_method' object is not subscriptable
In my case, it was occurred due to bad indentation.
Just indenting the line of code solved the issue.
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
For me worked this way:
private ListView yourListViewName;
private List<YourClassName> yourListName;
...
yourListName = new ArrayList<>();
yourAdapterName = new yourAdapterName(this, R.layout.your_layout_name, yourListName);
...
if (yourAdapterName.getCount() > 0) {
yourAdapterName.clear();
yourAdapterName.notifyDataSetChanged();
}
yourAdapterName.add(new YourClassName(yourParameter1, yourParameter2, ...));
yourListViewName.setAdapter(yourAdapterName);
And I would say the "pythonic" way to get lines without trailing newline characters is splitlines().
>>> text = "line 1\nline 2\r\nline 3\nline 4"
>>> text.splitlines()
['line 1', 'line 2', 'line 3', 'line 4']
I had a NavLink that I wanted to when clicked will scroll to that element like named anchor does. I implemented it this way.
<NavLink onClick={() => this.scrollToHref('plans')}>Our Plans</NavLink>
scrollToHref = (element) =>{
let node;
if(element === 'how'){
node = ReactDom.findDOMNode(this.refs.how);
console.log(this.refs)
}else if(element === 'plans'){
node = ReactDom.findDOMNode(this.refs.plans);
}else if(element === 'about'){
node = ReactDom.findDOMNode(this.refs.about);
}
node.scrollIntoView({block: 'start', behavior: 'smooth'});
}
I then give the component I wanted to scroll to a ref like this
<Investments ref="plans"/>
The following permissions and features are necessary in the AndroidManifest.xml file without which you will get the following dialog box
"It seems that your device does not support camera (or it is locked). Application will be closed"
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>
You can actually just use
$("#form").attr("target", "NewAction");
As far as I know, this will NOT fail silently.
If the page is opening in a new target, you may need to make sure the URL is unique each time because Webkit (chrome/safari) will cache the fact you have visited that URL and won't perform the post.
For example
$("form").attr("action", "/Pages/GeneratePreview?" + new Date().getMilliseconds());
First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:
I would use an anonymous type filled with your results
type:
string json = JsonConvert.SerializeObject(new
{
results = new List<Result>()
{
new Result { id = 1, value = "ABC", info = "ABC" },
new Result { id = 2, value = "JKL", info = "JKL" }
}
});
Also, note that the generated JSON has result items with id
s of type Number
instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id
to string
in the C#.
I'd also tweak your results
type and get rid of the backing fields:
public class Result
{
public int id { get ;set; }
public string value { get; set; }
public string info { get; set; }
}
Furthermore, classes conventionally are PascalCased
and not camelCased
.
Here's the generated JSON from the code above:
{
"results": [
{
"id": 1,
"value": "ABC",
"info": "ABC"
},
{
"id": 2,
"value": "JKL",
"info": "JKL"
}
]
}
If, like me, you found that @wiggin answer didn't work and images still did not appear in-line, you can use the 'align' property of the html image tag and some breaks to achieve the desired effect, for example:
# Title
<img align="left" src="./documentation/images/A.jpg" alt="Made with Angular" title="Angular" hspace="20"/>
<img align="left" src="./documentation/images/B.png" alt="Made with Bootstrap" title="Bootstrap" hspace="20"/>
<img align="left" src="./documentation/images/C.png" alt="Developed using Browsersync" title="Browsersync" hspace="20"/>
<br/><br/><br/><br/><br/>
## Table of Contents...
Obviously, you have to use more breaks depending on how big the images are: awful yes, but it worked for me so I thought I'd share.
You can use an optional parameter of JSON.stringify()
JSON.stringify(value[, replacer [, space]])
Parameters
- value The value to convert to a JSON string.
- replacer If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string. A detailed description of the replacer function is provided in the javaScript guide article Using native JSON.
- space Causes the resulting string to be pretty-printed.
For example:
JSON.stringify({a:1,b:2,c:{d:3, e:4}},null," ")
will give you following result:
"{
"a": 1,
"b": 2,
"c": {
"d": 3,
"e": 4
}
}"
date must be insert with two apostrophes' As example if the date is 2018/10/20. It can insert from these query
Query -
insert into run(id,name,dob)values(&id,'&name','2018-10-20')
Target the element you wish to change and use !important
to overwrite any existing styles that are assigned to that element. Be sure not to use the !important
declaration when it is not absolutely necessary.
div.navbar div.navbar-inner ul.nav a:hover {
color: #fff !important;
}
`e` in ['a', 'b', 'c'] # evaluates as False
`b` in ['a', 'b', 'c'] # evaluates as True
EDIT: With the clarification, new answer:
Note that PHP arrays are vastly different from Python's, combining arrays and dicts into one confused structure. Python arrays always have indices from 0
to len(arr) - 1
, so you can check whether your index is in that range. try/catch
is a good way to do it pythonically, though.
If you're asking about the hash functionality of PHP "arrays" (Python's dict
), then my previous answer still kind of stands:
`baz` in {'foo': 17, 'bar': 19} # evaluates as False
`foo` in {'foo': 17, 'bar': 19} # evaluates as True
Just in case, this might help someone like me.
I had this same issue in Unity 3D. I was attempting to use the emulators from Android Studio.
So I enabled Target Architecture->x86 Architecture
(although deprecated) in Player Settings and it worked!
If loading via pip install mysql-connector
and leads an error Unable to find Protobuf include directory
then this would be useful pip install mysql-connector==2.1.4
mysql-connector
is obsolete, so use pip install mysql-connector-python
. Same here
Make sure you image is a relative path such as:
@Url.Content("~/Content/images/myimage.png")
MVC4
<img src="~/Content/images/myimage.png" />
You could convert the byte[]
into a Base64
string
on the fly.
string base64String = Convert.ToBase64String(imageBytes);
<img src="@String.Format("data:image/png;base64,{0}", base64string)" />
Check code behind information, provided in global.asax. They should correctly point to the class in its code behind.
sample global.asax:
<%@ Application Codebehind="Global.asax.cs" Inherits="MyApplicationNamespace.MyMvcApplication" Language="C#" %>
sample code behind:
namespace MyApplicationNamespace
{
public class MyMvcApplication : System.Web.HttpApplication
{
protected void Application_Start( )
{
AreaRegistration.RegisterAllAreas( );
FilterConfig.RegisterGlobalFilters( GlobalFilters.Filters );
RouteConfig.RegisterRoutes( RouteTable.Routes );
BundleConfig.RegisterBundles( BundleTable.Bundles );
}
}
}
You need to switch single quotes [']
to double quotes ["]
because of parse
if you are using data-order attribute on the table then use it like this data-order='[[1, "asc"]]'
This is the best I've found for teaching new programmers, and without using additional libraries. I'd like something better though.
def initialize_twodlist(value):
list=[]
for row in range(10):
list.append([value]*10)
return list
This site gives some options on vertically centering your div: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
@SophieAlpert is right, +1, I just want to provide a modified version of her solution, without jQuery, based on this answer.
var WindowDimensions = React.createClass({
render: function() {
return <span>{this.state.width} x {this.state.height}</span>;
},
updateDimensions: function() {
var w = window,
d = document,
documentElement = d.documentElement,
body = d.getElementsByTagName('body')[0],
width = w.innerWidth || documentElement.clientWidth || body.clientWidth,
height = w.innerHeight|| documentElement.clientHeight|| body.clientHeight;
this.setState({width: width, height: height});
// if you are using ES2015 I'm pretty sure you can do this: this.setState({width, height});
},
componentWillMount: function() {
this.updateDimensions();
},
componentDidMount: function() {
window.addEventListener("resize", this.updateDimensions);
},
componentWillUnmount: function() {
window.removeEventListener("resize", this.updateDimensions);
}
});
If like me you just updated your password and ran
git push
to run into this issue, then there's a super easy fix.
For Mac users only. You need to delete your OSX Keychain access entries for GitHub. You can do it via terminal by running the following commands.
Through the command line, you can use the credential helper directly to erase the keychain entry.
To do this, type the following command:
git credential-osxkeychain erase
host=github.com
protocol=https
# [Now Press Return]
If it's successful, nothing will print out. To test that it works, try and clone a repository from GitHub or run your previous action again like in my case git push
. If you are prompted for a password, the keychain entry was deleted.
I don't think so. The API's will provide access to delayed quotes, there is no way that real time data or tick data, will be provided for free.
This is the way I would do it : saying that "list" is a <List<t>>
where t is a class with a Name and a Value field; but of course you can do it with any other class type.
list = list.Where(c=>c.Name == "height")
.Select( new t(){Name = c.Name, Value = 30})
.Union(list.Where(c=> c.Name != "height"))
.ToList();
This works perfectly ! It's a simple linq expression without any loop logic. The only thing you should be aware is that the order of the lines in the result dataset will be different from the order you had in the source dataset. So if sorting is important to you, just reproduce the same order by clauses in the final linq query.
I had the same issue and tried almost everything then found after I came to know I was trying it in the wrong block. I was trying it in steps block whereas it needs to be in the environment block.
stage('Release') {
environment {
my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
}
steps {
println my_var
}
}
But you might also want to look into a very different approach, listening for file-system events.
I found James Wald's answer the closest to my solution, except instead of "File->Import->General->Existing Projects into Workspace" (which did not work for me at all) I used "File->Import->Android->Existing Android Code Into Workspace". I am using Helios, maybe your version of Eclipse does not have this quirk.
Short answer (asked version): (format 3.33.20150710.182906)
Please, simple use a makefile
with:
MAJOR = 3
MINOR = 33
BUILD = $(shell date +"%Y%m%d.%H%M%S")
VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
CPPFLAGS = -DVERSION=$(VERSION)
program.x : source.c
gcc $(CPPFLAGS) source.c -o program.x
and if you don't want a makefile
, shorter yet, just compile with:
gcc source.c -o program.x -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"
Short answer (suggested version): (format 150710.182906)
Use a double
for version number:
MakeFile:
VERSION = $(shell date +"%g%m%d.%H%M%S")
CPPFLAGS = -DVERSION=$(VERSION)
program.x : source.c
gcc $(CPPFLAGS) source.c -o program.x
Or a simple bash command:
$ gcc source.c -o program.x -DVERSION=$(date +"%g%m%d.%H%M%S")
Tip:
Still don't like makefile
or is it just for a not-so-small test program? Add this line:
export CPPFLAGS='-DVERSION='$(date +"%g%m%d.%H%M%S")
to your ~/.profile
, and remember compile with gcc $CPPFLAGS ...
Long answer:
I know this question is older, but I have a small contribution to make. Best practice is always automatize what otherwise can became a source of error (or oblivion).
I was used to a function that created the version number for me. But I prefer this function to return a float
. My version number can be printed by: printf("%13.6f\n", version());
which issues something like: 150710.150411
(being Year (2 digits) month day DOT hour minute seconds).
But, well, the question is yours. If you prefer "major.minor.date.time", it will have to be a string. (Trust me, double is better. If you insist in a major, you can still use double if you set the major and let the decimals to be date+time, like: major.datetime = 1.150710150411
Lets get to business. The example bellow will work if you compile as usual, forgetting to set it, or use -DVERSION
to set the version directly from shell, but better of all, I recommend the third option: use a makefile
.
Three forms of compiling and the results:
Using make:
beco> make program.x
gcc -Wall -Wextra -g -O0 -ansi -pedantic-errors -c -DVERSION="\"3.33.20150710.045829\"" program.c -o program.o
gcc program.o -o program.x
Running:
__DATE__: 'Jul 10 2015'
__TIME__: '04:58:29'
VERSION: '3.33.20150710.045829'
Using -DVERSION:
beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=\"2.22.$(date +"%Y%m%d.%H%M%S")\"
Running:
__DATE__: 'Jul 10 2015'
__TIME__: '04:58:37'
VERSION: '2.22.20150710.045837'
Using the build-in function:
beco> gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors
Running:
__DATE__: 'Jul 10 2015'
__TIME__: '04:58:43'
VERSION(): '1.11.20150710.045843'
Source code
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4
5 #define FUNC_VERSION (0)
6 #ifndef VERSION
7 #define MAJOR 1
8 #define MINOR 11
9 #define VERSION version()
10 #undef FUNC_VERSION
11 #define FUNC_VERSION (1)
12 char sversion[]="9999.9999.20150710.045535";
13 #endif
14
15 #if(FUNC_VERSION)
16 char *version(void);
17 #endif
18
19 int main(void)
20 {
21
22 printf("__DATE__: '%s'\n", __DATE__);
23 printf("__TIME__: '%s'\n", __TIME__);
24
25 printf("VERSION%s: '%s'\n", (FUNC_VERSION?"()":""), VERSION);
26 return 0;
27 }
28
29 /* String format: */
30 /* __DATE__="Oct 8 2013" */
31 /* __TIME__="00:13:39" */
32
33 /* Version Function: returns the version string */
34 #if(FUNC_VERSION)
35 char *version(void)
36 {
37 const char data[]=__DATE__;
38 const char tempo[]=__TIME__;
39 const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
40 char omes[4];
41 int ano, mes, dia, hora, min, seg;
42
43 if(strcmp(sversion,"9999.9999.20150710.045535"))
44 return sversion;
45
46 if(strlen(data)!=11||strlen(tempo)!=8)
47 return NULL;
48
49 sscanf(data, "%s %d %d", omes, &dia, &ano);
50 sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
51 mes=(strstr(nomes, omes)-nomes)/3+1;
52 sprintf(sversion,"%d.%d.%04d%02d%02d.%02d%02d%02d", MAJOR, MINOR, ano, mes, dia, hora, min, seg);
53
54 return sversion;
55 }
56 #endif
Please note that the string is limited by MAJOR<=9999
and MINOR<=9999
. Of course, I set this high value that will hopefully never overflow. But using double
is still better (plus, it's completely automatic, no need to set MAJOR
and MINOR
by hand).
Now, the program above is a bit too much. Better is to remove the function completely, and guarantee that the macro VERSION
is defined, either by -DVERSION
directly into GCC command line (or an alias that automatically add it so you can't forget), or the recommended solution, to include this process into a makefile
.
Here it is the makefile
I use:
MakeFile source:
1 MAJOR = 3
2 MINOR = 33
3 BUILD = $(shell date +"%Y%m%d.%H%M%S")
4 VERSION = "\"$(MAJOR).$(MINOR).$(BUILD)\""
5 CC = gcc
6 CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors
7 CPPFLAGS = -DVERSION=$(VERSION)
8 LDLIBS =
9
10 %.x : %.c
11 $(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@
A better version with DOUBLE
Now that I presented you "your" preferred solution, here it is my solution:
Compile with (a) makefile or (b) gcc directly:
(a) MakeFile:
VERSION = $(shell date +"%g%m%d.%H%M%S")
CC = gcc
CFLAGS = -Wall -Wextra -g -O0 -ansi -pedantic-errors
CPPFLAGS = -DVERSION=$(VERSION)
LDLIBS =
%.x : %.c
$(CC) $(CFLAGS) $(CPPFLAGS) $(LDLIBS) $^ -o $@
(b) Or a simple bash command:
$ gcc program.c -o program.x -Wall -Wextra -g -O0 -ansi -pedantic-errors -DVERSION=$(date +"%g%m%d.%H%M%S")
Source code (double version):
#ifndef VERSION
#define VERSION version()
#endif
double version(void);
int main(void)
{
printf("VERSION%s: '%13.6f'\n", (FUNC_VERSION?"()":""), VERSION);
return 0;
}
double version(void)
{
const char data[]=__DATE__;
const char tempo[]=__TIME__;
const char nomes[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
char omes[4];
int ano, mes, dia, hora, min, seg;
char sversion[]="130910.001339";
double fv;
if(strlen(data)!=11||strlen(tempo)!=8)
return -1.0;
sscanf(data, "%s %d %d", omes, &dia, &ano);
sscanf(tempo, "%d:%d:%d", &hora, &min, &seg);
mes=(strstr(nomes, omes)-nomes)/3+1;
sprintf(sversion,"%04d%02d%02d.%02d%02d%02d", ano, mes, dia, hora, min, seg);
fv=atof(sversion);
return fv;
}
Note: this double function is there only in case you forget to define macro VERSION. If you use a makefile
or set an alias gcc gcc -DVERSION=$(date +"%g%m%d.%H%M%S")
, you can safely delete this function completely.
Well, that's it. A very neat and easy way to setup your version control and never worry about it again!
Please do not mark this response as correct as smitec has already answered correctly. I'm including a convenience function I keep in my .First library that makes converting a windows path to the format that works in R (the methods described by Sacha Epskamp). Simply copy the path to your clipboard (ctrl + c) and then run the function as pathPrep()
. No need for an argument. The path is printed to your console correctly and written to your clipboard for easy pasting to a script. Hope this is helpful.
pathPrep <- function(path = "clipboard") {
y <- if (path == "clipboard") {
readClipboard()
} else {
cat("Please enter the path:\n\n")
readline()
}
x <- chartr("\\", "/", y)
writeClipboard(x)
return(x)
}
Count()
is an extension method introduced by LINQ while the Count
property is part of the List itself (derived from ICollection
). Internally though, LINQ checks if your IEnumerable
implements ICollection
and if it does it uses the Count
property. So at the end of the day, there's no difference which one you use for a List
.
To prove my point further, here's the code from Reflector for Enumerable.Count()
public static int Count<TSource>(this IEnumerable<TSource> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
ICollection<TSource> is2 = source as ICollection<TSource>;
if (is2 != null)
{
return is2.Count;
}
int num = 0;
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
num++;
}
}
return num;
}
If you're using long lists, it appears the list comprehension's faster, not to mention more readable.
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "list(enumerate(mylist))"
1000000 loops, best of 3: 1.61 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[(i, j) for i, j in enumerate(mylist)]"
1000000 loops, best of 3: 0.978 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[t for t in enumerate(mylist)]"
1000000 loops, best of 3: 0.767 usec per loop
This reddit post helped me: https://www.reddit.com/r/swift/comments/4o8atc/xcode_8_which_swift/d4anpet
Xcode 8 uses Swift 3.0 as default. But you can turn on Swift 2.3. Go to project's Build Settings and set 'Use Legacy Swift Language Version' to YES.
Good old reddit :)
I just wanted to add an additional option: In your input add the form tag and specify the name of a form that doesn't exist on your page:
<input form="fakeForm" type="text" readonly value="random value" />
Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?
You can't, it has to start with elevated privileges. You can restart it with the runas
verb, which will prompt the user to switch to admin mode
static void RestartAsAdmin()
{
var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
Process.Start(startInfo);
Environment.Exit(0);
}
EDIT: actually, that's not true; HttpListener can run without elevated privileges, but you need to give permission for the URL on which you want to listen. See Darrel Miller's answer for details.
You can use - matplotlib.gridspec.GridSpec
Check - https://matplotlib.org/stable/api/_as_gen/matplotlib.gridspec.GridSpec.html
The below code displays a heatmap on right and an Image on left.
#Creating 1 row and 2 columns grid
gs = gridspec.GridSpec(1, 2)
fig = plt.figure(figsize=(25,3))
#Using the 1st row and 1st column for plotting heatmap
ax=plt.subplot(gs[0,0])
ax=sns.heatmap([[1,23,5,8,5]],annot=True)
#Using the 1st row and 2nd column to show the image
ax1=plt.subplot(gs[0,1])
ax1.grid(False)
ax1.set_yticklabels([])
ax1.set_xticklabels([])
#The below lines are used to display the image on ax1
image = io.imread("https://images-na.ssl-images- amazon.com/images/I/51MvhqY1qdL._SL160_.jpg")
plt.imshow(image)
plt.show()
Very ugly but does the trick if you only want compile time info (e.g. for debugging):
auto testVar = std::make_tuple(1, 1.0, "abc");
decltype(testVar)::foo= 1;
Returns:
Compilation finished with errors:
source.cpp: In function 'int main()':
source.cpp:5:19: error: 'foo' is not a member of 'std::tuple<int, double, const char*>'
You can use the following workaround to also include comma as a valid input:-
Through XML:
<EditText
android:inputType="number"
android:digits="0123456789.," />
Programmatically:
EditText input = new EditText(THE_CONTEXT);
input.setKeyListener(DigitsKeyListener.getInstance("0123456789.,"));
In this way Android system will show the numbers' keyboard and allow the input of comma. Hope this answers the question :)
Use \0
.
color: green\0;
I however do recommend conditional comments since you'd like to exclude IE9 as well and it's yet unpredictable whether this hack will affect IE9 as well or not.
Regardless, I've never had the need for an IE8 specific hack. What is it, the IE8 specific problem which you'd like to solve? Is it rendering in IE8 standards mode anyway? Its renderer is pretty good.
JPEG can't support transparency because it uses RGB color space. If you want transparency use a format that supports alpha values. Example PNG is an image format that uses RGBA color space where (r = red, g = green, b = blue, a = alpha value). Alpha value is used as an opacity measure, 0% is fully transparent and 100% is completely opaque. pixel.
Action Sheet in iOS10 with Swift3.0. Follow this link.
@IBAction func ShowActionSheet(_ sender: UIButton) {
// Create An UIAlertController with Action Sheet
let optionMenuController = UIAlertController(title: nil, message: "Choose Option from Action Sheet", preferredStyle: .actionSheet)
// Create UIAlertAction for UIAlertController
let addAction = UIAlertAction(title: "Add", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Add")
})
let saveAction = UIAlertAction(title: "Edit", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Edit")
})
let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Delete")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancel")
})
// Add UIAlertAction in UIAlertController
optionMenuController.addAction(addAction)
optionMenuController.addAction(saveAction)
optionMenuController.addAction(deleteAction)
optionMenuController.addAction(cancelAction)
// Present UIAlertController with Action Sheet
self.present(optionMenuController, animated: true, completion: nil)
}
Did you try to allow it for this directory via .htaccess?
Options +Indexes
I use this for some of my directories where directory listing is disabled by my provider
If you don't want to create a new dataframe, or if your dataframe has more columns than just the ones you want to split, you could:
df["flips"], df["row_name"] = zip(*df["row"].str.split().tolist())
del df["row"]
The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
In fact, when using generic on interface, the keyword is also extends. Here is the code example:
There are 2 classes that implements the Greeting interface:
interface Greeting {
void sayHello();
}
class Dog implements Greeting {
@Override
public void sayHello() {
System.out.println("Greeting from Dog: Hello ");
}
}
class Cat implements Greeting {
@Override
public void sayHello() {
System.out.println("Greeting from Cat: Hello ");
}
}
And the test code:
@Test
public void testGeneric() {
Collection<? extends Greeting> animals;
List<Dog> dogs = Arrays.asList(new Dog(), new Dog(), new Dog());
List<Cat> cats = Arrays.asList(new Cat(), new Cat(), new Cat());
animals = dogs;
for(Greeting g: animals) g.sayHello();
animals = cats;
for(Greeting g: animals) g.sayHello();
}
This is a step I use with ubuntu. It will allow you to insert more than 45 characters from your input but MySQL will cut your text to 45 characters to insert into the database.
Run command
sudo nano /etc/mysql/my.cnf
Then paste this code
[mysqld] sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
restart MySQL
sudo service mysql restart;
Why are you specifying myFile
there?
Git revert reverts the commit(s) that you specify.
git revert HEAD~2
reverts the HEAD~2
commit
git revert HEAD~2 myfile
reverts HEAD~2
AND myFile
I take myFile
is a file that you want to revert? In that case use
git checkout HEAD~2 -- myFile
I found this for online php validation:-
http://www.icosaedro.it/phplint/phplint-on-line.html
Hope this helps.
Another way with ES5 is to explicitely traverse the prototype chain using Object.getPrototypeOf(this)
const speaker = {
speak: () => console.log('the speaker has spoken')
}
const announcingSpeaker = Object.create(speaker, {
speak: {
value: function() {
console.log('Attention please!')
Object.getPrototypeOf(this).speak()
}
}
})
announcingSpeaker.speak()
try this
html code
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="firstname">
<input type="submit" name="submit" value="Submit">
</form>
php code:
if(isset($_POST['Submit'])){
$firstname=isset($_POST['firstname'])?$_post['firstname']:"";
echo $firstname;
}
You can get all 4-6gram using the code without other package below:
from itertools import chain
def get_m_2_ngrams(input_list, min, max):
for s in chain(*[get_ngrams(input_list, k) for k in range(min, max+1)]):
yield ' '.join(s)
def get_ngrams(input_list, n):
return zip(*[input_list[i:] for i in range(n)])
if __name__ == '__main__':
input_list = ['I', 'am', 'aware', 'that', 'nltk', 'only', 'offers', 'bigrams', 'and', 'trigrams', ',', 'but', 'is', 'there', 'a', 'way', 'to', 'split', 'my', 'text', 'in', 'four-grams', ',', 'five-grams', 'or', 'even', 'hundred-grams']
for s in get_m_2_ngrams(input_list, 4, 6):
print(s)
the output is below:
I am aware that
am aware that nltk
aware that nltk only
that nltk only offers
nltk only offers bigrams
only offers bigrams and
offers bigrams and trigrams
bigrams and trigrams ,
and trigrams , but
trigrams , but is
, but is there
but is there a
is there a way
there a way to
a way to split
way to split my
to split my text
split my text in
my text in four-grams
text in four-grams ,
in four-grams , five-grams
four-grams , five-grams or
, five-grams or even
five-grams or even hundred-grams
I am aware that nltk
am aware that nltk only
aware that nltk only offers
that nltk only offers bigrams
nltk only offers bigrams and
only offers bigrams and trigrams
offers bigrams and trigrams ,
bigrams and trigrams , but
and trigrams , but is
trigrams , but is there
, but is there a
but is there a way
is there a way to
there a way to split
a way to split my
way to split my text
to split my text in
split my text in four-grams
my text in four-grams ,
text in four-grams , five-grams
in four-grams , five-grams or
four-grams , five-grams or even
, five-grams or even hundred-grams
I am aware that nltk only
am aware that nltk only offers
aware that nltk only offers bigrams
that nltk only offers bigrams and
nltk only offers bigrams and trigrams
only offers bigrams and trigrams ,
offers bigrams and trigrams , but
bigrams and trigrams , but is
and trigrams , but is there
trigrams , but is there a
, but is there a way
but is there a way to
is there a way to split
there a way to split my
a way to split my text
way to split my text in
to split my text in four-grams
split my text in four-grams ,
my text in four-grams , five-grams
text in four-grams , five-grams or
in four-grams , five-grams or even
four-grams , five-grams or even hundred-grams
you can find more detail on this blog
Just throw everything you read into a MemoryStream
and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
var buffer = new byte[512];
var bytesRead = default(int);
while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
memstream.Write(buffer, 0, bytesRead);
bytes = memstream.ToArray();
}
Or if you don't want to manage the buffers:
var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
reader.BaseStream.CopyTo(memstream);
bytes = memstream.ToArray();
}
If your properties file path and your java class path are same then you should this.
For example:
src/myPackage/MyClass.java
src/myPackage/MyFile.properties
Properties prop = new Properties();
InputStream stream = MyClass.class.getResourceAsStream("MyFile.properties");
prop.load(stream);
This problem is a mismatch of your iOS version and Xcode version.
Example:
You have an iPhone with iOS 9.3 GM and your Xcode version is 7.2.1. This leads to the issue that you have to update your Xcode to 7.3 which includes SDKs and related stuff for iOS 9.3.
you could add an sed script to your commandline:
ls /home/user/new/*.txt | sed -r 's/^.+\///'
I have tried a lot of techniques and finally found one in C# side and JS Side. You cannot give a physical path to src attribute but you can give the base64 string as a src to Img tag. Lets look into the below C# code example.
<asp:Image ID="imgEvid" src="#" runat="server" Height="99px"/>
C# code
if (File.Exists(filepath)
{
byte[] imageArray = System.IO.File.ReadAllBytes(filepath);
string base64ImageRepresentation = Convert.ToBase64String(imageArray);
var val = $"data: image/png; base64,{base64ImageRepresentation}";
imgEvid.Attributes.Add("src", val);
}
Hope this will help
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO product_cate (site_title, sub_title)
VALUES ('$site_title', '$sub_title')";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO menu (menu_title, sub_menu)
VALUES ('$menu_title', '$sub_menu', )";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO blog_post (post_title, post_des, post_img)
VALUES ('$post_title ', '$post_des', '$post_img')";
Find Microsoft Visual C++ 2010 x86/x64 Redistributable – 10.0.xxxxx in the control panel of the add or remove programs if xxxxx > 30319 renmove it
Based on the solution of Édouard Lopez, but in two lines:
import jQuery from "jquery";
window.$ = window.jQuery = jQuery;
With pandas >= 1.0 there is now a dedicated string datatype:
1) You can convert your column to this pandas string datatype using .astype('string'):
df['zipcode'] = df['zipcode'].astype('string')
2) This is different from using str
which sets the pandas object datatype:
df['zipcode'] = df['zipcode'].astype(str)
3) For changing into categorical datatype use:
df['zipcode'] = df['zipcode'].astype('category')
You can see this difference in datatypes when you look at the info of the dataframe:
df = pd.DataFrame({
'zipcode_str': [90210, 90211] ,
'zipcode_string': [90210, 90211],
'zipcode_category': [90210, 90211],
})
df['zipcode_str'] = df['zipcode_str'].astype(str)
df['zipcode_string'] = df['zipcode_str'].astype('string')
df['zipcode_category'] = df['zipcode_category'].astype('category')
df.info()
# you can see that the first column has dtype object
# while the second column has the new dtype string
# the third column has dtype category
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 zipcode_str 2 non-null object
1 zipcode_string 2 non-null string
2 zipcode_category 2 non-null category
dtypes: category(1), object(1), string(1)
The 'string' extension type solves several issues with object-dtype NumPy arrays:
You can accidentally store a mixture of strings and non-strings in an object dtype array. A StringArray can only store strings.
object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text, but still object-dtype columns.
When reading code, the contents of an object dtype array is less clear than string.
More info on working with the new string datatype can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html