Check out in here, worked well for me, with no limits in the output size, no omitted elements, even beyond 1000
When Bootstrap Select initializes, it'll build a set of custom divs that run alongside the original <select>
element and will typically synchronize state between the two input mechanisms.
Which is to say that one way to handle events on bootstrap select is to listen for events on the original select that it modifies, regardless of who updated it.
Just listen for a change
event and get the selected value using javascript or jQuery like this:
$('select').on('change', function(e){
console.log(this.value,
this.options[this.selectedIndex].value,
$(this).find("option:selected").val(),);
});
*NOTE: As with any script reliant on the DOM, make sure you wait for the DOM ready event before executing
$(function() {_x000D_
_x000D_
$('select').on('change', function(e){_x000D_
console.log(this.value,_x000D_
this.options[this.selectedIndex].value,_x000D_
$(this).find("option:selected").val(),);_x000D_
});_x000D_
_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
<option val="Must"> Mustard </option>_x000D_
<option val="Cat" > Ketchup </option>_x000D_
<option val="Rel" > Relish </option>_x000D_
</select>
_x000D_
As this answer alludes, Bootstrap Select has their own set of custom events, including changed.bs.select
which:
fires after the select's value has been changed. It passes through event, clickedIndex, newValue, oldValue.
And you can use that like this:
$("select").on("changed.bs.select",
function(e, clickedIndex, newValue, oldValue) {
console.log(this.value, clickedIndex, newValue, oldValue)
});
$(function() {_x000D_
_x000D_
$("select").on("changed.bs.select", _x000D_
function(e, clickedIndex, newValue, oldValue) {_x000D_
console.log(this.value, clickedIndex, newValue, oldValue)_x000D_
});_x000D_
_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
<option val="Must"> Mustard </option>_x000D_
<option val="Cat" > Ketchup </option>_x000D_
<option val="Rel" > Relish </option>_x000D_
</select>
_x000D_
try:
var url = '/Home/Index/' + e.value;
window.location = window.location.host + url;
That should get you where you want.
You can use wc -l
to figure out the total # of lines.
You can then combine head
and tail
to get at the range you want. Let's assume the log is 40,000 lines, you want the last 1562 lines, then of those you want the first 838. So:
tail -1562 MyHugeLogFile.log | head -838 | ....
Or there's probably an easier way using sed
or awk
.
For those using CodeIgniter, there's a built-in Date Helper function called timezone_menu. These:
$this->load->helper('date');
echo timezone_menu('GMT', 'form-control', 'dropdown-name', ['id' => 'ci-timezone']);
Produce the following output:
<select name="dropdown-name" class="form-control" id="ci-timezone">
<option value="UM12">(UTC -12:00) Baker/Howland Island</option>
<option value="UM11">(UTC -11:00) Niue</option>
<option value="UM10">(UTC -10:00) Hawaii-Aleutian Standard Time, Cook Islands, Tahiti</option>
<option value="UM95">(UTC -9:30) Marquesas Islands</option>
<option value="UM9">(UTC -9:00) Alaska Standard Time, Gambier Islands</option>
<option value="UM8">(UTC -8:00) Pacific Standard Time, Clipperton Island</option>
<option value="UM7">(UTC -7:00) Mountain Standard Time</option>
<option value="UM6">(UTC -6:00) Central Standard Time</option>
<option value="UM5">(UTC -5:00) Eastern Standard Time, Western Caribbean Standard Time</option>
<option value="UM45">(UTC -4:30) Venezuelan Standard Time</option>
<option value="UM4">(UTC -4:00) Atlantic Standard Time, Eastern Caribbean Standard Time</option>
<option value="UM35">(UTC -3:30) Newfoundland Standard Time</option>
<option value="UM3">(UTC -3:00) Argentina, Brazil, French Guiana, Uruguay</option>
<option value="UM2">(UTC -2:00) South Georgia/South Sandwich Islands</option>
<option value="UM1">(UTC -1:00) Azores, Cape Verde Islands</option>
<option value="UTC" selected="selected">(UTC) Greenwich Mean Time, Western European Time</option>
<option value="UP1">(UTC +1:00) Central European Time, West Africa Time</option>
<option value="UP2">(UTC +2:00) Central Africa Time, Eastern European Time, Kaliningrad Time</option>
<option value="UP3">(UTC +3:00) Moscow Time, East Africa Time, Arabia Standard Time</option>
<option value="UP35">(UTC +3:30) Iran Standard Time</option>
<option value="UP4">(UTC +4:00) Azerbaijan Standard Time, Samara Time</option>
<option value="UP45">(UTC +4:30) Afghanistan</option>
<option value="UP5">(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time</option>
<option value="UP55">(UTC +5:30) Indian Standard Time, Sri Lanka Time</option>
<option value="UP575">(UTC +5:45) Nepal Time</option>
<option value="UP6">(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time</option>
<option value="UP65">(UTC +6:30) Cocos Islands, Myanmar</option>
<option value="UP7">(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam</option>
<option value="UP8">(UTC +8:00) Australian Western Standard Time, Beijing Time, Irkutsk Time</option>
<option value="UP875">(UTC +8:45) Australian Central Western Standard Time</option>
<option value="UP9">(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk Time</option>
<option value="UP95">(UTC +9:30) Australian Central Standard Time</option>
<option value="UP10">(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time</option>
<option value="UP105">(UTC +10:30) Lord Howe Island</option>
<option value="UP11">(UTC +11:00) Srednekolymsk Time, Solomon Islands, Vanuatu</option>
<option value="UP115">(UTC +11:30) Norfolk Island</option>
<option value="UP12">(UTC +12:00) Fiji, Gilbert Islands, Kamchatka Time, New Zealand Standard Time</option>
<option value="UP1275">(UTC +12:45) Chatham Islands Standard Time</option>
<option value="UP13">(UTC +13:00) Samoa Time Zone, Phoenix Islands Time, Tonga</option>
<option value="UP14">(UTC +14:00) Line Islands</option>
</select>
I think because C would be seen the C drive on the client pc, it wont let you. And if it could do this, it would be a big security hole.
<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'fr', layout: google.translate.TranslateElement.FloatPosition.TOP_RIGHT}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
In bash $1
is the first argument passed to the script, $2
second and so on
/usr/local/bin/abbyyocr9 -rl Swedish -if "$1" -of "$2" 2>&1
So you can use:
./your_script.sh some_source_file.png destination_file.txt
Explanation on double quotes;
consider three scripts:
# foo.sh
bash bar.sh $1
# cat foo2.sh
bash bar.sh "$1"
# bar.sh
echo "1-$1" "2-$2"
Now invoke:
$ bash foo.sh "a b"
1-a 2-b
$ bash foo2.sh "a b"
1-a b 2-
When you invoke foo.sh "a b"
then it invokes bar.sh a b
(two arguments), and with foo2.sh "a b"
it invokes bar.sh "a b"
(1 argument). Always have in mind how parameters are passed and expaned in bash, it will save you a lot of headache.
Lucky discovery
if objFolderItem
is Nothing when you call
objFolder.GetDetailsOf(objFolderItem, i)
the string returned is the name of the property, rather than its (undefined) value
e.g. when i=3
it returns "Date modified"
Doing it for all 288 values of I makes it clear why most cause it to return blank for most filetypes
e.g i=175
is "Horizontal resolution"
This seems to be old post but still I wanted to share how this issue got fixed for me.
For users, who do not have admin access and when they open a command prompt, it runs under the user privilege. It means, you may have path like C:\Users\
so when trying C:\Users\XYZ>mvn --version , it actually search the JAVA_HOME path from user variables not system variables in Environment Variables.
So, In order to fix this, we need to create a environment variable for JAVA_HOME in user variables.
Hope, this helps someone.
AccountList.Split("\r\n");
I had to edit /etc/apache2/sites-available/default
. The lines are the same as mentioned by RDL.
You can also try this to determine the current global sql_mode
value:
SELECT @@GLOBAL.sql_mode;
or session sql_mode
value:
SELECT @@SESSION.sql_mode;
I also had the feeling that the SQL mode was indeed empty.
Assuming array
is a character array that does not end in \0
, you will want to use strncpy
:
char * strncpy(char * destination, const char * source, size_t num);
like so:
strncpy(string, array, 20);
string[20] = '\0'
Then string
will be a null terminated C string, as desired.
As Diodeus stated, IE doesn't allow anything but the default border for <select>
elements. However, I know of two hacks to achieve a similar effect :
Use a DIV that is placed absolutely at the same position as the dropdown and set it's borders. It will appear that the dropdown has a border.
Use a Javascript solution, for instance, the one provided here.
It may however prove to be too much effort, so you should evaluate if you really require the border.
el.scrollIntoView()
This solution will not hurt your brain having to think about scrollTop
or scrollHeight
, has smooth scrolling built in, and even works in IE.
scrollIntoView() has options you can pass it like scrollIntoView({behavior: 'smooth'})
to get smooth scrolling.
methods: {
scrollToElement() {
const el = this.$el.getElementsByClassName('scroll-to-me')[0];
if (el) {
// Use el.scrollIntoView() to instantly scroll to the element
el.scrollIntoView({behavior: 'smooth'});
}
}
}
Then if you wanted to scroll to this element on page load you could call this method like this:
mounted() {
this.scrollToElement();
}
Else if you wanted to scroll to it on a button click or some other action you could call it the same way:
<button @click="scrollToElement">scroll to me</button>
The scroll works all the way down to IE 8. The smooth scroll effect does not work out of the box in IE or Safari. If needed there is a polyfill available for this here as @mostafaznv mentioned in the comments.
Here is a sample. the key to arrange is as follows
android:layout_width="0dp"
android:layout_weight="1"
Complete code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp">
<TextView
android:id="@+id/categoryName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="abcd" />
<TextView
android:id="@+id/spareName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="efgh" />
</LinearLayout>
Disclaimer: I work for a company, Particle Code, that makes a cross-platform framework. There are a ton of companies in this space. New ones seem to spring up every week. Good news for you: you have a lot of choices.
These frameworks take different approaches, and many of them are fundamentally designed to solve different problems. Some are focused on games, some are focused on apps. I would ask the following questions:
What do you want to write? Enterprise application, personal productivity application, puzzle game, first-person shooter?
What kind of development environment do you prefer? IDE or plain ol' text editor?
Do you have strong feelings about programming languages? Of the frameworks I'm familiar with, you can choose from ActionScript, C++, C#, Java, Lua, and Ruby.
My company is more in the game space, so I haven't played as much with the JavaScript+CSS frameworks like Titanium, PhoneGap, and Sencha. But I can tell you a bit about some of the games-oriented frameworks. Games and rich internet applications are an area where cross-platform frameworks can shine, because these applications tend to place more importance of being visually unique and less on blending in with native UIs. Here are a few frameworks to look for:
Unity www.unity3d.com is a 3D games engine. It's really unlike any other development environment I've worked in. You build scenes with 3D models, and define behavior by attaching scripts to objects. You can script in JavaScript, C#, or Boo. If you want to write a 3D physics-based game that will run on iOS, Android, Windows, OS X, or consoles, this is probably the tool for you. You can also write 2D games using 3D assets--a fine example of this is indie game Max and the Magic Marker, a 2D physics-based side-scroller written in Unity. If you don't know it, I recommend checking it out (especially if there are any kids in your household). Max is available for PC, Wii, iOS and Windows Phone 7 (although the latter version is a port, since Unity doesn't support WinPhone). Unity comes with some sample games complete with 3D assets and textures, which really helps getting up to speed with what can be a pretty complicated environment.
Corona www.anscamobile.com/corona is a 2D games engine that uses the Lua scripting language and supports iOS and Android. The selling point of Corona is the ability to write physics-based games very quickly in few lines of code, and the large number of Corona-based games in the iOS app store is a testament to its success. The environment is very lean, which will appeal to some people. It comes with a simulator and debugger. You add your text editor of choice, and you have a development environment. The base SDK doesn't include any UI components, like buttons or list boxes, but a CoronaUI add-on is available to subscribers.
The Particle SDK www.particlecode.com is a slightly more general cross-platform solution with a background in games. You can write in either Java or ActionScript, using a MVC application model. It includes an Eclipse-based IDE with a WYSIWYG UI editor. We currently support building for Android, iOS, webOS, and Windows Phone 7 devices. You can also output Flash or HTML5 for the web. The framework was originally developed for online multiplayer social games, such as poker and backgammon, and it suits 2D games and apps with complex logic. The framework supports 2D graphics and includes a 2D physics engine.
NB:
Today we announced that Particle Code has been acquired by Appcelerator, makers of the Titanium cross-platform framework.
...
As of January 1, 2012, [Particle Code] will no longer officially support the [Particle SDK] platform.
In terms of learning curve, I'd say that Unity had the steepest learning curve (for me), Corona was the simplest, and Particle and Airplay are somewhere in between.
Another interesting point is how the frameworks handle different form factors. Corona supports dynamic scaling, which will be familiar to Flash developers. This is very easy to use but means that you end up wasting screen space when going from a 4:3 screen like the iPhone to a 16:9 like the new qHD Android devices. The Particle SDK's UI editor lets you design flexible layouts that scale, but also lets you adjust the layouts for individual screen sizes. This takes a little more time but lets you make the app look custom made for each screen.
Of course, what works for you depends on your individual taste and work style as well as your goals -- so I recommend downloading a couple of these tools and giving them a shot. All of these tools are free to try.
Also, if I could just put in a public service announcement -- most of these tools are in really active development. If you find a framework you like, by all means send feedback and let them know what you like, what you don't like, and features you'd like to see. You have a real opportunity to influence what goes into the next versions of these tools.
Hope this helps.
One-liner in java 8 syntax:
pdfTestDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".txt"));
you have to reason in terms of hased password:
store the password as md5('bob123');
when bob is register to your app
$query = "INSERT INTO users (username,password) VALUES('bob','".md5('bob123')."');
then, when bob is logging-in:
$query = "SELECT * FROM users WHERE username = 'bob' AND password = '".md5('bob123')."';
obvioulsy use variables for username and password, these queries are generated by php and then you can execute them on mysql
You are probably experiencing an issue with a firewall. The 'problem' is that the port you specify is not the only port used, it uses 1 or maybe even 2 more ports for RMI, and those are probably blocked by a firewall.
One of the extra ports will not be know up front if you use the default RMI configuration, so you have to open up a big range of ports - which might not amuse the server administrator.
There is a solution that does not require opening up a lot of ports however, I've gotten it to work using the combined source snippets and tips from
http://forums.sun.com/thread.jspa?threadID=5267091 - link doesn't work anymore
http://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx
http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html
It's even possible to setup an ssh tunnel and still get it to work :-)
In your invocation, the two functions are the same.
average
can compute a weighted average though.
This was too good of an answer not to post it here. It's from a Gilles, a fellow user from askubuntu:
The clipboard is provided by the X server. It doesn't matter whether the server is headless or not, what matters is that your local graphical session is available to programs running on the remote machine. Thanks to X's network-transparent design, this is possible.
I assume that you're connecting to the remote server with SSH from a machine running Linux. Make sure that X11 forwarding is enabled both in the client configuration and in the server configuration. In the client configuration, you need to have the line
ForwardX11 yes
in~/.ssh/config
to have it on by default, or pass the option-X
to thessh
command just for that session. In the server configuration, you need to have the lineX11Forwarding yes
in/etc/ssh/sshd_config
(it is present by default on Ubuntu).To check whether X11 forwarding is enabled, look at the value of the
DISPLAY
environment variable:echo $DISPLAY
. You should see a value likelocalhost:10
(applications running on the remote machine are told to connect to a display running on the same machine, but that display connection is in fact forwarded by SSH to your client-side display). Note that ifDISPLAY
isn't set, it's no use setting it manually: the environment variable is always set correctly if the forwarding is in place. If you need to diagnose SSH connection issues, pass the option-vvv
tossh
to get a detailed trace of what's happening.If you're connecting through some other means, you may or may not be able to achieve X11 forwarding. If your client is running Windows, PuTTY supports X11 forwarding; you'll have to run an X server on the Windows machine such as Xming.
By Gilles from askubuntu
On submitting, you would get an array as if created like this:
$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );
However, I would suggest changing your form names to this format instead:
name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...
Using that format, it's much easier to loop through the values.
if ( isset( $_POST['diameters'] ) )
{
echo '<table>';
foreach ( $_POST['diameters'] as $diam )
{
// here you have access to $diam['top'] and $diam['bottom']
echo '<tr>';
echo ' <td>', $diam['top'], '</td>';
echo ' <td>', $diam['bottom'], '</td>';
echo '</tr>';
}
echo '</table>';
}
Since the only way to avoid a method to get overriden is to use the keyword super, I've thought to move up the method2() from SuperClass to another new Base class and then call it from SuperClass:
class Base
{
public void method2()
{
System.out.println("superclass method2");
}
}
class SuperClass extends Base
{
public void method1()
{
System.out.println("superclass method1");
super.method2();
}
}
class SubClass extends SuperClass
{
@Override
public void method1()
{
System.out.println("subclass method1");
super.method1();
}
@Override
public void method2()
{
System.out.println("subclass method2");
}
}
public class Demo
{
public static void main(String[] args)
{
SubClass mSubClass = new SubClass();
mSubClass.method1();
}
}
Output:
subclass method1
superclass method1
superclass method2
In config.inc.php
in the top-level directory, set
$cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized
// or
$cfg['Lang'] = 'en-utf-8'; // Force this language for all users
If Lang
isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there.
I didn't find the package of the most voted answer in my Python 3 dist.
I had the same problem and solved it installing the module pywin32:
In a normal python:
pip install pywin32
In anaconda:
conda install pywin32
My python installation (Intel® Distribution for Python) had some kind of dependency problem and was giving this error. After installing this module it stopped appearing.
You can provide more flexibility to your users by provide Browser Button to them
Private Sub btn_browser_file_Click()
Dim xRow As Long
Dim sh1 As Worksheet
Dim xl_app As Excel.Application
Dim xl_wk As Excel.Workbook
Dim WS As Workbook
Dim xDirect$, xFname$, InitialFoldr$
InitialFoldr$ = "C:\"
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder to list Files from"
.InitialFileName = InitialFoldr$
.Show
Range("H13").Activate
If .SelectedItems.Count <> 0 Then
xDirect$ = .SelectedItems(1) & "\"
Range("h12").Value = xDirect$
xFname$ = Dir(xDirect$, 7)
Do While xFname$ <> ""
If (Format(FileDateTime(xDirect$ & "\" & xFname$), "MM/DD/YYYY") > Format(Range("H10").Value, "MM/DD/YYYY")) Then
ActiveCell.Offset(xRow) = xFname$
xRow = xRow + 1
xFname$ = Dir
Else
xFname$ = Dir
xRow = xRow
End If
Loop
End If
End With
with this piece of code you can achieve this, easily. Tested code
If you truly wish to use PHP, you could use
include "file.php";
or
require "file.php";
and then in file.php, use a heredoc & echo it in.
file.php contents:
$some_js_code <<<_code
function myFunction()
{
Alert("Some JS code would go here.");
}
_code;
At the top of your PHP file, bring in the file using either include or require then in head (or body section) echo it in
<?php
require "file.php";
?>
<html>
<head>
<?php
echo $some_js_code;
?>
</script>
</head>
<body>
</body>
</html>
Different way but it works. Just my $.02...
img need src to use border is remover, i no know a why css is crazy
data:image/gif;base64,R0lGODlhAQABAPcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAABAAEAAAgEAP8FBAA7
So try example with SRC:
img.logo {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
background: url(http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg) no-repeat top left;_x000D_
}
_x000D_
<img class="logo" src="data:image/gif;base64,R0lGODlhAQABAPcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAAABAAEAAAgEAP8FBAA7">
_x000D_
So try example without SRC:
img.logo {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
background: url(http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg) no-repeat top left;_x000D_
}
_x000D_
<img class="logo">
_x000D_
lol... css crazy! good fun
Click “Default levels” right next to filter and do make sure that "Info" is checked.
Please see screenshot:
After installing maven using brew or manually, using macOS Catalina and using the terminal or iTerm to operate maven you will need to grant access to the apps to access user files.
System Preferences -> Privacy (button) -> Full Disk Access
And then add terminal or iTerm to that list.
You will also need to restart your application e.g. terminal or iTerm after giving them full disk access.
On Ubuntu Linux this solved it for me:
pip install graphviz
sudo apt-get install graphviz
You could also try conda install -c conda-forge graphviz
instead of pip if using Anaconda.
var x = [4, 5, 6];
for (i = 0, j = x[i]; i < x.length; j = x[++i]) {
console.log(i,j);
}
A lot cleaner...
Instead of using LIKE
, use REGEXP
. For example:
SELECT * WHERE value REGEXP 'THIS|THAT'
mysql> SELECT 'pi' REGEXP 'pi|apa'; -> 1
mysql> SELECT 'axe' REGEXP 'pi|apa'; -> 0
mysql> SELECT 'apa' REGEXP 'pi|apa'; -> 1
mysql> SELECT 'apa' REGEXP '^(pi|apa)$'; -> 1
mysql> SELECT 'pi' REGEXP '^(pi|apa)$'; -> 1
mysql> SELECT 'pix' REGEXP '^(pi|apa)$'; -> 0
On *nix, unlike Windows, the current directory is usually not in your $PATH
variable. So the current directory is not searched when executing commands. You don't need ./
for running applications because these applications are in your $PATH; most likely they are in /bin
or /usr/bin
.
IMO the #3 answer at this time by Chen Dachao is the right way to go if you want to capture any kind of number, but the regular expression can be shortened from:
/[-]{0,1}[\d]*[\.]{0,1}[\d]+/g
to:
/-?\d*\.?\d+/g
For example, this code:
"lin-grad.ient(217deg,rgba(255, 0, 0, -0.8), rgba(-255,0,0,0) 70.71%)".match(/-?\d*\.?\d+/g)
generates this array:
["217","255","0","0","-0.8","-255","0","0","0","70.71"]
I've butchered an MDN linear gradient example so that it fully tests the regexp and doesn't need to scroll here. I think I've included all the possibilities in terms of negative numbers, decimals, unit suffixes like deg and %, inconsistent comma and space usage, and the extra dot/period and hyphen/dash characters within the text "lin-grad.ient". Please let me know if I'm missing something. The only thing I can see that it does not handle is a badly formed decimal number like "0..8".
If you really want an array of numbers, you can convert the entire array in the same line of code:
array = whatever.match(/-?\d*\.?\d+/g).map(Number);
My particular code, which is parsing CSS functions, doesn't need to worry about the non-numeric use of the dot/period character, so the regular expression can be even simpler:
/-?[\d\.]+/g
It means that you compiled your classes under a specific JDK, but then try to run them under older version of JDK.
In my Case this works like a charm:
Open Terminal
Type: open ~/.bash_profile
Add the following lines:
export ANDROID_SDK=$HOME/Library/Android/sdk
export PATH=$ANDROID_SDK/emulator:$PATH
export PATH=$ANDROID_SDK/tools:$PATH
export PATH=$ANDROID_SDK/tools/bin:$PATH
export PATH=$ANDROID_SDK/platform-tools:$PATH
export ANDROID_SDK_ROOT=$ANDROID_SDK
export ANDROID_AVD_HOME=$HOME/.android/and
alias emulator='$ANDROID_SDK/emulator/emulator'
Save (hit Command+S). You may close the window or not.
Back to Terminal, type: source ~/.bash_profile
Show the installed emulators: emulator -list-avds
, something like:
Pixel_2_API_29
Pixel_3a_API_29
Pixel_C_API_29
Last, run the emulator: emulator @Pixel_2_API_29
This little class never gives me any problem, just extend it and use the copy() method:
import simplejson as json
class BlindCopy(object):
def copy(self, json_str):
dic = json.loads(json_str)
for k, v in dic.iteritems():
if hasattr(self, k):
setattr(self, k, v);
You need the *
so it says "zero or more of the previous character" and this should do it:
var reg = new RegExp('^\\d*$');
Python 3.10 (use |
): Example for a function which takes a single argument that is either an int
or str
and returns either an int
or str
:
def func(arg: int | str) -> int | str:
^^^^^^^^^ ^^^^^^^^^
type of arg return type
Python 3.5 - 3.9 (use typing.Union
):
from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
type of arg return type
For the special case of X | None
you can use Optional[X]
.
I tried entering a new line character using an excel Sheet. I entered my data by writing "abc" below a blank cell in Excel and then updated my db using the empty cell above the cell containing "abc" and the cell with data. I copy pasted both the cells in my SSMS. It worked for me
If DB is SQL Server then
select Convert(varchar(10),CONVERT(date,YourDateColumn,106),103)
It should work ok as it is in Unix, if you have properties file in current working directory. Another option would be adding your properties file to the classpath and getting the inputstream using this.getClass().getClassLoader().getResourceAsStream("xxxxx.properties");
More here
In my case, that happened because icu4c was upgraded to version 63 but my locally installed postgres image still referenced icu4c 62.1. Therefore i had to change the icu4c version used:
brew info icu4c
brew switch icu4c <version>
Where version
is the the installed version returned by info
First of all try this
sudo apt-get update
sudo apt-get clean
sudo apt-get autoremove
If error still persists then do this
sudo apt --fix-broken install
sudo apt-get update && sudo apt-get upgrade
sudo dpkg --configure -a
sudo apt-get install -f
Afterwards try this again:
sudo apt-get install npm
But if it still couldn't resolve issues check for the dependencies using sudo dpkg --configure -a
and remove them one-by-one . Let's say dependencies are on npm then go for this ,
sudo apt-get remove nodejs
sudo apt-get remove npm
Then go to /etc/apt/sources.list.d and remove any node list if you have. Then do a
sudo apt-get update
Then check for the dependencies problem again using sudo dpkg --configure -a
and if it's all clear then you are done .
Later on install npm again using this
v=8 # set to 4, 5, 6, ... as needed
curl -sL https://deb.nodesource.com/setup_$v.x | sudo -E bash -
Then install the Node.js package.
sudo apt-get install -y nodejs
The answer above will work for general cases also(for dependencies on other packages like django ,etc) just after first two processes use the same process for the package you are facing dependency with.
There is another way to do it, using org.apache.commons.io.IOUtils
to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON
or other object with Gson
, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
You can try overflow
css property.
1. Browser-native HTML inline embedding:
<embed
src="http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0&scrollbar=0"
type="application/pdf"
frameBorder="0"
scrolling="auto"
height="100%"
width="100%"
></embed>
<iframe
src="http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&navpanes=0&scrollbar=0"
frameBorder="0"
scrolling="auto"
height="100%"
width="100%"
></iframe>
Pro:
Cons:
2. Google Docs Viewer:
<iframe
src="https://drive.google.com/viewerng/viewer?embedded=true&url=http://infolab.stanford.edu/pub/papers/google.pdf#toolbar=0&scrollbar=0"
frameBorder="0"
scrolling="auto"
height="100%"
width="100%"
></iframe>
Pro:
Cons:
3. Other solutions to embed PDF:
IMPORTANT NOTE:
Please check the X-Frame-Options HTTP response header. It should be SAMEORIGIN.
X-Frame-Options SAMEORIGIN;
Some linux distributions have a php_mysql and php_mysqli package to install.
Write a single function and call it for both of them.
function yourHandler(e){
alert( 'something happened!' );
}
jQuery(':input').change(yourHandler).keyup(yourHandler);
The change() and keyup() event registration functions return the original set, so they can be chained.
the html:
<a class="xyz">your content</a>
the css:
.xyz{
display: block;
}
This will make the anchor be a block level element like a div.
In css you can't set table-cells max height, and if you white-space nowrap then you can't break it with max width, so the solution is javascript working in all browsers.
So, this can work for you.
For Limiting max-height of all cells or rows in table with Javascript:
This script is good for horizontal overflow tables.
This script increase the table width 300px each time, maximum 4000px until rows shrinks to max-height(160px) , and you can also edit numbers as your need.
var i = 0, row, table = document.getElementsByTagName('table')[0], j = table.offsetWidth;
while (row = table.rows[i++]) {
while (row.offsetHeight > 160 && j < 4000) {
j += 300;
table.style.width = j + 'px';
}
}
Source: HTML Table Solution Max Height Limit For Rows Or Cells By Increasing Table Width, Javascript
I think it is better practice to keep your response under single control and for this reason I found out the most official solution.
response()->json([...])
->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);
add this after namespace
declaration:
use Illuminate\Http\Response;
@adeneo answer works for Firefox and chrome... For IE the below can be used.
if (window.navigator.msSaveOrOpenBlob) {_x000D_
var blob = new Blob([decodeURIComponent(encodeURI(result.data))], {_x000D_
type: "text/csv;charset=utf-8;"_x000D_
});_x000D_
navigator.msSaveBlob(blob, 'FileName.csv');_x000D_
}
_x000D_
Table: Table is a preliminary storage for storing data and information in RDBMS. A table is a collection of related data entries and it consists of columns and rows.
View: A view is a virtual table whose contents are defined by a query. Unless indexed, a view does not exist as a stored set of data values in a database. Advantages over table are
If your RESTFul call sends XML Messages back and forth embedded in the Html Body of the HTTP request, you should be able to have all the benefits of WS-Security such as XML encryption, Cerificates, etc in your XML messages while using whatever security features are available from http such as SSL/TLS encryption.
It is a little rough, but here is something I put together that is comprised entirely of CSS and HTML.
This example also makes use of the :hover
pseudo class for each data cell <td>
. Elements can be easily updated to meet your needs, and the hover can quickly be disabled.
(However, I have not yet gotten the :hover
to properly work for full rows <tr>
. The last hovered row does not display with rounded corners on the bottom. I'm sure there is something simple that is getting overlooked.)
table.dltrc {_x000D_
width: 95%;_x000D_
border-collapse: separate;_x000D_
border-spacing: 0px;_x000D_
border: solid black 2px;_x000D_
border-radius: 8px;_x000D_
}_x000D_
_x000D_
tr.dlheader {_x000D_
text-align: center;_x000D_
font-weight: bold;_x000D_
border-left: solid black 1px;_x000D_
padding: 2px_x000D_
}_x000D_
_x000D_
td.dlheader {_x000D_
background: #d9d9d9;_x000D_
text-align: center;_x000D_
font-weight: bold;_x000D_
border-left: solid black 1px;_x000D_
border-radius: 0px;_x000D_
padding: 2px_x000D_
}_x000D_
_x000D_
tr.dlinfo,_x000D_
td.dlinfo {_x000D_
text-align: center;_x000D_
border-left: solid black 1px;_x000D_
border-top: solid black 1px;_x000D_
padding: 2px_x000D_
}_x000D_
_x000D_
td.dlinfo:first-child,_x000D_
td.dlheader:first-child {_x000D_
border-left: none;_x000D_
}_x000D_
_x000D_
td.dlheader:first-child {_x000D_
border-radius: 5px 0 0 0;_x000D_
}_x000D_
_x000D_
td.dlheader:last-child {_x000D_
border-radius: 0 5px 0 0;_x000D_
}_x000D_
_x000D_
_x000D_
/*===== hover effects =====*/_x000D_
_x000D_
_x000D_
/*tr.hover01:hover,_x000D_
tr.hover02:hover {_x000D_
background-color: #dde6ee;_x000D_
}*/_x000D_
_x000D_
_x000D_
/* === ROW HOVER === */_x000D_
_x000D_
_x000D_
/*tr.hover02:hover:last-child {_x000D_
background-color: #dde6ee;_x000D_
border-radius: 0 0 6px 6px;_x000D_
}*/_x000D_
_x000D_
_x000D_
/* === CELL HOVER === */_x000D_
_x000D_
td.hover01:hover {_x000D_
background-color: #dde6ee;_x000D_
}_x000D_
_x000D_
td.hover02:hover {_x000D_
background-color: #dde6ee;_x000D_
}_x000D_
_x000D_
td.hover02:first-child {_x000D_
border-radius: 0 0 0 6px;_x000D_
}_x000D_
_x000D_
td.hover02:last-child {_x000D_
border-radius: 0 0 6px 0;_x000D_
}
_x000D_
<body style="background:white">_x000D_
<br>_x000D_
<center>_x000D_
<table class="dltrc" style="background:none">_x000D_
<tbody>_x000D_
<tr class="dlheader">_x000D_
<td class="dlheader">Subject</td>_x000D_
<td class="dlheader">Title</td>_x000D_
<td class="dlheader">Format</td>_x000D_
</tr>_x000D_
<tr class="dlinfo hover01">_x000D_
<td class="dlinfo hover01">One</td>_x000D_
<td class="dlinfo hover01">Two</td>_x000D_
<td class="dlinfo hover01">Three</td>_x000D_
</tr>_x000D_
<tr class="dlinfo hover01">_x000D_
<td class="dlinfo hover01">Four</td>_x000D_
<td class="dlinfo hover01">Five</td>_x000D_
<td class="dlinfo hover01">Six</td>_x000D_
</tr>_x000D_
<tr class="dlinfo hover01">_x000D_
<td class="dlinfo hover01">Seven</td>_x000D_
<td class="dlinfo hover01">Eight</td>_x000D_
<td class="dlinfo hover01">Nine</td>_x000D_
</tr>_x000D_
<tr class="dlinfo2 hover02">_x000D_
<td class="dlinfo hover02">Ten</td>_x000D_
<td class="dlinfo hover01">Eleven</td>_x000D_
<td class="dlinfo hover02">Twelve</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</center>_x000D_
</body>
_x000D_
You can use setInterval()
, the arguments are the same.
const interval = setInterval(function() {
// method to be executed;
}, 5000);
clearInterval(interval); // thanks @Luca D'Amico
Nope - but you could use a template column:
<script runat="server">
TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {
object o = DataBinder.Eval(Container.DataItem, field);
if (converter == null) {
return (TResult)o;
}
return converter((T)o);
}
</script>
<asp:TemplateField>
<ItemTemplate>
<%# Eval<bool, string>("Active", b => b ? "Yes" : "No") %>
</ItemTemplate>
</asp:TemplateField>
Yes it is possible. When writing the stream creating the csv, the first thing to do is this:
myStream.Write(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length)
Change it to a table-valued function
Please refer to the following link, for example.
With SemaphoreSlim
you can achieve parallelism control.
var bag = new ConcurrentBag<object>();
var maxParallel = 20;
var throttler = new SemaphoreSlim(initialCount: maxParallel);
var tasks = myCollection.Select(async item =>
{
try
{
await throttler.WaitAsync();
var response = await GetData(item);
bag.Add(response);
}
finally
{
throttler.Release();
}
});
await Task.WhenAll(tasks);
var count = bag.Count;
I raise an event in the the form setting the value and subscribe to that event in the form(s) that need to deal with the value change.
You were right regarding how you want to generate salt i.e. its nothing but a random number. For this particular case it would protect your system from possible Dictionary attacks. Now, for the second problem what you could do is instead of using UTF-8 encoding you may want to use Base64. Here, is a sample for generating a hash. I am using Apache Common Codecs for doing the base64 encoding you may select one of your own
public byte[] generateSalt() {
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);
return bytes;
}
public String bytetoString(byte[] input) {
return org.apache.commons.codec.binary.Base64.encodeBase64String(input);
}
public byte[] getHashWithSalt(String input, HashingTechqniue technique, byte[] salt) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance(technique.value);
digest.reset();
digest.update(salt);
byte[] hashedBytes = digest.digest(stringToByte(input));
return hashedBytes;
}
public byte[] stringToByte(String input) {
if (Base64.isBase64(input)) {
return Base64.decodeBase64(input);
} else {
return Base64.encodeBase64(input.getBytes());
}
}
Here is some additional reference of the standard practice in password hashing directly from OWASP
I think 2 update calls should do
update VersionedFields
set Value = replace(value,'<iframe','<a><iframe')
update VersionedFields
set Value = replace(value,'> </iframe>','</a>')
You just do an opposite comparison. if Col2 <= 1
. This will return a boolean Series with False
values for those greater than 1 and True
values for the other. If you convert it to an int64
dtype, True
becomes 1
and False
become 0
,
df['Col3'] = (df['Col2'] <= 1).astype(int)
If you want a more general solution, where you can assign any number to Col3
depending on the value of Col2
you should do something like:
df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)
Or:
df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55
The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.
using (SqlConnection conn = new SqlConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO <table> (<date_column>) VALUES ('2010-01-01 12:00')";
cmd.ExecuteNonQuery();
}
It's been awhile since I wrote this stuff, so this may not be perfect. but the general idea is there.
WARNING: this is unsanitized. You should use parameters to avoid injection attacks.
EDIT: Since Jon insists.
When you are running a python script on windows in subprocess you should use python in front of the script name. Try:
process = subprocess.Popen("python /the/script.py")
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
As of NP++ V6.2.3 (nor sure about older versions) simply:
Hope this helps to achieve goal in simple and yet fast way:)
Check this basic code to setup html server. its work for me.
var http = require('http'), fs = require('fs'); fs.readFile('./index.html', function (err, html) { if (err) { throw err; } http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); response.write(html); response.end(); }).listen(8000); });
The recommendation is was to start their name with "X-". E.g. X-Forwarded-For
, X-Requested-With
. This is also mentioned in a.o. section 5 of RFC 2047.
Update 1: On June 2011, the first IETF draft was posted to deprecate the recommendation of using the "X-" prefix for non-standard headers. The reason is that when non-standard headers prefixed with "X-" become standard, removing the "X-" prefix breaks backwards compatibility, forcing application protocols to support both names (E.g, x-gzip
& gzip
are now equivalent). So, the official recommendation is to just name them sensibly without the "X-" prefix.
Update 2: On June 2012, the deprecation of recommendation to use the "X-" prefix has become official as RFC 6648. Below are cites of relevance:
3. Recommendations for Creators of New Parameters
...
- SHOULD NOT prefix their parameter names with "X-" or similar constructs.
4. Recommendations for Protocol Designers
...
SHOULD NOT prohibit parameters with an "X-" prefix or similar constructs from being registered.
MUST NOT stipulate that a parameter with an "X-" prefix or similar constructs needs to be understood as unstandardized.
MUST NOT stipulate that a parameter without an "X-" prefix or similar constructs needs to be understood as standardized.
Note that "SHOULD NOT" ("discouraged") is not the same as "MUST NOT" ("forbidden"), see also RFC 2119 for another spec on those keywords. In other words, you can keep using "X-" prefixed headers, but it's not officially recommended anymore and you may definitely not document them as if they are public standard.
Summary:
node-memwatch : detect and find memory leaks in Node.JS code. Check this tutorial Tracking Down Memory Leaks in Node.js
string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");
string path = Server.MapPath("~/App_Data/somedata.xml");
you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.
My solution:
First create "<style>" tags with an ID.
<style id="YourID">
.YourClass {background-color:red}
</style>
Then, I create a function in JavaScript like this:
document.getElementById('YourID').innerHTML = '.YourClass {background-color:blue}'
Worked like a charm for me.
I googled a bit, and found this code here:
File file = getJarFileToLoadFrom();
String lcStr = getNameOfClassToLoad();
URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });
Class loadedClass = cl.loadClass(lcStr);
Can anyone share opinions/comments/answers regarding this approach?
The below both ways works fine.
System.out.println("The Class Name is: " + this.getClass().getName());
System.out.println("The simple Class Name is: " + this.getClass().getSimpleName());
Output as below:
The Class Name is: package.Student
The simple Class Name is: Student
The accepted answer did not work for me in all browsers, but following css did work for me:
tr
{
display: table-row-group;
page-break-inside:avoid;
page-break-after:auto;
}
The html structure was:
<table>
<thead>
<tr></tr>
</thead>
<tbody>
<tr></tr>
<tr></tr>
...
</tbody>
</table>
In my case, there were some additional issues with the thead tr
, but this resolved the original issue of keeping the table rows from breaking.
Because of the header issues, I ultimately ended up with:
#theTable td *
{
page-break-inside:avoid;
}
This didn't prevent rows from breaking; just each cell's content.
No, if you do:
array = {}
IN your example you are using array
as a dictionary, not an array. If you need an array, in Python you use lists:
array = []
Then, to add items you do:
array.append('a')
I had similar problem, login was done with ajax, but browsers (firefox, chrome, safari and IE 7-10) would not offer to save password if form (#loginForm) is submitted with ajax.
As a SOLUTION I have added hidden submit input (#loginFormHiddenSubmit) to form that was submitted by ajax and after ajax call would return success I would trigger a click to hidden submit input. The page any way needed to refreshed. The click can be triggered with:
jQuery('#loginFormHiddenSubmit').click();
Reason why I have added hidden submit button is because:
jQuery('#loginForm').submit();
would not offer to save password in IE (although it has worked in other browsers).
Java has a class specifically for zip files and one even more specifically for Jar Files.
java.util.jar.JarOutputStream
java.util.jar.JarInputStream
using those you could, on a command from the console, using a scanner set to system.in
Scanner console = new Scanner(System.in);
String input = console.nextLine();
then get all the components and write them as a file.
JarEntry JE = null;
while((JE = getNextJarEntry()) != null)
{
//do stuff with JE
}
You can also use java.util.zip.ZipInputStream instead, as seeing a JAR file is in the same format as a ZIP file, ZipInputStream will be able to handle the Jar file, in fact JarInputStream actually extends ZipInputStream.
an alternative is also instead of getNextJarEntry, to use getNextEntry
$("#registerSubmit").serialize() // returns all the data in your form
$.ajax({
type: "POST",
url: 'your url',
data: $("#registerSubmit").serialize(),
success: function() {
//success message mybe...
}
});
I have used below command for export DB
mongodump --db database_name --collection collection_name
and below command worked for me to import DB
mongorestore --db database_name path_to_bson_file
I had a similar problem with HTML input fields in MVC. The web paged only showed the first keyword of the field. Example: input field: "The quick brown fox" Displayed value: "The"
The resolution was to put the variable in quotes in the value statement as follows:
<input class="ParmInput" type="text" id="respondingRangerUnit" name="respondingRangerUnit"
onchange="validateInteger(this.value)" value="@ViewBag.respondingRangerUnit">
In JavaScript this will translate to an object that with data might look like this
Interfaces in TypeScript are a dev time construct (purely for tooling ... 0 runtime impact). You should write the same TypeScript as your JavaScript.
for me, I have to add
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
right after:
xmlns:android="http://schemas.android.com/apk/res/android"
in res/layout/main.xml
package com.example.readfilefromexternalresource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends Activity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView);
String state = Environment.getExternalStorageState();
if (!(state.equals(Environment.MEDIA_MOUNTED))) {
Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();
} else {
BufferedReader reader = null;
try {
Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show();
File file = Environment.getExternalStorageDirectory();
File textFile = new File(file.getAbsolutePath()+File.separator + "chapter.xml");
reader = new BufferedReader(new FileReader(textFile));
StringBuilder textBuilder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
textView.setText(textBuilder);
} catch (FileNotFoundException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(reader != null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
In short, if you have multiple routes defined for your app's routing, enclosed with Switch
component like this;
<Switch>
<Route exact path="/" component={Home} />
<Route path="/detail" component={Detail} />
<Route exact path="/functions" component={Functions} />
<Route path="/functions/:functionName" component={FunctionDetails} />
</Switch>
Then you have to put exact
keyword to the Route which it's path is also included by another Route's path. For example home path /
is included in all paths so it needs to have exact
keyword to differentiate it from other paths which start with /
. The reason is also similar to /functions
path. If you want to use another route path like /functions-detail
or /functions/open-door
which includes /functions
in it then you need to use exact
for the /functions
route.
When dealing with strings often I find it easier to make the source file ObjC++, then I can concatenate std::strings using the second method shown in the question.
std::string stdstr = [nsstr UTF8String];
//easier to read and more portable string manipulation goes here...
NSString* nsstr = [NSString stringWithUTF8String:stdstr.c_str()];
Another option is to get a ".pem" (public key) file for that particular server, and install it locally into the heart of your JRE's "cacerts" file (use the keytool helper application), then it will be able to download from that server without complaint, without compromising the entire SSL structure of your running JVM and enabling download from other unknown cert servers...
With tqdm (conda install tqdm
or pip install tqdm
) you can add a progress meter to your loops in a second:
from time import sleep
from tqdm import tqdm
for i in tqdm(range(10)):
sleep(3)
60%|¦¦¦¦¦¦ | 6/10 [00:18<00:12, 0.33 it/s]
Also, there is a notebook version:
from tqdm.notebook import tqdm
for i in tqdm(range(100)):
sleep(3)
You can use tqdm.auto
instead of tqdm.notebook
to work in both a terminal and notebooks.
tqdm.contrib
contains some helper functions to do things like enumerate
, map
, and zip
. There are concurrent maps in tqdm.contrib.concurrent
.
You can even get progress sent to your phone after disconnecting from a jupyter notebook using tqdm.contrib.telegram
or tqdm.contrib.discord
.
If you use Tomcat, add '-Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true' in VM properties.
https://tomcat.apache.org/tomcat-7.0-doc/config/systemprops.html#Security
You can use the Positioned.fill
with Align
inside a Stack
:
Stack(
children: <Widget>[
Positioned.fill(
child: Align(
alignment: Alignment.centerRight,
child: ....
),
),
],
),
All major browsers now include native JSON encoding/decoding.
// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject);
// To decode (This produces an object)
var obj = JSON.parse(json_str);
Note that only valid JSON data will be encoded. For example:
var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"
Valid JSON types are: objects, strings, numbers, arrays, true
, false
, and null
.
Some JSON resources:
If the ActiveDirectory module is present add
import-module activedirectory
before your code.
To check if exist try:
get-module -listavailable
ActiveDirectory module is default present in windows server 2008 R2, install it in this way:
Import-Module ServerManager
Add-WindowsFeature RSAT-AD-PowerShell
For have it to work you need at least one DC in the domain as windows 2008 R2 and have Active Directory Web Services (ADWS) installed on it.
For Windows Server 2008 read here how to install it
Dom this attribute is very old and not accepted in modern browsers as far as I know, But here is an alternative to it, Try this
<script type="text/javascript" language="javascript">
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls", ".csv");
var fileExt = sender.value;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
alert("Invalid file selected, valid files are of " +
validExts.toString() + " types.");
return false;
}
else return true;
}
</script>
<input type="file" id="file" onchange="checkfile(this);" />
I guess it'll help you of course you can change this script according to your needs.
Correct your Code like this:
try
{ //method try starts
String sql = "INSERT into TblName (col1, col2) VALUES(?, ?)";
pStmt = obj.getConnection().prepareStatement(sql);
pStmt.setLong(1, subscriberID);
for (String language : additionalLangs) {
pStmt.setInt(2, Integer.parseInt(language));
pStmt.execute();
}
} //method/try ends
finally
{ //finally starts
pStmt.close()
}
Are you sure, that you're really closing your pStatements, connections and results?
To analyze open objects you can implment a delegator pattern, which wraps code around your statemant, connection and result objects. So you'll see, if an object will successfully closed.
An Example for: pStmt = obj.getConnection().prepareStatement(sql);
class obj{
public Connection getConnection(){
return new ConnectionDelegator(...here create your connection object and put it into ...);
}
}
class ConnectionDelegator implements Connection{
Connection delegates;
public ConnectionDelegator(Connection con){
this.delegates = con;
}
public Statement prepareStatement(String sql){
return delegates.prepareStatement(sql);
}
public void close(){
try{
delegates.close();
}finally{
log.debug(delegates.toString() + " was closed");
}
}
}
With the new CSS3 features, you could rotate the page the opposite orientation that they rotated. Sorry, no IE7- support. :(.
var rotate = 0 - window.orientation;
setAttribute("transform:rotate("+rotate+"deg);-ms-transform:rotate("+rotate+"deg);-webkit-transform:rotate("+rotate+"deg)", "style");
The other answers are what you asked about, but in case it’s useful to anyone else, here’s how to set the font conditionally from the screen DPI (Windows only):
set guifont=default
if has('windows')
"get dpi, strip out utf-16 garbage and new lines
"system() converts 0x00 to 0x01 for 'platform independence'
"should return something like 'PixelsPerXLogicalInch=192'
"get the part from the = to the end of the line (eg '=192') and strip
"the first character
"and convert to a number
let dpi = str2nr(strpart(matchstr(substitute(
\system('wmic desktopmonitor get PixelsPerXLogicalInch /value'),
\'\%x01\|\%x0a\|\%x0a\|\%xff\|\%xfe', '', 'g'),
\'=.*$'), 1))
if dpi > 100
set guifont=high_dpi_font
endif
endif
In Eclipse
, right click on the xsd
file you want to get --> Generate --> Java... --> Generator: "Schema to JAXB Java Classes".
I just faced the same problem, I had a bunch of xsd
files, only one of them being the XML Root Element
and it worked well what I explained above in Eclipse
In addition to specifying the path (as Jimmy mentioned) you can also force Bundler to use a local gem for your environment only by using the following configuration option:
$ bundle config local.GEM_NAME /path/to/local/git/repository
This is extremely helpful if you're developing two gems or a gem and a rails app side-by-side.
Note though, that this only works when you're already using git for your dependency, for example:
# In Gemfile
gem 'rack', :github => 'rack/rack', :branch => 'master'
# In your terminal
$ bundle config local.rack ~/Work/git/rack
As seen on the docs.
You can also use numpy.subtract
It has the advantage over the difference operator, -
, that you do not have to transform the sequences (list or tuples) into a numpy arrays — you save the two commands:
array1 = np.array([1.1, 2.2, 3.3])
array2 = np.array([1, 2, 3])
Example: (Python 3.5)
import numpy as np
result = np.subtract([1.1, 2.2, 3.3], [1, 2, 3])
print ('the difference =', result)
which gives you
the difference = [ 0.1 0.2 0.3]
Remember, however, that if you try to subtract sequences (lists or tuples) with the -
operator you will get an error. In this case, you need the above commands to transform the sequences in numpy arrays
Wrong Code:
print([1.1, 2.2, 3.3] - [1, 2, 3])
Adding to @marbel's answer (which is a great suggestion!), here's the script that worked for me on Mac OS X El Captain's Terminal, for batch conversion (since that's what the OP asked). I thought it would be trivial to do a for
loop but it wasn't! (had to change the extension by string manipulation and it looks like Mac's bash is a bit different also)
for x in $(ls *.xlsx); do x1=${x%".xlsx"}; in2csv $x > $x1.csv; echo "$x1.csv done."; done
Note:
${x%”.xlsx”}
is bash string manipulation which clips .xlsx
from the end of the string. You can use following approach which is ok for small projects
<body onresize="yourHandler(event)">
function yourHandler(e) {
console.log('Resized:', e.target.innerWidth)
}
_x000D_
<body onresize="yourHandler(event)">
Content... (resize browser to see)
</body>
_x000D_
Here is a short cheatsheet that covers typical cases:
// sort
list.sort(naturalOrder())
// sort (reversed)
list.sort(reverseOrder())
// sort by field
list.sort(comparing(Type::getField))
// sort by field (reversed)
list.sort(comparing(Type::getField).reversed())
// sort by int field
list.sort(comparingInt(Type::getIntField))
// sort by double field (reversed)
list.sort(comparingDouble(Type::getDoubleField).reversed())
// sort by nullable field (nulls last)
list.sort(comparing(Type::getNullableField, nullsLast(naturalOrder())))
// two-level sort
list.sort(comparing(Type::getField1).thenComparing(Type::getField2))
For example, you can pluck all fields from a result like this below.
I am picking out the 'balance' from an array and save to a variable
$kii = $user->pluck('balance');
then on the next line u can sum like this:
$sum = $kii->sum();
Hope it helps.
I use this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class IconImageUtilities
{
public static void setIconImage(Window window)
{
try
{
InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
BufferedImage bufferedImage = ImageIO.read(imageInputStream);
window.setIconImage(bufferedImage);
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}
Just place your image called Icon.png
in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window
family such as JFrame
or JDialog
:
IconImageUtilities.setIconImage(this);
Here is my recursive PHP function to convert PHP objects to an associative array:
// ---------------------------------------------------------
// ----- object_to_array_recursive --- function (PHP) ------
// ---------------------------------------------------------
// --- arg1: -- $object = PHP Object - required --
// --- arg2: -- $assoc = TRUE or FALSE - optional --
// --- arg3: -- $empty = '' (Empty String) - optional --
// ---------------------------------------------------------
// ----- Return: Array from Object --- (associative) -------
// ---------------------------------------------------------
function object_to_array_recursive($object, $assoc=TRUE, $empty='')
{
$res_arr = array();
if (!empty($object)) {
$arrObj = is_object($object) ? get_object_vars($object) : $object;
$i=0;
foreach ($arrObj as $key => $val) {
$akey = ($assoc !== FALSE) ? $key : $i;
if (is_array($val) || is_object($val)) {
$res_arr[$akey] = (empty($val)) ? $empty : object_to_array_recursive($val);
}
else {
$res_arr[$akey] = (empty($val)) ? $empty : (string)$val;
}
$i++;
}
}
return $res_arr;
}
// ---------------------------------------------------------
// ---------------------------------------------------------
Usage example:
// ---- Return associative array from object, ... use:
$new_arr1 = object_to_array_recursive($my_object);
// -- or --
// $new_arr1 = object_to_array_recursive($my_object, TRUE);
// -- or --
// $new_arr1 = object_to_array_recursive($my_object, 1);
// ---- Return numeric array from object, ... use:
$new_arr2 = object_to_array_recursive($my_object, FALSE);
For the kinds of large files I tend to get, I generally wouldn't even do this in R. I would use the cut
command in Linux to process data before it gets to R. This isn't a critique of R, just a preference for using some very basic Linux tools like grep, tr, cut, sort, uniq, and occasionally sed & awk (or Perl) when there's something to be done about regular expressions.
Another reason to use standard GNU commands is that I can pass them back to the source of the data and ask that they prefilter the data so that I don't get extraneous data. Most of my colleagues are competent with Linux, fewer know R.
(Updated) A method that I would like to use before long is to pair mmap
with a text file and examine the data in situ, rather than read it at all into RAM. I have done this with C, and it can be blisteringly fast.
try using .animate instead of .css or even just on the opacity one and leave .css on the display?? may b
jQuery(document).ready(function(){
if (jQuery('#nav .drop').animate('display') === 'block') {
jQuery('#main').animate('opacity') = '0.6';
You just use the method
public Object put(Object key, Object value)
if the key was already present in the Map then the previous value is returned.
Without INDIRECT(): =CELL("width", OFFSET($A$1,ROW()-1,COLUMN()-1) )
Some additional things that I can think of.
As @allsyed said sys.argv gives a list of components (including program name), so if you want to know the number of elements passed through command line you can use len() to determine it. Based on this, you can design exception/error messages if user didn't pass specific number of parameters.
Also if you looking for a better way to handle command line arguments, I would suggest you look at https://docs.python.org/2/howto/argparse.html
Assert.assertTrue(Math.abs(actual-expected) == 0)
Connect to your server via SSH
then connect to your mysql console
and
USE user_base
REPAIR TABLE TABLE;
If there are a lot of broken tables in current database:
mysqlcheck -uUSER -pPASSWORD --repair --extended user_base
If there are a lot of broken tables in a lot of databases:
mysqlcheck -uUSER -pPASSWORD --repair --extended -A
This can also be achieved using the Scalar-Valued Function
in MSSQL 2008
Declare your function as following,
CREATE FUNCTION [dbo].[FunctionName]
(@MaskId INT)
RETURNS Varchar(500)
AS
BEGIN
DECLARE @SchoolName varchar(500)
SELECT @SchoolName =ISNULL(@SchoolName ,'')+ MD.maskdetail +', '
FROM maskdetails MD WITH (NOLOCK)
AND MD.MaskId=@MaskId
RETURN @SchoolName
END
And then your final query will be like
SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid
ORDER BY m.maskname ;
Note: You may have to change the function, as I don't know the complete table structure.
Writing this answer as much for the community as for myself.
If there ever are problems symbolicating a crash report, one can overcome them as follows:
Create a separate folder, copy Foo.app
and Foo.app.dSYM
from the corresponding .xcarchive
into the folder. Also copy the .crash
report into the folder.
Open the crash report in TextEdit or elsewhere, go to the Binary Images:
section, and copy the first address there (e.g. 0xd7000
).
cd
into the folder. Now you can run the following command:
xcrun atos -o Foo.app/Foo -arch arm64 -l 0xd7000 0x0033f9bb
This will symbolicate the symbol at address 0x0033f9bb
. Please make sure to pick the correct value for the -arch
option (can be obtaned from the first line in the Binary Images:
section, or figured out from the Hardware Model:
in the crash report and the app's supported archs).
You can also copy the necessary addresses (e.g. a thread call stack) from the crash report directly into a text file (in TextEdit, hold Option and select the necessary text block, or copy and cut), to get something like this:
0x000f12fb
0x002726b7
0x0026d415
0x001f933b
0x001f86d3
Now you can save this into a text file, e.g. addr.txt
, and run the following command:
xcrun atos -o Foo.app/Foo -arch arm64 -l 0xd7000 -f addr.txt
This will give a nice symbolication for all the addresses at once.
P.S.
Before doing the above, it's worth checking that everything is set up correctly (as atos
will happily report something for basically any supplied address).
To do the checking, open the crash report, and go to the end of the call stack for Thread 0
. The first line from the end to list your app (usually the second one), e.g.:
34 Foo 0x0033f9bb 0xd7000 + 2525627
should be the main()
call. Symbolicating the address (0x0033f9bb
in this case) as described above should confirm that this is indeed main()
and not some random method or function.
If the address is not that of main()
, check your load address (-l
option) and arch (-arch
option).
P.P.S.
If the above doesn't work due to bitcode, download the dSYM for your build from iTunes Connect, extract the executable binary from the dSYM (Finder > Show Package Contents), copy it into the directory, and use it (i.e. Foo
) as the argument to atos
, instead of the Foo.app/Foo
.
I can see at least three options:
1.
df[:10]
2. Using head
df.head(10)
For negative values of n, this function returns all rows except the last n rows, equivalent to
df[:-n]
[Source].
3. Using iloc
df.iloc[:10]
Abstraction: Only necessary information is shown. Let's focus on the example of switching on a computer. The user does not have to know what goes on while the system is still loading (that information is hidden from the user).
Let's take another example, that of the ATM. The customer does not need to know how the machine reads the PIN and processes the transaction, all he needs to do is enter the PIN, take the cash and leave.
Encapsulation: Deals with hiding the sensitive data of a clas hence privatising part of it. It is a way of keeping some information private to its clients by allowing no access to it from outside.
"Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section."
No one actually answered the above part of the original poster's question.
Here's the answer: http://www.456bereastreet.com/archive/201112/the_difference_between_widthauto_and_width100/
As long as the value of width is auto, the element can have horizontal margin, padding and border without becoming wider than its container...
On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border... This may be what you want, but most likely it isn’t.
To visualise the difference I made an example: http://www.456bereastreet.com/lab/width-auto/
A File object in Java is a representation of a path to a directory or file, not the file itself. You don't need to have write access to the filesystem to create a File
object, you only need it if you intend to actually write to the file (using a FileOutputStream for example)
I use the following static helper method to retrieve the IP of a client:
public static String getClientIpAddr(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getHeader("HTTP_X_FORWARDED");
}
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getHeader("HTTP_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getHeader("HTTP_FORWARDED");
}
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getHeader("HTTP_VIA");
}
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getHeader("REMOTE_ADDR");
}
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
ip = request.getRemoteAddr();
}
return ip;
}
As the official specification says, "one or more different sets of data are combined in a single body". So when photos and music are handled as multipart messages as mentioned in the question, probably there is some plain text metadata associated as well, thus making the request containing different types of data (binary, text), which implies the usage of multipart.
I got here with a bit more general problem - I wanted to find files in directories matching pattern but not in their subdirectories.
My solution (assuming we're looking for all cpp
files living directly in arch
directories):
find . -path "*/arch/*/*" -prune -o -path "*/arch/*.cpp" -print
I couldn't use maxdepth since it limited search in the first place, and didn't know names of subdirectories that I wanted to exclude.
Reading all the explanations above, let me try to condense:
The problem might be your split()
call. Try just split(" ")
without the square brackets.
Maybe you got your columns backwards??
ALTER TABLE Employees
ADD FOREIGN KEY (UserID) <-- this needs to be a column of the Employees table
REFERENCES ActiveDirectories(id) <-- this needs to be a column of the ActiveDirectories table
Could it be that the column is called ID
in the Employees
table, and UserID
in the ActiveDirectories
table?
Then your command should be:
ALTER TABLE Employees
ADD FOREIGN KEY (ID) <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID) <-- column in table "ActiveDirectories"
You need to use jq 'keys[]'
. For example:
echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'
Will output a line separated list:
"example1"
"example2"
"example3"
Following solution worked for me.
.algncenterdiv {
display: block;
margin-left: auto;
margin-right: auto;
}
Line magics are only supported by the IPython command line. They cannot simply be used inside a script, because %something
is not correct Python syntax.
If you want to do this from a script you have to get access to the IPython API and then call the run_line_magic
function.
Instead of %matplotlib inline
, you will have to do something like this in your script:
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
A similar approach is described in this answer, but it uses the deprecated magic
function.
Note that the script still needs to run in IPython. Under vanilla Python the get_ipython
function returns None
and get_ipython().run_line_magic
will raise an AttributeError
.
So, if you have a statement something like the following, you're saying that you get no 'print' result?
select * from sysobjects PRINT 'Just selected * from sysobjects'
If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the timing of seeing the print statements, you may want to try using something like
raiserror ('My Print Statement', 10,1) with nowait
This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.
Add set nocount on
to the beginning of the stored proc (if you're on SQL Server). I just solved this problem in my own work and it was caused by intermediate results, such as "1203 Rows Affected"
, being loaded into the Recordset
I was trying to use.
The only issue I see are relative links and templates not being properly loaded because of this.
from the docs regarding HTML5 mode
Relative links
Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (
<base href="/my-base">
) or you must use absolute urls (starting with/
) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.
In your case you can add a forward slash /
in href
attributes ($location.path
does this automatically) and also to templateUrl
when configuring routes. This avoids routes like example.com/tags/another
and makes sure templates load properly.
Here's an example that works:
<div>
<a href="/">Home</a> |
<a href="/another">another</a> |
<a href="/tags/1">tags/1</a>
</div>
<div ng-view></div>
And
app.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: '/partials/template1.html',
controller: 'ctrl1'
})
.when('/tags/:tagId', {
templateUrl: '/partials/template2.html',
controller: 'ctrl2'
})
.when('/another', {
templateUrl: '/partials/template1.html',
controller: 'ctrl1'
})
.otherwise({ redirectTo: '/' });
});
If using Chrome you will need to run this from a server.
The dropdown width itself cannot be set. It's width depend on the option-values. See also here ( jsfiddle.net/LgS3C/ )
How the select box looks like is also depending on your browser.
You can build your own control or use Select2 https://select2.org
You should use Terms Query
{
"query" : {
"terms" : {
"tags" : ["c", "d"]
}
}
}
There is a way to use guards for individual (or multiple) attributes.
@debug: true;
header {
/* guard for attribute */
& when (@debug = true) {
background-color: yellow;
}
/* guard for nested class */
#title when (@debug = true) {
background-color: orange;
}
}
/* guard for class */
article when (@debug = true) {
background-color: red;
}
/* and when debug is off: */
article when not (@debug = true) {
background-color: green;
}
...and with Less 1.7; compiles to:
header {
background-color: yellow;
}
header #title {
background-color: orange;
}
article {
background-color: red;
}
I faced a similar kind of issue while using a custom object as a key in Treemap. Whenever you are using a custom object as a key in hashmap then you override two function equals and hashcode, However if you are using ContainsKey method of Treemap on this object then you need to override CompareTo method as well otherwise you will be getting this error Someone using a custom object as a key in hashmap in kotlin should do like following
data class CustomObjectKey(var key1:String = "" , var
key2:String = ""):Comparable<CustomObjectKey?>
{
override fun compareTo(other: CustomObjectKey?): Int {
if(other == null)
return -1
// suppose you want to do comparison based on key 1
return this.key1.compareTo((other)key1)
}
override fun equals(other: Any?): Boolean {
if(other == null)
return false
return this.key1 == (other as CustomObjectKey).key1
}
override fun hashCode(): Int {
return this.key1.hashCode()
}
}
For the case: "This has not been pushed, only committed." - if you use IntelliJ (or another JetBrains IDE) and you haven't pushed changes yet you can do next.
Done.
This will "uncommit" your changes and return your git status to the point before your last local commit. You will not lose any changes you made.
Theres two properties on the model you need to set. The first $primaryKey
to tell the model what column to expect the primary key on. The second $incrementing
so it knows the primary key isn't a linear auto incrementing value.
class MyModel extends Model
{
protected $primaryKey = 'my_column';
public $incrementing = false;
}
For more info see the Primary Keys
section in the documentation on Eloquent.
Found the solution as below.... posting it as it could help somebody else too :)
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
XMLGregorianCalendar xmlGregCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
System.out.println(xmlGregCal);
Output:
2014-04-24T11:15:00.000+02:00
You need to tell scp
where to send the file. In your command that is not working:
scp C:\Users\Admin\Desktop\WMU\5260\A2.c ~
You have not mentioned a remote server. scp
uses :
to delimit the host and path, so it thinks you have asked it to download a file at the path \Users\Admin\Desktop\WMU\5260\A2.c
from the host C
to your local home directory.
The correct upload command, based on your comments, should be something like:
C:\> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:
If you are running the command from your home directory, you can use a relative path:
C:\Users\Admin> pscp Desktop\WMU\5260\A2.c [email protected]:
You can also mention the directory where you want to this folder to be downloaded to at the remote server. i.e by just adding a path to the folder as below:
C:/> pscp C:\Users\Admin\Desktop\WMU\5260\A2.c [email protected]:/home/path_to_the_folder/
Unfortunately not... However, there's a simple trick if it's going to be less than 24 hours.
Oracle assumes that a number added to a date is in days. Convert the number of seconds into days. Add the current day, then use the to_date
function to take only the parts your interested in. Assuming you have x
seconds:
select to_char(sysdate + (x / ( 60 * 60 * 24 ) ), 'HH24:MI:SS')
from dual
This won't work if there's more than 24 hours, though you can remove the current data again and get the difference in days, hours, minutes and seconds.
If you want something like: 51:10:05
, i.e. 51 hours, 10 minutes and 5 seconds then you're going to have to use trunc
.
Once again assuming that you have x
seconds...
trunc(x / 60 / 60)
trunc((x - ( trunc(x / 60 / 60) * 60 * 60 )) / 60)
x - hours * 60 * 60 - minutes * 60
Leaving you with:
with hrs as (
select x, trunc(x / 60 / 60) as h
from dual
)
, mins as (
select x, h, trunc((x - h * 60 * 60) / 60) as m
from hrs
)
select h, m, x - (h * 60 * 60) - (m * 60)
from mins
I've set up a SQL Fiddle to demonstrate.
If you're okay with ES2017, await
is good:
const DEF_DELAY = 1000;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}
await sleep(100);
Note that the await
part needs to be in an async function:
//IIAFE (immediately invoked async function expression)
(async()=>{
//Do some stuff
await sleep(100);
//Do some more stuff
})()
You should check with SMTP.
That means you have to connect to that email's SMTP server.
After connecting to the SMTP server you should send these commands:
HELO somehostname.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>
If you get "<[email protected]> Relay access denied" that means this email is Invalid.
There is a simple PHP class. You can use it:
http://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html
By using drop_duplicates
pd.concat([df1,df2]).drop_duplicates(keep=False)
Update :
Above method only working for those dataframes they do not have duplicate itself, For example
df1=pd.DataFrame({'A':[1,2,3,3],'B':[2,3,4,4]})
df2=pd.DataFrame({'A':[1],'B':[2]})
It will output like below , which is wrong
Wrong Output :
pd.concat([df1, df2]).drop_duplicates(keep=False)
Out[655]:
A B
1 2 3
Correct Output
Out[656]:
A B
1 2 3
2 3 4
3 3 4
How to achieve that?
Method 1: Using isin
with tuple
df1[~df1.apply(tuple,1).isin(df2.apply(tuple,1))]
Out[657]:
A B
1 2 3
2 3 4
3 3 4
Method 2: merge
with indicator
df1.merge(df2,indicator = True, how='left').loc[lambda x : x['_merge']!='both']
Out[421]:
A B _merge
1 2 3 left_only
2 3 4 left_only
3 3 4 left_only
Based on official documentation https://developer.android.com/studio/command-line/variables.html you should change ANDROID_AVD_HOME environment var:
Emulator Environment Variables
By default, the emulator stores configuration files under $HOME/.android/ and AVD data under $HOME/.android/avd/. You can override the defaults by setting the following environment variables. The emulator -avd command searches the avd directory in the order of the values in $ANDROID_AVD_HOME, $ANDROID_SDK_HOME/.android/avd/, and $HOME/.android/avd/. For emulator environment variable help, type emulator -help-environment at the command line. For information about emulator command-line options, see Control the Emulator from the Command Line.
- ANDROID_EMULATOR_HOME: Sets the path to the user-specific emulator configuration directory. The default location is
$ANDROID_SDK_HOME/.android/.- ANDROID_AVD_HOME: Sets the path to the directory that contains all AVD-specific files, which mostly consist of very large disk images. The default location is $ANDROID_EMULATOR_HOME/avd/. You might want to specify a new location if the default location is low on disk space.
After change or set ANDROID_AVD_HOME you will have to move all content inside ~user/.android/avd/ to your new location and change path into ini file of each emulator, just replace it with your new path
Just use look-arounds to solve this:
(?<=^|,)garp(?=$|,)
The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.
As @alucic mentioned, use:
composer require vendor/package:version
or you can use:
composer update vendor/package:version
You should probably review this StackOverflow post about differences between composer install and composer update.
Related to question about version numbers, you can review Composer documentation on versions, but here in short:
So, with Tilde you will get automatic updates of patches but minor and major versions will not be updated. However, if you use Caret you will get patches and minor versions, but you will not get major (breaking changes) versions.
Tilde Version is considered a "safer" approach, but if you are using reliable dependencies (well-maintained libraries) you should not have any problems with Caret Version (because minor changes should not be breaking changes.
If you're using jQuery UI too, you can do like this:
var e = jQuery.Event("keypress");
e.keyCode = $.ui.keyCode.ENTER;
$("input").trigger(e);
Quite simple actually:
mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%{$needle}%'
");
The %
is a wildcard for any characters set (none, one or many). Do note that this can get slow on very large datasets so if your database grows you'll need to use fulltext indices.
The main reason you'd do this is to decouple your code from a specific implementation of the interface. When you write your code like this:
List list = new ArrayList();
the rest of your code only knows that data is of type List
, which is preferable because it allows you to switch between different implementations of the List
interface with ease.
For instance, say you were writing a fairly large 3rd party library, and say that you decided to implement the core of your library with a LinkedList
. If your library relies heavily on accessing elements in these lists, then eventually you'll find that you've made a poor design decision; you'll realize that you should have used an ArrayList
(which gives O(1) access time) instead of a LinkedList
(which gives O(n) access time). Assuming you have been programming to an interface, making such a change is easy. You would simply change the instance of List
from,
List list = new LinkedList();
to
List list = new ArrayList();
and you know that this will work because you have written your code to follow the contract provided by the List
interface.
On the other hand, if you had implemented the core of your library using LinkedList list = new LinkedList()
, making such a change wouldn't be as easy, as there is no guarantee that the rest of your code doesn't make use of methods specific to the LinkedList
class.
All in all, the choice is simply a matter of design... but this kind of design is very important (especially when working on large projects), as it will allow you to make implementation-specific changes later without breaking existing code.
var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);
We should be using --scan --pattern with redis 2.8 and later.
You can try using this wrapper on top of redis-cli. https://github.com/VijayantSoni/redis-helper
Element
inherits from Node
, in the same way that Dog
inherits from Animal
.
An Element
object "is-a" Node
object, in the same way that a Dog
object "is-a" Animal
object.
Node
is for implementing a tree structure, so its methods are for firstChild
, lastChild
, childNodes
, etc. It is more of a class for a generic tree structure.
And then, some Node
objects are also Element
objects. Element
inherits from Node
. Element
objects actually represents the objects as specified in the HTML file by the tags such as <div id="content"></div>
. The Element
class define properties and methods such as attributes
, id
, innerHTML
, clientWidth
, blur()
, and focus()
.
Some Node
objects are text nodes and they are not Element
objects. Each Node
object has a nodeType
property that indicates what type of node it is, for HTML documents:
1: Element node
3: Text node
8: Comment node
9: the top level node, which is document
We can see some examples in the console:
> document instanceof Node
true
> document instanceof Element
false
> document.firstChild
<html>...</html>
> document.firstChild instanceof Node
true
> document.firstChild instanceof Element
true
> document.firstChild.firstChild.nextElementSibling
<body>...</body>
> document.firstChild.firstChild.nextElementSibling === document.body
true
> document.firstChild.firstChild.nextSibling
#text
> document.firstChild.firstChild.nextSibling instanceof Node
true
> document.firstChild.firstChild.nextSibling instanceof Element
false
> Element.prototype.__proto__ === Node.prototype
true
The last line above shows that Element
inherits from Node
. (that line won't work in IE due to __proto__
. Will need to use Chrome, Firefox, or Safari).
By the way, the document
object is the top of the node tree, and document
is a Document
object, and Document
inherits from Node
as well:
> Document.prototype.__proto__ === Node.prototype
true
Here are some docs for the Node and Element classes:
https://developer.mozilla.org/en-US/docs/DOM/Node
https://developer.mozilla.org/en-US/docs/DOM/Element
You could try using the -Clear
parameter
Example:-Clear Attribute1LDAPDisplayName, Attribute2LDAPDisplayName
Kruskal can have better performance if the edges can be sorted in linear time, or are already sorted.
Prim's better if the number of edges to vertices is high.
Why not just use atoi? For example:
char myarray[4] = {'-','1','2','3'};
int i = atoi(myarray);
printf("%d\n", i);
Gives me, as expected:
-123
Update: why not - the character array is not null terminated. Doh!
[object Object]
This means somewhere the object is being converted to a string.
Converted to a string:
//Copy and paste in the browser console to see result
var product = {'name':'test'};
JSON.stringify(product + '');
Not converted to a string:
//Copy and paste in the browser console to see result
var product = {'name':'test'};
JSON.stringify(product);
My problem was having an export twice in index.ts
Removing one of them solved the problem.
This will solve all gulp problem
sudo npm install gulp && sudo npm install --save del && sudo gulp build
Cast the value so the compiler knows which function to call:
p.setval(static_cast<const char *>( 0 ));
Note, that you have a segmentation fault in your code after you get it to compile (depending on which function you really wanted to call).
Again with getElementById, but instead .value, use .innerText
<td id="test">Chicken</td>
document.getElementById('test').innerText; //the value of this will be 'Chicken'
It has discussed many times in SO. In short, "%z" is not supported because platform not support it. My solution is a new one, just skip the time zone.:
datetime.datetime.strptime(re.sub(r"[+-]([0-9])+", "", "Tue May 08 15:14:45 +0800 2012"),"%a %b %d %H:%M:%S %Y")
step 1: click on the blue icon on taskbar. It is "SDK MANAGER". Then next click on the Appearance & Behaviour -> System Settings -> Android Sdk
step2: select on "Android SDK location" and choose edit option.It will prompt you update/install the components. Then start the download or update and this may take a while , all you have to do is wait patiently. "In case you have previously installed the sdk it will show that the sdk android sdk is installed"
step3: once this is done the program will compile fine ,and no error will exist whatsoever.
I solved this in Windows 10 by using cmd instead of GitBash.
It has to do with character case and how git and command lines handles them.
Given a list of dates dates
:
Max date is max(dates)
Min date is min(dates)
Wrap the label and the input within a bootstraps div
<div class ="row">
<div class="col-md-4">Name:</div>
<div class="col-md-8"><input type="text"></div>
</div>
I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:
http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html
there is no color parameter listed where you might be able to set the colors for your bar graph.
However, the Series.plot() docs state the following at the end of the parameter list:
kwds : keywords
Options to pass to matplotlib plotting method
What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().
If you examine the docs for the matplotlib.pyplot.bar() method here:
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar
..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.
Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series(
[5, 4, 4, 1, 12],
index = ["AK", "AX", "GA", "SQ", "WN"]
)
#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')
#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')
#Plot the data:
my_colors = 'rgbkymc' #red, green, blue, black, etc.
pd.Series.plot(
s,
kind='bar',
color=my_colors,
)
plt.show()
Note that if there are more bars than colors in your sequence, the colors will repeat.
https://github.com/app-z/Json-to-SQLite
At first generate Plain Old Java Objects from JSON http://www.jsonschema2pojo.org/
Main method
void createDb(String dbName, String tableName, List dataList, Field[] fields){ ...
Fields name will create dynamically
This worked for with maven 3.5.4 and now Intellij Idea see this code as source:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<generatedSourcesDirectory>src/main/generated</generatedSourcesDirectory>
</configuration>
</plugin>
You can close a figure by calling matplotlib.pyplot.close
, for example:
from numpy import *
import matplotlib.pyplot as plt
from scipy import *
t = linspace(0, 0.1,1000)
w = 60*2*pi
fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)
You can also close all open figures by calling matplotlib.pyplot.close("all")
This is fixed in later versions of PHPMyAdmin. The Ubuntu Software Repositories for Ubuntu 18.04.2 holds version 4.6.6.5, while they're currently at 4.9.0.1. Updating your PHPMyAdmin installation will fix this problem, but might prove to be riskier than just editing that one line of code. Here's how I did it on my Ubuntu Server. Steps are essentially the same (with a different path) for all operating systems.
wget https://files.phpmyadmin.net/phpMyAdmin/4.9.0.1/phpMyAdmin-4.9.0.1-all-languages.zip
unzip phpMyAdmin-4.9.0.1-all-languages.zip
cp -r /usr/share/phpmyadmin ~/phpmyadmin-backup
cd phpMyAdmin-4.9.0.1-all-languages
rm -r /usr/share/phpmyadmin/doc/html
cp -R * /usr/share/phpmyadmin/
Verify that it works. If it doesn't, welll... You have a backup, so restore it and manually edit the faulty line. In my own personal experience, I discovered after doing this that version 4.6.6.5 was not only riddled with bugs, but also incredibly slow compared to the new 4.9.0.1. The speed increase was pure magic for something I though was of "WordPress" quality.
Having criticized the much-loved red-shaded Venn diagram, I thought it only fair to post my own attempt.
Although @Martin Smith's answer is the best of this bunch by a long way, his only shows the key column from each table, whereas I think ideally non-key columns should also be shown.
The best I could do in the half hour allowed, I still don't think it adequately shows that the nulls are there due to absence of key values in TableB
or that OUTER JOIN
is actually a union rather than a join:
Maybe, you have modified the structure of the war or deploying it on a different server version. Checkout these links Error deploying war into JBoss AS 7 (domain mode): "Failed to process phase STRUCTURE of deployment" and https://community.jboss.org/thread/199387?start=0&tstart=0&_sscc=t
If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$tag = 'YOUR_TAG_HERE';
$client_id = "YOUR_CLIENT_ID";
$url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
//Now parse through the $results array to display your results...
foreach($results['data'] as $item){
$image_link = $item['images']['low_resolution']['url'];
echo '<img src="'.$image_link.'" />';
}
Mine is the console application (it should work for the windows application as well) and I had same problem. To solve it I used PlatformTarget as x64 as my System.Data.OracleClient.dll (64 bit file) is at C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5. This will explicitly use 64 bit version of Oracle Client. This might help you if your solution works only on 64bit and if you are not using 32 bit dlls like dlls made in VB. I hope it will help you.
SELECT CAST(<COLUMN Name> AS VARCHAR(3)) + ','
FROM <TABLE Name>
FOR XML PATH('')
Use enumerate()
like so:
def draw_menu(options, selected_index):
for counter, option in enumerate(options):
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)
Note: You can optionally put parenthesis around counter, option
, like (counter, option)
, if you want, but they're extraneous and not normally included.
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
This works well for me:
jQuery(document).ready(function($) {
var intputElements = document.getElementsByTagName("INPUT");
for (var i = 0; i < intputElements.length; i++) {
intputElements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
if (e.target.name == "email") {
e.target.setCustomValidity("Please enter a valid email address.");
} else {
e.target.setCustomValidity("Please enter a password.");
}
}
}
}
});
and the form I'm using it with (truncated):
<form id="welcome-popup-form" action="authentication" method="POST">
<input type="hidden" name="signup" value="1">
<input type="email" name="email" id="welcome-email" placeholder="Email" required></div>
<input type="password" name="passwd" id="welcome-passwd" placeholder="Password" required>
<input type="submit" id="submitSignup" name="signup" value="SUBMIT" />
</form>
By default the Launcher Activity in you app will be launched when your app is in background and you click the notification, if you have any data part with your notifcation you can handle it in the same activity as follows,
if(getIntent().getExtras()! = null){
//do your stuff
}else{
//do that you normally do
}
You can use the dict.fromkeys
class method ...
>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}
This is the fastest way to create a dictionary where all the keys map to the same value.
But do not use this with mutable objects:
d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!
If you don't actually need to initialize all the keys, a defaultdict
might be useful as well:
from collections import defaultdict
d = defaultdict(True)
To answer the second part, a dict-comprehension is just what you need:
{k: k for k in range(10)}
You probably shouldn't do this but you could also create a subclass of dict
which works somewhat like a defaultdict
if you override __missing__
:
>>> class KeyDict(dict):
... def __missing__(self, key):
... #self[key] = key # Maybe add this also?
... return key
...
>>> d = KeyDict()
>>> d[1]
1
>>> d[2]
2
>>> d[3]
3
>>> print(d)
{}
Without explicitly providing the type as in command.Parameters.Add("@ID", SqlDbType.Int);
, it will try to implicitly convert the input to what it is expecting.
The downside of this, is that the implicit conversion may not be the most optimal of conversions and may cause a performance hit.
There is a discussion about this very topic here: http://forums.asp.net/t/1200255.aspx/1
For who is searching to do it without creating a background sector, just add those lines to the TextView
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
Also to make it selectable use:
android:textIsSelectable="true"
In my case, there was a mistake in the list of the parameters was not well formed. So make sure the parameters are well formed. For e.g. correct format of parameters
data: {'reporter': reporter,'partner': partner,'product': product}
All good answers above. One extra thing you should keep in mind - you can also have a pure virtual destructor. The only difference is that you still need to implement it.
Confused?
--- header file ----
class foo {
public:
foo() {;}
virtual ~foo() = 0;
virtual bool overrideMe() {return false;}
};
---- source ----
foo::~foo()
{
}
The main reason you'd want to do this is if you want to provide interface methods, as I have, but make overriding them optional.
To make the class an interface class requires a pure virtual method, but all of your virtual methods have default implementations, so the only method left to make pure virtual is the destructor.
Reimplementing a destructor in the derived class is no big deal at all - I always reimplement a destructor, virtual or not, in my derived classes.
It depends on what is in test.py
. The following is an appropriate structure:
# suppose this is your 'test.py' file
def main():
"""This function runs the core of your program"""
print("running main")
if __name__ == "__main__":
# if you call this script from the command line (the shell) it will
# run the 'main' function
main()
If you keep this structure, you can run it like this in the command line (assume that $
is your command-line prompt):
$ python test.py
$ # it will print "running main"
If you want to run it from the Python shell, then you simply do the following:
>>> import test
>>> test.main() # this calls the main part of your program
There is no necessity to use the subprocess
module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.
DECLARE @JCnt int=null
SEt @JCnt=(SELECT COUNT( ISNUll(EmpCode,0)) FROM tbl_Employees WHERE EmpCode=1 )
UPDATE #TempCode
SET janCA= CASE WHEN @JCnt>0 THEN (SELECT SUM (ISNUll(Amount,0)) FROM tbl_Salary WHERE Code=1 )ELSE 0 END
WHERE code=1
First, add the iOS Simulator to Applications:
ln -s /Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app /Applications/iPhone\ Simulator.app
From there you can open it in Finder or drag it to the launch bar.
Source: http://www.bram.us/2010/05/05/xcode-iphone-simulator-location/
Or simply:
Date.now
From MDN documentation:
The Date.now() method returns the number of milliseconds elapsed since January 1, 1970
Available since ECMAScript 5.1
It's the same as was mentioned above (new Date().getTime()
), but more shortcutted version.
In some cases it is tied to how the field is used. In some DB engines the field differences determine how (and if) you search for text in the field. CharFields are typically used for things that are searchable, like if you want to search for "one" in the string "one plus two". Since the strings are shorter they are less time consuming for the engine to search through. TextFields are typically not meant to be searched through (like maybe the body of a blog) but are meant to hold large chunks of text. Now most of this depends on the DB Engine and like in Postgres it does not matter.
Even if it does not matter, if you use ModelForms you get a different type of editing field in the form. The ModelForm will generate an HTML form the size of one line of text for a CharField and multiline for a TextField.
tl;dr What to do in modern (2018) times? Assume tel:
is supported, use it and forget about anything else.
The tel:
URI scheme RFC5431 (as well as sms:
but also feed:
, maps:
, youtube:
and others) is handled by protocol handlers (as mailto:
and http:
are).
They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto:
protocol handler with same meaning and behaviour of tel:
but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.
What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler()
and related functions) simplifying also the check for their support through isProtocolHandlerRegistered()
function.
There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).
In general what I suggest is:
tel:
is supported (yes, it's not true for very old devices but IMO you can ignore them).tel:
isn't supported then change links to use callto:
and repeat check desctibed in 3.tel:
and callto:
aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href
with javascript:void(0)
and (if number isn't repeated in text span) putting, telephone number in title
. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto:
and tel:
.Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:
tel:
is supported.tel:
with callto:
.tel:
or leave it as is (assuming there are good chances Skype is installed).I had to unistall the Workstation Components and SSMS Tools Pack (SSMS Tools Pack is an add-in for Microsoft SQL Server Management Studio (SSMS) including SSMS Express.) Installation of SQL 2008 is now proceeding as it should.
if all you need is the names, use xpath instead. No need to do the iteration yourself and check for null.
string xml = @"
<root>
<Employee name=""an"" />
<Employee name=""nobyd"" />
<Employee/>
</root>
";
var doc = new XmlDocument();
//doc.Load(path);
doc.LoadXml(xml);
var names = doc.SelectNodes("//Employee/@name");
Change from
<security mode="None">
to
<security mode="Transport">
in your web.config file. This change will allow you to use https instead of http