There are lot of GUI designers even like Eclipse plugins, just few of them could use both, Swing and SWT..
WindowBuilder Pro GUI Designer - eclipse marketplace
WindowBuilder Pro GUI Designer - Google code home page
and
Jigloo SWT/Swing GUI Builder - eclipse market place
Jigloo SWT/Swing GUI Builder - home page
The window builder is quite better tool..
But IMHO, GUIs created by those tools have really ugly and unmanageable code..
Same problem:
So I just did pip uninstall virtualenv
Then pip install virtualenv
pip install virtualenv --user
Collecting virtualenv Using cached https://files.pythonhosted.org/packages/b6/30/96a02b2287098b23b875bc8c2f58071c35d2efe84f747b64d523721dc2b5/virtualenv-16.0.0-py2.py3-none-any.whl Installing collected packages: virtualenv
Then I got this :
The script virtualenv is installed in '/Users/brahim/Library/Python/2.7/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
which clearly says where it is installed and what to do to get it
Although the answer that Gunter posted was correct, it is not different than what I already had posted. The problem was not the ENV
directive, but the subsequent instruction RUN export $PATH
There's no need to export the environment variables, once you have declared them via ENV
in your Dockerfile.
As soon as the RUN export ...
lines were removed, my image was built successfully
The easiest option for me was to rename the title of the terminal instead. Please see: https://superuser.com/questions/362227/how-to-change-the-title-of-the-mintty-window
In this answer, they mention to modify the PS1 variable. Note: my situation was particular to cygwin.
TL;DR Put this in your .bashrc file:
function settitle() {
export PS1="\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n$ "
echo -ne "\e]0;$1\a"
}
Put this in your .tmux.conf file, or similar formatting:
set -g pane-border-status bottom
set -g pane-border-format "#P #T #{pane_current_command}"
Then you can change the title of the pane by typing this in the console:
settitle titlename
Matplotlib related
from matplotlib.dates import drange
import datetime
base = datetime.date.today()
end = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
l = drange(base, end, delta)
The same problem happened with me but my problem was that I wasn't adding the FILE_NAME_WHERE_IS_MY_FUNCTION.js
so my file.html never found where my function was
Once I add the "file.js" I resolved the problem
<html ng-app='myApp'>
<body ng-controller='TextController'>
....
....
....
<script src="../file.js"></script>
</body>
</html>
:)
Android will not let you do this for security concerns. An evil developer could very easily steal user-entered login information.
Instead, you have to catch the text being displayed in the webview before it is displayed. If you don't want to set up a response handler (as per the other answers), I found this fix with some googling:
URL url = new URL("https://stackoverflow.com/questions/1381617");
URLConnection con = url.openConnection();
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(con.getContentType());
/* If Content-Type doesn't match this pre-conception, choose default and
* hope for the best. */
String charset = m.matches() ? m.group(1) : "ISO-8859-1";
Reader r = new InputStreamReader(con.getInputStream(), charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
This is a lot of code, and you should be able to copy/paster it, and at the end of it str
will contain the same html drawn in the webview. This answer is from Simplest way to correctly load html from web page into a string in Java and it should work on Android as well. I have not tested this and did not write it myself, but it might help you out.
Also, the URL this is pulling is hardcoded, so you'll have to change that.
I put together a little test here:
\documentclass[10pt,twocolumn]{article}
\title{Article Title}
\author{
First Author\\
Department\\
school\\
email@edu
\and
Second Author\\
Department\\
school\\
email@edu
\and
Third Author\\
Department\\
school\\
email@edu
\and
Fourth Author\\
Department\\
school\\
email@edu
}
\date{\today}
\begin{document}
\maketitle
\begin{abstract}
\ldots
\end{abstract}
\section{Introduction}
\ldots
\end{document}
Things to note, the title, author and date fields are declared before \begin{document}
. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn
in the document class.
This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}
. Here's a more detailed article on \LaTeX
font sizes:
https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont
To italicize you can use {\it First Name}
or \textit{First Name}
.
Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.
Your mileage may vary (mine sure did), but here's what worked for me (current version of Chrome as of this post is 33.x, and I was interested in 24.x)
Visit the Chromium repo proxy lookup site: http://omahaproxy.appspot.com/
In the little box called "Revision Lookup" type in the version number. This will translate it to a Subversion revision number. Keep that number in mind.
Visit the build repository: http://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html
Select the folder corresponding to the OS you're interested in (I have Win x64, but had to use Win,because there was no x64 build corresponding to the version I was looking for).
If you select Win, you could be in for a wait - as some of the pages have a lot of entries. Once the page loads, scroll to the folder containing the revision number you identified in an earlier step. If you don't find one, choose the next one up. This is a bit of trial and error to be honest - I had to back up about 50 revisions until I found a version close to the one I was looking for
Drill into that folder and download (on the Win version) chrome-win32.zip. That's all you need.
Unzip that file and then run chrome.exe
This worked for me and I'm running the latest Chrome alongside version 25, without problems (some profile issues on the older version, but that's neither here nor there). Didn't need to do anything else.
Again, YMMV, but try this solution first since it requires the least amount of tomfoolery.
The Unicode code blocks that the others answers gave certainly cover most of the Chinese Unicode characters, but check out some of these other code blocks, too.
CJK_UNIFIED_IDEOGRAPHS
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D
CJK_UNIFIED_IDEOGRAPHS_EXTENSION_E
CJK_COMPATIBILITY
CJK_COMPATIBILITY_FORMS
CJK_COMPATIBILITY_IDEOGRAPHS
CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT
CJK_RADICALS_SUPPLEMENT
CJK_STROKES
CJK_SYMBOLS_AND_PUNCTUATION
ENCLOSED_CJK_LETTERS_AND_MONTHS
ENCLOSED_IDEOGRAPHIC_SUPPLEMENT
KANGXI_RADICALS
IDEOGRAPHIC_DESCRIPTION_CHARACTERS
See my fuller discussion here. And this site is convenient for browsing Unicode.
First check the php.ini
file path by phpinfo()
; and then changed PHP.INI
params:
upload_max_filesize = 1000M
memory_limit = 1500M
post_max_size = 1500M
max_execution_time = 30
restarted Apache
set_time_limit(0); // safe_mode is off
ini_set('max_execution_time', 500); //500 seconds
Note: you can also use command to find php.ini
in Linux
locate `php.ini`
The angular2 way is to use listen
or listenGlobal
from Renderer
For example, if you want to add a click event to a Component, you have to use Renderer and ElementRef (this gives you as well the option to use ViewChild, or anything that retrieves the nativeElement
)
constructor(elementRef: ElementRef, renderer: Renderer) {
// Listen to click events in the component
renderer.listen(elementRef.nativeElement, 'click', (event) => {
// Do something with 'event'
})
);
You can use listenGlobal
that will give you access to document
, body
, etc.
renderer.listenGlobal('document', 'click', (event) => {
// Do something with 'event'
});
Note that since beta.2 both listen
and listenGlobal
return a function to remove the listener (see breaking changes section from changelog for beta.2). This is to avoid memory leaks in big applications (see #6686).
So to remove the listener we added dynamically we must assign listen
or listenGlobal
to a variable that will hold the function returned, and then we execute it.
// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;
// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;
constructor(elementRef: ElementRef, renderer: Renderer) {
// We cache the function "listen" returns
this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
// Do something with 'event'
});
// We cache the function "listenGlobal" returns
this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
// Do something with 'event'
});
}
ngOnDestroy() {
// We execute both functions to remove the respectives listeners
// Removes "listen" listener
this.listenFunc();
// Removs "listenGlobal" listener
this.globalListenFunc();
}
Here's a plnkr with an example working. The example contains the usage of listen
and listenGlobal
.
25/02/2017: Renderer
has been deprecated, now we should use (see line below). See the commit.RendererV2
10/03/2017: RendererV2
was renamed to Renderer2
. See the breaking changes.
RendererV2
has no more listenGlobal
function for global events (document, body, window). It only has a listen
function which achieves both functionalities.
For reference, I'm copy & pasting the source code of the DOM Renderer implementation since it may change (yes, it's angular!).
listen(target: 'window'|'document'|'body'|any, event: string, callback: (event: any) => boolean):
() => void {
if (typeof target === 'string') {
return <() => void>this.eventManager.addGlobalEventListener(
target, event, decoratePreventDefault(callback));
}
return <() => void>this.eventManager.addEventListener(
target, event, decoratePreventDefault(callback)) as() => void;
}
As you can see, now it verifies if we're passing a string (document, body or window), in which case it will use an internal addGlobalEventListener
function. In any other case, when we pass an element (nativeElement) it will use a simple addEventListener
To remove the listener it's the same as it was with Renderer
in angular 2.x. listen
returns a function, then call that function.
// Add listeners
let global = this.renderer.listen('document', 'click', (evt) => {
console.log('Clicking the document', evt);
})
let simple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
console.log('Clicking the button', evt);
});
// Remove listeners
global();
simple();
plnkr with Angular 4.0.0-rc.1 using RendererV2
plnkr with Angular 4.0.0-rc.3 using Renderer2
After a few futile hours battling with a 'SyntaxError: missing : after property id' message I can now expand on this topic:
border-width is a valid css property but it is not included in the jQuery css oject definition, so .css({border-width: '2px'}) will cause an error, but it's quite happy with .css({'border-width': '2px'}), presumably property names in quotes are just passed on as received.
What about using UIPageViewController
with an array of UICollectionViewControllers
? You'd have to fetch proper number of items in each UICollectionViewController
, but it shouldn't be hard. You'd get exactly the same look as the Springboard has.
I've thought about this and in my opinion you have to set:
self.collectionView.pagingEnabled = YES;
and create your own collection view layout by subclassing UICollectionViewLayout
. From the custom layout object you can access self.collectionView
, so you'll know what is the size of the collection view's frame
, numberOfSections
and numberOfItemsInSection:
. With that information you can calculate cells' frames
(in prepareLayout
) and collectionViewContentSize
. Here're some articles about creating custom layouts:
You can do this (or an approximation of it) without creating the custom layout. Add UIScrollView
in the blank view, set paging enabled in it. In the scroll view add the a collection view. Then add to it a width constraint, check in code how many items you have and set its constant
to the correct value, e.g. (self.view.frame.size.width * numOfScreens)
. Here's how it looks (numbers on cells show the indexPath.row
): https://www.dropbox.com/s/ss4jdbvr511azxz/collection_view.mov If you're not satisfied with the way cells are ordered, then I'm afraid you'd have to go with 1. or 2.
This should work (where enquiryId
is the id you need to match against):
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == enquiryId);
What this does is passes each vehicle in the list into the lambda predicate, evaluating the predicate. If the predicate returns true (ie. vehicle.EnquiryID == enquiryId
), then the current vehicle will be removed from the list.
If you know the types of the objects in your collections, then using the generic collections is a better approach. It avoids casting when retrieving objects from the collections, but can also avoid boxing if the items in the collection are value types (which can cause performance issues).
On a 64-bit Windows system, the reading of the various environment variables and some Windows Registry keys is redirected to different sources, depending whether the process doing the reading is 32-bit or 64-bit.
The table below lists these data sources:
X = HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion
Y = HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion
Z = HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
READING ENVIRONMENT VARIABLES: Source for 64-bit process Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
%ProgramFiles% : X\ProgramW6432Dir X\ProgramFilesDir (x86)
%ProgramFiles(x86)% : X\ProgramFilesDir (x86) X\ProgramFilesDir (x86)
%ProgramW6432% : X\ProgramW6432Dir X\ProgramW6432Dir
%CommonProgramFiles% : X\CommonW6432Dir X\CommonFilesDir (x86)
%CommonProgramFiles(x86)% : X\CommonFilesDir (x86) X\CommonFilesDir (x86)
%CommonProgramW6432% : X\CommonW6432Dir X\CommonW6432Dir
%ProgramData% : Z\ProgramData Z\ProgramData
READING REGISTRY VALUES: Source for 64-bit process Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
X\ProgramFilesDir : X\ProgramFilesDir Y\ProgramFilesDir
X\ProgramFilesDir (x86) : X\ProgramFilesDir (x86) Y\ProgramFilesDir (x86)
X\ProgramFilesPath : X\ProgramFilesPath = %ProgramFiles% Y\ProgramFilesPath = %ProgramFiles(x86)%
X\ProgramW6432Dir : X\ProgramW6432Dir Y\ProgramW6432Dir
X\CommonFilesDir : X\CommonFilesDir Y\CommonFilesDir
X\CommonFilesDir (x86) : X\CommonFilesDir (x86) Y\CommonFilesDir (x86)
X\CommonW6432Dir : X\CommonW6432Dir Y\CommonW6432Dir
So for example, for a 32-bit process, the source of the data for the %ProgramFiles%
and %ProgramFiles(x86)%
environment variables is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
.
However, for a 64-bit process, the source of the data for the %ProgramFiles%
environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir
...and the source of the data for the %ProgramFiles(x86)%
environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
Most default Windows installation put a string like C:\Program Files (x86)
into the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
but this (and others) can be changed.
Whatever is entered into these Windows Registry values will be read by Windows Explorer into respective Environment Variables upon login and then copied to any child process that it subsequently spawns.
The registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesPath
is especially noteworthy because most Windows installations put the string %ProgramFiles%
into it, to be read by 64-bit processes. This string refers to the environment variable %ProgramFiles%
which in turn, takes its data from the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir
...unless some program changes the value of this environment variable apriori.
I have written a small utility, which displays these environment variables for 64-bit and 32-bit processes. You can download it here.
The source code for VisualStudio 2017 is included and the compiled 64-bit and 32-bit binary executables are in the directories ..\x64\Release
and ..\x86\Release
, respectively.
This uses twitter bootstrap 3.x with one css class to get labels to sit on top of the inputs. Here's a fiddle link, make sure to expand results panel wide enough to see effect.
HTML:
<div class="row myform">
<div class="col-md-12">
<form name="myform" role="form" novalidate>
<div class="form-group">
<label class="control-label" for="fullName">Address Line</label>
<input required type="text" name="addr" id="addr" class="form-control" placeholder="Address"/>
</div>
<div class="form-inline">
<div class="form-group">
<label>State</label>
<input required type="text" name="state" id="state" class="form-control" placeholder="State"/>
</div>
<div class="form-group">
<label>ZIP</label>
<input required type="text" name="zip" id="zip" class="form-control" placeholder="Zip"/>
</div>
</div>
<div class="form-group">
<label class="control-label" for="country">Country</label>
<input required type="text" name="country" id="country" class="form-control" placeholder="country"/>
</div>
</form>
</div>
</div>
CSS:
.myform input.form-control {
display: block; /* allows labels to sit on input when inline */
margin-bottom: 15px; /* gives padding to bottom of inline inputs */
}
You can also "prepend" the environment variable setting by using 'environment' command:
run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }
In Python function are first class citezens, so you can just assign it to a property like any other value. Here we are assigning the method of A
's hello to a property on B
. After __init__
, hello will be attached to B as self.hello
, which is actually a reference to A's hello:
class A:
def hello(self, msg):
print(f"Hello {msg}")
class B:
hello = A.hello
print(A.hello)
print(B.hello)
b = B()
b.hello("good looking!")
Prints:
<function A.hello at 0x7fcce55b9e50>
<function A.hello at 0x7fcce55b9e50>
Hello good looking!
Use WebRequest. From Scott Hanselman:
public static string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Proxy = new System.Net.WebProxy(ProxyString, true);
//Add these, as we're doing a POST
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
//We need to count how many bytes we're sending.
//Post'ed Faked Forms should be name=value&
byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream ();
os.Write (bytes, 0, bytes.Length); //Push it out there
os.Close ();
System.Net.WebResponse resp = req.GetResponse();
if (resp== null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
you do not need to know pts number, just type:
ps all | grep bash
then:
kill pid1 pid2 pid3 ...
A saw a different post that also had diacritical marks, which is great
s.replace(/[^a-zA-Z0-9À-ž\s]/g, "")
This error occurs when you compile a java program using classes that support the Servlet API. The compiler searches for the library (included in a .jar file) by using the CLASSPATH. You can specify this when you compile using -classpath
or -cp
options as noted in other responses, but you should set up your environment to define the classpath as needed.
Set the CLASSPATH environment variable to reference the location of servlet-api.jar
, which depends on your setup (OS, how you installed, etc.)
Assuming you're using Tomcat and have installed it in one of 20 possible ways, the APIs used by servlets will be installed on your system, relative to wherever Tomcat is installed. For historical reasons, Tomcat is also known as "Catalina", so you can use the command "catalina" to run certain commands, and alone, it will report, amongst other things the CATALINA_BASE
. For example on my Mac using Tomcat installed using homebrew it's
Using CATALINA_BASE: /usr/local/Cellar/tomcat/8.5.9/libexec
The location of the Tomcat servlet libraries is under this in the lib
directory.
Set CATALINA_BASE, then set CLASSPATH using the base as a start, for example for Linux or OSX you might set this in .profile
, or .bash_profile
like so:
export CATALINA_BASE=/usr/local/Cellar/tomcat/8.5.9/libexec
export CLASSPATH=$CATALINA_BASE/lib/servlet-api.jar:$CLASSPATH
Exit the terminal/shell and come back in to run the profile. You should be able to see that the variable is set by using the echo
command, e.g.
echo $CLASSPATH
or in Windows
echo %CLASSPATH%
If it displays the full path to the jar `javac WebTest.java' compile your class.
Other answers are correct -- set up your IDE (Eclipse, IntelliJ) to know about Tomcat or build with Maven and you'll save pain.
They are identical according to sizeof()
In the absence of any reason to worry about "faster", always optimize for the human. Which makes more sense to the human reader?
You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress (also Enter key, backspace key, alter key ,control key)
<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>
Create a new Virtual machine in Virtual box, Select OS type Other and version Other/Unknown
On the Virtual Hard Disk screen, select "Use existing hard disk" and enter the path to the VMDK file.
It should boot your Chrome OS just fine.... BTW Chrome OS goes from VBOX bios screen to login in 7 seconds on my system!!!
Here is a working example with Angular version 2.3. Just call the constructor of the service the stand way like this constructor(private _userService:UserService) . And it will create a singleton for the app.
user.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { Subject } from 'rxjs/Subject';
import { User } from '../object/user';
@Injectable()
export class UserService {
private userChangedSource;
public observableEvents;
loggedUser:User;
constructor() {
this.userChangedSource = new Subject<any>();
this.observableEvents = this.userChangedSource.asObservable();
}
userLoggedIn(user:User) {
this.loggedUser = user;
this.userChangedSource.next(user);
}
...
}
app.component.ts
import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { UserService } from '../service/user.service';
import { User } from '../object/user';
@Component({
selector: 'myApp',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
loggedUser:User;
constructor(private _userService:UserService) {
this._userService.observableEvents.subscribe(user => {
this.loggedUser = user;
console.log("event triggered");
});
}
...
}
Use the XML Tools plugin for Notepad++ and then you can Auto-Indent the code with Ctrl+Alt+Shift+B .For the more point-and-click inclined, you could also go to Plugins --> XML Tools --> Pretty Print.
Basically, if you are not handling the exception in the same place as you are throwing it, then you can use "throws exception" at the definition of the function.
There's little need to set all the variables you're setting. CMake sets them to reasonable defaults. You should definitely not modify CMAKE_BINARY_DIR
or CMAKE_CACHEFILE_DIR
. Treat these as read-only.
First remove the existing problematic cache file from the src directory:
cd src
rm CMakeCache.txt
cd ..
Then remove all the set()
commands and do:
cd Compile && rm -rf *
cmake ../src
As long as you're outside of the source directory when running CMake, it will not modify the source directory unless your CMakeList explicitly tells it to do so.
Once you have this working, you can look at where CMake puts things by default, and only if you're not satisfied with the default locations (such as the default value of EXECUTABLE_OUTPUT_PATH
), modify only those you need. And try to express them relative to CMAKE_BINARY_DIR
, CMAKE_CURRENT_BINARY_DIR
, PROJECT_BINARY_DIR
etc.
If you look at CMake documentation, you'll see variables partitioned into semantic sections. Except for very special circumstances, you should treat all those listed under "Variables that Provide Information" as read-only inside CMakeLists.
Adding style="width:100%;max-width:640px"
to the image tag will scale it up to the viewport width, i.e. for larger windows it will look fixed width.
I am trying to get recursion too.
I found a way i think,
i think of it like a chain of steps(the step isnt constant it may change depending on the previous node)
I have to figure out 2 things:
example
factorial
1,2,6,24,120 ......... or
1,2*(1),3*(2*1),4*(3*2*1,5*(4*3*2*1)
step=multiple by last node
after the step what i need to get to the next node,abstract 1
ok
function =
n*f(n-1)
its 2 steps process
from a-->to step--->b
i hoped this help,just think about 2 thniks,not how to get from node to node,but node-->step-->node
node-->step is the body of the function step-->node is the arguments of the other function
bye:) hope i helped
If you have a 64-bit OS, instead of i686, you have x86_64
or ia64
in the output of uname -a
. In that you do not have any of these two strings; you have a 32-bit OS (note that this does not mean that your CPU is not 64-bit).
It may look cleaner using a key instead a cmp:
newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])
or as J.F.Sebastian and others suggested,
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
For completeness (as pointed out in comments by fitzgeraldsteele), add reverse=True
to sort descending
newlist = sorted(l, key=itemgetter('name'), reverse=True)
Here is the most concise solution so far:
function isArrayOfStrings(value: any): boolean {
return Array.isArray(value) && value.every(item => typeof item === "string");
}
Note that value.every
will return true
for an empty array. If you need to return false
for an empty array, you should add value.length
to the condition clause:
function isNonEmptyArrayOfStrings(value: any): boolean {
return Array.isArray(value) && value.length && value.every(item => typeof item === "string");
}
There is no any run-time type information in TypeScript (and there won't be, see TypeScript Design Goals > Non goals, 5), so there is no way to get the type of an empty array. For a non-empty array all you can do is to check the type of its items, one by one.
var a = { b: { c: 9 } };
function value(layer, path, value) {
var i = 0,
path = path.split('.');
for (; i < path.length; i++)
if (value != null && i + 1 === path.length)
layer[path[i]] = value;
layer = layer[path[i]];
return layer;
};
value(a, 'b.c'); // 9
value(a, 'b.c', 4);
value(a, 'b.c'); // 4
This is a lot of code when compared to the much simpler eval
way of doing it, but like Simon Willison says, you should never use eval.
Also, JSFiddle.
I found the solution.
As said in the EDIT of my answer, a <div>
is misfunctioning in a <table>
.
So I wrote this code instead :
<tr id="hidden" style="display:none;">
<td class="depot_table_left">
<label for="sexe">Sexe</label>
</td>
<td>
<select type="text" name="sexe">
<option value="1">Sexe</option>
<option value="2">Joueur</option>
<option value="3">Joueuse</option>
</select>
</td>
</tr>
And this is working fine.
Thanks everybody ;)
"/tmp/mysql.sock" will be created automatically when you start the MySQL server. So remember to do that before starting the rails server.
I know this thread is too old but recently I was wondering how to delete eclipse
app on my MacBook Pro
running macOS High Sierra
.
Bellow are the steps which I followed to delete it from my system. Added screenshots for more clear understanding.
Open the eclipse app and it will show an app icon in dock. If it is not already present in dock then please try to run the app from Spotlight Search
by pressing ?
+ space
.
Now right click on that eclipse logo from dock and click Show in Finder
under Options
.
eclipse
app in an external finder window.eclipse
) by pressing ?
+ delete
.Trash
as well if you are removing it from system completely.Thanks. Hope this helped.
Facebook built something called Augmented Traffic Control. A brief summary from their GitHub page:
Augmented Traffic Control (ATC) is a tool to simulate network conditions. It allows controlling the connection that a device has to the internet. Developers can use ATC to test their application across varying network conditions, easily emulating high speed, mobile, and even severely impaired networks. Aspects of the connection that can be controlled include:
- bandwidth
- latency
- packet loss
- corrupted packets
- packets ordering
In order to be able to shape the network traffic, ATC must be running on a device that routes the traffic and sees the real IP address of the device, like your network gateway for instance. This also allows any devices that route through ATC to be able to shape their traffic. Traffic can be shaped/unshaped using a web interface allowing any devices with a web browser to use ATC without the need for a client application.
You can find it here on GitHub: https://github.com/facebook/augmented-traffic-control
They have also written a blog post about it: https://code.facebook.com/posts/1561127100804165/augmented-traffic-control-a-tool-to-simulate-network-conditions/
Actually this is not really the same to import a variable with:
from file1 import x1
print(x1)
and
import file1
print(file1.x1)
Altough at import time x1 and file1.x1 have the same value, they are not the same variables. For instance, call a function in file1 that modifies x1 and then try to print the variable from the main file: you will not see the modified value.
Sounds like you're overextending regex for this purpose. What I would do is use a regex to match a few date formats and then use a separate function to validate the values of the date fields so extracted.
to set RichTextBox text:
richTextBox1.Document.Blocks.Clear();
richTextBox1.Document.Blocks.Add(new Paragraph(new Run("Text")));
to get RichTextBox text:
string richText = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
For java 1.5 or greater:
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>
For java 1.4:
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>
For java 1.3:
java -Xnoagent -Djava.compiler=NONE -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 <YourAppName>
Here is output from a simple program:
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 HelloWhirled
Listening for transport dt_socket at address: 1044
Hello whirled
I have a 2010 iMac with 8GB of RAM, running Eclipse Neon.2 Release (4.6.2) with Java 1.8.0_25. With the VM argument -Xmx6g, I ran the following code:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
try {
sb.append('a');
} catch (Throwable e) {
System.out.println(i);
break;
}
}
System.out.println(sb.toString().length());
This prints:
Requested array size exceeds VM limit
1207959550
So, it seems that the max array size is ~1,207,959,549. Then I realized that we don't actually care if Java runs out of memory: we're just looking for the maximum array size (which seems to be a constant defined somewhere). So:
for (int i = 0; i < 1_000; i++) {
try {
char[] array = new char[Integer.MAX_VALUE - i];
Arrays.fill(array, 'a');
String string = new String(array);
System.out.println(string.length());
} catch (Throwable e) {
System.out.println(e.getMessage());
System.out.println("Last: " + (Integer.MAX_VALUE - i));
System.out.println("Last: " + i);
}
}
Which prints:
Requested array size exceeds VM limit
Last: 2147483647
Last: 0
Requested array size exceeds VM limit
Last: 2147483646
Last: 1
Java heap space
Last: 2147483645
Last: 2
So, it seems the max is Integer.MAX_VALUE - 2, or (2^31) - 3
P.S. I'm not sure why my StringBuilder
maxed out at 1207959550
while my char[]
maxed out at (2^31)-3. It seems that AbstractStringBuilder
doubles the size of its internal char[]
to grow it, so that probably causes the issue.
in this scenario:
DELETE FROM tableA
WHERE (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
aren't you missing the column you want to compare to? example:
DELETE FROM tableA
WHERE entitynum in (SELECT q.entitynum
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date'));
I assume it's that column since in your select statement you're selecting from the same table you're wanting to delete from with that column.
Assuming it's a server control, you can use Request["ButtonName"]
To see if a specific button was clicked: if (Request["ButtonName"] != null)
Since nobody's posted the naughty back door way yet:
public int getLength(String arg) {
Field count = String.class.getDeclaredField("count");
count.setAccessible(true); //may throw security exception in "real" environment
return count.getInt(arg);
}
;)
String to wstring
std::wstring Str2Wstr(const std::string& str)
{
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);
std::wstring wstrTo(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
}
wstring to String
std::string Wstr2Str(const std::wstring& wstr)
{
typedef std::codecvt_utf8<wchar_t> convert_typeX;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
If you need the index in the forEach then this provides a way.
public class IndexedValue {
private final int index;
private final Object value;
public IndexedValue(final int index, final Object value) {
this.index = index;
this.value = value;
}
public int getIndex() {
return index;
}
public Object getValue() {
return value;
}
}
Then use it as follows.
@Test
public void withIndex() {
final List<String> list = Arrays.asList("a", "b");
IntStream.range(0, list.size())
.mapToObj(index -> new IndexedValue(index, list.get(index)))
.forEach(indexValue -> {
System.out.println(String.format("%d, %s",
indexValue.getIndex(),
indexValue.getValue().toString()));
});
}
For apscheduler
< 3.0, see Unknown's answer.
For apscheduler
> 3.0
from apscheduler.schedulers.blocking import BlockingScheduler
sched = BlockingScheduler()
@sched.scheduled_job('interval', seconds=10)
def timed_job():
print('This job is run every 10 seconds.')
@sched.scheduled_job('cron', day_of_week='mon-fri', hour=10)
def scheduled_job():
print('This job is run every weekday at 10am.')
sched.configure(options_from_ini_file)
sched.start()
apscheduler
documentation.
This for apscheduler-3.3.1
on Python 3.6.2
.
"""
Following configurations are set for the scheduler:
- a MongoDBJobStore named “mongo”
- an SQLAlchemyJobStore named “default” (using SQLite)
- a ThreadPoolExecutor named “default”, with a worker count of 20
- a ProcessPoolExecutor named “processpool”, with a worker count of 5
- UTC as the scheduler’s timezone
- coalescing turned off for new jobs by default
- a default maximum instance limit of 3 for new jobs
"""
from pytz import utc
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ProcessPoolExecutor
"""
Method 1:
"""
jobstores = {
'mongo': {'type': 'mongodb'},
'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors = {
'default': {'type': 'threadpool', 'max_workers': 20},
'processpool': ProcessPoolExecutor(max_workers=5)
}
job_defaults = {
'coalesce': False,
'max_instances': 3
}
"""
Method 2 (ini format):
"""
gconfig = {
'apscheduler.jobstores.mongo': {
'type': 'mongodb'
},
'apscheduler.jobstores.default': {
'type': 'sqlalchemy',
'url': 'sqlite:///jobs.sqlite'
},
'apscheduler.executors.default': {
'class': 'apscheduler.executors.pool:ThreadPoolExecutor',
'max_workers': '20'
},
'apscheduler.executors.processpool': {
'type': 'processpool',
'max_workers': '5'
},
'apscheduler.job_defaults.coalesce': 'false',
'apscheduler.job_defaults.max_instances': '3',
'apscheduler.timezone': 'UTC',
}
sched_method1 = BlockingScheduler() # uses overrides from Method1
sched_method2 = BlockingScheduler() # uses same overrides from Method2 but in an ini format
@sched_method1.scheduled_job('interval', seconds=10)
def timed_job():
print('This job is run every 10 seconds.')
@sched_method2.scheduled_job('cron', day_of_week='mon-fri', hour=10)
def scheduled_job():
print('This job is run every weekday at 10am.')
sched_method1.configure(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=utc)
sched_method1.start()
sched_method2.configure(gconfig=gconfig)
sched_method2.start()
INSERT INTO table_name1 (id, name, address, contact_number) SELECT id, name, address, contact_number FROM table_name2;
I have used Eloff's answer successfully for Python 3.1 [many thanks!].
I upgraded to Python 3.2.3, and ran into errors.
The solution, provided here thanks to the responder Thomas K, is to insert super().__init__()
into the following code:
def __init__(self):
self.reset()
self.fed = []
... in order to make it look like this:
def __init__(self):
super().__init__()
self.reset()
self.fed = []
... and it will work for Python 3.2.3.
Again, thanks to Thomas K for the fix and for Eloff's original code provided above!
it is too late I know, howewer there is no succesfully answer. I found the answer from another website. I fixed the issue when I delete the System.Runtime assemblydependency. I deleted this.
<dependentAssembly>
<assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/>
</dependentAssembly>
Best Regards
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}]
};
var returnedData = $.grep(data.items, function (element, index) {
return element.id == 1;
});
alert(returnedData[0].id + " " + returnedData[0].category);
The returnedData is returning an array of objects, so you can access it by array index.
I faced the same problem in Derby IBM DB2 embedded database in a java desktop application, and after a day of searching I finally found how it's done :
SELECT days (table1.datecolomn) - days (current date) FROM table1 WHERE days (table1.datecolomn) - days (current date) > 5
for more information check this site
For MariaDB, use modify column:
ALTER TABLE table_name MODIFY COLUMN column_name VARCHAR (500);
It will work.
I found this question because I wanted to generate a web page with links to all the websites running on my IIS instance. I used Alexander Shapkin's answer to come up with the following to generate a bunch of links.
$hostname = "localhost"
Foreach ($Site in get-website) {
Foreach ($Bind in $Site.bindings.collection) {
$data = [PSCustomObject]@{
name=$Site.name;
Protocol=$Bind.Protocol;
Bindings=$Bind.BindingInformation
}
$data.Bindings = $data.Bindings -replace '(:$)', ''
$html = "<a href=""" + $data.Protocol + "://" + $data.Bindings + """>" + $data.name + "</a>"
$html.Replace("*", $hostname);
}
}
Then I paste the results into this hastily written HTML:
<html>
<style>
a { display: block; }
</style>
{paste PowerShell results here}
</body>
</html>
What you want can be achieved by modifying the hosts file through Fiddler 2 application.
Follow these steps:
Install Fiddler2
Navigate to Fiddler2 menu:- Tools > HOSTS.. (Click to select)
Add a line like this:-
localhost:8080 www.mydomainname.com
Save the file & then checkout
www.mydomainname.com
in browser.
Everyone else's solution has one drawback or another.
find -type d -readable -exec sh -c 'printf "%s " "$1"; ls -1UA "$1" | wc -l' sh {} ';'
Explanation:
-type d
: we're interested in directories.-readable
: We only want them if it's possible to list the files in them. Note that find
will still emit an error when it tries to search for more directories in them, but this prevents calling -exec
for them.-exec sh -c BLAH sh {} ';'
: for each directory, run this script fragment, with $0
set to sh
and $1
set to the filename.printf "%s " "$1"
: portably and minimally print the directory name, followed by only a space, not a newline.ls -1UA
: list the files, one per line, in directory order (to avoid stalling the pipe), excluding only the special directories .
and ..
wc -l
: count the linesFor beginners: To create your .bash_profile
file in your home directory on MacOS, run:
nano ~/.bash_profile
Then you can paste in the following:
https://gist.github.com/mocon/0baf15e62163a07cb957888559d1b054
As you can see, it includes some example aliases and an environment variable at the bottom.
One you're done making your changes, follow the instructions at the bottom of the Nano editor window to WriteOut (Ctrl-O
) and Exit (Ctrl-X
). Then quit your Terminal and reopen it, and you will be able to use your newly defined aliases and environment variables.
This has changed for android 4.4.2. .. you should look in the repository file and download https://dl-ssl.google.com/android/repository/repository-10.xml
In manual install dir structure should look like
Now you have to..
At this point you should have a working android installation.
substr(i,j)
means that you start from the index i
(assuming the first index to be 0) and take next j
chars.
It does not mean going up to the index j
.
Use the Config class:
Config::set('site_settings', $site_settings);
Config::get('site_settings');
http://laravel.com/docs/4.2/configuration
Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests.
The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:
public class child : parent {
public child(int i) : base(i) {
Console.WriteLine("child");
}
}
You can check whether $items is actually an array and whether it contains any items:
if(is_array($items) && count($items) > 0)
{
foreach($items as $item) { }
}
It's not pretty and it's not fast, but it works, it's a one-liner and it's LINQy:
List<string> a = text.Select((c, i) => new { Char = c, Index = i }).GroupBy(o => o.Index / 4).Select(g => new String(g.Select(o => o.Char).ToArray())).ToList();
I faced similar issue and changing defaultConnectionFactory to be SqlConnectionFactory helped me solve it.
Set return type to Void
instead of void
and return null
// Modify existing method
public static Void displayInt(Integer i) {
System.out.println(i);
return null;
}
OR
// Or use Lambda
myForEach(theList, i -> {System.out.println(i);return null;});
try this in playground
var str:String = "Hello, playground"
let range = Range(start:advance(str.startIndex,1), end: advance(str.startIndex,8))
it will give you "ello, p"
However where this gets really interesting is that if you make the last index bigger than the string in playground it will show any strings that you defined after str :o
Range() appears to be a generic function so that it needs to know the type it is dealing with.
You also have to give it the actual string your interested in playgrounds as it seems to hold all stings in a sequence one after another with their variable name afterwards.
So
var str:String = "Hello, playground"
var str2:String = "I'm the next string"
let range = Range(start:advance(str.startIndex,1), end: advance(str.startIndex,49))
gives "ello, playground?str???I'm the next string?str2?"
works even if str2 is defined with a let
:)
>>> from dis import dis
>>> dis(compile('not 10 == 20', '', 'exec'))
1 0 LOAD_CONST 0 (10)
3 LOAD_CONST 1 (20)
6 COMPARE_OP 2 (==)
9 UNARY_NOT
10 POP_TOP
11 LOAD_CONST 2 (None)
14 RETURN_VALUE
>>> dis(compile('10 != 20', '', 'exec'))
1 0 LOAD_CONST 0 (10)
3 LOAD_CONST 1 (20)
6 COMPARE_OP 3 (!=)
9 POP_TOP
10 LOAD_CONST 2 (None)
13 RETURN_VALUE
Here you can see that not x == y
has one more instruction than x != y
. So the performance difference will be very small in most cases unless you are doing millions of comparisons and even then this will likely not be the cause of a bottleneck.
As of v1.8.8 there is also the option USE_MDFILE_AS_MAINPAGE
. So make sure to add your index file, e.g. README.md, to INPUT
and set it as this option's value:
INPUT += README.md
USE_MDFILE_AS_MAINPAGE = README.md
Make sure your antivirus program isn't interfering and be sure to add an exclusion to your firewall.
The best and easy way for image resize using Java Swing is:
jLabel.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass().getResource("/res/image.png")).getImage().getScaledInstance(200, 50, Image.SCALE_SMOOTH)));
For better display, identify the actual height & width of image and resize based on width/height percentage
I've generally used xml drawables to create shadow/elevation on a pre-lollipop widget. Here, for example, is an xml drawable that can be used on pre-lollipop devices to simulate the floating action button's elevation.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:top="8px">
<layer-list>
<item>
<shape android:shape="oval">
<solid android:color="#08000000"/>
<padding
android:bottom="3px"
android:left="3px"
android:right="3px"
android:top="3px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#09000000"/>
<padding
android:bottom="2px"
android:left="2px"
android:right="2px"
android:top="2px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#10000000"/>
<padding
android:bottom="2px"
android:left="2px"
android:right="2px"
android:top="2px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#11000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#12000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#13000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#14000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#15000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#16000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
<item>
<shape android:shape="oval">
<solid android:color="#17000000"/>
<padding
android:bottom="1px"
android:left="1px"
android:right="1px"
android:top="1px"
/>
</shape>
</item>
</layer-list>
</item>
<item>
<shape android:shape="oval">
<solid android:color="?attr/colorPrimary"/>
</shape>
</item>
</layer-list>
In place of ?attr/colorPrimary
you can choose any color. Here's a screenshot of the result:
The modern way (as of 2020) to add entries to a multimap (a map of lists) in Java is:
map.computeIfAbsent("apple", k -> new ArrayList<>()).add(2);
map.computeIfAbsent("apple", k -> new ArrayList<>()).add(3);
According to Map.computeIfAbsent
docs:
If the specified key is not already associated with a value (or is mapped to
null
), attempts to compute its value using the given mapping function and enters it into this map unlessnull
.Returns:
the current (existing or computed) value associated with the specified key, or null if the computed value is null
The most idiomatic way to iterate a map of lists is using Map.forEach
and Iterable.forEach
:
map.forEach((k, l) -> l.forEach(v -> /* use k and v here */));
Or, as shown in other answers, a traditional for
loop:
for (Map.Entry<String, List<Integer>> e : map.entrySet()) {
String k = e.getKey();
for (Integer v : e.getValue()) {
/* use k and v here */
}
}
You could also just use regular expressions to accomplish a slightly simpler job if this is enough for you (e.g. as seen in [1]).
They are build in into javascript so you can use them without any libraries.
function isValidDate(dateString) {
var regEx = /^\d{4}-\d{2}-\d{2}$/;
return dateString.match(regEx) != null;
}
would be a function to check if the given string is four numbers - two numbers - two numbers (almost yyyy-mm-dd). But you can do even more with more complex expressions, e.g. check [2].
isValidDate("23-03-2012") // false
isValidDate("1987-12-24") // true
isValidDate("22-03-1981") // false
isValidDate("0000-00-00") // true
According to reactjs.org, componentWillMount will not be supported in the future. https://reactjs.org/docs/react-component.html#unsafe_componentwillmount
There is no need to use componentWillMount.
If you want to do something before the component mounted, just do it in the constructor().
If you want to do network requests, do not do it in componentWillMount. It is because doing this will lead to unexpected bugs.
Network requests can be done in componentDidMount.
Hope it helps.
updated on 08/03/2019
The reason why you ask for componentWillMount is probably because you want to initialize the state before renders.
Just do it in useState.
const helloWorld=()=>{
const [value,setValue]=useState(0) //initialize your state here
return <p>{value}</p>
}
export default helloWorld;
or maybe You want to run a function in componentWillMount, for example, if your original code looks like this:
componentWillMount(){
console.log('componentWillMount')
}
with hook, all you need to do is to remove the lifecycle method:
const hookComponent=()=>{
console.log('componentWillMount')
return <p>you have transfered componeWillMount from class component into hook </p>
}
I just want to add something to the first answer about useEffect.
useEffect(()=>{})
useEffect runs on every render, it is a combination of componentDidUpdate, componentDidMount and ComponentWillUnmount.
useEffect(()=>{},[])
If we add an empty array in useEffect it runs just when the component mounted. It is because useEffect will compare the array you passed to it. So it does not have to be an empty array.It can be array that is not changing. For example, it can be [1,2,3] or ['1,2']. useEffect still only runs when component mounted.
It depends on you whether you want it to run just once or runs after every render. It is not dangerous if you forgot to add an array as long as you know what you are doing.
I created a sample for hook. Please check it out.
https://codesandbox.io/s/kw6xj153wr
updated on 21/08/2019
It has been a while since I wrote the above answer. There is something that I think you need to pay attention to. When you use
useEffect(()=>{},[])
When react compares the values you passed to the array [], it uses Object.is()
to compare.
If you pass an object to it, such as
useEffect(()=>{},[{name:'Tom'}])
This is exactly the same as:
useEffect(()=>{})
It will re-render every time because when Object.is()
compares an object, it compares its reference, not the value itself. It is the same as why {}==={} returns false because their references are different.
If you still want to compare the object itself not the reference, you can do something like this:
useEffect(()=>{},[JSON.stringify({name:'Tom'})])
you should run standlone.bat or .sh with -c standalone-full.xml switch may be work.
I always return multiple values by using a combination of list()
and array()
s:
function DecideStuffToReturn() {
$IsValid = true;
$AnswerToLife = 42;
// Build the return array.
return array($IsValid, $AnswerToLife);
}
// Part out the return array in to multiple variables.
list($IsValid, $AnswerToLife) = DecideStuffToReturn();
You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.
See list()
for more information.
If you dont want to hard-code the cell addresses you can use the ROW()
function.
eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))
Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.
As suggested you can change the pivot table content and paste as values.
But if you want to change the values dynamically the easiest way I found is
Go To Insert->create pivot table
Now in the dialog box in the input data field select the cells of your previous pivot table.
I've seen
anEvent.isPopupTrigger()
be used before. I'm fairly new to Java so I'm happy to hear thoughts about this approach :)
Add: Architectures: $(ARCHS_STANDARD_INCLUDING_64_BIT)
Valid architectures: arm64 armv7 armv7s
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
I experienced this error yesterday. Took me a while to realise that the main
entry in package.json
was pointing to a file that I'd moved. Once I updated that the error disappeared and the package worked.
I've came through a case recently where I've needed check value of checkbox when user clicked on button. The only proper way to do so is to use prop()
attribute.
var ansValue = $("#ans").prop('checked') ? $("#ans").val() : 0;
this worked in my case maybe someone will need it.
When I've tried .attr(':checked')
it returned checked
but I wanted boolean value and .val()
returned value of attribute value
.
Ok here is my version of doing this. I noticed that you want your output to be 7
, which means you dont want to count special characters and numbers. So here is regex pattern:
re.findall("[a-zA-Z_]+", string)
Where [a-zA-Z_]
means it will match any character beetwen a-z
(lowercase) and A-Z
(upper case).
About spaces. If you want to remove all extra spaces, just do:
string = string.rstrip().lstrip() # Remove all extra spaces at the start and at the end of the string
while " " in string: # While there are 2 spaces beetwen words in our string...
string = string.replace(" ", " ") # ... replace them by one space!
This one will be working in python 3
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
@abstractmethod
def foo(self):
pass
Abstract()
>>> TypeError: Can not instantiate abstract class Abstract with abstract methods foo
My solution is basically the same as dickoa's but a little easier to interpret:
data(mtcars)
n = nrow(mtcars)
trainIndex = sample(1:n, size = round(0.7*n), replace=FALSE)
train = mtcars[trainIndex ,]
test = mtcars[-trainIndex ,]
If you mean, you want to scroll through multiple items in your stackpanel, try putting a grid around it. By definition, a stackpanel has infinite length.
So try something like this:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel Width="311">
<TextBlock Text="{Binding A}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" FontSize="28" />
<TextBlock Text="{Binding B}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</Grid>
You could even make this work with a ScrollViewer
Press Ctl+T
will open a search box. Delete # symbol and enter your file name.
There is also an .isInstance
method on the "Class
" class. if you get an object's class via myBanana.getClass()
you can see if your object myApple
is an instance of the same class as myBanana
via
myBanana.getClass().isInstance(myApple)
When you extract a single row from a data frame you get a one-row data frame. Convert it to a numeric vector:
as.numeric(df[1,])
As @Roland suggests, unlist(df[1,])
will convert the one-row data frame to a numeric vector without dropping the names. Therefore unname(unlist(df[1,]))
is another, slightly more explicit way to get to the same result.
As @Josh comments below, if you have a not-completely-numeric (alphabetic, factor, mixed ...) data frame, you need as.character(df[1,])
instead.
To meet these criteria: modify original list in situ, no list copies, only one pass, works, a traditional solution is to iterate backwards:
for i in xrange(len(somelist) - 1, -1, -1):
element = somelist[i]
do_action(element)
if check(element):
del somelist[i]
Bonus: Doesn't do len(somelist)
on each iteration. Works on any version of Python (at least as far back as 1.5.2) ... s/xrange/range/ for 3.X.
Update: If you want to iterate forwards, it's possible, just trickier and uglier:
i = 0
n = len(somelist)
while i < n:
element = somelist[i]
do_action(element)
if check(element):
del somelist[i]
n = n - 1
else:
i = i + 1
# will get you the current local (session based) state.
SHOW Variables WHERE Variable_name='foreign_key_checks';
If you didn't SET GLOBAL, only your session was affected.
<!DOCTYPE html>
<html>
<title>Welcome</title>
<style type="text/css">
.head1 {
width:300px;
border-right:1px solid #333;
float:left;
height:500px;
}
.head2 {
float:left;
padding-left:100PX;
padding-top:10PX;
}
</style>
<body>
<h1 class="head1">Ramya</h1>
<h2 class="head2">Reddy</h2>
</body>
</html>
I have hosted an open-source project to enable Android phone to IP camera:
http://code.google.com/p/ipcamera-for-android
Raw video data is fetched from LocalSocket, and the MDAT MOOV of MP4 was checked first before streaming. The live video is packed in FLV format, and can be played via Flash video player with a build in web server :)
Please try this command node --version or node -v, either of which should return something like v4.4.5
.
Use nchar
if vector of strings is called x
(nchar(x) - nchar(gsub(' ','',x))) + 1
Find out number of spaces then add one
I've adopted Crazy Yoghurt's answer to swift's extensions.
extension UILabel {
func boldRange(_ range: Range<String.Index>) {
if let text = self.attributedText {
let attr = NSMutableAttributedString(attributedString: text)
let start = text.string.characters.distance(from: text.string.startIndex, to: range.lowerBound)
let length = text.string.characters.distance(from: range.lowerBound, to: range.upperBound)
attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: self.font.pointSize)], range: NSMakeRange(start, length))
self.attributedText = attr
}
}
func boldSubstring(_ substr: String) {
if let text = self.attributedText {
var range = text.string.range(of: substr)
let attr = NSMutableAttributedString(attributedString: text)
while range != nil {
let start = text.string.characters.distance(from: text.string.startIndex, to: range!.lowerBound)
let length = text.string.characters.distance(from: range!.lowerBound, to: range!.upperBound)
var nsRange = NSMakeRange(start, length)
let font = attr.attribute(NSFontAttributeName, at: start, effectiveRange: &nsRange) as! UIFont
if !font.fontDescriptor.symbolicTraits.contains(.traitBold) {
break
}
range = text.string.range(of: substr, options: NSString.CompareOptions.literal, range: range!.upperBound..<text.string.endIndex, locale: nil)
}
if let r = range {
boldRange(r)
}
}
}
}
May be there is not good conversion between Range and NSRange, but I didn't found something better.
I like to do this dynamically depending on the number of options in the select; to hide the search for selects with 10 or fewer results, I do:
$fewResults = $("select>option:nth-child(11)").closest("select");
$fewResults.select2();
$('select').not($fewResults).select2({ minimumResultsForSearch : -1 });
Python doesn't have static variables but you can fake it by defining a callable class object and then using it as a function. Also see this answer.
class Foo(object):
# Class variable, shared by all instances of this class
counter = 0
def __call__(self):
Foo.counter += 1
print Foo.counter
# Create an object instance of class "Foo," called "foo"
foo = Foo()
# Make calls to the "__call__" method, via the object's name itself
foo() #prints 1
foo() #prints 2
foo() #prints 3
Note that __call__
makes an instance of a class (object) callable by its own name. That's why calling foo()
above calls the class' __call__
method. From the documentation:
Instances of arbitrary classes can be made callable by defining a
__call__()
method in their class.
new Date().toString();
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
Dateformatter can make it to any string you want
More understandable code from: https://en.cppreference.com/w/cpp/algorithm/unique
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cctype>
int main()
{
// remove duplicate elements
std::vector<int> v{1,2,3,1,2,3,3,4,5,4,5,6,7};
std::sort(v.begin(), v.end()); // 1 1 2 2 3 3 3 4 4 5 5 6 7
auto last = std::unique(v.begin(), v.end());
// v now holds {1 2 3 4 5 6 7 x x x x x x}, where 'x' is indeterminate
v.erase(last, v.end());
for (int i : v)
std::cout << i << " ";
std::cout << "\n";
}
ouput:
1 2 3 4 5 6 7
If you want to make address directly, the worksheet must exist.
Turning off automatic recalculation want help you :)
But... you can get value indirectly...
.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"
At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.
But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.
You can shorten the suggested code for this as well as generalize for unexpected errors. Here you go:
Public Function InCollection(col As Collection, key As String) As Boolean
On Error GoTo incol
col.Item key
incol:
InCollection = (Err.Number = 0)
End Function
This way Convert all Data From Filelds(Columns) In Table To Record (Row).
Declare @TableName [nvarchar](128)
Declare @ExecStr nvarchar(max)
Declare @Where nvarchar(max)
Set @TableName = 'myTableName'
--Enter Filtering If Exists
Set @Where = ''
--Set @ExecStr = N'Select * From '+quotename(@TableName)+@Where
--Exec(@ExecStr)
Drop Table If Exists #tmp_Col2Row
Create Table #tmp_Col2Row
(Field_Name nvarchar(128) Not Null
,Field_Value nvarchar(max) Null
)
Set @ExecStr = N' Insert Into #tmp_Col2Row (Field_Name , Field_Value) '
Select @ExecStr += (Select N'Select '''+C.name+''' ,Convert(nvarchar(max),'+quotename(C.name) + ') From ' + quotename(@TableName)+@Where+Char(10)+' Union All '
from sys.columns as C
where (C.object_id = object_id(@TableName))
for xml path(''))
Select @ExecStr = Left(@ExecStr,Len(@ExecStr)-Len(' Union All '))
--Print @ExecStr
Exec (@ExecStr)
Select * From #tmp_Col2Row
Go
I think the $emit
function works better for what I think you're asking for. It keeps your component separated from the Vue instance so that it is reusable in many contexts.
// Child component
<template>
<div id="app">
<test @click="$emit('test-click')"></test>
</div>
</template>
Use it in HTML
// Parent component
<test @test-click="testFunction">
HTML
<input [(ngModel)] = "searchTerm" (ngModelChange) = "search()"/>
<div *ngFor = "let item of items">{{item.name}}</div>
Component
search(): void {
let term = this.searchTerm;
this.items = this.itemsCopy.filter(function(tag) {
return tag.name.indexOf(term) >= 0;
});
}
Note that this.itemsCopy is equal to this.items and should be set before doing the search.
int
is predefined in library function c# but in java we can create object of Integer
When I accidentally switched to a guest wifi network I got this error. Had to switch back to my default wifi network.
select count(*) from dbo.tablename where address_line_1 LIKE '%[\'']%' {eSCAPE'\'}
Why not using exit codes? If a git repository exists in the current directory, then git branch
and git tag
commands return exit code of 0; otherwise, a non-zero exit code will be returned. This way, you can determine if a git repository exist or not. Simply, you can run:
git tag > /dev/null 2>&1 && [ $? -eq 0 ]
Advantage: Flexibe. It works for both bare and non-bare repositories, and in sh, zsh and bash.
git tag
: Getting tags of the repository to determine if exists or not.> /dev/null 2>&1
: Preventing from printing anything, including normal and error outputs.[ $? -eq 0 ]
: Check if the previous command returned with exit code 0 or not. As you may know, every non-zero exit means something bad happened. $?
gets the exit code of the previous command, and [
, -eq
and ]
perform the comparison.As an example, you can create a file named check-git-repo
with the following contents, make it executable and run it:
#!/bin/sh
if git tag > /dev/null 2>&1 && [ $? -eq 0 ]; then
echo "Repository exists!";
else
echo "No repository here.";
fi
Edit: (after the code change)
There is no way for us to tell you whether you need or not to call your parent's __init__
(or any other function). Inheritance obviously would work without such call. It all depends on the logic of your code: for example, if all your __init__
is done in parent class, you can just skip child-class __init__
altogether.
consider the following example:
>>> class A:
def __init__(self, val):
self.a = val
>>> class B(A):
pass
>>> class C(A):
def __init__(self, val):
A.__init__(self, val)
self.a += val
>>> A(4).a
4
>>> B(5).a
5
>>> C(6).a
12
With X installed (e.g. from homebrew, or Quartz), a simple "xterm &" does (nearly) the trick, it opens a new terminal window (not a tab, though).
Take a look at java.text.DateFormat. Easier to use (with a bit less power) is the derived class, java.text.SimpleDateFormat
And here is a good intro to Java internationalization: http://java.sun.com/docs/books/tutorial/i18n/index.html (the "Formatting" section addressing your problem, and more).
I found this to work quite well:
^\(*\+*[1-9]{0,3}\)*-*[1-9]{0,3}[-. /]*\(*[2-9]\d{2}\)*[-. /]*\d{3}[-. /]*\d{4} *e*x*t*\.* *\d{0,4}$
It works for these number formats:
1-234-567-8901
1-234-567-8901 x1234
1-234-567-8901 ext1234
1 (234) 567-8901
1.234.567.8901
1/234/567/8901
12345678901
1-234-567-8901 ext. 1234
(+351) 282 433 5050
Make sure to use global AND multiline flags to make sure.
I guess I found a simpler solution
temp1 = pd.melt(df1, id_vars=["location"], var_name='Date', value_name='Value')
temp2 = pd.melt(df1, id_vars=["name"], var_name='Date', value_name='Value')
Concat whole temp1
with temp2
's column name
temp1['new_column'] = temp2['name']
You now have what you asked for.
Making the "Copy Local" property True for the reference did it for me. Expand References, right-click on System.Net.Http and change the value of Copy Local property to True in the properties window. I'm using VS2019.
Apparently the new way to do it is detailed here:
http://aspnetwebstack.codeplex.com/discussions/350492
To quote Henrik,
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new ObjectContent<T>(T, myFormatter, "application/some-format");
So basically, one has to create a ObjectContent type, which apparently can be returned as an HttpContent object.
pip install pandas make sure, this is 'pandas' not 'panda'
If you are not able to access pip, then got to C:\Python37\Scripts and run pip.exe install pandas.
Alternatively, you can add C:\Python37\Scripts in the env variables for windows machines. Hope this helps.
Hint: break up the 32-bit integer to 4 8-bit integers, and print them out.
Something along the lines of this (not compiled, YMMV):
int i = 0xDEADBEEF; // some 32-bit integer
printf("%i.%i.%i.%i",
(i >> 24) & 0xFF,
(i >> 16) & 0xFF,
(i >> 8) & 0xFF,
i & 0xFF);
Try, Its working for me.
[[self.textField valueForKey:@"textInputTraits"] setValue:[UIColor redColor] strong textforKey:@"insertionPointColor"];
Ok, I've achieved the same thing using Bootstrap 3.0
Example with the latest bootstrap
The HTML:
<div class="header">
whatever
</div>
<div class="container-fluid wrapper">
<div class="row">
<div class="col-md-3 navigation"></div>
<div class="col-md-9 content"></div>
</div>
</div>
The SCSS:
html, body, .wrapper {
padding: 0;
margin: 0;
height: 100%;
}
$headerHeight: 43px;
.navigation, .content {
display: table-cell;
float: none;
vertical-align: top;
}
.wrapper {
display: table;
width: 100%;
margin-top: -$headerHeight;
padding-top: $headerHeight;
}
.header {
height: $headerHeight;
}
.row {
height: 100%;
margin: 0;
display: table-row;
&:before, &:after {
content: none;
}
}
.navigation {
background: #4a4d4e;
padding-left: 0;
padding-right: 0;
}
You can use this site: https://cachedviews.com/ . Cache View or Cached Pages of Any Website - Google Cached Pages of Any Website
I had success using .on() like so:
$('.leadtoscore').on('click', {event_type: 'shot'}, add_event);
Then inside the add_event
function you get access to 'shot' like this:
event.data.event_type
See the .on() documentation for more info, where they provide the following example:
function myHandler( event ) {
alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );
Here is my implementation in C#:
public static PointF PointOnCircle(float radius, float angleInDegrees, PointF origin)
{
// Convert from degrees to radians via multiplication by PI/180
float x = (float)(radius * Math.Cos(angleInDegrees * Math.PI / 180F)) + origin.X;
float y = (float)(radius * Math.Sin(angleInDegrees * Math.PI / 180F)) + origin.Y;
return new PointF(x, y);
}
Try this:
@echo off
setlocal
cd /d %~dp0
Call :UnZipFile "C:\Temp\" "c:\path\to\batch.zip"
exit /b
:UnZipFile <ExtractTo> <newzipfile>
set vbs="%temp%\_.vbs"
if exist %vbs% del /f /q %vbs%
>%vbs% echo Set fso = CreateObject("Scripting.FileSystemObject")
>>%vbs% echo If NOT fso.FolderExists(%1) Then
>>%vbs% echo fso.CreateFolder(%1)
>>%vbs% echo End If
>>%vbs% echo set objShell = CreateObject("Shell.Application")
>>%vbs% echo set FilesInZip=objShell.NameSpace(%2).items
>>%vbs% echo objShell.NameSpace(%1).CopyHere(FilesInZip)
>>%vbs% echo Set fso = Nothing
>>%vbs% echo Set objShell = Nothing
cscript //nologo %vbs%
if exist %vbs% del /f /q %vbs%
Revision
To have it perform the unzip on each zip file creating a folder for each use:
@echo off
setlocal
cd /d %~dp0
for %%a in (*.zip) do (
Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
)
exit /b
If you don't want it to create a folder for each zip, change
Call :UnZipFile "C:\Temp\%%~na\" "c:\path\to\%%~nxa"
to
Call :UnZipFile "C:\Temp\" "c:\path\to\%%~nxa"
Yes numpy has a size function, and shape and size are not quite the same.
Input
import numpy as np
data = [[1, 2, 3, 4], [5, 6, 7, 8]]
arrData = np.array(data)
print(data)
print(arrData.size)
print(arrData.shape)
Output
[[1, 2, 3, 4], [5, 6, 7, 8]]
8 # size
(2, 4) # shape
Not a regexp expert, but I think you could use a negative lookahead from the start, e.g. ^(?!foo).*$
shouldn't match anything starting with foo
.
I like this approach
my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)
Note the appended d and s to the brackets respectively.
output will be:
I scored 3 goals and took 5 penalties
elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).
By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.
It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.
Not programming related, but I'll answer anyway. It's in /etc/hosts
.
You can change it with a simple text editor such as nano
.
(Obviously you would need a jailbroken iphone for this)
I add the following code to /root/.bashrc to run the code only once,
Please commit the container to the image before run this script, otherwise the 'docker_services' file will be created in the images and no service will be run.
if [ ! -e /var/run/docker_services ]; then
echo "Starting services"
service mysql start
service ssh start
service nginx start
touch /var/run/docker_services
fi
I believe a clean and nice way to perform subtraction or addition of any time unit (months, days, hours, minutes, seconds, ...) can be achieved using the java.time.Instant class.
Example for subtracting 5 days from the current time and getting the result as Date:
new Date(Instant.now().minus(5, ChronoUnit.DAYS).toEpochMilli());
Another example for subtracting 1 hour and adding 15 minutes:
Date.from(Instant.now().minus(Duration.ofHours(1)).plus(Duration.ofMinutes(15)));
If you need more accuracy, Instance measures up to nanoseconds. Methods manipulating nanosecond part:
minusNano()
plusNano()
getNano()
Also, keep in mind, that Date is not as accurate as Instant.
Make sure you don't have a minSdkVersion
set in your build.gradle
with a value higher than 8. If you don't specify it at all, it's supposed to use the value in your AndroidManfiest.xml
, which seems to already be properly set.
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
Had the same exact error on WinXP box with latest build of my .NET 4 code. Checked previous builds - now they crash too! Ok, so it's not me :). No suggestions here/above helped.
Much more recent (2018-05-09) report of the same problem: Application Crash with exit code 80131506.
A: We were receiving a similar error, but we believe ours was caused by the Citrix memory optimizer.
The resolution was to force a regeneration of the .Net core libraries on the host(s) where the issue was occurring:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe update /force
Root cause is still unknown (machine is not being updated and has little use), but that did it for me!
Use the FOR command to echo a file line by line, and with the 'skip' option to miss a number of starting lines...
FOR /F "skip=1" %i in (file2.txt) do @echo %i
You could redirect the output of a batch file, containing something like...
FOR /F %%i in (file1.txt) do @echo %%i
FOR /F "skip=1" %%i in (file2.txt) do @echo %%i
Note the double % when a FOR variable is used within a batch file.
Ex: In web.xml file the tag
<context-param>
<param-name>chatpropertyfile</param-name>
<!-- Name of the chat properties file. It contains the name and description of rooms.-->
<param-value>chat.properties</param-value>
</context-param>
And chat.properties you can declare your properties like this
For Ex :
Jsp = Discussion about JSP can be made here.
Java = Talk about java and related technologies like J2EE.
ASP = Discuss about Active Server Pages related technologies like VBScript and JScript etc.
Web_Designing = Any discussion related to HTML, JavaScript, DHTML etc.
StartUp = Startup chat room. Chatter is added to this after he logs in.
I use this in my code in a custom class. Comes in handy for sending out emails like [email protected] "no-reply@" + BaseSiteUrl Works fine on any site.
// get a sites base urll ex: example.com
public static string BaseSiteUrl
{
get
{
HttpContext context = HttpContext.Current;
string baseUrl = context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/');
return baseUrl;
}
}
If you want to use it in codebehind get rid of context.
I'm going to make a bit of an assumption here because I'm not sure. I don't think my MySQL (running on latest 20.04 upgraded) even has a root. I have tried setting one and I remember having problems. I suspect there is not a root user and it will automatically log you in as the MySQL root user if you're logged in as root.
Why do I think this? Because when I do MySQL -u root -p, it will accept any password and log me in as the MySQL root user when I am logged in as root.
I have confirmed that trying that on a non root user doesn't work.
I like this model.
EDIT 2020.12.19: It is no longer a mystery to me why if you are logged in as the root user you get logged into MySQL as the root user. It has to do with the authentication type. Later versions of MySQL are configured with the MySQL plugin 'auth_socket' (maybe you've noticed the /run/mysqld/mysqld.sock file on your system and wondered about it). The plugin uses the SO_PEERCRED option provided by the library auth_socket.so.
You can revert back to password authentication if desired simply by create/update of the password. Showing both ways and options below to make clear.
CREATE USER 'valerie'@'localhost' IDENTIFIED WITH auth_socket;
CREATE USER 'valerie'@'localhost' IDENTIFIED BY 'password';
A bit late in the game but just in case it helps anyone.
If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).
The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.
I got the url above from PayPal's tech support.
Tested using a simple Hosted button and IPN. Good luck.
Here an example with Swift 3.0
let manager = AFHTTPSessionManager(sessionConfiguration: URLSessionConfiguration.default)
manager.requestSerializer = AFJSONRequestSerializer()
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Content-Type")
manager.requestSerializer.setValue("application/json", forHTTPHeaderField: "Accept")
if authenticated {
if let user = UserDAO.currentUser() {
manager.requestSerializer.setValue("Authorization", forHTTPHeaderField: user.headerForAuthentication())
}
}
manager.post(url, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, responseObject: Any?) in
if var jsonResponse = responseObject as? [String: AnyObject] {
// here read response
}
}) { (task: URLSessionDataTask?, error: Error) in
print("POST fails with error \(error)")
}
I had the same problem and after trying all of the above suggestions, it turned out that my IntelliJ installation had not picked up my JAVA_HOME system variable, and it had no SDK/JDK set.
I fixed it by following these instructions: Configuring Global, Project and Module SDKs
Looks good to me. If the indexer was unsigned (uint etc), you might have to take that into account. Call me lazy, but in that (unsigned) case, I might just use a counter-variable:
uint pos = arr.Length;
for(uint i = 0; i < arr.Length ; i++)
{
arr[--pos] = 42;
}
(actually, even here you'd need to be careful of cases like arr.Length = uint.MaxValue... maybe a != somewhere... of course, that is a very unlikely case!)
**Elaborated Answer...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
// Remember to add a reference to the System.Management assembly
using System.Management;
using System.Diagnostics;
namespace ShutDown
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnShutDown_Click(object sender, EventArgs e)
{
ManagementBaseObject mboShutdown = null;
ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
mcWin32.Get();
// You can't shutdown without security privileges
mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");
// Flag 1 means we want to shut down the system
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";
foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
}
}
}
}
If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ?
If you need to dynamically import code the built-in function __ import__ and the module imp are worth looking at.
>>> import sys
>>> sys.path = ['/path/to/script'] + sys.path
>>> __import__('test')
<module 'test' from '/path/to/script/test.pyc'>
>>> __import__('test').run()
'Hello world!'
test.py:
def run():
return "Hello world!"
If you're using Python 3.1 or later, you should also take a look at importlib.
Using width/height on inline elements is not always a good idea.
You can use display: inline-block
instead
Use something like this
$.getJSON("../../data/file.json", function(json) {
console.log(json); // this will show the info in firebug console
alert(json);
});
Try
gdb --args InsertionSortWithErrors arg1toinsort arg2toinsort
This does not sound like a good idea.
You should abstract out the function to include in the rest of your JavaScript code from the data returned by Ajax methods.
For what it's worth, though, (and I don't understand why you're inserting a script block in a div?) even inline script methods written in a script block will be accessible.
This is usually caused by your CSV having been saved along with an (unnamed) index (RangeIndex
).
(The fix would actually need to be done when saving the DataFrame, but this isn't always an option.)
read_csv
with index_col=[0]
argumentIMO, the simplest solution would be to read the unnamed column as the index. Specify an index_col=[0]
argument to pd.read_csv
, this reads in the first column as the index. (Note the square brackets).
df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df
a b c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
# Save DataFrame to CSV.
df.to_csv('file.csv')
<!- ->
pd.read_csv('file.csv')
Unnamed: 0 a b c
0 0 x x x
1 1 x x x
2 2 x x x
3 3 x x x
4 4 x x x
# Now try this again, with the extra argument.
pd.read_csv('file.csv', index_col=[0])
a b c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
Note
You could have avoided this in the first place by usingindex=False
if the output CSV was created in pandas, if your DataFrame does not have an index to begin with:df.to_csv('file.csv', index=False)
But as mentioned above, this isn't always an option.
str.match
If you cannot modify the code to read/write the CSV file, you can just remove the column by filtering with str.match
:
df
Unnamed: 0 a b c
0 0 x x x
1 1 x x x
2 2 x x x
3 3 x x x
4 4 x x x
df.columns
# Index(['Unnamed: 0', 'a', 'b', 'c'], dtype='object')
df.columns.str.match('Unnamed')
# array([ True, False, False, False])
df.loc[:, ~df.columns.str.match('Unnamed')]
a b c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
The third template parameter for priority_queue
is the comparator. Set it to use greater
.
e.g.
std::priority_queue<int, std::vector<int>, std::greater<int> > max_queue;
You'll need #include <functional>
for std::greater
.
@Min
and @Max
are used for validating numeric fields which could be String
(representing number), int
, short
, byte
etc and their respective primitive wrappers.
@Size
is used to check the length constraints on the fields.
As per documentation @Size
supports String
, Collection
, Map
and arrays
while @Min
and @Max
supports primitives and their wrappers. See the documentation.
Best way is use DateTime object to convert your date.
$myDateTime = DateTime::createFromFormat('Y-m-d', $weddingdate);
$formattedweddingdate = $myDateTime->format('d-m-Y');
Note: It will support for PHP 5 >= 5.3.0 only.
.wrap
{
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
#if defined LINUX || defined ANDROID
// your code here
#endif /* LINUX || ANDROID */
or-
#if defined(LINUX) || defined(ANDROID)
// your code here
#endif /* LINUX || ANDROID */
Both above are the same, which one you use simply depends on your taste.
P.S.: #ifdef
is simply the short form of #if defined
, however, does not support complex condition.
Further-
#if defined LINUX && defined ANDROID
#if defined LINUX ^ defined ANDROID
Upgrading from Kepler to Luna worked for me.
I had just added some components for Java 1.8 support. It seems that they where not as compatible as I would like or that I mixed the wrong ones. It really caused a lot of problems. Trying to update the system reported errors as they couldn't fulfill some dependencies. Maven upgrades didn't work. Tried a lot of things.
So, if there is no reason to avoid the upgrade just add the luna repository to avalilable software sites (Luna http://download.eclipse.org/releases/luna/ ) and "check for updates". It is better to have all the components with the same version and there are some nice new features.
To multiply, use mult
for signed multiplication and multu
for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0
that means that you assume the result will fit in 32 bits.
The 32 most significant bits will be held in the HI
special register (accessible by mfhi
instruction) and the 32 least significant bits will be held in the LO
special register (accessible by the mflo
instruction):
E.g.:
li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0
To divide, use div
for signed division and divu
for unsigned division. In this case, the HI
special register will hold the remainder and the LO
special register will hold the quotient of the division.
E.g.:
div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0
This is how I did it.
Step 1: Install Java 11
You can download Java 11 dmg for mac from here: https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html
Step 2: After installation of Java 11. Confirm installation of all versions. Type the following command in your terminal.
/usr/libexec/java_home -V
Step 3: Edit .bash_profile
sudo nano ~/.bash_profile
Step 4: Add 11.0.1 as default. (Add below line to bash_profile file).
export JAVA_HOME=$(/usr/libexec/java_home -v 11.0.1)
to switch to any version
export JAVA_HOME=$(/usr/libexec/java_home -v X.X.X)
Now Press CTRL+X to exit the bash. Press 'Y' to save changes.
Step 5: Reload bash_profile
source ~/.bash_profile
Step 6: Confirm current version of Java
java -version
If you use multiple users at android, verify that the app is uninstalled everywhere.
I started off using curl
, but since have migrated to use kibana
. Here is some more information on the ELK stack from elastic.co (E elastic search, K kibana): https://www.elastic.co/elk-stack
With kibana your POST
requests are a bit more simple:
POST /<INDEX_NAME>/<TYPE_NAME>
{
"field": "value",
"id": 1,
"account_id": 213,
"name": "kimchy"
}
This has worked for me in the past and it will even expand environment variables in the file if it can.
for /F "delims=" %%a in (LogName.txt) do (
echo %%a>>MyDestination.txt
)
You may use simplehtmldom. Most of the jQuery selectors are supported in simplehtmldom. An example is given below
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');
// Find all images
foreach($html->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($html->find('a') as $element)
echo $element->href . '<br>';
You can use this code:
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(TIME_OUT);
conection.connect();
// Getting file length
int lenghtOfFile = conection.getContentLength();
// Create a Input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
OutputStream output = new FileOutputStream(
"/sdcard/9androidnet.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (SocketTimeoutException e) {
connectionTimeout=true;
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
I had the same problem, but I forgot to include the file into grunt/gulp minimization process.
grunt.initConfig({
uglify: {
my_target: {
files: {
'dest/output.min.js': ['src/input1.js', 'src/missing_controller.js']
}
}
}
});
Hope that helps.
In the past, I had no error logs in two cases:
php_error_log
file..htaccess
, for example wrong rewrite module settings. In this situation errors are logged to Apache error_log
file.textField.layer.borderWidth = 3;
will add border, which worked as padding for me.
Honestly, Wikipedia might be the best place to look for an answer to this.
If NP = P, then we can solve very hard problems much faster than we thought we could before. If we solve only one NP-Complete problem in P (polynomial) time, then it can be applied to all other problems in the NP-Complete category.
This work for me when I wanted to show a photo depending on the gender of the user:
<img th:src="${generou}=='Femenino' ? @{/images/user_mujer.jpg}: @{/images/user.jpg}" alt="AdminLTE Logo" class="brand-image img-circle elevation-3">
The string literal is pased according to the current dateformat setting, see SET DATEFORMAT
. One format which will always work is the '20090525' one.
Now, of course, you need to define 'does not work'. No records gets updated? Perhaps the Id=1
doesn't match any record...
If it says 'One record changed' then perhaps you need to show us how you verify...
In your quesion code you are using TimeSpan.FromMinutes
incorrectly. Please see the MSDN Documentation for TimeSpan.FromMinutes, which gives the following method signature:
public static TimeSpan FromMinutes(double value)
hence, the following code won't compile
var intMinutes = TimeSpan.FromMinutes(varTime); // won't compile
Instead, you can use the TimeSpan.TotalMinutes property to perform this arithmetic. For instance:
TimeSpan varTime = (DateTime)varFinish - (DateTime)varValue;
double fractionalMinutes = varTime.TotalMinutes;
int wholeMinutes = (int)fractionalMinutes;
You can specify the destination directory as second parameter of the git clone
command, so you can do:
git clone <remote> .
This will clone the repository directly in the current local directory.
I wanted to hide the waiting spinner div when the i frame content is fully loaded on IE, i tried literally every solution mentioned in Stackoverflow.Com, but with nothing worked as i wanted.
Then i had an idea, that when the i frame content is fully loaded, the $(Window ) load event might be fired. And that exactly what happened. So, i wrote this small script, and worked like magic:
$(window).load(function () {
//alert("Done window ready ");
var lblWait = document.getElementById("lblWait");
if (lblWait != null ) {
lblWait.style.visibility = "false";
document.getElementById("divWait").style.display = "none";
}
});
Hope this helps.
Sometimes when you download plugins you may get (.zip) files then just rename with (.hpi) and then extract all the plugins and move to <jenkinsHome>/plugins/
directory.
Here is a quick and dirty way to extract the code from V3 or V4 ipynb without using ipython. It does not check cell types, etc.
import sys,json
f = open(sys.argv[1], 'r') #input.ipynb
j = json.load(f)
of = open(sys.argv[2], 'w') #output.py
if j["nbformat"] >=4:
for i,cell in enumerate(j["cells"]):
of.write("#cell "+str(i)+"\n")
for line in cell["source"]:
of.write(line)
of.write('\n\n')
else:
for i,cell in enumerate(j["worksheets"][0]["cells"]):
of.write("#cell "+str(i)+"\n")
for line in cell["input"]:
of.write(line)
of.write('\n\n')
of.close()
Try this
<input onkeypress='return event.charCode >= 48 && _x000D_
event.charCode <= 57 || _x000D_
event.charCode == 46'>
_x000D_
Just utilize toString
or toLocaleString
I'd say. So:
var page_number:number = 3;
window.location.hash = page_number.toLocaleString();
These throw an error if page_number
is null
or undefined
. If you don't want that you can choose the fix appropriate for your situation:
// Fix 1:
window.location.hash = (page_number || 1).toLocaleString();
// Fix 2a:
window.location.hash = !page_number ? "1" page_number.toLocaleString();
// Fix 2b (allows page_number to be zero):
window.location.hash = (page_number !== 0 && !page_number) ? "1" page_number.toLocaleString();
There is too much data to be displayed on the screen, therefore a summary is displayed instead.
If you want to output the data anyway (it won't probably fit on a screen and does not look very well):
print paramdata.values
converts the dataframe to its numpy-array matrix representation.
paramdata.columns
stores the respective column names and
paramdata.index
stores the respective index (row names).
In your action you need first to load companies like so :
$companies = App\Company::all();
return view('listing.company')->with('companies' => $companies)->render();
This will make the companies variable available in the view, and it should render the HTML correctly.
Try to use postman chrome extension to debug your view.
public void captureScreen(String fileName) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRectangle);
ImageIO.write(image, "png", new File(fileName));
}
If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
Also see this SO thread: Open directory dialog
Relative import happens whenever you are importing a package relative to the current script/package.
Consider the following tree for example:
mypkg
+-- base.py
+-- derived.py
Now, your derived.py
requires something from base.py
. In Python 2, you could do it like this (in derived.py
):
from base import BaseThing
Python 3 no longer supports that since it's not explicit whether you want the 'relative' or 'absolute' base
. In other words, if there was a Python package named base
installed in the system, you'd get the wrong one.
Instead it requires you to use explicit imports which explicitly specify location of a module on a path-alike basis. Your derived.py
would look like:
from .base import BaseThing
The leading .
says 'import base
from module directory'; in other words, .base
maps to ./base.py
.
Similarly, there is ..
prefix which goes up the directory hierarchy like ../
(with ..mod
mapping to ../mod.py
), and then ...
which goes two levels up (../../mod.py
) and so on.
Please however note that the relative paths listed above were relative to directory where current module (derived.py
) resides in, not the current working directory.
@BrenBarn has already explained the star import case. For completeness, I will have to say the same ;).
For example, you need to use a few math
functions but you use them only in a single function. In Python 2 you were permitted to be semi-lazy:
def sin_degrees(x):
from math import *
return sin(degrees(x))
Note that it already triggers a warning in Python 2:
a.py:1: SyntaxWarning: import * only allowed at module level
def sin_degrees(x):
In modern Python 2 code you should and in Python 3 you have to do either:
def sin_degrees(x):
from math import sin, degrees
return sin(degrees(x))
or:
from math import *
def sin_degrees(x):
return sin(degrees(x))
There's an answer above which says "cursors are the SLOWEST way to access data inside SQL Server... cursors are over thirty times slower than set based alternatives."
This statement may be true under many circumstances, but as a blanket statement it's problematic. For example, I've made good use of cursors in situations where I want to perform an update or delete operation affecting many rows of a large table which is receiving constant production reads. Running a stored procedure which does these updates one row at a time ends up being faster than set-based operations, because the set-based operation conflicts with the read operation and ends up causing horrific locking problems (and may kill the production system entirely, in extreme cases).
In the absence of other database activity, set-based operations are universally faster. In production systems, it depends.
To be concise and precise download the compatible jdbc (.jar) file compatible with your MySql version and put it in lib
folder.
For example for MySQL 8.0.2 download Connector/J 8.0.20
Specify the width of the table:
table
{
table-layout: fixed;
width: 100px;
}
See jsFiddle
You can also try:
{
"dateProp": { $gt: new Date('06/15/2016').getTime() }
}
In your case scenario, Why not use GROUP BY and HAVING clause instead of JOINING table to itself. You may also use other useful function. see this link
SELECT *
FROM sys.objects
WHERE type = 'V'
This is very good: http://simononsoftware.com/virtualenv-tutorial-part-2/
And this is a slightly more practical one: https://web.archive.org/web/20160404222648/https://iamzed.com/2009/05/07/a-primer-on-virtualenv/
Use @RequestParam in your method arguments so Spring can bind them, also use the @RequestMapping.params array to narrow the method that will be used by spring. Sample code:
@RequestMapping("/userGrid",
params = {"_search", "nd", "rows", "page", "sidx", "sort"})
public @ResponseBody GridModel getUsersForGrid(
@RequestParam(value = "_search") String search,
@RequestParam(value = "nd") int nd,
@RequestParam(value = "rows") int rows,
@RequestParam(value = "page") int page,
@RequestParam(value = "sidx") int sidx,
@RequestParam(value = "sort") Sort sort) {
// Stuff here
}
This way Spring will only execute this method if ALL PARAMETERS are present saving you from null checking and related stuff.
You can also add 'active' class to the selected item.
$('.dropdown').on( 'click', '.dropdown-menu li a', function() {
var target = $(this).html();
//Adds active class to selected item
$(this).parents('.dropdown-menu').find('li').removeClass('active');
$(this).parent('li').addClass('active');
//Displays selected text on dropdown-toggle button
$(this).parents('.dropdown').find('.dropdown-toggle').html(target + ' <span class="caret"></span>');
});
See the jsfiddle example
Basically It is used in HeapOverflows or other reversing type Problems i.e. If you want to change a 64 bit ELF to 32 bit ELF and it is showing error while converting.
You can simply run the commands
apt-get install gcc-multilib g++-multilib
which will update your libraries Packages upgraded:
The following additional packages will be installed: g++-8-multilib gcc-8-multilib lib32asan5 lib32atomic1 lib32gcc-8-dev lib32gomp1 lib32itm1 lib32mpx2 lib32quadmath0 lib32stdc++-8-dev lib32ubsan1 libc-dev-bin libc6 libc6-dbg libc6-dev libc6-dev-i386 libc6-dev-x32 libc6-i386 libc6-x32 libx32asan5 libx32atomic1 libx32gcc-8-dev libx32gcc1 libx32gomp1 libx32itm1 libx32quadmath0 libx32stdc++-8-dev libx32stdc++6 libx32ubsan1 Suggested packages: lib32stdc++6-8-dbg libx32stdc++6-8-dbg glibc-doc The following NEW packages will be installed: g++-8-multilib g++-multilib gcc-8-multilib gcc-multilib lib32asan5 lib32atomic1 lib32gcc-8-dev lib32gomp1 lib32itm1 lib32mpx2 lib32quadmath0 lib32stdc++-8-dev lib32ubsan1 libc6-dev-i386 libc6-dev-x32 libc6-x32 libx32asan5 libx32atomic1 libx32gcc-8-dev libx32gcc1 libx32gomp1 libx32itm1 libx32quadmath0 libx32stdc++-8-dev libx32stdc++6 libx32ubsan1
similar to this will be shown to your terminal
var List = @Html.Raw(Json.Encode(Model));
$.ajax({
type: 'post',
url: '/Controller/action',
data:JSON.stringify({ 'item': List}),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//do your actions
},
error: function (response) {
alert("error occured");
}
});
I spent quite a lot of time figuring out how to do this in Intellij 13x. I apparently never added the properties files to the artifacts that required them, which is a separate step in Intellij. The setup below also works when you have a properties file that is shared by multiple modules.
First thing, the example you gave is not a valid list.
example_list = [u'nowplaying',u'PBS', u'PBS', u'nowplaying', u'job', u'debate',u'thenandnow']
Suppose if above is the example list. Then you can use the following recipe as give the itertools example doc that can return the unique values and preserving the order as you seem to require. The iterable here is the example_list
from itertools import ifilterfalse
def unique_everseen(iterable, key=None):
"List unique elements, preserving order. Remember all elements ever seen."
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
seen = set()
seen_add = seen.add
if key is None:
for element in ifilterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element