The 00947 message indicates that the record which you are trying to send to Oracle lacks one or more of the columns which was included at the time the table was created. The 00913 message indicates that the record which you are trying to send to Oracle includes more columns than were included at the time the table was created. You just need to check the number of columns and its type in both the tables ie the tables that are involved in the sql.
scan
can read from a web page automatically; you don't necessarily have to mess with connections.
You asked about performance. See this perf test comparing 'concat', '+' and 'join' - in short the + operator wins by far.
* {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
ul {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
li {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
background: silver;_x000D_
width: 100%;_x000D_
height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
<li>This is the text</li>_x000D_
</ul>
_x000D_
On the comments:
sscanf(Abcd, "%f %s", &f,&s);
Gives an Error.
This is the right way:
sscanf(Abcd, "%f %s", &f,qPrintable(s));
Here is my solution first:
For example, I suppose that we have an object that contains three value pairs:
function findKey(object, value) {
for (let key in object)
if (object[key] === value) return key;
return "key is not found";
}
const object = { id_1: "apple", id_2: "pear", id_3: "peach" };
console.log(findKey(object, "pear"));
//expected output: id_2
We can simply write a findKey(array, value) that takes two parameters which are an object and the value of the key you are looking for. As such, this method is reusable and you do not need to manually iterate the object every time by only passing two parameters for this function.
Owl Carousel version matters a lot, as of now (2nd Aug 2020) the version is 2.3.4
and the right options for autoplay are:
$(".owl-carousel").owlCarousel({
autoplay : true,
autoplayTimeout: 3000,//Autoplay interval timeout.
loop:true,//Infinity loop. Duplicate last and first items to get loop illusion.
items:1 //The number of items you want to see on the screen.
});
Read more Owl configurations
This works:
var img = document.createElement('img');
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
document.getElementById('gamediv').appendChild(img)
Or using jQuery:
$('<img/>')
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
.appendTo('#gamediv');
All $_GET
parameters have a string datatype, therefore, is_int
will always return false.
You can see this by calling var_dump
:
var_dump($_GET['p']); // string(2) "54"
Using is_numeric
will provide the desired result (mind you, that allows values such as: 0x24
).
You can easily achieve what you want using the appendix
package. Here's a sample file that shows you how. The key is the titletoc
option when calling the package. It takes whatever value you've defined in \appendixname
and the default value is Appendix
.
\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents
\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
\chapter{Consectetur adipiscing elit}
\chapter{Mauris euismod}
\end{appendices}
\end{document}
The output looks like
Just a few (others have suggested some of these)
Method 1:
''.join(i for i in myStr if not i.isdigit())
Method 2:
def removeDigits(s):
answer = []
for char in s:
if not char.isdigit():
answer.append(char)
return ''.join(char)
Method 3:
''.join(filter(lambda x: not x.isdigit(), mystr))
Method 4:
nums = set(map(int, range(10)))
''.join(i for i in mystr if i not in nums)
Method 5:
''.join(i for i in mystr if ord(i) not in range(48, 58))
I have faced the same problem with a real android device.
Solution: Based on this answer by Niltoid
for Mac user: open your network preference, here you will get your local IP.
Instead of the *
selector you can use the :not(selector)
with the >
selector and set something that definitely wont be a child.
Edit: I thought it would be faster but it turns out I was wrong. Disregard.
Example:
.container > :not(marquee){
color:red;
}
<div class="container">
<p></p>
<span></span>
<div>
place your "a href" tag without any styling before div / span of text. then make your styling in the div/span tag.
for the most restricted styling email client.
<div><a href=""><span style="text-decoration:none">title</span><a/></div>
Not knowing the actual details, my guess is that it makes an attempt to join like you might join relative URIs. For example:
urljoin('/some/abs/path', '../other') = '/some/abs/other'
This means that when you join a path with a preceding slash, you are actually joining one base to another, in which case the second gets precedence.
The defer attribute is a boolean attribute.
When present, it specifies that the script is executed when the page has finished parsing.
Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).
Note: There are several ways an external script can be executed:
If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing) If async is not present and defer is present: The script is executed when the page has finished parsing If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page
You can get the total number of rows containing a specific name using:
SELECT COUNT(*) FROM tbl_foo WHERE name = 'sarmen'
Given the count, you can now get the nth row using:
SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT (n - 1), 1
Where 1 <= n <= COUNT(*) from the first query.
Example:
getting the 3rd row
SELECT * FROM tbl_foo WHERE name = 'sarmen' LIMIT 2, 1
to sum it up
1) in AndroidStudio's settings > compile
enable checkbox named Compile independent modules in parallel
.
2) Under Help> Edit Custom VM Options
I have:
-Xms1024m
-Xmx4096m # <------ increase this to most of your RAM
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=440m
-XX:+UseCompressedOops
-XX:-HeapDumpOnOutOfMemoryError
-Dfile.encoding=UTF-8
P.S. - Some people say Note, instead of VM options, it's better to combine can be overriden by combining those lines into one line single command in gradle.properties, like this :
org.gradle.jvmargs=-Xms1024m -Xmx4096m ......
3) I have an old dual core with 4GB ram, running ubuntu. Qs command line option I have only --offline
(which specifies that the build should operate without accessing network resources). I also enabled the remaining checkboxes and now it's running ok:
Make project automatically
Use in-process building Configure on demand
Check the AndroidStudio's settings, under compile that the checkbox Compile independent modules in parallel
is enabled.
Under Vmoptions I have
-Xmx2048m -XX:MaxPermSize=1024
I have an old dual core with 4GB ram, running ubuntu. Qs commandline option I have only --offline
, which specifies that the build should operate without accessing network resources. I enabled also the remaining checkboxes:
Configure on demand
and it is running ok
Edit
It is possible to provide additional options through studio.vmoptions
located at (just replace X.X with version):
Windows: go to %USERPROFILE%\.AndroidStudioX.X\studio.exe.vmoptions
(or studio64.exe.vmoptions
)
Mac: ~/Library/Preferences/.AndroidStudioX.X/studio.vmoptions
Linux: ~/.AndroidStudioX.X/studio.vmoptions
(and/or studio64.vmoptions
)
Increasing the value of -Xmx
should help a lot. E.g
-Xms1024m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=256m
-XX:+UseCompressedOops
will assign 4G as max heap, with initial value of 1G
Edit:
On windows the defaults are stored into C:\Program Files\Android\Android Studio\bin\*.vmoptions
. The IDE allows you to tweak those values through Help->Edit Custom VM options
(thanks to @Code-Read
for pointing it out).
EDIT 2:
Android studio 3.5 makes easier to change same of those values. Just go to:
Preferences > Appearance & Behavior > System Settings > Memory Settings
Track the remote branch
You can specify the default remote repository for pushing and pulling using git-branch’s track option. You’d normally do this by specifying the --track option when creating your local master branch, but as it already exists we’ll just update the config manually like so:
Edit your .git/config
[branch "master"]
remote = origin
merge = refs/heads/master
Now you can simply git push and git pull.
[source]
I have this function in my code base, this should work for you.
public static Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}
also see this similar question
import UIKit
class TabbarViewController: UITabBarController,UITabBarControllerDelegate {
//MARK:- View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//Tabbar delegate method
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
yourView.popToRootViewController(animated:false)
}
}
<!--ForExport data in iamge -->
<script type="text/javascript">
function ConvertToImage(btnExport) {
html2canvas($("#dvTable")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
$("[id*=hfImageData]").val(base64);
__doPostBack(btnExport.name, "");
});
return false;
}
</script>
<!--ForExport data in iamge -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="../js/html2canvas.min.js"></script>
<table>
<tr>
<td valign="top">
<asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
<div id="dvTable" class="divsection2" style="width: 350px">
<asp:HiddenField ID="hfImageData" runat="server" />
<table width="100%">
<tr>
<td>
<br />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
protected void ExportToImage(object sender, EventArgs e)
{
string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
byte[] bytes = Convert.FromBase64String(base64);
Response.Clear();
Response.ContentType = "image/png";
Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
}
The typical solution to this is to write your own function to clone an object. If you are able to provide copy constructors and copy assignement operators, this may be as far as you need to go.
class Foo
{
public:
Foo();
Foo(const Foo& rhs) { /* copy construction from rhs*/ }
Foo& operator=(const Foo& rhs) {};
};
// ...
Foo orig;
Foo copy = orig; // clones orig if implemented correctly
Sometimes it is beneficial to provide an explicit clone()
method, especially for polymorphic classes.
class Interface
{
public:
virtual Interface* clone() const = 0;
};
class Foo : public Interface
{
public:
Interface* clone() const { return new Foo(*this); }
};
class Bar : public Interface
{
public:
Interface* clone() const { return new Bar(*this); }
};
Interface* my_foo = /* somehow construct either a Foo or a Bar */;
Interface* copy = my_foo->clone();
EDIT: Since Stack
has no member variables, there's nothing to do in the copy constructor or copy assignment operator to initialize Stack
's members from the so-called "right hand side" (rhs
). However, you still need to ensure that any base classes are given the opportunity to initialize their members.
You do this by calling the base class:
Stack(const Stack& rhs)
: List(rhs) // calls copy ctor of List class
{
}
Stack& operator=(const Stack& rhs)
{
List::operator=(rhs);
return * this;
};
This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.
Some possible alternatives:
Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.
Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.
I faced this issue and it get resolved by following steps.
Delete non existing JRE path from this file as mention in below
-vm C:/Program Files/Java/jre1.8.0_181/bin
Save this file and run eclipse again.
yet another edit: As of version 5.2 pluck
is not deprecated anymore, it just got new behaviour (same as lists
previously - see side-note below):
edit: As of version 5.1 pluck
is deprecated, so start using value
instead:
DB::table('users')->where('username', $username)->value('groupName');
// valid for L4 / L5.0 only
DB::table('users')->where('username', $username)->pluck('groupName');
this will return single value of groupName
field of the first row found.
SIDE NOTE reg. @TomasButeler comment: As Laravel doesn't follow sensible versioning, there are sometimes cases like this. At the time of writing this answer we had pluck
method to get SINGLE value from the query (Laravel 4.* & 5.0).
Then, with L5.1 pluck
got deprecated and, instead, we got value
method to replace it.
But to make it funny, pluck
in fact was never gone. Instead it just got completely new behaviour and... deprecated lists
method.. (L5.2) - that was caused by the inconsistency between Query Builder and Collection methods (in 5.1 pluck
worked differently on the collection and query, that's the reason).
I realize this is an old question, but the same issue happened to me, but for a completely different reason.
It could be that cvs-dude changed certificates, so it no longer matches the certificate you have cached.
You can go to TortoiseSVN->Settings->Saved Data and click the 'Clear' button next to 'Authentication data' and then try again.
You should add dataType: "html"
to the request. Im quite sure you wont be able to search the DOM of the returned html if it doesnt know it is html.
Yes, you need to write it like your second line. Java doesn't have the python style syntactic sugar of your first line.
Alternatively you could put your valid values into an array and check for the existence of symbol
in the array.
You can use a checkbox
to simulate onClick with CSS:
input[type=checkbox]:checked + p {
display: none;
}
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
Example:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
It should work. I tried it; same outcome. But when I used this:
var length = 1;
var html = "";
for (var i = 0; i < length; i++) {
html += '<div id="codeSnippet"></div>';
html += '<script type="text/javascript">';
html += 'your script here';
html += '</script>';
}
$('#someElement').replaceWith(a);
This worked for me.
Edit: I forgot the #someelement
(btw I might want to use #someElement
because of conventions)
The most important thing here is the += so the html is added and not replaced.
Leave a comment if it didn't work. I'd like to help you out!
Note that you can also make your Makefile simpler, at the same time:
DEBUG ?= 1
ifeq (DEBUG, 1)
CFLAGS =-g3 -gdwarf2 -DDEBUG
else
CFLAGS=-DNDEBUG
endif
CXX = g++ $(CFLAGS)
CC = gcc $(CFLAGS)
EXECUTABLE = output
OBJECTS = CommandParser.tab.o CommandParser.yy.o Command.o
LIBRARIES = -lfl
all: $(EXECUTABLE)
$(EXECUTABLE): $(OBJECTS)
$(CXX) -o $@ $^ $(LIBRARIES)
%.yy.o: %.l
flex -o $*.yy.c $<
$(CC) -c $*.yy.c
%.tab.o: %.y
bison -d $<
$(CXX) -c $*.tab.c
%.o: %.cpp
$(CXX) -c $<
clean:
rm -f $(EXECUTABLE) $(OBJECTS) *.yy.c *.tab.c
Now you don't have to repeat filenames all over the place. Any .l files will get passed through flex and gcc, any .y files will get passed through bison and g++, and any .cpp files through just g++.
Just list the .o files you expect to end up with, and Make will do the work of figuring out which rules can satisfy the needs...
for the record:
$@
The name of the target file (the one before the colon)
$<
The name of the first (or only) prerequisite file (the first one after the colon)
$^
The names of all the prerequisite files (space separated)
$*
The stem (the bit which matches the %
wildcard in the rule definition.
This is the most discussed aspect of the Selectors Level 4 specification. With this, a selector will be able to style an element according to its child by using an exclamation mark after the given selector (!).
For example:
body! a:hover{
background: red;
}
will set a red background-color if the user hovers over any anchor.
But we have to wait for browsers' implementation :(
One more example:
If you have Column from A to D, and need to highlight the whole line (e.g. from A to D) if B is "Complete", then you can do it following:
"Custom formula is": =$B:$B="Completed"
Background Color: red
Range: A:D
Of course, you can change Range to A:T if you have more columns.
If B contains "Complete", use search as following:
"Custom formula is": =search("Completed",$B:$B)
Background Color: red
Range: A:D
Python's built-in CSV module can handle this easily:
import csv
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(a)
This assumes your list is defined as a
, as it is in your question. You can tweak the exact format of the output CSV via the various optional parameters to csv.writer()
as documented in the library reference page linked above.
Update for Python 3
import csv
with open("out.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(a)
A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules.
In the case of a REST API with a JSON payload, 400's are typically, and correctly I would say, used to indicate that the JSON is invalid in some way according to the API specification for the service.
By that logic, both the scenarios you provided should be 400s.
Imagine instead this were XML rather than JSON. In both cases, the XML would never pass schema validation--either because of an undefined element or an improper element value. That would be a bad request. Same deal here.
With PHP 5.3, you can now do this:
function doIt($callback) { $callback(); }
doIt(function() {
// this will be done
});
Finally a nice way to do it. A great addition to PHP, because callbacks are awesome.
You can stop the image from overlapping it's edges by clipping the image and applying a wrapper element which sets the blur effect to 0 pixels. This is how it looks like:
HTML
<div id="wrapper">
<div id="image"></div>
</div>
CSS
#wrapper {
width: 1024px;
height: 768px;
border: 1px solid black;
// 'blur(0px)' will prevent the wrapped image
// from overlapping the border
-webkit-filter: blur(0px);
-moz-filter: blur(0px);
-ms-filter: blur(0px);
filter: blur(0px);
}
#wrapper #image {
width: 1024px;
height: 768px;
background-image: url("../images/cats.jpg");
background-size: cover;
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-ms-filter: blur(10px);
filter: blur(10px);
// Position 'absolute' is needed for clipping
position: absolute;
clip: rect(0px, 1024px, 768px, 0px);
}
This Works for me in Windows 7 to 10 with parameters, when kick starting app or file from anywhere (including browser) and also when accessing file from anywhere. Replace (YOUR BATCH SCRIPT HERE anchor) with your code. This solution May Help :)
@echo off
call :isAdmin
if %errorlevel% == 0 (
goto :run
) else (
echo Requesting administrative privileges...
goto :UACPrompt
)
exit /b
:isAdmin
fsutil dirty query %systemdrive% >nul
exit /b
:run
<YOUR BATCH SCRIPT HERE>
exit /b
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %~1", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
(B)|(A)
then use what group 2 captures...
Sadly this happens to me quite regularly as well and I use git stash
if I realized my mistake before git commit
and use git cherry-pick
otherwise, both commands are explained pretty well in other answers
I want to add a clarification for git checkout targetBranch
: this command will only preserve your working directory and staged snapshot if targetBranch has the same history as your current branch
If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally
@Amber's statement is not false, when you move to a newBranch,git checkout -b newBranch
, a new pointer is created and it is pointing to the exact same commit as your current branch.
In fact, if you happened to have an another branch that shares history with your current branch (both point at the same commit) you can "move your changes" by git checkout targetBranch
However, usually different branches means different history, and Git will not allow you to switch between these branches with a dirty working directory or staging area. in which case you can either do git checkout -f targetBranch
(clean and throwaway changes) or git stage
+ git checkout targetBranch
(clean and save changes), simply running git checkout targetBranch
will give an error:
error: Your local changes to the following files would be overwritten by checkout: ... Please commit your changes or stash them before you switch branches. Aborting
It's better to use $(window).scroll()
rather than $('#Eframe').on("mousewheel")
$('#Eframe').on("mousewheel")
will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.
$(window).scroll(function(){
var scrollPos = $(document).scrollTop();
console.log(scrollPos);
});
If #Eframe
is an element with overflow:scroll
on it and you want it's scroll position. I think this should work (I haven't tested it though).
$('#Eframe').scroll(function(){
var scrollPos = $('#Eframe').scrollTop();
console.log(scrollPos);
});
The accepted answer wasn't working for me when trying to parse the registry for uninstall strings, and execute them. Turns out I didn't need the call to Invoke-Expression
after all.
I finally came across this nice template for seeing how to execute uninstall strings:
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$app = 'MyApp'
$apps= @{}
Get-ChildItem $path |
Where-Object -FilterScript {$_.getvalue('DisplayName') -like $app} |
ForEach-Object -process {$apps.Set_Item(
$_.getvalue('UninstallString'),
$_.getvalue('DisplayName'))
}
foreach ($uninstall_string in $apps.GetEnumerator()) {
$uninstall_app, $uninstall_arg = $uninstall_string.name.split(' ')
& $uninstall_app $uninstall_arg
}
This works for me, namely because $app
is an in house application that I know will only have two arguments. For more complex uninstall strings you may want to use the join operator. Also, I just used a hash-map, but really, you'd probably want to use an array.
Also, if you do have multiple versions of the same application installed, this uninstaller will cycle through them all at once, which confuses MsiExec.exe
, so there's that too.
Just testing for end of file with feof
would do, I think.
Sure:
var query = grades.GroupBy(student => student.Name)
.Select(group =>
new { Name = group.Key,
Students = group.OrderByDescending(x => x.Grade) })
.OrderBy(group => group.Students.First().Grade);
Note that you can get away with just taking the first grade within each group after ordering, because you already know the first entry will be have the highest grade.
Then you could display them with:
foreach (var group in query)
{
Console.WriteLine("Group: {0}", group.Name);
foreach (var student in group.Students)
{
Console.WriteLine(" {0}", student.Grade);
}
}
OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.
OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.
OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.
So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.
I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK
Try this:
import matplotlib as plt
after importing the file we can use matplotlib library but remember to use it as plt
df.plt(kind='line',figsize=(10,5))
after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.
Recent Debian have Python package androguard
:
Description-en: full Python tool to play with Android files
Androguard is a full Python tool to play with Android files.
* DEX, ODEX
* APK
* Android's binary xml
* Android resources
* Disassemble DEX/ODEX bytecodes
* Decompiler for DEX/ODEX files
Install corresponding packages:
sudo apt-get install androguard python-networkx
Decompile DEX file:
$ androdd -i classes.dex -o ./dir-for-output
Extract classes.dex
from Apk + Decompile:
$ androdd -i app.apk -o ./dir-for-output
Apk file is nothing more that Java archive (JAR), you may extract files from archive via:
$ unzip app.apk -d ./dir-for-output
With jQuery > 1.6.1 should be better to use this syntax:
$('#span_id select option[value="' + some_value + '"]').prop('selected', true);
The classes for the OOXML file formats (such as XSSF for .xlsx) are in a different Jar file. You need to include the poi-ooxml jar in your project, along with the dependencies for it
You can get a list of all the components and their dependencies on the POI website here.
What you probably want to do is download the 3.11 binary package, grab the poi-ooxml
jar from it, and the dependencies in the ooxml-lib
directory. Import these into your project and you'll be sorted.
Alternately, if you use Maven, you can see here for the list of the artificats you'll want to depend on, but it'd want to be something like:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
The poi-ooxml maven dependency will pull in the main POI jar and the dependencies for you automatically. If you want to work with the non-spreadsheet formats, you'd also want to depend on the poi-scratchpad
artifact too, as detailed on the POI components page
I'm just beginning to use JPype 0.5.4.2 (july 2011) and it looks like it's working nicely...
I'm on Xubuntu 10.04
Here is another example of a recursive copy function that lets you copy the contents of the directory (including sub-directories) one file at a time, which I used to solve this problem.
import os
import shutil
def recursive_copy(src, dest):
"""
Copy each file from src dir to dest dir, including sub-directories.
"""
for item in os.listdir(src):
file_path = os.path.join(src, item)
# if item is a file, copy it
if os.path.isfile(file_path):
shutil.copy(file_path, dest)
# else if item is a folder, recurse
elif os.path.isdir(file_path):
new_dest = os.path.join(dest, item)
os.mkdir(new_dest)
recursive_copy(file_path, new_dest)
EDIT: If you can, definitely just use shutil.copytree(src, dest)
. This requires that that destination folder does not already exist though. If you need to copy files into an existing folder, the above method works well!
This is how Windows Mobile has worked for... well... ever! Here's what Microsoft have to say on the matter:
http://blogs.msdn.com/windowsmobile/archive/2006/10/05/The-Emperor-Has-No-Close.aspx (is it sad that I remembered the title of the blog post all the way from 2006? I found the article on Google by searching "the emperor has no close" lol)
In short:
If the system needs more memory while the app is in the background, it’ll close the app. But, if the system doesn’t need more memory, the app will stay in RAM and be ready to come back quickly the next time the user needs it.
Many comments in this question at O'Reilly suggest that Android behaves in much the same way, closing applications that haven't been used for a while only when Android needs the memory they're using.
Since this is a standard feature, then changing the behavior to forcefully close would be changing the user experience. Many users would be used to the gentle dismissal of their Android apps so when they dismiss one with the intention of returning to it after performing some other tasks, they may be rather frustrated that the state of the application is reset, or that it takes longer to open. I would stick with the standard behavior because it is what is expected.
Since you have a DataTable already, and since I am assuming you are using SQL Server 2008 or better, this is probably the most straightforward way. First, in your database, create the following two objects:
CREATE TYPE dbo.MyDataTable -- you can be more speciifc here
AS TABLE
(
col1 INT,
col2 DATETIME
-- etc etc. The columns you have in your data table.
);
GO
CREATE PROCEDURE dbo.InsertMyDataTable
@dt AS dbo.MyDataTable READONLY
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.RealTable(column list) SELECT column list FROM @dt;
END
GO
Now in your C# code:
DataTable tvp = new DataTable();
// define / populate DataTable
using (connectionObject)
{
SqlCommand cmd = new SqlCommand("dbo.InsertMyDataTable", connectionObject);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvparam = cmd.Parameters.AddWithValue("@dt", tvp);
tvparam.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();
}
If you had given more specific details in your question, I would have given a more specific answer.
Try this
$("#message span").text("hello world!");
function Errormessage(txt) {
var elem = $("#message");
elem.fadeIn("slow");
// find the span inside the div and assign a text
elem.children("span").text("your text");
elem.children("a.close-notify").click(function() {
elem.fadeOut("slow");
});
}
Try to install Integrated Native Developer Experience
" Is a cross-architecture productivity suite that provides developers with tools, support, and IDE integration to create high-performance C++/Java* applications for Windows* on Intel® architecture, OS X on Intel® architecture and Android* on ARM* and Intel® architecture."
I use this method to change the color of the line with PorterDuff, with no other drawable.
public void changeBottomColorSearchView(int color) {
int searchPlateId = mSearchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
View searchPlate = mSearchView.findViewById(searchPlateId);
searchPlate.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
}
I believe (and I am hardly well-versed in Python) that the main difference is that a tuple is immutable (it can't be changed in place after assignment) and a list is mutable (you can append, change, subtract, etc).
So, I tend to make my tuples things that shouldn't change after assignment and my lists things that can.
>>> myseries[myseries == 7]
3 7
dtype: int64
>>> myseries[myseries == 7].index[0]
3
Though I admit that there should be a better way to do that, but this at least avoids iterating and looping through the object and moves it to the C level.
a) Open the "php.ini". For XAMPP,it is located in C:\XAMPP\php\php.ini. Find out if you are using WAMP or LAMP server. Note : Make a backup of php.ini file
b) Search [mail function] in the php.ini file.
You can find like below.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = postmaster@localhost
Change the localhost to the smtp server name of your ISP. No need to change the smtp_port. Leave it as 25. Change sendmail_from from postmaster@localhost to your domain email address which will be used as from address..
So for me, it will become like this.
[mail function]
; For Win32 only.
SMTP = smtp.planetghost.com
smtp_port = 25
; For Win32 only.
sendmail_from = [email protected]
auth_username = [email protected]
auth_password = example_password
c) Restart the XAMPP or WAMP(apache server) so that changes will start working.
d) Now try to send the mail using the mail() function ,
mail("[email protected]","Success","Great, Localhost Mail works");
================================================================================
Another way
Gmail servers use SMTP Authentication under SSL. I think that there is no way to use the mail() function under that circumstances, so you might want to check these alternatives:
They both support SMTP auth under SSL.
Credit : Check reference answer here
use this function to get the capture image path
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Uri mImageCaptureUri = intent.getData();
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
System.out.println(mImageCaptureUri);
//getImgPath(mImageCaptureUri);// it will return the Capture image path
}
}
public String getImgPath(Uri uri) {
String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
} finally {
myCursor.close();
}
return largeImagePath;
}
Curly braces are always needed for accessing array elements and carrying out brace expansion.
It's good to be not over-cautious and use {}
for shell variable expansion even when there is no scope for ambiguity.
For example:
dir=log
prog=foo
path=/var/${dir}/${prog} # excessive use of {}, not needed since / can't be a part of a shell variable name
logfile=${path}/${prog}.log # same as above, . can't be a part of a shell variable name
path_copy=${path} # {} is totally unnecessary
archive=${logfile}_arch # {} is needed since _ can be a part of shell variable name
So, it is better to write the three lines as:
path=/var/$dir/$prog
logfile=$path/$prog.log
path_copy=$path
which is definitely more readable.
Since a variable name can't start with a digit, shell doesn't need {}
around numbered variables (like $1
, $2
etc.) unless such expansion is followed by a digit. That's too subtle and it does make to explicitly use {}
in such contexts:
set app # set $1 to app
fruit=$1le # sets fruit to apple, but confusing
fruit=${1}le # sets fruit to apple, makes the intention clear
See:
This was an old question, but existing answers ignore the serious issue of throwing away any custom attributes when you regenerate the model. I am adding a more detailed answer to cover the current options available.
[DisplayName("Name goes here")]
attribute to the data model class. The downside is that this is thrown away whenever you regenerate the data models.Html.LabelFor
. e.g. @Html.LabelFor(model => model.SomekingStatus, "My New Label", new { @class = "control-label"})
Reference: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.labelextensions.labelfor(v=vs.118).aspx The downside to this is that you must repeat the label in every view.Microsoft allows for decorating properties on an Entity Framework class, without modifying the existing class! This by having meta-data classes that attach to your database classes (effectively a sideways extension of your EF class). This allow attributes to be added to the associated class and not to the class itself so the changes are not lost when you regenerate the data models.
For example, if your data class is MyModel
with a SomekingStatus
property, you could do it like this:
First declare a partial class of the same name (and using the same namespace), which allows you to add a class attribute without being overridden:
[MetadataType(typeof(MyModelMetaData))]
public partial class MyModel
{
}
All generated data model classes are partial classes, which allow you to add extra properties and methods by simply creating more classes of the same name (this is very handy and I often use it e.g. to provide formatted string versions of other field types in the model).
Step 2: add a metatadata class referenced by your new partial class:
public class MyModelMetaData
{
// Apply DisplayNameAttribute (or any other attributes)
[DisplayName("My New Label")]
public string SomekingStatus;
}
[required]
etc) so you may need to duplicate those in the Meta-data class.Compare day only (ignoring time component):
Date.prototype.sameDay = function(d) {
return this.getFullYear() === d.getFullYear()
&& this.getDate() === d.getDate()
&& this.getMonth() === d.getMonth();
}
Usage:
if(date1.sameDay(date2)) {
// highlight day on calendar or something else clever
}
I no longer recommend modifying the prototype
of built-in objects. Try this instead:
function isSameDay(d1, d2) {
return d1.getFullYear() === d2.getFullYear() &&
d1.getDate() === d2.getDate() &&
d1.getMonth() === d2.getMonth();
}
console.log(isSameDay(new Date('Jan 15 2021 02:39:53 GMT-0800'), new Date('Jan 15 2021 23:39:53 GMT-0800')));
console.log(isSameDay(new Date('Jan 15 2021 10:39:53 GMT-0800'), new Date('Jan 16 2021 10:39:53 GMT-0800')));
_x000D_
N.B. the year/month/day will be returned for your timezone; I recommend using a timezone-aware library if you want to check if two dates are on the same day in a different timezone.
e.g.
> (new Date('Jan 15 2021 01:39:53 Z')).getDate() // Jan 15 in UTC
14 // Returns "14" because I'm in GMT-08
Based on Haim's answer I created a PHP code to test and display all the differences between two databases. This will also display if a table is present in source or test databases. You have to change with your details the <> variables content.
<?php
$User = "<DatabaseUser>";
$Pass = "<DatabasePassword>";
$SourceDB = "<SourceDatabase>";
$TestDB = "<DatabaseToTest>";
$link = new mysqli( "p:". "localhost", $User, $Pass, "" );
if ( mysqli_connect_error() ) {
die('Connect Error ('. mysqli_connect_errno() .') '. mysqli_connect_error());
}
mysqli_set_charset( $link, "utf8" );
mb_language( "uni" );
mb_internal_encoding( "UTF-8" );
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $SourceDB .'";';
$SourceDB_Content = query( $link, $sQuery );
if ( !is_array( $SourceDB_Content) ) {
echo "Table $SourceDB cannot be accessed";
exit(0);
}
$sQuery = 'SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'. $TestDB .'";';
$TestDB_Content = query( $link, $sQuery );
if ( !is_array( $TestDB_Content) ) {
echo "Table $TestDB cannot be accessed";
exit(0);
}
$SourceDB_Tables = array();
foreach( $SourceDB_Content as $item ) {
$SourceDB_Tables[] = $item["TABLE_NAME"];
}
$TestDB_Tables = array();
foreach( $TestDB_Content as $item ) {
$TestDB_Tables[] = $item["TABLE_NAME"];
}
//var_dump( $SourceDB_Tables, $TestDB_Tables );
$LookupTables = array_merge( $SourceDB_Tables, $TestDB_Tables );
$NoOfDiscrepancies = 0;
echo "
<table border='1' width='100%'>
<tr>
<td>Table</td>
<td>Found in $SourceDB (". count( $SourceDB_Tables ) .")</td>
<td>Found in $TestDB (". count( $TestDB_Tables ) .")</td>
<td>Test result</td>
<tr>
";
foreach( $LookupTables as $table ) {
$FoundInSourceDB = in_array( $table, $SourceDB_Tables ) ? 1 : 0;
$FoundInTestDB = in_array( $table, $TestDB_Tables ) ? 1 : 0;
echo "
<tr>
<td>$table</td>
<td><input type='checkbox' ". ($FoundInSourceDB == 1 ? "checked" : "") ."></td>
<td><input type='checkbox' ". ($FoundInTestDB == 1 ? "checked" : "") ."></td>
<td>". compareTables( $SourceDB, $TestDB, $table ) ."</td>
</tr>
";
}
echo "
</table>
<br><br>
No of discrepancies found: $NoOfDiscrepancies
";
function query( $link, $q ) {
$result = mysqli_query( $link, $q );
$errors = mysqli_error($link);
if ( $errors > "" ) {
echo $errors;
exit(0);
}
if( $result == false ) return false;
else if ( $result === true ) return true;
else {
$rset = array();
while ( $row = mysqli_fetch_assoc( $result ) ) {
$rset[] = $row;
}
return $rset;
}
}
function compareTables( $source, $test, $table ) {
global $link;
global $NoOfDiscrepancies;
$sQuery = "
SELECT column_name,ordinal_position,data_type,column_type FROM
(
SELECT
column_name,ordinal_position,
data_type,column_type,COUNT(1) rowcount
FROM information_schema.columns
WHERE
(
(table_schema='$source' AND table_name='$table') OR
(table_schema='$test' AND table_name='$table')
)
AND table_name IN ('$table')
GROUP BY
column_name,ordinal_position,
data_type,column_type
HAVING COUNT(1)=1
) A;
";
$result = query( $link, $sQuery );
$data = "";
if( is_array( $result ) && count( $result ) > 0 ) {
$NoOfDiscrepancies++;
$data = "<table><tr><td>column_name</td><td>ordinal_position</td><td>data_type</td><td>column_type</td></tr>";
foreach( $result as $item ) {
$data .= "<tr><td>". $item["column_name"] ."</td><td>". $item["ordinal_position"] ."</td><td>". $item["data_type"] ."</td><td>". $item["column_type"] ."</td></tr>";
}
$data .= "</table>";
return $data;
}
else {
return "Checked but no discrepancies found!";
}
}
?>
The error may occur when the number of times you iterate the array is greater than the actual size of the array. for example:
$one="909";
for($i=0;$i<10;$i++)
echo ' '.$one[$i];
will show the error. first case u can take the mod of i.. for example
function mod($i,$length){
$m = $i % $size;
if ($m > $size)
mod($m,$size)
return $m;
}
for($i=0;$i<10;$i++)
{
$k=mod($i,3);
echo ' '.$one[$k];
}
or might be it not an array (maybe it was a value and you tried to access it like an array) for example:
$k = 2;
$k[0];
You can download a list of symbols from here. You have an option to download the whole list directly into excel file. You will have to register though.
You use the ajaxStop to execute code when the ajax are completed:
$(document).ajaxStop(function(){
setTimeout("window.location = 'otherpage.html'",100);
});
You can use Google's Gson library to convert json to Hashmap. Try below code
String jsonString = "Your JSON string";
HashMap<String,String> map = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, String>>(){}.getType());
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
Create PROCEDURE Stored_Procedure_Name_2
(
@param1 int = 5 ,
@param2 varchar(max),
@param3 varchar(max)
)
AS
DECLARE @Table TABLE
(
/*TABLE DEFINITION*/
id int,
name varchar(max),
address varchar(max)
)
INSERT INTO @Table
EXEC Stored_Procedure_Name_1 @param1 , @param2 = 'Raju' ,@param3 =@param3
SELECT id ,name ,address FROM @Table
You can use find
to find all matching files recursively:
$ find . -iname "*dbg*" -exec rename _dbg.txt .txt '{}' \;
EDIT: what the '{}'
and \;
are?
The -exec
argument makes find execute rename
for every matching file found. '{}'
will be replaced with the path name of the file. The last token, \;
is there only to mark the end of the exec expression.
All that is described nicely in the man page for find:
-exec utility [argument ...] ;
True if the program named utility returns a zero value as its
exit status. Optional arguments may be passed to the utility.
The expression must be terminated by a semicolon (``;''). If you
invoke find from a shell you may need to quote the semicolon if
the shell would otherwise treat it as a control operator. If the
string ``{}'' appears anywhere in the utility name or the argu-
ments it is replaced by the pathname of the current file.
Utility will be executed from the directory from which find was
executed. Utility and arguments are not subject to the further
expansion of shell patterns and constructs.
If you use enterprise computer and unable to access system environments
use RapidEE to edit user variables then add to path these
%AppData%\npm
or
%USERPROFILE%\AppData\Roaming\npm
it worked for me on windows
In order to prepend a key-value pair to an object so the for in works with that element first do this:
var nwrow = {'newkey': 'value' };
for(var column in row){
nwrow[column] = row[column];
}
row = nwrow;
The answers so far tell you how to find existing branches:
git branch -r
Or repositories for the same project [see note below]:
git remote -v
There is another case. You might want to know about other project repositories hosted on the same server.
To discover that information, I use SSH or PuTTY to log into to host and ls
to find the directories containing the other repositories. For example, if I cloned a repository by typing:
git clone ssh://git.mycompany.com/git/ABCProject
and want to know what else is available, I log into git.mycompany.com via SSH or PuTTY and type:
ls /git
assuming ls
says:
ABCProject DEFProject
I can use the command
git clone ssh://git.mycompany.com/git/DEFProject
to gain access to the other project.
NOTE: Usually
git remote
simply tells me aboutorigin
-- the repository from which I cloned the project.git remote
would be handy if you were collaborating with two or more people working on the same project and accessing each other's repositories directly rather than passing everything through origin.
UPDATE 2:
See this answer . - 2019-11-05
You can also now have it auto-open Developer Tools in Pop-ups if they were open where you opened them from. For example, if you do not have Dev Tools open and you get a popup, it won't open with Dev Tools. But if you Have Dev Tools Open and then you click something, the popup will have Dev-Tools Automatically opened.
UPDATE:
Time has changed, you can now use --auto-open-devtools-for-tabs as in this answer – Wouter Huysentruit May 18 at 11:08
OP:
I played around with the startup string for Chrome on execute, but couldn't get it to persist to new tabs.
I also thought about a defined PATH method that you could invoke from prompt. This is possible with the SendKeys command, but again, only on a new instance. And DevTools doesn't persist to new tabs.
Browsing the Google Product Forums, there doesn't seem to be a built-in way to do this in Chrome. You'll have to use a keystroke solution or F12 as mentioned above.
I recommended it as a feature. I know I'm not the first either.
Something along the lines of...
$('select option:nth(1)').attr("selected","selected");
Maybe a bit late, but I found this answer looking over the internet. It could help others with the same problem.
$sudo mysql -u root
[mysql] use mysql;
[mysql] update user set plugin='' where User='root';
[mysql] flush privileges;
[mysql] \q
Now you should be able to log in as root in phpmyadmin.
(Found here.)
You can read multiple variables from file like this:
for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H
where param.txt:
PARAM1=value1
PARAM2=value2
...
Don't check File.Exists()
like that. In fact, the whole thing is over-complicated. This should do what you need:
Dim strFile As String = $@"C:\ErrorLog_{DateTime.Today:dd-MMM-yyyy}.txt"
File.AppendAllText(strFile, $"Error Message in Occured at-- {DateTime.Now}{Environment.NewLine}")
Got it all down to two lines of code :)
This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout
.
someView.layoutParams = LinearLayout.LayoutParams(100, 200)
This allows to set the width and height (100
and 200
) in a single line.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<gradient
android:endColor="@color/color1"
android:gradientRadius="250dp"
android:startColor="#8F15DA"
android:type="radial" />
<corners
android:bottomLeftRadius="50dp"
android:bottomRightRadius="50dp"
android:radius="3dp"
android:topLeftRadius="0dp"
android:topRightRadius="50dp" />
</shape>
TLDR; Pandas groupby.agg
has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use
df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))
Mean Sum
dummy
1 0.036901 0.369012
OR
df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')
Mean Sum
dummy
1 0.036901 0.369012
Pandas has changed the behavior of GroupBy.agg
in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.
From the documentation,
To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in
GroupBy.agg()
, known as “named aggregation”, where
- The keywords are the output column names
- The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.
You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>)
.
import pandas as pd
pd.__version__
# '0.25.0.dev0+840.g989f912ee'
# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
'height': [9.1, 6.0, 9.5, 34.0],
'weight': [7.9, 7.5, 9.9, 198.0]
})
df.groupby('kind').agg(
max_height=('height', 'max'), min_weight=('weight', 'min'),)
max_height min_weight
kind
cat 9.5 7.9
dog 34.0 7.5
Alternatively, you can use pd.NamedAgg
(essentially a namedtuple) which makes things more explicit.
df.groupby('kind').agg(
max_height=pd.NamedAgg(column='height', aggfunc='max'),
min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)
max_height min_weight
kind
cat 9.5 7.9
dog 34.0 7.5
It is even simpler for Series, just pass the aggfunc to a keyword argument.
df.groupby('kind')['height'].agg(max_height='max', min_height='min')
max_height min_height
kind
cat 9.5 9.1
dog 34.0 6.0
Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:
df.groupby('kind')['height'].agg(**{'max height': 'max', ...})
In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning
:
df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed
# in a future version
Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.
df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})
returns
op1 op2
dummy
1 0.328953 0.032895
Or,
df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])
op1 op2
dummy
1 0.328953 0.032895
Try to create a new database and import every table, query etc into this new database. With this import Access recreates all the objects from scratch. If there is some sort of corruption in an object, it should be solved.
If you're Lucky only the corrupted item(s) will be lost, if any.
I made something simular, a RatingBar with individual rating icons, I'm using VectorDrawables for the rating icons but you could use any type of drawable
The matrix you pasted
[[ 1, 8, 50],
[ 8, 64, 400],
[ 50, 400, 2500]]
Has a determinant of zero. This is the definition of a Singular matrix (one for which an inverse does not exist)
There are two problems on our way to the absolute path:
The following code will give us all useful paths:
URL localPackage = this.getClass().getResource("");
URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
String localDir = localPackage.getPath();
String loaderDir = urlLoader.getPath();
System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);
Here both functions that can be used for localization of the resource folder are researched. As for class
, it can be got in either way, statically or dynamically.
If the project is not in the plugin, the code if run in JUnit, will print:
loaderDir = /C:.../ws/source.dir/target/test-classes/
localDir = /C:.../ws/source.dir/target/test-classes/package/
So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName)
, for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.
If the class is in the package that is in the plugin, the output of the same test will be:
loaderDir = /C:.../ws/plugin/bin/
localDir = /C:.../ws/plugin/bin/package/
So, again we should go up and down the folder tree.
The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:
loaderDir = /C:.../ws/plugin/
localDir = /package/
Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src
or src/test/resource
here.
You can insert the code into yours and see the paths that you have.
Using numpy, you can do:
y = x.astype(int)
If you were using a non-numpy array, you could use a list comprehension:
y = [int(val) for val in x]
The Wikipedia page on sorting algorithms has a great comparison chart.
http://en.wikipedia.org/wiki/Sorting_algorithm#Comparison_of_algorithms
This line solved my problem:
<%#DateTime.Parse(Eval("DDDate").ToString()).ToString("dd-MM-yyyy")%>
My simple solution:
npm install --save-dev babel-plugin-transform-runtime
npm install --save-dev babel-plugin-transform-async-to-generator
.babelrc
{
"presets": [
["latest", {
"es2015": {
"loose": true
}
}],
"react",
"stage-0"
],
"plugins": [
"transform-runtime",
"transform-async-to-generator"
]
}
If you have just a few places where you wish to create this effect, you can use the following html code that requires no css. Just insert it.
<a href="TARGET URL GOES HERE"><img src="URL OF FIRST IMAGE GOES HERE"
onmouseover="this.src='URL OF IMAGE ON HOVER GOES HERE'"
onmouseout="this.src='URL OF FIRST IMAGE GOES HERE AGAIN'" /></A>
Be sure to write the quote marks exactly as they are here, or it will not work.
I had the same problem and it was due to me not declaring the blank object first at the top of my controller:
$scope.model = {}
<input ng-model="model.firstProperty">
Hope this will works for you!
My favorite method to use would be the BorderLayout method. Here are the five examples with each position the component could go in. The example is for if the component were a button. We will add it to a JPanel, p. The button will be called b.
//To align it to the left
p.add(b, BorderLayout.WEST);
//To align it to the right
p.add(b, BorderLayout.EAST);
//To align it at the top
p.add(b, BorderLayout.NORTH);
//To align it to the bottom
p.add(b, BorderLayout.SOUTH);
//To align it to the center
p.add(b, BorderLayout.CENTER);
Don't forget to import it as well by typing:
import java.awt.BorderLayout;
There are also other methods in the BorderLayout class involving things like orientation, but you can do your own research on that if you curious about that. I hope this helped!
const getFirstWord = string => {
const firstWord = [];
for (let i = 0; i < string.length; i += 1) {
if (string[i] === ' ') break;
firstWord.push(string[i]);
}
return firstWord.join('');
};
console.log(getFirstWord('Hello World'));
or simplify it:
const getFirstWord = string => {
const words = string.split(' ');
return words[0];
};
console.log(getFirstWord('Hello World'));
Visual C++ 2013 Update 5 Redistributable Package fixed issue for me. Download link:
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
if you have this error when you ionic run android --device
## codova - android update
npm install -g cordova
cordova platform update android
(gdb) maintenance info sections
Exec file:
`/path/to/app.out', file type elf32-littlearm.
0x0000->0x0360 at 0x00008000: .intvecs ALLOC LOAD READONLY DATA HAS_CONTENTS
This is from comment by phihag above, deserves a separate answer. This works but info proc
does not on the arm-none-eabi-gdb v7.4.1.20130913-cvs from the gcc-arm-none-eabi Ubuntu package.
You can do it using write() :
#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()
You can write a script like this:
cd /X/Y
git pull
You can name it something like gitpull
.
If you'd rather have it do arbitrary directories instead of /X/Y
:
cd $1
git pull
Then you can call it with gitpull /X/Z
Lastly, you can try finding repositories. I have a ~/git
folder which contains repositories, and you can use this to do a pull on all of them.
g=`find /X -name .git`
for repo in ${g[@]}
do
cd ${repo}
cd ..
git pull
done
In Rails 4, simply use
.hero {
background-image: url("picture.jpg");
}
Or if it's from a database context you can use
@Html.DropDownListFor(model => model.MyOption, db.MyOptions.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }))
If you wrapped your divs, like this:
<div id="main">
<div id="sidebar"></div>
<div id="page-wrap"></div>
</div>
You could use this styling:
#main {
width: 800px;
margin: 0 auto;
}
#sidebar {
width: 200px;
height: 400px;
background: red;
float: left;
}
#page-wrap {
width: 600px;
background: #ffffff;
height: 400px;
margin-left: 200px;
}
This is a slightly different look though, so I'm not sure it's what you're after. This would center all 800px
as a unit, not the 600px
centered with the 200px
on the left side. The basic approach is your sidebar floats left, but inside the main div, and the #page-wrap
has the width of your sidebar as it's left margin to move that far over.
Update based on comments: For this off-centered look, you can do this:
<div id="page-wrap">
<div id="sidebar"></div>
</div>
With this styling:
#sidebar {
position: absolute;
left: -200px;
width: 200px;
height: 400px;
background: red;
}
#page-wrap {
position: relative;
width: 600px;
background: #ffffff;
height: 400px;
margin: 0 auto;
}
If you are using eclipse, you can follow the steps here (maven in 5 min not working) for getting your proxy information. Once done follow the steps below:
C:\apache-maven-3.1.0\conf\
settings.xml
to C:\Users\[UserFolder]\.m2
Modify the proxy in settings.xml
based on the info that you get from the above link.
<proxy> <active>true</active> <protocol>http</protocol> <host>your proxy</host> <port>your port</port> </proxy>
Open eclipse
Go to: Windows > Preferences > Maven > User Settings
Browse the settings.xml
from .m2
folder
Click Update Settings
Click Reindex
Apply the changes and Click OK
You can now try to create Maven Project in Eclipse
you should use this code:
$json = json_encode(array_map('utf8_encode', $arr))
array_map function converts special characters in UTF8 standard
A local variable is memory on the stack, that memory is not automatically invalidated when you go out of scope. From a Function deeper nested (higher on the stack in memory), its perfectly safe to access this memory.
Once the Function returns and ends though, things get dangerous. Usually the memory is not deleted or overwritten when you return, meaning the memory at that adresss is still containing your data - the pointer seems valid.
Until another function builds up the stack and overwrites it. This is why this can work for a while - and then suddenly cease to function after one particularly deeply nested set of functions, or a function with really huge sized or many local objects, reaches that stack-memory again.
It even can happen that you reach the same program part again, and overwrite your old local function variable with the new function variable. All this is very dangerous and should be heavily discouraged. Do not use pointers to local objects!
MYSQL 8.0:
Search my.ini
in disk, we will find this folder:
C:\ProgramData\MySQL\MySQL Server 8.0
It'sProgramData
, notProgram file
Data is in sub-folder: \Data
.
Each database
owns a folder, each table
is file, each index
is 1+ files.
I often just open the console and look for the solution in the objects methods. Quite often it's already there:
>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello s'
Short answer: Use string.replace()
.
You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams>
and you are passing var model = tm.Name.ToList();
name list. You have to pass list of Teams.
You have to pass following model
var model = new List<Teams>();
model.Add(new Teams { Name = new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name = new List<string>(){"John","XYZ"} });
return View(model);
I had one availability zone where I could connect and another where I could not. After a few hours I got so frustrated that I deleted everything in that availability zone.
Building everything back I had to make sure to create EVERYTHING. This included:
CIDR: 10.0.0.0/24
Destination: 0.0.0.0/0
Target: <Internet Gateway from earlier>
CIDR: 10.0.0.0/24
Routing Table: <Routing Table from earlier
It took me a LOT of fumbling to get all of this. I've ordered the steps in the way I think might be most efficient, but you may have to adjust them to get one item available for the next.
I'm not suggesting that you go thermo nuclear as I did. I'm offering all this information so that you can check these associations to ensure yours are appropriate.
I do not have admin privileges since this machine was issued by my job.
npm config get prefix | clip
npm config get prefix
rundll32 sysdm.cpl,EditEnvironmentVariables
To tint an image, you can use CSS3 background
to stack images and a linear-gradient
. In the example below, I use a linear-gradient
with no actual gradient. The browser treats gradients as images (I think it actually generates a bitmap and overlays it) and thus, is actually stacking multiple images.
background: linear-gradient(0deg, rgba(2,173,231,0.5), rgba(2,173,231,0.5)), url(images/mba-grid-5px-bg.png) repeat;
Will yield a graph-paper with light blue tint, if you had the png. Note that the stacking order might work in reverse to your mental model, with the first item being on top.
Excellent documentation by Mozilla, here:
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_multiple_backgrounds
Tool for building the gradients:
http://www.colorzilla.com/gradient-editor/
Note - doesn't work in IE11! I'll post an update when I find out why, since its supposed to.
You need to use lambda:
button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))
I have also faced this problem. Finally I got a solution. Use this bellow code. Hope: problem will be solve.
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
To complete Sandy Chapman's answer, here is a solution in Objective-C (put this category anywhere you want to change UILabel
Appearance
):
@implementation UILabel (FontOverride)
- (void)setSubstituteFontName:(NSString *)name UI_APPEARANCE_SELECTOR {
self.font = [UIFont fontWithName:name size:self.font.pointSize];
}
@end
The interface file, should have this method declared publicly to be used later from places like your app delegate:
@interface UILabel (FontOverride)
- (void)setSubstituteFontName:(NSString *)name UI_APPEARANCE_SELECTOR;
@end
Then, you can change the Appearance
with:
[[UILabel appearance] setSubstituteFontName:@"SourceSansPro-Light"];
This should work:
cat "$API" >> "$CONFIG"
You need to use the >>
operator to append to a file. Redirecting with >
causes the file to be overwritten. (truncated).
For Sourcetree users: If you want to ignore a specific folder, just select a file from this folder, right-click on it and do "Ignore...". You will have a pop-up menu where you can ignore "Ignore everything beneath: <YOUR UNWANTED FOLDER>"
If you have the "Ignore" option greyed out, you have to select the "Stop Tracking" option. After that the file will be added to Staged files with a minus sign on red background icon and the file's icon in Unstaged files list will change to a question sign on a violet background. Now in Unstaged files list, the "Ignore" option is enabled again. Just do as described above.
Just in general, if this happens in Windows, and you are using tortoisegit, it is the status cache of tortoisegit. Kill that process and it will be freed.
If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ()
.
case
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore
But it'll be better if you show your full query to get context of what you actually need.
Check this Spring 3 WebMVC - Optional Path Variables. It shows an article of making an extension to AntPathMatcher to enable optional path variables and might be of help. All credits to Sebastian Herold for posting the article.
Try to change the compatibility level, worked for me.
Verify what level it is
USE VJ_DATABASE;
GO
SELECT compatibility_level
FROM sys.databases WHERE name = 'VJ_DATABASE';
GO
Then make it compatible with the older version
ALTER DATABASE VJ_DATABASE
SET COMPATIBILITY_LEVEL = 110;
GO
By default, Sql Server 2014 will change the db versions compatibility to only 2014, using the @@ version
you should be able to tell, which version Sql Server is.
Then run the command above to change it the version you have.
Additional step: Ensure you look at the accessibility of the DB is not reset, do this by right clicking on properties of the folder and the database. (make sure you have rights so you don't get an access denied)
Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="...">
it will work.
Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module
What you are trying to deserialize to a Dictionary is actually a Javascript object serialized to JSON. In Javascript, you can use this object as an associative array, but really it's an object, as far as the JSON standard is concerned.
So you would have no problem deserializing what you have with a standard JSON serializer (like the .net ones, DataContractJsonSerializer and JavascriptSerializer) to an object (with members called AppName, AnotherAppName, etc), but to actually interpret this as a dictionary you'll need a serializer that goes further than the Json spec, which doesn't have anything about Dictionaries as far as I know.
One such example is the one everybody uses: JSON .net
There is an other solution if you don't want to use an external lib, which is to convert your Javascript object to a list before serializing it to JSON.
var myList = [];
$.each(myObj, function(key, value) { myList.push({Key:key, Value:value}) });
now if you serialize myList to a JSON object, you should be capable of deserializing to a List<KeyValuePair<string, ValueDescription>>
with any of the aforementioned serializers. That list would then be quite obvious to convert to a dictionary.
Note: ValueDescription being this class:
public class ValueDescription
{
public string Description { get; set; }
public string Value { get; set; }
}
<div style="width:100%;">
<div style="margin-left:45px;">
<asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
</div>
</div>
Remove the spaces from the original string and split on semicolon
$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')
Or all in one line:
$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')
$addresses
becomes:
@('[email protected]','[email protected]','[email protected]')
Remember that a single =
is always an assignment in C or C++.
Your test should be if ( match == 0 && k == M )
you made a typo on the k == M
test.
If you really mean k=M
(i.e. a side-effecting assignment inside a test) you should for readability reasons code if (match == 0 && (k=m) != 0)
but most coding rules advise not writing that.
BTW, your mistake suggests to ask for all warnings (e.g. -Wall
option to g++
), and to upgrade to recent compilers. The next GCC 4.8 will give you:
% g++-trunk -Wall -c ederman.cc
ederman.cc: In function ‘void foo()’:
ederman.cc:9:30: error: lvalue required as left operand of assignment
if ( match == 0 && k = M )
^
and Clang 3.1 also tells you ederman.cc:9:30: error: expression is not assignable
So use recent versions of free compilers and enable all the warnings when using them.
Maybe late, but this is how i solved it: http://jsfiddle.net/KqsK2/18/
$(document).ready(function() {
fixSelect(document.getElementsByTagName("select"));
});
function fixSelect(selectList)
{
for (var i = 0; i != selectList.length; i++)
{
setActions(selectList[i]);
}
}
function setActions(select)
{
$(select).click(function() {
if (select.getElementsByTagName("option").length == 1)
{
active(select);
}
});
$(select).focus(function() {
active(select);
});
$(select).blur(function() {
inaktiv(select);
});
$(select).keypress(function(e) {
if (e.which == 13) {
inaktiv(select);
}
});
var optionList = select.getElementsByTagName("option");
for (var i = 0; i != optionList.length; i++)
{
setActionOnOption(optionList[i], select);
}
}
function setActionOnOption(option, select)
{
$(option).click(function() {
inaktiv(select);
});
}
function active(select)
{
var temp = $('<select/>');
$('<option />', {value: 1,text:$(select).find(':selected').text()}).appendTo(temp);
$(temp).insertBefore($(select));
$(select).attr('size', select.getElementsByTagName('option').length);
$(select).css('position', 'absolute');
$(select).css('margin-top', '-6px');
$(select).css({boxShadow: '2px 3px 4px #888888'});
}
function inaktiv(select)
{
if($(select).parent().children('select').length!=1)
{
select.parentNode.removeChild($(select).parent().children('select').get(0));
}
$(select).attr('size', 1);
$(select).css('position', 'static');
$(select).css({boxShadow: ''});
$(select).css('margin-top', '0px');
}
This worked for me:
<script>
jQuery.noConflict();
// Use jQuery via jQuery() instead of via $()
jQuery(document).ready(function(){
jQuery("div").hide();
});
</script>
Reason: "Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $".
Read full reason here: https://api.jquery.com/jquery.noconflict/
If this solves your issue, it's likely another library is also using $.
If it's a new project, I'd just drop the database, and create a new one with a proper charset:
CREATE DATABASE <dbname> CHARACTER SET utf8;
If you need run code after 100% loaded with image and files, test this in mounted()
:
document.onreadystatechange = () => {
if (document.readyState == "complete") {
console.log('Page completed with image and files!')
// fetch to next page or some code
}
}
More info: MDN Api onreadystatechange
As described in the above solution you should enable the user interaction first and add the tap gesture
this code has been tested using
yourlabel.isUserInteractionEnabled = true
yourlabel.addGestureRecognizer(UITapGestureRecognizer(){
//TODO
})
UPDATE:3 Now that I have upgraded to new Router, @borislemke's approach will not work if you use CanDeactivate
guard. I'm degrading to my old method, ie:
this answer
UPDATE2: Router events in new-router look promising and the answer by @borislemke seems to cover the main aspect of spinner implementation, I havent't tested it but I recommend it.
UPDATE1: I wrote this answer in the era of Old-Router
, when there used to be only one event route-changed
notified via router.subscribe()
. I also felt overload of the below approach and tried to do it using only router.subscribe()
, and it backfired because there was no way to detect canceled navigation
. So I had to revert back to lengthy approach(double work).
If you know your way around in Angular2, this is what you'll need
Boot.ts
import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyApp} from 'path/to/MyApp-Component';
import { SpinnerService} from 'path/to/spinner-service';
bootstrap(MyApp, [SpinnerService]);
Root Component- (MyApp)
import { Component } from '@angular/core';
import { SpinnerComponent} from 'path/to/spinner-component';
@Component({
selector: 'my-app',
directives: [SpinnerComponent],
template: `
<spinner-component></spinner-component>
<router-outlet></router-outlet>
`
})
export class MyApp { }
Spinner-Component (will subscribe to Spinner-service to change the value of active accordingly)
import {Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
selector: 'spinner-component',
'template': '<div *ngIf="active" class="spinner loading"></div>'
})
export class SpinnerComponent {
public active: boolean;
public constructor(spinner: SpinnerService) {
spinner.status.subscribe((status: boolean) => {
this.active = status;
});
}
}
Spinner-Service (bootstrap this service)
Define an observable to be subscribed by spinner-component to change the status on change, and function to know and set the spinner active/inactive.
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';
@Injectable()
export class SpinnerService {
public status: Subject<boolean> = new Subject();
private _active: boolean = false;
public get active(): boolean {
return this._active;
}
public set active(v: boolean) {
this._active = v;
this.status.next(v);
}
public start(): void {
this.active = true;
}
public stop(): void {
this.active = false;
}
}
All Other Routes' Components
(sample):
import { Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
template: `<div *ngIf="!spinner.active" id="container">Nothing is Loading Now</div>`
})
export class SampleComponent {
constructor(public spinner: SpinnerService){}
ngOnInit(){
this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component
}
ngOnDestroy(){
this.spinner.start();
}
}
dict.fromkeys([1, 2, 3, 4])
This is actually a classmethod, so it works for dict-subclasses (like collections.defaultdict
) as well. The optional second argument specifies the value to use for the keys (defaults to None
.)
Solution for me (Android Studio) :
1) Use shortcut Ctrl+Shift+Alt+S or File -> Project Structure
2) and increase the level of SDK "Compile SDK Version".
You could try this:
find. -name *.ear -exec du {} \;
This will give you the size in bytes. But the du command also accepts the parameters -k for KB and -m for MB. It will give you an output like
5000 ./dir1/dir2/earFile1.ear
5400 ./dir1/dir2/earFile2.ear
5400 ./dir1/dir3/earFile1.ear
Simple PHP option:
echo 'part-that-needs-encoding' | php -R 'echo urlencode($argn);'
FWIW, I had what I think is a related problem and came up with a workaround: I wrote a Chrome Extension that did an document.execCommand('paste') into a textarea with focus on window unload in order to populate the element with the system clipboard contents. This worked 100% of the time manually, but the execCommand returned false almost all the time when run under Selenium.
I added a driver.refresh() after the initial driver.get( myChromeExtensionURL ), and now it works 100% of the time. This was with Selenium driver version 2.16.333243 and Chrome version 43 on Mac OS 10.9.
When I was researching the problem, I didn't see any mentions of this workaround, so I thought I'd document my discovery for those following in my Selenium/focus/execCommand('paste') footsteps.
I composed this code as an example. Hope the idea works!
<?php
$friends = array('Robert', 'Louis', 'Ferdinand');
function greetings($friends){
echo "Greetings, $friends <br>";
}
foreach ($friends as $friend) {
greetings($friend);
}
?>
I had the same problem, I use PyCharm as an editor and when I created the project, PyCharm created a Flask Server. What I did was create a server with Python in the following way;
basically what I did was create a new server but flask if not python
I hope it helps you
Here is some relevant code:
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
// Now you can access an https URL without having the certificate in the truststore
try {
URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}
This will completely disable SSL checking—just don't learn exception handling from such code!
To do what you want, you would have to implement a check in your TrustManager that prompts the user.
There's the NUMBERFORMATTER jQuery plugin, details below:
https://code.google.com/p/jquery-numberformatter/
From the above link:
This plugin is a NumberFormatter plugin. Number formatting is likely familiar to anyone who's worked with server-side code like Java or PHP and who has worked with internationalization.
EDIT: Replaced the link with a more direct one.
My point is that I just want the raw DATETIME string, so I can parse it myself as is.
That makes me think that your "workaround" is not a workaround, but in fact the only way to get the value from the database into your code:
SELECT CAST(add_date AS CHAR) as add_date
By the way, some more notes from the MySQL documentation:
MySQL Constraints on Invalid Data:
Before MySQL 5.0.2, MySQL is forgiving of illegal or improper data values and coerces them to legal values for data entry. In MySQL 5.0.2 and up, that remains the default behavior, but you can change the server SQL mode to select more traditional treatment of bad values such that the server rejects them and aborts the statement in which they occur.
[..]
If you try to store NULL into a column that doesn't take NULL values, an error occurs for single-row INSERT statements. For multiple-row INSERT statements or for INSERT INTO ... SELECT statements, MySQL Server stores the implicit default value for the column data type.
MySQL 5.x Date and Time Types:
MySQL also allows you to store '0000-00-00' as a “dummy date” (if you are not using the NO_ZERO_DATE SQL mode). This is in some cases more convenient (and uses less data and index space) than using NULL values.
[..]
By default, when MySQL encounters a value for a date or time type that is out of range or otherwise illegal for the type (as described at the beginning of this section), it converts the value to the “zero” value for that type.
Based on W3schools default transition value is: all 0s ease 0s
, which should be the cross-browser compatible way of disabling the transition.
Here is a link: https://www.w3schools.com/cssref/css3_pr_transition.asp
first of all you should define an .xml file and make keyboard UI in it:
<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
android:keyWidth="12.50%p"
android:keyHeight="7%p">
<!--
android:horizontalGap="0.50%p"
android:verticalGap="0.50%p"
NOTE When we add a horizontalGap in pixels, this interferes with keyWidth in percentages adding up to 100%
NOTE When we have a horizontalGap (on Keyboard level) of 0, this make the horizontalGap (on Key level) to move from after the key to before the key... (I consider this a bug)
-->
<Row>
<Key android:codes="-5" android:keyLabel="remove" android:keyEdgeFlags="left" />
<Key android:codes="48" android:keyLabel="0" />
<Key android:codes="55006" android:keyLabel="clear" />
</Row>
<Row>
<Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left" />
<Key android:codes="50" android:keyLabel="2" />
<Key android:codes="51" android:keyLabel="3" />
</Row>
<Row>
<Key android:codes="52" android:keyLabel="4" android:keyEdgeFlags="left" />
<Key android:codes="53" android:keyLabel="5" />
<Key android:codes="54" android:keyLabel="6" />
</Row>
<Row>
<Key android:codes="55" android:keyLabel="7" android:keyEdgeFlags="left" />
<Key android:codes="56" android:keyLabel="8" />
<Key android:codes="57" android:keyLabel="9" />
</Row>
In this example you have 4 rows and in each row you have 3 keys. also you can put an icon in each key you want.
Then you should add xml tag in your activity UI like this:
<android.inputmethodservice.KeyboardView
android:id="@+id/keyboardview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/white"
android:focusable="true"
android:focusableInTouchMode="true"
android:visibility="visible" />
Also in your .java activity file you should define the keyboard and assign it to a EditText:
CustomKeyboard mCustomKeyboard1 = new CustomKeyboard(this,
R.id.keyboardview1, R.xml.horizontal_keyboard);
mCustomKeyboard1.registerEditText(R.id.inputSearch);
This code asign inputSearch (which is a EditText) to your keyboard.
import android.app.Activity;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
import android.text.Editable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class CustomKeyboard {
/** A link to the KeyboardView that is used to render this CustomKeyboard. */
private KeyboardView mKeyboardView;
/** A link to the activity that hosts the {@link #mKeyboardView}. */
private Activity mHostActivity;
/** The key (code) handler. */
private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {
public final static int CodeDelete = -5; // Keyboard.KEYCODE_DELETE
public final static int CodeCancel = -3; // Keyboard.KEYCODE_CANCEL
public final static int CodePrev = 55000;
public final static int CodeAllLeft = 55001;
public final static int CodeLeft = 55002;
public final static int CodeRight = 55003;
public final static int CodeAllRight = 55004;
public final static int CodeNext = 55005;
public final static int CodeClear = 55006;
@Override
public void onKey(int primaryCode, int[] keyCodes) {
// NOTE We can say '<Key android:codes="49,50" ... >' in the xml
// file; all codes come in keyCodes, the first in this list in
// primaryCode
// Get the EditText and its Editable
View focusCurrent = mHostActivity.getWindow().getCurrentFocus();
if (focusCurrent == null
|| focusCurrent.getClass() != EditText.class)
return;
EditText edittext = (EditText) focusCurrent;
Editable editable = edittext.getText();
int start = edittext.getSelectionStart();
// Apply the key to the edittext
if (primaryCode == CodeCancel) {
hideCustomKeyboard();
} else if (primaryCode == CodeDelete) {
if (editable != null && start > 0)
editable.delete(start - 1, start);
} else if (primaryCode == CodeClear) {
if (editable != null)
editable.clear();
} else if (primaryCode == CodeLeft) {
if (start > 0)
edittext.setSelection(start - 1);
} else if (primaryCode == CodeRight) {
if (start < edittext.length())
edittext.setSelection(start + 1);
} else if (primaryCode == CodeAllLeft) {
edittext.setSelection(0);
} else if (primaryCode == CodeAllRight) {
edittext.setSelection(edittext.length());
} else if (primaryCode == CodePrev) {
View focusNew = edittext.focusSearch(View.FOCUS_BACKWARD);
if (focusNew != null)
focusNew.requestFocus();
} else if (primaryCode == CodeNext) {
View focusNew = edittext.focusSearch(View.FOCUS_FORWARD);
if (focusNew != null)
focusNew.requestFocus();
} else { // insert character
editable.insert(start, Character.toString((char) primaryCode));
}
}
@Override
public void onPress(int arg0) {
}
@Override
public void onRelease(int primaryCode) {
}
@Override
public void onText(CharSequence text) {
}
@Override
public void swipeDown() {
}
@Override
public void swipeLeft() {
}
@Override
public void swipeRight() {
}
@Override
public void swipeUp() {
}
};
/**
* Create a custom keyboard, that uses the KeyboardView (with resource id
* <var>viewid</var>) of the <var>host</var> activity, and load the keyboard
* layout from xml file <var>layoutid</var> (see {@link Keyboard} for
* description). Note that the <var>host</var> activity must have a
* <var>KeyboardView</var> in its layout (typically aligned with the bottom
* of the activity). Note that the keyboard layout xml file may include key
* codes for navigation; see the constants in this class for their values.
* Note that to enable EditText's to use this custom keyboard, call the
* {@link #registerEditText(int)}.
*
* @param host
* The hosting activity.
* @param viewid
* The id of the KeyboardView.
* @param layoutid
* The id of the xml file containing the keyboard layout.
*/
public CustomKeyboard(Activity host, int viewid, int layoutid) {
mHostActivity = host;
mKeyboardView = (KeyboardView) mHostActivity.findViewById(viewid);
mKeyboardView.setKeyboard(new Keyboard(mHostActivity, layoutid));
mKeyboardView.setPreviewEnabled(false); // NOTE Do not show the preview
// balloons
mKeyboardView.setOnKeyboardActionListener(mOnKeyboardActionListener);
// Hide the standard keyboard initially
mHostActivity.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
/** Returns whether the CustomKeyboard is visible. */
public boolean isCustomKeyboardVisible() {
return mKeyboardView.getVisibility() == View.VISIBLE;
}
/**
* Make the CustomKeyboard visible, and hide the system keyboard for view v.
*/
public void showCustomKeyboard(View v) {
mKeyboardView.setVisibility(View.VISIBLE);
mKeyboardView.setEnabled(true);
if (v != null)
((InputMethodManager) mHostActivity
.getSystemService(Activity.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
/** Make the CustomKeyboard invisible. */
public void hideCustomKeyboard() {
mKeyboardView.setVisibility(View.GONE);
mKeyboardView.setEnabled(false);
}
/**
* Register <var>EditText<var> with resource id <var>resid</var> (on the
* hosting activity) for using this custom keyboard.
*
* @param resid
* The resource id of the EditText that registers to the custom
* keyboard.
*/
public void registerEditText(int resid) {
// Find the EditText 'resid'
EditText edittext = (EditText) mHostActivity.findViewById(resid);
// Make the custom keyboard appear
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
// NOTE By setting the on focus listener, we can show the custom
// keyboard when the edit box gets focus, but also hide it when the
// edit box loses focus
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
showCustomKeyboard(v);
else
hideCustomKeyboard();
}
});
edittext.setOnClickListener(new OnClickListener() {
// NOTE By setting the on click listener, we can show the custom
// keyboard again, by tapping on an edit box that already had focus
// (but that had the keyboard hidden).
@Override
public void onClick(View v) {
showCustomKeyboard(v);
}
});
// Disable standard keyboard hard way
// NOTE There is also an easy way:
// 'edittext.setInputType(InputType.TYPE_NULL)' (but you will not have a
// cursor, and no 'edittext.setCursorVisible(true)' doesn't work )
edittext.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
EditText edittext = (EditText) v;
int inType = edittext.getInputType(); // Backup the input type
edittext.setInputType(InputType.TYPE_NULL); // Disable standard
// keyboard
edittext.onTouchEvent(event); // Call native handler
edittext.setInputType(inType); // Restore input type
return true; // Consume touch event
}
});
// Disable spell check (hex strings look like words to Android)
edittext.setInputType(edittext.getInputType()
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}
}
// NOTE How can we change the background color of some keys (like the
// shift/ctrl/alt)?
// NOTE What does android:keyEdgeFlags do/mean
You need to execute this as a dynamic sp like
DECLARE @ExcludedList VARCHAR(MAX)
SET @ExcludedList = '3,4,22,6014'
declare @sql nvarchar(Max)
Set @sql='SELECT * FROM [A] WHERE Id NOT IN ('+@ExcludedList+')'
exec sp_executesql @sql
var bmp = new Bitmap(@"path\picture.bmp");
using( Graphics g = Graphics.FromImage( bmp ) )
{
g.DrawString( ... );
}
picturebox1.Image = bmp;
gem install shutup
then go in the current folder of your rails project and run
shutup
# this will kill the Rails process currently running
You can use the command 'shutup' every time you want
DICLAIMER: I am the creator of this gem
NOTE: if you are using rvm install the gem globally
rvm @global do gem install shutup
You can access your array keys like so:
foreach ($array as $key => $value)
fill_parent
will make the width or height of the element to be as
large as the parent element, in other words, the container.
wrap_content
will make the width or height be as large as needed to
contain the elements within it.
You can do a sort_values()
on the dataframe before you do the groupby. Pandas preserves the ordering in the groupby.
In [44]: d.head(10)
Out[44]:
name transcript exon
0 ENST00000456328 2 1
1 ENST00000450305 2 1
2 ENST00000450305 2 2
3 ENST00000450305 2 3
4 ENST00000456328 2 2
5 ENST00000450305 2 4
6 ENST00000450305 2 5
7 ENST00000456328 2 3
8 ENST00000450305 2 6
9 ENST00000488147 1 11
for _, a in d.head(10).sort_values(["transcript", "exon"]).groupby(["name", "transcript"]): print(a)
name transcript exon
1 ENST00000450305 2 1
2 ENST00000450305 2 2
3 ENST00000450305 2 3
5 ENST00000450305 2 4
6 ENST00000450305 2 5
8 ENST00000450305 2 6
name transcript exon
0 ENST00000456328 2 1
4 ENST00000456328 2 2
7 ENST00000456328 2 3
name transcript exon
9 ENST00000488147 1 11
The command setwd("~/")
should set your working directory to your home directory. You might be experiencing problems because the OS you are using does not recognise "~/"
as your home directory: this might be because of the OS, or it might be because of not having set that as your home directory elsewhere.
As you have tagged the post using RStudio:
You will now have set the folder as your working directory. Use the command getwd()
to get the working directory as it is now set, and save that as a variable string at the top of your script. Then use setwd
with that string as the argument, so that each time you run the script you use the same directory.
For example at the top of my script I would have:
work_dir <- "C:/Users/john.smith/Documents"
setwd(work_dir)
Note: You can play back the audio data only to the standard output device.
Currently, that is the mobile device speaker or a Bluetooth headset. You
cannot play sound files in the conversation audio during a call.
See official link
http://developer.android.com/guide/topics/media/mediaplayer.html
A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.
Try disabling all non-essential modules (in php.ini
), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.
If that doesn't help, you should report a php bug.
If you're transpiling and have access to ES6, you can use spread syntax which specifically applies each iterable item of an object as a discrete argument, just the way $.when()
needs it.
$.when(...deferreds).done(() => {
// do stuff
});
Another way of returning all files in subdirectories is to use the pathlib
module, introduced in Python 3.4, which provides an object oriented approach to handling filesystem paths (Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi):
from pathlib import Path
rootdir = Path('C:/Users/sid/Desktop/test')
# Return a list of regular files only, not directories
file_list = [f for f in rootdir.glob('**/*') if f.is_file()]
# For absolute paths instead of relative the current dir
file_list = [f for f in rootdir.resolve().glob('**/*') if f.is_file()]
Since Python 3.5, the glob
module also supports recursive file finding:
import os
from glob import iglob
rootdir_glob = 'C:/Users/sid/Desktop/test/**/*' # Note the added asterisks
# This will return absolute paths
file_list = [f for f in iglob(rootdir_glob, recursive=True) if os.path.isfile(f)]
The file_list
from either of the above approaches can be iterated over without the need for a nested loop:
for f in file_list:
print(f) # Replace with desired operations
function converToLocalTime(serverDate) {
var dt = new Date(Date.parse(serverDate));
var localDate = dt;
var gmt = localDate;
var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
var localNow = new Date().getTimezoneOffset(); // get the timezone
// offset in minutes
var localTime = min - localNow; // get the local time
var dateStr = new Date(localTime * 1000 * 60);
// dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return dateStr;
}
Extending @Valeh Hajiyev great and clear answer for mysqli
driver tests:
Debug your database connection using this script at the end of ./config/database.php:
/* Your db config here */
$db['default'] = array(
// ...
'dbdriver' => 'mysqli',
// ...
);
/* Connection test: */
echo '<pre>';
print_r($db['default']);
echo '</pre>';
echo 'Connecting to database: ' .$db['default']['database'];
$mysqli_connection = new MySQLi($db['default']['hostname'],
$db['default']['username'],
$db['default']['password'],
$db['default']['database']);
if ($mysqli_connection->connect_error) {
echo "Not connected, error: " . $mysqli_connection->connect_error;
}
else {
echo "Connected.";
}
die( 'file: ' .__FILE__ . ' Line: ' .__LINE__);
If you want authentication try domainname\administrator as the username.
If you don't want authentication then remove all the tickboxes in the authenticated access section of the direcory security > edit window.
Here is the one-liner version getting the client's IP address:
$ip = @$_SERVER['HTTP_CLIENT_IP'] ?: @$_SERVER['HTTP_X_FORWARDED_FOR'] ?: @$_SERVER['REMOTE_ADDR'];
Notes:
@
, it suppresses the PHP notices.Value from HTTP_X_FORWARDED_FOR
may consist multiple addresses separated by comma, so if you prefer to get the first one, you can use the following method:
current(explode(',', @$_SERVER['HTTP_X_FORWARDED_FOR']))
FileInfo fi = new FileInfo("C:\\test\\report.xlsx");
if(fi.Exists)
{
System.Diagnostics.Process.Start(@"C:\test\report.xlsx");
}
else
{
//file doesn't exist
}
below will work with any previously pushed revision, not only HEAD
for abbreviated revision hash:
git log -1 --pretty=format:%h
for long revision hash:
git log -1 --pretty=format:%H
This topic is super old, but I needed a solution that worked on desktop AND mobile and none of these seemed to work for me. Unfortunately, this is the solution I came up with that involves checking the window width and comparing it to the mobile menu breakpoint:
$( 'a.dropdown-toggle' ).on( 'click', function( e ) {
var $a = $( this ),
$parent = $a.parent( 'li' ),
mobile_bp = 767, // Default breakpoint, may need to change this.
window_width = $( window ).width(),
is_mobile = window_width <= mobile_bp;
if ( is_mobile && ! $parent.hasClass( 'open' ) ) {
e.preventDefault();
return false;
}
location.href = $a.attr( 'href' );
return true;
});
Should not enclose true with double quote " " it should be like
$(document).ready(function() {
$('input').attr('required', true);
});
Also you can use prop
jQuery(document).ready(function() {
$('input').prop('required', true);
});
Instead of true you can try required. Such as
$('input').prop('required', 'required');
The key checks for FAST REFRESH includes the following:
1) An Oracle materialized view log must be present for each base table.
2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition.
3) If there are outer joins, unique constraints must be placed on the join columns of the inner table.
No 3 is easy to miss and worth highlighting here
In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:
SELECT COUNT(id) AS theCount, `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY theCount DESC
LIMIT 20
I stumbled upon this problem during attempt to dockerise Avahi which needs to be aware of its public IP to function properly. Assigning static IP to the container is tricky due to lack of support for static IP assignment in Docker.
This article describes technique how to assign static IP to the container on Debian:
Docker service should be started with DOCKER_OPTS="--bridge=br0 --ip-masq=false --iptables=false"
. I assume that br0
bridge is already configured.
Container should be started with --cap-add=NET_ADMIN --net=bridge
Inside container pre-up ip addr flush dev eth0
in /etc/network/interfaces
can be used to dismiss IP address assigned by Docker as in following example:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
pre-up ip addr flush dev eth0
address 192.168.0.249
netmask 255.255.255.0
gateway 192.168.0.1
/etc/init.d/networking start
. Also entry script needs to edit or populate /etc/hosts
file in order to remove references to Docker-assigned IP.This is my personal solution, based on the information here (this thread):
var Divs = new Array();
var Elemns = document.getElementsByClassName("divisao");
try {
Divs = Elemns.prototype.slice.call(Elemns);
} catch(e) {
Divs = $A(Elemns);
}
Where $A was described by Gareth Davis in his post:
function $A(iterable) {
if (!iterable) return [];
if ('toArray' in Object(iterable)) return iterable.toArray();
var length = iterable.length || 0, results = new Array(length);
while (length--) results[length] = iterable[length];
return results;
}
If browser supports the best way, ok, otherwise will use the cross browser.
In Python 3, I find pathlib is the easiest way to do this. Request's response.content marries up nicely with pathlib's write_bytes.
from pathlib import Path
import requests
filename = Path('metadata.pdf')
url = 'http://www.hrecos.org//images/Data/forweb/HRTVBSH.Metadata.pdf'
response = requests.get(url)
filename.write_bytes(response.content)
The following sets up the situation I had, using table variables.
DECLARE @Object_Table TABLE
(
Id INT NOT NULL PRIMARY KEY
)
DECLARE @Link_Table TABLE
(
ObjectId INT NOT NULL,
DataId INT NOT NULL
)
DECLARE @Data_Table TABLE
(
Id INT NOT NULL Identity(1,1),
Data VARCHAR(50) NOT NULL
)
-- create two objects '1' and '2'
INSERT INTO @Object_Table (Id) VALUES (1)
INSERT INTO @Object_Table (Id) VALUES (2)
-- create some data
INSERT INTO @Data_Table (Data) VALUES ('Data One')
INSERT INTO @Data_Table (Data) VALUES ('Data Two')
-- link all data to first object
INSERT INTO @Link_Table (ObjectId, DataId)
SELECT Objects.Id, Data.Id
FROM @Object_Table AS Objects, @Data_Table AS Data
WHERE Objects.Id = 1
Thanks to another answer that pointed me towards the OUTPUT clause I can demonstrate a solution:
-- now I want to copy the data from from object 1 to object 2 without looping
INSERT INTO @Data_Table (Data)
OUTPUT 2, INSERTED.Id INTO @Link_Table (ObjectId, DataId)
SELECT Data.Data
FROM @Data_Table AS Data INNER JOIN @Link_Table AS Link ON Data.Id = Link.DataId
INNER JOIN @Object_Table AS Objects ON Link.ObjectId = Objects.Id
WHERE Objects.Id = 1
It turns out however that it is not that simple in real life because of the following error
the OUTPUT INTO clause cannot be on either side of a (primary key, foreign key) relationship
I can still OUTPUT INTO
a temp table and then finish with normal insert. So I can avoid my loop but I cannot avoid the temp table.
Only need to fill datagrid again like this:
this.XXXTableAdapter.Fill(this.DataSet.XXX);
If you use automaticlly connect from dataGridView this code create automaticlly in Form_Load()
If you guys are facing "Permission Denial: starting Intent..." error or if the app is getting crash without any reason during launching the app - Then use this single line code in Manifest
android:exported="true"
Please be careful with finish(); , if you missed out it the app getting frozen. if its mentioned the app would be a smooth launcher.
finish();
The other solution only works for two activities that are in the same application. In my case, application B doesn't know class com.example.MyExampleActivity.class
in the code, so compile will fail.
I searched on the web and found something like this below, and it works well.
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);
You can also use the setClassName method:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();
You can also pass the values from one app to another app :
Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
launchIntent.putExtra("AppID", "MY-CHILD-APP1");
launchIntent.putExtra("UserID", "MY-APP");
launchIntent.putExtra("Password", "MY-PASSWORD");
startActivity(launchIntent);
finish();
} else {
Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}
You have to enable curl with php.
Here is the instructions for same
I run this
var data = '{"rut" : "' + $('#cb_rut').val() + '" , "email" : "' + $('#email').val() + '" }';
var data = JSON.parse(data);
$.ajax({
type: 'GET',
url: 'linkserverApi',
success: function(success) {
console.log('Success!');
console.log(success);
},
error: function() {
console.log('Uh Oh!');
},
jsonp: 'jsonp'
});
And edit header in the response
'Access-Control-Allow-Methods' , 'GET, POST, PUT, DELETE'
'Access-Control-Max-Age' , '3628800'
'Access-Control-Allow-Origin', 'websiteresponseUrl'
'Content-Type', 'text/javascript; charset=utf8'
NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.
Updating Visual Studio to 'Update 2' got it working again.
Tools -> Extensions and Updates ->Visual Studio Update 2
As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.
You can achieve an expected result with requests
library as well:
import requests
url = "http://www.mywebsite.org/Data%20Set.zip"
print(f"Before: {url}")
print(f"After: {requests.utils.unquote(url)}")
Output:
$ python3 test_url_unquote.py
Before: http://www.mywebsite.org/Data%20Set.zip
After: http://www.mywebsite.org/Data Set.zip
Might be handy if you are already using requests
, without using another library for this job.
Most of my XML parsing life is spent extracting nuggets of useful information out of truckloads of XML (Amazon MWS). As such, my answer assumes you want only specific information and you know where it is located.
I find the easiest way to use XMLReader is to know which tags I want the information out of and use them. If you know the structure of the XML and it has lots of unique tags, I find that using the first case is the easy. Cases 2 and 3 are just to show you how it can be done for more complex tags. This is extremely fast; I have a discussion of speed over on What is the fastest XML parser in PHP?
The most important thing to remember when doing tag-based parsing like this is to use if ($myXML->nodeType == XMLReader::ELEMENT) {...
- which checks to be sure we're only dealing with opening nodes and not whitespace or closing nodes or whatever.
function parseMyXML ($xml) { //pass in an XML string
$myXML = new XMLReader();
$myXML->xml($xml);
while ($myXML->read()) { //start reading.
if ($myXML->nodeType == XMLReader::ELEMENT) { //only opening tags.
$tag = $myXML->name; //make $tag contain the name of the tag
switch ($tag) {
case 'Tag1': //this tag contains no child elements, only the content we need. And it's unique.
$variable = $myXML->readInnerXML(); //now variable contains the contents of tag1
break;
case 'Tag2': //this tag contains child elements, of which we only want one.
while($myXML->read()) { //so we tell it to keep reading
if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') { // and when it finds the amount tag...
$variable2 = $myXML->readInnerXML(); //...put it in $variable2.
break;
}
}
break;
case 'Tag3': //tag3 also has children, which are not unique, but we need two of the children this time.
while($myXML->read()) {
if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') {
$variable3 = $myXML->readInnerXML();
break;
} else if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Currency') {
$variable4 = $myXML->readInnerXML();
break;
}
}
break;
}
}
}
$myXML->close();
}
You should use labels attribute inside plot function and the value of this attribute should be the vector containing the values that you want for each point to have.
If you're dealing with longer strings I believe this should outperform most of the other options by reducing the number of allocated strings to either zero or one:
function trim(str, ch) {
var start = 0,
end = str.length;
while(start < end && str[start] === ch)
++start;
while(end > start && str[end - 1] === ch)
--end;
return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}
// Usage:
trim('|hello|world|', '|'); // => 'hello|world'
Or if you want to trim from a set of multiple characters:
function trimAny(str, chars) {
var start = 0,
end = str.length;
while(start < end && chars.indexOf(str[start]) >= 0)
++start;
while(end > start && chars.indexOf(str[end - 1]) >= 0)
--end;
return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}
// Usage:
trimAny('|hello|world ', [ '|', ' ' ]); // => 'hello|world'
// because '.indexOf' is used, you could also pass a string for the 2nd parameter:
trimAny('|hello| world ', '| '); // => 'hello|world'
EDIT: For fun, trim words (rather than individual characters)
// Helper function to detect if a string contains another string
// at a specific position.
// Equivalent to using `str.indexOf(substr, pos) === pos` but *should* be more efficient on longer strings as it can exit early (needs benchmarks to back this up).
function hasSubstringAt(str, substr, pos) {
var idx = 0, len = substr.length;
for (var max = str.length; idx < len; ++idx) {
if ((pos + idx) >= max || str[pos + idx] != substr[idx])
break;
}
return idx === len;
}
function trimWord(str, word) {
var start = 0,
end = str.length,
len = word.length;
while (start < end && hasSubstringAt(str, word, start))
start += word.length;
while (end > start && hasSubstringAt(str, word, end - len))
end -= word.length
return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}
// Usage:
trimWord('blahrealmessageblah', 'blah');
Your question is pretty hard to decode, but I'll try taking a stab at it.
You say:
I want to create a json object having two fields
uniqueIDofSelect
andoptionValue
in javascript.
And then you say:
I need output like
[{"selectID":2,"optionValue":"2"}, {"selectID":4,"optionvalue":"1"}]
Well, this example output doesn't have the field named uniqueIDofSelect
, it only has optionValue
.
Anyway, you are asking for array of objects...
Then in the comment to michaels answer you say:
It creates json object array. but I need only one json object.
So you don't want an array of objects?
What do you want then?
Please make up your mind.
I've never come across point 2? Can you explain why you think this affects deployment in any way. If anything maven allows you to structure your projects in a modularised way that actually allows hot fixes for bugs in a particular tier, and allows independent development of an API from the remainder of the project for example.
It is possible that you are trying to cram everything into a single module, in which case the problem isn't really maven at all, but the way you are using it.
Personally, I think the simplest approach to do an http post and get the response is to use the WebClient class. This class nicely abstracts the details. There's even a full code example in the MSDN documentation.
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx
In your case, you want the UploadData() method. (Again, a code sample is included in the documentation)
http://msdn.microsoft.com/en-us/library/tdbbwh0a(VS.80).aspx
UploadString() will probably work as well, and it abstracts it away one more level.
http://msdn.microsoft.com/en-us/library/system.net.webclient.uploadstring(VS.80).aspx
Apart from the alternative solutions that were posted here (which are correct), no one has actually answered your question by addressing what was wrong with your code.
It seems as though you were trying to implement a selection sort algorithm. I will not go into the details of how sorting works here, but I have included a few links for your reference =)
Your code was syntactically correct, but logically wrong. You were partially sorting your strings by only comparing each string with the strings that came after it. Here is a corrected version (I retained as much of your original code to illustrate what was "wrong" with it):
static String Array[]={" Hello " , " This " , "is ", "Sorting ", "Example"};
String temp;
//Keeps track of the smallest string's index
int shortestStringIndex;
public static void main(String[] args)
{
//I reduced the upper bound from Array.length to (Array.length - 1)
for(int j=0; j < Array.length - 1;j++)
{
shortestStringIndex = j;
for (int i=j+1 ; i<Array.length; i++)
{
//We keep track of the index to the smallest string
if(Array[i].trim().compareTo(Array[shortestStringIndex].trim())<0)
{
shortestStringIndex = i;
}
}
//We only swap with the smallest string
if(shortestStringIndex != j)
{
String temp = Array[j];
Array[j] = Array[shortestStringIndex];
Array[shortestStringIndex] = temp;
}
}
}
Further Reading
The problem with this approach is that its asymptotic complexity is O(n^2). In simplified words, it gets very slow as the size of the array grows (approaches infinity). You may want to read about better ways to sort data, such as quicksort.
So you are doing this a bit backwards. Typically you'd do something like this:
?<div class='article'>
Article 1
</div>
<div class='article'>
Article 2
</div>
<div class='article'>
Article 3
</div>?
And then in your jQuery:
$('.article').click(function(){
article = $(this).text(); //$(this) is what you clicked!
});?
When I see things like #search-item .search-article
, #search-item .search-article
, and #search-item .search-article
I sense you are overspecifying your CSS which makes writing concise jQuery very difficult. This should be avoided if at all possible.
Although it sounds absolutely strange, with me it mattered to capitalize the 'O' in the import path of import {Observable} from 'rxjs/Observable
. The error message with observable_1.Observable.of is not a function
stays present if I import the Observable from rxjs/observable
. Strange but I hope it helps others.
Putting this here in case I forget it later and Google it again.
In my case I wanted the extra column to have the same data for each row
Where $syncData is an array of IDs:
$syncData = array_map(fn($locationSysid) => ['other_column' => 'foo'], array_flip($syncData));
or without arrow
$syncData = array_map(function($locationSysid) {
return ['ENTITY' => 'dbo.Cli_Core'];
}, array_flip($syncData));
(array_flip means we're using the IDs as the index for the array)
<script type="text/javascript">
var options={
format: 'mm/dd/yyyy',
todayHighlight: true,
autoclose: true,
};
$('#datetimepicker').datepicker(options);
</script>
You haven't put the shared library in a location where the loader can find it. look inside the /usr/local/opencv
and /usr/local/opencv2
folders and see if either of them contains any shared libraries (files beginning in lib
and usually ending in .so
). when you find them, create a file called /etc/ld.so.conf.d/opencv.conf
and write to it the paths to the folders where the libraries are stored, one per line.
for example, if the libraries were stored under /usr/local/opencv/libopencv_core.so.2.4
then I would write this to my opencv.conf
file:
/usr/local/opencv/
Then run
sudo ldconfig -v
If you can't find the libraries, try running
sudo updatedb && locate libopencv_core.so.2.4
in a shell. You don't need to run updatedb
if you've rebooted since compiling OpenCV.
References:
About shared libraries on Linux: http://www.eyrie.org/~eagle/notes/rpath.html
About adding the OpenCV shared libraries: http://opencv.willowgarage.com/wiki/InstallGuide_Linux
I guess you want user to be redirected to ~/AreaZ
URL once (s)he has visited ~/
URL.
I'd achieve by means of the following code within your root HomeController
.
public class HomeController
{
public ActionResult Index()
{
return RedirectToAction("ActionY", "ControllerX", new { Area = "AreaZ" });
}
}
And the following route in Global.asax
.
routes.MapRoute(
"Redirection to AreaZ",
String.Empty,
new { controller = "Home ", action = "Index" }
);
singletonList can hold instance of any object. Object state can be modify.
List<Character> list = new ArrayList<Character>();
list.add('X');
list.add('Y');
System.out.println("Initial list: "+ list);
List<List<Character>> list2 = Collections.singletonList(list);
list.add('Z');
System.out.println(list);
System.out.println(list2);
We can not define unmodifiableList like above.
If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:
// prefix="prefix_text"
// If the user changes the prefix, restore the input with the prefix:
if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
document.getElementById('myInput').value = prefix;
numpy provides a simple function to do the exact same thing: supposing you have a masked array 'a', calling numpy.ma.compress_rows(a) will delete the rows containing a masked value. I guess this is much faster this way...
If you look at either of the following keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist
You can find a list of the SIDs there with various values, including where their "home paths" which includes their usernames.
I'm not sure how dependable this is and I wouldn't recommend messing about with this unless you're really sure what you're doing.
I think both are correct programming wise,
But i think your first option is more correct in an object oriented way, because in the constructor is when the object is created, and it is when the variable should initialized.
I think it is the "by the book" convention, but it is open for discussion.
Create a new Application Pool
Go to the Advanced Settings of this application pool
Set the Enable 32-Bit Application to True
Point your web application to use this new Pool
Here's a simple (Python 2.6.2) solution... which is in-line with the OP's original request (now six-months old); and should be a perfectly acceptable solution in any "programming 101" course... Hence this post.
import math
def isPrime(n):
for i in range(2, int(math.sqrt(n)+1)):
if n % i == 0:
return False;
return n>1;
print 2
for n in range(3, 50):
if isPrime(n):
print n
This simple "brute force" method is "fast enough" for numbers upto about about 16,000 on modern PC's (took about 8 seconds on my 2GHz box).
Obviously, this could be done much more efficiently, by not recalculating the primeness of every even number, or every multiple of 3, 5, 7, etc for every single number... See the Sieve of Eratosthenes (see eliben's implementation above), or even the Sieve of Atkin if you're feeling particularly brave and/or crazy.
Caveat Emptor: I'm a python noob. Please don't take anything I say as gospel.