You could use replicate
or sapply
:
R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL)))
replicate
is a wrapper for the common use of sapply
for repeated evaluation of an expression (which will usually involve random number generation).
It's because you haven't declared outchar
before you use it. That means that the compiler will assume it's a function returning an int
and taking an undefined number of undefined arguments.
You need to add a prototype pf the function before you use it:
void outchar(char); /* Prototype (declaration) of a function to be called */ int main(void) { ... } void outchar(char ch) { ... }
Note the declaration of the main
function differs from your code as well. It's actually a part of the official C specification, it must return an int
and must take either a void
argument or an int
and a char**
argument.
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
You are using the wrong iteration counter, replace inp.charAt(i)
with inp.charAt(j)
.
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
You cannot do new T()
due to type erasure. The default constructor can only be
public Navigation() { this("", "", null); }
You can create other constructors to provide default values for trigger and description. You need an concrete object of T
.
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.
You should read Working with Auto Layout Programmatically and Visual Format Language.
You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
maybe this will help you out:
or this page:
www.scala-lang.org/node/6372
What you show looks like a mesh warp. That would be straightforward using OpenGL, but "straightforward OpenGL" is like straightforward rocket science.
I wrote an iOS app for my company called Face Dancerthat's able to do 60 fps mesh warp animations of video from the built-in camera using OpenGL, but it was a lot of work. (It does funhouse mirror type changes to faces - think "fat booth" live, plus lots of other effects.)
Here's one way in XSLT 2
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"','''')"/> </xsl:template> </xsl:stylesheet>
Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <xsl:variable name="apos">'</xsl:variable> <xsl:template match="text()"> <xsl:value-of select="translate(.,'"',$apos)"/> </xsl:template> </xsl:stylesheet>
I'm not sure what you're trying to do, but here's something to consider: c();
won't do anything. c
is an instance of the class checkbox
and not a method to be called. So consider this:
public class FirstWindow extends JFrame { public FirstWindow() { checkbox c = new checkbox(); c.yourMethod(yourParameters); // call the method you made in checkbox } } public class checkbox extends JFrame { public checkbox(yourParameters) { // this is the constructor method used to initialize instance variables } public void yourMethod() // doesn't have to be void { // put your code here } }
If you must use a 2d array:
int numOfPairs = 10; String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){ for(int j = 0; j < array[i].length; j++){ array[i] = new String[2]; array[i][0] = "original word"; array[i][1] = "rearranged word"; } }
Does this give you a hint?
Look at java.lang.BigDecimal, may solve your problem.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.
Here an example:
print ('This is \x1b[31mred\x1b[0m.')
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
There should be three pages here:
I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.
I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.
You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST
submission on step 1 (and 2 if applicable).
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
This is version problem, install the right dependant version
npm uninstall node-sass
npm install [email protected]
I understand the issue with arm64 and Xcode 12 and I was able to resolve build issues by excluding the arm64 architecture for iPhone Simulator or by setting ONLY_ACTIVE_ARCH for Release scheme. However I still have problems to push my framework using pod repo push.
I found out that setting s.pod_target_xcconfig in my podspec does not apply this setting to dependencies defined in the same podspec. I can see it in the dummy App project that Cocoapods is generating during the validation. Cocoapods validation is running release scheme for simulator and this is failing when one or more dependencies doesn't exclude arm64 or is not set to build active architecture only.
A solution could be to force Cocoapods to add post install script while validating the project or let it build Debug scheme, because the Debug scheme is only building active architecture.
I ended up using Xcode 11 to release my pod to pass the validation. You can download Xcode 11 from developer.apple.com, copy it to Applications folder as Xcode11.app and switch using sudo xcode-select --switch /Applications/Xcode11.app/Contents/Developer
. Don't forget to switch back when done.
I got this error when I added the service class. I was using Angular 9 Went for several solutions, nothing helped me to resolve this issue. If U tried everything make sure u added ng module reference in core lib inside service. See Img
I solved the same issue by following steps:
Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10
After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap
In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",
Now after updating package.json, use the command npm update
After this use command ng serve and my error got resolved
I got the same issue when adding @angular/flex-layout to my Angular 8 project now with
`npm install @angular/flex-layout --save`.
This since now that command installed the major 9th version of the flex-layout package. Instead of upgrading everything else to the last version, I solved it by installing the last 8th major version of the package instead.
npm install @angular/[email protected] --save
Within IntelliJ, open pom.xml file.
Add this section before <dependencies>
(if your file already has a <properties>
section, just add the <maven.compiler...>
lines below to that existing section):
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
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)
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
This error also comes when you run the command
node filename.ts
and not
node filename.js
To simply put, with node command we will have to run the JavaScript file (filename.js) and not the TypeScript file unless we are using a package like ts-node
Fixed by adding crossorigin to the script tag.
From: https://code.jquery.com/
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org
Just add .pack
between the name and the extension in the <script>
tag in src.
i.e.:
<script src="name.pack.js">
// code here
</script>
I came across this problem on Windows too. The solution for me was to switch from a 32-bit to a 64-bit version of Python. Indeed, a 32-bit software, like a 32-bit CPU, can adress a maximum of 4 GB of RAM (2^32). So if you have more than 4 GB of RAM, a 32-bit version cannot take advantage of it.
With a 64-bit version of Python (the one labeled x86-64 in the download page), the issue disappeared.
You can check which version you have by entering the interpreter. I, with a 64-bit version, now have:
Python 3.7.5rc1 (tags/v3.7.5rc1:4082f600a5, Oct 1 2019, 20:28:14) [MSC v.1916 64 bit (AMD64)]
, where [MSC v.1916 64 bit (AMD64)] means "64-bit Python".
Note : as of the time of this writing (May 2020), matplotlib is not available on python39, so I recommand installing python37, 64 bits.
Sources :
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
I made some small changes to Alex McKay's function/usage that I think make it a little easier to follow why it works and also adheres to the no-use-before-define rule.
First, define this function to use:
const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }
In the way I've written it, the generic for the function lists the object first, then the property on the object second (these can occur in any order, but if you specify U extends key of T
before T extends object
you break the no-use-before-define
rule, and also it just makes sense to have the object first and its' property second. Finally, I've used the more common function syntax instead of the arrow operators (=>
).
Anyways, with those modifications you can just use it like this:
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Smith",
age: 20
};
getKeyValue(user, "name")
Which, again, I find to be a bit more readable.
I experienced the same issue, but in addition to Python being blocked, all programs in the Scripts
folder were too. The other answers about aliases, path and winpty
didn't help.
I finally found that it was my antivirus (Avast) which decided overnight for some reason to just block all compiled python scripts for some reason.
The fix is fortunately easy: simply whitelist the whole Python directory. See here for a full explanation.
you should use second argument with ViewChild like this:
@ViewChild("eleDiv", { static: false }) someElement: ElementRef;
Cause you Only Call Hooks from React Functions
. See more here https://reactjs.org/docs/hooks-rules.html#only-call-hooks-from-react-functions. Just convert Allowance
class component to functional component. The demo working here https://codesandbox.io/s/amazing-poitras-k2fuf
const Allowance = () => {
const [allowances, setAllowances] = useState([]);
useEffect(() => {
fetch("http://127.0.0.1:8000/allowances")
.then(data => {
return data.json();
})
.then(data => {
setAllowances(data);
})
.catch(err => {
console.log(123123);
});
}, []);
const classes = useStyles();
return (
<Paper className={classes.root}>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell>Allow ID</TableCell>
<TableCell align="right">Description</TableCell>
<TableCell align="right">Allow Amount</TableCell>
<TableCell align="right">AllowType</TableCell>
</TableRow>
</TableHead>
<TableBody>
{allowances.map(row => (
<TableRow key={row.id}>
<TableCell component="th" scope="row">
{row.AllowID}
</TableCell>
<TableCell align="right">{row.AllowDesc}</TableCell>
<TableCell align="right">{row.AllowAmt}</TableCell>
<TableCell align="right">{row.AllowType}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
);
};
export default Allowance;
I added %matplotlib inline and my plot showed up in Jupyter Notebook.
You have two options with simple and idiomatic Typescript:
DNATranscriber: { [char: string]: string } = {
G: "C",
C: "G",
T: "A",
A: "U",
};
This is the index signature the error message is talking about. Reference
DNATranscriber: { G: string; C: string; T: string; A: string } = {
G: "C",
C: "G",
T: "A",
A: "U",
};
Apart from other responses, from my understanding of the following, you only need to prepare for Dark mode when compiling against iOS 13 SDK (using XCode 11).
The system assumes that apps linked against the iOS 13 or later SDK support both light and dark appearances. In iOS, you specify the specific appearance you want by assigning a specific interface style to your window, view, or view controller. You can also disable support for Dark Mode entirely using an Info.plist key.
You can use GeometryReader in a handy extension to fill the parent
extension View {
func fillParent(alignment:Alignment = .center) -> some View {
return GeometryReader { geometry in
self
.frame(width: geometry.size.width,
height: geometry.size.height,
alignment: alignment)
}
}
}
so using the requested example, you get
struct ContentView : View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.lineLimit(nil)
.font(.body)
}
.fillParent(alignment:.topLeading)
.background(Color.red)
}
}
(note the spacer is no longer needed)
You have to set the http header at the http response of your resource. So it needs to be set serverside, you can remove the "HTTP_OPTIONS"-header from your angular HTTP-Post request.
Instead of converting the class to a function, an easy step would be to create a function to include the jsx for the component which uses the 'classes', in your case the <container></container>
and then call this function inside the return of the class render() as a tag. This way you are moving out the hook to a function from the class. It worked perfectly for me. In my case it was a <table>
which i moved to a function- TableStmt outside and called this function inside the render as <TableStmt/>
Problem occurs when we want to import CommonJS module into ES6 module codebase.
Before these flags we had to import CommonJS modules with star (* as something
) import:
// node_modules/moment/index.js
exports = moment
// index.ts file in our app
import * as moment from 'moment'
moment(); // not compliant with es6 module spec
// transpiled js (simplified):
const moment = require("moment");
moment();
We can see that *
was somehow equivalent to exports
variable. It worked fine, but it wasn't compliant with es6 modules spec. In spec, the namespace record in star import (moment
in our case) can be only a plain object, not callable (moment()
is not allowed).
With flag esModuleInterop
we can import CommonJS modules in compliance with es6
modules spec. Now our import code looks like this:
// index.ts file in our app
import moment from 'moment'
moment(); // compliant with es6 module spec
// transpiled js with esModuleInterop (simplified):
const moment = __importDefault(require('moment'));
moment.default();
It works and it's perfectly valid with es6 modules spec, because moment
is not namespace from star import, it's default import.
But how does it work? As you can see, because we did a default import, we called the default
property on a moment
object. But we didn't declare a default
property on the exports
object in the moment library. The key is the __importDefault
function. It assigns module (exports
) to the default
property for CommonJS modules:
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
As you can see, we import es6 modules as they are, but CommonJS modules are wrapped into an object with the default
key. This makes it possible to import defaults on CommonJS modules.
__importStar
does the similar job - it returns untouched esModules, but translates CommonJS modules into modules with a default
property:
// index.ts file in our app
import * as moment from 'moment'
// transpiled js with esModuleInterop (simplified):
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
And what about allowSyntheticDefaultImports
- what is it for? Now the docs should be clear:
Allow default imports from modules with no default export. This does not affect code emit, just typechecking.
In moment
typings we don't have specified default export, and we shouldn't have, because it's available only with flag esModuleInterop
on. So allowSyntheticDefaultImports
will not report an error if we want to import default from a third-party module which doesn't have a default export.
I think the answer from cheez (https://stackoverflow.com/users/122933/cheez) is the easiest and most effective one. I'd elaborate a little bit over it so it would not modify a numpy function for the whole session period.
My suggestion is below. I´m using it to download the reuters dataset from keras which is showing the same kind of error:
old = np.load
np.load = lambda *a,**k: old(*a,**k,allow_pickle=True)
from keras.datasets import reuters
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(num_words=10000)
np.load = old
del(old)
I used google colab to run my models and everything was perfect untill i used inline tesorboard. With tensorboard inline, I had the same issue of "Module 'tensorflow' has no attribute 'contrib'".
It was able to run training when rebuild and reinstall the model using setup.py(research folder) after initialising tensorboard.
import React, { useState } from "react"
const inputTextValue = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
return {
value,
onChange: (e) => { setValue(e.target.value) }
};
};
export default () => {
const textValue = inputTextValue("");
return (<>
<input {...textValue} />
</>
);
}
/*"Solution I Tired Changed Name of Funtion in Captial "*/
import React, { useState } from "react"
const InputTextValue = ({ initialValue }) => {
const [value, setValue] = useState(initialValue);
return {
value,
onChange: (e) => { setValue(e.target.value) }
};
};
export default () => {
const textValue = InputTextValue("");
return (<>
<input {...textValue} />
</>
);
}
You can remove the 2nd argument type array []
but the fetchBusinesses()
will also be called every update. You can add an IF
statement into the fetchBusinesses()
implementation if you like.
React.useEffect(() => {
fetchBusinesses();
});
The other one is to implement the fetchBusinesses()
function outside your component. Just don't forget to pass any dependency arguments to your fetchBusinesses(dependency)
call, if any.
function fetchBusinesses (fetch) {
return fetch("theURL", { method: "GET" })
.then(res => normalizeResponseErrors(res))
.then(res => res.json())
.then(rcvdBusinesses => {
// some stuff
})
.catch(err => {
// some error handling
});
}
function YourComponent (props) {
const { fetch } = props;
React.useEffect(() => {
fetchBusinesses(fetch);
}, [fetch]);
// ...
}
The imports have changed for core-js version 3.0.1 - for example
import 'core-js/es6/array';
and
import 'core-js/es7/array';
can now be provided simply by the following
import 'core-js/es/array';
if you would prefer not to bring in the whole of core-js
Try this.
editqueForm = this.fb.group({
user: [this.question.user],
questioning: [this.question.questioning, Validators.required],
questionType: [this.question.questionType, Validators.required],
options: new FormArray([])
})
setValue() and patchValue()
if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:
formgroup.setValue({name: ‘abc’, age: ‘25’});
It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.
On the other hand patchvalue()
is a lot easier on that part, let’s say you only want to assign the name as a new value:
formgroup.patchValue({name:’abc’});
You need to add an event, before call your handleFunction like this:
function SingInContainer() {
..
..
handleClose = () => {
}
return (
<SnackBar
open={open}
handleClose={() => handleClose}
variant={variant}
message={message}
/>
<SignInForm/>
)
}
I faced this problem when I first tried python after installing windows10 + python3.7(64bit) + anacconda3 + jupyter notebook.
I solved this problem by refering to "https://vispud.blogspot.com/2019/05/tensorflow200a0-attributeerror-module.html"
I agree with
I believe "Session()" has been removed with TF 2.0.
I inserted two lines. One is tf.compat.v1.disable_eager_execution()
and the other is sess = tf.compat.v1.Session()
My Hello.py is as follows:
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
hello = tf.constant('Hello, TensorFlow!')
sess = tf.compat.v1.Session()
print(sess.run(hello))
Since the cleanup is not dependent on the username
, you could put the cleanup in a separate useEffect
that is given an empty array as second argument.
Example
const { useState, useEffect } = React;_x000D_
_x000D_
const ForExample = () => {_x000D_
const [name, setName] = useState("");_x000D_
const [username, setUsername] = useState("");_x000D_
_x000D_
useEffect(_x000D_
() => {_x000D_
console.log("effect");_x000D_
},_x000D_
[username]_x000D_
);_x000D_
_x000D_
useEffect(() => {_x000D_
return () => {_x000D_
console.log("cleaned up");_x000D_
};_x000D_
}, []);_x000D_
_x000D_
const handleName = e => {_x000D_
const { value } = e.target;_x000D_
_x000D_
setName(value);_x000D_
};_x000D_
_x000D_
const handleUsername = e => {_x000D_
const { value } = e.target;_x000D_
_x000D_
setUsername(value);_x000D_
};_x000D_
_x000D_
return (_x000D_
<div>_x000D_
<div>_x000D_
<input value={name} onChange={handleName} />_x000D_
<input value={username} onChange={handleUsername} />_x000D_
</div>_x000D_
<div>_x000D_
<div>_x000D_
<span>{name}</span>_x000D_
</div>_x000D_
<div>_x000D_
<span>{username}</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
function App() {_x000D_
const [shouldRender, setShouldRender] = useState(true);_x000D_
_x000D_
useEffect(() => {_x000D_
setTimeout(() => {_x000D_
setShouldRender(false);_x000D_
}, 5000);_x000D_
}, []);_x000D_
_x000D_
return shouldRender ? <ForExample /> : null;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"></div>
_x000D_
The following steps can be used:
sudo apt-get -y update
---------
sudo apt-get install python3.7
--------------
python3.7
-------------
curl -O https://bootstrap.pypa.io/get-pip.py
-----------------
sudo apt install python3-pip
-----------------
sudo apt install python3.7-venv
-----------------
python3.7 -m venv /home/ubuntu/app
-------------
cd app
----------------
source bin/activate
Little late to the party but why don't you guys try animation.No I am not telling you to manage animation controllers and disposing them off and all that stuff.theres a built-in widget for that called TweenAnimationBuilder.You can animate between values of any type,heres an example with a Duration class
TweenAnimationBuilder<Duration>(
duration: Duration(minutes: 3),
tween: Tween(begin: Duration(minutes: 3), end: Duration.zero),
onEnd: () {
print('Timer ended');
},
builder: (BuildContext context, Duration value, Widget child) {
final minutes = value.inMinutes;
final seconds = value.inSeconds % 60;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: Text('$minutes:$seconds',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 30)));
}),
and You also get onEnd call back which notifies you when the animation completes;
here's the output
For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.
You have forgotten to mark the getProducts return type as an array. In your getProducts it says that it will return a single product. So change it to this:
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
Much like setState in Class components created by extending React.Component
or React.PureComponent
, the state update using the updater provided by useState
hook is also asynchronous, and will not be reflected immediately.
Also, the main issue here is not just the asynchronous nature but the fact that state values are used by functions based on their current closures, and state updates will reflect in the next re-render by which the existing closures are not affected, but new ones are created. Now in the current state, the values within hooks are obtained by existing closures, and when a re-render happens, the closures are updated based on whether the function is recreated again or not.
Even if you add a setTimeout
the function, though the timeout will run after some time by which the re-render would have happened, the setTimeout
will still use the value from its previous closure and not the updated one.
setMovies(result);
console.log(movies) // movies here will not be updated
If you want to perform an action on state update, you need to use the useEffect hook, much like using componentDidUpdate
in class components since the setter returned by useState doesn't have a callback pattern
useEffect(() => {
// action on update of movies
}, [movies]);
As far as the syntax to update state is concerned, setMovies(result)
will replace the previous movies
value in the state with those available from the async request.
However, if you want to merge the response with the previously existing values, you must use the callback syntax of state updation along with the correct use of spread syntax like
setMovies(prevMovies => ([...prevMovies, ...result]));
I had a similar issue thanks @ford04 helped me out.
However, another error occurred.
NB. I am using ReactJS hooks
ndex.js:1 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
What causes the error?
import {useHistory} from 'react-router-dom'
const History = useHistory()
if (true) {
history.push('/new-route');
}
return (
<>
<render component />
</>
)
This could not work because despite you are redirecting to new page all state and props are being manipulated on the dom or simply rendering to the previous page did not stop.
What solution I found
import {Redirect} from 'react-router-dom'
if (true) {
return <redirect to="/new-route" />
}
return (
<>
<render component />
</>
)
You are catching the error but then you are re throwing it. You should try and handle it more gracefully, otherwise your user is going to see 500, internal server, errors.
You may want to send back a response telling the user what went wrong as well as logging the error on your server.
I am not sure exactly what errors the request might return, you may want to return something like.
router.get("/emailfetch", authCheck, async (req, res) => {
try {
let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
emailFetch = emailFetch.data
res.send(emailFetch)
} catch(error) {
res.status(error.response.status)
return res.send(error.message);
})
})
This code will need to be adapted to match the errors that you get from the axios call.
I have also converted the code to use the try and catch syntax since you are already using async.
I have resolved import error by Ctrl + Shift + P. Type "Preferences settings" and select the option Preferences Open Settings (JSON)
And add the line "python.pythonPath": "/usr/bin/"
So the JSON content should look like:
{
"python.pythonPath": "/usr/bin/"
}
Keep other configuration lines if they are present. This should import all modules that you have installed using PIP for autocomplete.
You should not set state (or do anything else with side effects) from within the rendering function. When using hooks, you can use useEffect
for this.
The following version works:
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const StateSelector = () => {
const initialValue = [
{ id: 0, value: " --- Select a State ---" }];
const allowedState = [
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
const [stateOptions, setStateValues] = useState(initialValue);
// initialValue.push(...allowedState);
console.log(initialValue.length);
// ****** BEGINNING OF CHANGE ******
useEffect(() => {
// Should not ever set state during rendering, so do this in useEffect instead.
setStateValues(allowedState);
}, []);
// ****** END OF CHANGE ******
return (<div>
<label>Select a State:</label>
<select>
{stateOptions.map((localState, index) => (
<option key={localState.id}>{localState.value}</option>
))}
</select>
</div>);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<StateSelector />, rootElement);
and here it is in a code sandbox.
I'm assuming that you want to eventually load the list of states from some dynamic source (otherwise you could just use allowedState
directly without using useState
at all). If so, that api call to load the list could also go inside the useEffect
block.
In my case I had recently changed a database connection string in my appstettings.json file. Without logging or error catching in place I suspect this error wound up causing the "HTTP Error 500.30 - ANCM In-Process Start Failure" error.
I happened to notice the exchange between x-freestyler and Tahir Khalid where Tahir suggested an IOC problem in startup. Since my startup had not changed recently but my appstettings.json had - I determined that the connection string in my appstettings.json was the cause of the problem. I corrected an incorrect connection string and the problem was solved. Thanks to the whole community.
I have the same problem after upgrading to Gradle Wrapper 5.0., Now I switch back to 4.10.3 which just released 5 December 2018 based on Gradle documentation and use Android Gradle Plugin: 3.2.1 (the latest stable version).
A React Node
is one of the following types:
Boolean
(which is ignored)null
or undefined
(which is ignored)Number
String
React element
(result of JSX
)This post will go through the following topics:
merge
has shortcomings here)Oftentimes, the situation arises when multiple DataFrames are to be merged together. Naively, this can be done by chaining merge
calls:
df1.merge(df2, ...).merge(df3, ...)
However, this quickly gets out of hand for many DataFrames. Furthermore, it may be necessary to generalise for an unknown number of DataFrames.
Here I introduce pd.concat
for multi-way joins on unique keys, and DataFrame.join
for multi-way joins on non-unique keys. First, the setup.
# Setup.
np.random.seed(0)
A = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'valueA': np.random.randn(4)})
B = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'valueB': np.random.randn(4)})
C = pd.DataFrame({'key': ['D', 'E', 'J', 'C'], 'valueC': np.ones(4)})
dfs = [A, B, C]
# Note, the "key" column values are unique, so the index is unique.
A2 = A.set_index('key')
B2 = B.set_index('key')
C2 = C.set_index('key')
dfs2 = [A2, B2, C2]
If your keys (here, the key could either be a column or an index) are unique, then you can use pd.concat
. Note that pd.concat
joins DataFrames on the index.
# merge on `key` column, you'll need to set the index before concatenating
pd.concat([
df.set_index('key') for df in dfs], axis=1, join='inner'
).reset_index()
key valueA valueB valueC
0 D 2.240893 -0.977278 1.0
# merge on `key` index
pd.concat(dfs2, axis=1, sort=False, join='inner')
valueA valueB valueC
key
D 2.240893 -0.977278 1.0
Omit join='inner'
for a FULL OUTER JOIN. Note that you cannot specify LEFT or RIGHT OUTER joins (if you need these, use join
, described below).
concat
is fast, but has its shortcomings. It cannot handle duplicates.
A3 = pd.DataFrame({'key': ['A', 'B', 'C', 'D', 'D'], 'valueA': np.random.randn(5)})
pd.concat([df.set_index('key') for df in [A3, B, C]], axis=1, join='inner')
ValueError: Shape of passed values is (3, 4), indices imply (3, 2)
In this situation, we can use join
since it can handle non-unique keys (note that join
joins DataFrames on their index; it calls merge
under the hood and does a LEFT OUTER JOIN unless otherwise specified).
# join on `key` column, set as the index first
# For inner join. For left join, omit the "how" argument.
A.set_index('key').join(
[df.set_index('key') for df in (B, C)], how='inner').reset_index()
key valueA valueB valueC
0 D 2.240893 -0.977278 1.0
# join on `key` index
A3.set_index('key').join([B2, C2], how='inner')
valueA valueB valueC
key
D 1.454274 -0.977278 1.0
D 0.761038 -0.977278 1.0
Jump to other topics in Pandas Merging 101 to continue learning:
* you are here
Try setting the "endOfLine":"auto"
in your .prettierrc file (inside the object)
Or set
"prettier/prettier": ["error", {
..
"endOfLine":"auto"
..
}],
inside the rules object of the eslintrc file.
If you are using windows machine endOfLine can be "crlf" basing on your git config.
import { combineReducers } from '../../store/reducers';
should be
import combineReducers from '../../store/reducers';
since it's a default export, and not a named export.
There's a good breakdown of the differences between the two here.
As the others have mentioned, useState
works - here is how mobx-react-lite implements updates - you could do something similar.
Define a new hook, useForceUpdate
-
import { useState, useCallback } from 'react'
export function useForceUpdate() {
const [, setTick] = useState(0);
const update = useCallback(() => {
setTick(tick => tick + 1);
}, [])
return update;
}
and use it in a component -
const forceUpdate = useForceUpdate();
if (...) {
forceUpdate(); // force re-render
}
See https://github.com/mobxjs/mobx-react-lite/blob/master/src/utils.ts and https://github.com/mobxjs/mobx-react-lite/blob/master/src/useObserver.ts
On Ubuntu 18.04, I ran into this issue because the apt
package for wheel
does not include the wheel
command. I think pip tries to import the wheel
python package, and if that succeeds assumes that the wheel
command is also available. Ubuntu breaks that assumption.
The apt python3 code package is named python3-wheel
. This is installed automatically because python3-pip
recommends it.
The apt python3 wheel command package is named python-wheel-common
. Installing this too fixes the "failed building wheel" errors for me.
React hooks are a new way (still being developed) to access the core features of react such as state
without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick
prop, you could do something like:
...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setMoreStuff(...);
...
};
and onClick:
<button onClick={setCount}>
Click me
</button>
Let's quickly explain what is going on in this line:
const [count, setCounter] = useState(0);
useState(0)
returns a tuple where the first parameter count
is the current state of the counter and setCounter
is the method that will allow us to update the counter's state. We can use the setCounter
method to update the state of count
anywhere - In this case we are using it inside of the setCount
function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.
I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState
, useEffect
, useContext
, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail, hope it helps.
update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.
Assuming that you already downloaded chromeDriver, this error is also occurs when already multiple chrome tabs are open.
If you close all tabs and run again, the error should clear up.
I had a similir problem, but in my case, I put a row in the leading of the ListView, and it was consuming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recommend to check if the problem is a larger widget than its container can have.
Expanded(child:MyListView())
When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.
In my case, I had to comment out com.google.firebase.firebase-crash
plugin:
apply plugin: 'com.android.application'
// apply plugin: 'com.google.firebase.firebase-crash' <== this plugin causes the error
It is a bug since Android Studio 3.3.0
As mentioned in the comments, the Starting Guide is the place to start with Java 11 and JavaFX 11.
The key to work as you did before Java 11 is to understand that:
JavaFX project
If you create a regular JavaFX default project in IntelliJ (without Maven or Gradle) I'd suggest you download the SDK from here. Note that there are jmods as well, but for a non modular project the SDK is preferred.
These are the easy steps to run the default project:
/Users/<user>/Downloads/javafx-sdk-11/lib/
. Once you do this you will notice that the JavaFX classes are now recognized in the editor.Before you run the default project, you just need to add these to the VM options:
--module-path /Users/<user>/Downloads/javafx-sdk-11/lib --add-modules=javafx.controls,javafx.fxml
Run
Maven
If you use Maven to build your project, follow these steps:
Add the JavaFX 11 dependencies.
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>11</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>11</version>
</dependency>
</dependencies>
Once you do this you will notice that the JavaFX classes are now recognized in the editor.
You will notice that Maven manages the required dependencies for you: it will add javafx.base and javafx.graphics for javafx.controls, but most important, it will add the required classifier based on your platform. In my case, Mac.
This is why your jars org.openjfx:javafx-controls:11
are empty, because there are three possible classifiers (windows, linux and mac platforms), that contain all the classes and the native implementation.
In case you still want to go to your .m2 repo and take the dependencies from there manually, make sure you pick the right one (for instance .m2/repository/org/openjfx/javafx-controls/11/javafx-controls-11-mac.jar
)
Replace default maven plugins with those from here.
Run mvn compile javafx:run
, and it should work.
Similar works as well for Gradle projects, as explained in detail here.
EDIT
The mentioned Getting Started guide contains updated documentation and sample projects for IntelliJ:
JavaFX 11 without Maven/Gradle, see non-modular sample or modular sample projects.
JavaFX 11 with Maven, see non-modular sample or modular sample projects.
JavaFX 11 with Gradle, see non-modular sample or modular sample projects.
I had a similar error while I was creating a custom modal.
const CustomModal = (visible, modalText, modalHeader) => {}
Problem was that I didn't wrap my values to curly brackets like this.
const CustomModal = ({visible, modalText, modalHeader}) => {}
If you have multiple values to pass to the component, you should use curly brackets around it.
The problem is pyaudio does not have wheels for python 3.7 just try some lower version like 3.6
then install pyaudio
It works
You should declare your method first in void initState()
, so when the first time pages has been loaded, it will init your method first, hope it can help
If your project is not AndroidX (mean Appcompat) and got this error, try to downgrade dependencies versions that triggers this error, in my case play-services-location ("implementation 'com.google.android.gms:play-services-location:17.0.0'") , I solved the problem by downgrading to com.google.android.gms:play-services-location:16.0.0'
When you use routerLink like this, then you need to pass the value of the route it should go to. But when you use routerLink with the property binding syntax, like this: [routerLink]
, then it should be assigned a name of the property the value of which will be the route it should navigate the user to.
So to fix your issue, replace this routerLink="['/about']"
with routerLink="/about"
in your HTML.
There were other places where you used property binding syntax when it wasn't really required. I've fixed it and you can simply use the template syntax below:
<nav class="main-nav>
<ul
class="main-nav__list"
ng-sticky
addClass="main-sticky-link"
[ngClass]="ref.click ? 'Navbar__ToggleShow' : ''">
<li class="main-nav__item" routerLinkActive="active">
<a class="main-nav__link" routerLink="/">Home</a>
</li>
<li class="main-nav__item" routerLinkActive="active">
<a class="main-nav__link" routerLink="/about">About us</a>
</li>
</ul>
</nav>
It also needs to know where exactly should it load the template for the Component corresponding to the route it has reached. So for that, don't forget to add a <router-outlet></router-outlet>
, either in your template provided above or in a parent component.
There's another issue with your AppRoutingModule
. You need to export the RouterModule
from there so that it is available to your AppModule
when it imports it. To fix that, export it from your AppRoutingModule
by adding it to the exports
array.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { MainLayoutComponent } from './layout/main-layout/main-layout.component';
import { AboutComponent } from './components/about/about.component';
import { WhatwedoComponent } from './components/whatwedo/whatwedo.component';
import { FooterComponent } from './components/footer/footer.component';
import { ProjectsComponent } from './components/projects/projects.component';
const routes: Routes = [
{ path: 'about', component: AboutComponent },
{ path: 'what', component: WhatwedoComponent },
{ path: 'contacts', component: FooterComponent },
{ path: 'projects', component: ProjectsComponent},
];
@NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes),
],
exports: [RouterModule],
declarations: []
})
export class AppRoutingModule { }
- Can someone give a simple definition of what
Record
is?
A Record<K, T>
is an object type whose property keys are K
and whose property values are T
. That is, keyof Record<K, T>
is equivalent to K
, and Record<K, T>[K]
is (basically) equivalent to T
.
- Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all objects, sinceK
has some purpose...
As you note, K
has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>
, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }
.
- Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'
and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties
and sometimes accepted:
const y = {a: "hey", b: "you"};
acceptR(y); // okay
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
Hope that helps. Good luck!
You can use
nditer
Here I calculated no. of positive and negative coefficients in a logistic regression:
b=sentiment_model.coef_
pos_coef=0
neg_coef=0
for i in np.nditer(b):
if i>0:
pos_coef=pos_coef+1
else:
neg_coef=neg_coef+1
print("no. of positive coefficients is : {}".format(pos_coef))
print("no. of negative coefficients is : {}".format(neg_coef))
Output:
no. of positive coefficients is : 85035
no. of negative coefficients is : 36199
I don't know this is the proper answer or not but it worked for me
Increase Gridle Wrapper Property
distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip
and Build Gridle to
classpath 'com.android.tools.build:gradle:3.4.2'
its showing error because of the version.
Look to this, may be help you.
class ScrollView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new LayoutBuilder(
builder:
(BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: viewportConstraints.maxHeight),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Hello world!!"),
//You can add another children
]),
),
);
},
);
}
}
I ended up here when searching for ”rxjs download file using post”.
This was my final product. It uses the file name and type given in the server response.
import { ajax, AjaxResponse } from 'rxjs/ajax';
import { map } from 'rxjs/operators';
downloadPost(url: string, data: any) {
return ajax({
url: url,
method: 'POST',
responseType: 'blob',
body: data,
headers: {
'Content-Type': 'application/json',
'Accept': 'text/plain, */*',
'Cache-Control': 'no-cache',
}
}).pipe(
map(handleDownloadSuccess),
);
}
handleDownloadSuccess(response: AjaxResponse) {
const downloadLink = document.createElement('a');
downloadLink.href = window.URL.createObjectURL(response.response);
const disposition = response.xhr.getResponseHeader('Content-Disposition');
if (disposition) {
const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
const filename = matches[1].replace(/['"]/g, '');
downloadLink.setAttribute('download', filename);
}
}
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
In Colum widget Text alignment will be centred automatically, so use crossAxisAlignment: CrossAxisAlignment.start
to align start.
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(""),
Text(""),
]);
Run the Gradle build with a command line argument --warning-mode=all
to see what exactly the deprecated features are.
It will give you a detailed description of found issues with links to the Gradle docs for instructions how to fix your build.
Adding --stacktrace
to that, you will also be able to pinpoint where the warning comes from, if it's triggered by outdated code in one of the plugins and not your build script.
You can simply use password field value as a pattern for confirm password field. For Example :
<div class="form-group">
<input type="password" [(ngModel)]="userdata.password" name="password" placeholder="Password" class="form-control" required #password="ngModel" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" />
<div *ngIf="password.invalid && (myform.submitted || password.touched)" class="alert alert-danger">
<div *ngIf="password.errors.required"> Password is required. </div>
<div *ngIf="password.errors.pattern"> Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters.</div>
</div>
</div>
<div class="form-group">
<input type="password" [(ngModel)]="userdata.confirmpassword" name="confirmpassword" placeholder="Confirm Password" class="form-control" required #confirmpassword="ngModel" pattern="{{ password.value }}" />
<div *ngIf=" confirmpassword.invalid && (myform.submitted || confirmpassword.touched)" class="alert alert-danger">
<div *ngIf="confirmpassword.errors.required"> Confirm password is required. </div>
<div *ngIf="confirmpassword.errors.pattern"> Password & Confirm Password does not match.</div>
</div>
</div>
I surggest using the CopyTo method, so here is my two cent on a solution that is easy to explain and simple. The CopyTo method copies the array to another array at a given index. In this case myArray is copied to newArr starting at index 1 so index 0 in newArr can hold the new value.
var newValue = 1;
var myArray = new int[5] { 2, 3, 4, 5, 6 };
var newArr = new int[myArray.Length + 1];
myArray.CopyTo(newArr, 1);
newArr[0] = newValue;
//debug
for(var i = 0; i < newArr.Length; i++){
Console.WriteLine(newArr[i].ToString());
}
//output
1
2
3
4
5
6
Adding to what was already said.
if you want to *ngFor
an element , and hide \ show elements in it, on hover, like you added in the comments, you should re-think the whole concept.
a more appropriate way to do it, does not involve angular at all.
I would go with pure CSS instead, using its native :hover
property.
something like:
App.Component.css
div span.only-show-on-hover {
visibility: hidden;
}
div:hover span.only-show-on-hover {
visibility: visible;
}
App.Component.html
<div *ngFor="let i of [1,2,3,4]" > hover me please.
<span class="only-show-on-hover">you only see me when hovering</span>
</div>
added a demo: https://stackblitz.com/edit/hello-angular-6-hvgx7n?file=src%2Fapp%2Fapp.component.html
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
Although I've tried all the previous answers, only the following one worked out:
1 - Open Powershell (as Admin)
2 - Run:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
3 - Run:
Install-PackageProvider -Name NuGet
The author is Niels Weistra: Microsoft Forum
You can use !setup.py install
to do that.
Colab is just like a Jupyter notebook. Therefore, we can use the !
operator here to install any package in Colab. What !
actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a !
preceding the line.
For example: !pip install tensorflow
. This will treat that line (here pip install tensorflow
) as a command prompt line and not some Python code. However, if you do this without adding the !
preceding the line, it'll throw up an error saying "invalid syntax".
But keep in mind that you'll have to upload the setup.py
file to your drive before doing this (preferably into the same folder where your notebook is).
Hope this answers your question :)
I tried following the above tutorial. Thing is tensorflow changes a lot and so do the NVIDIA versions needed for running on a GPU. The next issue is that your driver version determines your toolkit version etc. As of today this information about the software requirements should shed some light on how they interplay:
NVIDIA® GPU drivers —CUDA 9.0 requires 384.x or higher.
CUDA® Toolkit —TensorFlow supports CUDA 9.0.
CUPTI ships with the CUDA Toolkit.
cuDNN SDK (>= 7.2) Note: Make sure your GPU has compute compatibility >3.0
(Optional) NCCL 2.2 for multiple GPU support.
(Optional) TensorRT 4.0 to improve latency and throughput for inference on some models.
And here you'll find the up-to-date requirements stated by tensorflow (which will hopefully be updated by them on a regular basis).
AndroidX is the open-source project that the Android team uses to develop, test, package, version and release libraries within Jetpack.
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
Put these flags in your gradle.properties
android.enableJetifier=true
android.useAndroidX=true
Changes in gradle:
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0-alpha04'
When migrating on Android studio, the app/gradle file is automatically updated with the correction library impleemntations from the standard library
Refer to: https://developer.android.com/jetpack/androidx/migrate
Not tested but should work
products.sort((a,b)=>a.title.rendered > b.title.rendered)
And this:
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
suppose to be solution of deprecated:
FirebaseInstanceId.getInstance().getToken()
EDIT
FirebaseInstanceId.getInstance().getInstanceId().getResult().getToken()
can produce exception if the task is not yet completed, so the method witch Nilesh Rathod described (with .addOnSuccessListener
) is correct way to do it.
Kotlin:
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(this) { instanceIdResult ->
val newToken = instanceIdResult.token
Log.e("newToken", newToken)
}
In addition to @Cinn's answer, you can define a class like this
class MyAppBar extends AppBar with PreferredSizeWidget {
@override
get preferredSize => Size.fromHeight(50);
MyAppBar({Key key, Widget title}) : super(
key: key,
title: title,
// maybe other AppBar properties
);
}
or this way
class MyAppBar extends PreferredSize {
MyAppBar({Key key, Widget title}) : super(
key: key,
preferredSize: Size.fromHeight(50),
child: AppBar(
title: title,
// maybe other AppBar properties
),
);
}
and then use it instead of standard one
Depending on your logic, if you want to close only the current fragment you have to pass viewLifecycleOwner, code is shown below:
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
requireActivity().finish()
}
})
However, if you want to close application on backPressed no matter from what fragment(probably you wouldn't want that!), don't pass the viewLifecycleOwner. Also if you want to disable the back button, do not do anything inside the handleOnBackPressed(), see below:
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// do nothing it will disable the back button
}
})
If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think) Enter the following commands to do flask run
$ export FLASK_APP = hello.py
$ export FLASK_ENV = development
$ flask run
Alternatively you can do the following (I haven't tried this but one resource online talks about it)
$ export FLASK_APP = hello.py
$ python -m flask run
source: For more
There are already many nice answers to this problem but I would like to share a wonderful site that I came across when I couldnt solve the 'TesseractNotFound Error: tesseract is not installed or it's not in your path” Please refer this site: https://www.thetopsites.net/article/50655738.shtml
I realised that I got this error because I installed pytesseract with pip but forget to install the binary. You are probably missing tesseract-ocr from your machine. Check the installation instructions here: https://github.com/tesseract-ocr/tesseract/wiki
On a Mac, you can just install using homebrew:
brew install tesseract
It should run fine after that!
Under Windows 10 OS environment, the following method works for me:
Go to this link and Download tesseract and install it. Windows version is available here: https://github.com/UB-Mannheim/tesseract/wiki
Find script file pytesseract.py from C:\Users\User\Anaconda3\Lib\site-packages\pytesseract and open it. Change the following code from tesseract_cmd = 'tesseract' to: tesseract_cmd = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe' (This is the path where you install Tesseract-OCR so please check where you install it and accordingly update the path)
You may also need to add environment variable C:/Program Files (x86)/Tesseract-OCR/
Hope it works for you!
Create your assets directory the same as lib level
like this
projectName
-android
-ios
-lib
-assets
-pubspec.yaml
then your pubspec.yaml like
flutter:
assets:
- assets/images/
now you can use Image.asset("/assets/images/")
In addition to the previous answers, if you're looking to access VUE_APP_* env variables in your sass (either the sass section of a vue component or a scss file), then you can add the following to your vue.config.js (which you may need to create if you don't have one):
let sav = "";
for (let e in process.env) {
if (/VUE_APP_/i.test(e)) {
sav += `$${e}: "${process.env[e]}";`;
}
}
module.exports = {
css: {
loaderOptions: {
sass: {
data: sav,
},
},
},
}
The string sav seems to be prepended to every sass file that before processing, which is fine for variables. You could also import mixins at this stage to make them available for the sass section of each vue component.
You can then use these variables in your sass section of a vue file:
<style lang="scss">
.MyDiv {
margin: 1em 0 0 0;
background-image: url($VUE_APP_CDN+"/MyImg.png");
}
</style>
or in a .scss file:
.MyDiv {
margin: 1em 0 0 0;
background-image: url($VUE_APP_CDN+"/MyImg.png");
}
from https://www.matt-helps.com/post/expose-env-variables-vue-cli-sass/
You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.
Instead you should set the option responseType
to text
:
addToCart(productId: number, quantity: number): Observable<any> {
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'}
).pipe(catchError(this.errorHandlerService.handleError));
}
You can either use the previous API packages version of artifacts or the new Androidx, never both.
If you wanna use the previous version, replace your dependencies with
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.android.support.constraint:constraint-layout:1.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:design:28.0.0-alpha3'
implementation 'com.android.support:cardview-v7:28.0.0-alpha3'
}
if you want to use Androidx:
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.0-alpha3'
implementation 'androidx.constraintlayout:constraintlayout:1.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha3'
implementation 'com.google.android.material:material:1.0.0-alpha3'
implementation 'androidx.cardview:cardview:1.0.0-alpha3'
}
Compress your .sql
file, and make sure to name it .[format].[compression]
, i.e.
database.sql.zip
.
As noted above, PhpMyAdmin throws this error if your .sql
file is larger than the Maximum allowed upload size -- but, in my case the maximum was 50MiB despite that I had set all options noted in previous answers (look for the "Max: 50MiB" next to the upload button in PhpMyAdmin).
One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:
pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'
Try this
<mat-form-field>
<mat-select [(ngModel)]="modeselect" [placeholder]="modeselect">
<mat-option value="domain">Domain</mat-option>
<mat-option value="exact">Exact</mat-option>
</mat-select>
</mat-form-field>
Component:
export class SelectValueBindingExample {
public modeselect = 'Domain';
}
Also, don't forget to import FormsModule
in your app.module
A very simple way to do this is by the following:
onClick={this.fun.bind(this)}
and for the function:
fun() {
this.props.history.push("/Home");
}
finlay you need to import withRouter:
import { withRouter } from 'react-router-dom';
and export it as:
export default withRouter (comp_name);
NPX:
Web developers can have dozens of projects on their development machines, and each project has its own particular set of npm-installed dependencies. A few years back, the usual advice for dealing with CLI applications like Grunt or Gulp was to install them locally in each project and also globally so they could easily be run from the command line.
But installing globally caused as many problems as it solved. Projects may depend on different versions of command line tools, and polluting the operating system with lots of development-specific CLI tools isn’t great either. Today, most developers prefer to install tools locally and leave it at that.
Local versions of tools allow developers to pull projects from GitHub without worrying about incompatibilities with globally installed versions of tools. NPM can just install local versions and you’re good to go. But project specific installations aren’t without their problems: how do you run the right version of the tool without specifying its exact location in the project or playing around with aliases?
That’s the problem npx solves. A new tool included in NPM 5.2, npx is a small utility that’s smart enough to run the right application when it’s called from within a project.
If you wanted to run the project-local version of mocha, for example, you can run npx mocha inside the project and it will do what you expect.
A useful side benefit of npx is that it will automatically install npm packages that aren’t already installed. So, as the tool’s creator Kat Marchán points out, you can run npx benny-hill without having to deal with Benny Hill polluting the global environment.
If you want to take npx for a spin, update to the most recent version of npm.
I get the same issue and i solved it by replacing :
implementation 'com.google.firebase:firebase-core:16.0.1'
to
implementation 'com.google.firebase:firebase-core:15.0.2'
and everything solved and worked well.
None of the above solution work for me. I tried and very frustrated until I watched the following video: https://www.youtube.com/watch?v=tGinfzlp0fE
pip uninstall mysql-connector
work on some computer and it might not work for other computer.
I did the followings:
pip uninstall mysql-connector
pip uninstall mysql-connector-python
pip install mysql-connector-python
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
The connection string format must be mongodb://user:password@host:port/db
For example:
MongoClient.connect('mongodb://user:[email protected]:27017/yourDB', { useNewUrlParser: true } )
This could be your connectors for MySQL which need to be updated, as MySQL8 changed the encryption of passwords - so older connectors are encrypting them incorrectly.
The maven repo for the java connector can be found here.
If you use flyway plugin, you should also consider updating it, too!
Then you can simply update your maven pom with:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
Or for others who use Gradle, you can update build.gradle with:
buildscript {
ext {
...
}
repositories {
...
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath('mysql:mysql-connector-java:8.0.11')
}
}
I was also facing such an issue while dockerizing our existing application. The solution si to add allowPublicKeyRetrieval connection option of MySQL with a value of true to the JDBC connection string. If that is not working , try adding useSSL option to false as well .
The resultant string would look like this :
jdbc:mysql://<database server ip>:3306/databaseName?allowPublicKeyRetrieval=true&useSSL=false
I don't know about CLI, I had tried, but I couldn't. I deleted using IDE Idea history.
If You use an Intellij Idea, just open History changes.
Tap by main folder of the project -> right click -> local history -> show history.
Then from top to bottom revert changes.
It should help! Good luck!=)
OK, finally we have an answer...
You are correctly specifying headers: {"Content-Type": "application/json"},
to set your content type. Under the hood either the package http
or the lower level dart:io HttpClient
is changing this to application/json; charset=utf-8
. However, your server web application obviously isn't expecting the suffix.
To prove this I tried it in Java, with the two versions
conn.setRequestProperty("content-type", "application/json; charset=utf-8"); // fails
conn.setRequestProperty("content-type", "application/json"); // works
Are you able to contact the web application owner to explain their bug? I can't see where Dart is adding the suffix, but I'll look later.
EDIT
Later investigation shows that it's the http
package that, while doing a lot of the grunt work for you, is adding the suffix that your server dislikes. If you can't get them to fix the server then you can by-pass http
and use the dart:io HttpClient
directly. You end up with a bit of boilerplate which is normally handled for you by http
.
Working example below:
import 'dart:convert';
import 'dart:io';
import 'dart:async';
main() async {
String url =
'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
Map map = {
'data': {'apikey': '12345678901234567890'},
};
print(await apiRequest(url, map));
}
Future<String> apiRequest(String url, Map jsonMap) async {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
// todo - you should check the response.statusCode
String reply = await response.transform(utf8.decoder).join();
httpClient.close();
return reply;
}
Depending on your use case, it may be more efficient to re-use the HttpClient, rather than keep creating a new one for each request. Todo - add some error handling ;-)
For me the problem was that I was setting REQUESTS_CA_BUNDLE
in my .bash_profile
/Users/westonagreene/.bash_profile:
...
export REQUESTS_CA_BUNDLE=/usr/local/etc/openssl/cert.pem
...
Once I set REQUESTS_CA_BUNDLE
to blank (i.e. removed from .bash_profile
), requests
worked again.
export REQUESTS_CA_BUNDLE=""
The problem only exhibited when executing python requests
via a CLI (Command Line Interface). If I ran requests.get(URL, CERT)
it resolved just fine.
Mac OS Catalina (10.15.6).
Pyenv of 3.6.11.
Error message I was getting: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)
My answer elsewhere: https://stackoverflow.com/a/64151964/4420657
Let's first make it clear what's going on.
MySQL 8 has supports pluggable authentication methods. By default, one of them named caching_sha2_password
is used rather than our good old mysql_native_password
(source). It should be obvious that using a crypto algorithm with several handshakes is more secure than plain password passing that has been there for 24 years!
Now, the problem is mysqljs
in Node (the package you install with npm i mysql
and use it in your Node code) doesn't support this new default authentication method of MySQL 8, yet. The issue is in here: https://github.com/mysqljs/mysql/issues/1507 and is still open, after 3 years, as of July 2019.
UPDATE June 2019: There is a new PR in mysqljs now to fix this!
UPDATE Feb 2020: Apparently it's scheduled to come in version 3 of mysqljs.
UPDATE July 2020: Apparently it's still not in yet (as of April 2020 at least), but it's claimed that node-mysql2 is supporting Authentication switch request. Please comment below if node-mysql2
is working fine for this issue -- I will test it later myself.
That's what everybody suggests here (e.g. top answer above). You just get into mysql
and run a query saying root
is fine using old mysql_native_password
method for authentication:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password ...
The good thing is, life is going to be simple and you can still use good old tools like Sequel Pro without any issue. But the problem is, you are not taking advantage of a more secure (and cool, read below) stuffs available to you.
MySQL X DevAPI for Node is a replacement to Node's Mysqljs package, provided by http://dev.mysql.com official guys.
It works like a charm supporting caching_sha2_password
authentication. (Just make sure you use port 33060
for X Protocol communications.)
The bad thing is, you have left our old mysql
package that everyone is so used to and relies on.
The good thing is, your app is more secure now and you can take advantage of a ton of new things that our good old friends didn't provide! Just check out the tutorial of X DevAPI and you'll see it has a ton of new sexy features that can come in handy. You just need to pay the price of a learning curve, which expectedly comes with any technology upgrade. :)
PS. Unfortunately, this XDevAPI Package doesn't have types definition (understandable by TypeScript) yet, so if you are on typescript, you will have problems. I tried to generate .d.ts using dts-gen
and dtsmake
, but no success. So keep that in mind.
Cheers!
Starting with 1.6.4, Arduino IDE can be used to program and upload the NodeMCU board by installing the ESP8266 third-party platform package (refer https://github.com/esp8266/Arduino):
To install additional ESP8266WiFi library:
After above steps, you should compile the sketch normally.
In my case there was a need for:
@Injectable({
providedIn: 'root' // <- ADD THIS
})
export class FooService { ...
instead of just:
@Injectable()
export class FooService { ...
You should use html autofocus for this:
<input *ngIf="show" #search type="text" autofocus />
Note: if your component is persisted and reused it will only autofocus the first time the fragment is attached. This can be overcome by having a global dom listener that checks for autofocus attribute inside a dom fragment when it is attached and then reapplying it or focus via javascript.
It's easy to use typescript version 2.9+. So you can easily import JSON files as @kentor decribed.
But if you need to use older versions:
You can access JSON files in more TypeScript way. First, make sure your new typings.d.ts
location is the same as with the include
property in your tsconfig.json
file.
If you don't have an include property in your tsconfig.json
file. Then your folder structure should be like that:
- app.ts
+ node_modules/
- package.json
- tsconfig.json
- typings.d.ts
But if you have an include
property in your tsconfig.json
:
{
"compilerOptions": {
},
"exclude" : [
"node_modules",
"**/*spec.ts"
], "include" : [
"src/**/*"
]
}
Then your typings.d.ts
should be in the src
directory as described in include
property
+ node_modules/
- package.json
- tsconfig.json
- src/
- app.ts
- typings.d.ts
As In many of the response, You can define a global declaration for all your JSON files.
declare module '*.json' {
const value: any;
export default value;
}
but I prefer a more typed version of this. For instance, let's say you have configuration file config.json
like that:
{
"address": "127.0.0.1",
"port" : 8080
}
Then we can declare a specific type for it:
declare module 'config.json' {
export const address: string;
export const port: number;
}
It's easy to import in your typescript files:
import * as Config from 'config.json';
export class SomeClass {
public someMethod: void {
console.log(Config.address);
console.log(Config.port);
}
}
But in compilation phase, you should copy JSON files to your dist folder manually. I just add a script property to my package.json
configuration:
{
"name" : "some project",
"scripts": {
"build": "rm -rf dist && tsc && cp src/config.json dist/"
}
}
For getting the IP Camera video link:
IP
and PORT
in browserThere are two primary contenders for python apps on Android
This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."
This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.
Both are active projects and their github accounts shows a fair amount of recent activity.
Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.
On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.
I went to system
preferences -> mysql -> initialize database -> use legacy password encryption(instead of strong) -> entered same password
as my config.inc.php
file, restarted the apache server and it worked. I was still suspicious about it so I stopped the apache and mysql server and started them again and now it's working.
you can remove it first, and install again ,it will be ok. for centos:
yum remove python-pip
yum install python-pip
I am facing Same Problem i do following Setup Now Application Work fine
1-
<compilation debug="true" targetFramework="4.7.1">
<assemblies>
<add assembly="netstandard, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=cc7b13ffcd2ddd51"/>
</assemblies>
</compilation>
2- Add Reference
**C:\Program Files (x86)\Microsoft Visual
Studio\2017\Professional\Common7\IDE\Extensions\Microsoft\ADL
Tools\2.4.0000.0\ASALocalRun\netstandard.dll**
3-
Copy Above Path Dll to Application Bin Folder on web server
You can try creating a css for your font with font-face (like explained here)
Step #1
Create a css file with font face and place it somewhere, like in assets/fonts
customfont.css
@font-face {
font-family: YourFontFamily;
src: url("/assets/font/yourFont.otf") format("truetype");
}
Step #2
Add the css to your .angular-cli.json in the styles
config
"styles":[
//...your other styles
"assets/fonts/customFonts.css"
]
Do not forget to restart ng serve
after doing this
Step #3
Use the font in your code
component.css
span {font-family: YourFontFamily; }
Just remove /Observable
from 'rxjs/Observable';
If you then get Cannot find module 'rxjs-compat/Observable'
just put below line to thr terminal and press enter.
npm install --save rxjs-compat
As @cryptoboy said - check what pip/python version you have installed
demon@UbuntuHP:~$ pip -V
demon@UbuntuHP:~$ pip2 -V
demon@UbuntuHP:~$ pip3 -V
and then check for no-needed libraries in your .local/lib/ folder.
I did backup of settings when I was migrating to newer Kubuntu and in had .local/lib/python2.7/ folder in my home directory. Installed python 3.6. I just removed the old folder and now everything works great!
It also might be that you haven't declared you Dependency Injected service, as a provider in the component that you injected it to. That was my case :)
The answers of installing pip via:
curl https://bootstrap.pypa.io/get-pip.py |sudo python
or curl https://bootstrap.pypa.io/get-pip.py | python
did not work for me as I kept on getting the error:
Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping
ERROR: Could not find a version that satisfies the requirement pip (from versions: none)
ERROR: No matching distribution found for pip
I had to install pip
manually via:
pip
distribution websitetar.gz
versioncd
into the directorypython setup.py install
In such a case I would recommand using the ternary operator:
child: condition ? Container() : Center()
and try to avoid code of the form:
if (condition) return A else return B
which is needlessly more verbose than the ternary operator.
But if more logic is needed you may also:
The Builder widget is meant for allowing the use of a closure when a child widget is required:
A platonic widget that calls a closure to obtain its child widget.
It is convenient anytime you need logic to build a widget, it avoids the need to create a dedicated function.
You use the Builder widget as the child, you provide your logic in its builder
method:
Center(
child: Builder(
builder: (context) {
// any logic needed...
final condition = _whateverLogicNeeded();
return condition
? Container();
: Center();
}
)
)
The Builder provides a convenient place to hold the creational logic. It is more straightforward than the immediate anonymous function proposed by atreeon.
Also I agree that the logic should be extracted from the UI code, but when it's really UI logic it is sometimes more legible to keep it there.
It is because TypeScript 2.7 includes a strict class checking where all the properties should be initialized in the constructor. A workaround is to add
the !
as a postfix to the variable name:
makes!: any[];
After mounting on drive, use shutil.unpack_archive. It works with almost all archive formats (e.g., “zip”, “tar”, “gztar”, “bztar”, “xztar”) and it's simple:
import shutil
shutil.unpack_archive("filename", "path_to_extract")
There is two way for hide a element
Use the "hidden" html attribute But in angular you can bind it with one or more fields like this :
<input class="txt" type="password" [(ngModel)]="input_pw" [hidden]="isHidden">
2.Better way of doing this is to use " *ngIf " directive like this :
<input class="txt" type="password" [(ngModel)]="input_pw" *ngIf="!isHidden">
Now why this is a better way because it doesn't just hide the element, it will removes it from the html code so this will help your page to render.
I had the same issue and I fixed it this way:
mywork
.myWork
. Let us call the class HelloWorld
.Note: First, make sure that Java is running properly using the CMD command in that way you will understand the problem is on eclipse and not on JDK.
My project use ButterKnife and Retro lambda, setting JavaVersion.VERSION_1_8 will not work. It always blames at ButterKnife static interface function until I found this Migrate from Retrolambda
TL;DR
Just add JavaVersion.VERSION_1_8 and completely REMOVE retrolambda from your project. It will build successfully.
Following what @viveknuna suggested, I upgraded to the latest version of node.js and npm using the downloaded installer. I also installed the latest version of yarn using a downloaded installer. Then, as you can see below, I upgraded angular-cli and typescript. Here's what that process looked like:
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g @angular/cli@latest
C:\Users\Jack\AppData\Roaming\npm\ng -> C:\Users\Jack\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\@angular\cli\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
+ @angular/[email protected]
added 75 packages, removed 166 packages, updated 61 packages and moved 24 packages in 29.084s
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm install -g typescript
C:\Users\Jack\AppData\Roaming\npm\tsserver -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsserver
C:\Users\Jack\AppData\Roaming\npm\tsc -> C:\Users\Jack\AppData\Roaming\npm\node_modules\typescript\bin\tsc
+ [email protected]
updated 1 package in 2.427s
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>node -v
v8.10.0
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm -v
5.6.0
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn --version
1.5.1
Thereafter, I ran yarn
and npm start
in my angular folder and all appears to be well. Here's what that looked like:
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>yarn
yarn install v1.5.1
[1/4] Resolving packages...
[2/4] Fetching packages...
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
warning "@angular/cli > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning "@angular/cli > @angular-devkit/schematics > @schematics/[email protected]" has incorrect peer dependency "@angular-devkit/[email protected]".
warning " > [email protected]" has incorrect peer dependency "@angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0".
warning " > [email protected]" has incorrect peer dependency "@angular/core@^2.3.1 || >=4.0.0-beta <5.0.0".
[4/4] Building fresh packages...
Done in 232.79s.
D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular>npm start
> [email protected] start D:\Dev\AspNetBoilerplate\MyProject\3.5.0\angular
> ng serve --host 0.0.0.0 --port 4200
** NG Live Development Server is listening on 0.0.0.0:4200, open your browser on http://localhost:4200/ **
Date: 2018-03-22T13:17:28.935Z
Hash: 8f226b6fa069b7c201ea
Time: 22494ms
chunk {account.module} account.module.chunk.js () 129 kB [rendered]
chunk {app.module} app.module.chunk.js () 497 kB [rendered]
chunk {common} common.chunk.js (common) 1.46 MB [rendered]
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 515 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 1.1 MB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 1.53 MB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 15.1 MB [initial] [rendered]
webpack: Compiled successfully.
Boosting your maven-compiler-plugin to 3.8.0 seems to be necessary but not sufficient. If you're still having problems, you should also make sure your JAVA_HOME environment variable is set to Java 10 (or 11) if you're running from the command line. (The error message you get won't tell you this.) Or if you're running from an IDE, you need to make sure it is set to run maven with your current JDK.
For disabling any Button in flutter such as FlatButton
, RaisedButton
, MaterialButton
, IconButton
etc all you need to do is to set the onPressed
and onLongPress
properties to null. Below is some simple examples for some of the buttons:
FlatButton (Enabled)
FlatButton(
onPressed: (){},
onLongPress: null, // Set one as NOT null is enough to enable the button
textColor: Colors.black,
disabledColor: Colors.orange,
disabledTextColor: Colors.white,
child: Text('Flat Button'),
),
FlatButton (Disabled)
FlatButton(
onPressed: null,
onLongPress: null,
textColor: Colors.black,
disabledColor: Colors.orange,
disabledTextColor: Colors.white,
child: Text('Flat Button'),
),
RaisedButton (Enabled)
RaisedButton(
onPressed: (){},
onLongPress: null, // Set one as NOT null is enough to enable the button
// For when the button is enabled
color: Colors.lightBlueAccent,
textColor: Colors.black,
splashColor: Colors.blue,
elevation: 8.0,
// For when the button is disabled
disabledTextColor: Colors.white,
disabledColor: Colors.orange,
disabledElevation: 0.0,
child: Text('Raised Button'),
),
RaisedButton (Disabled)
RaisedButton(
onPressed: null,
onLongPress: null,
// For when the button is enabled
color: Colors.lightBlueAccent,
textColor: Colors.black,
splashColor: Colors.blue,
elevation: 8.0,
// For when the button is disabled
disabledTextColor: Colors.white,
disabledColor: Colors.orange,
disabledElevation: 0.0,
child: Text('Raised Button'),
),
IconButton (Enabled)
IconButton(
onPressed: () {},
icon: Icon(Icons.card_giftcard_rounded),
color: Colors.lightBlueAccent,
disabledColor: Colors.orange,
),
IconButton (Disabled)
IconButton(
onPressed: null,
icon: Icon(Icons.card_giftcard_rounded),
color: Colors.lightBlueAccent,
disabledColor: Colors.orange,
),
Note: Some of buttons such as IconButton
have only the onPressed
property.
I was facing the same issue and i found out that I was having two terminals in visual studio code, On first terminal it was already running my flutter project and on the other terminal I was running different solutions shared in this thread. Due to this reason no solution was working for me. So there are two ways you can solve this problem. 1- Restart visual studio code (it will automatically close the terminals) 2- Stop the terminal in which flutter project is already running and then run flutter clean command.
You can use DropDownButton
class in order to create drop down list :
...
...
String dropdownValue = 'One';
...
...
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButton<String>(
value: dropdownValue,
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>['One', 'Two', 'Free', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
...
...
please refer to this flutter web page
If you have stumbled upon this problem due to getting this error recently out of nowhere in react native- this is due to the latest BREAKING CHANGE in Google Play service and Firebase. Check this thread first -
https://github.com/facebook/react-native/issues/25293
And solution would mostly be like this -
https://github.com/facebook/react-native/issues/25293#issuecomment-503045776
I had a big dataset and .loc[] was taking too long so I found a vectorized way to do it. Recall that you can set a column to a logical operator, so this works:
file['Flag'] = (file['Claim_Amount'] > 0)
This gives a Boolean, which I wanted, but you can multiply it by, say, 1 to make an Integer.
In my case it was the order of importing in index.js
/* /components/index.js */
import List from './list.vue';
import ListItem from './list-item.vue';
export {List, ListItem}
and if you use ListItem
component inside of List
component it will show this error as it is not correctly imported. Make sure that all dependency components are imported first in order.
Use
implementation 'com.android.support:appcompat-v7:27.1.1'
Don't use like
implementation 'com.android.support:appcompat-v7:27.+'
It may give you an error and don't use an older version than this.
or event don't do like this
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
etc... numbers of libraries and then
implementation 'com.android.support:appcompat-v7:27.+'
the same library but it has a different version, it can give you an error.
I know this has already been highly voted in here by now, but I'd rather go for a custom directive approach and rely on the ClipboardEvent as @jockeisorby suggested, while also making sure the listener is correctly removed (same function needs to be provided for both the add and remove event listeners)
stackblitz demo
import { Directive, Input, Output, EventEmitter, HostListener } from "@angular/core";
@Directive({ selector: '[copy-clipboard]' })
export class CopyClipboardDirective {
@Input("copy-clipboard")
public payload: string;
@Output("copied")
public copied: EventEmitter<string> = new EventEmitter<string>();
@HostListener("click", ["$event"])
public onClick(event: MouseEvent): void {
event.preventDefault();
if (!this.payload)
return;
let listener = (e: ClipboardEvent) => {
let clipboard = e.clipboardData || window["clipboardData"];
clipboard.setData("text", this.payload.toString());
e.preventDefault();
this.copied.emit(this.payload);
};
document.addEventListener("copy", listener, false)
document.execCommand("copy");
document.removeEventListener("copy", listener, false);
}
}
and then use it as such
<a role="button" [copy-clipboard]="'some stuff'" (copied)="notify($event)">
<i class="fa fa-clipboard"></i>
Copy
</a>
public notify(payload: string) {
// Might want to notify the user that something has been pushed to the clipboard
console.info(`'${payload}' has been copied to clipboard`);
}
Note: notice the window["clipboardData"]
is needed for IE as it does not understand e.clipboardData
Your can use DataSourceBuilder for this purpose.
@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(Environment env) {
final String datasourceUsername = env.getRequiredProperty("spring.datasource.username");
final String datasourcePassword = env.getRequiredProperty("spring.datasource.password");
final String datasourceUrl = env.getRequiredProperty("spring.datasource.url");
final String datasourceDriver = env.getRequiredProperty("spring.datasource.driver-class-name");
return DataSourceBuilder
.create()
.username(datasourceUsername)
.password(datasourcePassword)
.url(datasourceUrl)
.driverClassName(datasourceDriver)
.build();
}
This worked for me!!!!
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>academy.learnprogramming</groupId>
<artifactId>hello-maven</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<target>10</target>
<source>10</source>
<release>10</release>
</configuration>
</plugin>
</plugins>
</build>
</project>
Looks like you forgot the mode parameter when calling open
, try w
:
file = open("copy.txt", "w")
file.write("Your text goes here")
file.close()
The default value is r
and will fail if the file does not exist
'r' open for reading (default)
'w' open for writing, truncating the file first
Other interesting options are
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
See Doc for Python2.7 or Python3.6
-- EDIT --
As stated by chepner in the comment below, it is better practice to do it with a with
statement (it guarantees that the file will be closed)
with open("copy.txt", "w") as file:
file.write("Your text goes here")
Below are the steps that worked for me
from google.colab import drive drive.mount('/content/drive')
import sys sys.path.insert(0,’/content/drive/My Drive/ColabNotebooks’)
%cd drive/MyDrive/ColabNotebooks %pwd
import my_module
If you get the following error 'Name Null is not defined' then do the following
5.1 Download my_module.ipynb from colab as my_module.py file (file->Download .py)
5.2 Upload the *.py file to drive/MyDrive/ColabNotebooks in Google drive
5.3 import my_module will work now
For me changing compile to implementation fixed it
Before
compile 'androidx.recyclerview:recyclerview:1.0.0'
compile 'androidx.cardview:cardview:1.0.0'
//Retrofit Dependencies
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
After
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
//Retrofit Dependencies
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
You can have a datetime picker when using matInput
with type datetime-local
like so:
<mat-form-field>
<input matInput type="datetime-local" placeholder="start date">
</mat-form-field>
You can click on each part of the placeholder to set the day, month, year, hours,minutes and whether its AM or PM.
Check your XML
files for resolving the Errors.Most of the time the changes made to your XML
files get Affected.so try to check the last changes you made.
Try to Clean your Project....It Works
Happy Coding:)
if you don't need to pass arguments to function, just remove () from function like below:
<td><span onClick={this.toggle}>Details</span></td>
but if you want to pass arguments, you should do like below:
<td><span onClick={(e) => this.toggle(e,arg1,arg2)}>Details</span></td>
This examples shows calling a method
class ParentPage extends StatefulWidget {
@override
_ParentPageState createState() => _ParentPageState();
}
class _ParentPageState extends State<ParentPage> {
final GlobalKey<ChildPageState> _key = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Parent")),
body: Center(
child: Column(
children: <Widget>[
Expanded(
child: Container(
color: Colors.grey,
width: double.infinity,
alignment: Alignment.center,
child: RaisedButton(
child: Text("Call method in child"),
onPressed: () => _key.currentState.methodInChild(), // calls method in child
),
),
),
Text("Above = Parent\nBelow = Child"),
Expanded(
child: ChildPage(
key: _key,
function: methodInParent,
),
),
],
),
),
);
}
methodInParent() => Fluttertoast.showToast(msg: "Method called in parent", gravity: ToastGravity.CENTER);
}
class ChildPage extends StatefulWidget {
final Function function;
ChildPage({Key key, this.function}) : super(key: key);
@override
ChildPageState createState() => ChildPageState();
}
class ChildPageState extends State<ChildPage> {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.teal,
width: double.infinity,
alignment: Alignment.center,
child: RaisedButton(
child: Text("Call method in parent"),
onPressed: () => widget.function(), // calls method in parent
),
);
}
methodInChild() => Fluttertoast.showToast(msg: "Method called in child");
}
import pickle
intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()
Test your pickle quickly. pickle is a part of standard python library and available by default.
What would be wrong with doing;
<div className="" key={index}>
{i.title}
</div>
[/*Use IIFE */]
{(function () {
if (child.children && child.children.length !== 0) {
let menu = createMenu(child.children);
console.log("nested menu", menu);
return menu;
}
})()}
I’m lazy and my memory is bad, so I decided to create easycolab which is easier to memorize and type:
import easycolab as ec
ec.mount()
Make sure to install it first: !pip install easycolab
The mount()
method basically implement this:
from google.colab import drive
drive.mount(‘/content/drive’)
cd ‘/content/gdrive/My Drive/’
You can try as follows:
//------ js/functions.js ------
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ js/main.js ------
import { square, diag } from './functions.js';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
You can also import completely:
//------ js/main.js ------
import * as lib from './functions.js';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
Normally we use ./fileName.js
for importing own js file/module
and fileName.js
is used for importing package/library
module
When you will include the main.js file to your webpage you must set the type="module" attribute as follows:
<script type="module" src="js/main.js"></script>
For more details please check ES6 modules
The below code useful to display in the map insertion order.
<ul>
<li *ngFor="let recipient of map | keyvalue: asIsOrder">
{{recipient.key}} --> {{recipient.value}}
</li>
</ul>
.ts file add the below code.
asIsOrder(a, b) {
return 1;
}
Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate
is a date input field in template.
import {formatDate} from '@angular/common';
this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));
In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.
For QtCreator and Examples and API Docs:
sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `
sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`
sudo apt-get install build-essential qtcreator qt5-default
If something is also missing, then:
sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `
Hope to be helpful.
Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing
This error can also show up if there are parts in your string that json.loads()
does not recognize. An in this example string, an error will be raised at character 27 (char 27)
.
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
My solution to this would be to use the string.replace()
to convert these items to a string:
import json
string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""
string = string.replace("False", '"False"')
dict_list = json.loads(string)
You can use Programmatic Navigation.In order to go back, you use this:
router.go(n)
Where n can be positive or negative (to go back). This is the same as history.back().So you can have your element like this:
<a @click="$router.go(-1)">back</a>
You're only exporting it in your NgModule, you need to import it too
@NgModule({
imports: [
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule,
]
exports: [
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule,
],
declarations: [
SearchComponent,
],
})export class MaterialModule {};
better yet
const modules = [
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule
];
@NgModule({
imports: [...modules],
exports: [...modules]
,
})export class MaterialModule {};
You're declaring component (SearchComponent) depending on Angular Material before all Angular dependency are imported
Like BrowserAnimationsModule
Try moving it to MaterialModule, or before it
Go to preferences(settings) : click on Build,Execution,Deployment .....then select : Instant Run ......and uncheck its topmost checkbox (i.e Disable Instant Run)
Since December 2020 xlrd no longer supports xlsx-Files as explained in the official changelog. You can use openpyxl
instead:
pip install openpyxl
And in your python-file:
import pandas as pd
pd.read_excel('path/to/file.xlsx', engine='openpyxl')
Edit file /usr/share/phpmyadmin/libraries/sql.lib.php
using this command:
sudo nano +613 /usr/share/phpmyadmin/libraries/sql.lib.php
On line 613 the count function always evaluates to true since there is no closing parenthesis after $analyzed_sql_results['select_expr']
. Making the below replacements resolves this, then you will need to delete the last closing parenthesis on line 614, as it's now an extra parenthesis.
Replace:
((empty($analyzed_sql_results['select_expr']))
|| (count($analyzed_sql_results['select_expr'] == 1)
&& ($analyzed_sql_results['select_expr'][0] == '*')))
With:
((empty($analyzed_sql_results['select_expr']))
|| (count($analyzed_sql_results['select_expr']) == 1)
&& ($analyzed_sql_results['select_expr'][0] == '*'))
Restart the server apache:
sudo service apache2 restart
From v2.0 many users are using path, but we can use either path or url. For example in django 2.1.1 mapping to functions through url can be done as follows
from django.contrib import admin
from django.urls import path
from django.contrib.auth import login
from posts.views import post_home
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^posts/$', post_home, name='post_home'),
]
where posts is an application & post_home is a function in views.py
The corrected code is
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand:
words = line.decode().split()
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
running the code above produces
{'Who': 1, 'is': 1, 'already': 1, 'sick': 1, 'and': 1, 'pale': 1, 'with': 1, 'grief': 1}
I have MongoDB shell version v3.6.4, below code use mongoclient, It's good for me:
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var url = 'mongodb://localhost:27017/video';
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, client)
{
assert.equal(null, err);
console.log("Successfully connected to server");
var db = client.db('video');
// Find some documents in our collection
db.collection('movies').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc.title);
});
// Close the DB
client.close();
});
// Declare success
console.log("Called find()");
});
For me, I got this error while working on some Udacity projects. I fixed it by adding the following code to the top-level build.gradle file.
allprojects {
String osName = System.getProperty("os.name").toLowerCase()
if (osName.contains("windows")) {
buildDir = "C:/tmp/${rootProject.name}/${project.name}"
}
repositories {
jcenter()
google()
}
}
Unlike it's most popular commercial competitor, numpy pretty much from the outset is about "arbitrary-dimensional" arrays, that's why the core class is called ndarray
. You can check the dimensionality of a numpy array using the .ndim
property. The .shape
property is a tuple of length .ndim
containing the length of each dimensions. Currently, numpy can handle up to 32 dimensions:
a = np.ones(32*(1,))
a
# array([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1.]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])
a.shape
# (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
a.ndim
# 32
If a numpy array happens to be 2d like your second example, then it's appropriate to think about it in terms of rows and columns. But a 1d array in numpy is truly 1d, no rows or columns.
If you want something like a row or column vector you can achieve this by creating a 2d array with one of its dimensions equal to 1.
a = np.array([[1,2,3]]) # a 'row vector'
b = np.array([[1],[2],[3]]) # a 'column vector'
# or if you don't want to type so many brackets:
b = np.array([[1,2,3]]).T
It look's as if you forgot to activate you virtual environment
try running python3 -m venv venv
or if you already have virtual environment
set up try to activate it by running source venv/bin/activate
This is my code for extracting pdf.
import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here' + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)
Please refer to this repo of mine for more details.
Here is my solution
private static final int NOTIFICATION_ID = 200;
private static final String CHANNEL_ID = "myChannel";
private static final String CHANNEL_NAME = "myChannelName";
private void startForeground() {
final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getApplicationContext(), CHANNEL_ID);
Notification notification;
notification = mBuilder.setTicker(getString(R.string.app_name)).setWhen(0)
.setOngoing(true)
.setContentTitle(getString(R.string.app_name))
.setContentText("Send SMS gateway is running background")
.setSmallIcon(R.mipmap.ic_launcher)
.setShowWhen(true)
.build();
NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE);
//All notifications should go through NotificationChannel on Android 26 & above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(NOTIFICATION_ID, notification);
}
Hope it will help :)
I have added dataType: 'jsonp' and it works!
$.ajax({
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
url: '',
success: function(jsondata){
}
})
JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More
You would need also to import the HttpClientModule
from Angular '@angular/common/http'
into your main AppModule for making HTTP requests.
app.module.ts
import { HttpClientModule } from '@angular/common/http';
import { ServiceService } from '../../../services/service.service';
@NgModule({
imports: [
HttpClientModule
],
providers: [
ServiceService
]
})
export class AppModule {...}
In Angular 5, the query params are accessed by subscribing to this.route.queryParams
(note that later Angular versions recommend queryParamMap
, see also other answers).
Example: /app?param1=hallo¶m2=123
param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
console.log('Called Constructor');
this.route.queryParams.subscribe(params => {
this.param1 = params['param1'];
this.param2 = params['param2'];
});
}
whereas, the path variables are accessed by this.route.snapshot.params
Example: /param1/:param1/param2/:param2
param1: string;
param2: string;
constructor(private route: ActivatedRoute) {
this.param1 = this.route.snapshot.params.param1;
this.param2 = this.route.snapshot.params.param2;
}
This work for me. In the android\app\build.gradle file you need to specify the following
compileSdkVersion 26
buildToolsVersion "26.0.1"
and then find this
compile "com.android.support:appcompat-v7"
and make sure it says
compile "com.android.support:appcompat-v7:26.0.1"
I had this problem i.e. works fine when pasted into browser but 505s when done through java. It was simply the spaces that needed to be escaped/encoded.
How about
Select I.Fee
From Item I
WHERE (days(GETDATE()) - days(I.DateCreated) < 365)
I had the similar issue and the above examples doesn't help me to read properties. I have posted the complete class which will help you to read properties values from application.properties file in SpringBoot application in the below link.
Spring Boot - Environment @Autowired throws NullPointerException
From the Express site, define a NotFound exception and throw it whenever you want to have a 404 page OR redirect to /404 in the below case:
function NotFound(msg){
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
NotFound.prototype.__proto__ = Error.prototype;
app.get('/404', function(req, res){
throw new NotFound;
});
app.get('/500', function(req, res){
throw new Error('keyboard cat!');
});
Plenty of good solutions here.
One challenge not really addressed in any of them is how to visually identify certain hard-to-spot non-ASCII characters that resemble other plain ASCII ones. For example, en dashes can appear almost exactly like hyphens and curly quotes look a lot like straight quotes, depending on your text editor's font.
This one-liner, which should work on Mac or Linux, will strip characters not in the ASCII printable range and show you the differences side-by-side:
# assumes Bash shell; for Bourne shell (sh), rearrange as a pipe and
# give '-' as second argument to 'sdiff' instead
sdiff --suppress-common-lines script.py <(tr -cd '\11\12\15\40-\176' <script.py)
The characters \11
, \12
, and \15
are tab, newline, and carriage return, respectively, in octal; the remaining range is the visible ASCII characters. (hat tip)
Another tip gleaned from this SO thread uses an inverse character class consisting of anything not in the ASCII visible range, and highlights it:
grep --color '[^ -~]' script.py
This should also work fine with the macOS / BSD version of grep.
Even though the question is quite fuzzy and the HTML snippet is quite limited, I suppose
.feature_desc {
display: block;
}
.feature_desc:before {
content: "";
display: block;
}
might give you want you want to achieve without the <br/>
element. Though it would help to see your CSS applied to these elements.
NOTE. The example above doesn't work in IE7 though.
Haha, I have been stuck at that point a while ago as well, so I am glad I can help you out with a solution, that worked for me at least :)
What you want to do is define a new style within values/styles.xml so it looks like this
<resources>
<style name = "AppTheme" parent = "android:Theme.Holo.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<style name = "NoActionBar" parent = "@android:style/Theme.Holo.Light">
<item name = "android:windowActionBar">false</item>
<item name = "android:windowNoTitle">true</item>
</style>
</resources>
Only the NoActionBar style is intresting for you. At last you have to set is as your application's theme in the AndroidManifest.xml so it looks like this
<application
android:allowBackup = "true"
android:icon = "@drawable/ic_launcher"
android:label = "@string/app_name"
android:theme = "@style/NoActionBar" <!--This is the important line-->
>
<activity
[...]
I hope this helps, if not, let me know.
SHOW CREATE TABLE yourTable;
or
SHOW COLUMNS FROM yourTable;
The Material Design Typography page has demos for some of these fonts and suggestions on choosing fonts and styles.
For code sleuths: fonts.xml
is the definitive and ever-expanding list of Android fonts.
Set the android:fontFamily
and android:textStyle
attributes, e.g.
<!-- Roboto Bold -->
<TextView
android:fontFamily="sans-serif"
android:textStyle="bold" />
to the desired values from this table:
Font | android:fontFamily | android:textStyle
-------------------------|-----------------------------|-------------------
Roboto Thin | sans-serif-thin |
Roboto Light | sans-serif-light |
Roboto Regular | sans-serif |
Roboto Bold | sans-serif | bold
Roboto Medium | sans-serif-medium |
Roboto Black | sans-serif-black |
Roboto Condensed Light | sans-serif-condensed-light |
Roboto Condensed Regular | sans-serif-condensed |
Roboto Condensed Medium | sans-serif-condensed-medium |
Roboto Condensed Bold | sans-serif-condensed | bold
Noto Serif | serif |
Noto Serif Bold | serif | bold
Droid Sans Mono | monospace |
Cutive Mono | serif-monospace |
Coming Soon | casual |
Dancing Script | cursive |
Dancing Script Bold | cursive | bold
Carrois Gothic SC | sans-serif-smallcaps |
(Noto Sans is a fallback font; you can't specify it directly)
Note: this table is derived from fonts.xml
. Each font's family name and style is listed in fonts.xml, e.g.
<family name="serif-monospace">
<font weight="400" style="normal">CutiveMono.ttf</font>
</family>
serif-monospace
is thus the font family, and normal
is the style.
Based on the log of fonts.xml and the former system_fonts.xml, you can see when each font was added:
In Case of not considering '0' or 'NULL' in average function. Simply use
AVG(NULLIF(your_column_name,0))
It depends on what you are comparing to None. Some classes have custom comparison methods that treat == None
differently from is None
.
In particular the output of a == None
does not even have to be boolean !! - a frequent cause of bugs.
For a specific example take a numpy array where the ==
comparison is implemented elementwise:
import numpy as np
a = np.zeros(3) # now a is array([0., 0., 0.])
a == None #compares elementwise, outputs array([False, False, False]), i.e. not boolean!!!
a is None #compares object to object, outputs False
I had this error running php-fpm in a chroot jail. I tried creating etc/php.ini and /usr/share/zoneinfo in the chroot directory, but it just didn't work. I even tried strace-ing the php-fpm daemons to see what file they were missing - nothing jumped out.
So in case Google brings you here because you get this error when using php-fpm configured for chroot, you can probably fix it by adding this line to /etc/php-fpm.d/www.conf
in the ENV section:
env[TZ] = America/New_York
A php-fpm restart is normally required for it to take effect. Hope this helps somebody out there.
I also had this problem on OSX. The solution was uncommenting the extension = pgsql.so
in php.ini.default
and deleting the .default
suffix, since the file php.ini
was not there.
If you are using XAMPP, the php.ini file resides in /XAMPP/xampfiles/etc
This went a little weird for me, from one day to the next one the script that have been working since days just stop working. There wasn´t a newer version of mysql or any kind of upgrade but I was getting the same error, so I give a last try to the CSV file and notice that the end of lines were using \n instead of the expected ( per my script ) \r\n so I save it with the right EOL and run the script again without any trouble.
I think is kind of odd for mysql to tell me The used command is not allowed with this MySQL version since the reason was completely different.
My working command looks like this:
LOAD DATA LOCAL INFILE 'file-name' IGNORE INTO TABLE table-name CHARACTER SET latin1 FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES.
Adding mode:'no-cors'
to the request header guarantees that no response will be available in the response
Adding a "non standard" header, line 'access-control-allow-origin'
will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent
You're also doing fetch
wrong ... fetch
returns a "promise" for a Response
object which has promise creators for json
, text
, etc. depending on the content type...
In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work
function send(){
var myVar = {"id" : 1};
console.log("tuleb siia", document.getElementById('saada').value);
fetch("http://localhost:3000", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify(myVar)
}).then(function(response) {
return response.json();
}).then(function(muutuja){
document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
});
}
however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do
function send(){
var myVar = {"id" : 1};
console.log("tuleb siia", document.getElementById('saada').value);
fetch("http://localhost:3000", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify(myVar)
}).then(function(response) {
return response.text();
}).then(function(muutuja){
document.getElementById('väljund').innerHTML = muutuja;
});
}
Clearly you need a factory pattern!
KeyFactory keyFactory = new KeyFactory();
KeyObj keyObj = keyFactory.getKeyObj(wParam);
keyObj.doStuff();
class VK_F11 extends KeyObj {
boolean val;
public void doStuff() {
val = !val;
}
}
class VK_F12 extends KeyObj {
boolean val;
public void doStuff() {
val = !val;
}
}
class KeyFactory {
public KeyObj getKeyObj(int param) {
switch(param) {
case VK_F11:
return new VK_F11();
case VK_F12:
return new VK_F12();
}
throw new KeyNotFoundException("Key " + param + " was not found!");
}
}
:D
</sarcasm>
First WebClient
is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:
string address = string.Format(
"http://foobar/somepage?arg1={0}&arg2={1}",
Uri.EscapeDataString("escape me"),
Uri.EscapeDataString("& me !!"));
string text;
using (WebClient client = new WebClient())
{
text = client.DownloadString(address);
}
No, [^\x20-\x7E]
is not ASCII.
This is real ASCII:
[^\x00-\x7F]
Otherwise, it will trim out newlines and other special characters that are part of the ASCII table!
Maybe VisualVM can help (haven't yet had a chance to try it myself). Link:
http://java.sun.com/javase/6/docs/technotes/guides/visualvm/coredumps.html
Works great for me, and you can chose how much you want to go back in the functions:
function getCaller(functionBack= 0) {
const back = functionBack * 2;
const stack = new Error().stack.split('at ');
const stackIndex = stack[3 + back].includes('C:') ? (3 + back) : (4 + back);
const isAsync = stack[stackIndex].includes('async');
let result;
if (isAsync)
result = stack[stackIndex].split(' ')[1].split(' ')[0];
else
result = stack[stackIndex].split(' ')[0];
return result;
}
the safest way is to put the ! for the regex negation within the [[ ]]
like this:
if [[ ! ${STR} =~ YOUR_REGEX ]]; then
otherwise it might fail on certain systems.
$('#some_select_box option:selected').remove();
Use >>
instead of >
when directing output to a file:
your_command >> file_to_append_to
If file_to_append_to
does not exist, it will be created.
Example:
$ echo "hello" > file
$ echo "world" >> file
$ cat file
hello
world
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
String to byte array: "FooBar".split('').map(c => c.charCodeAt(0));
Byte array to string: [102, 111, 111, 98, 97, 114].map(c => String.fromCharCode(c)).join('');
Yes, your conclusion is correct. socket.recv
is a blocking call.
socket.recv(1024)
will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv
won't block.
socket.recv
will also end with an empty string if the connection is closed or there is an error.
If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking
.
I had issues with socket.setblocking
in the past, but feel free to try it if you want.
I think that if you define the logic in an extension method the code will be much more readable:
public static class EnumerableExtensions {
public static string Join<T>(this IEnumerable<T> self, string separator) {
return String.Join(separator, self.Select(e => e.ToString()).ToArray());
}
}
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString() {
return string.Format("{0} {1}", FirstName, LastName);
}
}
// ...
List<Person> people = new List<Person>();
// ...
string fullNames = people.Join(", ");
string lastNames = people.Select(p => p.LastName).Join(", ");
AngularJS form elements look for the required
attribute to perform validation functions. ng-required
allows you to set the required
attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)
As an example, <input required>
and <input ng-required="true">
are essentially the same thing
If you are wondering why this is this way, (and not just make <input required="true">
or <input required="false">
), it is due to the limitations of HTML - the required
attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false"
would be invalid HTML)
You can do the same in python by simply importing the second file, code at the top level will run when imported. I'd suggest this is messy at best, and not a good programming practice. You would be better off organizing your code into modules
Example:
F1.py:
print "Hello, "
import f2
F2.py:
print "World!"
When run:
python ./f1.py
Hello,
World!
Edit to clarify: The part I was suggesting was "messy" is using the import
statement only for the side effect of generating output, not the creation of separate source files.
All I'm really interested in is the ownership and permissions information for the first level subdirectories.
I found a easy solution while playing my fish, which fits your need perfectly.
ll `ls`
or
ls -l $(ls)
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property]
or, even worse, x.key
will give you completely misleading results.
It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty
is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)
If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object
will give you your desired effect.
Since using hasOwnProperty
is probably what you want, and considering that you may want a fallback method, I present to you the following solution:
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
The above is a working, cross-browser, solution to hasOwnProperty
, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.
Using Kotlin
val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
try {
val jsonObject = JSONObject(data)
val infoObj = jsonObject.getJSONObject("ApiInfo")
} catch (e: Exception) {
}
An analytic solution with only one nested query:
SELECT * FROM
(
SELECT t.*, Row_Number() OVER (ORDER BY name) MyRow FROM sometable t
)
WHERE MyRow BETWEEN 10 AND 20;
Rank()
could be substituted for Row_Number()
but might return more records than you are expecting if there are duplicate values for name.
You have two options.
Make the menu bar temporarily visible.
Make the menu bar permanently visible.
Steps:
$table->date('user_id')->nullable();
In your file create_file
, the null option must be enabled.
$(document).ready(function () {
$('#chkDisableEnableElements').change(function () {
if ($('#chkDisableEnableElements').is(':checked')) {
enableElements($('#divDifferentElements').children());
}
else {
disableElements($('#divDifferentElements').children());
}
});
});
function disableElements(el) {
for (var i = 0; i < el.length; i++) {
el[i].disabled = true;
disableElements(el[i].children);
}
}
function enableElements(el) {
for (var i = 0; i < el.length; i++) {
el[i].disabled = false;
enableElements(el[i].children);
}
}
I like to use a custom "foreach" function of sorts for these kinds of things:
function Each( objs, func )
{
if ( objs.length ) for ( var i = 0, ol = objs.length, v = objs[ 0 ]; i < ol && func( v, i ) !== false; v = objs[ ++i ] );
else for ( var p in objs ) if ( func( objs[ p ], p ) === false ) break;
}
(Can't remember where I found the above function, but it has been quite useful.)
Then after fetching your objects (to elements
in this example) just do
Each( elements, function( element )
{
element.addEventListener( "mouseover", function()
{
element.classList.add( "active" );
//element.setAttribute( "class", "active" );
element.setAttribute( "src", "newsource" );
});
// Remove class and new src after "mouseover" ends, if you wish.
element.addEventListener( "mouseout", function()
{
element.classList.remove( "active" );
element.setAttribute( "src", "originalsource" );
});
});
classList
is a simple way for handling elements' classes. Just needs a shim for a few browsers. If you must use setAttribute
you must remember that whatever is set with it will overwrite the previous values.
EDIT: Forgot to mention that you need to use attachEvent
instead of addEventListener
on some IE versions. Test with if ( document.addEventListener ) {...}
.
I am not experienced at all so feel free to correct things. However, I tried all these answers, but always had a problem in some screen. So I tried the following that worked for me and looks as I want it in almost all screens with the exception of mobile.
<div class="wrapper">
<div id="Section-Title">
<div id="h2"> YOUR TITLE
<div id="line"><hr></div>
</div>
</div>
</div>
CSS:
.wrapper{
background:#fff;
max-width:100%;
margin:20px auto;
padding:50px 5%;}
#Section-Title{
margin: 2% auto;
width:98%;
overflow: hidden;}
#h2{
float:left;
width:100%;
position:relative;
z-index:1;
font-family:Arial, Helvetica, sans-serif;
font-size:1.5vw;}
#h2 #line {
display:inline-block;
float:right;
margin:auto;
margin-left:10px;
width:90%;
position:absolute;
top:-5%;}
#Section-Title:after{content:""; display:block; clear:both; }
.wrapper:after{content:""; display:block; clear:both; }
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var d = new Date(res);
var month = d.getMonth() + 1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month < 10 ? '0' : '') + month + '/' +
(day < 10 ? '0' : '') + day;
$('#txtEndDate').val(output);
In addition to the excellent answers above, let me offer you a link to the following article (by Patrick Thomson) which explains monads by relating the concept to the JavaScript library jQuery (and its way of using "method chaining" to manipulate the DOM): jQuery is a Monad
The jQuery documentation itself doesn't refer to the term "monad" but talks about the "builder pattern" which is probably more familiar. This doesn't change the fact that you have a proper monad there maybe without even realizing it.
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
function toggleCheck(employeeId) {
var data = 'referenceid= '+ employeeId +'&referencestatus=' 1;
console.log(data);
$.ajax({
type : 'POST',
url : 'edit',
data : data,
cache: false,
async : false,
success : function(employeeId) {
alert("Success");
window.redirect = "Users.jsp";
}
});
}
When objects are constructed, it is always first construct base class subobject, therefore, base class constructor is called first, then call derived class constructors. The reason is that derived class objects contain subobjects inherited from base class. You always need to call the base class constructor to initialze base class subobjects. We usually call the base class constructor on derived class's member initialization list. If you do not call base class constructor explicitly, the compile will call the default constructor of base class to initialize base class subobject. However, implicit call on default constructor does not necessary work at all times (for example, if base class defines a constructor that could not be called without arguments).
When objects are out of scope, it will first call destructor of derived class,then call destructor of base class.
If you don't want to go back to all the activities on your application, you can use
android:launchMode="singleTask"
Learn more here: http://developer.android.com/guide/topics/manifest/activity-element.html
using(var client = new System.Net.WebClient()) {
client.UploadData(address,"PUT",data);
}
Well you can use the window.onclose
event and return false
in the event handler.
function closedWin() {
confirm("close ?");
return false; /* which will not allow to close the window */
}
if(window.addEventListener) {
window.addEventListener("close", closedWin, false);
}
window.onclose = closedWin;
Code was taken from this site.
In the other hand, if they force the closing (by using task manager or something in those lines) you cannot do anything about it.
You could use the way to solve the problem!
initialize:function(){
this.trigger('remove-compnents-cart');
var _this = this;
Backbone.View.prototype.on('remove-compnents-cart',function(){
//Backbone.View.prototype.remove;
Backbone.View.prototype.off();
_this.undelegateEvents();
})
}
Another way:Create a global variable,like this:_global.routerList
initialize:function(){
this.routerName = 'home';
_global.routerList.push(this);
}
/*remove it in memory*/
for (var i=0;i<_global.routerList.length;i++){
Backbone.View.prototype.remove.call(_global.routerList[i]);
}
A bit late and not exactly suited here, but I'm gonna add my solution here, because my question had been closed as a duplicate of this one, and because this solution is completely different.
I needed a general way to instruct Json.NET
to prefer the most specific constructor for a user defined struct type, so I can omit the JsonConstructor
attributes which would add a dependency to the project where each such struct is defined.
I've reverse engineered a bit and implemented a custom contract resolver where I've overridden the CreateObjectContract
method to add my custom creation logic.
public class CustomContractResolver : DefaultContractResolver {
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var c = base.CreateObjectContract(objectType);
if (!IsCustomStruct(objectType)) return c;
IList<ConstructorInfo> list = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).OrderBy(e => e.GetParameters().Length).ToList();
var mostSpecific = list.LastOrDefault();
if (mostSpecific != null)
{
c.OverrideCreator = CreateParameterizedConstructor(mostSpecific);
c.CreatorParameters.AddRange(CreateConstructorParameters(mostSpecific, c.Properties));
}
return c;
}
protected virtual bool IsCustomStruct(Type objectType)
{
return objectType.IsValueType && !objectType.IsPrimitive && !objectType.IsEnum && !objectType.Namespace.IsNullOrEmpty() && !objectType.Namespace.StartsWith("System.");
}
private ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
{
method.ThrowIfNull("method");
var c = method as ConstructorInfo;
if (c != null)
return a => c.Invoke(a);
return a => method.Invoke(null, a);
}
}
I'm using it like this.
public struct Test {
public readonly int A;
public readonly string B;
public Test(int a, string b) {
A = a;
B = b;
}
}
var json = JsonConvert.SerializeObject(new Test(1, "Test"), new JsonSerializerSettings {
ContractResolver = new CustomContractResolver()
});
var t = JsonConvert.DeserializeObject<Test>(json);
t.A.ShouldEqual(1);
t.B.ShouldEqual("Test");
A submodule is nothing but a clone of a git repo within another repo with some extra meta data (gitlink tree entry, .gitmodules file )
$ cd your_submodule
$ git checkout master
<hack,edit>
$ git commit -a -m "commit in submodule"
$ git push
$ cd ..
$ git add your_submodule
$ git commit -m "Updated submodule"
Try this:
Open PgAdmin -> Files -> Open pgpass.conf
You would get the path of pgpass.conf
at the bottom of the window.
Go to that location and open this file, you can find your password there.
If the above does not work, you may consider trying this:
1. edit pg_hba.conf to allow trust authorization temporarily
2. Reload the config file (pg_ctl reload)
3. Connect and issue ALTER ROLE / PASSWORD to set the new password
4. edit pg_hba.conf again and restore the previous settings
5. Reload the config file again
They have already answered how to use a global variable.
I will tell you why the use of global variables is a bad idea as a result of this question carried out in stackoverflow in Spanish.
Explicit translation of the text in Spanish:
The problem with global variables is that they create hidden dependencies. When it comes to large applications, you yourself do not know / remember / you are clear about the objects you have and their relationships.
So, you can not have a clear notion of how many objects your global variable is using. And if you want to change something of the global variable, for example, the meaning of each of its possible values, or its type? How many classes or compilation units will that change affect? If the amount is small, it may be worth making the change. If the impact will be great, it may be worth looking for another solution.
But what is the impact? Because a global variable can be used anywhere in the code, it can be very difficult to measure it.
In addition, always try to have a variable with the shortest possible life time, so that the amount of code that makes use of that variable is the minimum possible, and thus better understand its purpose, and who modifies it.
A global variable lasts for the duration of the program, and therefore, anyone can use the variable, either to read it, or even worse, to change its value, making it more difficult to know what value the variable will have at any given program point. .
Another problem is the order of destruction. Variables are always destroyed in reverse order of their creation, whether they are local or global / static variables (an exception is the primitive types, int
,enum
s, etc., which are never destroyed if they are global / static until they end the program).
The problem is that it is difficult to know the order of construction of the global (or static) variables. In principle, it is indeterminate.
If all your global / static variables are in a single compilation unit (that is, you only have a .cpp
), then the order of construction is the same as the writing one (that is, variables defined before, are built before).
But if you have more than one .cpp
each with its own global / static variables, the global construction order is indeterminate. Of course, the order in each compilation unit (each .cpp
) in particular, is respected: if the global variableA
is defined before B
,A
will be built before B
, but It is possible that between A
andB
variables of other .cpp
are initialized. For example, if you have three units with the following global / static variables:
In the executable it could be created in this order (or in any other order as long as the relative order is respected within each .cpp
):
Why is this important? Because if there are relations between different static global objects, for example, that some use others in their destructors, perhaps, in the destructor of a global variable, you use another global object from another compilation unit that turns out to be already destroyed ( have been built later).
I tried to find the source that I will use in this example, but I can not find it (anyway, it was to exemplify the use of singletons, although the example is applicable to global and static variables). Hidden dependencies also create new problems related to controlling the behavior of an object, if it depends on the state of a global variable.
Imagine you have a payment system, and you want to test it to see how it works, since you need to make changes, and the code is from another person (or yours, but from a few years ago). You open a new main
, and you call the corresponding function of your global object that provides a bank payment service with a card, and it turns out that you enter your data and they charge you. How, in a simple test, have I used a production version? How can I do a simple payment test?
After asking other co-workers, it turns out that you have to "mark true", a global bool that indicates whether we are in test mode or not, before beginning the collection process. Your object that provides the payment service depends on another object that provides the mode of payment, and that dependency occurs in an invisible way for the programmer.
In other words, the global variables (or singletones), make it impossible to pass to "test mode", since global variables can not be replaced by "testing" instances (unless you modify the code where said code is created or defined). global variable, but we assume that the tests are done without modifying the mother code).
This is solved by means of what is called * dependency injection *, which consists in passing as a parameter all the dependencies that an object needs in its constructor or in the corresponding method. In this way, the programmer ** sees ** what has to happen to him, since he has to write it in code, making the developers gain a lot of time.
If there are too many global objects, and there are too many parameters in the functions that need them, you can always group your "global objects" into a class, style * factory *, that builds and returns the instance of the "global object" (simulated) that you want , passing the factory as a parameter to the objects that need the global object as dependence.
If you pass to test mode, you can always create a testing factory (which returns different versions of the same objects), and pass it as a parameter without having to modify the target class.
Not necessarily, there may be good uses for global variables. For example, constant values ??(the PI value). Being a constant value, there is no risk of not knowing its value at a given point in the program by any type of modification from another module. In addition, constant values ??tend to be primitive and are unlikely to change their definition.
It is more convenient, in this case, to use global variables to avoid having to pass the variables as parameters, simplifying the signatures of the functions.
Another can be non-intrusive "global" services, such as a logging class (saving what happens in a file, which is usually optional and configurable in a program, and therefore does not affect the application's nuclear behavior), or std :: cout
,std :: cin
or std :: cerr
, which are also global objects.
Any other thing, even if its life time coincides almost with that of the program, always pass it as a parameter. Even the variable could be global in a module, only in it without any other having access, but that, in any case, the dependencies are always present as parameters.
Answer by: Peregring-lk
http://jsbin.com/tidob/1/edit?js,console,output
The native JSON object includes two key methods.
1. JSON.parse()
2. JSON.stringify()
The JSON.parse()
method parses a JSON string - i.e. reconstructing the original JavaScript object
var jsObject = JSON.parse(jsonString);
JSON.stringify() method accepts a JavaScript object and returns its JSON equivalent.
var jsonString = JSON.stringify(jsObject);
Lambda Expression result
var storesList = context.Stores.Select(x => new { Value= x.name,Text= x.ID }).ToList();
To compare character you use the ==
operator:
if (c == ' ')
Answer updated to Python 3.7 and more
Here is how you can turn a date-and-time object
(aka datetime.datetime
object, the one that is stored inside models.DateTimeField
django model field)
into a date object (aka datetime.date
object):
from datetime import datetime
#your date-and-time object
# let's supposed it is defined as
datetime_element = datetime(2020, 7, 10, 12, 56, 54, 324893)
# where
# datetime_element = datetime(year, month, day, hour, minute, second, milliseconds)
# WHAT YOU WANT: your date-only object
date_element = datetime_element.date()
And just to be clear, if you print those elements, here is the output :
print(datetime_element)
2020-07-10 12:56:54.324893
print(date_element)
2020-07-10
This error means that, while linking, compiler is not able to find the definition of main()
function anywhere.
In your makefile, the main
rule will expand to something like this.
main: producer.o consumer.o AddRemove.o
gcc -pthread -Wall -o producer.o consumer.o AddRemove.o
As per the gcc
manual page, the use of -o
switch is as below
-o file Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If
-o
is not specified, the default is to put an executable file ina.out
.
It means, gcc will put the output in the filename provided immediate next to -o
switch. So, here instead of linking all the .o
files together and creating the binary [main
, in your case], its creating the binary as producer.o
, linking the other .o
files. Please correct that.
When setting Access-Control-Allow-Origin
in .htaccess, only following worked:
SetEnvIf Origin "http(s)?://(.+\.)?domain\.com(:\d{1,5})?$" CRS=$0
Header always set Access-Control-Allow-Origin "%{CRS}e" env=CRS
I tried several other suggested keywords Header append
, Header set
, none worked as suggested in many answers on SO, though I have no idea if these keywords are outdated or not valid for nginx.
Here is my complete solution:
SetEnvIf Origin "http(s)?://(.+\.)?domain\.com(:\d{1,5})?$" CRS=$0
Header always set Access-Control-Allow-Origin "%{CRS}e" env=CRS
Header merge Vary "Origin"
Header always set Access-Control-Allow-Methods "GET, POST"
Header always set Access-Control-Allow-Headers: *
# Cached for a day
Header always set Access-Control-Max-Age: 86400
RewriteEngine On
# Respond with 200OK for OPTIONS
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
These sites may help:
to get IMEI (international mobile equipment identifier)
public String getIMEI(Activity activity) {
TelephonyManager telephonyManager = (TelephonyManager) activity
.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
to get device unique id
public String getDeviceUniqueID(Activity activity){
String device_unique_id = Secure.getString(activity.getContentResolver(),
Secure.ANDROID_ID);
return device_unique_id;
}
long dateTime = DateTime.Now.Ticks;
Console.WriteLine(dateTime);
Console.WriteLine(new DateTime(dateTime));
Console.ReadKey();
import java.util.Scanner;
public class Main {
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the first integer:");
int b = input.nextInt();
System.out.println("Please enter the second integer:");
int d = input.nextInt();
System.out.println("The GCD of " + b + " and " + d + " is " + getGcd(b,d) + ".");
}
public static int getGcd(int b, int d)
{
int gcd = 1;
if(b>d)
{
for(int i = d; i >=1; i--)
{
if(b%i==0 && d%i ==0)
{
return i;
}
}
}
else
{
for(int j = b; j >=1; j--)
{
if(b%j==0 && d% j==0)
{
return j;
}
}
}
return gcd;
}
}
There is a new charting library in town: JChartlib JChartLib http://freshmeat.net/projects/jchartlib
You could use
var a = document.querySelector('a[data-a="1"]');
instead of
var a = document.querySelector('a[data-a=1]');
My code :
$("input.numeric").keypress(function(e) { /* pour les champs qui ne prennent que du numeric en entrée */
var key = e.charCode || e.keyCode || 0;
var keychar = String.fromCharCode(key);
/*alert("keychar:"+keychar + " \n charCode:" + e.charCode + " \n key:" +key);*/
if ( ((key == 8 || key == 9 || key == 46 || key == 35 || key == 36 || (key >= 37 && key <= 40)) && e.charCode==0) /* backspace, end, begin, top, bottom, right, left, del, tab */
|| (key >= 48 && key <= 57) ) { /* 0-9 */
return;
} else {
e.preventDefault();
}
});
SELECT e1.empno EmployeeId, e1.ename EmployeeName,
e1.mgr ManagerId, e2.ename AS ManagerName
FROM emp e1, emp e2
where e1.mgr = e2.empno
I would like say that extensibility lack of printf
is not entirely true:
In C, it is true. But in C, there are no real classes.
In C++, it is possible to overload cast operator, so, overloading a char*
operator and using printf
like this:
Foo bar;
...;
printf("%s",bar);
can be possible, if Foo overload the good operator. Or if you made a good method. In short, printf
is as extensible as cout
for me.
Technical argument I can see for C++ streams (in general... not only cout.) are:
Typesafety. (And, by the way, if I want to print a single '\n'
I use putchar('\n')
... I will not use a nuke-bomb to kill an insect.).
Simpler to learn. (no "complicated" parameters to learn, just to use <<
and >>
operators)
Work natively with std::string
(for printf
there is std::string::c_str()
, but for scanf
?)
For printf
I see:
Easier, or at least shorter (in term of characters written) complex formatting. Far more readable, for me (matter of taste I guess).
Better control of what the function made (Return how many characters where written and there is the %n
formatter: "Nothing printed. The argument must be a pointer to a signed int, where the number of characters written so far is stored." (from printf - C++ Reference)
Better debugging possibilities. For same reason as last argument.
My personal preferences go to printf
(and scanf
) functions, mainly because I love short lines, and because I don't think type problems on printing text are really hard to avoid.
The only thing I deplore with C-style functions is that std::string
is not supported. We have to go through a char*
before giving it to printf
(with the std::string::c_str()
if we want to read, but how to write?)
A) To control sys.getdefaultencoding()
output:
python -c 'import sys; print(sys.getdefaultencoding())'
ascii
Then
echo "import sys; sys.setdefaultencoding('utf-16-be')" > sitecustomize.py
and
PYTHONPATH=".:$PYTHONPATH" python -c 'import sys; print(sys.getdefaultencoding())'
utf-16-be
You could put your sitecustomize.py higher in your PYTHONPATH
.
Also you might like to try reload(sys).setdefaultencoding
by @EOL
B) To control stdin.encoding
and stdout.encoding
you want to set PYTHONIOENCODING
:
python -c 'import sys; print(sys.stdin.encoding, sys.stdout.encoding)'
ascii ascii
Then
PYTHONIOENCODING="utf-16-be" python -c 'import sys;
print(sys.stdin.encoding, sys.stdout.encoding)'
utf-16-be utf-16-be
Finally: you can use A) or B) or both!
To expand upon the accepted answer, you can create custom MarkerImages
of any color using the API at http://chart.googleapis.com
In addition to changing color, this also changes marker shape, which may be unwanted.
const marker = new window.google.maps.Marker(
position: markerPosition,
title: markerTitle,
map: map)
marker.addListener('click', () => marker.setIcon(changeIcon('00ff00'));)
const changeIcon = (newIconColor) => {
const newIcon = new window.google.maps.MarkerImage(
`http://chart.googleapis.com/chart?
chst=d_map_spin&chld=1.0|0|${newIconColor}|60|_|%E2%80%A2`,
new window.google.maps.Size(21, 34),
new window.google.maps.Point(0, 0),
new window.google.maps.Point(10, 34),
new window.google.maps.Size(21,34)
);
return newIcon
}
deleting tensorflow from cDrive/users/envs/tensorflow and after that
conda create -n tensorflow python=3.6
activate tensorflow
pip install --ignore-installed --upgrade tensorflow
now its working for newer versions of python thank you
I suppose better would be to use re.match() function. here is an example which may help you.
import re
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
sentences = word_tokenize("I love to learn NLP \n 'a :(")
#for i in range(len(sentences)):
sentences = [word.lower() for word in sentences if re.match('^[a-zA-Z]+', word)]
sentences
If you want it as a string (for example, a 10-digit phone number) you can use this:
n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])
If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.
But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.
You will definitely want to start with a good web scraping framework. Later on you may decide that they are too limiting and you can put together your own stack of libraries but without a lot of scraping experience your design will be much worse than pjscrape or scrapy.
Note: I use the terms crawling and scraping basically interchangeable here. This is a copy of my answer to your Quora question, it's pretty long.
Tools
Get very familiar with either Firebug or Chrome dev tools depending on your preferred browser. This will be absolutely necessary as you browse the site you are pulling data from and map out which urls contain the data you are looking for and what data formats make up the responses.
You will need a good working knowledge of HTTP as well as HTML and will probably want to find a decent piece of man in the middle proxy software. You will need to be able to inspect HTTP requests and responses and understand how the cookies and session information and query parameters are being passed around. Fiddler (http://www.telerik.com/fiddler) and Charles Proxy (http://www.charlesproxy.com/) are popular tools. I use mitmproxy (http://mitmproxy.org/) a lot as I'm more of a keyboard guy than a mouse guy.
Some kind of console/shell/REPL type environment where you can try out various pieces of code with instant feedback will be invaluable. Reverse engineering tasks like this are a lot of trial and error so you will want a workflow that makes this easy.
Language
PHP is basically out, it's not well suited for this task and the library/framework support is poor in this area. Python (Scrapy is a great starting point) and Clojure/Clojurescript (incredibly powerful and productive but a big learning curve) are great languages for this problem. Since you would rather not learn a new language and you already know Javascript I would definitely suggest sticking with JS. I have not used pjscrape but it looks quite good from a quick read of their docs. It's well suited and implements an excellent solution to the problem I describe below.
A note on Regular expressions: DO NOT USE REGULAR EXPRESSIONS TO PARSE HTML. A lot of beginners do this because they are already familiar with regexes. It's a huge mistake, use xpath or css selectors to navigate html and only use regular expressions to extract data from actual text inside an html node. This might already be obvious to you, it becomes obvious quickly if you try it but a lot of people waste a lot of time going down this road for some reason. Don't be scared of xpath or css selectors, they are WAY easier to learn than regexes and they were designed to solve this exact problem.
Javascript-heavy sites
In the old days you just had to make an http request and parse the HTML reponse. Now you will almost certainly have to deal with sites that are a mix of standard HTML HTTP request/responses and asynchronous HTTP calls made by the javascript portion of the target site. This is where your proxy software and the network tab of firebug/devtools comes in very handy. The responses to these might be html or they might be json, in rare cases they will be xml or something else.
There are two approaches to this problem:
The low level approach:
You can figure out what ajax urls the site javascript is calling and what those responses look like and make those same requests yourself. So you might pull the html from http://example.com/foobar and extract one piece of data and then have to pull the json response from http://example.com/api/baz?foo=b... to get the other piece of data. You'll need to be aware of passing the correct cookies or session parameters. It's very rare, but occasionally some required parameters for an ajax call will be the result of some crazy calculation done in the site's javascript, reverse engineering this can be annoying.
The embedded browser approach:
Why do you need to work out what data is in html and what data comes in from an ajax call? Managing all that session and cookie data? You don't have to when you browse a site, the browser and the site javascript do that. That's the whole point.
If you just load the page into a headless browser engine like phantomjs it will load the page, run the javascript and tell you when all the ajax calls have completed. You can inject your own javascript if necessary to trigger the appropriate clicks or whatever is necessary to trigger the site javascript to load the appropriate data.
You now have two options, get it to spit out the finished html and parse it or inject some javascript into the page that does your parsing and data formatting and spits the data out (probably in json format). You can freely mix these two options as well.
Which approach is best?
That depends, you will need to be familiar and comfortable with the low level approach for sure. The embedded browser approach works for anything, it will be much easier to implement and will make some of the trickiest problems in scraping disappear. It's also quite a complex piece of machinery that you will need to understand. It's not just HTTP requests and responses, it's requests, embedded browser rendering, site javascript, injected javascript, your own code and 2-way interaction with the embedded browser process.
The embedded browser is also much slower at scale because of the rendering overhead but that will almost certainly not matter unless you are scraping a lot of different domains. Your need to rate limit your requests will make the rendering time completely negligible in the case of a single domain.
Rate Limiting/Bot behaviour
You need to be very aware of this. You need to make requests to your target domains at a reasonable rate. You need to write a well behaved bot when crawling websites, and that means respecting robots.txt and not hammering the server with requests. Mistakes or negligence here is very unethical since this can be considered a denial of service attack. The acceptable rate varies depending on who you ask, 1req/s is the max that the Google crawler runs at but you are not Google and you probably aren't as welcome as Google. Keep it as slow as reasonable. I would suggest 2-5 seconds between each page request.
Identify your requests with a user agent string that identifies your bot and have a webpage for your bot explaining it's purpose. This url goes in the agent string.
You will be easy to block if the site wants to block you. A smart engineer on their end can easily identify bots and a few minutes of work on their end can cause weeks of work changing your scraping code on your end or just make it impossible. If the relationship is antagonistic then a smart engineer at the target site can completely stymie a genius engineer writing a crawler. Scraping code is inherently fragile and this is easily exploited. Something that would provoke this response is almost certainly unethical anyway, so write a well behaved bot and don't worry about this.
Testing
Not a unit/integration test person? Too bad. You will now have to become one. Sites change frequently and you will be changing your code frequently. This is a large part of the challenge.
There are a lot of moving parts involved in scraping a modern website, good test practices will help a lot. Many of the bugs you will encounter while writing this type of code will be the type that just return corrupted data silently. Without good tests to check for regressions you will find out that you've been saving useless corrupted data to your database for a while without noticing. This project will make you very familiar with data validation (find some good libraries to use) and testing. There are not many other problems that combine requiring comprehensive tests and being very difficult to test.
The second part of your tests involve caching and change detection. While writing your code you don't want to be hammering the server for the same page over and over again for no reason. While running your unit tests you want to know if your tests are failing because you broke your code or because the website has been redesigned. Run your unit tests against a cached copy of the urls involved. A caching proxy is very useful here but tricky to configure and use properly.
You also do want to know if the site has changed. If they redesigned the site and your crawler is broken your unit tests will still pass because they are running against a cached copy! You will need either another, smaller set of integration tests that are run infrequently against the live site or good logging and error detection in your crawling code that logs the exact issues, alerts you to the problem and stops crawling. Now you can update your cache, run your unit tests and see what you need to change.
Legal Issues
The law here can be slightly dangerous if you do stupid things. If the law gets involved you are dealing with people who regularly refer to wget and curl as "hacking tools". You don't want this.
The ethical reality of the situation is that there is no difference between using browser software to request a url and look at some data and using your own software to request a url and look at some data. Google is the largest scraping company in the world and they are loved for it. Identifying your bots name in the user agent and being open about the goals and intentions of your web crawler will help here as the law understands what Google is. If you are doing anything shady, like creating fake user accounts or accessing areas of the site that you shouldn't (either "blocked" by robots.txt or because of some kind of authorization exploit) then be aware that you are doing something unethical and the law's ignorance of technology will be extraordinarily dangerous here. It's a ridiculous situation but it's a real one.
It's literally possible to try and build a new search engine on the up and up as an upstanding citizen, make a mistake or have a bug in your software and be seen as a hacker. Not something you want considering the current political reality.
Who am I to write this giant wall of text anyway?
I've written a lot of web crawling related code in my life. I've been doing web related software development for more than a decade as a consultant, employee and startup founder. The early days were writing perl crawlers/scrapers and php websites. When we were embedding hidden iframes loading csv data into webpages to do ajax before Jesse James Garrett named it ajax, before XMLHTTPRequest was an idea. Before jQuery, before json. I'm in my mid-30's, that's apparently considered ancient for this business.
I've written large scale crawling/scraping systems twice, once for a large team at a media company (in Perl) and recently for a small team as the CTO of a search engine startup (in Python/Javascript). I currently work as a consultant, mostly coding in Clojure/Clojurescript (a wonderful expert language in general and has libraries that make crawler/scraper problems a delight)
I've written successful anti-crawling software systems as well. It's remarkably easy to write nigh-unscrapable sites if you want to or to identify and sabotage bots you don't like.
I like writing crawlers, scrapers and parsers more than any other type of software. It's challenging, fun and can be used to create amazing things.
Generally, you can use the func(*tuple)
syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:
t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])
This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
If your test class extends the Spring JUnit classes
(e.g., AbstractTransactionalJUnit4SpringContextTests
or any other class that extends AbstractSpringContextTests
), you can access the app context by calling the getContext()
method.
Check out the javadocs for the package org.springframework.test.
in mysql 5.7 the password field has been replaced with authentication_string so you would do something like this instead
update user set authentication_string=PASSWORD("root") where User='root';
See this link MySQL user DB does not have password columns - Installing MySQL on OSX
Shorter option to extract the second word in a sentence:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('THIS IS A TEST', ' ', 2), ' ', -1) as FoundText
select Name, Value, AnotherColumn
from out_pumptable
where Value =
(
select Max(Value)
from out_pumptable as f where f.Name=out_pumptable.Name
)
group by Name, Value, AnotherColumn
Try like this, It works.
This link just gave me the best answer:
$ wget --no-clobber --convert-links --random-wait -r -p --level 1 -E -e robots=off -U mozilla http://base.site/dir/
Worked like a charm.
To quote MDN on FormData
(emphasis mine):
The
FormData
interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using theXMLHttpRequest.send()
method. It uses the same format a form would use if the encoding type were set to"multipart/form-data"
.
So when using FormData
you are locking yourself into multipart/form-data
. There is no way to send a FormData
object as the body and not sending data in the multipart/form-data
format.
If you want to send the data as application/x-www-form-urlencoded
you will either have to specify the body as an URL-encoded string, or pass a URLSearchParams
object. The latter unfortunately cannot be directly initialized from a form
element. If you don’t want to iterate through your form elements yourself (which you could do using HTMLFormElement.elements
), you could also create a URLSearchParams
object from a FormData
object:
const data = new URLSearchParams();
for (const pair of new FormData(formElement)) {
data.append(pair[0], pair[1]);
}
fetch(url, {
method: 'post',
body: data,
})
.then(…);
Note that you do not need to specify a Content-Type
header yourself.
As noted by monk-time in the comments, you can also create URLSearchParams
and pass the FormData
object directly, instead of appending the values in a loop:
const data = new URLSearchParams(new FormData(formElement));
This still has some experimental support in browsers though, so make sure to test this properly before you use it.
I saw this question while I was looking for a way to count multiple files lines, so if you want to count multiple file lines of a .txt file you can do this,
cat *.txt | wc -l
it will also run on one .txt file ;)
You cannot have a different sized border than the div itself.
the solution would be to just add another div under neath, centered or absolute positioned, with the desired 1pixel border and only 1pixel in height.
I left the original border in so you can see the width, and have two examples -- one with 100 width, and the other with 100 width centered. Delete the one you dont wish to use.
"dependencies": {
"some-package": "github:github_username/some-package"
}
or just
"dependencies": {
"some-package": "github_username/some-package"
}
The quick and dirty way, you can view the available environment variables from the below link.
http://localhost:8080/env-vars.html/
Just replace localhost
with your Jenkins hostname, if its different
w/o flip:
<?php
foreach ($items as $key => $value) {
if ($id === $value) {
unset($items[$key]);
}
}
Ran into this issue, npm i @ionic/app-scripts
was the only thing that worked.
Method 1 :
var stringValue = "true";
var boolValue = (/true/i).test(stringValue) //returns true
Method 2 :
var stringValue = "true";
var boolValue = (stringValue =="true"); //returns true
Method 3 :
var stringValue = "true";
var boolValue = JSON.parse(stringValue); //returns true
Method 4 :
var stringValue = "true";
var boolValue = stringValue.toLowerCase() == 'true'; //returns true
Method 5 :
var stringValue = "true";
var boolValue = getBoolean(stringValue); //returns true
function getBoolean(value){
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
source: http://codippa.com/how-to-convert-string-to-boolean-javascript/
it is not displayed in your application... it is under your emulator's logcat
I'm surprised no one has mentioned this, but for the simple (and probably most encountered) case of squaring, you just multiply by itself.
float someNumber;
float result = someNumber * someNumber;
To expand on Johan's answer, if the part_num column in the sub-select can contain null values then the query will break.
To correct this, add a null check...
SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN
(SELECT pd.part_num FROM wpsapi4.product_details pd
where pd.part_num is not null)
Enable allow_url_fopen From cPanel Or WHM in PHP INI Section
For JBoss, in standalone.xml, put after .
<extensions>
</extensions>
<system-properties>
<property name="my.project.dir" value="/home/francesco" />
</system-properties>
For eclipse:
http://www.avajava.com/tutorials/lessons/how-do-i-set-system-properties.html?page=2
99% of our AWS setup is recyclable. So for me it doesn't really matter if I terminate an instance -- nothing is lost ever. E.g. my application is automatically deployed on an instance from SVN, our logs are written to a central syslog server.
The only benefit of instance storage that I see are cost-savings. Otherwise EBS-backed instances win. Eric mentioned all the advantages.
[2012-07-16] I would phrase this answer a lot different today.
I haven't had any good experience with EBS-backed instances in the past year or so. The last downtimes on AWS pretty much wrecked EBS as well.
I am guessing that a service like RDS uses some kind of EBS as well and that seems to work for the most part. On the instances we manage ourselves, we have got rid off EBS where possible.
Getting rid to an extend where we moved a database cluster back to iron (= real hardware). The only remaining piece in our infrastructure is a DB server where we stripe multiple EBS volumes into a software RAID and backup twice a day. Whatever would be lost in between backups, we can live with.
EBS is a somewhat flakey technology since it's essentially a network volume: a volume attached to your server from remote. I am not negating the work done with it – it is an amazing product since essentially unlimited persistent storage is just an API call away. But it's hardly fit for scenarios where I/O performance is key.
And in addition to how network storage behaves, all network is shared on EC2 instances. The smaller an instance (e.g. t1.micro, m1.small) the worse it gets because your network interfaces on the actual host system are shared among multiple VMs (= your EC2 instance) which run on top of it.
The larger instance you get, the better it gets of course. Better here means within reason.
When persistence is required, I would always advice people to use something like S3 to centralize between instances. S3 is a very stable service. Then automate your instance setup to a point where you can boot a new server and it gets ready by itself. Then there is no need to have network storage which lives longer than the instance.
So all in all, I see no benefit to EBS-backed instances what so ever. I rather add a minute to bootstrap, then run with a potential SPOF.
The percentage %
sign followed by two hexadecimal numbers (UTF-8 character representation) typically denotes a string which has been encoded to be part of a URI. This ensures that characters that would otherwise have special meaning don't interfere. In your case %20
is immediately recognisable as a whitespace character - while not really having any meaning in a URI it is encoded in order to avoid breaking the string into multiple "parts".
Don't get me wrong, regex is the bomb! However any web technology worth caring about will already have tools available in it's library to handle standards like this for you. Why re-invent the wheel...?
var str = 'xPasswords%20do%20not%20match';
console.log( decodeURI(str) ); // "xPasswords do not match"
Javascript has both decodeURI
and decodeURIComponent
which differ slightly in respect to their encodeURI
and encodeURIComponent
counterparts - you should familiarise yourself with the documentation.
Create custom directive
masterApp.directive('ngRenderCallback', function() {
return {
restrict: "A",
link: function ($scope, element, attrs) {
setTimeout(function(){
$scope[attrs.ngEl] = element[0];
$scope.$eval(attrs.ngRenderCallback);
}, 30);
}
}
});
code for html template
<div ng-render-callback="fnRenderCarousel('carouselA')" ng-el="carouselA"></div>
function in controller
$scope.fnRenderCarousel = function(elName){
$($scope[elName]).carousel();
}
This can be a nice way to do it that does not involve long constructors
class Person {
firstName?: string = 'Bob';
lastName?: string = 'Smith';
// Pass in this class as the required params
constructor(params: Person) {
// object.assign will overwrite defaults if params exist
Object.assign(this, params)
}
}
// you can still use the typing
function sayName(params: Person){
let name = params.firstName + params.lastName
alert(name)
}
// you do have to call new but for my use case this felt better
sayName(new Person({firstName: 'Gordon'}))
sayName(new Person({lastName: 'Thomas'}))
Depends on a lot of factors... List implementation, CPU architecture, JVM, loop semantics, complexity of equals method, etc... By the time the list gets big enough to effectively benchmark (1000+ elements), Hash-based binary lookups beat linear searches hands-down, and the difference only scales up from there.
Hope this helps!
We can use map_df
with purrr.
library(mice)
library(purrr)
# map_df with purrr
map_df(airquality, function(x) sum(is.na(x)))
# A tibble: 1 × 6
# Ozone Solar.R Wind Temp Month Day
# <int> <int> <int> <int> <int> <int>
# 1 37 7 0 0 0 0
Use the setAttribute
method:
document.getElementById('item1').setAttribute('data', "icon: 'base2.gif', url: 'output.htm', target: 'AccessPage', output: '1'");
But you really should be using data followed with a dash and with its property, like:
<li ... data-icon="base.gif" ...>
And to do it in JS use the dataset
property:
document.getElementById('item1').dataset.icon = "base.gif";
Trying to do things as smooth as possible - I here suggest modifying GuyWhoLikesPowershell's suggestion slightly.
I replaced the if and until with one while - and I check for "Stopped", since I don't want to start if status is "starting" or " Stopping".
$Service = 'ServiceName'
while ((Get-Service $Service).Status -eq 'Stopped')
{
Start-Service $Service -ErrorAction SilentlyContinue
Start-Sleep 10
}
Return "$($Service) has STARTED"
TL;DR: add the parameter cursorclass=MySQLdb.cursors.DictCursor
at the end of your MySQLdb.connect
.
I had a working code and the DB moved, I had to change the host/user/pass. After this change, my code stopped working and I started getting this error. Upon closer inspection, I copy-pasted the connection string on a place that had an extra directive. The old code read like:
conn = MySQLdb.connect(host="oldhost",
user="olduser",
passwd="oldpass",
db="olddb",
cursorclass=MySQLdb.cursors.DictCursor)
Which was replaced by:
conn = MySQLdb.connect(host="newhost",
user="newuser",
passwd="newpass",
db="newdb")
The parameter cursorclass=MySQLdb.cursors.DictCursor
at the end was making python allow me to access the rows using the column names as index. But the poor copy-paste eliminated that, yielding the error.
So, as an alternative to the solutions already presented, you can also add this parameter and access the rows in the way you originally wanted. ^_^ I hope this helps others.
Here's a mixin that you can mix into any model class which gives each instance an update
method:
class UpdateMixin(object):
def update(self, **kwargs):
if self._state.adding:
raise self.DoesNotExist
for field, value in kwargs.items():
setattr(self, field, value)
self.save(update_fields=kwargs.keys())
The self._state.adding
check checks to see if the model is saved to the database, and if not, raises an error.
(Note: This update
method is for when you want to update a model and you know the instance is already saved to the database, directly answering the original question. The built-in update_or_create
method featured in Platinum Azure's answer already covers the other use-case.)
You would use it like this (after mixing this into your user model):
user = request.user
user.update(favorite_food="ramen")
Besides having a nicer API, another advantage to this approach is that it calls the pre_save
and post_save
hooks, while still avoiding atomicity issues if another process is updating the same model.
You can do this:
IEnumerable<object> list = new List<object>(){1, 4, 5}.AsEnumerable();
CallFunction(list);
To process line by line, this is an elegant solution:
def stream_lines(file_name):
file = open(file_name)
while True:
line = file.readline()
if not line:
file.close()
break
yield line
As long as there're no blank lines.
Using apache's rewrite_module can change your script extensions. Give this thread a good read.
Firstly a warning: you should never tinker with DOM that is managed by React, which you are doing by calling ReactDOM.render(<SampleComponent ... />);
With React, you should use SampleComponent directly in the main App.
var App = require('./App.js');
var SampleComponent = require('./SampleComponent.js');
ReactDOM.render(<App/>, document.body);
The content of your Component is irrelevant, but it should be used like this:
var App = React.createClass({
render: function() {
return (
<div>
<h1>App main component! </h1>
<SampleComponent name="SomeName"/>
</div>
);
}
});
You can then extend your app component to use a list.
var App = React.createClass({
render: function() {
var componentList = [
<SampleComponent name="SomeName1"/>,
<SampleComponent name="SomeName2"/>
]; // Change this to get the list from props or state
return (
<div>
<h1>App main component! </h1>
{componentList}
</div>
);
}
});
I would really recommend that you look at the React documentation then follow the "Get Started" instructions. The time you spend on that will pay off later.
I updated the SDK version in app.json to match with the react native SDK version in package.json to fix this issue
In app.json
"sdkVersion": "37.0.0",
In package.json
"react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz",
here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner
class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}
Functions cannot be used to modify base table information, use a stored procedure.
Applying inline-block
to the element that is to be centered and applying text-align:center
to the parent block did the trick for me.
Works even on <span>
tags.
I've run into issues with Webclient.Downloadstring before. If you do, you can try this:
WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
html = sr.ReadToEnd();
}
This is my two cents:
$('#container_element').scroll( function(){
console.log($(this).scrollTop()+' + '+ $(this).height()+' = '+ ($(this).scrollTop() + $(this).height()) +' _ '+ $(this)[0].scrollHeight );
if($(this).scrollTop() + $(this).height() == $(this)[0].scrollHeight){
console.log('bottom found');
}
});
Simply use size
instead of len
!
>>> from numpy import size
>>> N = [2, 3, 5]
>>> size(N)
3
>>> N = array([2, 3, 5])
>>> size(N)
3
>>> P = 5
>>> size(P)
1
$("#contactForm").submit(function() {
$.post(url, $.param($(this).serializeArray()), function(data) {
});
});
A comma at the end of the print statement omits the new line.
for i in xrange(1,100):
print i,
but this does not overwrite.
A very late answer, but hope this will help
^(.+?)/([\w]+\.log)$
This uses lazy check for /
, and I just modified the accepted answer
you can do:
var = 1
if type(var) == int:
print('your variable is an integer')
or:
var2 = 'this is variable #2'
if type(var2) == str:
print('your variable is a string')
else:
print('your variable IS NOT a string')
hope this helps!
A much simpler way to do this is to use vCenter Converter Standalone Client and do a P2V but in this case a V2V. It is much faster than copying the entire VM files onto some storage somewhere and copy it onto your new vCenter. It takes a long time to copy or exporting it to an OVF template and then import it. You can set your vCenter Converter Standalone Client to V2V in one step and synchronize and then have it power up the VM on the new Vcenter and shut off on the old vCenter. Simple.
For me using this method I was able to move a VM from one vCenter to another vCenter in about 30 minutes as compared to copying or exporting which took over 2hrs. Your results may vary.
This process below, from another responder, would work even better if you can present that datastore to ESXi servers on the vCenter and then follow step 2. Eliminating having to copy all the VMs then follow rest of the process.
In the solution below I used python3.4
as binary, but it's safe to use with any version or binary of python. it works fine on windows too (except the downloading pip with wget
obviously but just save the file locally and run it with python).
This is great if you have multiple versions of python installed, so you can manage external libraries per python version.
So first, I'd recommend get-pip.py
, it's great to install pip :
wget https://bootstrap.pypa.io/get-pip.py
Then you need to install pip for your version of python, I have python3.4
so for me this is the command :
python3.4 get-pip.py
Now pip is installed for python3.4
and in order to get libraries for python3.4
one need to call it within this version, like this :
python3.4 -m pip
So if you want to install numpy you would use :
python3.4 -m pip install numpy
Note that numpy
is quite the heavy library. I thought my system was hanging and failing.
But using the verbose option, you can see that the system is fine :
python3.4 -m pip install numpy -v
This may tell you that you lack python.h but you can easily get it :
On RHEL (Red hat, CentOS, Fedora) it would be something like this :
yum install python34-devel
On debian-like (Debian, Ubuntu, Kali, ...) :
apt-get install python34-dev
Then rerun this :
python3.4 -m pip install numpy -v
I noticed that problem because of AdBlock Extension, I turned off AdBlock extension the issue got resolve.
I needed this information too and got information with this method,
Launch PowerShell
run the 'import-module servermanager' command ( without quotes )
after that for asp.net 3.5 check run the 'get-windowsfeature web-asp-net' command ( without quotes )
for asp.net 4.5 check run the 'get-windowsfeature Net-Framework-45-Core' command ( without quotes )
Both of the commands will inform you below Install State header.
Detecting version via GUI in server environment and details can be found in this link.
Parallelism is simultaneous execution of processes on a multiple cores per CPU
or multiple CPUs (on a single motherboard)
.
Concurrency is when Parallelism is achieved on a single core/CPU
by using scheduling algorithms that divides the CPU’s time (time-slice). Processes are interleaved.
Units:
- 1 or many cores in a single CPU (pretty much all modern day processors)
- 1 or many CPUs on a motherboard (think old school servers)
- 1 application is 1 program (think Chrome browser)
- 1 program can have 1 or many processes (think each Chrome browser tab is a process)
- 1 process can have 1 or many threads from 1 program (Chrome tab playing Youtube video in 1 thread, another thread spawned for comments section, another for users login info)
- Thus, 1 program can have 1 or many threads of execution
- 1 process is
thread(s)+allocated memory resources by OS
(heap, registers, stack, class memory)
If your XML goes quite deep, you might want to consider using XPath, which comes with your JRE, so you can access the contents far more easily using:
String text = xp.evaluate("//add[@job='351']/tag[position()=1]/text()",
document.getDocumentElement());
Full example:
import static org.junit.Assert.assertEquals;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class XPathTest {
private Document document;
@Before
public void setup() throws Exception {
String xml = "<add job=\"351\"><tag>foobar</tag><tag>foobar2</tag></add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(new InputSource(new StringReader(xml)));
}
@Test
public void testXPath() throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xp = xpf.newXPath();
String text = xp.evaluate("//add[@job='351']/tag[position()=1]/text()",
document.getDocumentElement());
assertEquals("foobar", text);
}
}
you can do it this way
private String GET(String url, Map<String, String> header) throws IOException {
Headers headerbuild = Headers.of(header);
Request request = new Request.Builder().url(url).headers(headerbuild).
build();
Response response = client.newCall(request).execute();
return response.body().string();
}
Set level to OFF (instead of DEBUG, INFO, ....)
Os X Mojave 10.14 has:
Error: The Command Line Tools header package must be installed on Mojave.
Solution. Go to
/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
location and install the package manually. And brew will start working and we can run:
brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git
For those that want to get the x and y coordinates of various positions of an element, relative to the document.
const getCoords = (element, position) => {
const { top, left, width, height } = element.getBoundingClientRect();
let point;
switch (position) {
case "top left":
point = {
x: left + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "top center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "top right":
point = {
x: left + width + window.pageXOffset,
y: top + window.pageYOffset
};
break;
case "center left":
point = {
x: left + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "center right":
point = {
x: left + width + window.pageXOffset,
y: top + height / 2 + window.pageYOffset
};
break;
case "bottom left":
point = {
x: left + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
case "bottom center":
point = {
x: left + width / 2 + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
case "bottom right":
point = {
x: left + width + window.pageXOffset,
y: top + height + window.pageYOffset
};
break;
}
return point;
};
getCoords(document.querySelector('selector'), 'center')
getCoords(document.querySelector('selector'), 'bottom right')
getCoords(document.querySelector('selector'), 'top center')
In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.
Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.
Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).
The registry keys of interest (At least in some versions of windows) are:
HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart
will have the value 1
if delayed, 0
if not.HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay
or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay
(on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.Columns("A:E").Select
Can be directly replaced by
Columns(1).Resize(, 5).EntireColumn.Select
Where 1 can be replaced by a variable
n = 5
Columns(n).Resize(, n+4).EntireColumn.Select
In my opinion you are best dealing with a block of columns rather than looping through columns n to n + 4 as it is more efficient.
In addition, using select will slow your code down. So instead of selecting your columns and then performing an action on the selection try instead to perform the action directly. Below is an example to change the colour of columns A-E to yellow.
Columns(1).Resize(, 5).EntireColumn.Interior.Color = 65535
While setting the value in the constructor would work, using the Doctrine Lifecycle events might be a better solution.
By leveraging the prePersist
Lifecycle Event, you could set your default value on your entity only on initial persist.
I think this will be simple and fast -
var scrollWidth= window.innerWidth-$(document).width()
You should be able to get this done using delegates, lambda expression
private void button2_Click(object sender, EventArgs e)
{
label1.Text = "waiting....";
Task<string> sCode = Task.Run(async () =>
{
string msg =await GenerateCodeAsync();
return msg;
});
label1.Text += sCode.Result;
}
private Task<string> GenerateCodeAsync()
{
return Task.Run<string>(() => GenerateCode());
}
private string GenerateCode()
{
Thread.Sleep(2000);
return "I m back" ;
}
SOLVED
After banging my head on the wall for a couple days with this issue, it was looking like the problem had something to do with the content type negotiation between the client and server. I dug deeper into that using Fiddler to check the request details coming from the client app, here's a screenshot of the raw request as captured by fiddler:
What's obviously missing there is the Content-Type
header, even though I was setting it as seen in the code sample in my original post. I thought it was strange that the Content-Type
never came through even though I was setting it, so I had another look at my other (working) code calling a different Web API service, the only difference was that I happened to be setting the req.ContentType
property prior to writing to the request body in that case. I made that change to this new code and that did it, the Content-Type
was now showing up and I got the expected success response from the web service. The new code from my .NET client now looks like this:
req.Method = "POST"
req.ContentType = "application/json"
lstrPagingJSON = JsonSerializer(Of Paging)(lPaging)
bytData = Encoding.UTF8.GetBytes(lstrPagingJSON)
req.ContentLength = bytData.Length
reqStream = req.GetRequestStream()
reqStream.Write(bytData, 0, bytData.Length)
reqStream.Close()
'// Content-Type was being set here, causing the problem
'req.ContentType = "application/json"
That's all it was, the ContentType
property just needed to be set prior to writing to the request body
I believe this behavior is because once content is written to the body it is streamed to the service endpoint being called, any other attributes pertaining to the request need to be set prior to that. Please correct me if I'm wrong or if this needs more detail.
A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.
Check the success field for true or false
private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
JsonObject jsonObject = null;
URLConnection connection = null;
InputStream is = null;
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String url = "https://www.google.com/recaptcha/api/siteverify";
try {
String query = String.format("secret=%s&response=%s&remoteip=%s",
URLEncoder.encode(secret, charset),
URLEncoder.encode(response, charset),
URLEncoder.encode(remoteip, charset));
connection = new URL(url + "?" + query).openConnection();
is = connection.getInputStream();
JsonReader rdr = Json.createReader(is);
jsonObject = rdr.readObject();
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return jsonObject;
}
Setting PYTHONPATH can also help with this problem.
Here is how it can be done on Windows
set PYTHONPATH=.
Answer to my question (after several Google searches) revealed the following:
$ curl https://pkgconfig.freedesktop.org/releases/pkg-config-0.29.tar.gz -o pkgconfig.tgz
$ tar -zxf pkgconfig.tgz && cd pkg-config-0.29
$ ./configure && make install
from the following link: Link showing above
Thanks to everyone for their comments, and sorry for my linux/OSX ignorance!
Doing this fixed my issues as mentioned above.
The best way is to use fixtures.
Note: Keep in mind that fixtures do direct inserts and don't use your model so if you have callbacks that populate data you will need to find a workaround.
A different approach could be
<script type="text/javascript">
function CheckData() {
//you may want to check something here and based on that wanna return true and false from the function.
if(MyStuffIsokay)
return true;//will cause form to postback to server.
else
return false;//will cause form Not to postback to server
}
</script>
@using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
{
.........
.........
.........
.........
<input type="submit" value= "Save Employee" onclick="return CheckData();"/>
}
in simply words you can use this method
users.sort(function(a,b){return a.firstname < b.firstname ? -1 : 1});
Is this what you had in mind?
$("document").ready( function() {
// do your stuff
}
Here is a good table for printf
specifiers. So it should be %hu
for unsigned short int
.
And link to Wikipedia "C data types" too.
This is what I use:
private void ExpireAllCookies()
{
if (HttpContext.Current != null)
{
int cookieCount = HttpContext.Current.Request.Cookies.Count;
for (var i = 0; i < cookieCount; i++)
{
var cookie = HttpContext.Current.Request.Cookies[i];
if (cookie != null)
{
var expiredCookie = new HttpCookie(cookie.Name) {
Expires = DateTime.Now.AddDays(-1),
Domain = cookie.Domain
};
HttpContext.Current.Response.Cookies.Add(expiredCookie); // overwrite it
}
}
// clear cookies server side
HttpContext.Current.Request.Cookies.Clear();
}
}
// Sorted
let Sorted = Object.entries({ "a":4, "b":0.5 , "c":0.35, "d":5 }).sort((prev, next) => prev[1] - next[1])
>> [ [ 'c', 0.35 ], [ 'b', 0.5 ], [ 'a', 4 ], [ 'd', 5 ] ]
//Min:
Sorted.shift()
>> [ 'c', 0.35 ]
// Max:
Sorted.pop()
>> [ 'd', 5 ]
As an alternative to the previous answers, guava's Splitter
API can be used if other operations are to be applied to the resulting lines, like trimming lines or filtering empty lines :
import com.google.common.base.Splitter;
Iterable<String> split = Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings().split(docStr);
Note that the result is an Iterable
and not an array.
In addition to the suggested answers, you can do this with some lazy generation and list comprehension magic:
import os, glob, itertools
results = itertools.chain.from_iterable(glob.iglob(os.path.join(root,'*.c'))
for root, dirs, files in os.walk('src'))
for f in results: print(f)
Besides fitting in one line and avoiding unnecessary lists in memory, this also has the nice side effect, that you can use it in a way similar to the ** operator, e.g., you could use os.path.join(root, 'some/path/*.c')
in order to get all .c files in all sub directories of src that have this structure.
You can use the instanceof
operator for this. From MDN:
The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:
class Animal {_x000D_
name;_x000D_
_x000D_
constructor(name) {_x000D_
this.name = name;_x000D_
}_x000D_
}_x000D_
_x000D_
const animal = new Animal('fluffy');_x000D_
_x000D_
// true because Animal in on the prototype chain of animal_x000D_
console.log(animal instanceof Animal); // true_x000D_
// Proof that Animal is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
_x000D_
// true because Object in on the prototype chain of animal_x000D_
console.log(animal instanceof Object); _x000D_
// Proof that Object is on the prototype chain_x000D_
console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
_x000D_
console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
_x000D_
_x000D_
The prototype chain in this example is:
animal > Animal.prototype > Object.prototype
Sub Addrisk()
Dim rActive As Range
Dim Count_Id_Column as long
Set rActive = ActiveCell
Application.ScreenUpdating = False
with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
for i = 1 to .range("A1045783").end(xlup).row
if 'something' = 'something' then
.range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
.range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
.range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
'change I to move on to next row (will get + 1 end of iteration)
i = i + 1
end if
On Error Resume Next
.SpecialCells(xlCellTypeConstants).ClearContents
On Error GoTo 0
End With
next i
End With
Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates
End Sub
Use this
def prod(iterable):
p = 1
for n in iterable:
p *= n
return p
Since there's no built-in prod
function.
I just want to point out, that there has been a recent addition to the .NET documentation regarding email validation, also utilitzing Regex operations. A thorough explanation to their implementation can be found there.
For convenience, here is a list of their test results:
// Valid: [email protected]
// Valid: [email protected]
// Valid: [email protected]
// Invalid: [email protected]
// Valid: [email protected]
// Valid: js#[email protected]
// Valid: j_9@[129.126.118.1]
// Invalid: [email protected]
// Invalid: js*@proseware.com
// Invalid: [email protected]
// Valid: [email protected]
// Valid: [email protected]
// Valid: "j\"s\""@proseware.com
// Valid: js@contoso.??
This is probably slower than what you want, but you can do:
>>> tostring = vectorize(lambda x: str(x))
>>> numpy.where(tostring(phis).astype('float64') != phis)
(array([], dtype=int64),)
It looks like it rounds off the values when it converts to str from float64, but this way you can customize the conversion however you like.
If you are writing a webapp, ensure that you don't have conflicting versions of a jar in your container's global library directory and also in your app. You may not necessarily know which jar is being used by the classloader.
e.g.
Use \b
for word boundaries:
sed -i 's/\boldtext\b/newtext/g' <file>
I tried every possible solution to fix this frustrating error and only below worked for me. In your build.gradle add this:
android {
aaptOptions.cruncherEnabled = false
aaptOptions.useNewCruncher = false }
It is called the Conditional Operator (which is a ternary operator).
It has the form of: condition
? value-if-true
: value-if-false
Think of the ?
as "then" and :
as "else".
Your code is equivalent to
if (max != 0)
hsb.s = 255 * delta / max;
else
hsb.s = 0;
Using this.props.children
is the idiomatic way to pass instantiated components to a react component
const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>
When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div
or span
):
const Label = props => <span>{props.children}</span>
const Button = props => {
const Inner = props.inner; // Note: variable name _must_ start with a capital letter
return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>
If what you want to do is to pass a children-like parameter as a prop, you can do that:
const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />
After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.
With androidx, the classic support libraries no longer work.
Simple solution is to use following code
In your build.gradle
file
android{
...
...
defaultConfig {
...
...
multiDexEnabled true
}
...
}
dependencies {
...
...
implementation 'androidx.multidex:multidex:2.0.1'
}
And in your manifest just add name attribute to the application tag
<manifest ...>
<application
android:name="androidx.multidex.MultiDexApplication"
...
...>
...
...
</application>
</manifest>
If your application is targeting API 21 or above multidex is enables by default.
Now if you want to get rid of many of the issues you face trying to support multidex - first try using code shrinking by setting minifyEnabled true
.
The correct way would be to use "--" to stop processing arguments, as already mentioned. This is due to the usage of getopt_long (GNU C-function from getopt.h) in the source of the tool.
This is why you notice the same phenomena on other command-line tools; since most of them are GNU tools, and use this call,they exhibit the same behavior.
As a side note - getopt_long is what gives us the cool choice between -rlo and --really_long_option and the combination of arguments in the interpreter.
Try this
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String userName = authentication.getName();
If you meant .. to REDIRECT from that page to another, the function is really simple
header("Location:www.google.com");
A more groovyesque approach would be to use inject in combination with metaClass:
I would to love to say:
String myInput="This string is FORBIDDEN"
myInput.containsAny(["FORBIDDEN","NOT_ALLOWED"]) //=>true
And the method would be:
myInput.metaClass.containsAny={List<String> notAllowedTerms->
notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}
If you need containsAny to be present for any future String variable then add the method to the class instead of the object:
String.metaClass.containsAny={notAllowedTerms->
notAllowedTerms?.inject(false,{found,term->found || delegate.contains(term)})
}
Just in case you actually mean 'discard changes' whenever you use 'git stash' (and don't really use git stash to stash it temporarily), in that case you can use
git checkout -- <file>
Note that git stash is just a quicker and simple alternative to branching and doing stuff.
This can also be done by P/Invoking the C standard library's system
function.
using System.Runtime.InteropServices;
[DllImport("msvcrt.dll")]
public static extern int system(string format);
system("copy Test.txt Test2.txt");
Output:
1 file(s) copied.
Old question, but some of us are in git-posh
(powershell). This is the solution for that:
git ls-files -ci --exclude-standard | foreach { git rm --cached $_ }
The solution that fixed the issue was using the following steps:
In Start Menu, search for "mysql". Among the results, you should see the "MySQL Installer - Community". Run it. MySQL Installer window will show up as shown below. Find "MySQL Server" under Product and click on "Reconfigure" link. MySQL Installer Community
The MySQL Installer will show up (same one you used for the first MySQL Server installation). Go through all the steps.
After the MySQL Installer was finished, I started the MySQL service again.
final
means that the value cannot be changed after initialization, that's what makes it a constant. static
means that instead of having space allocated for the field in each object, only one instance is created for the class.
So, static final
means only one instance of the variable no matter how many objects are created and the value of that variable can never change.
If you are on Android 4.0 or above, and you are on a mac, then here is a ruby script that will save your app contents to the desktop. I would imagine this would also work in Ubuntu, though I didn't test it.
puts "enter your package name"
package_name = gets.chomp
puts "press the 'Back up my data' button on your device"
`adb backup -f ~/Desktop/data.ab -noapk #{package_name}`
puts "press enter once once the 'Backup finished' toast has appeared"
gets.chomp
puts "extracting..."
`dd if=data.ab bs=1 skip=24 | openssl zlib -d | tar -xvf -`
to run -> ruby your_ruby_file_name.rb
This script is "happy path" only, so please make sure your device is connected and that adb has been added to your profile.
Below is just a little variant of the script provided by @"Juuso Ohtonen".
I have add a password variable and counter so you can can check the progression of your backup. Also I replaced simple brackets []
by double brackets [[]]
to prevent an error I had on macos.
$ sudo redis-cli
INFO keyspace
AUTH yourpassword
INFO keyspace
#!/bin/bash
# Default to '*' key pattern, meaning all redis keys in the namespace
REDIS_KEY_PATTERN="${REDIS_KEY_PATTERN:-*}"
PASS="yourpassword"
i=1
for key in $(redis-cli -a "$PASS" --scan --pattern "$REDIS_KEY_PATTERN")
do
echo $i.
((i=i+1))
type=$(redis-cli -a "$PASS" type $key)
if [[ $type = "list" ]]
then
printf "$key => \n$(redis-cli -a "$PASS" lrange $key 0 -1 | sed 's/^/ /')\n"
elif [[ $type = "hash" ]]
then
printf "$key => \n$(redis-cli -a "$PASS" hgetall $key | sed 's/^/ /')\n"
else
printf "$key => $(redis-cli -a "$PASS" get $key)\n"
fi
echo
done
bash redis_print.sh > redis.bak
tail redis.bak
You could use java-aes-crypto or Facebook's Conceal
java-aes-crypto
Quoting from the repo
A simple Android class for encrypting & decrypting strings, aiming to avoid the classic mistakes that most such classes suffer from.
Facebook's conceal
Quoting from the repo
Conceal provides easy Android APIs for performing fast encryption and authentication of data
By invoking its toString()
method.
Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.
I figured out the demo and implemented it the following way:
$.datepicker.setDefaults(
$.extend(
{'dateFormat':'dd-mm-yy'},
$.datepicker.regional['nl']
)
);
I needed to set the default for the dateformat too ...
I know this is old now but TSQL => 2016, you can use STRING_SPLIT:
DECLARE @InList varchar(255) = 'This;Is;My;List';
WITH InList (Item) AS (
SELECT value FROM STRING_SPLIT(@InList, ';')
)
SELECT *
FROM [Table]
WHERE [Item] IN (SELECT Tag FROM InList)
long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();
Got same problem with project porting from VS2013 to VS2017,
Fix: change "Properties->General->Windows SDK Version" to 10
This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...
If you have Node.Js setup then you can use http-server. Just run npm install http-server -g
and you will be able to use it in terminal like http-server C:\location\to\app.
Kirill Fuchs
Disclaimer: Many would strongly advise against this. The only time it'd really be a problem was if a library added a prototype function with the same name (that behaved differently) or something like that.
Array.prototype.containsAny = function(arr) {
return this.some(
(v) => (arr.indexOf(v) >= 0)
)
}
Without using big arrow functions:
Array.prototype.containsAny = function(arr) {
return this.some(function (v) {
return arr.indexOf(v) >= 0
})
}
var a = ["a","b"]
console.log(a.containsAny(["b","z"])) // Outputs true
console.log(a.containsAny(["z"])) // Outputs false
In Windows platform, these file types are used for certificate information. Normally used for SSL certificate and Public Key Infrastructure (X.509).
for more information visit:Certificate Files: .Cer x .Pvk x .Pfx
It depends where exactly you want to get the information from. You have a bunch of options:
<manifest>
element will have a package
attribute.adb
, you can launch adb shell
and execute pm list packages -f
, which shows the package name for each installed apk.PackageManager
Once you've got the package name, you simply link to market://search?q=pname:<package_name>
or http://market.android.com/search?q=pname:<package_name>
. Both will open the market on an Android device; the latter obviously has the potential to work on other hardware as well (it doesn't at the minute).
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
eduffy had a good idea. He just got it backwards in his code example. Either in JavaScript or in SQLite you can replace the apostrophe with the accent symbol.
He (accidentally I am sure) placed the accent symbol as the delimiter for the string instead of replacing the apostrophe in O'Brian. This is in fact a terrifically simple solution for most cases.
Try npm install --production
and then npm start
.
Use a foreach loop instead of a for loop - it solved my problem.
int j = 0;
foreach (Microsoft.Office.Interop.Word.Page p in pane.Pages)
{
var bits = p.EnhMetaFileBits;
var target = path1 +j.ToString()+ "_image.doc";
try
{
using (var ms = new MemoryStream((byte[])(bits)))
{
var image = System.Drawing.Image.FromStream(ms);
var pngTarget = Path.ChangeExtension(target, "png");
image.Save(pngTarget, System.Drawing.Imaging.ImageFormat.Png);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
j++;
}
Here is a modification of a program that worked for me. It uses Word 2007 with the Save As PDF add-in installed. It searches a directory for .doc files, opens them in Word and then saves them as a PDF. Note that you'll need to add a reference to Microsoft.Office.Interop.Word to the solution.
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
...
// Create a new Microsoft Word application object
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
// C# doesn't have optional arguments so we'll need a dummy value
object oMissing = System.Reflection.Missing.Value;
// Get list of Word files in specified directory
DirectoryInfo dirInfo = new DirectoryInfo(@"\\server\folder");
FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");
word.Visible = false;
word.ScreenUpdating = false;
foreach (FileInfo wordFile in wordFiles)
{
// Cast as Object for word Open method
Object filename = (Object)wordFile.FullName;
// Use the dummy value as a placeholder for optional arguments
Document doc = word.Documents.Open(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
doc.Activate();
object outputFileName = wordFile.FullName.Replace(".doc", ".pdf");
object fileFormat = WdSaveFormat.wdFormatPDF;
// Save document into PDF Format
doc.SaveAs(ref outputFileName,
ref fileFormat, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing);
// Close the Word document, but leave the Word application open.
// doc has to be cast to type _Document so that it will find the
// correct Close method.
object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
doc = null;
}
// word has to be cast to type _Application so that it will find
// the correct Quit method.
((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;
Per Mozilla's Map documentation, you can initialize as follows:
private _gridOptions:Map<string, Array<string>> =
new Map([
["1", ["test"]],
["2", ["test2"]]
]);
I am a fan on PyOFC2 : http://btbytes.github.com/pyofc2/
It just just a package that makes it easy to generate the JSON data needed for Open Flash Charts 2, which are very beautiful. Check out the examples on the link above.
Um,
I might be a bit too late here but isn't this kinda the point to EWS ?
https://msdn.microsoft.com/en-us/library/dd633710(EXCHG.80).aspx
Takes about 6 lines of code to get the mail from a mailbox:
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
//service.Credentials = new NetworkCredential( "{Active Directory ID}", "{Password}", "{Domain Name}" );
service.AutodiscoverUrl( "[email protected]" );
FindItemsResults<Item> findResults = service.FindItems(
WellKnownFolderName.Inbox,
new ItemView( 10 )
);
foreach ( Item item in findResults.Items )
{
Console.WriteLine( item.Subject );
}
Open a command prompt.
Go to the directory where you have your .java files
Create a directory build
Run java compilation from the command line
javac -d ./build *.java
if there are no errors, in the build directory you should have your class tree
move to the build directory and do a
jar cvf YourJar.jar *
For adding manifest check jar command line switches
Spark NLP is another option that I used and it is working excellent. A simple tutorial can be found here. https://github.com/JohnSnowLabs/spark-nlp-workshop/blob/master/jupyter/annotation/english/spell-check-ml-pipeline/Pretrained-SpellCheckML-Pipeline.ipynb
Yes, contains is case sensitive. You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:
Pattern.compile(Pattern.quote(wantedStr), Pattern.CASE_INSENSITIVE).matcher(source).find();
EDIT: If s2 contains regex special characters (of which there are many) it's important to quote it first. I've corrected my answer since it is the first one people will see, but vote up Matt Quail's since he pointed this out.
Though I upvoted the answer marked as correct. I wanted to touch on a few things for anyone stumbling upon this.
In general, if you're filtering specifically on Date values alone. Microsoft recommends using the language neutral format of ymd
or y-m-d
.
Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.
To do a date comparison using the aforementioned approach is simple. Consider the following, contrived example.
--112 is ISO format 'YYYYMMDD'
declare @filterDate char(8) = CONVERT(char(8), GETDATE(), 112)
select
*
from
Sales.Orders
where
CONVERT(char(8), OrderDate, 112) = @filterDate
In a perfect world, performing any manipulation to the filtered column should be avoided because this can prevent SQL Server from using indexes efficiently. That said, if the data you're storing is only ever concerned with the date and not time, consider storing as DATETIME
with midnight as the time. Because:
When SQL Server converts the literal to the filtered column’s type, it assumes midnight when a time part isn’t indicated. If you want such a filter to return all rows from the specified date, you need to ensure that you store all values with midnight as the time.
Thus, assuming you are only concerned with date, and store your data as such. The above query can be simplified to:
--112 is ISO format 'YYYYMMDD'
declare @filterDate char(8) = CONVERT(char(8), GETDATE(), 112)
select
*
from
Sales.Orders
where
OrderDate = @filterDate
Decode and save image as PNG
header('content-type: image/png');
ob_start();
$ret = fopen($fullurl, 'r', true, $context);
$contents = stream_get_contents($ret);
$base64 = 'data:image/PNG;base64,' . base64_encode($contents);
echo "<img src=$base64 />" ;
ob_end_flush();
DOCKER USERS: This also happens when you have hit around 90% of your Docker image size limit (seems like 10% is needed for caching or so). The wording is confusing, as this simply means the amount of disk space Docker can use for basically everything.
To fix, go to your Docker desktop settings > Disk > move slider a bit more to the right > Apply.
I encounter this problem, because I have <VirtualHost>
defined both in httpd.conf and httpd-ssl.conf.
in httpd.conf, it's defined as
<VirtualHost localhost>
in httpd-ssl.conf, it's defined as
<VirtualHost _default_:443>
The following change solved this problem, add :80 in httpd.conf
<VirtualHost localhost:80>
I solved this, without having to completely reinstall Visual Studio 2013.
For those who may come across this in the future, the following steps worked for me:
vs_professional.exe
).If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3
Click the link for 'examine the log file' and look near the bottom of the log, for this line:
open regedit.exe
and do an Edit > Find...
for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
. This was found in:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
Edit the BundleVersion
value and change it to a lower version. I changed mine from 12.0.21005.13
to 12.0.21000.13
:
Exit the registry
Run the ISO (or vs_professional.exe
) again. If it has a repair button like the image below, you can skip to step 4.
Run the ISO (or vs_professional.exe
) again. This time repair should be visible.
Click Repair
and let it update your installation and apply its embedded license key. This took about 20 minutes.
Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product
:
Hope this helps somebody in the future!
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):
$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );
So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:
$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );
Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,
The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.
That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.
Coming late to the party, but...
With oracle 11.2.0.1 there is a semantic hint that can do this: IGNORE_ROW_ON_DUPKEY_INDEX
Example:
insert /*+ IGNORE_ROW_ON_DUPKEY_INDEX(customer_orders,pk_customer_orders) */
into customer_orders
(order_id, customer, product)
values ( 1234, 9876, 'K598')
;
UPDATE: Although this hint works (if you spell it correctly), there are better approaches which don't require Oracle 11R2:
First approach—direct translation of above semantic hint:
begin
insert into customer_orders
(order_id, customer, product)
values ( 1234, 9876, 'K698')
;
commit;
exception
when DUP_VAL_ON_INDEX
then ROLLBACK;
end;
Second aproach—a lot faster than both above hints when there's a lot of contention:
begin
select count (*)
into l_is_matching_row
from customer_orders
where order_id = 1234
;
if (l_is_matching_row = 0)
then
insert into customer_orders
(order_id, customer, product)
values ( 1234, 9876, 'K698')
;
commit;
end if;
exception
when DUP_VAL_ON_INDEX
then ROLLBACK;
end;
After following the guide (or using Spring Initializr), I had a WAR that worked on my local computer, but didn't work remote (running on Tomcat).
There was no error message, it just said "Spring servlet initializer was found", but didn't do anything at all.
17-Aug-2016 16:58:13.552 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.4
17-Aug-2016 16:58:13.593 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive /opt/tomcat/webapps/ROOT.war
17-Aug-2016 16:58:16.243 INFO [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
and
17-Aug-2016 16:58:16.301 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log 2 Spring WebApplicationInitializers detected on classpath
17-Aug-2016 16:58:21.471 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring embedded WebApplicationContext
17-Aug-2016 16:58:25.133 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log ContextListener: contextInitialized()
17-Aug-2016 16:58:25.133 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log SessionListener: contextInitialized()
Nothing else happened. Spring Boot just didn't run.
Apparently I compiled the server with Java 1.8, and the remote computer had Java 1.7.
After compiling with Java 1.7, it started working.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version> <!-- added this line -->
<start-class>myapp.SpringApplication</start-class>
</properties>