Expanding on @user2366975's answer, to get the current screen size in a multi-screen setup using Tkinter (code in Python 2/3):
try:
# for Python 3
import tkinter as tk
except ImportError:
# for Python 2
import Tkinter as tk
def get_curr_screen_geometry():
"""
Workaround to get the size of the current screen in a multi-screen setup.
Returns:
geometry (str): The standard Tk geometry string.
[width]x[height]+[left]+[top]
"""
root = tk.Tk()
root.update_idletasks()
root.attributes('-fullscreen', True)
root.state('iconic')
geometry = root.winfo_geometry()
root.destroy()
return geometry
(Should work cross-platform, tested on Linux only)
you can create bitmaps for the highes resolution / size your application will run and resize them in the code (at run time)
check this article http://nuvornapps-en.blogspot.com.es/
From developer.android.com:
public void finishAffinity ()
Added in API level 16
Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch.
Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.
If you want the display dimensions in pixels you can use getSize
:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
If you're not in an Activity
you can get the default Display
via WINDOW_SERVICE
:
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
If you are in a fragment and want to acomplish this just use Activity.WindowManager (in Xamarin.Android) or getActivity().getWindowManager() (in java).
Before getSize
was introduced (in API level 13), you could use the getWidth
and getHeight
methods that are now deprecated:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight(); // deprecated
For the use case you're describing however, a margin/padding in the layout seems more appropriate.
Another way is: DisplayMetrics
A structure describing general information about a display, such as its size, density, and font scaling. To access the DisplayMetrics members, initialize an object like this:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
We can use widthPixels
to get information for:
"The absolute width of the display in pixels."
Example:
Log.d("ApplicationTagName", "Display width in px is " + metrics.widthPixels);
Api level 30 update
final WindowMetrics metrics = windowManager.getCurrentWindowMetrics();
// Gets all excluding insets
final WindowInsets windowInsets = metrics.getWindowInsets();
Insets insets = windowInsets.getInsetsIgnoreVisibility(WindowInsets.Type.navigationBars()
| WindowInsets.Type.displayCutout());
int insetsWidth = insets.right + insets.left;
int insetsHeight = insets.top + insets.bottom;
// Legacy size that Display#getSize reports
final Rect bounds = metrics.getBounds();
final Size legacySize = new Size(bounds.width() - insetsWidth,
bounds.height() - insetsHeight);
Go to Phone Settings --> Developer Options --> Simulate Secondary Displays
and turn it to None
.
If you don't see Developer Options
in the settings menu
(it should be at the bottom, go Settings ==> About phone
and tap on the Build number
a lot of times)
in Winforms, there is a Screen class you can use to get data about screen dimensions and color depth for all displays connected to the computer. Here's the docs page: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx
CHANGING the screen resolution is trickier. There is a Resolution third party class that wraps the native code you'd otherwise hook into. Use its CResolution nested class to set the screen resolution to a new height and width; but understand that doing this will only work for height/width combinations the display actually supports (800x600, 1024x768, etc, not 817x435).
Use AsyncTaskLoader to keep your data safe even if the activity changes, instead of using AsyncTask that is a better way to build apps than preventing screen rotation.
You should read Supporting multiple screens. You must define dpi on your emulator. 240 is hdpi, 160 is mdpi and below that are usually ldpi.
Extract from Android Developer Guide link above:
320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
You can use the Configuration.screenLayout
bitmask.
Example:
if ((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_LARGE) {
// on a large screen device ...
}
Edited solution that will make your SplashScreen look great on all APIs including API21 to API23
If you are only targeting APIs24+ you can simply scale down your vector drawable directly in its xml file like so:
<vector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:aapt="http://schemas.android.com/aapt"
android:viewportWidth="640"
android:viewportHeight="640"
android:width="240dp"
android:height="240dp">
<path
android:pathData="M320.96 55.9L477.14 345L161.67 345L320.96 55.9Z"
android:strokeColor="#292929"
android:strokeWidth="24" />
</vector>
in the code above I am rescaling a drawable I drew on a 640x640 canvas to be 240x240. then i just put it in my splash screen drawable like so and it works great:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque"
android:paddingBottom="20dp" android:paddingRight="20dp" android:paddingLeft="20dp" android:paddingTop="20dp">
<!-- The background color, preferably the same as your normal theme -->
<item>
<shape>
<size android:height="120dp" android:width="120dp"/>
<solid android:color="@android:color/white"/>
</shape>
</item>
<!-- Your product logo - 144dp color version of your app icon -->
<item
android:drawable="@drawable/logo_vect"
android:gravity="center">
</item>
</layer-list>
my code is actually only drawing the triangle in the picture at the bottom but here you see what you can achieve with this. Resolution is finally great as opposed to the pixelated edges I was getting when using bitmap. so use a vector drawable by all means (there is a site called vectr that I used to create mine without the hasle of downloading specialized software).
EDIT in order to make it work also on API21-22-23
While the solution above works for devices runing API24+ I got really disappointed after installing my app a device running API22. I noticed that the splashscreen was again trying to fill the entire view and looking like shit. After tearing my eyebrows out for half a day I finally brute-forced a solution by sheer willpower.
you need to create a second file named exactly like the splashscreen xml (lets say splash_screen.xml) and place it into 2 folders called drawable-v22 and drawable-v21 that you will create in the res/ folder (in order to see them you have to change your project view from Android to Project). This serves to tell your phone to redirect to files placed in those folders whenever the relevant device runs an API corresponding to the -vXX suffix in the drawable folder, see this link. place the following code in the Layer-list of the splash_screen.xml file that you create in these folders:
<item>
<shape>
<size android:height="120dp" android:width="120dp"/>
<solid android:color="@android:color/white"/>
</shape>
</item>
<!-- Your product logo - 144dp color version of your app icon -->
<item android:gravity="center">
<bitmap android:gravity="center"
android:src="logo_vect"/>
</item>
For some reason for these APIs you have to wrap your drawable in a bitmap in order to make it work and jet the final result looks the same. The issue is that you have to use the aproach with the aditional drawable folders as the second version of the splash_screen.xml file will lead to your splash screen not being shown at all on devices running APIs higher than 23. You might also have to place the first version of the splash_screen.xml into drawable-v24 as android defaults to the closest drawable-vXX folder it can find for resources. hope this helps
Note that
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden"
is added in the manifest file - where the activity is defined.
It can also be when you don't have a proper php extension loaded. I would double check that you have all of the required php extensions loaded on your system if it isn't the memory limit issue.
Using MediaQuery
class:
MediaQueryData queryData;
queryData = MediaQuery.of(context);
MediaQuery: Establishes a subtree in which media queries resolve to the given data.
MediaQueryData: Information about a piece of media (e.g., a window).
To get Device Pixel Ratio:
queryData.devicePixelRatio
To get width and height of the device screen:
queryData.size.width
queryData.size.height
To get text scale factor:
queryData.textScaleFactor
Using AspectRatio
class:
From doc:
A widget that attempts to size the child to a specific aspect ratio.
The widget first tries the largest width permitted by the layout constraints. The height of the widget is determined by applying the given aspect ratio to the width, expressed as a ratio of width to height.
For example, a 16:9 width:height aspect ratio would have a value of 16.0/9.0. If the maximum width is infinite, the initial width is determined by applying the aspect ratio to the maximum height.
Now consider a second example, this time with an aspect ratio of 2.0 and layout constraints that require the width to be between 0.0 and 100.0 and the height to be between 0.0 and 100.0. We'll select a width of 100.0 (the biggest allowed) and a height of 50.0 (to match the aspect ratio).
//example
new Center(
child: new AspectRatio(
aspectRatio: 100 / 100,
child: new Container(
decoration: new BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.orange,
)
),
),
),
Here is an example on how to center an object vertically with jQuery:
var div= $('#div_SomeDivYouWantToAdjust');
div.css("top", ($(window).height() - div.height())/2 + 'px');
But you could easily change that to whatever your needs are.
Put into css file:
html { background: url(images/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; }
URL images/bg.jpg is your background image
swift 3.0
for width
UIScreen.main.bounds.size.width
for height
UIScreen.main.bounds.size.height
You could just use the imageView's image cache. It will render the entire view as it is layed out (scaled,bordered with a background etc) to a new bitmap.
just make sure it built.
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
there's your bitmap as the screen saw it.
Here budy. This will give you only the width and height of the workarea
System.Windows.SystemParameters.WorkArea.Width
System.Windows.SystemParameters.WorkArea.Height
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace centrewindow
{
public partial class Form1 : Form
{
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
[DllImport("user32.dll")]
public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
[DllImport("user32.dll")]
public static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
CentreWindow(Handle, GetMonitorDimensions());
}
private void CentreWindow(IntPtr handle, Size monitorDimensions)
{
RECT rect;
GetWindowRect(new HandleRef(this, handle), out rect);
var x1Pos = monitorDimensions.Width/2 - (rect.Right - rect.Left)/2;
var x2Pos = rect.Right - rect.Left;
var y1Pos = monitorDimensions.Height/2 - (rect.Bottom - rect.Top)/2;
var y2Pos = rect.Bottom - rect.Top;
SetWindowPos(handle, 0, x1Pos, y1Pos, x2Pos, y2Pos, 0);
}
private Size GetMonitorDimensions()
{
return SystemInformation.PrimaryMonitorSize;
}
}
}
Centers any window you can get the handle of
You can get the screen size with the Toolkit.getScreenSize()
method.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
On a multi-monitor configuration you should use this :
GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();
If you want to get the screen resolution in DPI you'll have to use the getScreenResolution()
method on Toolkit
.
Resources :
I have the feeling that the check should be different
new: h < 768 || w < 1024
You can use this define to calculate if you are using the iPhone 5 based on screen size:
#define IS_IPHONE_5 ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
then use a simple if
statement :
if (IS_IPHONE_5) {
// What ever changes
}
you can Use Window Or Linux Os
import os
os.system('cls')
os.system('clear')
you can use subprocess module
import subprocess as sp
x=sp.call('cls',shell=True)
If the project is created using Xcode 6, then use the below mentioned code to detect the devices..
printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] nativeBounds].size.width,(int)[[UIScreen mainScreen] nativeBounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
{
if([[UIScreen mainScreen] nativeBounds].size.height == 960 || [[UIScreen mainScreen] nativeBounds].size.height == 480){
printf("Device Type : iPhone 4,4s ");
}else if([[UIScreen mainScreen] nativeBounds].size.height == 1136){
printf("Device Type : iPhone 5,5S/iPod 5 ");
}else if([[UIScreen mainScreen] nativeBounds].size.height == 1334){
printf("Device Type : iPhone 6 ");
}else if([[UIScreen mainScreen] nativeBounds].size.height == 2208){
printf("Device Type : iPhone 6+ ");
}
}
}else{
printf("Device Type : iPad");
}
If the project was created in Xcode 5 and opened in Xcode 6, then use the below mentioned code to detect the devices.(This code works if no launching images for iPhone 6,6+ are assigned)
printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] nativeBounds].size.width,(int)[[UIScreen mainScreen] nativeBounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
{
if([[UIScreen mainScreen] nativeBounds].size.height == 960 || [[UIScreen mainScreen] nativeBounds].size.height == 480){
printf("Device Type : iPhone 4,4s");
appType=1;
}else if([[UIScreen mainScreen] nativeBounds].size.height == 1136 || [[UIScreen mainScreen] nativeBounds].size.height == 1704){
printf("Device Type : iPhone 5,5S,6,6S/iPod 5 ");
appType=3;
}
}
}else{
printf("Device Type : iPad");
appType=2;
}
If you are still using Xcode 5 all together then use the following code to detect the devices (iPhone 6 and 6+ will not be detected)
printf("\nDetected Resolution : %d x %d\n\n",(int)[[UIScreen mainScreen] bounds].size.width,(int)[[UIScreen mainScreen] bounds].size.height);
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone){
if ([[UIScreen mainScreen] respondsToSelector: @selector(scale)])
{
CGSize result = [[UIScreen mainScreen] bounds].size;
CGFloat scale = [UIScreen mainScreen].scale;
result = CGSizeMake(result.width * scale, result.height * scale);
if(result.height == 960 || result.height == 480){
printf("Device Type : iPhone 4,4S ");
}else if(result.height == 1136){
printf("Device Type : iPhone 5s/iPod 5");
}
}
}else{
printf("Device Type : iPad");
}
Title bar in android is called Action bar. So if you want to remove it from any specific activity, go to AndroidManifest.xml and add the theme type. Such as android:theme="@style/Theme.AppCompat.Light.NoActionBar"
.
Example:
<activity
android:name=".SplashActivity"
android:noHistory="true"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Ctrl+A, Ctrl+K to wipe the current line in the terminal. You can then recall it with Ctrl+Y if you need.
To view a list of all images on your Docker host, run:
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
apache_snapshot latest 13037686eac3 22 seconds ago 249MB
ubuntu latest 00fd29ccc6f1 3 weeks ago 111MB
Now you can run the Docker image as a container in interactive mode:
$ docker run -it apache_snapshot /bin/bash
OR if you don't have any images locally,Search Docker Hub for an image to download:
$ docker search ubuntu
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
ubuntu Ubuntu is a Debian... 6759 [OK]
dorowu/ubuntu-desktop-lxde-vnc Ubuntu with openss... 141 [OK]
rastasheep/ubuntu-sshd Dockerized SSH ser... 114 [OK]
ansible/ubuntu14.04-ansible Ubuntu 14.04 LTS w... 88 [OK]
ubuntu-upstart Upstart is an even... 80 [OK]
Pull the Docker image from a repository with the docker pull command:
$ docker pull ubuntu
Run the Docker image as a container:
$ docker run -it ubuntu /bin/bash
If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.
<select
ng-model="Choice.SelectedOption"
ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>
Updated fiddle http://jsfiddle.net/gFCzV/34/
Python 3.6+:
coordinates = [('a',1,2), ('b',3,4), ('c',5,6)]
for x in coordinates: plt.annotate(x[0], (x[1], x[2]))
If a profiler is not applicable in your setup, you may try to identify the thread following steps in this post.
Basically, there are three steps:
top -H
and get PID of the thread with highest CPU.This works without needing jQuery:
var textArea = document.getElementById("my-text-area");
var arrayOfLines = textArea.value.split("\n"); // arrayOfLines is array where every element is string of one line
I have created an answer for this post that might help: https://stackoverflow.com/a/63816822/2399164
Summary:
I am a little late to the game but I believe I found a simple solution to this problem...
<?xml version="1.0" encoding="utf-8"?> <configuration> <packageSources> <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" /> <add key="{{CUSTOM NAME}}" value="{{CUSTOM SOURCE}}" /> </packageSources> <packageRestore> <add key="enabled" value="True" /> <add key="automatic" value="True" /> </packageRestore> <bindingRedirects> <add key="skip" value="False" /> </bindingRedirects> <packageManagement> <add key="format" value="0" /> <add key="disabled" value="False" /> </packageManagement> </configuration>
That is it! Create your "Dockerfile" here as well
Run docker build with your Dockerfile and all will get resolved
You can use the search
property of the window.location
object to obtain the query part of the URL. Note that it includes the question mark (?) at the beginning, just in case that affects how you intend to parse it.
def find_idx(str, ch):
yield [i for i, c in enumerate(str) if c == ch]
for idx in find_idx('babak karchini is a beginner in python ', 'i'):
print(idx)
output:
[11, 13, 15, 23, 29]
Another option is to use NewtonSoft.JSON.
var dictionary = JObject.FromObject(anObject).ToObject<Dictionary<string, object>>();
You could try my Beavertail ADSI browser - it should show you the current AD tree, and from it, you should be able to figure out the path and all.
Or if you're on .NET 3.5, using the System.DirectoryServices.AccountManagement
namespace, you could also do it programmatically:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
This would create a basic, default domain context and you should be able to peek at its properties and find a lot of stuff from it.
Or:
UserPrincipal myself = UserPrincipal.Current;
This will give you a UserPrincipal
object for yourself, again, with a ton of properties to inspect. I'm not 100% sure what you're looking for - but you most likely will be able to find it on the context or the user principal somewhere!
I got it!...hehe
protected DataTable RetrieveEmployeeSubInfo(string employeeNo)
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
try
{
cmd = new SqlCommand("RETRIEVE_EMPLOYEE", pl.ConnOpen());
cmd.Parameters.Add(new SqlParameter("@EMPLOYEENO", employeeNo));
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = dt;
}
catch (Exception x)
{
MessageBox.Show(x.GetBaseException().ToString(), "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
cmd.Dispose();
pl.MySQLConn.Close();
}
return dt;
}
#multiple-background{_x000D_
box-sizing: border-box;_x000D_
width: 123px;_x000D_
height: 30px;_x000D_
font-size: 12pt;_x000D_
border-radius: 7px; _x000D_
background: url("https://cdn0.iconfinder.com/data/icons/woocons1/Checkbox%20Full.png"), linear-gradient(to bottom, #4ac425, #4ac425);_x000D_
background-repeat: no-repeat, repeat;_x000D_
background-position: 5px center, 0px 0px;_x000D_
background-size: 18px 18px, 100% 100%;_x000D_
color: white; _x000D_
border: 1px solid #e4f6df;_x000D_
box-shadow: .25px .25px .5px .5px black;_x000D_
padding: 3px 10px 0px 5px;_x000D_
text-align: right;_x000D_
}
_x000D_
<div id="multiple-background"> Completed </div>
_x000D_
protected void grdDis_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
#region Dynamically Show gridView header From data base
getAllheaderName();/*To get all Allowences master headerName*/
TextBox txt_Days = (TextBox)grdDis.HeaderRow.FindControl("txtDays");
txt_Days.Text = hidMonthsDays.Value;
#endregion
}
}
The easiest way is to use python-memcached-stats package, https://github.com/abstatic/python-memcached-stats
The keys() method should get you going.
Example -
from memcached_stats import MemcachedStats
mem = MemcachedStats()
mem.keys()
['key-1',
'key-2',
'key-3',
... ]
When soapAction
is missing in the SOAP 1.2 request (and many clients do not set it, even when it is specified in WSDL), some app servers (eg. jboss) infer the "actual" soapAction
from {xsd:import namespace}+{wsdl:operation name}
.
So, to make the inferred "actual" soapAction
match the expected soapAction
, you can set the expected soapAction to {xsd:import namespace}+{wsdl:operation name}
in your WS definition (@WebMethod(action=...
) for Java EE)
Eg. for a typical Java EE case, this helps (not the Stewart's case, National Rail WS has 'soapAction' set):
@WebMethod(action = "http://packagename.of.your.webservice.class.com/methodName")
If you cannot change the server, you will have to force client to fill soapAction
.
you can use ClearContents. ex,
Range("X").Cells.ClearContents
The name of the array indicates the starting address. Starting address of both namet2
and nameIt2
are different. So the equal to (==
) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp()
, or we can compare character by character using a loop.
It seems that you want a list structure with very fast removal and random access by index (not by key) times. An ArrayList
gives you the latter and a HashMap
or TreeMap
give you the former.
There is one structure in Apache Commons Collections that may be what you are looking for, the TreeList. The JavaDoc specifies that it is optimized for quick insertion and removal at any index in the list. If you also need generics though, this will not help you.
To support IE11 with auto-placement, I converted grid
to table
layout every time I used the grid layout in 1 dimension only. I also used margin
instead of grid-gap
.
The result is the same, see how you can do it here https://jsfiddle.net/hp95z6v1/3/
Using Bootstrap 3.3.5 and .container-fluid
, this is how I get full width with no gutters or horizontal scrolling on mobile. Note that .container-fluid
was re-introduced in 3.1.
Full width on mobile/tablet, 1/4 screen on desktop
<div class="container-fluid"> <!-- Adds 15px left/right padding -->
<div class="row"> <!-- Adds -15px left/right margins -->
<div class="col-md-4 col-md-offset-4" style="padding-left: 0, padding-right: 0"> <!-- col classes adds 15px padding, so remove the same amount -->
<!-- Full-width for mobile -->
<!-- 1/4 screen width for desktop -->
</div>
</div>
</div>
Full width on all resolutions (mobile, table, desktop)
<div class="container-fluid"> <!-- Adds 15px left/right padding -->
<div class="row"> <!-- Adds -15px left/right margins -->
<div>
<!-- Full-width content -->
</div>
</div>
</div>
For those who use Gradle instead of Maven, add this to the dependencies in your build file:
compile('javax.xml.bind:jaxb-api:2.3.0')
On Unix:
touch .gitignore
On Windows:
echo > .gitignore
These commands executed in a terminal will create a .gitignore
file in the current location.
Then just add information to this .gitignore
file (using Notepad++ for example) which files or folders should be ignored. Save your changes. That's it :)
More information: .gitignore
On Mac OS X, save your file with a .py extension. Press ? + B. It runs in a window below.
To be clear and answer @Dean's question: EBS-type root storage doesn't seem to be ephemeral. Data is persistent across reboots and actually it doesn't make any sense to use ebs-backed root volume which is 'ephemeral'. This wouldn't be different from image-based root volume.
Big screen:
Small screen (Mobile)
if this is what you wanted this is code https://plnkr.co/edit/PCCJb9f7f93HT4OubLmM?p=preview
CSS + HTML + JQUERY :
_x000D_
@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";_x000D_
body {_x000D_
font-family: 'Poppins', sans-serif;_x000D_
background: #fafafa;_x000D_
}_x000D_
_x000D_
p {_x000D_
font-family: 'Poppins', sans-serif;_x000D_
font-size: 1.1em;_x000D_
font-weight: 300;_x000D_
line-height: 1.7em;_x000D_
color: #999;_x000D_
}_x000D_
_x000D_
a,_x000D_
a:hover,_x000D_
a:focus {_x000D_
color: inherit;_x000D_
text-decoration: none;_x000D_
transition: all 0.3s;_x000D_
}_x000D_
_x000D_
.navbar {_x000D_
padding: 15px 10px;_x000D_
background: #fff;_x000D_
border: none;_x000D_
border-radius: 0;_x000D_
margin-bottom: 40px;_x000D_
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
}_x000D_
_x000D_
.navbar-btn {_x000D_
box-shadow: none;_x000D_
outline: none !important;_x000D_
border: none;_x000D_
}_x000D_
_x000D_
.line {_x000D_
width: 100%;_x000D_
height: 1px;_x000D_
border-bottom: 1px dashed #ddd;_x000D_
margin: 40px 0;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
SIDEBAR STYLE_x000D_
----------------------------------------------------- */_x000D_
_x000D_
#sidebar {_x000D_
width: 250px;_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100vh;_x000D_
z-index: 999;_x000D_
background: #7386D5;_x000D_
color: #fff !important;_x000D_
transition: all 0.3s;_x000D_
}_x000D_
_x000D_
#sidebar.active {_x000D_
margin-left: -250px;_x000D_
}_x000D_
_x000D_
#sidebar .sidebar-header {_x000D_
padding: 20px;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
#sidebar ul.components {_x000D_
padding: 20px 0;_x000D_
border-bottom: 1px solid #47748b;_x000D_
}_x000D_
_x000D_
#sidebar ul p {_x000D_
color: #fff;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
#sidebar ul li a {_x000D_
padding: 10px;_x000D_
font-size: 1.1em;_x000D_
display: block;_x000D_
color:white;_x000D_
}_x000D_
_x000D_
#sidebar ul li a:hover {_x000D_
color: #7386D5;_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
#sidebar ul li.active>a,_x000D_
a[aria-expanded="true"] {_x000D_
color: #fff;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
a[data-toggle="collapse"] {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
a[aria-expanded="false"]::before,_x000D_
a[aria-expanded="true"]::before {_x000D_
content: '\e259';_x000D_
display: block;_x000D_
position: absolute;_x000D_
right: 20px;_x000D_
font-family: 'Glyphicons Halflings';_x000D_
font-size: 0.6em;_x000D_
}_x000D_
_x000D_
a[aria-expanded="true"]::before {_x000D_
content: '\e260';_x000D_
}_x000D_
_x000D_
ul ul a {_x000D_
font-size: 0.9em !important;_x000D_
padding-left: 30px !important;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
ul.CTAs {_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
ul.CTAs a {_x000D_
text-align: center;_x000D_
font-size: 0.9em !important;_x000D_
display: block;_x000D_
border-radius: 5px;_x000D_
margin-bottom: 5px;_x000D_
}_x000D_
_x000D_
a.download {_x000D_
background: #fff;_x000D_
color: #7386D5;_x000D_
}_x000D_
_x000D_
a.article,_x000D_
a.article:hover {_x000D_
background: #6d7fcc !important;_x000D_
color: #fff !important;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
CONTENT STYLE_x000D_
----------------------------------------------------- */_x000D_
_x000D_
#content {_x000D_
width: calc(100% - 250px);_x000D_
padding: 40px;_x000D_
min-height: 100vh;_x000D_
transition: all 0.3s;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
#content.active {_x000D_
width: 100%;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
MEDIAQUERIES_x000D_
----------------------------------------------------- */_x000D_
_x000D_
@media (max-width: 768px) {_x000D_
#sidebar {_x000D_
margin-left: -250px;_x000D_
}_x000D_
#sidebar.active {_x000D_
margin-left: 0;_x000D_
}_x000D_
#content {_x000D_
width: 100%;_x000D_
}_x000D_
#content.active {_x000D_
width: calc(100% - 250px);_x000D_
}_x000D_
#sidebarCollapse span {_x000D_
display: none;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
_x000D_
<title>Collapsible sidebar using Bootstrap 3</title>_x000D_
_x000D_
<!-- Bootstrap CSS CDN -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<!-- Our Custom CSS -->_x000D_
<link rel="stylesheet" href="style2.css">_x000D_
<!-- Scrollbar Custom CSS -->_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
<div class="wrapper">_x000D_
<!-- Sidebar Holder -->_x000D_
<nav id="sidebar">_x000D_
<div class="sidebar-header">_x000D_
<h3>Header as you want </h3>_x000D_
</h3>_x000D_
</div>_x000D_
_x000D_
<ul class="list-unstyled components">_x000D_
<p>Dummy Heading</p>_x000D_
<li class="active">_x000D_
<a href="#menu">Animación</a>_x000D_
_x000D_
</li>_x000D_
<li>_x000D_
<a href="#menu">Ilustración</a>_x000D_
_x000D_
_x000D_
</li>_x000D_
<li>_x000D_
<a href="#menu">Interacción</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Blog</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Acerca</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">contacto</a>_x000D_
</li>_x000D_
_x000D_
_x000D_
</ul>_x000D_
_x000D_
_x000D_
</nav>_x000D_
_x000D_
<!-- Page Content Holder -->_x000D_
<div id="content">_x000D_
_x000D_
<nav class="navbar navbar-default">_x000D_
<div class="container-fluid">_x000D_
_x000D_
<div class="navbar-header">_x000D_
<button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
<i class="glyphicon glyphicon-align-left"></i>_x000D_
<span>Toggle Sidebar</span>_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="#">Page</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>_x000D_
_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<!-- jQuery CDN -->_x000D_
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>_x000D_
<!-- Bootstrap Js CDN -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<!-- jQuery Custom Scroller CDN -->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
_x000D_
_x000D_
$('#sidebarCollapse').on('click', function() {_x000D_
$('#sidebar, #content').toggleClass('active');_x000D_
$('.collapse.in').toggleClass('in');_x000D_
$('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
if this is what you want .
This is what worked for me. Issue is earlier I didn't set Content Type(header) when I used exchange method.
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("param1", "123");
map.add("param2", "456");
map.add("param3", "789");
map.add("param4", "123");
map.add("param5", "456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
final HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(map ,
headers);
JSONObject jsonObject = null;
try {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(
"https://url", HttpMethod.POST, entity,
String.class);
if (responseEntity.getStatusCode() == HttpStatus.CREATED) {
try {
jsonObject = new JSONObject(responseEntity.getBody());
} catch (JSONException e) {
throw new RuntimeException("JSONException occurred");
}
}
} catch (final HttpClientErrorException httpClientErrorException) {
throw new ExternalCallBadRequestException();
} catch (HttpServerErrorException httpServerErrorException) {
throw new ExternalCallServerErrorException(httpServerErrorException);
} catch (Exception exception) {
throw new ExternalCallServerErrorException(exception);
}
ExternalCallBadRequestException and ExternalCallServerErrorException are the custom exceptions here.
Note: Remember HttpClientErrorException is thrown when a 4xx error is received. So if the request you send is wrong either setting header or sending wrong data, you could receive this exception.
In the accepted answer, for Laravel 4 the headers array is constructed incorrectly. Use:
$headers = array(
'Content-Type' => 'application/pdf',
);
If anyone wants permanent redirection from one page /a
to another page /b
We can use redirect:
option added in the router.js
. For example if we want to redirect the users always to a separate page when he types the root or base url /
:
const router = new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "/",
redirect: "/someOtherPage",
name: "home",
component: Home,
// () =>
// import(/* webpackChunkName: "home" */ "./views/pageView/home.vue"),
},
]
using System.IO;
if (File.Exists(path))
{
Console.WriteLine("file exists");
}
nan is never equal to nan
if z!=z:z=0
so for a 2D array
for entry in nparr:
if entry!=entry:entry=0
Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.
In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.
The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new
keyword, and the context within that function (the this
keyword) will refer to the actual object instance where you call it.
Consider this example:
// constructor function
function MyClass () {
var privateVariable; // private member only available within the constructor fn
this.privilegedMethod = function () { // it can access private members
//..
};
}
// A 'static method', it's just like a normal function
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};
MyClass.prototype.publicMethod = function () {
// the 'this' keyword refers to the object instance
// you can access only 'privileged' and 'public' members
};
var myObj = new MyClass(); // new object instance
myObj.publicMethod();
MyClass.staticMethod();
I ran into an issue today with @Pumbaa80's code. I'm trying to apply JSON syntax highlighting to data that I'm rendering in a Mithril view, so I need to create DOM nodes for everything in the JSON.stringify
output.
I split the really long regex into its component parts as well.
render_json = (data) ->
# wraps JSON data in span elements so that syntax highlighting may be
# applied. Should be placed in a `whitespace: pre` context
if typeof(data) isnt 'string'
data = JSON.stringify(data, undefined, 2)
unicode = /"(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?/
keyword = /\b(true|false|null)\b/
whitespace = /\s+/
punctuation = /[,.}{\[\]]/
number = /-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/
syntax = '(' + [unicode, keyword, whitespace,
punctuation, number].map((r) -> r.source).join('|') + ')'
parser = new RegExp(syntax, 'g')
nodes = data.match(parser) ? []
select_class = (node) ->
if punctuation.test(node)
return 'punctuation'
if /^\s+$/.test(node)
return 'whitespace'
if /^\"/.test(node)
if /:$/.test(node)
return 'key'
return 'string'
if /true|false/.test(node)
return 'boolean'
if /null/.test(node)
return 'null'
return 'number'
return nodes.map (node) ->
cls = select_class(node)
return Mithril('span', {class: cls}, node)
Code in context on Github here
This is a bit of going around the problem, but I have written a function that basically deals with the extra columns:
def merge_fix_cols(df_company,df_product,uniqueID):
df_merged = pd.merge(df_company,
df_product,
how='left',left_on=uniqueID,right_on=uniqueID)
for col in df_merged:
if col.endswith('_x'):
df_merged.rename(columns = lambda col:col.rstrip('_x'),inplace=True)
elif col.endswith('_y'):
to_drop = [col for col in df_merged if col.endswith('_y')]
df_merged.drop(to_drop,axis=1,inplace=True)
else:
pass
return df_merged
Seems to work well with my merges!
I have a workaround that seems reasonably clean to me. So I'm answering my own question.
Since 0 as the first section header's height doesn't work, I return 1. Then I use the contentInset to hide that height underneath the navigation bar.
Objective-C:
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
if (section == 0)
return 1.0f;
return 32.0f;
}
- (NSString*) tableView:(UITableView *) tableView titleForHeaderInSection:(NSInteger)section
{
if (section == 0) {
return nil;
} else {
// return some string here ...
}
}
- (void) viewDidLoad
{
[super viewDidLoad];
self.tableView.contentInset = UIEdgeInsetsMake(-1.0f, 0.0f, 0.0f, 0.0);
}
Swift:
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? 1.0 : 32
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset = UIEdgeInsets(top: -1, left: 0, bottom: 0, right: 0)
}
Use TO_CHAR
function.
select TO_CHAR(BLOB_FIELD) from TABLE_WITH_BLOB where ID = '<row id>'
Converts NCHAR
, NVARCHAR2
, CLOB
, or NCLOB
data to the database character set. The value returned is always VARCHAR2
.
This code (example) :
Chronology ch1 = GregorianChronology.getInstance(); Chronology ch2 = ISOChronology.getInstance(); DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1); DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2); System.out.println(dt); System.out.println(dt2); boolean b = dt.equals(dt2); System.out.println(b);
Will print :
2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false
You are probably comparing two DateTimes with same date but different Chronology.
I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.
I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.
I hope this helps.
You turn off pack_propagate
by setting pack_propagate(0)
Turning off pack_propagate
here basically says don't let the widgets inside the frame control it's size. So you've set it's width and height to be 500. Turning off propagate stills allows it to be this size without the widgets changing the size of the frame to fill their respective width / heights which is what would happen normally
To turn off resizing the root window, you can set root.resizable(0, 0)
, where resizing is allowed in the x
and y
directions respectively.
To set a maxsize to window, as noted in the other answer you can set the maxsize
attribute or minsize
although you could just set the geometry of the root window and then turn off resizing. A bit more flexible imo.
Whenever you set grid
or pack
on a widget it will return None
. So, if you want to be able to keep a reference to the widget object you shouldn't be setting a variabe to a widget where you're calling grid
or pack
on it. You should instead set the variable to be the widget Widget(master, ....)
and then call pack
or grid
on the widget instead.
import tkinter as tk
def startgame():
pass
mw = tk.Tk()
#If you have a large number of widgets, like it looks like you will for your
#game you can specify the attributes for all widgets simply like this.
mw.option_add("*Button.Background", "black")
mw.option_add("*Button.Foreground", "red")
mw.title('The game')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = tk.Frame(master=mw,bg='black')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=tk.BOTH, expand=1) #Expand the frame to fill the root window
#Changed variables so you don't have these set to None from .pack()
go = tk.Button(master=back, text='Start Game', command=startgame)
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy)
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()
mw.mainloop()
For InnoDB tables, Percona has a recovery tool which may help. It is far from fail-safe or perfect, and how fast you stopped your MySQL server after the accidental deletes has a major impact. If you're quick enough, changes are you can recover quite a bit of data, but recovering all data is nigh impossible.
Of cours, proper daily backups, binlogs, and possibly a replication slave (which won't help for accidental deletes but does help in case of hardware failure) are the way to go, but this tool could enable you to save as much data as possible when you did not have those yet.
Using OpenSSL's EVP interface (the following is for OpenSSL 1.1):
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <openssl/evp.h>
bool computeHash(const std::string& unhashed, std::string& hashed)
{
bool success = false;
EVP_MD_CTX* context = EVP_MD_CTX_new();
if(context != NULL)
{
if(EVP_DigestInit_ex(context, EVP_sha256(), NULL))
{
if(EVP_DigestUpdate(context, unhashed.c_str(), unhashed.length()))
{
unsigned char hash[EVP_MAX_MD_SIZE];
unsigned int lengthOfHash = 0;
if(EVP_DigestFinal_ex(context, hash, &lengthOfHash))
{
std::stringstream ss;
for(unsigned int i = 0; i < lengthOfHash; ++i)
{
ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
}
hashed = ss.str();
success = true;
}
}
}
EVP_MD_CTX_free(context);
}
return success;
}
int main(int, char**)
{
std::string pw1 = "password1", pw1hashed;
std::string pw2 = "password2", pw2hashed;
std::string pw3 = "password3", pw3hashed;
std::string pw4 = "password4", pw4hashed;
hashPassword(pw1, pw1hashed);
hashPassword(pw2, pw2hashed);
hashPassword(pw3, pw3hashed);
hashPassword(pw4, pw4hashed);
std::cout << pw1hashed << std::endl;
std::cout << pw2hashed << std::endl;
std::cout << pw3hashed << std::endl;
std::cout << pw4hashed << std::endl;
return 0;
}
The advantage of this higher level interface is that you simply need to swap out the EVP_sha256()
call with another digest's function, e.g. EVP_sha512()
, to use a different digest. So it adds some flexibility.
I couldn't get my PYTHONPATH to work properly. I realized adding export
fixed the issue:
(did work)
export PYTHONPATH=$PYTHONPATH:~/test/site-packages
vs.
(did not work)
PYTHONPATH=$PYTHONPATH:~/test/site-packages
In a commercial scenario, a serious contestant for sure is yFiles for HTML:
It offers:
Here is a sample rendering that shows most of the requested features:
Full disclosure: I work for yWorks, but on Stackoverflow I do not represent my employer.
its a matter of speed. using the iterator accesses the elements faster. a similar question was answered here:
What's faster, iterating an STL vector with vector::iterator or with at()?
Edit: speed of access varies with each cpu and compiler
Use Son Of Strike which has a command ObjSize
.
Note that actual memory consumed is always larger than ObjSize
reports due to a synkblk
which resides directly before the object data.
Read more about both here MSDN Magazine Issue 2005 May - Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects.
These days according to the golang github with for Ubuntu, it's possible to install the latest version of Go easily via a snap:
Using snaps also works quite well:
# This will give you the latest version of go
$ sudo snap install --classic go
Potentially preferable to fussing with outdated and/or 3rd party PPAs
I think you are getting confused about what the a:active
CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected
into your CSS and when you select a link, update the selected menu item with new class e.g.
<div class="menuBar">
<ul>
<li class="selected"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
....
</ul>
</div>
// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; }
// more general CSS
li.selected a { color: #FF0000; }
You will need to update your template page to take in a selectedPage
parameter.
I'm seeing a lot of answers proposing a build or a re-build but just in case this don't fix your problem just notice that IDEA can detect a method but it will not compile in case you have a new
before as it will be expecting the instance.
You can Highlight text in a <textarea>
, using a <div>
carefully placed behind it.
check out Highlight Text Inside a Textarea.
Normally you can use None
, but you can also use objc.NULL
, e.g.
import objc
val = objc.NULL
Especially useful when working with C code in Python.
Also see: Python objc.NULL Examples
CREATE TABLE something (
column1 INTEGER NOT NULL,
column2 INTEGER NOT NULL,
value,
PRIMARY KEY ( column1, column2)
);
You can redirect the output to /dev/null
. For more info regarding /dev/null read this link.
You can hide the output of a comand in the following ways :
echo -n "Installing nano ......"; yum install nano > /dev/null; echo " done.";
Redirect the standard output to /dev/null
, but not the standard error. This will show the errors occurring during the installation, for example if yum
cannot find a package.
echo -n "Installing nano ......"; yum install nano &> /dev/null; echo " done.";
While this code will not show anything in the terminal since both standard error and standard output are redirected and thus nullified to /dev/null
.
@WebFilter(urlPatterns="/*")
public class XSSFilter implements Filter {
private static final org.apache.log4j.Logger LOGGER = LogManager.getLogger(XSSFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
LOGGER.info("Initiating XSSFilter... ");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpRequestWrapper requestWrapper = new HttpRequestWrapper(req);
chain.doFilter(requestWrapper, response);
}
@Override
public void destroy() {
LOGGER.info("Destroying XSSFilter... ");
}
}
You need to implement Filter and need to be annotated with @WebFilter(urlPatterns="/*")
And in Application or Configuration class you need to add @ServletComponentScan By this it your filter will get registered.
In my case the hosting had a whitelist for remote connection to MySql. Try to add your IP to whitelist in hosting admin panel.
What you want to do is use the HTML5 attribute placeholder
which lets you set a default value for your input box:
<input type="text" name="inputBox" placeholder="enter your text here">
This should achieve what you're looking for. However, be careful because the placeholder attribute is not supported in Internet Explorer 9 and earlier versions.
Quick Update, effective from February 15th, 2015, we cannot submit apps to the store that were developed using an SDK prior to iOS 8. So, keeping that in mind , its better to not to worry about this issue as many people have suggested that apps made in Swift can be deployed to OS X 10.9 and iOS 7.0 as well.
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
The simplest way is to just redirect the output, like so:
Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) > c:\user\documents\diff_output.txt
>
will cause the output file to be overwritten if it already exists.
>>
will append new text to the end of the output file if it already exists.
Let's fit the model:
> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)
Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)
Residuals:
Min 1Q Median 3Q Max
-245.74 -113.99 -32.05 104.96 484.81
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 811.2267 76.9755 10.539 2.29e-13 ***
body.weight 7.0595 0.9776 7.221 7.03e-09 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433
F-statistic: 52.15 on 1 and 42 DF, p-value: 7.025e-09
The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).
This can be computed using confint
:
> confint(fit, 'body.weight', level=0.95)
2.5 % 97.5 %
body.weight 5.086656 9.0324
Still another solution:
timezone('utc', now())
If you have several dialogs that could be opened on a page, this will allow any of them to be closed by clicking on the background:
$('body').on('click','.ui-widget-overlay', function() {
$('.ui-dialog').filter(function () {
return $(this).css("display") === "block";
}).find('.ui-dialog-content').dialog('close');
});
(Only works for modal dialogs, as it relies on '.ui-widget-overlay'. And it does close all open dialogs any time the background of one of them is clicked.)
You can use Multiline Search and Replace in Visual Studio macro which provides nice GUI for the task.
We have a winXP build pc, and use Visual Build Pro 6 to build our software. since some of our developers use VS 2010 the project files now contain reference to "tool version 4.0" and from what I can tell, this tells Visual Build it needs to find a sdk7.x somewhere, even though we only build for .NET 3.5. This caused it not to find lc.exe. I tried to fool it by pointing all the macros to the 6.0A sdk that came with VS2008 which is installed on the pc, but that did not work.
I eventually got it working by downloading and installing sdk 7.1. I then created a registry key for 7.0A and pointed the install path to the install path of the 7.1 sdk. now it happily finds a compatible "lc.exe" and all the code compiles fine. I have a feeling I will now also be able to compile .NET 4.0 code even though VS2010 is not installed, but I have not tried that yet.
You don't need initialization lists for that:
std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);
If you're having an issue where the Resources added are images and are not getting copied to your build folder on compiling. You need to change the "Build Action" to None from Resource ( which is the default) and change the Copy to "If Newer" or "Always" as shown below :
I had this error few days a go and I sped too many time on fixing this error.
public boolean save(OrderHeader header) {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
try {
session.save(header);
for (OrderDetail detail : header.getDetails()) {
session.save(detail);
}
transaction.commit();
session.close();
return true;
} catch (HibernateException exception) {
exception.printStackTrace();
transaction.rollback();
return false;
}
}
Before i get this error , I didn't have mentioned ID generation type on the OrderDetil Object. when without generating Orderdetails' id it keeps Id as 0 for every OrderDetail objects. this what #jbx explained. Yes it is the best answer. this one example how it happens.
I assume you mean that you want the final SQL query, with parameter values interpolated into it. I understand that this would be useful for debugging, but it is not the way prepared statements work. Parameters are not combined with a prepared statement on the client-side, so PDO should never have access to the query string combined with its parameters.
The SQL statement is sent to the database server when you do prepare(), and the parameters are sent separately when you do execute(). MySQL's general query log does show the final SQL with values interpolated after you execute(). Below is an excerpt from my general query log. I ran the queries from the mysql CLI, not from PDO, but the principle is the same.
081016 16:51:28 2 Query prepare s1 from 'select * from foo where i = ?'
2 Prepare [2] select * from foo where i = ?
081016 16:51:39 2 Query set @a =1
081016 16:51:47 2 Query execute s1 using @a
2 Execute [2] select * from foo where i = 1
You can also get what you want if you set the PDO attribute PDO::ATTR_EMULATE_PREPARES. In this mode, PDO interpolate parameters into the SQL query and sends the whole query when you execute(). This is not a true prepared query. You will circumvent the benefits of prepared queries by interpolating variables into the SQL string before execute().
Re comment from @afilina:
No, the textual SQL query is not combined with the parameters during execution. So there's nothing for PDO to show you.
Internally, if you use PDO::ATTR_EMULATE_PREPARES, PDO makes a copy of the SQL query and interpolates parameter values into it before doing the prepare and execute. But PDO does not expose this modified SQL query.
The PDOStatement object has a property $queryString, but this is set only in the constructor for the PDOStatement, and it's not updated when the query is rewritten with parameters.
It would be a reasonable feature request for PDO to ask them to expose the rewritten query. But even that wouldn't give you the "complete" query unless you use PDO::ATTR_EMULATE_PREPARES.
This is why I show the workaround above of using the MySQL server's general query log, because in this case even a prepared query with parameter placeholders is rewritten on the server, with parameter values backfilled into the query string. But this is only done during logging, not during query execution.
This should work:
.panel > .panel-heading {
background-image: none;
background-color: red;
color: white;
}
For those who stumble upon this question, here's how to achieve this layout with a Grid
:
<Grid>
<TextBlock Text="Server:"/>
<TextBlock Text="http://127.0.0.1" HorizontalAlignment="Right"/>
</Grid>
creates
Server: http://127.0.0.1
There are a number of ways to "convert" an integer to a string in PHP.
The traditional computer science way would be to cast the variable as a string:
$int = 5;
$int_as_string = (string) $int;
echo $int . ' is a '. gettype($int) . "\n";
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
You could also take advantage of PHP's implicit type conversion and string interpolation:
$int = 5;
echo $int . ' is a '. gettype($int) . "\n";
$int_as_string = "$int";
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
$string_int = $int.'';
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
Finally, similar to the above, any function that accepts and returns a string could be used to convert and integer. Consider the following:
$int = 5;
echo $int . ' is a '. gettype($int) . "\n";
$int_as_string = trim($int);
echo $int_as_string . ' is a ' . gettype($int_as_string) . "\n";
I wouldn't recommend the final option, but I've seen code in the wild that relied on this behavior, so thought I'd pass it along.
just copy the image and then paste it, you will get the output
![image.png](attachment:image.png)
Additional hint: If you have multiple projects with different toolchains open, check the build console header for the failing project's path.
I've just spent half an hour trying to fix a build that showed this error because another project with hopelessly outdated toolchain settings was open in the same workbench. Closing the other project re-enabled the build.
Using a more functional approach, you can implement the match with a one-liner using an array function:
ECMAScript 6:
const regexList = [/apple/, /pear/];
const text = "banana pear";
const isMatch = regexList.some(rx => rx.test(text));
ECMAScript 5:
var regexList = [/apple/, /pear/];
var text = "banana pear";
var isMatch = regexList.some(function(rx) { return rx.test(text); });
In your css add folllowing
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}
And then in you code you can add ng-cloak directive. For example,
<div ng-cloak>
Welcome {{data.name}}
</div>
Thats it!
The problem is that System. currentTimeMillis();
returns the number of milliseconds from 1970-01-01T00:00:00Z, but new Date()
gives the current local time. Adding the ZONE_OFFSET and DST_OFFSET from the Calendar class gives you the time in UTC.
Calendar rightNow = Calendar.getInstance();
// offset to add since we're not UTC
long offset = rightNow.get(Calendar.ZONE_OFFSET) +
rightNow.get(Calendar.DST_OFFSET);
long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
(24 * 60 * 60 * 1000);
System.out.println(sinceMidnight + " milliseconds since midnight");
Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:
"temp" environment variable setting - then it would be:
%temp%\Temporary ASP.NET Files
Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:
c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files
There are also cases where the temp folder can be set via config for a machine or site specific using this:
<compilation tempDirectory="d:\MyTempPlace" />
I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.
Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.
You should bring your data into long (i.e. molten) format to use it with ggplot2
:
library("reshape2")
mdf <- melt(mdf, id.vars="Company", value.name="value", variable.name="Year")
And then you have to use aes( ... , group = Company )
to group them:
ggplot(data=mdf, aes(x=Year, y=value, group = Company, colour = Company)) +
geom_line() +
geom_point( size=4, shape=21, fill="white")
>>> import os
>>> os.system('cd c:\mydir')
In fact, os.system()
can execute any command that windows command prompt can execute, not just change dir.
bool isValid = c.GetType() == typeof(TForm) ? true : false;
or simpler
bool isValid = c.GetType() == typeof(TForm);
If you have the developer console (JavaScript) in your browser, you can type this code in:
urls = document.querySelectorAll('a'); for (url in urls) console.log(urls[url].href);
Shortened:
n=$$('a');for(u in n)console.log(n[u].href)
double d = 2.22977777;
d = ( (double) ( (int) (d * 1000.0) ) ) / 1000.0 ;
Of course, this won't work if you're trying to truncate rounding error, but it should work fine with the values you give in your examples. See the first two answers to this question for details on why it won't work sometimes.
If you would like to support really old browsers you should parse the date string, since using the ISO8601 date format with the Date
constructor is not supported pre IE9:
var queryDate = '2009-11-01',
dateParts = queryDate.match(/(\d+)/g)
realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
// months are 0-based!
// For >= IE9
var realDate = new Date('2009-11-01');
$('#datePicker').datepicker({ dateFormat: 'yy-mm-dd' }); // format to show
$('#datePicker').datepicker('setDate', realDate);
Check the above example here.
Use:
$ git submodule
It will list all the submodules in the specified Git repository.
You can also create a custom jumbotron with whatever features/changes you want and apply that class in your html.
.jumbotronTransp {
padding: 30px;
margin-bottom: 30px;
font-size: 21px;
font-weight: 200;
line-height: 2.1428571435;
color: inherit;
background-color: transparent;
}
The documentation for the Python 3 CSV module provides this example:
with open('example.csv', newline='') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
# ... process CSV file contents here ...
The Sniffer
will try to auto-detect many things about the CSV file. You need to explicitly call its has_header()
method to determine whether the file has a header line. If it does, then skip the first row when iterating the CSV rows. You can do it like this:
if sniffer.has_header():
for header_row in reader:
break
for data_row in reader:
# do something with the row
Though nearly the same as most of the other responses, I think this is the most efficient and concise way to implement it. Using TryGetValue is faster than using ContainsKey and reindexing into the dictionary as some other solutions have shown.
void Add(string key, string val)
{
List<string> list;
if (!dictionary.TryGetValue(someKey, out list))
{
values = new List<string>();
dictionary.Add(key, list);
}
list.Add(val);
}
Try using
<table border="1" cellspacing="0" cellpadding="0" class="template-table"
style="table-layout: fixed; width: 100%">
as table style along with
<td style="word-break:break-word">long text</td>
for td it works for normal/real scenario text with words, not for random typed letters without gaps
I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:
home = System.getenv('HOME')
It helps to keep in mind that anything that works in pure Java will work in Gradle too.
For first character in word use .capitalized
in swift and for whole-word use .uppercased()
Here are my 2 cents on different options for completing this:
Third party tools: Probably the easiest way to get the job done is to create an empty database on lower version and then use third party tools to read the backup and synchronize new newly created database with the backup.
Red gate is one of the most popular but there are many others like ApexSQL Diff , ApexSQL Data Diff, Adept SQL, Idera …. All of these are premium tools but you can get the job done in trial mode ;)
Generating scripts: as others already mentioned you can always script structure and data using SSMS but you need to take into consideration the order of execution. By default object scripts are not ordered correctly and you’ll have to take care of the dependencies. This may be an issue if database is big and has a lot of objects.
Import and export wizard: This is not an ideal solution as it will not restore all objects but only data tables but you can consider it for quick and dirty fixes when it’s needed.
It's true, minimal-ui
could be both useful and harmful, and I suppose the trade-off now has another balance, in favor of newer, bigger iPhones.
I've been dealing with the issue while working with my js framework for HTML5 apps. After many attempted solutions, each with their drawbacks, I surrendered to considering that space lost on iPhones previous than 6. Given the situation, I think that the only solid and predictable behavior is a pre-determined one.
In short, I ended up preventing any form of minimal-ui, so at least my screen height is always the same and you always know what actual space you have for your app.
With the help of time, enough users will have more room.
EDIT
This is a little simplified, for demo purpose, but should work for you. Assuming you have a main container
html, body, #main {
height: 100%;
width: 100%;
overflow: hidden;
}
.view {
width: 100%;
height: 100%;
overflow: scroll;
}
Then:
then with js, I set #main
's height to the window's available height. This also helps dealing with other scrolling bugs found in both iOS and Android. It also means that you need to deal on how to update it, just note that;
I block over-scrolling when reaching the boundaries of the scroll. This one is a bit more deep in my code, but I think you can as well follow the principle of this answer for basic functionality. I think it could flickr a little, but will do the job.
As a sidenote: this app too is bookmarkable, as it uses an internal routing to hashed addresses, but I also added a prompt iOS users to add to home. I feel this way helps loyalty and returning visitors (and so the lost space is back).
Having a look at the blog here I found the solution in one of the comments. Make sure you got the rpmforge
repository added to your CentOS yum and just run the flowing command:
yum --disablerepo=base,updates --enablerepo=rpmforge-extras install git
If you already have git installed then use:
yum --disablerepo=base,updates --enablerepo=rpmforge-extras update git
Related question(s):
Thanks to Anthony Hatzopoulos, for git v1.8x
you'll need to use git18 as in:
yum --disablerepo=base,updates --enablerepo=rpmforge-extras install git18
Also thanks to @Axlrod for the below hint and @Hiphip for the feedback:
Change the rpmforge.repo
file to have rpmforge-extras
to enabled,
yum update git
. Otherwise it complained about dependency problems.
Installing a specific version of git say 2.x I found this nice and easy-to-follow guide on how to download the GIT source and compile it yourself (and install it). If the accepted answer does not give you the version you want, try the following instructions:
http://tecadmin.net/install-git-2-0-on-centos-rhel-fedora/
(And pasted/reformatted from above source in case it is removed later)
Step 1: Install Required Packages
Firstly we need to make sure that we have installed required packages on your system. Use following command to install required packages before compiling Git source.
# yum install curl-devel expat-devel gettext-devel openssl-devel zlib-devel
# yum install gcc perl-ExtUtils-MakeMaker
Step 2: Uninstall old Git RPM
Now remove any prior installation of Git through RPM file or Yum package manager. If your older version is also compiled through source, then skip this step.
# yum remove git
Step 3: Download and Compile Git Source
Download git source code from kernel git or simply use following command to download Git 2.0.4.
# cd /usr/src
# wget https://www.kernel.org/pub/software/scm/git/git-2.0.4.tar.gz
# tar xzf git-2.0.4.tar.gz
After downloading and extracting Git source code, Use following command to compile source code.
# cd git-2.0.4
# make prefix=/usr/local/git all
# make prefix=/usr/local/git install
#
# echo 'export PATH=$PATH:/usr/local/git/bin' >> /etc/bashrc
# or
# echo 'export PATH=$PATH:/usr/local/git/bin' > /etc/profile.d/git.sh
#
# source /etc/bashrc
HINT 1: Updated method of adding compiled git bin directory to bashrc. Because
echo "export PATH=$PATH:/usr/local/git/bin" >> /etc/bashrc
used "" instead of '', it would expand the current session's value for $PATH instead of keeping it as a variable, and could adversely affect the entire system. At the minimum, it should use '' instead of "" and should really be a separate script in/etc/profile.d/
HINT 2 (@DJB):
/usr/local/git/bin
before$PATH
, since the older version of git was already on $PATH:export PATH=/usr/local/git/bin:$PATH
Step 4. Check Git Version
One completion of above steps, you have successfully install Git in your system. Let use following command to check git version
# git --version
git version 2.0.4
I also wanted to add that the "Getting Started" guide at the GIT website also includes instructions on how to download and compile it yourself:
http://git-scm.com/book/en/v2/Getting-Started-Installing-Git
If you want to select a value based on true / false use
[selected]="opt.selected == true"
<option *ngFor="let opt of question.options" [value]="opt.key" [selected]="opt.selected == true">{{opt.selected+opt.value}}</option>
checkit out
I have a full discussion of events and delegates in my events article. For the simplest kind of event, you can just declare a public event and the compiler will create both an event and a field to keep track of subscribers:
public event EventHandler Foo;
If you need more complicated subscription/unsubscription logic, you can do that explicitly:
public event EventHandler Foo
{
add
{
// Subscription logic here
}
remove
{
// Unsubscription logic here
}
}
/^((?P<scheme>https?|ftp):\/)?\/?((?P<username>.*?)(:(?P<password>.*?)|)@)?(?P<hostname>[^:\/\s]+)(?P<port>:([^\/]*))?(?P<path>(\/\w+)*\/)(?P<filename>[-\w.]+[^#?\s]*)?(?P<query>\?([^#]*))?(?P<fragment>#(.*))?$/
From my answer on a similar question. Works better than some of the others mentioned because they had some bugs (such as not supporting username/password, not supporting single-character filenames, fragment identifiers being broken).
The following code sample, will match the pattern even in case of space characters in between. i.e. :
<td><a href='/path/to/file'>Name of File</a></td>
as well as:
<td> <a href='/path/to/file' >Name of File</a> </td>
Method returns true or false, depending on whether the input htmlTd string matches the pattern or no. If it matches, the out params contain the link and name respectively.
/// <summary>
/// Assigns proper values to link and name, if the htmlId matches the pattern
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
link = null;
name = null;
string pattern = "<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>";
if (Regex.IsMatch(htmlTd, pattern))
{
Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
link = r.Match(htmlTd).Result("${link}");
name = r.Match(htmlTd).Result("${name}");
return true;
}
else
return false;
}
I have tested this and it works correctly.
I have fixed the by this way:
Create a folder in your resource directory name "drawable-nodpi"
and then move yours all resources in this directory from others drawable directory.
Now clean your project and then rebuilt. Run again hopefully it will work this time without any resource not found exception.
Your class Delivery
has no access modifier, which means it defaults to internal
. If you then try to expose a property of that type as public
, it won't work. Your type (class) needs to have the same, or higher access as your property.
More about access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx
Found these docu on the google docu pages:
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
Try this to remove the first and last bracket of string ex.[1,2,3]
String s =str.replaceAll("[", "").replaceAll("]", "");
Exptected result = 1,2,3
Add !important
rule to display: table
of your .v-center
class.
.v-center {
display:table !important;
border:2px solid gray;
height:300px;
}
Your display property is being overridden by bootstrap to display: block
.
This is code that I have effectively used before, passing "/"
as the strPath parameter.
public static Cookie eraseCookie(String strCookieName, String strPath) {
Cookie cookie = new Cookie(strCookieName, "");
cookie.setMaxAge(0);
cookie.setPath(strPath);
return cookie;
}
This worked
<button onclick="window.location.href=window.location.href; return false;">Continue</button>
The reason it didn't work without the
return false;is that previously it treated that as a form submit button. With an explicit return false on it, it doesn't do the form submit and just does the reload of the same page that was a result of a previous POST to that page.
If speed is what you need and extra dependencies are not a problem, you maybe find numba
quite useful (now it is pretty easy to install, on any platform). The classic ray_tracing
approach you proposed can be easily ported to numba
by using numba @jit
decorator and casting the polygon to a numpy array. The code should look like:
@jit(nopython=True)
def ray_tracing(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
The first execution will take a little longer than any subsequent call:
%%time
polygon=np.array(polygon)
inside1 = [numba_ray_tracing_method(point[0], point[1], polygon) for
point in points]
CPU times: user 129 ms, sys: 4.08 ms, total: 133 ms
Wall time: 132 ms
Which, after compilation will decrease to:
CPU times: user 18.7 ms, sys: 320 µs, total: 19.1 ms
Wall time: 18.4 ms
If you need speed at the first call of the function you can then pre-compile the code in a module using pycc
. Store the function in a src.py like:
from numba import jit
from numba.pycc import CC
cc = CC('nbspatial')
@cc.export('ray_tracing', 'b1(f8, f8, f8[:,:])')
@jit(nopython=True)
def ray_tracing(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
if __name__ == "__main__":
cc.compile()
Build it with python src.py
and run:
import nbspatial
import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in
np.linspace(0,2*np.pi,lenpoly)[:-1]]
# random points set of points to test
N = 10000
# making a list instead of a generator to help debug
points = zip(np.random.random(N),np.random.random(N))
polygon = np.array(polygon)
%%time
result = [nbspatial.ray_tracing(point[0], point[1], polygon) for point in points]
CPU times: user 20.7 ms, sys: 64 µs, total: 20.8 ms
Wall time: 19.9 ms
In the numba code I used: 'b1(f8, f8, f8[:,:])'
In order to compile with nopython=True
, each var needs to be declared before the for loop
.
In the prebuild src code the line:
@cc.export('ray_tracing' , 'b1(f8, f8, f8[:,:])')
Is used to declare the function name and its I/O var types, a boolean output b1
and two floats f8
and a two-dimensional array of floats f8[:,:]
as input.
For my use case, I need to check if multiple points are inside a single polygon - In such a context, it is useful to take advantage of numba parallel capabilities to loop over a series of points. The example above can be changed to:
from numba import jit, njit
import numba
import numpy as np
@jit(nopython=True)
def pointinpolygon(x,y,poly):
n = len(poly)
inside = False
p2x = 0.0
p2y = 0.0
xints = 0.0
p1x,p1y = poly[0]
for i in numba.prange(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
D = np.empty(len(points), dtype=numba.boolean)
for i in numba.prange(0, len(D)):
D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
return D
Note: pre-compiling the above code will not enable the parallel capabilities of numba (parallel CPU target is not supported by pycc/AOT
compilation) see: https://github.com/numba/numba/issues/3336
Test:
import numpy as np
lenpoly = 100
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)[:-1]]
polygon = np.array(polygon)
N = 10000
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
For N=10000
on a 72 core machine, returns:
%%timeit
parallelpointinpolygon(points, polygon)
# 480 µs ± 8.19 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
0
instead of 1
(thanks @mehdi):for i in numba.prange(0, len(D))
Follow-up on the comparison made by @mehdi, I am adding a GPU-based method below. It uses the point_in_polygon
method, from the cuspatial
library:
import numpy as np
import cudf
import cuspatial
N = 100000002
lenpoly = 1000
polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in
np.linspace(0,2*np.pi,lenpoly)]
polygon = np.array(polygon)
points = np.random.uniform(-1.5, 1.5, size=(N, 2))
x_pnt = points[:,0]
y_pnt = points[:,1]
x_poly =polygon[:,0]
y_poly = polygon[:,1]
result = cuspatial.point_in_polygon(
x_pnt,
y_pnt,
cudf.Series([0], index=['geom']),
cudf.Series([0], name='r_pos', dtype='int32'),
x_poly,
y_poly,
)
Following @Mehdi comparison. For N=100000002
and lenpoly=1000
- I got the following results:
time_parallelpointinpolygon: 161.54760098457336
time_mpltPath: 307.1664695739746
time_ray_tracing_numpy_numba: 353.07356882095337
time_is_inside_sm_parallel: 37.45389246940613
time_is_inside_postgis_parallel: 127.13793849945068
time_is_inside_rapids: 4.246025562286377
hardware specs:
Notes:
The cuspatial.point_in_poligon
method, is quite robust and powerful, it offers the ability to work with multiple and complex polygons (I guess at the expense of performance)
The numba
methods can also be 'ported' on the GPU - it will be interesting to see a comparison which includes a porting to cuda
of fastest method mentioned by @Mehdi (is_inside_sm
).
You can use a memory watchpoint in unmanaged code. Not sure if these are available in managed code though.
As a note of caution this answer provided by the user above me is correct.
SharedPreferences preferences = this.getActivity().getSharedPreferences("pref",0);
However, if you attempt to get anything in the fragment before onAttach is called getActivity() will return null.
Why not just
$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");
EDIT: You can also use the Expr class (Doctrine2).
My solution is a wrapper around app.route:
def corsapp_route(path, origin=('127.0.0.1',), **options):
"""
Flask app alias with cors
:return:
"""
def inner(func):
def wrapper(*args, **kwargs):
if request.method == 'OPTIONS':
response = make_response()
response.headers.add("Access-Control-Allow-Origin", ', '.join(origin))
response.headers.add('Access-Control-Allow-Headers', ', '.join(origin))
response.headers.add('Access-Control-Allow-Methods', ', '.join(origin))
return response
else:
result = func(*args, **kwargs)
if 'Access-Control-Allow-Origin' not in result.headers:
result.headers.add("Access-Control-Allow-Origin", ', '.join(origin))
return result
wrapper.__name__ = func.__name__
if 'methods' in options:
if 'OPTIONS' in options['methods']:
return app.route(path, **options)(wrapper)
else:
options['methods'].append('OPTIONS')
return app.route(path, **options)(wrapper)
return wrapper
return inner
@corsapp_route('/', methods=['POST'], origin=['*'])
def hello_world():
...
If you have downloaded the AS + SDK bundle: in Windows 10
C:\Users\ your User Name \AppData\Local\Android\sdk\platform-tools\
Run adb.exe
Type adb shell.
Now able to access adb and the db.
I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate
instead.
I know you asked what enumerate means, but when I understood the following, I also understood how enumerate
makes iterating over a list while knowing the index of the current item easier (and more readable).
list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
letter = list_of_letters[i]
print (i, letter)
The output is:
0 a
1 b
2 c
I also used to do something, even sillier before I read about the enumerate
function.
i = 0
for n in list_of_letters:
print (i, n)
i += 1
It produces the same output.
But with enumerate
I just have to write:
list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
print (i, letter)
select convert(varchar(10), cast(fmdate as date), 101) from sery
Without cast I was not getting fmdate converted, so fmdate was a string.
The apps UI only works for panels.
The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.
Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.
Alternatively you can also draw the button somewhere else and insert it as an image.
More info: https://developers.google.com/apps-script/guides/menus
You can get any type of extra data from intent, no matter if it's an object or string or any type of data.
Bundle extra = getIntent().getExtras();
if (extra != null){
String str1 = (String) extra.get("obj"); // get a object
String str2 = extra.getString("string"); //get a string
}
and the Shortest solution is:
Boolean isGranted = getIntent().getBooleanExtra("tag", false);
If you wanna maintain the same order in your list, say: your Map looks like:
map.put(1, "msg1")
map.put(2, "msg2")
map.put(3, "msg3")
and you want your list looks like
["msg1", "msg2", "msg3"] // same order as the map
you will have to iterate through the Map:
// sort your map based on key, otherwise you will get IndexOutofBoundException
Map<String, String> treeMap = new TreeMap<String, String>(map)
List<String> list = new List<String>();
for (treeMap.Entry<Integer, String> entry : treeMap.entrySet()) {
list.add(entry.getKey(), entry.getValue());
}
Create a file called MoveFiles.bat with the syntax
move c:\Sourcefoldernam\*.* e:\destinationFolder
then schedule a task to run that MoveFiles.bat every 10 hours.
I have created my own file templates for NSObject
, UIView
and UIViewController
so when I create new classes, the files are all set up with private sections and logging of class' address in init and dealloc.
Example (NSObject
derived class named 'test' will start like this):
//=====================================================
// Private Interface
//=====================================================
@interface test (private)
@end
//=====================================================
// Public Implementation
//=====================================================
@implementation test
- (void)dealloc {
NSLog(@">>> Dealloc: test [0x%X]", self);
[super dealloc];
NSLog(@"<<< Dealloc: test");
}
- (id) init
{
self = [super init];
if(self) {
NSLog(@">>> Alloc: test [0x%X]", self);
}
return self;
}
@end
//=====================================================
// Private Implementation
//=====================================================
@implementation test (private)
@end
Plenty of resources are available for this, for example Cocoa dev: Design your own Xcode project templates.
It can handle recursive objects or arrays in the STANDARD query form like a=val&b[0]=val&b[1]=val&c=val&d[some key]=val
, here's the final function.
const objectToQueryString = (initialObj) => {
const reducer = (obj, parentPrefix = null) => (prev, key) => {
const val = obj[key];
key = encodeURIComponent(key);
const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;
if (val == null || typeof val === 'function') {
prev.push(`${prefix}=`);
return prev;
}
if (['number', 'boolean', 'string'].includes(typeof val)) {
prev.push(`${prefix}=${encodeURIComponent(val)}`);
return prev;
}
prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&'));
return prev;
};
return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&');
};
const testCase1 = {
name: 'Full Name',
age: 30
}
const testCase2 = {
name: 'Full Name',
age: 30,
children: [
{name: 'Child foo'},
{name: 'Foo again'}
],
wife: {
name: 'Very Difficult to say here'
}
}
console.log(objectToQueryString(testCase1));
console.log(objectToQueryString(testCase2));
Expand the snippet below to verify the result in your browser -
const objectToQueryString = (initialObj) => {
const reducer = (obj, parentPrefix = null) => (prev, key) => {
const val = obj[key];
key = encodeURIComponent(key);
const prefix = parentPrefix ? `${parentPrefix}[${key}]` : key;
if (val == null || typeof val === 'function') {
prev.push(`${prefix}=`);
return prev;
}
if (['number', 'boolean', 'string'].includes(typeof val)) {
prev.push(`${prefix}=${encodeURIComponent(val)}`);
return prev;
}
prev.push(Object.keys(val).reduce(reducer(val, prefix), []).join('&'));
return prev;
};
return Object.keys(initialObj).reduce(reducer(initialObj), []).join('&');
};
const testCase1 = {
name: 'Full Name',
age: 30
}
const testCase2 = {
name: 'Full Name',
age: 30,
children: [
{name: 'Child foo'},
{name: 'Foo again'}
],
wife: {
name: 'Very Difficult to say here'
}
}
console.log(objectToQueryString(testCase1));
console.log(objectToQueryString(testCase2));
_x000D_
functions
, null
, undefined
keys
and values
for empty objects and arrays.new Number(1)
or new String('my string')
because NO ONE should ever do thatvar hoverAndClick = function() {
// Your actions here
} ;
$("#target").hover( hoverAndClick ).click( hoverAndClick ) ;
You can do it without a directive but i'm not sure it's the best way. To do this you must create array of array from the data you want to display in the table, and after that use 2 ng-repeat to iterate through the array.
to create the array for display use this function like that products.chunk(3)
Array.prototype.chunk = function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
}
and then do something like that using 2 ng-repeat
<div class="row" ng-repeat="row in products.chunk(3)">
<div class="col-sm4" ng-repeat="item in row">
{{item}}
</div>
</div>
You must set the height of the container explicitly
#container {
height:100%;
width:100%;
position:absolute;
}
You can use
$(window).on('load', function() {
// your code here
});
Which will wait until the page is loaded. $(document).ready()
waits until the DOM is loaded.
In plain JS:
window.addEventListener('load', function() {
// your code here
})
Try this character set:
[ \t]
This does only match a space or a tabulator.
I'm not sure there is an api to get the default system font name. So I just get the name like this :
//get system default font
UILabel *label = [[UILabel alloc] init];
fontname = label.font.fontName;
[label release];
Looks stupid but it works.
For your actual form, if you were to just post the results to your same page, it should probably work out all right. Try something like:
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="POST>
"Hash and Range Primary Key" means that a single row in DynamoDB has a unique primary key made up of both the hash and the range key. For example with a hash key of X and range key of Y, your primary key is effectively XY. You can also have multiple range keys for the same hash key but the combination must be unique, like XZ and XA. Let's use their examples for each type of table:
Hash Primary Key – The primary key is made of one attribute, a hash attribute. For example, a ProductCatalog table can have ProductID as its primary key. DynamoDB builds an unordered hash index on this primary key attribute.
This means that every row is keyed off of this value. Every row in DynamoDB will have a required, unique value for this attribute. Unordered hash index means what is says - the data is not ordered and you are not given any guarantees into how the data is stored. You won't be able to make queries on an unordered index such as Get me all rows that have a ProductID greater than X. You write and fetch items based on the hash key. For example, Get me the row from that table that has ProductID X. You are making a query against an unordered index so your gets against it are basically key-value lookups, are very fast, and use very little throughput.
Hash and Range Primary Key – The primary key is made of two attributes. The first attribute is the hash attribute and the second attribute is the range attribute. For example, the forum Thread table can have ForumName and Subject as its primary key, where ForumName is the hash attribute and Subject is the range attribute. DynamoDB builds an unordered hash index on the hash attribute and a sorted range index on the range attribute.
This means that every row's primary key is the combination of the hash and range key. You can make direct gets on single rows if you have both the hash and range key, or you can make a query against the sorted range index. For example, get Get me all rows from the table with Hash key X that have range keys greater than Y, or other queries to that affect. They have better performance and less capacity usage compared to Scans and Queries against fields that are not indexed. From their documentation:
Query results are always sorted by the range key. If the data type of the range key is Number, the results are returned in numeric order; otherwise, the results are returned in order of ASCII character code values. By default, the sort order is ascending. To reverse the order, set the ScanIndexForward parameter to false
I probably missed some things as I typed this out and I only scratched the surface. There are a lot more aspects to take into consideration when working with DynamoDB tables (throughput, consistency, capacity, other indices, key distribution, etc.). You should take a look at the sample tables and data page for examples.
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
I found that the following is useful if you need the return value:
result = %x[ls]
puts result
I specifically wanted to list the pids of all the Java processes on my machine, and used this:
ids = %x[ps ax | grep java | awk '{ print $1 }' | xargs]
I composed this for my own use-case (es5 environment), thought this might be useful for someone, so here it is:
function deepCompare(obj1, obj2) {
var diffObj = Array.isArray(obj2) ? [] : {}
Object.getOwnPropertyNames(obj2).forEach(function(prop) {
if (typeof obj2[prop] === 'object') {
diffObj[prop] = deepCompare(obj1[prop], obj2[prop])
// if it's an array with only length property => empty array => delete
// or if it's an object with no own properties => delete
if (Array.isArray(diffObj[prop]) && Object.getOwnPropertyNames(diffObj[prop]).length === 1 || Object.getOwnPropertyNames(diffObj[prop]).length === 0) {
delete diffObj[prop]
}
} else if(obj1[prop] !== obj2[prop]) {
diffObj[prop] = obj2[prop]
}
});
return diffObj
}
This might be not really efficient, but will output an object with only different props based on second Obj.
I was using the p12 which I exported with Keychain in my MacBook, however, it didn't work on my java-apns server code. What I had to do was to create a new p12 key as stated here, using my already generated pem keys:
openssl pkcs12 -export -in your_app.pem -inkey your_key.pem -out your_app_key.p12
Then updated the path to that new p12 file and everything worked perfectly.
The SpeechRecognition
library requires Python 3.3 or up:
Requirements
[...]
The first software requirement is Python 3.3 or better. This is required to use the library.
and from the Trove classifiers:
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
The urllib.request
module is part of the Python 3 standard library; in Python 2 you'd use urllib2
here.
Also:
window.location.href += (window.location.href.indexOf('?') > -1 ? '&' : '?') + 'param=1'
Just one liner of Shlomi answer usable in bookmarklets
You have to actually call some method to create the directories. Just creating a file
object will not create the corresponding file or directory on the file system.
You can use File#mkdirs()
method to create the directory: -
theFile.mkdirs();
Difference between File#mkdir()
and File#mkdirs()
is that, the later will create any intermediate directory if it does not exist.
Residuum did provide a correct answer to how you should get shell exec to find your script, but in regards to security, there are a couple of points.
I would imagine you don't want your shell script to be in your web root, as it would be visible to anyone with web access to your server.
I would recommend moving the shell script to outside of the webroot
<?php
$tempFolder = '/tmp';
$webRootFolder = '/var/www';
$scriptName = 'myscript.sh';
$moveCommand = "mv $webRootFolder/$scriptName $tempFolder/$scriptName";
$output = shell_exec($moveCommand);
?>
In regards to the:
i added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers works
You can modify this to only cover the specific commands in your script which require sudo. Otherwise, if none of the commands in your sh script require sudo to execute, you don't need to do this at all anyway.
Try running the script as the apache user (use the su command to switch to the apache user) and if you are not prompted for sudo or given permission denied, etc, it'll be fine.
ie:
sudo su apache (or www-data)
cd /var/www
sh ./myscript
Also... what brought me here was that I wanted to run a multi line shell script using commands that are dynamically generated. I wanted all of my commands to run in the same shell, which won't happen using multiple calls to shell_exec(). The answer to that one is to do it like Jenkins - create your dynamically generated multi line of commands, put it in a variable, save it to a file in a temp folder, execute that file (using shell_exec in() php as Jenkins is Java), then do whatever you want with the output, and delete the temp file
... voila
https://wiki.jenkins.io/display/JENKINS/Installing+Jenkins+on+Ubuntu
Once installed like this, you can update to the later version of Jenkins (when it comes out) by running the following commands:
-------
sudo apt-get update
sudo apt-get install jenkins
-------
(aptitude or apt-get doesn't make any difference.)
What does this package do?
Jenkins will be launched as a daemon up on start. See /etc/init.d/jenkins for more details.
The 'jenkins' user is created to run this service.
Log file will be placed in /var/log/jenkins/jenkins.log. Check this file if you are troubleshooting Jenkins.
/etc/default/jenkins will capture configuration parameters for the launch like e.g JENKINS_HOME
By default, Jenkins listen on port 8080. Access this port with your browser to start configuration.
I had the same issue, but I have resolved it the next:
1) Install jdk1.8...
2) In AndroidStudio File->Project Structure->SDK Location, select your directory where the JDK is located, by default Studio uses embedded JDK but for some reason it produces error=216.
3) Click Ok.
preg_replace('/[^a-zA-Z0-9_ \-()\/%-&]/s', '', $String);
To complement the previous answers, after you edit your CSS file, you just need to edit CAROUSEL.TRANSITION_DURATION
(in bootstrap.js) or c.TRANSITION_DURATION
(if you use bootstrap.min.js) and to change the value inside it (600 for default). The final value must be the same that you put in your CSS file (for example, 10s in CSS = 10000 in .js)
Carousel.VERSION = '3.3.2'
Carousel.TRANSITION_DURATION = xxxxx /* Your number here*/
Carousel.DEFAULTS = {
interval: 5000 /* you could change this value too, but to add data-interval="xxxx" to your html it's fine too*/
pause: 'hover',
wrap: true,
keyboard: true
}
I think its pretty straight forward with reflection
MyClass mobj = MyClass.class.cast(obj);
and if class name is different
Object newObj = Class.forName(classname).cast(obj);
Debugging needs to be enabled on the target device in order for adb
to see it.
Kotlin code:
if (file.exists()){
val bitmap = BitmapFactory.decodeFile(file.absolutePath)
val exif = ExifInterface(file.absoluteFile.toString())
val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
val matrix = Matrix()
when(orientation){
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90F)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180F)
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270F)
}
val rotatedBitmap = Bitmap.createBitmap(bitmap, 0,0 , bitmap.width, bitmap.height, matrix, true)
bitmap.recycle()
iv_capture.setImageBitmap(rotatedBitmap)
}
What about the shortcut CTRL+L?
It works for all shells e.g. Python, Bash, MySQL, MATLAB, etc.
The Distinct() guarantees that there are no duplicates pair (CategoryId, CategoryName).
- exactly that
Anonymous types 'magically' implement Equals
and GetHashcode
I assume another error somewhere. Case sensitivity? Mutable classes? Non-comparable fields?
This is what I managed to do so far. I guess this is kind of what you're trying to pull out. The only thing is that I can still not manage to assign the proper height to the container DIV.
The HTML:
<div id="container">
<div id="header">HEADER</div>
<div id="fixeddiv-top">FIXED DIV (TOP)</div>
<div id="content-container">
<div id="content">CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT</div>
</div>
<div id="fixeddiv-bottom">FIXED DIV (BOTTOM)</div>
</div>
And the CSS:
html {
height:100%;
}
body {
height:100%;
margin:0;
padding:0;
}
#container {
width:600px;
height:50%;
text-align:center;
display:block;
position:relative;
}
#header {
background:#069;
text-align:center;
width:100%;
height:80px;
}
#fixeddiv-top {
background:#AAA;
text-align:center;
width:100%;
height:20px;
}
#content-container {
height:100%;
}
#content {
text-align:center;
height:100%;
background:#F00;
margin:0 auto;
overflow:auto;
}
#fixeddiv-bottom {
background:#AAA;
text-align:center;
width:100%;
height:20px;
}
In vim You can type :%!xxd to turn it into a hexeditor. :%!xxd -r to go back to normal mode. xxd is shipped in a vim installation.
See here for some remarks about editing binary files with vim (boils down to :set binary to avoid trouble, use only the "R" or "r" command to change text, don't delete characters).
If You are an Emacs fan, see here for a guide on how to edit a binary file with Emacs.
An implicitly declared function is one that has neither a prototype nor a definition, but is called somewhere in the code. Because of that, the compiler cannot verify that this is the intended usage of the function (whether the count and the type of the arguments match). Resolving the references to it is done after compilation, at link-time (as with all other global symbols), so technically it is not a problem to skip the prototype.
It is assumed that the programmer knows what he is doing and this is the premise under which the formal contract of providing a prototype is omitted.
Nasty bugs can happen if calling the function with arguments of a wrong type or count. The most likely manifestation of this is a corruption of the stack.
Nowadays this feature might seem as an obscure oddity, but in the old days it was a way to reduce the number of header files included, hence faster compilation.
This solution will work regardless of the number of char
variables you have:
char c1 = 'z';
char c2 = 'w';
std::string s1{c1};
std::string s12{c1, c2};
For Bootstrap 4 you may have to use .modal-backdrop.show
and play around with !important
flag on both background-color
and opacity
.
E.g.
.modal-backdrop.show {
background-color: #f00;
opacity: 0.75;
}
Should it be necessary to manually remove a service:
You will have to reboot before the list gets updated in services
for /f "tokens=* delims= " %%f in (myfile) do
This reads a file line-by-line, removing leading spaces (thanks, jeb).
set line=%%f
sets then the line
variable to the line just read and
call :procesToken
calls a subroutine that does something with the line
:processToken
is the start of the subroutine mentioned above.
for /f "tokens=1* delims=/" %%a in ("%line%") do
will then split the line at /
, but stopping tokenization after the first token.
echo Got one token: %%a
will output that first token and
set line=%%b
will set the line
variable to the rest of the line.
if not "%line%" == "" goto :processToken
And if line
isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.
This error happen usually when tables in the query doesn't exist. Just check the table's spelling in the query, and it will work.
To do this via TSQL (ssms query window or sqlcmd.exe) just run:
RESTORE DATABASE MyDatabase FROM DISK='c:\backups\MyDataBase1.bak'
To do it via GUI - open SSMS, right click on Databases and follow the steps below
Due to PEP-0469 which renamed iteritems() to items() and PEP-3113 which removed Tuple parameter unpacking, in Python 3.x you should write Martijn Pieters? answer like this:
my_dictionary = dict(map(lambda item: (item[0], f(item[1])), my_dictionary.items()))
Using bitwise_and, bitwise_or, and bitwise_not you can modify any bit configurations to another bit configurations (i.e. these set of operators are "functionally complete"). However, for operations like modulus, the general formula would be necessarily be quite complicated, I wouldn't even bother trying to recreate it.
Also, if you had multiple event handlers attached to the same selector executing the same function, you could use
$('table.planning_grid').on('mouseenter mouseleave', function() {
//JS Code
});
\n is add a new line.
Please note java has method System.out.println("Write text here");
Notice the difference:
Code:
System.out.println("Text 1");
System.out.println("Text 2");
Output:
Text 1
Text 2
Code:
System.out.print("Text 1");
System.out.print("Text 2");
Output:
Text 1Text 2
For Linux or OSX, you can use ipfw
.
From Quora (http://www.quora.com/What-is-the-best-tool-to-simulate-a-slow-internet-connection-on-a-Mac)
Essentially using a firewall to throttle all network data:
Define a rule that uses a pipe to reroute all traffic from any source address to any destination address, execute the following command (as root, or using sudo):
$ ipfw add pipe 1 all from any to any
To configure this rule to limit bandwidth to 300Kbit/s and impose 200ms of latency each way:
$ ipfw pipe 1 config bw 300Kbit/s delay 200ms
To remove all rules and recover your original network connection:
$ ipfw flush
See https://docs.djangoproject.com/en/stable/ref/templates/builtins/#if : just use, to reproduce their example:
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% else %}
No athletes.
{% endif %}
The following css property will do it
position: fixed;
I hope this help.
I would just point out that... there are many kind of unordered_map
s.
Look up the Wikipedia Article on hash map. Depending on which implementation was used, the characteristics in term of look-up, insertion and deletion might vary quite significantly.
And that's what worries me the most with the addition of unordered_map
to the STL: they will have to choose a particular implementation as I doubt they'll go down the Policy
road, and so we will be stuck with an implementation for the average use and nothing for the other cases...
For example some hash maps have linear rehashing, where instead of rehashing the whole hash map at once, a portion is rehash at each insertion, which helps amortizing the cost.
Another example: some hash maps use a simple list of nodes for a bucket, others use a map, others don't use nodes but find the nearest slot and lastly some will use a list of nodes but reorder it so that the last accessed element is at the front (like a caching thing).
So at the moment I tend to prefer the std::map
or perhaps a loki::AssocVector
(for frozen data sets).
Don't get me wrong, I'd like to use the std::unordered_map
and I may in the future, but it's difficult to "trust" the portability of such a container when you think of all the ways of implementing it and the various performances that result of this.
There are known issues with IE and Opera not removing session cookies when setting the expire date to the past (which is what the jQuery cookie plugin does)
This works fine in Safari and Mozilla/FireFox.
This worked for me:
<html>
<head>
<title>scroll</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<style>
div.container {
overflow:hidden;
width:200px;
height:200px;
}
div.content {
position:relative;
width:200px;
height:200px;
overflow:hidden;
top:0;
}
</style>
<div class="container">
<p>
<a href="javascript:up();"><img src="/images/img_flecha_left.png" class="up" /></a>
<a href="javascript:down();"><img src="/images/img_flecha_left.png" class="down" /></a>
</p>
<div class="content">
<p>Hello World</p><p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
<p>Hello World</p>
</div>
</div>
<script>
function up() {
var topVal = $(".content").css("top"); //alert(topVal);
var val=parseInt(topVal.replace("px",""));
val=val-20;
$(".content").css("top", val+"px");
}
function down() {
var topVal = $(".content").css("top"); //alert(topVal);
var val=parseInt(topVal.replace("px",""));
val=val+20;
$(".content").css("top", val+"px");
}
</script>
</body>
</html>
this is my solution to the problem. I used it in a chatbot to replace the different words at once.
def mass_replace(text, dct):
new_string = ""
old_string = text
while len(old_string) > 0:
s = ""
sk = ""
for k in dct.keys():
if old_string.startswith(k):
s = dct[k]
sk = k
if s:
new_string+=s
old_string = old_string[len(sk):]
else:
new_string+=old_string[0]
old_string = old_string[1:]
return new_string
print mass_replace("The dog hunts the cat", {"dog":"cat", "cat":"dog"})
this will become The cat hunts the dog
Read about the super keyword (Scroll down the Subclass Constructors). If I understand your question, you probably want to call a superclass constructor?
It is worth noting that the Java compiler will automatically put in a no-arg constructor call to the superclass if you do not explicitly invoke a superclass constructor.
This answer will work for you if you need the following conditions met (none of the current answers met these conditions):
I believe that 3 is the minimal number of HTML elements to satisfy these conditions:
.input-icon{_x000D_
position: absolute;_x000D_
left: 3px;_x000D_
top: calc(50% - 0.5em); /* Keep icon in center of input, regardless of the input height */_x000D_
}_x000D_
input{_x000D_
padding-left: 17px;_x000D_
}_x000D_
.input-wrapper{_x000D_
position: relative;_x000D_
}
_x000D_
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"/>_x000D_
<div class="input-wrapper">_x000D_
<input id="stuff">_x000D_
<label for="stuff" class="fa fa-user input-icon"></label>_x000D_
</div>
_x000D_
Ivo Wetzel's answer doesn't seem to be valid in Socket.io 0.9 anymore.
In short you must now save the socket.id
and use io.sockets.socket(savedSocketId).emit(...)
to send messages to it.
This is how I got this working in clustered Node.js server:
First you need to set Redis store as the store so that messages can go cross processes:
var express = require("express");
var redis = require("redis");
var sio = require("socket.io");
var client = redis.createClient()
var app = express.createServer();
var io = sio.listen(app);
io.set("store", new sio.RedisStore);
// In this example we have one master client socket
// that receives messages from others.
io.sockets.on('connection', function(socket) {
// Promote this socket as master
socket.on("I'm the master", function() {
// Save the socket id to Redis so that all processes can access it.
client.set("mastersocket", socket.id, function(err) {
if (err) throw err;
console.log("Master socket is now" + socket.id);
});
});
socket.on("message to master", function(msg) {
// Fetch the socket id from Redis
client.get("mastersocket", function(err, socketId) {
if (err) throw err;
io.sockets.socket(socketId).emit(msg);
});
});
});
I omitted the clustering code here, because it makes this more cluttered, but it's trivial to add. Just add everything to the worker code. More docs here http://nodejs.org/api/cluster.html
Other than the advantages listed in the answers given, one more advantage of NestedScrollView over ScrollView is its compatibility with CoordinatorLayout. The ScrollView does not cooperate with the CoordinatorLayout. You have to use NestedScrollView to get "scroll off-screen" behaviour for the toolbar.
Toolbar will not collapse with Scrollview as child of CoordinatorLayout
Why not:
onItemClick: function (event) {
event.currentTarget.style.backgroundColor = '#ccc';
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick}>Component 1</li>
</ul>
</div>
);
}
And if you want to be more React-ive about it, you might want to set the selected item as state of its containing React component, then reference that state to determine the item's color within render
:
onItemClick: function (event) {
this.setState({ selectedItem: event.currentTarget.dataset.id });
//where 'id' = whatever suffix you give the data-* li attribute
},
render: function() {
return (
<div>
<ul>
<li onClick={this.onItemClick} data-id="1" className={this.state.selectedItem == 1 ? "on" : "off"}>Component 1</li>
<li onClick={this.onItemClick} data-id="2" className={this.state.selectedItem == 2 ? "on" : "off"}>Component 2</li>
<li onClick={this.onItemClick} data-id="3" className={this.state.selectedItem == 3 ? "on" : "off"}>Component 3</li>
</ul>
</div>
);
},
You'd want to put those <li>
s into a loop, and you need to make the li.on
and li.off
styles set your background-color
.
# Patrick Burwell's Ping Script - [email protected] #
$Output= @() #sets an array
$names = Get-Content ".\input\ptd.pc_list.txt" #sets a list to use, like a DNS dump
foreach ($name in $names){ #sets the input by enumerating a text file to loop through and sets a variable to execute against
if ($IPV4 = Test-Connection -Delay 15 -ComputerName $name -Count 1 -ErrorAction SilentlyContinue|select IPV4Address #run ping and sets only IPV4Address response variable
){# If true then run...
$Output+= $Name,($IPV4.IPV4Address).IPAddressToString # Fills the array with the #true response
Write-Host $Name',','Ping,'($IPV4.IPV4Address).IPAddressToString -ForegroundColor Green #Sets the output to receive the Name, result and IPV4Address and prints the reply to the console with specific colors
}
else{#If false then run...
$Output+= "$name," #Fills the array with the #false response
Write-Host "$Name," -ForegroundColor Red #Prints the reply to the console with specific colors
}
}
#$Output | Out-file ".\output\result.csv" #<-- use to export to a text file (Set path as needed)
#$Output | Export-CSV ".\output\result.csv" -NoTypeInformation #<-- use to export to a csv file (Set path as needed)
#If you choose, you can merely have the reply by the name and IP, and the Name and no IP by removing the Ping comments
Or just use Apache CXF's wsdl2java to generate objects you can use.
It is included in the binary package you can download from their website. You can simply run a command like this:
$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl
It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):
DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);
There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html
Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315
I think that what you have written is perfectly fine. I also don't see any readability issue with having multiple return statements.
I would always prefer to return from the point in the code when I know to return and this will avoid running logic below the return.
There can be an argument for having a single return point for debugging and logging. But, in your code, there is no issue of debugging and logging if we use it. It is very simple and readable the way you wrote.
SCSS option for changing all of the buttons...
// do something for each color
@each $color, $value in $theme-colors {
// nav-link outline colors on the outer nav element
.nav-outline-#{$color} .nav-link {
@include button-outline-variant($value);
margin: 2px 0;
}
// nav-link colors on the outer nav element
.nav-#{$color} .nav-link {
@include button-variant($value, $value);
margin: 2px 0;
}
}
so you end up with all the defined colors .nav-primary
similar to the .btn-primary
...
<div class="col-2 nav-secondary">
<div class="nav flex-column nav-pills" id="v-pills-tab" role="tablist" aria-orientation="vertical">
<a class="nav-link" aria-expanded="true" aria-controls="addService" data-toggle="pill" href="#addService" role="tab" aria-selected="false">
Add Service
</a>
<a class="nav-link" aria-expanded="true" aria-controls="bonusPayment" data-toggle="pill" href="#bonusPayment" role="tab" aria-selected="false">
Bonus Payment
</a>
<a class="nav-link" aria-expanded="true" aria-controls="oneTimeInvoice" data-toggle="pill" href="#oneTimeInvoice" role="tab" aria-selected="false">
Invoice - One Time
</a>
<a class="nav-link active" aria-expanded="true" aria-controls="oneTimePayment" data-toggle="pill" href="#oneTimePayment" role="tab" aria-selected="true">
Payment - One Time
</a>
</div>
</div>
It is possible and is deceptively easy:
bin\Debug
folder below the project file (.csproj).app.publish
folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.
It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.
long dateTime = DateTime.Now.Ticks;
Console.WriteLine(dateTime);
Console.WriteLine(new DateTime(dateTime));
Console.ReadKey();
-F
is an argument to awk
itself:
$echo "1: " | awk -F":" '/1/ {print $1}'
1
I found the simplest way:
gnome-terminal --tab -e 'command 1' --tab -e 'command 2'
I use tmux
instead of using terminal directly. So what I want is really a single and simple command/shell file to build the development env
with several tmux
windows. The shell code is as below:
#!/bin/bash
tabs="adb ana repo"
gen_params() {
local params=""
for tab in ${tabs}
do
params="${params} --tab -e 'tmux -u attach-session -t ${tab}'"
done
echo "${params}"
}
cmd="gnome-terminal $(gen_params)"
eval $cmd
I fought with this problem for a few hours before stumbling on the obvious answer. The problem I had was I was using different ssh implementations between when I generated my keys and when I used git.
I used ssh-keygen from the command prompt to generate my keys and but when I tried "git clone ssh://..." I got the same results as you, a prompt for the password and the message "fatal: The remote end hung up unexpectedly".
Determine which ssh windows is using by executing the Windows "where" command.
C:\where ssh
C:\Program Files (x86)\Git\bin\ssh.exe
The second line tells you which exact program will be executed.
Next you need to determine which ssh that git is using. Find this by:
C:\set GIT_SSH
GIT_SSH=C:\Program Files\TortoiseSVN\bin\TortoisePlink.exe
And now you see the problem.
To correct this simply execute:
C:\set GIT_SSH=C:\Program Files (x86)\Git\bin\ssh.exe
To check if changes are applied:
C:\set GIT_SSH
GIT_SSH=C:\Program Files (x86)\Git\bin\ssh.exe
Now git will be able to use the keys that you generated earlier.
This fix is so far only for the current window. To fix it completely you need to change your environment variable.
Now any future command windows you open will have the correct settings.
Hope this helps.
I had this or a similar problem after installing Tomcat.
The other answers didn't quite work, but got me on the right path. I answered this at https://stackoverflow.com/a/20762179/3128838 after discovering a YouTube video showing the exact problem I was having.
There is another way to disable JPA tools for the project, that doesn't require to uninstall JPA features/plug-ins. I tested on https://github.com/Jasig/uPortal project wich was mentioned in https://bugs.eclipse.org/bugs/show_bug.cgi?id=386171 and claims to have similar problems:
After disabling JPA facet for uportal-war project form repository above I don't see any JPA related jobs in Eclipse Progress View.
You have to bind the resize
event on the window
object, not on a generic html element.
You could then use this:
$(window).resize(function() {
...
});
and within the callback function you can check the new width of your div
calling
$('.a-selector').width();
So, the answer to your question is no, you can't bind the resize
event to a div.
I have a site where a logging-script writes a new line of text to a textfile after an action from the user, who can be using any OS.
Using PHP_EOL don't seem to be optimal in this case. If the user is on Mac OS and writes to the textfile it will put \n. When opening the textfile on a windows computer it doesn't show a line break. For this reason i use "\r\n" instead which works when opening the file on any OS.
I managed to get this done using Jackson
in Spring 5. Depending on the object Jackson might not work in all cases.
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
ObjectMapper mapper = new ObjectMapper();
Staff staff = createStaff();
// pretty print
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
System.out.println("-------------------------------------------------------------------")
System.out.println(json);
System.out.println("-------------------------------------------------------------------")
the output would be something like
-------------------------------------------------------------------
{
"id" : 1,
"internalStaffId" : "1",
"staffCms" : 1,
"createdAt" : "1",
"updatedAt" : "1",
"staffTypeChange" : null,
"staffOccupationStatus" : null,
"staffNote" : null
}
-------------------------------------------------------------------
More examples using Jackson
here
You can try GSON
also. Should be something like this:
Gson gson = new Gson();
System.out.println(gson.toJson(objectYouWantToPrint).toString());
To take 6footunder's comment and turn it into an answer, HttpContent
is abstract so you need to use one of the derived classes:
Java Servlets are server-side Java program modules that procedure and answer customer demands and actualize the servlet interface. It helps in improving Web server usefulness with negligible overhead, upkeep and support.
A servlet goes about as a mediator between the customer and the server. As servlet modules keep running on the server, they can get and react to demands made by the customer. Demand and reaction objects of the servlet offer a helpful method to deal with HTTP asks for and send content information back to the customer.
Since a servlet is coordinated with the Java dialect, it additionally has all the Java highlights, for example, high movability, stage autonomy, security and Java database availability.
Instead of the below line
//header("Location:".ADMIN_URL."/index.php");
write
echo("<script>location.href = '".ADMIN_URL."/index.php?msg=$msg';</script>");
or
?><script><?php echo("location.href = '".ADMIN_URL."/index.php?msg=$msg';");?></script><?php
It'll definitely solve your problem. I faced the same problem but I solved through writing header location in the above way.
I tried every method listed here and in Android adb devices unauthorized
What eventually worked for me was the option just below USB Debugging 'Revoke auths'
Not sure if I am late to the party but I found this nice example that overrides the JSONObject constructor and makes sure that the JSON data are output in the same way as they are added. Behind the scenes JSONObject uses the MAP and MAP does not guarantee the order hence we need to override it to make sure we are receiving our JSON as per our order.
If you add this to your JSONObject then the resulting JSON would be in the same order as you have created it.
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;
import lombok.extern.java.Log;
@Log
public class JSONOrder {
public static void main(String[] args) throws IOException {
JSONObject jsontest = new JSONObject();
try {
Field changeMap = jsonEvent.getClass().getDeclaredField("map");
changeMap.setAccessible(true);
changeMap.set(jsonEvent, new LinkedHashMap<>());
changeMap.setAccessible(false);
} catch (IllegalAccessException | NoSuchFieldException e) {
log.info(e.getMessage());
}
jsontest.put("one", "I should be first");
jsonEvent.put("two", "I should be second");
jsonEvent.put("third", "I should be third");
System.out.println(jsonEvent);
}
}
The problem with these extension methods is that when the UIView/UIButton later adjusts it's size, you have no chance to change the CALayer's size to match the new size. Which will leave you with a misplaced border. I found it was better to subclass my UIButton, you could of course subclass other UIViews as well. Here is some code:
enum BorderedButtonSide {
case Top, Right, Bottom, Left
}
class BorderedButton : UIButton {
private var borderTop: CALayer?
private var borderTopWidth: CGFloat?
private var borderRight: CALayer?
private var borderRightWidth: CGFloat?
private var borderBottom: CALayer?
private var borderBottomWidth: CGFloat?
private var borderLeft: CALayer?
private var borderLeftWidth: CGFloat?
func setBorder(side: BorderedButtonSide, _ color: UIColor, _ width: CGFloat) {
let border = CALayer()
border.backgroundColor = color.CGColor
switch side {
case .Top:
border.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: width)
borderTop?.removeFromSuperlayer()
borderTop = border
borderTopWidth = width
case .Right:
border.frame = CGRect(x: frame.size.width - width, y: 0, width: width, height: frame.size.height)
borderRight?.removeFromSuperlayer()
borderRight = border
borderRightWidth = width
case .Bottom:
border.frame = CGRect(x: 0, y: frame.size.height - width, width: frame.size.width, height: width)
borderBottom?.removeFromSuperlayer()
borderBottom = border
borderBottomWidth = width
case .Left:
border.frame = CGRect(x: 0, y: 0, width: width, height: frame.size.height)
borderLeft?.removeFromSuperlayer()
borderLeft = border
borderLeftWidth = width
}
layer.addSublayer(border)
}
override func layoutSubviews() {
super.layoutSubviews()
borderTop?.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: borderTopWidth!)
borderRight?.frame = CGRect(x: frame.size.width - borderRightWidth!, y: 0, width: borderRightWidth!, height: frame.size.height)
borderBottom?.frame = CGRect(x: 0, y: frame.size.height - borderBottomWidth!, width: frame.size.width, height: borderBottomWidth!)
borderLeft?.frame = CGRect(x: 0, y: 0, width: borderLeftWidth!, height: frame.size.height)
}
}
This problem also arises when you have mockito-all on your class path, which is already deprecated.
If possible just include mockito-core.
Maven config for mixing junit, mockito and hamcrest:
<dependencies>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
JSON.parse
All of the answers here use JSON.parse()
in an unsafe way.
You should always put all calls to JSON.parse()
in a try/catch
block especially when you parse JSON coming from an external source, like you do here.
You can use request
to parse the JSON automatically which wasn't mentioned here in other answers. There is already an answer using request
module but it uses JSON.parse()
to manually parse JSON - which should always be run inside a try {} catch {}
block to handle errors of incorrect JSON or otherwise the entire app will crash. And incorrect JSON happens, trust me.
Other answers that use http
also use JSON.parse()
without checking for exceptions that can happen and crash your application.
Below I'll show few ways to handle it safely.
All examples use a public GitHub API so everyone can try that code safely.
request
Here's a working example with request
that automatically parses JSON:
'use strict';
var request = require('request');
var url = 'https://api.github.com/users/rsp';
request.get({
url: url,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
// data is already parsed as JSON:
console.log(data.html_url);
}
});
http
and try/catch
This uses https
- just change https
to http
if you want HTTP connections:
'use strict';
var https = require('https');
var options = {
host: 'api.github.com',
path: '/users/rsp',
headers: {'User-Agent': 'request'}
};
https.get(options, function (res) {
var json = '';
res.on('data', function (chunk) {
json += chunk;
});
res.on('end', function () {
if (res.statusCode === 200) {
try {
var data = JSON.parse(json);
// data is available here:
console.log(data.html_url);
} catch (e) {
console.log('Error parsing JSON!');
}
} else {
console.log('Status:', res.statusCode);
}
});
}).on('error', function (err) {
console.log('Error:', err);
});
http
and tryjson
This example is similar to the above but uses the tryjson
module. (Disclaimer: I am the author of that module.)
'use strict';
var https = require('https');
var tryjson = require('tryjson');
var options = {
host: 'api.github.com',
path: '/users/rsp',
headers: {'User-Agent': 'request'}
};
https.get(options, function (res) {
var json = '';
res.on('data', function (chunk) {
json += chunk;
});
res.on('end', function () {
if (res.statusCode === 200) {
var data = tryjson.parse(json);
console.log(data ? data.html_url : 'Error parsing JSON!');
} else {
console.log('Status:', res.statusCode);
}
});
}).on('error', function (err) {
console.log('Error:', err);
});
The example that uses request
is the simplest. But if for some reason you don't want to use it then remember to always check the response code and to parse JSON safely.
The current PHP Nightrain (4.0.0) is written in Python and it uses the wxPython libraries. So far wxPython has been working well to get PHP Nightrain where it is today but in order to push PHP Nightrain to its next level, we are introducing a sibling of PHP Nightrain, the PHPWebkit!
It's an update to PHP Nightrain.
Try writing all the errors to a file.
error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
Something like that.
The SmtpClient can be used by code:
SmtpClient mailer = new SmtpClient();
mailer.Host = "mail.youroutgoingsmtpserver.com";
mailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");
I had several inconveniences with all the solutions because I needed the type of Instant variable and the Time Zone always interfered changing everything, then combining solutions I saw that this is a good option.
LocalDate today = LocalDate.now();
Instant startDate = Instant.parse(today.toString()+"T00:00:00Z");
Instant endDate = Instant.parse(today.toString()+"T23:59:59Z");
and we have as a result
startDate = 2020-01-30T00:00:00Z
endDate = 2020-01-30T23:59:59Z
I hope it helps you
first, give the div an id. Then, call function appendClass:
<script language="javascript">
function appendClass(elementId, classToAppend){
var oldClass = document.getElementById(elementId).getAttribute("class");
if (oldClass.indexOf(classToAdd) == -1)
{
document.getElementById(elementId).setAttribute("class", classToAppend);
}
}
</script>