I am trying to obtain a handle on one of the views in the Action Bar
I will assume that you mean something established via android:actionLayout
in your <item>
element of your <menu>
resource.
I have tried calling findViewById(R.id.menu_item)
To retrieve the View
associated with your android:actionLayout
, call findItem()
on the Menu
to retrieve the MenuItem
, then call getActionView()
on the MenuItem
. This can be done any time after you have inflated the menu resource.
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.
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID
before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.
You have to nest the requests:
$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ obj = name; // sID is only now available! sID = obj.id; console.log(sID); });
name.id
is sufficient unless you really need the other variables outside the function.$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ // We don't need sID or obj here - name.id is sufficient console.log(name.id); doSecondRequest(name.id); }); /// TODO Choose a better name function doSecondRequest(sID) { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){ console.log(stats); }); }
Hapy New Year :)
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
Instead of using ->bindParam()
you can pass the data only at the time of ->execute()
:
$data = [ ':item_name' => $_POST['item_name'], ':item_type' => $_POST['item_type'], ':item_price' => $_POST['item_price'], ':item_description' => $_POST['item_description'], ':image_location' => 'images/'.$_FILES['file']['name'], ':status' => 0, ':id' => 0, ]; $stmt->execute($data);
In this way you would know exactly what values are going to be sent.
Two ways.
i. You can put it in ApplicationController and add the filters in the controller
class ApplicationController < ActionController::Base def filter_method end end class FirstController < ApplicationController before_filter :filter_method end class SecondController < ApplicationController before_filter :filter_method end
But the problem here is that this method will be added to all the controllers since all of them extend from application controller
ii. Create a parent controller and define it there
class ParentController < ApplicationController def filter_method end end class FirstController < ParentController before_filter :filter_method end class SecondController < ParentController before_filter :filter_method end
I have named it as parent controller but you can come up with a name that fits your situation properly.
You can also define the filter method in a module and include it in the controllers where you need the filter
You basically have two choices:
1.Require an instance:
public Navigation(T t) { this("", "", t); }
2.Require a class instance:
public Navigation(Class<T> c) { this("", "", c.newInstance()); }
You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.
Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for/path/to/repo.git
andfoo
forhost.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
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 ")
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.
You can use Jquery's on method and listen for the scroll
event.
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
I believe that you are looking for the java.lang.BigDecimal class.
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
The linked list holds operations on the shared data structure.
For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).
In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.
In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
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
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.
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
You are looking to see if a single value is in an array. Use in_array
.
However note that case is important, as are any leading or trailing spaces. Use var_dump
to find out the length of the strings too, and see if they fit.
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
Happened to me when I passing null to the middleware
function
Route::middleware(null)->group(function () {
Route::get('/some-path', [SomeController::class, 'search']);
});
Passing []
for no middleware works or probably just remove the middleware
call if not using middleware :D
I do not think the warnings you have received are related. I had the same warnings which turned out to be the chrome extension React Dev Tools. Removed the extension and the errors have gone.
I've also faced this problem and figure out it by upgrading the react-scripts
package from "react-scripts": "3.x.x"
to "react-scripts": "^3.4.1"
(or the latest available version).
node_modules\
folderpackage-lock.json
filepackage.json
file from "react-scripts": "3.x.x"
to "react-scripts": "^3.4.1"
npm i
npm start
And it works!!
The best way to overcome on this issue is that, just remove node_modules and package-lock.json file and further install npm with npm i it solved my problem
(along CUDA Toolkit 11.0 RC)
To solve the same issue as OP, I just had to find cudart64_101.dll on my disk (in my case C:\Program Files\NVIDIA Corporation\NvStreamSrv) and add it as variable environment (that is add value C:\Program Files\NVIDIA\Corporation\NvStreamSrv)cudart64_101.dll to user's environment variable Path).
I have the same issue, but I use GitLab instead of Jenkins. The steps I had to do to get over the issue:
I realize that is more specific to my setup. But without doing all of the steps above I would still continue to get this error message
Return code is: 501 , ReasonPhrase:HTTPS Required
I've done most things you are proposing with Java compiler and bytecode and solved the problem in the past. It's been almost 1 month since I ran my Java code (and back then everything was fixed), but now the problem appeared again. Don't know why, pretty annoyed though!
This time the solution was: Right click to project name -> Open module settings F4 -> Language level ...and there you can define the language level your project/pc is.
No maven/pom configuration worked for me both in the past and now and I've already set the Java compiler and bytecode at 12.
It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.
Let's say you have something like this in your code:
$str = "test";
echo($str{0});
since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:
$str = "test";
echo($str[0]);
Fixing the code in the question will look something like this:
public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
$records = $this->listRecords($zoneID, $type, $name);
if (isset($records->result[0]->id)) {
return $records->result[0]->id;
}
return false;
}
Switch to an older openssl package
brew switch openssl 1.0.2s
Or, depending on your exact system configuration, you may need to switch to a different version. Check the output of ls -al /usr/local/Cellar/openssl
for the version number to switch to.
brew switch openssl 1.0.2q
# or
brew switch openssl 1.0.2r
# or
brew switch openssl 1.0.2s
# or
brew switch openssl 1.0.2t
# etc...
This happened to me when I registered a new domain name, e.g., "new" for example.com (new.example.com). The name could not be resolved temporarily in my location for a couple of hours, while it could be resolved abroad. So I used a proxy to test the website where I saw net::ERR_HTTP2_PROTOCOL_ERROR
in chrome console for some AJAX posts. Hours later, when the name could be resloved locally, those error just dissappeared.
I think the reason for that error is those AJAX requests were not redirected by my proxy, it just visit a website which had not been resolved by my local DNS resolver.
TypeScript, React, index.html
//conf.js:
window.bar = "bar";
//index.html
<script type="module" src="./conf.js"></script>
//tsconfig.json
"include": ["typings-custom/**/*.ts"]
//typings-custom/typings.d.ts
declare var bar:string;
//App.tsx
console.log('bar', window.bar);
or
console.log('bar', bar);
I'm also in a "trial and error" for that, but this answer from Google Chrome Labs' Github helped me a little. I defined it into my main file and it worked - well, for only one third-party domain. Still making tests, but I'm eager to update this answer with a better solution :)
EDIT: I'm using PHP 7.4 now, and this syntax is working good (Sept 2020):
$cookie_options = array(
'expires' => time() + 60*60*24*30,
'path' => '/',
'domain' => '.domain.com', // leading dot for compatibility or use subdomain
'secure' => true, // or false
'httponly' => false, // or false
'samesite' => 'None' // None || Lax || Strict
);
setcookie('cors-cookie', 'my-site-cookie', $cookie_options);
If you have PHP 7.2 or lower (as Robert's answered below):
setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");
If your host is already updated to PHP 7.3, you can use (thanks to Mahn's comment):
setcookie('cookieName', 'cookieValue', [
'expires' => time()+(7*24*3600,
'path' => '/',
'domain' => 'domain.com',
'samesite' => 'None',
'secure' => true,
'httponly' => true
]);
Another thing you can try to check the cookies, is to enable the flag below, which—in their own words—"will add console warning messages for every single cookie potentially affected by this change":
chrome://flags/#cookie-deprecation-messages
See the whole code at: https://github.com/GoogleChromeLabs/samesite-examples/blob/master/php.md, they have the code for same-site-cookies
too.
I have found that in pretty older project there is no metro-config
in node_modules
. If it is the case with you, then,
Go to node_modules/metro-bundler/src/blacklist.js
And do the same step as mentioned in other answers, i.e.
Replace
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
with
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
P.S. I faced the same situation in a couple of projects so thought sharing it might help someone.
Edit
As per comment by @beltrone the file might also exist in,
node_modules\metro\src\blacklist.js
use this line, this worked for me
mongoose.set('useUnifiedTopology', true);
Caused by 4: com.android.builder.internal.aapt.AaptException: Dependent features configured but no package ID was set.
All feature modules have to apply the library
plugin and NOT the application
plugin.
apply plugin: 'com.android.library'
It all depends on the stacktrace of each one. Cause 1 WorkExecutionException
may be the consequence of other causes. So I suggest reading the full stacktrace from the last cause printed towards the first cause. So if we solve the last cause, it is very likely that we will have fixed the chain of causes from the last to the first.
I attach an example of my stacktrace where the original or concrete problem was in the last cause:
Caused by: org.gradle.workers.internal.DefaultWorkerExecutor$WorkExecutionException: A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction
Caused by: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-4.2.0-alpha16-6840111-linux Daemon #0: Unexpected error during link, attempting to stop daemon.
Caused by: java.io.IOException: Unable to make AAPT link command.
Caused by 4: com.android.builder.internal.aapt.AaptException: Dependent features configured but no package ID was set.
GL
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 :
This code keep clicking "Refresh folder" in the file explorer pane.
function ClickRefresh(){
console.log("Working");
document.querySelector("[icon='colab:folder-refresh']").click()
}
const myjob = setInterval(ClickRefresh, 60000)
See the announcement for ASP.NET Core 3 Preview 4, which explains that this tool is no longer built-in and requires an explicit install:
The dotnet ef tool is no longer part of the .NET Core SDK
This change allows us to ship
dotnet ef
as a regular .NET CLI tool that can be installed as either a global or local tool. For example, to be able to manage migrations or scaffold aDbContext
, installdotnet ef
as a global tool typing the following command:
dotnet tool install --global dotnet-ef
To install a specific version of the tool, use the following command:
dotnet tool install --global dotnet-ef --version 3.1.4
The reason for the change is explained in the docs:
Why
This change allows us to distribute and update
dotnet ef
as a regular .NET CLI tool on NuGet, consistent with the fact that the EF Core 3.0 is also always distributed as a NuGet package.
In addition, you might need to add the following NuGet packages to your project:
Workaround: If you have installed python from exe follow below steps.
Step 1: Uninstall python
Step 2: Install python and check Python path check box as highlighted in below screentshot(yellow).
This solved me the problem.
In Angular 8, ViewChild always takes 2 param, and second params always has static: true or static: false
You can try like this:
@ViewChild('nameInput', {static: false}) component
Also,the static: false
is going to be the default fallback behaviour in Angular 9.
What are static false/true: So as a rule of thumb you can go for the following:
{ static: true }
needs to be set when you want to access the
ViewChild in ngOnInit.
{ static: false }
can only be accessed in ngAfterViewInit. This is
also what you want to go for when you have a structural directive
(i.e. *ngIf) on your element in your template.
For me , the error was calling the function useState outside the function default exported
This will eliminate the error and is type safe:
this.DNATranscriber[character as keyof typeof DNATranscriber]
CORS headers should be sent from the server. If you use PHP it will be like this:
header('Access-Control-Allow-Origin: your-host');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: your-methods like POST,GET');
header('Access-Control-Allow-Headers: content-type or other');
header('Content-Type: application/json');
What we ended up doing is stopped using the class components and created Functional Components, using useEffect()
from the Hooks API for lifecycle methods. This allows you to still use makeStyles()
with Lifecycle Methods without adding the complication of making Higher-Order Components. Which is much simpler.
Example:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';
import { Container, makeStyles } from '@material-ui/core';
import LogoButtonCard from '../molecules/Cards/LogoButtonCard';
const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
margin: theme.spacing(1)
},
highlight: {
backgroundColor: 'red',
}
}));
// Highlight is a bool
const Welcome = ({highlight}) => {
const [userName, setUserName] = useState('');
const [isAuthenticated, setIsAuthenticated] = useState(true);
const classes = useStyles();
useEffect(() => {
axios.get('example.com/api/username/12')
.then(res => setUserName(res.userName));
}, []);
if (!isAuthenticated()) {
return <Redirect to="/" />;
}
return (
<Container maxWidth={false} className={highlight ? classes.highlight : classes.root}>
<LogoButtonCard
buttonText="Enter"
headerText={isAuthenticated && `Welcome, ${userName}`}
buttonAction={login}
/>
</Container>
);
}
}
export default Welcome;
I Tried adding the below statement on my API on the express server and it worked with Angular8.
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET , PUT , POST , DELETE");
res.header("Access-Control-Allow-Headers", "Content-Type, x-requested-with");
next(); // Important
})
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.
Add <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version> in property tag
problem resolve
https://medium.com/@saannjaay/unknown-error-in-pom-xml-66fb2414991b
Yes, installing previous a version of numpy solved the problem.
For those who uses PyCharm IDE:
in my IDE (Pycharm), File->Settings->Project Interpreter: I found my numpy to be 1.16.3, so I revert back to 1.16.1. Click + and type numpy in the search, tick "specify version" : 1.16.1 and choose--> install package.
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
This issue might be helpful for you, it explains how to achieve TPUStrategy
, a popular functionality of tf.contrib
in TF<2.0.
So, in TF 1.X you could do the following:
resolver = tf.contrib.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.contrib.distribute.initialize_tpu_system(resolver)
strategy = tf.contrib.distribute.TPUStrategy(resolver)
And in TF>2.0, where tf.contrib
is deprecated, you achieve the same by:
tf.config.experimental_connect_to_host('grpc://' + os.environ['COLAB_TPU_ADDR'])
resolver = tf.distribute.cluster_resolver.TPUClusterResolver('grpc://' + os.environ['COLAB_TPU_ADDR'])
tf.tpu.experimental.initialize_tpu_system(resolver)
strategy = tf.distribute.experimental.TPUStrategy(resolver)
In the app function you have incorrectly spelled the word setpersonSate
, missing the letter t
, thus it should be setpersonState
.
Error:
const app = props => {
const [personState, setPersonSate] = useState({....
Solution:
const app = props => {
const [personState, setPersonState] = useState({....
For ng9 upgraders:
npm i -g core-js@^3
..then:
npm cache clean -f
..followed by:
npm i
You haven't started the bundler yet. Run npm start
or react-native start
in the root directory of your project before react-native run-android
.
Try following command sequence on Ubuntu terminal:
sudo apt-get install software-properties-common
sudo apt-add-repository universe
sudo apt-get update
sudo apt-get install python-pip
Open this folder "C:\ProgramData\" and right-click on "\Anaconda3". go to properties -> security and check all the boxes for each user. This worked for me.
It sounds like you are using Visual Studio's Web Compiler extension. There is an open issue for this found here: https://github.com/madskristensen/WebCompiler/issues/413
There is a workaround posted in that issue:
C:\Users\USERNAME\AppData\Local\Temp\WebCompilerX.X.X
(X is the version of WebCompiler)node_modules
folder: caniuse-lite
and browserslist
Open up CMD (inside C:\Users\USERNAME\AppData\Local\Temp\WebCompilerX.X.X
) and run: npm i caniuse-lite browserslist
You must link an event in your onClick. Additionally, the click function must receive the event. See the example
export default function Component(props) {
function clickEvent (event, variable){
console.log(variable);
}
return (
<div>
<IconButton
key="close"
aria-label="Close"
color="inherit"
onClick={e => clickEvent(e, 10)}
>
</div>
)
}
I couldn't resolve the version mismatch by following any of the answers when using Visual Studio, but simply updating the Selenium.WebDriver and Selenium.WebDriver.ChromeDriver nuget packages to the latest versions worked.
I was using Chrome v78, and upgrading chromedriver to v78 still gave the incompatibility error. CAD's answer led me to the solution.
add @method('PUT') on the form
exp:
<form action="..." method="POST">
@csrf
@method('PUT')
</form>
import tensorflow as tf
sess = tf.Session()
this code will show an Attribute error on version 2.x
to use version 1.x code in version 2.x
try this
import tensorflow.compat.v1 as tf
sess = tf.Session()
The easiest way I found is this:
https://github.com/nteract/hydrogen/issues/922#issuecomment-405456346
Just open another (non-running, existing) notebook on the same kernel, and the issue is magically gone; you can again save the notebooks that were previously showing the _xsrf
error.
If you have already closed the Jupyter home page, you can find a link to it on the terminal from which Jupyter was started.
As the @Jordan Stefanelli answer: If you encounter the same problem as me that the integrated Terminal cannot read input from user as below hanging (env. Windows 10)
my solution was to replace cygwin's gdb and g ++ with mingw64's.
then the input output are normal
also you can enable "external console" option to solve it:)
you can change it by enabling "externalConsole":true in the launch.json then you will get a pop up console window that you can type in.
I solved this problem, I changed build system to Legacy Build System
from New Build System
In Xcode v10+, select File > Project Settings
In previous Xcode, select File > Workspace Settings
Change Build System to Legacy Build System
from New Build System
--> Click Done.
pip3
not pip
. You can create an alias like you did with python3
if you like.
A more production-ready way to handle this is to actually ensure that name
is present. Assuming this is a minimal example of a larger project that a group of people are involved with, you don't know how getPerson
will change in the future.
if (!person.name) {
throw new Error("Unexpected error: Missing name");
}
let name1: string = person.name;
Alternatively, you can type name1
as string | undefined
, and handle cases of undefined
further down. However, it's typically better to handle unexpected errors earlier on.
You can also let TypeScript infer the type by omitting the explicit type: let name1 = person.name
This will still prevent name1
from being reassigned as a number, for example.
For those newbies like me, don't assign variable to service response, meaning do
export class ShopComponent implements OnInit {
public productsArray: Product[];
ngOnInit() {
this.productService.getProducts().subscribe(res => {
this.productsArray = res;
});
}
}
Instead of
export class ShopComponent implements OnInit {
public productsArray: Product[];
ngOnInit() {
this.productsArray = this.productService.getProducts().subscribe();
}
}
There're 3 ways to achieve this after conda
4.6. (The last method has the highest priority.)
Use sub-command conda config
to change the setting.
conda config --set auto_activate_base false
In fact, the former conda config
sub-command is changing configuration file .condarc
. We can modify .condarc
directly. Add following content into .condarc
under your home directory,
# auto_activate_base (bool)
# Automatically activate the base environment during shell
# initialization. for `conda init`
auto_activate_base: false
Set environment variable CONDA_AUTO_ACTIVATE_BASE
in the shell's init file. (.bashrc
for bash, .zshrc
for zsh)
CONDA_AUTO_ACTIVATE_BASE=false
To convert from the
condarc
file-based configuration parameter name to the environment variable parameter name, make the name all uppercase and prependCONDA_
. For example, conda’salways_yes
configuration parameter can be specified using aCONDA_ALWAYS_YES
environment variable.
The environment settings take precedence over corresponding settings in .condarc
file.
Appears to be a bug at the momment: https://issuetracker.google.com/issues/123054726
Solution that worked for me:
Create a .travis.yml file in your project directory and copy these lines:
before_script:
- mkdir "$ANDROID_HOME/licenses" || true
- echo "24333f8a63b6825ea9c5514f83c2829b004d1fee" > "$ANDROID_HOME/licenses/android-sdk-license"
I got round thid by writing/reading to a file. I guessed cv.imread would put it into the format it needed. This code for anki Vector SDK program but you get the idea.
tmpImage = robot.camera.latest_image.raw_image.save('temp.png')
pilImage = cv.imread('temp.png')
I upgraded to PHP 7.3, and None of these worked for me before I used,
sudo wget https://getcomposer.org/download/1.8.0/composer.phar -O /usr/local/bin/composer && sudo chmod 755 /usr/local/bin/composer
It's just the version dependency. PHP 7.3
and composer update worked like a charm!
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>
I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem
On MacOS Mojave, only way I could fix it was with brew upgrade
Try to keep your state minimal. There is no need to store
const initialValue = [
{ id: 0,value: " --- Select a State ---" }];
as state. Separate the permanent from the changing
const ALL_STATE_VALS = [
{ id: 0,value: " --- Select a State ---" }
{ id: 1, value: "Alabama" },
{ id: 2, value: "Georgia" },
{ id: 3, value: "Tennessee" }
];
Then you can store just the id as your state:
const StateSelector = () =>{
const [selectedStateOption, setselectedStateOption] = useState(0);
return (
<div>
<label>Select a State:</label>
<select>
{ALL_STATE_VALS.map((option, index) => (
<option key={option.id} selected={index===selectedStateOption}>{option.value}</option>
))}
</select>
</div>);
)
}
Because the application crashes. For whom saving time on this exception!
And the error code says it throws an exception because it can't find a file in the initial phase. See the Environment Settings section. In my scenario, it worked when I changed the following code
var environment = whb.GetSetting("environment");
to
var environment = "Development";// whb.GetSetting("environment");
Because I have appsettings.development.json but I didn't have appsettings.production.json. Why it can't find any file because it's looking for different thing on right place.
In gradle-wrapper.properties I changed back from gradle-5.1.1 to distributionUrl=https://services.gradle.org/distributions/gradle-4.10.3-all.zip
The general way to find any type is by example. The beauty of typescript is that you have access to all types, so long as you have the correct @types/
files.
To answer this myself I just thought of a component react uses that has the children
prop. The first thing that came to mind? How about a <div />
?
All you need to do is open vscode and create a new .tsx
file in a react project with @types/react
.
import React from 'react';
export default () => (
<div children={'test'} />
);
Hovering over the children
prop shows you the type. And what do you know -- Its type is ReactNode
(no need for ReactNode[]
).
Then if you click into the type definition it brings you straight to the definition of children
coming from DOMAttributes
interface.
// node_modules/@types/react/index.d.ts
interface DOMAttributes<T> {
children?: ReactNode;
...
}
Note: This process should be used to find any unknown type! All of them are there just waiting for you to find them :)
Dec 25th, 2019 :
Whoever facing issue regarding Image not showing in Flutter , let me give you simple checkpoints :
First point is very important
To fix this install the specific typescript version 3.1.6
npm i [email protected] --save-dev --save-exact
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
https://reactjs.org/docs/hooks-reference.html#usememo
Remember that the function passed to useMemo runs during rendering. Don’t do anything there that you wouldn’t normally do while rendering. For example, side effects belong in useEffect, not useMemo.
I just published react-delta which solves this exact sort of scenario. In my opinion, useEffect
has too many responsibilities.
Object.is
react-delta
breaks useEffect
's responsibilities into several smaller hooks.
Responsibility #1
usePrevious(value)
useLatest(value)
useDelta(value, options)
useDeltaArray(valueArray, options)
useDeltaObject(valueObject, options)
some(deltaArray)
every(deltaArray)
Responsibility #2
In my experience, this approach is more flexible, clean, and concise than useEffect
/useRef
solutions.
This is another option:
export default function Counter() {
}
Enable cross-origin requests in ASP.NET Web API click for more info
Enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:
Install-Package Microsoft.AspNet.WebApi.Cors
This command installs the latest package and updates all dependencies, including the core Web API libraries. Use the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.
Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:
using System.Web.Http;
namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Next, add the [EnableCors] attribute to your controller/ controller methods
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebService.Controllers
{
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
In my case was that I changed a line in a script of my Xcode project and that line was badly written (I forgot to add ";" at the end of the line). So I added the ";" and clean and build project.
This issue was gone, after I've updated my all libraries like nodejs, typescript, yarn, npm, etc for my project.
This fixed my problem:
ng generate component nameComponent --module app.module
in my case, the error was with www-data user but not with normal user on development. The error was a problem to initialize an x display for this user. So, the problem was resolved running my selenium test without opening a browser window, headless:
opts.set_headless(True)
Alternatively you can use img2pdf to convert images to pdf. Install it on Debian or Ubuntu with:
sudo apt install img2pdf
Convert one or more images to pdf:
img2pdf img.jpg -o output.pdf
It uses a different mechanism than imagemagick to embed the image into the pdf. When possible Img2pdf embeds the image directly into the pdf, without decoding and recoding the image.
You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.
When using storageClass
Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.
storageClass
-line from the PersistentVolumeClaimAt creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.
The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.
The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound
"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.
A PersistentVolume without StorageClass is considered to be static.
"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.
In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:
apiVersion: v1
kind: PersistentVolume
metadata:
name: ckan-pv-home
labels:
type: local
spec:
capacity:
storage: 100Mi
hostPath:
path: "/mnt/data/ckan"
The PersistentVolumeSpec allows us to define multiple attributes.
I chose a hostPath
volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.
I have had similar problem and I found a solution to that
if you are echo or print something from controller while return to view this problem will pop up.
so make sure that you are not using echo or print when your controller returns
This is how I did it.
Step 1: Install Java 11
You can download Java 11 dmg for mac from here: https://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html
Step 2: After installation of Java 11. Confirm installation of all versions. Type the following command in your terminal.
/usr/libexec/java_home -V
Step 3: Edit .bash_profile
sudo nano ~/.bash_profile
Step 4: Add 11.0.1 as default. (Add below line to bash_profile file).
export JAVA_HOME=$(/usr/libexec/java_home -v 11.0.1)
to switch to any version
export JAVA_HOME=$(/usr/libexec/java_home -v X.X.X)
Now Press CTRL+X to exit the bash. Press 'Y' to save changes.
Step 5: Reload bash_profile
source ~/.bash_profile
Step 6: Confirm current version of Java
java -version
I was having this issue and nothing worked. I ran xcode-select --install
and also installed /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
.
BACKGROUND
Since I was having issues with App Store on a new laptop, I was forced to download the Xcode Beta installer from the Apple website to install Xcode outside App Store. So I only had Xcode Beta installed.
SOLUTION
This, (I think), was making clang
to not find the SDKROOT
directory /Applications/Xcode.app/....
, because there is no Beta
in the path, or maybe Xcode Beta simply doesn't install it (I don't know).
To fix the issue, I had to remove Xcode Beta and resolve the App Store issue to install the release version.
tldr;
If you have Xcode Beta, try cleaning up everything and installing the release version before trying out the solutions that are working for other people.
This is just a warning and it will probably be fixed before 2019 with plugin updates so don't worry about it. I would recommend you to use compatible versions of your plugins and gradle.
You can check your plugin version and gradle version here for better experience and performance.
https://developer.android.com/studio/releases/gradle-plugin
Try using the stable versions for a smooth and warning/error free code.
I also occured the error,and I sloved it by removing the curly braces,hope it will help someone else.
You can see that ,I did not put the con in the curly brace,and the error occured ,when I remove the burly brace , the error disappeared.
const modal = (props) => {
const { show, onClose } = props;
let con = <div className="modal" onClick={onClose}>
{props.children}
</div>;
return show === true ? (
{con}
) : (
<div>hello</div>
);
There are an article about the usage of the curly brace.click here
[edit] Note 2020: I used to manual sign this project. In projects where I automatically signed, I never had this issue. [/edit]
I had the same problem, and spent hours searching for an answer, removing profiles, cleaning project, and so on.
Have you distributed your app? You need to switch back to your developer profile, but not in General under the project settings, but in Build settings.
Under Signing, look at your Code Signing Identity.
Make sure that both your Debug and Release are set your iOS Developer, and not iOS Distribution; or your iOS Developer Provisioning profile, if not set to the automatic values.
The same goes with Provisioning Profile. It should be your developing profile, and not your distribution profile.
Hope this will help future developers in need.
I was having same error In ReactJS statless function while using ReactJs Hook useState. I wanted to set state of an object array , so if I use the following way
const [items , setItems] = useState([]);
and update the state like this:
const item = { id : new Date().getTime() , text : 'New Text' };
setItems([ item , ...items ]);
I was getting error:
Argument of type '{ id: number; text: any }' is not assignable to parameter of type 'never'
but if do it like this,
const [items , setItems] = useState([{}]);
Error is gone but there is an item at 0 index which don't have any data(don't want that).
so the solution I found is:
const [items , setItems] = useState([] as any);
I had just added the SystemConfiguration.framework and Reachability h and m when the issue began. I tried all of these solutions and ended up removing systemConfiguration.framework and that fixed it for me. The Reachability h and m are still in the project.
The "Legacy Build System" solution didn't work for me. What worked it was:
i've try a lot of ways, but only this work for me
thanks for workaround
check your .env
MYSQL_VERSION=latest
then type this command
$ docker-compose exec mysql bash
$ mysql -u root -p
(login as root)
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'root';
ALTER USER 'default'@'%' IDENTIFIED WITH mysql_native_password BY 'secret';
then go to phpmyadmin and login as :
hope it help
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
Updated Answer
As of June11, 2018 it is now mandatory to have a billing account to get API key. You can still make keyless calls to the Maps JavaScript API and Street View Static API which will return low-resolution maps that can be used for development. Enabling billing still gives you $200 free credit monthly for your projects.
This answer is no longer valid
As long as you're using a testing API key it is free to register and use. But when you move your app to commercial level you have to pay for it. When you enable billing, google gives you $200 credit free each month that means if your app's map usage is low you can still use it for free even after the billing enabled, if it exceeds the credit limit now you have to pay for it.
you can try binding property whit route
in your component.ts
user:any = 'linkABC'
;
in your component.html
<a target="_blank" href="yourtab/{{user}}">new tab </a>
This worked for me (using WSL)
sudo /etc/init.d/redis start
(for any other service, check the init.d folder for filenames)
The use of the deprecated new Buffer()
constructor (i.E. as used by Yarn) can cause deprecation warnings. Therefore one should NOT use the deprecated/unsafe Buffer constructor.
According to the deprecation warning new Buffer()
should be replaced with one of:
Buffer.alloc()
Buffer.allocUnsafe()
or Buffer.from()
Another option in order to avoid this issue would be using the safe-buffer package instead.
You can also try (when using yarn..):
yarn global add yarn
as mentioned here: Link
Another suggestion from the comments (thx to gkiely): self-update
Note: self-update is not available. See policies for enforcing versions within a project
In order to update your version of Yarn, run
curl --compressed -o- -L https://yarnpkg.com/install.sh | bash
I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.
(The strange thing was that all ssh-*
commands were valid, (bash could execute as program) but the openssh package wasn't installed.)
In your scenario, converting a string to a boolean can be done via something like someString === 'true'
(as was already answered).
However, let me try to address your main issue: dealing with the local storage.
The local storage only supports strings as values; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.
A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.
The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.
function setItemInStorage(key, item) {
localStorage.setItem(key, JSON.stringify(item));
}
function getItemFromStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
Your example could then be rewritten as:
setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);
And:
if (getItemFromStorage('CheckOutPageReload')) {
const pageLoadParams = getItemFromStorage('CheckOutPageReload');
this.btnLoginNumOne = pageLoadParams[0];
this.btnLoginEdit = pageLoadParams[1];
}
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
If it's a single text widget that you want to wrap, you can either use Flexible or Expanded widgets.
Expanded(
child: Text('Some lengthy text for testing'),
)
or
Flexible(
child: Text('Some lengthy text for testing'),
)
For multiple widgets, you may choose Wrap widget. For further details checkout this
Just type the command you want execute with the user permission, if you don't want to change the permission:
pip3 install --upgrade tensorflow-gpu --user
hello everyone I had the same issue and non of the above answers fixed so I went to the flutter official GitHub and found the answer there here is the link and you have to follow all these steps.
https://github.com/flutter/flutter/issues/67986
flutter upgrade
flutter config --android-studio-dir="C:\Program Files\Android\Android Studio"
for mac you can do the following as answered by Andrew
ln -s ~/Library/Application\ Support/Google/AndroidStudio4.1/plugins ~/Library/Application\ Support/AndroidStudio4.1
flutter doctor -v
then if the issue still persistes then just shift to the beta channel and the upgrade flutter then it will fix it.
flutter channel beta
flutter upgrade
you can enable flutter web as an optional steps
Using Blob
as a source for an img
:
template:
<img [src]="url">
component:
public url : SafeResourceUrl;
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
this.getImage('/api/image.jpg').subscribe(x => this.url = x)
}
public getImage(url: string): Observable<SafeResourceUrl> {
return this.http
.get(url, { responseType: 'blob' })
.pipe(
map(x => {
const urlToBlob = window.URL.createObjectURL(x) // get a URL for the blob
return this.sanitizer.bypassSecurityTrustResourceUrl(urlToBlob); // tell Anuglar to trust this value
}),
);
}
Further reference about trusting save values
try this instead For Window
TASKKILL //F //IM dart.exe
This worked!
This error can be due to many many things.
The key here seems the hint about error reading
. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.
You could also try with sudo
, that might solve a permission problem if that's the case.
Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...
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>
you can use localStorage for storing the json data:
the example is given below:-
let JSONDatas = [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "Find", "label": "Find..."},
{"id": "FindAgain", "label": "Find Again"},
{"id": "Copy"},
{"id": "CopyAgain", "label": "Copy Again"},
{"id": "CopySVG", "label": "Copy SVG"},
{"id": "ViewSVG", "label": "View SVG"}
]
localStorage.setItem("datas", JSON.stringify(JSONDatas));
let data = JSON.parse(localStorage.getItem("datas"));
console.log(data);
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)
28.0.0
is the final version of support libraries. Android has migrated to AndroidX. To use the latest android libraries, Migrating to AndroidX
Edit: Versions
28.0.0-rc02
and28.0.0
are now available.
I don't see any 28.0
version on Google Maven. Only 28.0.0-alpha1
and 28.0.0-alpha3
. Just change it to either of those or how it was previously, i.e., with .+
which just means any version under 28
major release.
For an alpha appcompat release 28.+
makes more sense.
Here is the script I use in a Dockerfile
based on windows/servercore
to achieve complete PowerShellGallery setup through Artifactory mirrors (require access to GitHub releases too)
ARG ONEGET_PACKAGEMANAGEMENT="https://artifactory/artifactory/github-releases/OneGet/oneget/releases/download/1.4/PackageManagement.zip"
ARG ONEGET_ZIPFILE="C:/PackageManagement.zip"
RUN $ProviderPath = 'C:/Program Files/PackageManagement/ProviderAssemblies/nuget/2.8.5.208/'; `
Invoke-WebRequest -Uri ${Env:ONEGET_PACKAGEMANAGEMENT} -OutFile ${Env:ONEGET_ZIPFILE}; `
Expand-Archive ${Env:ONEGET_ZIPFILE} -DestinationPath "C:/" -Force; `
New-Item -ItemType "directory" -Path $ProviderPath -Force; `
Move-Item -Path "C:/PackageManagement/fullclr/Microsoft.PackageManagement.NuGetProvider.dll" -Destination $ProviderPath -Force; `
Remove-Item -Recurse -Force -Path "C:/PackageManagement",${Env:ONEGET_ZIPFILE}; `
Install-PackageProvider -Name NuGet -RequiredVersion 2.8.5.208 -Force; `
Register-PSRepository -Name "artifactory-powershellgallery-remote" -SourceLocation "https://artifactory/artifactory/api/nuget/powershellgallery-remote"; `
Unregister-PSRepository -Name PSGallery;
I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:
While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(
Thanks for help.
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).
You should use jwt.verify it will check if the token is expired. jwt.decode should not be used if the source is not trusted as it doesn't check if the token is valid.
Had the same issue but in my case the fix was slightly different, as no updates were showing for the Android SDK Tools. I opened the Virtual Device Manager and realised my emulator was running API 27. Checked back in the SDK Manager and I didn't have API 27 SDK Tools installed at all. Installing v 27 resolved the issue for me.
If you added "spring-boot-starter-data-jpa" dependency in pom.xml, Please add respective database in dependency like h2 and etc.
You can't.
As a workaround you can use a // @ts-nocheck
comment at the top of a file to disable type-checking for that file: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/
So to disable checking for a block (function, class, etc.), you can move it into its own file, then use the comment/flag above. (This isn't as flexible as block-based disabling of course, but it's the best option available at the moment.)
Update: I've since written a very detailed explanation of the various ways you can install Ruby gems on a Mac. My original recommendation to use a script still stands, but my article goes into more detail: https://www.moncefbelyamani.com/the-definitive-guide-to-installing-ruby-gems-on-a-mac/
You are correct that macOS won't let you change anything with the Ruby version that comes installed with your Mac. However, it's possible to install gems like bundler
using a separate version of Ruby that doesn't interfere with the one provided by Apple.
Using sudo
to install gems, or changing permissions of system files and directories is strongly discouraged, even if you know what you are doing. Can we please stop providing this bad advice? Here's a detailed article I wrote showing how sudo gem install
can wipe out your computer: https://www.moncefbelyamani.com/why-you-should-never-use-sudo-to-install-ruby-gems/
The solution involves two main steps:
PATH
such that the location of the new Ruby version is first in the PATH
. Some tools do this automatically for you. If you're not familiar with the PATH
and how it works, read my guide.There are several ways to install Ruby on a Mac. The best way that I recommend, and that I wish was more prevalent in the various installation instructions out there, is to use an automated script that will set up a proper Ruby environment for you. This drastically reduces the chances of running into an error due to inadequate instructions that make the user do a bunch of stuff manually and leaving it up to them to figure out all the necessary steps.
The other route you can take is to spend extra time doing everything manually and hoping for the best. First, you will want to install Homebrew, which installs the prerequisite command line tools, and makes it easy to install other necessary tools.
Then, the two easiest ways to install a separate version of Ruby are:
Choose one of these four options:
brew install chruby ruby-install
If you chose chruby
and ruby-install
, you can then install the latest Ruby like this:
ruby-install ruby
Once you've installed everything and configured your .zshrc
or .bash_profile
according to the instructions from the tools above, quit and restart Terminal, then switch to the version of Ruby that you want. In the case of chruby
, it would be something like this:
chruby 2.7.2
Whether you need to configure .zshrc
or .bash_profile
depends on which shell you are using. If you're not sure, read this guide: https://www.moncefbelyamani.com/which-shell-am-i-using-how-can-i-switch/
brew install ruby
Then update your PATH
by running (replace 2.7.0
with your newly installed version):
echo 'export PATH="/usr/local/opt/ruby/bin:/usr/local/lib/ruby/gems/2.7.0/bin:$PATH"' >> ~/.zshrc
Then "refresh" your shell for these changes to take effect:
source ~/.zshrc
Or you can open a new terminal tab, or quit and restart Terminal.
Replace .zshrc
with .bash_profile
if you are using Bash. If you're not sure which shell you are using, read this guide: https://www.moncefbelyamani.com/which-shell-am-i-using-how-can-i-switch/
To check that you're now using the non-system version of Ruby, you can run the following commands:
which ruby
It should be something other than /usr/bin/ruby
ruby -v
It should be something other than 2.6.3 if you're on macOS Catalina. As of today, 2.7.2 is the latest Ruby version.
Once you have this new version of Ruby installed, you can now install bundler (or any other gem):
gem install bundler
You are calling:
JSON.parse(scatterSeries)
But when you defined scatterSeries
, you said:
var scatterSeries = [];
When you try to parse it as JSON it is converted to a string (""
), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.
scatterSeries
is not JSON. Do not try to parse it as JSON.
data
is not JSON either (getJSON
will parse it as JSON automatically).
ch
is JSON … but shouldn't be. You should just create a plain object in the first place:
var ch = {
"name": "graphe1",
"items": data.results[1]
};
scatterSeries.push(ch);
In short, for what you are doing, you shouldn't have JSON.parse
anywhere in your code. The only place it should be is in the jQuery library itself.
the solution lies in creating a new key when generating the signed apk. this worked for me without a fuss.
when you install, the warning will not come.
Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin
not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors
at your server side.
You can fetch request using mode: 'cors'
. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.
So in both condition you need to configure cors
in your server or you need to use custom proxy server.
Response headers are generally set on the server. Set 'Access-Control-Allow-Headers'
to 'Content-Type'
on server side
If anyone is getting this error using Nginx, try adding the following to your server config:
server {
listen 443 ssl;
...
}
The issue stems from Nginx serving an HTTP server to a client expecting HTTPS on whatever port you're listening on. When you specify ssl
in the listen
directive, you clear this up on the server side.
As a windows user, run an Admin powershell and launch :
python -m pip install --upgrade pip
By Default angular return responseType as Json, but we can configure below types according to your requirement.
responseType: 'arraybuffer'|'blob'|'json'|'text'
Ex:
this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'});
Adding androidTestImplementation 'androidx.test:runner:1.2.0-alpha05'
works for me.
My situation was similar to the Damo's one - some Products were added to the Pods project twice. The structure of my Podfile was:
# platform :ios, '11.0'
def shared_pods
use_frameworks!
pod 'SharedPod1'
end
target 'Target1' do
pod 'SomePod1'
shared_pods
end
target 'Target2' do
shared_pods
end
and all shared pods were added twice. Uncommenting of first line and then pod install
solved the problem.
Just gone through the same problem when trying to import a CSV (400 MBs) and was also getting an error in red saying
Error - incorrect format parameter
Initially thought it could have been the parameters and tested again. Faster, from my previous experince with it, I realized that it was due to other reasons (size of the file, execution of script has a maximum time defined, etc).
So, I've gone to php.ini
and changed the values from the following settings
max_execution_time = 3000
max_input_time = 120
memory_limit = 512M
post_max_size = 1500M
upload_max_filesize = 1500M
After this modification, stoped MySQL and Apache and started them again, went to phpmyadmin trying to import. Then I reached another error
Fatal error: Maximum execution time of 300 seconds exceeded
which was fixed by simply setting in xampp/phpmyadmin/libraries/config.default.php
$cfg['ExecTimeLimit'] = 0;
Setting it to 0 disables execution time limits.
Then, after a while, the import happened without problems.
In one of your dataframes the year is a string and the other it is an int64
you can convert it first and then join (e.g. df['year']=df['year'].astype(int)
or as RafaelC suggested df.year.astype(int)
)
Edit: Also note the comment by Anderson Zhu: Just in case you have None
or missing values in one of your dataframes, you need to use Int64
instead of int
. See the reference here.
sudo npm cache clean --force --unsafe-perm
and then npm i goes normally
if anyone come here to convert firebase Timestamp
here this will help
Timestamp time;
DateTime.fromMicrosecondsSinceEpoch(time.microsecondsSinceEpoch)
By default, Elasticsearch installed goes into read-only mode when you have less than 5% of free disk space. If you see errors similar to this:
Elasticsearch::Transport::Transport::Errors::Forbidden: [403] {"error":{"root_cause":[{"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"}],"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"},"status":403}
Or in /usr/local/var/log/elasticsearch.log you can see logs similar to:
flood stage disk watermark [95%] exceeded on [nCxquc7PTxKvs6hLkfonvg][nCxquc7][/usr/local/var/lib/elasticsearch/nodes/0] free: 15.3gb[4.1%], all indices on this node will be marked read-only
Then you can fix it by running the following commands:
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_cluster/settings -d '{ "transient": { "cluster.routing.allocation.disk.threshold_enabled": false } }'
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
here is a simple solution.
the problem is because you are using latest version for one library and lower version for the other library. try to balance it. the best solution is to use latest version for all of your libraries.
To solve your problem simply click here and see the latest version of libraries and include it in you project and then synchronize it.
in my case the following is working for me:
dependencies{
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.google.firebase:firebase-database:16.1.0'
}
apply plugin: 'com.google.gms.google-services'
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
jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.
from pandas import DataFrame, concat
a = DataFrame([{'a':1, 'c':2,'d':3 }])
b = DataFrame([{'a':4,'b':5, 'd':6,'e':7}])
>>> concat([a,b],sort=False)
a c d b e
0 1 2.0 3 NaN NaN
0 4 NaN 6 5.0 7.0
>>> concat([a,b],sort=True)
a b c d e
0 1 NaN 2.0 3 NaN
0 4 5.0 NaN 6 7.0
As of April 2018, Chrome's autoplay policies changed:
"Chrome's autoplay policies are simple:
Autoplay with sound is allowed if:
Also
Chrome's developer site has more information, including some programming examples, which can be found here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
You need to add { useNewUrlParser: true }
in the mongoose.connect() method.
mongoose.connect('mongodb://localhost:27017/Notification',{ useNewUrlParser: true });
As Mentioned in above repilies:
Starting with MySQL 8.0.4, the MySQL team changed the default authentication plugin for MySQL server from mysql_native_password to caching_sha2_password.
So there are three ways to resolve this issue:
1. drop USER 'user_name'@'localhost';
flush privileges;
CREATE USER 'user_name'@'localhost' IDENTIFIED BY 'user_name';
GRANT ALL PRIVILEGES ON * . * TO 'user_name'@'localhost';
ALTER USER 'user_name'@'localhost' IDENTIFIED WITH mysql_native_password BY
'user_name';
2. drop USER 'user_name'@'localhost';
flush privileges;
CREATE USER 'user_name'@'localhost' IDENTIFIED WITH mysql_native_password BY 'user_name';
GRANT ALL PRIVILEGES ON * . * TO 'user_name'@'localhost'
3. If the user is already created, the use the following command:
ALTER USER 'user_name'@'localhost' IDENTIFIED WITH mysql_native_password BY
'user_name';
First of all, please make sure your Database server is up and running. I was getting the same error, after trying all the answers listed here I found out that my Database server was not running.
You can check the same from MySQL Workbench, or Command line using
mysql -u USERNAME -p
This sounds obvious, but many times we assume that Database server is up and running all the time, especially when we are working on our local machine, when we restart/shutdown the machine, Database server will be shutdown automatically.
This error comes up when you try to clone a repository in a folder which still contains .git
folder (Hidden folder).
If the earlier answers doesn't work then you can proceed with my answer. Hope it will solve your issue.
Open terminal & change the directory to the destination folder (where you want to clone).
Now type: ls -a
You may see a folder named .git
.
You have to remove that folder by the following command: rm -rf .git
Now you are ready to clone your project.
Just had the same error message, but when I was running a package.json with:
"scripts": {
"build": "tsc -p ./src",
}
tsc
is the command to run the TypeScript compiler.
I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install
didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev
) to solve the problem.
npm uninstal @angular/material
and also clear file custom-theme.scss
If you've installed flutter from the snap store on Ubuntu, you'll find the SDK at
/home/(username)/snap/flutter/common/flutter
FYI - I installed Flutter on Ubuntu 20.04 LTS using snap install
and am using Android Studio 4.0.1 installed via JetBrains toolbox app
sudo snap install flutter --classic
sudo snap install flutter-gallery
flutter channel dev
flutter upgrade
flutter config --enable-linux-desktop
It was not necessary to install the SDK separately, the snap steps above will place the SDK at
/home/(username)/snap/flutter/common/flutter
Here's the Android Studio Pop-up for a new Flutter app accepting this location for the Flutter SDK:
This terminal command:
open /Applications/Python\ 3.7/Install\ Certificates.command
Found here: https://stackoverflow.com/a/57614113/6207266
Resolved it for me. With my config
pip install --upgrade certifi
had no impact.
I was trying to create a web application with spring boot and I got the same error. After inspecting I found that I was missing a dependency. So, be sure to add following dependency to your pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
This may work:
grant all on dbtest.* to 'dbuser'@'%' identified by 'mysql_password';
You can try: ng serve --configuration=dev/prod
To build use: ng build --prod --configuration=dev
Hope you are using a different kind of environment.
My case was a little different. After restarting my system, I had not whitelisted my IP address on Mongo while doing local development.
Select Network Access > Add IP Address > Add your current IP Address
Add this to your gradle file.
implementation 'com.android.support:support-annotations:27.1.1'
$ mysql -u root -p
Enter password: (enter your root password)
(Replace your_new_password
with the password you want to use)
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_new_password';
mysql> FLUSH PRIVILEGES;
mysql> quit
Then try connecting using node
I think it is not useful to configure the mysql server without caching_sha2_password encryption, we have to find a way to publish, send or obtain secure information through the network. As you see in the code below I dont use variable $db_name, and Im using a user in mysql server with standar configuration password. Just create a Standar user password and config all privilages. it works, but how i said without segurity.
<?php
$db_name="db";
$mysql_username="root";
$mysql_password="****";
$server_name="localhost";
$conn=mysqli_connect($server_name,$mysql_username,$mysql_password);
if ($conn) {
echo "connetion success";
}
else{
echo mysqli_error($conn);
}
?>
The import form and the module declaration need to agree about the shape of the module, about what it exports.
When you write (a suboptimal practice for importing JSON since TypeScript 2.9 when targeting compatible module formatssee note)
declare module "*.json" {
const value: any;
export default value;
}
You are stating that all modules that have a specifier ending in .json
have a single export named default
.
There are several ways you can correctly consume such a module including
import a from "a.json";
a.primaryMain
and
import * as a from "a.json";
a.default.primaryMain
and
import {default as a} from "a.json";
a.primaryMain
and
import a = require("a.json");
a.default.primaryMain
The first form is the best and the syntactic sugar it leverages is the very reason JavaScript has default
exports.
However I mentioned the other forms to give you a hint about what's going wrong. Pay special attention to the last one. require
gives you an object representing the module itself and not its exported bindings.
So why the error? Because you wrote
import a = require("a.json");
a.primaryMain
And yet there is no export named primaryMain
declared by your "*.json"
.
All of this assumes that your module loader is providing the JSON as the default
export as suggested by your original declaration.
Note: Since TypeScript 2.9, you can use the --resolveJsonModule
compiler flag to have TypeScript analyze imported .json
files and provide correct information regarding their shape obviating the need for a wildcard module declaration and validating the presence of the file. This is not supported for certain target module formats.
Actually, it's not possible with axios as of now. The status codes which falls in the range of 2xx
only, can be caught in .then()
.
A conventional approach is to catch errors in the catch()
block like below:
axios.get('/api/xyz/abcd')
.catch(function (error) {
if (error.response) {
// Request made and server responded
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
});
Another approach can be intercepting requests or responses before they are handled by then or catch.
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
In file "/usr/local/bin/pip" change from pip._internal import main
to from pip import main
I had some issues playing on Android Phone. After few tries I found out that when Data Saver is on there is no auto play:
There is no autoplay if Data Saver mode is enabled. If Data Saver mode is enabled, autoplay is disabled in Media settings.
Set Copy Enbale to true in netstandard.dll properties.
Open Solution Explorer and right click on netstandard.dll. Set Copy Local to true.
I had a similar issue. Back-revving RXJS from 6.x to the latest 5.x release fixed it for Angular 5.2.x.
Open package.json.
Change "rxjs": "^6.0.0",
to "rxjs": "^5.5.10",
run npm update
I was trying to install docker-compose on "Ubuntu 16.04.5 LTS" but after installing it like this:
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
I was getting:
-bash: /usr/local/bin/docker-compose: Permission denied
and while I was using it with sudo I was getting:
sudo: docker-compose: command not found
So here's the steps that I took and solved my problem:
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose
Check your folder structure where you are executing the command, you should run the command 'ng serve' where there should be a angular.json file in the structure.
angular.json file will be generated by default when we run the command
npm install -g '@angular/cli' ng new Project_name then cd project_folder then, run ng serve. it worked for me
HttpClientModule needs to be in the imports array, and remove it from providers. That section is for you to tell Angular which services the module has (written by you and not imported from a library).
WARNING: This answer is useful if you have problems with JAVA_HOME environmental variable and the direction of that. If you do not have this problem, you should not try this solution.
If you have this error and you tried with flutter doctor --android-licenses or sdkmanager --licenses and you got a problem with your JAVA_HOME environmental variable, then you have to read this.
I have a MacOS Catalina ant I could resolve this problem successfully with the next steps:
Please, let me know if you have doubts.
I recently ran into this issue for a different reason: I was running some tests synchronously using jest -i
, and it would just timeout. For whatever reasoning, running the same tests using jest --runInBand
(even though -i
is meant to be an alias) doesn't time out.
Maybe this will help someone ¯\_(:/)_/¯
I faced same problem when I updated the Java version to 12.x. I was executing my project through Eclipse IDE. I am not sure whether this error is caused by compatibility issues.
However, I removed 12.x from my system and installed 8.x and my project started working fine.
Add the line below in application.properties file under resource folder and restart your application.
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
The error is not refering to myfunction
but to start
.
async function start() {
....
const result = await helper.myfunction('test', 'test');
}
// My function_x000D_
const myfunction = async function(x, y) {_x000D_
return [_x000D_
x,_x000D_
y,_x000D_
];_x000D_
}_x000D_
_x000D_
// Start function_x000D_
const start = async function(a, b) {_x000D_
const result = await myfunction('test', 'test');_x000D_
_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
// Call start_x000D_
start();
_x000D_
I use the opportunity of this question to advise you about an known anti pattern using await
which is : return await
.
WRONG
async function myfunction() {_x000D_
console.log('Inside of myfunction');_x000D_
}_x000D_
_x000D_
// Here we wait for the myfunction to finish_x000D_
// and then returns a promise that'll be waited for aswell_x000D_
// It's useless to wait the myfunction to finish before to return_x000D_
// we can simply returns a promise that will be resolved later_x000D_
_x000D_
// useless async here_x000D_
async function start() {_x000D_
// useless await here_x000D_
return await myfunction();_x000D_
}_x000D_
_x000D_
// Call start_x000D_
(async() => {_x000D_
console.log('before start');_x000D_
_x000D_
await start();_x000D_
_x000D_
console.log('after start');_x000D_
})();
_x000D_
CORRECT
async function myfunction() {_x000D_
console.log('Inside of myfunction');_x000D_
}_x000D_
_x000D_
// Here we wait for the myfunction to finish_x000D_
// and then returns a promise that'll be waited for aswell_x000D_
// It's useless to wait the myfunction to finish before to return_x000D_
// we can simply returns a promise that will be resolved later_x000D_
_x000D_
// Also point that we don't use async keyword on the function because_x000D_
// we can simply returns the promise returned by myfunction_x000D_
function start() {_x000D_
return myfunction();_x000D_
}_x000D_
_x000D_
// Call start_x000D_
(async() => {_x000D_
console.log('before start');_x000D_
_x000D_
await start();_x000D_
_x000D_
console.log('after start');_x000D_
})();
_x000D_
Also, know that there is a special case where return await
is correct and important : (using try/catch)
In my case, this error happened with a new project.
none of the proposed solutions here worked, so I simply reinstalled all the packages and started working correctly.
Alright so for me nothing worked.
I was using spring boot with hibernate. The spring boot version was ~2.0.1 and I would keep get this error and null pointer exception upon compilation. The issue was with hibernate that needed a version bump. But after that I had some other issues that seemed like the annotation processor was not recognised so I decided to just bump spring from 2.0.1 to 2.1.7-release and everything worked as expected.
You still need to add the above plugin tough
Hope it helps!
try to reload daemon then restart docker service.
systemctl daemon-reload
I know it's a relative old post but, I would like to share what worked for me: I've simply input "http://" before "localhost" in the url. Hope it helps somebody.
From at least, the 2.0
version, Spring-Data-Jpa
modified findOne()
.
Now, findOne()
has neither the same signature nor the same behavior.
Previously, it was defined in the CrudRepository
interface as:
T findOne(ID primaryKey);
Now, the single findOne()
method that you will find in CrudRepository
is the one defined in the QueryByExampleExecutor
interface as:
<S extends T> Optional<S> findOne(Example<S> example);
That is implemented finally by SimpleJpaRepository
, the default implementation of the CrudRepository
interface.
This method is a query by example search and you don't want that as a replacement.
In fact, the method with the same behavior is still there in the new API, but the method name has changed.
It was renamed from findOne()
to findById()
in the CrudRepository
interface :
Optional<T> findById(ID id);
Now it returns an Optional
, which is not so bad to prevent NullPointerException
.
So, the actual method to invoke is now Optional<T> findById(ID id)
.
How to use that?
Learning Optional
usage.
Here's important information about its specification:
A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.
Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).
Some hints on how to use Optional
with Optional<T> findById(ID id)
.
Generally, as you look for an entity by id, you want to return it or make a particular processing if that is not retrieved.
Here are three classical usage examples.
You could write :
Foo foo = repository.findById(id)
.orElse(new Foo());
or get a null
default value if it makes sense (same behavior as before the API change) :
Foo foo = repository.findById(id)
.orElse(null);
You could write :
return repository.findById(id)
.orElseThrow(() -> new EntityNotFoundException(id));
You could write :
Optional<Foo> fooOptional = fooRepository.findById(id);
if (fooOptional.isPresent()) {
Foo foo = fooOptional.get();
// processing with foo ...
} else {
// alternative processing....
}
For me, when I was running "flutter doctor" command from Ubuntu Command line - It showed me below error.
[?] Android toolchain - develop for Android devices ? Unable to locate Android SDK.
From this error, it is obvious that "flutter doctor" was not able to find the "android sdk" and the reason for that was my android sdk was downloaded in a custom location on my Ubuntu machine.
So we must need to tell "flutter doctor" about this custom android location, using below command,
flutter config --android-sdk /home/myhome/Downloads/softwares/android-sdk/
Need to replace /home/myhome/Downloads/softwares/android-sdk/
with path to your custom location/place where android sdk is available.
Once this is done, and re-run "flutter doctor" and now it has detected the android sdk location and hence I could run avd/emulator by typing "flutter run"
It had happened to me when I replace the default value with a new dynamic value. But, somehow your code may be dependent on that default value. So try keeping a constant with default value stored somewhere to fallback.
const defVal = 'abcd';
String dynVal = defVal;
// dropdown list whose value is dynVal that keeps changing with onchanged
// when rebuilding or setState((){})
dynVal = defVal;
// rebuilding here...
I solved this problem using this command COMPOSER_MEMORY_LIMIT=-1
Example: COMPOSER_MEMORY_LIMIT=-1 composer requires larval/ui
Usually it's because of sdk versions and/or dependencies.
For Cordova developers, put your dependencies settings in "project.properties
" file under CORDOVA_PROJECT_ROOT/platforms/android/
folder, like this:
target=android-26
android.library.reference.1=CordovaLib
android.library.reference.2=app
cordova.system.library.1=com.android.support:support-v4:26.1.0
cordova.gradle.include.2=cordova-plugin-googlemaps/app-tbxml-android.gradle
cordova.system.library.3=com.android.support:support-core-utils:26.1.0
cordova.system.library.4=com.google.android.gms:play-services-maps:15.0.0
cordova.system.library.5=com.google.android.gms:play-services-location:15.0.0
So if you use CLI "cordova build
", it will overwrite the dependencies section:
dependencies {
implementation fileTree(dir: 'libs', include: '*.jar')
// SUB-PROJECT DEPENDENCIES START
/* section being overwritten by cordova, referencing project.properties */
...
// SUB-PROJECT DEPENDENCIES END
}
If you are using proper libraries and its versions in project.properties, you should be fine.
Note: For MAC OS
What worked is Tools->Flutter->open Android module in Android studio, For me plugin flutter_email_sender was giving this error, so I copied local.properties file into it and the build become successful.
Or
Open Terminal
Run touch ~/.bash_profile; open ~/.bash_profile
export ANDROID_HOME=/Users/<macusername>/Library/Android/sdk
export ANDROID_SDK_ROOT=/Users/<macusername>/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Run source ~/.bash_profile
in android studio terminal
Go to the directory where you put additional libraries and delete duplicated libraries.
Others have answered so I'll add my 2-cents.
You can either use autoconfiguration (i.e. don't use a @Configuration to create a datasource) or java configuration.
Auto-configuration:
define your datasource type then set the type properties. E.g.
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.hikari.driver-class-name=org.h2.Driver
spring.datasource.hikari.jdbc-url=jdbc:h2:mem:testdb
spring.datasource.hikari.username=sa
spring.datasource.hikari.password=password
spring.datasource.hikari.max-wait=10000
spring.datasource.hikari.connection-timeout=30000
spring.datasource.hikari.idle-timeout=600000
spring.datasource.hikari.max-lifetime=1800000
spring.datasource.hikari.leak-detection-threshold=600000
spring.datasource.hikari.maximum-pool-size=100
spring.datasource.hikari.pool-name=MyDataSourcePoolName
Java configuration:
Choose a prefix and define your data source
spring.mysystem.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.mysystem.datasource.jdbc-
url=jdbc:sqlserver://databaseserver.com:18889;Database=MyDatabase;
spring.mysystem.datasource.username=dsUsername
spring.mysystem.datasource.password=dsPassword
spring.mysystem.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.mysystem.datasource.max-wait=10000
spring.mysystem.datasource.connection-timeout=30000
spring.mysystem.datasource.idle-timeout=600000
spring.mysystem.datasource.max-lifetime=1800000
spring.mysystem.datasource.leak-detection-threshold=600000
spring.mysystem.datasource.maximum-pool-size=100
spring.mysystem.datasource.pool-name=MySystemDatasourcePool
Create your datasource bean:
@Bean(name = { "dataSource", "mysystemDataSource" })
@ConfigurationProperties(prefix = "spring.mysystem.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
You can leave the datasource type out, but then you risk spring guessing what datasource type to use.
The actual answer did not worked for me.
But setting ANDROID_HOME
in you ~/.bash_profile
and logout then login, make it work!
This may be an Android Studio issue since It is not setting this environment variable for the open projects.
This error might be also for plugin versions. You can fix it in the .POM file like the followings:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
In my case, just changingTarget JVM Version like this: File > Setting > Kotlin Compiler > Target JVM Version > 1.8 did not help. However, it does resolved compile time error. But failed at runtime.
I also had to add following in app build.gradle file to make it work.
android {
// Other code here...
kotlinOptions {
jvmTarget = "1.8"
}
}
1) Tried creating a new branch and pushing. Worked for a couple of times but faced the same error again.
2)Just ran these two statements before pushing the code. All I did was to cancel the proxy.
$ git config --global --unset http.proxy
$ git config --global --unset https.proxy
3) Faced the issue again after couple of weeks. I have updated homebrew and it got fixed
f = open("Path/To/Your/File.txt", "w") # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name) # Write inside file
f.close() # Close file
# Method 2shush
with open("Path/To/Your/File.txt", "w") as f: # Opens file and casts as f
f.write("Hello World form " + f.name) # Writing
# File closed automatically
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/images/json: dial unix /var/run/docker.sock: connect: permission denied
sudo chmod 666 /var/run/docker.sock
This fix my problem.
If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".
Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."
My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.
As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.
A Worker Process is user mode code whose role is to process requests, such as processing requests to return a static page.
The worker process is controlled by the www service.
worker processes also run application code, Such as ASP .NET applications and XML web Services.
When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process“w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll)and adds the mapping into IIS.
When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.
For more detail refer URL http://aspnetnova.blogspot.in/2011/12/how-iis-process-for-aspnet-requests.html
You have a lot of variants for using @RequestParam
with additional optional elements, e.g.
@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr
If you don't put required = false
- param will be required by default.
defaultValue = "someValue"
- the default value to use as a fallback when the request parameter is not provided or has an empty value.
If request and method param are the same - you don't need value = "someAttr"
Why does not it work?
Because the background CSS with background:none!important
has one #ID
A CSS selector file that contains an #id
will always have a higher value than one .class
If you want to work, you need add #id
on your .image-list li
like this:
#an-element .image-list li {
display: inline-block;
background-image: url("http://placekitten.com/150/50")!important;
padding: 1em;
border: 1px solid blue;
}
This download fixed my VB6 EXE and Access 2016 (using ACEDAO.DLL) run-time error 429. Took me 2 long days to get it resolved because there are so many causes of 429.
http://www.microsoft.com/en-ca/download/details.aspx?id=13255
QUOTE from link: "This download will install a set of components that can be used to facilitate transfer of data between 2010 Microsoft Office System files and non-Microsoft Office applications"
Alternatively, constructing a JMX console yourself doesn't need to be hard. Just plug in Jolokia and create a web page getting the attributes that you're interested in. Admittedly, it doesn't allow you to do trend analysis, but it does allow you to construct something that is really geared towards your purpose.
I constructed something in just a few lines: http://nxt.flotsam.nl/ears-and-eyes.html
Of course Fibonacci numbers can be computed in O(n) by applying the Binet formula:
from math import floor, sqrt
def fib(n):
return int(floor(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))+0.5))
As the commenters note it's not O(1) but O(n) because of 2**n
. Also a difference is that you only get one value, while with recursion you get all values of Fibonacci(n)
up to that value.
Check for a static version of your page in /public and delete it if it's there. When Rails 3.x caches pages, it leaves a static version in your public folder and loads that when users hit your site. This will remain even after you clear your cache.
Previous answers got you list of torch.Size Here is how to get list of ints
listofints = [int(x) for x in tensor.shape]
Something like this:
<Text style={{color: 'blue'}}
onPress={() => Linking.openURL('http://google.com')}>
Google
</Text>
using the Linking
module that's bundled with React Native.
You can also use one of the standard library functools.lru_cache
or functools.cache
decorators in front of the function:
from functools import lru_cache
@lru_cache def expensive_function(): return None
You don't need --header "Content-Length: $LENGTH".
curl --request POST --data-binary "@template_entry.xml" $URL
Note that GET request does not support content body widely.
Also remember that POST request have 2 different coding schema. This is first form:
$ nc -l -p 6666 & $ curl --request POST --data-binary "@README" http://localhost:6666 POST / HTTP/1.1 User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6 Host: localhost:6666 Accept: */* Content-Length: 9309 Content-Type: application/x-www-form-urlencoded Expect: 100-continue .. -*- mode: rst; coding: cp1251; fill-column: 80 -*- .. rst2html.py README README.html .. contents::
You probably request this:
-F/--form name=content (HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content- Type multipart/form-data according to RFC2388. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
In 2021 - use ES6 Template Literals for this task. If you need IE11 Support - use a transpiler.
let a = `something something`;
Template Literals are fast, powerful and produce cleaner code.
If you need IE11 support and you don't have transpiler, stay strong and use \xa0
- it is a NO-BREAK SPACE char.
Reference from UTF-8 encoding table and Unicode characters, you can write as below:
var a = 'something' + '\xa0\xa0\xa0\xa0\xa0\xa0\xa0' + 'something';
To set the color of a font, you must first initialize the color by doing this:
Color maroon = new Color (128, 0, 0);
Once you've done that, you then put:
Font font = new Font ("Courier New", 1, 25); //Initializes the font
c.setColor (maroon); //Sets the color of the font
c.setFont (font); //Sets the font
c.drawString ("Your text here", locationX, locationY); //Outputs the string
Note: The 1 represents the type of font and this can be used to replace Font.PLAIN and the 25 represents the size of your font.
As far as i experienced zposition is a best way.
self.view.layer.zPosition = 1;
netstat -tlpn
It will show the list something like below:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1393/sshd
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1859/master
tcp 0 0 123.189.192.64:7654 0.0.0.0:* LISTEN 2463/monit
tcp 0 0 127.0.0.1:24135 0.0.0.0:* LISTEN 21450/memcached
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 16781/mysqld
Use as root for all details. The -t
option limits the output to TCP connections, -l
for listening ports, -p
lists the program name and -n
shows the numeric version of the port instead of a named version.
In this way you can see the process name and the port.
goto begin and end of all parents closures
var foo=false;
var loop1=true;
LABEL1: do {var LABEL1GOTO=false;
console.log("here be 2 times");
if (foo==false){
foo=true;
LABEL1GOTO=true;continue LABEL1;// goto up
}else{
break LABEL1; //goto down
}
console.log("newer go here");
} while(LABEL1GOTO);
You were on the right track. IrfanView sets the background for transparency the same as the viewing color around the image.
You just need to re-open the image with IrfanView after changing the view color to white.
To change the viewing color in Irfanview go to:
Options > Properties/Settings > Viewing > Main window color
ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;
You can do this with the apksigner
tool that is part of the Android SDK:
apksigner verify --print-certs my_app.apk
You can find apksigner inside the build-tools directory. For example:
~/Library/Android/sdk/build-tools/29.0.1/apksigner
Qt C++ will show this error when you change a class such that it now inherits from QObject (ie so that it can now use signals/slots). Running qmake -r will call moc and fix this problem.
If you are working with others via some sort of version control, you will want to make some change to your .pro file (ie add/remove a blank line). When everyone else gets your changes and runs make, make will see that the .pro file has changed and automatically run qmake. This will save your teammates from repeating your frustration.
zmk's approach uses list comprehension which is very fast, yet keeps the order naturally. For applying to case sensitive strings it can be easily modified. This also preserves the original case.
def DelDupes(aseq) :
seen = set()
return [x for x in aseq if (x.lower() not in seen) and (not seen.add(x.lower()))]
Closely associated functions are:
def HasDupes(aseq) :
s = set()
return any(((x.lower() in s) or s.add(x.lower())) for x in aseq)
def GetDupes(aseq) :
s = set()
return set(x for x in aseq if ((x.lower() in s) or s.add(x.lower())))
You need to escape your backslash by preceding it with, yes, another backslash:
print("\\")
And for versions prior to Python 3:
print "\\"
The \
character is called an escape character, which interprets the character following it differently. For example, n
by itself is simply a letter, but when you precede it with a backslash, it becomes \n
, which is the newline character.
As you can probably guess, \
also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.
You can add security provider by editing java.security with using following code with creating static block:
static {
Security.addProvider(new BouncyCastleProvider());
}
If you are using maven project, then you will have to add dependency for BouncyCastleProvider as follows in pom.xml file of your project.
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.47</version>
</dependency>
If you are using normal java project, then you can add download bcprov-jdk15on-147.jar from the link given below and edit your classpath.
http://www.java2s.com/Code/Jar/b/Downloadbcprovextjdk15on147jar.htm
For my private repository reference I didn't want to include a secure token, and none of the other simple (i.e. specifying only in package.json) worked. Here's what did work:
You can get the week number directly from datetime as string.
>>> import datetime
>>> datetime.date(2010, 6, 16).strftime("%V")
'24'
Also you can get different "types" of the week number of the year changing the strftime
parameter for:
%U
- Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. Examples: 00, 01, …, 53
%W
- Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. Examples: 00, 01, …, 53[...]
(Added in Python 3.6, backported to some distribution's Python 2.7's) Several additional directives not required by the C89 standard are included for convenience. These parameters all correspond to ISO 8601 date values. These may not be available on all platforms when used with the
strftime()
method.[...]
%V
- ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4. Examples: 01, 02, …, 53from: datetime — Basic date and time types — Python 3.7.3 documentation
I've found out about it from here. It worked for me in Python 2.7.6
I used the jQuery slim version and got this error. By using the normal jQuery version the issue got resolved.
for(int i = 0; i < n; i++) {
existing_string += 'c';
}
but you should use StringBuilder instead, and save memory
int n = 3;
String existing_string = "string";
StringBuilder builder = new StringBuilder(existing_string);
for (int i = 0; i < n; i++) {
builder.append(" append ");
}
System.out.println(builder.toString());
The easiest solution is the first one of your examples:
<a href="#link" class="btn btn-info" role="button">Link Button</a>
The reason it's not working for you is most likely, as you say, a problem in the theme you're using. There is no reason to resort to bloated extra markup or inline Javascript for this.
I try to understand the famous sentence in my way: "Python dose not care an object is a real duck or not. All it cares is whether the object, first 'quack', second 'like a duck'."
There is a good website. http://www.voidspace.org.uk/python/articles/duck_typing.shtml#id14
The author pointed that duck typing let you create your own classes that have their own internal data structure - but are accessed using normal Python syntax.
var emptyDictionary = [String: String]()
var populatedDictionary = ["key1": "value1", "key2": "value2"]
Note: if you are going to change the contents of the dictionary over time then declare it as a var
(variable). You can declare an empty dictionary as a let
(constant) but it is pointless if you have the intention of changing its contents over time, since constant can't be changed after it has been initialized.
Old answer:
Creating an empty dictionary of type <String, String>
would look as follows:
var emptyDictionary = Dictionary<String, String>()
Echo key and value of an array without and with loop
$array = array(
'kk6NFKK'=>'name',
'nnbDDD'=>'claGg',
'nnbDDD'=>'kaoOPOP',
'nnbDDD'=>'JWIDE4',
'nnbDDD'=>'lopO'
);
print_r(each($array));
Output
Array
(
[1] => name
[value] => name
[0] => kk6NFKK
[key] => kk6NFKK
)
If you want to remove multiple whitespace items and replace them with single spaces, the easiest way is with a regexp like this:
>>> import re
>>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
>>> re.sub('\s+',' ',myString)
'I want to Remove all white spaces, new lines and tabs '
You can then remove the trailing space with .strip()
if you want to.
The simplest and most portable way is.
var varFieldName = "good";
var ob = {};
Object.defineProperty(ob, varFieldName , { value: "Fresh Value" });
Based on #abeing answer!
If you would like to write your own, you can start with this six-part document detailing effective usage of C# 2.0 data structures and how to go about analyzing your implementation of data structures in C#. Each article has examples and an installer with samples you can follow along with.
“An Extensive Examination of Data Structures Using C# 2.0” by Scott Mitchell
The following seems to work:
import datetime
print (datetime.datetime.now().strftime("%y"))
The datetime.data object that it wants is on the "left" of the dot rather than the right. You need an instance of the datetime to call the method on, which you get through now()
This isn't an answer. I was struggling but then realized that my install was trying to connect to internet to download dependencies.
So, I downloaded and installed dependencies first and then installed with below command. It worked
python -m pip install filename.tar.gz
If you use Alamofire, it is enough to encoding type to "URLEncoding.httpBody"
With that, you can send your data as a string in the httpbody allthough you defined it json in your code.
It worked for me..
UPDATED for
var url = "http://..."
let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]
let url = NSURL(string:"url" as String)
request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody , headers: _headers).responseJSON(completionHandler: {
response in response
let jsonResponse = response.result.value as! NSDictionary
if jsonResponse["access_token"] != nil
{
access_token = String(describing: jsonResponse["accesstoken"]!)
}
})
Just use std::string
:
std::cout << std::string( n, ' ' );
In many cases, however, depending on what comes next, is may be
simpler to just add n
to the parameter to an std::setw
.
I created a shell templating script named shtpl
. My shtpl
uses a jinja-like syntax which, now that I use ansible a lot, I'm pretty familiar with:
$ cat /tmp/test
{{ aux=4 }}
{{ myarray=( a b c d ) }}
{{ A_RANDOM=$RANDOM }}
$A_RANDOM
{% if $(( $A_RANDOM%2 )) == 0 %}
$A_RANDOM is even
{% else %}
$A_RANDOM is odd
{% endif %}
{% if $(( $A_RANDOM%2 )) == 0 %}
{% for n in 1 2 3 $aux %}
\$myarray[$((n-1))]: ${myarray[$((n-1))]}
/etc/passwd field #$n: $(grep $USER /etc/passwd | cut -d: -f$n)
{% endfor %}
{% else %}
{% for n in {1..4} %}
\$myarray[$((n-1))]: ${myarray[$((n-1))]}
/etc/group field #$n: $(grep ^$USER /etc/group | cut -d: -f$n)
{% endfor %}
{% endif %}
$ ./shtpl < /tmp/test
6535
6535 is odd
$myarray[0]: a
/etc/group field #1: myusername
$myarray[1]: b
/etc/group field #2: x
$myarray[2]: c
/etc/group field #3: 1001
$myarray[3]: d
/etc/group field #4:
More info on my github
A free and easy to use service is provided at Webtechriser (click here to read the article) (called wipmania). This one is a JSONP service and requires plain javascript coding with HTML. It can also be used in JQuery. I modified the code a bit to change the output format and this is what I've used and found to be working: (it's the code of my HTML page)
<html>_x000D_
<body>_x000D_
<p id="loc"></p>_x000D_
_x000D_
_x000D_
<script type="text/javascript">_x000D_
var a = document.getElementById("loc");_x000D_
_x000D_
function jsonpCallback(data) { _x000D_
a.innerHTML = "Latitude: " + data.latitude + _x000D_
"<br/>Longitude: " + data.longitude + _x000D_
"<br/>Country: " + data.address.country; _x000D_
}_x000D_
</script>_x000D_
<script src="http://api.wipmania.com/jsonp?callback=jsonpCallback"_x000D_
type="text/javascript"></script>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
PLEASE NOTE: This service gets the location of the visitor without prompting the visitor to choose whether to share their location, unlike the HTML 5 geolocation API (the code that you've written). Therefore, privacy is compromised. So, you should make judicial use of this service.
It may be caused by IE's box model bug. To fix this, you can use the Box Model Hack.
You cant remove a single event, but all? at once? just do
document.body.innerHTML = document.body.innerHTML
Use the :not selector.
$(".thisclass:not(#thisid)").doAction();
If you have multiple ids or selectors just use the comma delimiter, in addition:
(".thisclass:not(#thisid,#thatid)").doAction();
You have so many choices, how could you be confused :-)? The main controls are:
# \pset format
# \H
# \x
# \pset pager off
Each has options and interactions with the others. The most automatic options are:
# \x off;\pset format wrapped
# \x auto
The newer "\x auto" option switches to line-by-line display only "if needed".
-[ RECORD 1 ]---------------
id | 6
description | This is a gallery of oilve oil brands.
authority | I love olive oil, and wanted to create a place for
reviews and comments on various types.
-[ RECORD 2 ]---------------
id | 19
description | XXX Test A
authority | Testing
The older "\pset format wrapped" is similar in that it tries to fit the data neatly on screen, but falls back to unaligned if the headers won't fit. Here's an example of wrapped:
id | description | authority
----+--------------------------------+---------------------------------
6 | This is a gallery of oilve | I love olive oil, and wanted to
; oil brands. ; create a place for reviews and
; ; comments on various types.
19 | Test Test A | Testing
I got here searching for this error:
No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator
Nothing to do with Retrofit but if you are using Jackson this error got solved by adding a default constructor to the class throwing the error. More here: https://www.baeldung.com/jackson-exception
In drawable I use this xml code to define the border and background:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="4dp" android:color="#D8FDFB" />
<padding android:left="7dp" android:top="7dp"
android:right="7dp" android:bottom="7dp" />
<corners android:radius="4dp" />
<solid android:color="#f0600000"/>
</shape>
You can do this with AngularStrap which
is a set of native directives that enables seamless integration of Bootstrap 3.0+ into your AngularJS 1.2+ app."
You can inject the entire library like this:
var app = angular.module('MyApp', ['mgcrea.ngStrap']);
Or only pull in the tooltip feature like this:
var app = angular.module('MyApp', ['mgcrea.ngStrap.tooltip']);
var app = angular.module('MyApp', ['mgcrea.ngStrap']);
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.2/angular-strap.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.2/angular-strap.tpl.min.js"></script>_x000D_
_x000D_
<div ng-app="MyApp" class="container" >_x000D_
_x000D_
<button type="button" _x000D_
class="btn btn-default" _x000D_
data-trigger="hover" _x000D_
data-placement="right"_x000D_
data-title="Tooltip on right"_x000D_
bs-tooltip>_x000D_
MyButton_x000D_
</button>_x000D_
_x000D_
</div>
_x000D_
<?php
$start = strtotime("12:00");
$end = // Run query to get datetime value from db
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>
I tried all of the above, nothing worked for me. Then I changed tomcat port numbers both HTTP/1.1 and Tomcat admin port and it got solved.
I see other solutions above worked for the people but it is worth to try this one if any of the above doesn't work.
Thanks everyone!
A more-advanced example:
? unlimited arguments.
? exist on file system (either
file
ordirectory
?) or a genericstring
.? specify if is a file
? specify is a directory
? no extensions, would work in legacy scripts!
? minimal code ?
@echo off :loop ::-------------------------- has argument ? if ["%~1"]==[""] ( echo done. goto end ) ::-------------------------- argument exist ? if not exist %~s1 ( echo not exist ) else ( echo exist if exist %~s1\NUL ( echo is a directory ) else ( echo is a file ) ) ::-------------------------- shift goto loop :end pause
? other stuff..?
¦ in %~1
- the ~
removes any wrapping "
or '
.
¦ in %~s1
- the s
makes the path be DOS 8.3 naming
, which is a nice trick to avoid spaces in file-name while checking stuff (and this way no need to wrap the resource with more "
s.
¦ the ["%~1"]==[""]
"can not be sure" if the argument is a file/directory or just a generic string yet, so instead the expression uses brackets and the original unmodified %1
(just without the "
wrapping, if any..)
if there were no arguments of if we've used shift
and the arg-list pointer has passed the last one, the expression will be evaluated to [""]==[""]
.
¦ this is as much specific you can be without using more tricks (it would work even in windows-95's batch-scripts...)
save it as identifier.cmd
it can identify an unlimited arguments (normally you are limited to %1
-%9
), just remember to wrap the arguments with inverted-commas, or use 8.3 naming, or drag&drop them over (it automatically does either of above).
this allows you to run the following commands:
?identifier.cmd c:\windows
and to get
exist is a directory done
?identifier.cmd "c:\Program Files (x86)\Microsoft Office\OFFICE11\WINWORD.EXE"
and to get
exist is a file done
? and multiple arguments (of course this is the whole-deal..)
identifier.cmd c:\windows\system32 c:\hiberfil.sys "c:\pagefile.sys" hello-world
and to get
exist is a directory exist is a file exist is a file not exist done.
naturally it can be a lot more complex, but nice examples should always be simple and minimal. :)
published here:CMD Ninja - Unlimited Arguments Processing, Identifying If Exist In File-System, Identifying If File Or Directory
and here is a working example that takes any amount of APK files (Android apps) and installs them on your device via debug-console (ADB.exe): Make The Previous Post A Mass APK Installer That Does Not Uses ADB Install-Multi Syntax
You should add spaces between test condition:
if [ $# -ne 1 ];
then echo "illegal number of parameters"
fi
I hope this helps.
This line seems to sum up the crux of your problem:
The issue with this is that now you can't call any new methods (only overrides) on the implementing class, as your object reference variable has the interface type.
You are pretty stuck in your current implementation, as not only do you have to attempt a cast, you also need the definition of the method(s) that you want to call on this subclass. I see two options:
1. As stated elsewhere, you cannot use the String representation of the Class name to cast your reflected instance to a known type. You can, however, use a String
equals()
test to determine whether your class is of the type that you want, and then perform a hard-coded cast:
try {
String className = "com.path.to.ImplementationType";// really passed in from config
Class c = Class.forName(className);
InterfaceType interfaceType = (InterfaceType)c.newInstance();
if (className.equals("com.path.to.ImplementationType") {
((ImplementationType)interfaceType).doSomethingOnlyICanDo();
}
} catch (Exception e) {
e.printStackTrace();
}
This looks pretty ugly, and it ruins the nice config-driven process that you have. I dont suggest you do this, it is just an example.
2. Another option you have is to extend your reflection from just Class
/Object
creation to include Method
reflection. If you can create the Class
from a String passed in from a config file, you can also pass in a method name from that config file and, via reflection, get an instance of the Method
itself from your Class
object. You can then call invoke
(http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object, java.lang.Object...)) on the Method
, passing in the instance of your class that you created. I think this will help you get what you are after.
Here is some code to serve as an example. Note that I have taken the liberty of hard coding the params for the methods. You could specify them in a config as well, and would need to reflect on their class names to define their Class
obejcts and instances.
public class Foo {
public void printAMessage() {
System.out.println(toString()+":a message");
}
public void printAnotherMessage(String theString) {
System.out.println(toString()+":another message:" + theString);
}
public static void main(String[] args) {
Class c = null;
try {
c = Class.forName("Foo");
Method method1 = c.getDeclaredMethod("printAMessage", new Class[]{});
Method method2 = c.getDeclaredMethod("printAnotherMessage", new Class[]{String.class});
Object o = c.newInstance();
System.out.println("this is my instance:" + o.toString());
method1.invoke(o);
method2.invoke(o, "this is my message, from a config file, of course");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException nsme){
nsme.printStackTrace();
} catch (IllegalAccessException iae) {
iae.printStackTrace();
} catch (InstantiationException ie) {
ie.printStackTrace();
} catch (InvocationTargetException ite) {
ite.printStackTrace();
}
}
}
and my output:
this is my instance:Foo@e0cf70
Foo@e0cf70:a message
Foo@e0cf70:another message:this is my message, from a config file, of course
This example selects a new Range
of Cells
defined by the current cell to a cell 5 to the right.
Note that .Offset
takes arguments of Offset(row, columns)
and can be quite useful.
Sub testForStackOverflow()
Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub
Go into your project.
install Gradle.
https://docs.gradle.org/current/userguide/installation.html
On a mac: brew install gradle
Then gradle build --stacktrace
Maybe something like this...
try
{
// ...
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
var response = ex.Response as HttpWebResponse;
if (response != null)
{
Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
}
else
{
// no http status code available
}
}
else
{
// no http status code available
}
}
Please run below code may it helps you :)
var str = "this,is,an,example";_x000D_
var strArr = str.split(',');_x000D_
var data = "";_x000D_
for(var i=0; i<strArr.length; i++){_x000D_
data += "Index : "+i+" value : "+strArr[i]+"<br/>";_x000D_
}_x000D_
document.getElementById('print').innerHTML = data;
_x000D_
<div id="print">_x000D_
</div>
_x000D_
Select cell B2 and click "Freeze Panes" this will freeze Row 1 and Column A.
For future reference, selecting Freeze Panes in Excel will freeze the rows above your selected cell and the columns to the left of your selected cell. For example, to freeze rows 1 and 2 and column A, you could select cell B3 and click Freeze Panes. You could also freeze columns A and B and row 1, by selecting cell C2 and clicking "Freeze Panes".
Visual Aid on Freeze Panes in Excel 2010 - http://www.dummies.com/how-to/content/how-to-freeze-panes-in-an-excel-2010-worksheet.html
Microsoft Reference Guide (More Complicated, but resourceful none the less) - http://office.microsoft.com/en-us/excel-help/freeze-or-lock-rows-and-columns-HP010342542.aspx
You can use boost::optional
(or std::optional
for newer versions), which was developed in particular for decision of your problem:
boost::optional<int> y[50];
....
geoGraph.y[x] = nums[x];
....
const size_t size_y = sizeof(y)/sizeof(y[0]); //!!!! correct size of y!!!!
for(int i=0; i<size_y;i++){
if(y[i]) { //check for null
p[i].SetPoint(Recto.Height()-x,*y[i]);
....
}
}
P.S. Do not use C-type array -> use std::array or std::vector:
std::array<int, 50> y; //not int y[50] !!!
We Use:
@ContextConfiguration(locations="file:WebContent/WEB-INF/spitterMVC-servlet.xml")
the project is a eclipse dynamic web project, then the path is:
{project name}/WebContent/WEB-INF/spitterMVC-servlet.xml
A double bitwise not operator can be used to truncate floats. The other operations you mentioned are available through Math.floor
, Math.ceil
, and Math.round
.
> ~~2.5
2
> ~~(-1.4)
-1
ORACLE/PLSQL:
NVL FUNCTION
SELECT NVL(SUM(Price), 0) AS TotalPrice
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)
This SQL statement would return 0
if the SUM(Price)
returned a null value. Otherwise, it would return the SUM(Price)
value.
You can close a figure by calling matplotlib.pyplot.close
, for example:
from numpy import *
import matplotlib.pyplot as plt
from scipy import *
t = linspace(0, 0.1,1000)
w = 60*2*pi
fig = plt.figure()
plt.plot(t,cos(w*t))
plt.plot(t,cos(w*t-2*pi/3))
plt.plot(t,cos(w*t-4*pi/3))
plt.show()
plt.close(fig)
You can also close all open figures by calling matplotlib.pyplot.close("all")
You have this option also:
type Configuration struct {
Val string
Proxy
}
type Proxy struct {
Address string
Port string
}
func main() {
c := &Configuration{"test", Proxy{"addr", "port"}}
fmt.Println(c)
}
I developed this to compare if two hashes are equal
def hash_equal?(hash1, hash2)
array1 = hash1.to_a
array2 = hash2.to_a
(array1 - array2 | array2 - array1) == []
end
The usage:
> hash_equal?({a: 4}, {a: 4})
=> true
> hash_equal?({a: 4}, {b: 4})
=> false
> hash_equal?({a: {b: 3}}, {a: {b: 3}})
=> true
> hash_equal?({a: {b: 3}}, {a: {b: 4}})
=> false
> hash_equal?({a: {b: {c: {d: {e: {f: {g: {h: 1}}}}}}}}, {a: {b: {c: {d: {e: {f: {g: {h: 1}}}}}}}})
=> true
> hash_equal?({a: {b: {c: {d: {e: {f: {g: {marino: 1}}}}}}}}, {a: {b: {c: {d: {e: {f: {g: {h: 2}}}}}}}})
=> false
Rotating Counter Clockwise ( standard column to row pivot ) As List and Dict
rows = [
['A', 'B', 'C', 'D'],
[1,2,3,4],
[1,2,3],
[1,2],
[1],
]
pivot = []
for row in rows:
for column, cell in enumerate(row):
if len(pivot) == column: pivot.append([])
pivot[column].append(cell)
print(rows)
print(pivot)
print(dict([(row[0], row[1:]) for row in pivot]))
Produces:
[['A', 'B', 'C', 'D'], [1, 2, 3, 4], [1, 2, 3], [1, 2], [1]]
[['A', 1, 1, 1, 1], ['B', 2, 2, 2], ['C', 3, 3], ['D', 4]]
{'A': [1, 1, 1, 1], 'B': [2, 2, 2], 'C': [3, 3], 'D': [4]}
Depending on what you are using this for, you may need to specify the data type (see 'dtype').
For example, to create a 2D array of 8-bit values (suitable for use as a monochrome image):
myarray = numpy.empty(shape=(H,W),dtype='u1')
For an RGB image, include the number of color channels in the shape: shape=(H,W,3)
You may also want to consider zero-initializing with numpy.zeros
instead of using numpy.empty
. See the note here.
With minimal editing to your code (Not sure if they've taught classes or not in your course), change:
def close_window(root):
root.destroy()
to
def close_window():
window.destroy()
and it should work.
Explanation:
Your version of close_window
is defined to expect a single argument, namely root
. Subsequently, any calls to your version of close_window
need to have that argument, or Python will give you a run-time error.
When you created a Button
, you told the button to run close_window
when it is clicked. However, the source code for Button widget is something like:
# class constructor
def __init__(self, some_args, command, more_args):
#...
self.command = command
#...
# this method is called when the user clicks the button
def clicked(self):
#...
self.command() # Button calls your function with no arguments.
#...
As my code states, the Button
class will call your function with no arguments. However your function is expecting an argument. Thus you had an error. So, if we take out that argument, so that the function call will execute inside the Button class, we're left with:
def close_window():
root.destroy()
That's not right, though, either, because root
is never assigned a value. It would be like typing in print(x)
when you haven't defined x
, yet.
Looking at your code, I figured you wanted to call destroy
on window
, so I changed root
to window
.
I've been searching through all the examples and answers of how to pass any array to sql server without the hassle of creating new Table type,till i found this linK, below is how I applied it to my project:
--The following code is going to get an Array as Parameter and insert the values of that --array into another table
Create Procedure Proc1
@UserId int, //just an Id param
@s nvarchar(max) //this is the array your going to pass from C# code to your Sproc
AS
declare @xml xml
set @xml = N'<root><r>' + replace(@s,',','</r><r>') + '</r></root>'
Insert into UserRole (UserID,RoleID)
select
@UserId [UserId], t.value('.','varchar(max)') as [RoleId]
from @xml.nodes('//root/r') as a(t)
END
Hope you enjoy it
try these two line from terminal
sudo killall mysqld
sudo /Applications/XAMPP/xamppfiles/bin/mysql.server start
Ben is completely correct in his answer - so keep what he says in mind. What I'm about to tell you isn't a full explanation, but it's a very easy way to remember how e.target
, e.currentTarget
work in relation to mouse events and the display list:
e.target
= The thing under the mouse (as ben says... the thing that triggers the event).
e.currentTarget
= The thing before the dot... (see below)
So if you have 10 buttons inside a clip with an instance name of "btns" and you do:
btns.addEventListener(MouseEvent.MOUSE_OVER, onOver);
// btns = the thing before the dot of an addEventListener call
function onOver(e:MouseEvent):void{
trace(e.target.name, e.currentTarget.name);
}
e.target
will be one of the 10 buttons and e.currentTarget
will always be the "btns" clip.
It's worth noting that if you changed the MouseEvent to a ROLL_OVER or set the property btns.mouseChildren
to false, e.target
and e.currentTarget
will both always be "btns".
You can use :
sheet.addMergedRegion(new CellRangeAddress(startRowIndx, endRowIndx, startColIndx,endColIndx));
Make sure the CellRangeAddress does not coincide with other merged regions as that will throw an exception.
For what you were trying to do this should work:
sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 0, 3));
local constants:
const val NAME = "name"
Global constants:
object MyConstants{
val NAME = "name"
val ID = "_id"
var EMAIL = "email"
}
access MyConstants.NAME
You could use a dictionary approach like this one. Basically you assign the value you want to be distinct as a key in the "dictionary" (here we use an array as an object to avoid dictionary-mode). If the key did not exist then you add that value as distinct.
Here is a working demo:
var array = [{"name":"Joe", "age":17}, {"name":"Bob", "age":17}, {"name":"Carl", "age": 35}];_x000D_
var unique = [];_x000D_
var distinct = [];_x000D_
for( let i = 0; i < array.length; i++ ){_x000D_
if( !unique[array[i].age]){_x000D_
distinct.push(array[i].age);_x000D_
unique[array[i].age] = 1;_x000D_
}_x000D_
}_x000D_
var d = document.getElementById("d");_x000D_
d.innerHTML = "" + distinct;
_x000D_
<div id="d"></div>
_x000D_
This will be O(n) where n is the number of objects in array and m is the number of unique values. There is no faster way than O(n) because you must inspect each value at least once.
The previous version of this used an object, and for in. These were minor in nature, and have since been minorly updated above. However, the reason for a seeming advance in performance between the two versions in the original jsperf was due to the data sample size being so small. Thus, the main comparison in the previous version was looking at the difference between the internal map and filter use versus the dictionary mode lookups.
I have updated the code above, as noted, however, I have also updated the jsperf to look through 1000 objects instead of 3. 3 overlooked many of the performance pitfalls involved (obsolete jsperf).
Performance
https://jsperf.com/filter-vs-dictionary-more-data When I ran this dictionary was 96% faster.
Those two parameters (or variants of) are sent, by convention, with all events.
sender
: The object which has raised the evente
an instance of EventArgs
including, in many cases, an object which inherits from EventArgs
. Contains additional information about the event, and sometimes provides ability for code handling the event to alter the event somehow.In the case of the events you mentioned, neither parameter is particularly useful. The is only ever one page raising the events, and the EventArgs
are Empty
as there is no further information about the event.
Looking at the 2 parameters separately, here are some examples where they are useful.
sender
Say you have multiple buttons on a form. These buttons could contain a Tag
describing what clicking them should do. You could handle all the Click
events with the same handler, and depending on the sender
do something different
private void HandleButtonClick(object sender, EventArgs e)
{
Button btn = (Button)sender;
if(btn.Tag == "Hello")
MessageBox.Show("Hello")
else if(btn.Tag == "Goodbye")
Application.Exit();
// etc.
}
Disclaimer : That's a contrived example; don't do that!
e
Some events are cancelable. They send CancelEventArgs
instead of EventArgs
. This object adds a simple boolean property Cancel
on the event args. Code handling this event can cancel the event:
private void HandleCancellableEvent(object sender, CancelEventArgs e)
{
if(/* some condition*/)
{
// Cancel this event
e.Cancel = true;
}
}
Do not use ABSOLUTE PATH to refer to the name of the image for example: C:/xamp/www/Archivos/images/templatemo_image_02_opt_20160401-1244.jpg
. You must use the reference to its location within webserver. For example using ../../Archivos/images/templatemo_image_02_opt_20160401-1244.jpg
depending on where your process is running.
In Django, it acts as a configuration class and keeps the configuration data in one place!!
The loading of a .json
file from harddisk is an asynchronous operation and thus it needs to specify a callback function to execute after the file is loaded.
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
readTextFile("/Users/Documents/workspace/test.json", function(text){
var data = JSON.parse(text);
console.log(data);
});
This function works also for loading a .html
or .txt
files, by overriding the mime type parameter to "text/html"
, "text/plain"
etc.
Why not just use key name on dictionary, C# has this:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("UserID", "test");
string userIDFromDictionaryByKey = dict["UserID"];
If you look at the tip suggestion:
but as for this method, I don't understand the purpose of Integer.MAX_VALUE and Integer.MIN_VALUE.
By starting out with smallest
set to Integer.MAX_VALUE
and largest
set to Integer.MIN_VALUE
, they don't have to worry later about the special case where smallest
and largest
don't have a value yet. If the data I'm looking through has a 10
as the first value, then numbers[i]<smallest
will be true (because 10
is <
Integer.MAX_VALUE
) and we'll update smallest
to be 10
. Similarly, numbers[i]>largest
will be true
because 10
is >
Integer.MIN_VALUE
and we'll update largest
. And so on.
Of course, when doing this, you must ensure that you have at least one value in the data you're looking at. Otherwise, you end up with apocryphal numbers in smallest
and largest
.
Note the point Onome Sotu makes in the comments:
...if the first item in the array is larger than the rest, then the largest item will always be Integer.MIN_VALUE because of the else-if statement.
Which is true; here's a simpler example demonstrating the problem (live copy):
public class Example
{
public static void main(String[] args) throws Exception {
int[] values = {5, 1, 2};
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
for (int value : values) {
if (value < smallest) {
smallest = value;
} else if (value > largest) {
largest = value;
}
}
System.out.println(smallest + ", " + largest); // 1, 2 -- WRONG
}
}
To fix it, either:
Don't use else
, or
Start with smallest
and largest
equal to the first element, and then loop the remaining elements, keeping the else if
.
Here's an example of that second one (live copy):
public class Example
{
public static void main(String[] args) throws Exception {
int[] values = {5, 1, 2};
int smallest = values[0];
int largest = values[0];
for (int n = 1; n < values.length; ++n) {
int value = values[n];
if (value < smallest) {
smallest = value;
} else if (value > largest) {
largest = value;
}
}
System.out.println(smallest + ", " + largest); // 1, 5
}
}
Require all files from routes
folder and apply as middleware. No external modules needed.
// require
const path = require("path");
const { readdirSync } = require("fs");
// apply as middleware
readdirSync("./routes").map((r) => app.use("/api", require("./routes/" + r)));
Using a decorator for measuring execution time for functions can be handy. There is an example at http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods.
Below I've shamelessly pasted the code from the site mentioned above so that the example exists at SO in case the site is wiped off the net.
import time
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '%r (%r, %r) %2.2f sec' % \
(method.__name__, args, kw, te-ts)
return result
return timed
class Foo(object):
@timeit
def foo(self, a=2, b=3):
time.sleep(0.2)
@timeit
def f1():
time.sleep(1)
print 'f1'
@timeit
def f2(a):
time.sleep(2)
print 'f2',a
@timeit
def f3(a, *args, **kw):
time.sleep(0.3)
print 'f3', args, kw
f1()
f2(42)
f3(42, 43, foo=2)
Foo().foo()
// John
POSIX 7 example
It is also worth checking the example from the standard: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
aflag=
bflag=
while getopts ab: name
do
case $name in
a) aflag=1;;
b) bflag=1
bval="$OPTARG";;
?) printf "Usage: %s: [-a] [-b value] args\n" $0
exit 2;;
esac
done
if [ ! -z "$aflag" ]; then
printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"
And then we can try it out:
$ sh a.sh
Remaining arguments are:
$ sh a.sh -a
Option -a specified
Remaining arguments are:
$ sh a.sh -b
No arg for -b option
Usage: a.sh: [-a] [-b value] args
$ sh a.sh -b myval
Option -b "myval" specified
Remaining arguments are:
$ sh a.sh -a -b myval
Option -a specified
Option -b "myval" specified
Remaining arguments are:
$ sh a.sh remain
Remaining arguments are: remain
$ sh a.sh -- -a remain
Remaining arguments are: -a remain
Tested in Ubuntu 17.10, sh
is dash 0.5.8.
All is not work for me but Once I delete the ".metadata" & ".recommenders" of workspace and also delete the "bin" and "setting" folder and then after I re-import the same project then It worked for me.
Try this on for size:
The actual dateTime object your looking to format is in the dt.Value property, and not on the dt2 object itself.
DateTime? dt2 = DateTime.Now;
Console.WriteLine(dt2.HasValue ? dt2.Value.ToString("yyyy-MM-dd hh:mm:ss") : "[N/A]");
I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header "Gender " and I had it listed as:
[['Gender']]
If it's easy enough for you to access your csv, you can use the excel formula trim()
to clip any spaces of the cells.
or remove it like this
df.columns = df.columns.to_series().apply(lambda x: x.strip())
There are a few ways to accomplish that:
# Rename the local branch to the new name
git branch -m <old_name> <new_name>
# Delete the old branch on remote - where <remote> is, for example, origin
git push <remote> --delete <old_name>
# Or shorter way to delete remote branch [:]
git push <remote> :<old_name>
# Prevent git from using the old name when pushing in the next step.
# Otherwise, git will use the old upstream name instead of <new_name>.
git branch --unset-upstream <old_name>
# Push the new branch to remote
git push <remote> <new_name>
# Reset the upstream branch for the new_name local branch
git push <remote> -u <new_name>
Credit: ptim
# In this option, we will push the branch to the remote with the new name
# While keeping the local name as is
git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>
When you use the git branch -m
(move), Git is also updating your tracking branch with the new name.
git remote rename legacy legacy
git remote rename
is trying to update your remote section in your configuration file. It will rename the remote with the given name to the new name, but in your case, it did not find any, so the renaming failed.
But it will not do what you think; it will rename your local configuration remote name and not the remote branch.
Note Git servers might allow you to rename Git branches using the web interface or external programs (like Sourcetree, etc.), but you have to keep in mind that in Git all the work is done locally, so it's recommended to use the above commands to the work.
Leaving my specific solution of this for prosperity, as it's a tricky version of this problem:
Type 'System.Linq.Enumerable+WhereSelectArrayIterator[T...] was not marked as serializable
Due to a class with an attribute IEnumerable<int>
eg:
[Serializable]
class MySessionData{
public int ID;
public IEnumerable<int> RelatedIDs; //This can be an issue
}
Originally the problem instance of MySessionData
was set from a non-serializable list:
MySessionData instance = new MySessionData(){
ID = 123,
RelatedIDs = nonSerizableList.Select<int>(item => item.ID)
};
The cause here is the concrete class that the Select<int>(...)
returns, has type data that's not serializable, and you need to copy the id's to a fresh List<int>
to resolve it.
RelatedIDs = nonSerizableList.Select<int>(item => item.ID).ToList();
You can find the correct dependencies here apply changes to app.gradle and project.gradle and tell me about this, greetings!
Your apply plugin: 'com.google.gms.google-services' in app.gradle looks like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.2"
defaultConfig {
applicationId "com.example.personal.numbermania"
minSdkVersion 10
targetSdkVersion 24
versionCode 1
versionName "1.0"
multiDexEnabled true
}
dexOptions {
incremental true
javaMaxHeapSize "4g" //Here stablished how many cores you want to use your android studi 4g = 4 cores
}
buildTypes {
debug
{
debuggable true
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.android.support:design:24.2.1'
compile 'com.google.firebase:firebase-ads:9.6.1'
compile 'com.google.firebase:firebase-core:9.6.1'
compile 'com.google.android.gms:play-services:9.6.1'
}
apply plugin: 'com.google.gms.google-services'
Add classpath to the project's gradle:
classpath 'com.google.gms:google-services:3.0.0'
Google play services library on SDK Manager:
If you are looking for a specific content in all files from a directory structure, you may use find
since it is more clear what you are doing:
find -type f -exec grep -l "texthere" {} +
Note that -l
(downcase of L) shows the name of the file that contains the text. Remove it if you instead want to print the match itself. Or use -H
to get the file together with the match. All together, other alternatives are:
find -type f -exec grep -Hn "texthere" {} +
Where -n
prints the line number.
I made a small function to extract the video id out of a Youtube url which can be seen below.
var videoId = function(url) {_x000D_
var match = url.match(/v=([0-9a-z_-]{1,20})/i);_x000D_
return (match ? match['1'] : false);_x000D_
};_x000D_
_x000D_
console.log(videoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ'));_x000D_
console.log(videoId('https://www.youtube.com/watch?t=17s&v=dQw4w9WgXcQ'));_x000D_
console.log(videoId('https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=17s'));
_x000D_
This function will extract the video id even if there are multiple parameters in the url.
The function strstr() in PHP 5.3 should do this job.. The third parameter however should be set to true..
But if you're not using 5.3, then the function below should work accurately:
function strbstr( $str, $char, $start=0 ){
if ( isset($str[ $start ]) && $str[$start]!=$char ){
return $str[$start].strbstr( $str, $char, $start+1 );
}
}
I haven't tested it though, but this should work just fine.. And it's pretty fast as well
git add myfile.h
git commit -m "your commit message"
git push -u origin master
if you don't remember all the files you need to update, use
git status
1024 is appropriate for a wide variety of circumstances, although in practice you may see better performance with a larger or smaller buffer size.
This would depend on a number of factors including file system block size and CPU hardware.
It is also common to choose a power of 2 for the buffer size, since most underlying hardware is structured with fle block and cache sizes that are a power of 2. The Buffered classes allow you to specify the buffer size in the constructor. If none is provided, they use a default value, which is a power of 2 in most JVMs.
Regardless of which buffer size you choose, the biggest performance increase you will see is moving from nonbuffered to buffered file access. Adjusting the buffer size may improve performance slightly, but unless you are using an extremely small or extremely large buffer size, it is unlikely to have a signifcant impact.
string text = "Retrieves a substring from this instance. The substring starts at a specified character position. Some other text";
string result = text.Substring(text.IndexOf('.') + 1,text.LastIndexOf('.')-text.IndexOf('.'))
This will cut the part of string which lays between the special characters.
Just wanted to show my codes:
function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Specify the maxrecursion option at the end of the query:
...
from EmployeeTree
option (maxrecursion 0)
That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.
Try the following:
var $tabs = $('#tabs-menu').tabs();
var selected = $tabs.tabs('option', 'selected');
var divAssocAtual = $('#tabs-menu ul li').tabs()[selected].hash;
If you want to select multiple cells and copy their values to the clipboard without all those annoying quotes the following code may be useful. This is an enhancement of the code given above from user3616725.
Sub CopyCells()
'Attach Microsoft Forms 2.0 Library: tools\references\Browse\FM20.DLL
'Then set a keyboard shortcut to the CopyCells Macro (eg Crtl T)
Dim objData As New DataObject
Dim cell As Object
Dim concat As String
Dim cellValue As String
CR = ""
For Each cell In Selection
If IsNumeric(cell.Value) Then
cellValue = LTrim(Str(cell.Value))
Else
cellValue = cell.Value
End If
concat = concat + CR + cellValue
CR = Chr(13)
Next
objData.SetText (concat)
objData.PutInClipboard
End Sub
This simple snippet of code does what you want
GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
KeyboardUtil.hideKeyboard(getActivity());
return true;
}
});
mScrollView.setOnTouchListener((v, e) -> gestureDetector.onTouchEvent(e));
Try invoking your command with Invoke-Expression
:
Invoke-Expression $cmd1
Here is a working example on my machine:
$cmd = "& 'C:\Program Files\7-zip\7z.exe' a -tzip c:\temp\test.zip c:\temp\test.txt"
Invoke-Expression $cmd
iex
is an alias for Invoke-Expression
so you could do:
iex $cmd1
For a full list :
Visit https://ss64.com/ps/ for more Powershell
stuff.
Good Luck...
No, you can not do Insert/Update/Delete.
Functions only work with select
statements. And it has only READ-ONLY Database Access.
In addition:
The r
makes the string a raw string, which doesn't process escape characters (however, since there are none in the string, it is actually not needed here).
Also, re.match
matches from the beginning of the string. In other words, it looks for an exact match between the string and the pattern. To match stuff that could be anywhere in the string, use re.search
. See a demonstration below:
>>> import re
>>> line = 'This,is,a,sample,string'
>>> re.match("sample", line)
>>> re.search("sample", line)
<_sre.SRE_Match object at 0x021D32C0>
>>>
Maybe you have to try getActivity().getSupportActionBar().setTitle()
if you are using support_v7.
Even better, you do not need to create separate android xml layout for list cell view. You can just use "android.R.layout.simple_list_item_1" if the list only contains textview.
private class ExampleAdapter extends ArrayAdapter<String>{
public ExampleAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView tv = (TextView) view.findViewById(android.R.id.text1);
tv.setTextColor(0);
return view;
}
Don't forget that unlike Windows, all Unix based system need to have the source before destination unlike Windows
On Windows its:
mov $source , %destination
but on the Mac its the other way around.
Why are you trying to roll your own solution. Spring-boot already supports that.
If you don't already have one, add an application.properties
file to src\main\resources
. In that properties file, add 2 properties:
server.contextPath=/mainstay
server.port=12378
UPDATE (Spring Boot 2.0)
As of Spring Boot 2.0 (due to the support of both Spring MVC and Spring WebFlux) the contextPath
has been changed to the following:
server.servlet.contextPath=/mainstay
You can then remove your configuration for the custom servlet container. If you need to do some post processing on the container you can add a EmbeddedServletContainerCustomizer
implementation to your configuration (for instance to add the error pages).
Basically the properties inside the application.properties
serve as a default you can always override them by using another application.properties
next to the artifact you deliver or by adding JVM parameters (-Dserver.port=6666
).
See also The Reference Guide especially the properties section.
The class ServerProperties
implements the EmbeddedServletContainerCustomizer
. The default for contextPath
is ""
. In your code sample you are setting the contextPath
directly on the TomcatEmbeddedServletContainerFactory
. Next the ServerProperties
instance will process this instance and reset it from your path to ""
. (This line does a null
check but as the default is ""
it always fail and set the context to ""
and thus overriding yours).
According to @Data description you can use:
All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.
In your terminal/console (only Linux, in windows you need Putty)
ssh user@ip
php -i | grep "Loaded Configuration File"
And it will show you something like this Loaded Configuration File => /etc/php.ini
.
ALTERNATIVE METHOD
You can make a php file on your website, which run: <?php phpinfo(); ?>
, and you can see the php.ini location on the line with: "Loaded Configuration File".
Update This command gives the path right away
cli_php_ini=php -i | grep /.+/php.ini -oE #ref. https://stackoverflow.com/a/15763333/248616
php_ini="${cli_php_ini/cli/apache2}" #replace cli by apache2 ref. https://stackoverflow.com/a/13210909/248616
It takes some time to return results, easily many tens of seconds, but wmic works well and can be scripted:
wmic product where "Name like '%Word%'" get Name, Version, IdentifyingNumber
result:
IdentifyingNumber Name Version
{90140000-001B-0409-0000-0000000FF1CE} Microsoft Office Word MUI (English) 2010 14.0.6029.1000
The IdentifingNumber
is the ProductCode. I didn't see a property for UpgradeCode, but perhaps it might be buried under something else. See http://quux.wiki.zoho.com/WMIC-Snippets.html for many other examples, including uninstall:
wmic path win32_product where "name = 'HP Software Update'" call Uninstall
Swift is worry that your case statement is not covering all cases, to fix it you need to create a default case:
do {
let sandwich = try makeMeSandwich(kitchen)
print("i eat it \(sandwich)")
} catch SandwichError.NotMe {
print("Not me error")
} catch SandwichError.DoItYourself {
print("do it error")
} catch Default {
print("Another Error")
}
Chain both class selectors (without a space in between):
.foo.bar {
/* Styles for element(s) with foo AND bar classes */
}
If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar
in this case) instead, regardless of what other classes you list.
To illustrate how other browsers and IE6 interpret this, consider this CSS:
* {
color: black;
}
.foo.bar {
color: red;
}
Output on supported browsers is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Not selected, black text [3] -->
Output on IE6 is:
<div class="foo">Hello Foo</div> <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div> <!-- Selected, red text [2] -->
Footnotes:
foo
.foo
and bar
.bar
.
bar
.bar
, regardless of any other classes listed.just do this:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
a * b
The results of the test and source code are below (you can set the number of iterations in the app). The time is in milliseconds, and each entry is an average result of running the test 5-10 times. I found that generally it is accurate to 2-3 significant digits and after that it would vary with each run. That gives a margin of error of less than 1%. The test was running on an iPhone 3G as that's the target platform I was interested in.
numberOfItems NSArray (ms) C Array (ms) Ratio
100 0.39 0.0025 156
191 0.61 0.0028 218
3,256 12.5 0.026 481
4,789 16 0.037 432
6,794 21 0.050 420
10,919 36 0.081 444
19,731 64 0.15 427
22,030 75 0.162 463
32,758 109 0.24 454
77,969 258 0.57 453
100,000 390 0.73 534
The classes provided by Cocoa for handling data sets (NSDictionary, NSArray, NSSet etc.) provide a very nice interface for managing information, without having to worry about the bureaucracy of memory management, reallocation etc. Of course this does come at a cost though. I think it's pretty obvious that say using an NSArray of NSNumbers is going to be slower than a C Array of floats for simple iterations, so I decided to do some tests, and the results were pretty shocking! I wasn't expecting it to be this bad. Note: these tests are conducted on an iPhone 3G as that's the target platform I was interested in.
In this test I do a very simple random access performance comparison between a C float* and NSArray of NSNumbers
I create a simple loop to sum up the contents of each array and time them using mach_absolute_time(). The NSMutableArray takes on average 400 times longer!! (not 400 percent, just 400 times longer! thats 40,000% longer!).
Header:
// Array_Speed_TestViewController.h
// Array Speed Test
// Created by Mehmet Akten on 05/02/2009.
// Copyright MSA Visuals Ltd. 2009. All rights reserved.
#import <UIKit/UIKit.h>
@interface Array_Speed_TestViewController : UIViewController {
int numberOfItems; // number of items in array
float *cArray; // normal c array
NSMutableArray *nsArray; // ns array
double machTimerMillisMult; // multiplier to convert mach_absolute_time() to milliseconds
IBOutlet UISlider *sliderCount;
IBOutlet UILabel *labelCount;
IBOutlet UILabel *labelResults;
}
-(IBAction) doNSArray:(id)sender;
-(IBAction) doCArray:(id)sender;
-(IBAction) sliderChanged:(id)sender;
@end
Implementation:
// Array_Speed_TestViewController.m
// Array Speed Test
// Created by Mehmet Akten on 05/02/2009.
// Copyright MSA Visuals Ltd. 2009. All rights reserved.
#import "Array_Speed_TestViewController.h"
#include <mach/mach.h>
#include <mach/mach_time.h>
@implementation Array_Speed_TestViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSLog(@"viewDidLoad");
[super viewDidLoad];
cArray = NULL;
nsArray = NULL;
// read initial slider value setup accordingly
[self sliderChanged:sliderCount];
// get mach timer unit size and calculater millisecond factor
mach_timebase_info_data_t info;
mach_timebase_info(&info);
machTimerMillisMult = (double)info.numer / ((double)info.denom * 1000000.0);
NSLog(@"machTimerMillisMult = %f", machTimerMillisMult);
}
// pass in results of mach_absolute_time()
// this converts to milliseconds and outputs to the label
-(void)displayResult:(uint64_t)duration {
double millis = duration * machTimerMillisMult;
NSLog(@"displayResult: %f milliseconds", millis);
NSString *str = [[NSString alloc] initWithFormat:@"%f milliseconds", millis];
[labelResults setText:str];
[str release];
}
// process using NSArray
-(IBAction) doNSArray:(id)sender {
NSLog(@"doNSArray: %@", sender);
uint64_t startTime = mach_absolute_time();
float total = 0;
for(int i=0; i<numberOfItems; i++) {
total += [[nsArray objectAtIndex:i] floatValue];
}
[self displayResult:mach_absolute_time() - startTime];
}
// process using C Array
-(IBAction) doCArray:(id)sender {
NSLog(@"doCArray: %@", sender);
uint64_t start = mach_absolute_time();
float total = 0;
for(int i=0; i<numberOfItems; i++) {
total += cArray[i];
}
[self displayResult:mach_absolute_time() - start];
}
// allocate NSArray and C Array
-(void) allocateArrays {
NSLog(@"allocateArrays");
// allocate c array
if(cArray) delete cArray;
cArray = new float[numberOfItems];
// allocate NSArray
[nsArray release];
nsArray = [[NSMutableArray alloc] initWithCapacity:numberOfItems];
// fill with random values
for(int i=0; i<numberOfItems; i++) {
// add number to c array
cArray[i] = random() * 1.0f/(RAND_MAX+1);
// add number to NSArray
NSNumber *number = [[NSNumber alloc] initWithFloat:cArray[i]];
[nsArray addObject:number];
[number release];
}
}
// callback for when slider is changed
-(IBAction) sliderChanged:(id)sender {
numberOfItems = sliderCount.value;
NSLog(@"sliderChanged: %@, %i", sender, numberOfItems);
NSString *str = [[NSString alloc] initWithFormat:@"%i items", numberOfItems];
[labelCount setText:str];
[str release];
[self allocateArrays];
}
//cleanup
- (void)dealloc {
[nsArray release];
if(cArray) delete cArray;
[super dealloc];
}
@end
From : memo.tv
////////////////////
Available since the introduction of blocks, this allows to iterate an array with blocks. Its syntax isn't as nice as fast enumeration, but there is one very interesting feature: concurrent enumeration. If enumeration order is not important and the jobs can be done in parallel without locking, this can provide a considerable speedup on a multi-core system. More about that in the concurrent enumeration section.
[myArray enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
[self doSomethingWith:object];
}];
[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self doSomethingWith:object];
}];
/////////// NSFastEnumerator
The idea behind fast enumeration is to use fast C array access to optimize iteration. Not only is it supposed to be faster than traditional NSEnumerator, but Objective-C 2.0 also provides a very concise syntax.
id object;
for (object in myArray) {
[self doSomethingWith:object];
}
/////////////////
NSEnumerator
This is a form of external iteration: [myArray objectEnumerator] returns an object. This object has a method nextObject that we can call in a loop until it returns nil
NSEnumerator *enumerator = [myArray objectEnumerator];
id object;
while (object = [enumerator nextObject]) {
[self doSomethingWith:object];
}
/////////////////
objectAtIndex: enumeration
Using a for loop which increases an integer and querying the object using [myArray objectAtIndex:index] is the most basic form of enumeration.
NSUInteger count = [myArray count];
for (NSUInteger index = 0; index < count ; index++) {
[self doSomethingWith:[myArray objectAtIndex:index]];
}
////////////// From : darkdust.net
You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.
Set<String> abc = new HashSet<String>();
abc.add("A");
abc.add("B");
abc.add("C");
String separator = ", ";
int total = abc.size() * separator.length();
for (String s : abc) {
total += s.length();
}
StringBuilder sb = new StringBuilder(total);
for (String s : abc) {
sb.append(separator).append(s);
}
String result = sb.substring(separator.length()); // remove leading separator
I will select Session, first of all session is more secure then cookies, cookies is client site data and session is server site data. Cookies is used to identify a user, because it is small pieces of code that is embedded my server with user computer browser. On the other hand Session help you to secure you identity because web server don’t know who you are because HTTP address changes the state 192.168.0.1 to 765487cf34ert8ded…..or something else numbers with the help of GET and POST methods. Session stores data of user in unique ID session that even user ID can’t match with each other. Session stores single user information in all pages of one application. Cookies expire is set with the help of setcookies() whereas session expire is not set it is expire when user turn off browsers.
When there is a need to restrict access to some functions, we'll use the static keyword while defining and declaring a function.
/* file ab.c */
static void function1(void)
{
puts("function1 called");
}
And store the following code in another file ab1.c
/* file ab1.c */
int main(void)
{
function1();
getchar();
return 0;
}
/* in this code, we'll get a "Undefined reference to function1".Because function 1 is declared static in file ab.c and can't be used in ab1.c */
I understand your dilemma, but Python is not PHP and coding style known as Easier to Ask for Forgiveness than for Permission (or EAFP in short) is a common coding style in Python.
See the source (from documentation):
EAFP - Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
So, basically, using try-catch statements here is not a last resort; it is a common practice.
PHP has associative and non-associative arrays, Python has lists, tuples and dictionaries. Lists are similar to non-associative PHP arrays, dictionaries are similar to associative PHP arrays.
If you want to check whether "key" exists in "array", you must first tell what type in Python it is, because they throw different errors when the "key" is not present:
>>> l = [1,2,3]
>>> l[4]
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
l[4]
IndexError: list index out of range
>>> d = {0: '1', 1: '2', 2: '3'}
>>> d[4]
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
d[4]
KeyError: 4
And if you use EAFP coding style, you should just catch these errors appropriately.
If you insist on using LBYL approach, these are solutions for you:
for lists just check the length and if possible_index < len(your_list)
, then your_list[possible_index]
exists, otherwise it doesn't:
>>> your_list = [0, 1, 2, 3]
>>> 1 < len(your_list) # index exist
True
>>> 4 < len(your_list) # index does not exist
False
for dictionaries you can use in
keyword and if possible_index in your_dict
, then your_dict[possible_index]
exists, otherwise it doesn't:
>>> your_dict = {0: 0, 1: 1, 2: 2, 3: 3}
>>> 1 in your_dict # index exists
True
>>> 4 in your_dict # index does not exist
False
Did it help?
Use this:
echo "${@:2}"
The following syntax:
echo "${*:2}"
would work as well, but is not recommended, because as @Gordon already explained, that using *
, it runs all of the arguments together as a single argument with spaces, while @
preserves the breaks between them (even if some of the arguments themselves contain spaces). It doesn't make the difference with echo
, but it matters for many other commands.
If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output()
command. Here is an example:
output = subprocess.check_output('ls')
To also redirect stderr you can use the following:
output = subprocess.check_output('ls', stderr=subprocess.STDOUT)
In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.
output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)
I got the same error after updating a referenced dll in a desktop executable project. The issue was as people here mentioned related an old reference and simple to fix but hasn’t been mentioned here, so I thought it might save other people’s time.
Anyway I updated dll A and got the error from another referenced dll let’s call it B here where dll A has a reference to dll B.
Updating dll B fixed the issue.
After a fair amount of work, I was able to get it to build on Ubuntu 12.04 x86 and Debian 7.4 x86_64. I wrote up a guide below. Can you please try following it to see if it resolves the issue?
If not please let me know where you get stuck.
Install Common Dependencies
sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev
Install NumArray 1.5.2
wget http://goo.gl/6gL0q3 -O numarray-1.5.2.tgz
tar xfvz numarray-1.5.2.tgz
cd numarray-1.5.2
sudo python setup.py install
Install Numeric 23.8
wget http://goo.gl/PxaHFW -O numeric-23.8.tgz
tar xfvz numeric-23.8.tgz
cd Numeric-23.8
sudo python setup.py install
Install HDF5 1.6.5
wget ftp://ftp.hdfgroup.org/HDF5/releases/hdf5-1.6/hdf5-1.6.5.tar.gz
tar xfvz hdf5-1.6.5.tar.gz
cd hdf5-1.6.5
./configure --prefix=/usr/local
sudo make
sudo make install
Install Nanoengineer
git clone https://github.com/kanzure/nanoengineer.git
cd nanoengineer
./bootstrap
./configure
make
sudo make install
Troubleshooting
On Debian Jessie, you will receive the error message that cant pants mentioned. There seems to be an issue in the automake scripts. x86_64-linux-gnu-gcc
is inserted in CFLAGS
and gcc
will interpret that as a name of one of the source files. As a workaround, let's create an empty file with that name. Empty so that it won't change the program and that very name so that compiler picks it up. From the cloned nanoengineer directory, run this command to make gcc happy (it is a hack yes, but it does work) ...
touch sim/src/x86_64-linux-gnu-gcc
If you receive an error message when attemping to compile HDF5 along the lines of: "error: call to ‘__open_missing_mode’ declared with attribute error: open with O_CREAT in second argument needs 3 arguments", then modify the file perform/zip_perf.c, line 548 to look like the following and then rerun make...
output = open(filename, O_RDWR | O_CREAT, S_IRUSR|S_IWUSR);
If you receive an error message about Numeric/arrayobject.h not being found when building Nanoengineer, try running
export CPPFLAGS=-I/usr/local/include/python2.7
./configure
make
sudo make install
If you receive an error message similar to "TRACE_PREFIX undeclared", modify the file sim/src/simhelp.c lines 38 to 41 to look like this and re-run make:
#ifdef DISTUTILS
static char tracePrefix[] = "";
#else
static char tracePrefix[] = "";
If you receive an error message when trying to launch NanoEngineer-1 that mentions something similar to "cannot import name GL_ARRAY_BUFFER_ARB", modify the lines in the following files
/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/setup_draw.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/graphics/drawing/GLPrimitiveBuffer.py
/usr/local/bin/NanoEngineer1_0.9.2.app/program/prototype/test_drawing.py
that look like this:
from OpenGL.GL import GL_ARRAY_BUFFER_ARB
from OpenGL.GL import GL_ELEMENT_ARRAY_BUFFER_ARB
to look like this:
from OpenGL.GL.ARB.vertex_buffer_object import GL_ARRAY_BUFFER_AR
from OpenGL.GL.ARB.vertex_buffer_object import GL_ELEMENT_ARRAY_BUFFER_ARB
I also found an additional troubleshooting text file that has been removed, but you can find it here
Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.
echo <<<MYTAG
<tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>
<tr><td> <input type="hidden" name="type" value="$var4" ></td></tr>
MYTAG;
I think it should be R.color.black
Also take a look at Converting android color string in runtime into int
If I understand the question correctly, it has to do with output buffering and the affect this might have on closing/ending tags. I am not sure that is an entirely valid question. The problem is that the output buffer does not mean all content is held in memory before sending it out to the client. It means some of the content is.
The programmer can purposely flush the buffer, or the output buffer so does the output buffer option in PHP really change how the closing tag affects coding? I would argue that it does not.
And maybe that is why most of the answers went back to personal style and syntax.
Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv
I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard. I did pre-load AD into PowerShell before hand:
Get-Module -ListAvailable | Import-Module
I know plenty of people have said it in a long winded way, but:
C is faster because it does less (for you).
I guess you want to convert the values contained in the Map
to a list
? Easiest is to call the values()
method of the Map
interface. This will return the Collection
of value objects contained in the Map
.
Note that this Collection
is backed by the Map
object and any changes to the Map
object will reflect here. So if you want a separate copy not bound to your Map
object, simply create a new List
object like an ArrayList
passing the value Collection
as below.
ArrayList<String> list = new ArrayList<String>(map.values());
.button input,
.button a {
...
}
Just do git checkout path/to/file-I-want-to-bring-back.txt
Here is another dirty hack :)
.application-title > img {
display: none;
}
.application-title::before {
content: url(path/example.jpg);
}
Make your audioSounds
and minTime
variables as static variables, as you are using them in a static method (playSound
).
Marking a method as static
prevents the usage of non-static (instance) members in that method.
To understand more , please read this SO QA:
I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.
In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.
In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile
or /etc/.bashrc
but otherwise, they're not permanent. They're stored in RAM.
There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.
You can view shell variables with the set
command (though note that unlike windows, variables are not set in linux with the set command).
set -o posix; set
(doing that set -o posix once first, helps not display too much unnecessary stuff). So set
displays shell variables.
You can view environment variables with the env
command
shell variables are set with e.g. just a = 5
environment variables are set with export, export also sets the shell variable
Here you see shell variable zzz set with zzz = 5, and see it shows when running set
but doesn't show as an environment variable.
Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables
$ zzz=5
$ set | grep zzz
zzz=5
$ env | grep zzz
$ export yyy=5
$ set | grep yyy
yyy=5
$ env | grep yyy
yyy=5
$
other useful threads
https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables
https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference
Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf
then it sets $1 to asdf, and if you do echo $1
you see asdf. If you do set a=5
it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose
, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose
to turn verbose off. Windows has no such usage for its set command.
I would recommend using Offset
assuming that the Headers are in Row 1. See this example
Option Explicit
Sub Sample()
Dim rRange As Range, filRange As Range, Rng as Range
'Remove any filters
ActiveSheet.AutoFilterMode = False
'~~> Set your range
Set rRange = Sheets("Sheet1").Range("A1:E10")
With rRange
'~~> Set your criteria and filter
.AutoFilter Field:=1, Criteria1:="=1"
'~~> Filter, offset(to exclude headers)
Set filRange = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
Debug.Print filRange.Address
For Each Rng In filRange
'~~> Your Code
Next
End With
'Remove any filters
ActiveSheet.AutoFilterMode = False
End Sub
The Pythonic way to create a static class is simply to declare those methods outside of a class (Java uses classes both for objects and for grouping related functions, but Python modules are sufficient for grouping related functions that do not require any object instance). However, if you insist on making a method at the class level that doesn't require an instance (rather than simply making it a free-standing function in your module), you can do so by using the "@staticmethod" decorator.
That is, the Pythonic way would be:
# My module
elements = []
def add_element(x):
elements.append(x)
But if you want to mirror the structure of Java, you can do:
# My module
class World(object):
elements = []
@staticmethod
def add_element(x):
World.elements.append(x)
You can also do this with @classmethod
if you care to know the specific class (which can be handy if you want to allow the static method to be inherited by a class inheriting from this class):
# My module
class World(object):
elements = []
@classmethod
def add_element(cls, x):
cls.elements.append(x)
Thanks to TheSoftwareJedi for providing useful information about snapping tool in Windows 7. Shortcut to open Snipping tool : Go to Start, type sni And you will find the name in the list "Snipping Tool"
I set the
variable name : JAVA_HOME value : C:\Program Files\Java\jdk1.6.0_32
I set these properties in system/environment variables without semicolon, tomcat is running on my system.
It really works.
do it using jQuery put inside code on the <head></head>
tag
<script type="text/javascript">
$(document).ready(function() {
var docHeight = $(window).height();
var footerHeight = $('#footer').height();
var footerTop = $('#footer').position().top + footerHeight;
if (footerTop < docHeight) {
$('#footer').css('margin-top', 10 + (docHeight - footerTop) + 'px');
}
});
</script>
Another nice approach can be seen here: http://blogs.microsoft.co.il/blogs/eladkatz/archive/2011/05/29/what-is-the-easiest-way-to-set-spacing-between-items-in-stackpanel.aspx Link is broken -> this is webarchive of this link.
It shows how to create an attached behavior, so that syntax like this would work:
<StackPanel local:MarginSetter.Margin="5">
<TextBox Text="hello" />
<Button Content="hello" />
<Button Content="hello" />
</StackPanel>
This is the easiest & fastest way to set Margin to several children of a panel, even if they are not of the same type. (I.e. Buttons, TextBoxes, ComboBoxes, etc.)
public static LocalDateTime timestampToLocalDateTime(Long timestamp) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), TimeZone.getDefault().toZoneId());
}
This isn't part of numpy
, but it will work with numpy.ndarray
objects. A numpy.matrix
can be converted to a numpy.ndarray
and a numpy.ndarray
can be converted to a numpy.matrix
.
from sklearn.metrics import mean_squared_error
mse = mean_squared_error(A, B)
See Scikit Learn mean_squared_error for documentation on how to control axis.
On iOS 9:
Settings -> General -> Device Management -> Developer app / your Apple ID -> Add/remove trust there
Keep in mind that the for-loop and foreach-loop are not always equivalent. List enumerators will throw an exception if the list changes, but you won't always get that warning with a normal for loop. You might even get a different exception if the list changes at just the wrong time.
Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.
C:\Windows\SysWOW64>regsvr32 "c:\dll.name"
throw new RuntimeException(msg);
unlike any other Exceptions I think RuntimeException is the only one that will not stall the program but it can still keep running and recover just print out a bunch of Exception lines? correct me if I am wrong.
=RIGHT(A1)
is quite sufficient (where the string is contained in A1).
Similar in nature to LEFT, Excel's RIGHT function extracts a substring from a string starting from the right-most character:
SYNTAX
RIGHT( text, [number_of_characters] )
Parameters or Arguments
text
The string that you wish to extract from.
number_of_characters
Optional. It indicates the number of characters that you wish to extract starting from the right-most character. If this parameter is omitted, only 1 character is returned.
Applies To
Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000
Since number_of_characters is optional and defaults to 1
it is not required in this case.
However, there have been many issues with trailing spaces and if this is a risk for the last visible character (in general):
=RIGHT(TRIM(A1))
might be preferred.
Consider you need to develop a program through which you need to pass two arguments. First of all, you need to open Program.cs class and add arguments in the Main method as like below and pass these arguments to the constructor of the Windows form.
static class Program
{
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args[0], Convert.ToInt32(args[1])));
}
}
In windows form class, add a parameterized constructor which accepts the input values from Program class as like below.
public Form1(string s, int i)
{
if (s != null && i > 0)
MessageBox.Show(s + " " + i);
}
To test this, you can open command prompt and go to the location where this exe is placed. Give the file name then parmeter1 parameter2. For example, see below
C:\MyApplication>Yourexename p10 5
From the C# code above, it will prompt a Messagebox with value p10 5
.
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
First a link to some documentation of fork()
http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html
The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.
So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.
If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().
pid_t pid = fork()
if(pid == 0) {
printf("this is a child: my new unique pid is %d\n", getpid());
} else {
printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}
and below is some inline comments on your code
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
pid_t pid1, pid2, pid3;
pid1=0, pid2=0, pid3=0;
pid1= fork(); /* A */
if(pid1 == 0){
/* This is child A */
pid2=fork(); /* B */
pid3=fork(); /* C */
} else {
/* This is parent A */
/* Child B and C will never reach this code */
pid3=fork(); /* D */
if(pid3==0) {
/* This is child D fork'ed from parent A */
pid2=fork(); /* E */
}
if((pid1 == 0)&&(pid2 == 0)) {
/* pid1 will never be 0 here so this is dead code */
printf("Level 1\n");
}
if(pid1 !=0) {
/* This is always true for both parent and child E */
printf("Level 2\n");
}
if(pid2 !=0) {
/* This is parent E (same as parent A) */
printf("Level 3\n");
}
if(pid3 !=0) {
/* This is parent D (same as parent A) */
printf("Level 4\n");
}
}
return 0;
}
Use the in
keyword without is
.
if "x" in dog:
print "Yes!"
If you'd like to check for the non-existence of a character, use not in
:
if "x" not in dog:
print "No!"
For me the code:
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
throws error, but I added name attribute to input:
<form (submit)="addTodo()">_x000D_
<input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
and it started to work.
As stated by @Dugini, some config entries have been removed. Maximal:
webdriver.DesiredCapabilities.FIREFOX['proxy'] = {
"httpProxy":PROXY,
"ftpProxy":PROXY,
"sslProxy":PROXY,
"noProxy":[],
"proxyType":"MANUAL"
}
This will get all files in a directory and remove them.
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
dir = os.path.join(BASE_DIR, "foldername")
for root, dirs, files in os.walk(dir):
for file in files:
path = os.path.join(dir, file)
os.remove(path)
Use NGX Cookie Service
Inastall this package: npm install ngx-cookie-service --save
Add the cookie service to your app.module.ts as a provider:
import { CookieService } from 'ngx-cookie-service';
@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule, ... ],
providers: [ CookieService ],
bootstrap: [ AppComponent ]
})
Then call in your component:
import { CookieService } from 'ngx-cookie-service';
constructor( private cookieService: CookieService ) { }
ngOnInit(): void {
this.cookieService.set( 'name', 'Test Cookie' ); // To Set Cookie
this.cookieValue = this.cookieService.get('name'); // To Get Cookie
}
That's it!
Easiest way to do it would be this
std::string myWord = "myWord";
char myArray[myWord.size()+1];//as 1 char space for null is also required
strcpy(myArray, myWord.c_str());
Solution that worked for me:
Try this to test if a file is a directory:
FOR /F "delims=" %I IN ('DIR /B /AD "filename" 2^>^&1 ^>NUL') DO IF "%I" == "File Not Found" ECHO Not a directory
This only will tell you whether a file is NOT a directory, which will also be true if the file doesn't exist, so be sure to check for that first if you need to. The carets (^) are used to escape the redirect symbols and the file listing output is redirected to NUL to prevent it from being displayed, while the DIR listing's error output is redirected to the output so you can test against DIR's message "File Not Found".
Received SQLSTATE 01000 in the following error message below:
SQL Agent - Jobs Failed: The SQL Agent Job "LiteSpeed Backup Full" has failed with the message "The job failed. The Job was invoked by User X. The last step to run was step 1 (Step1). NOTE: Failed to notify via email. - Executed as user: X. LiteSpeed(R) for SQL Server Version 6.5.0.1460 Copyright 2011 Quest Software, Inc. [SQLSTATE 01000] (Message 1) LiteSpeed for SQL Server could not open backup file: (N:\BACKUP2\filename.BAK). The previous system message is the reason for the failure. [SQLSTATE 42000] (Error 60405). The step failed."
In my case this was related to permission on drive N following an SQL Server failover on an Active/Passive SQL cluster.
All SQL resources where failed over to the seconary resouce and back to the preferred node following maintenance. When the Quest LiteSpeed job then executed on the preferred node it was clear the previous permissions for SQL server user X had been lost on drive N and SQLSTATE 10100 was reported.
Simply added the permissions again to the backup destination drive and the issue was resolved.
Hope that helps someone.
Windows 2008 Enterprise
SQL Server 2008 Active/Passive cluster.
Remember to always wrap variables in double quotes when referencing them in a Bash script. Kids these days grow up with the idea that they can have spaces and lots of other funny characters in their directory names. (Spaces! Back in my days, we didn't have no fancy spaces! ;))
One day, one of those kids will run your script with $DIRECTORY
set to "My M0viez"
and your script will blow up. You don't want that. So use this.
if [ -d "$DIRECTORY" ]; then
# Will enter here if $DIRECTORY exists, even if it contains spaces
fi
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.now();
System.out.println("Formatted Date: " + formatter.format(localDate));
Java 8 LocalDate
C++ Implementation (not by me) here. Note that when your bytes are over 65535, you need to shift with a long value as shown here.
In Xcode Beta 5, they no longer let you do:
var xyz : NSString?
if xyz {
// Do something using `xyz`.
}
This produces an error:
does not conform to protocol 'BooleanType.Protocol'
You have to use one of these forms:
if xyz != nil {
// Do something using `xyz`.
}
if let xy = xyz {
// Do something using `xy`.
}
System.setProperty("gate.home", "/some/directory");
After that you can retrieve its value later by calling
String value = System.getProperty("gate.home");
That's it.
If this error appears suddenly, it means the project is missing some frameworks. Libraries and dependent projects can require frameworks, so if you've added one recently then that can cause this error.
To add frameworks, right click on the project name in the project view, select Add, then select Existing frameworks from the list. Then find the framework with the symbols you're missing.
The other thing is if you added any classes in the compiled resources and removed that classes from the project then the error appears. The best thing to do is remove the classes from the compile resources(Build settings--> compile sources) which have removed from the project.
In my case i have added the admob classes in the project and compiled the project. In a later case i dont want to include admobs in my project so i deleted the references of the admob classes from my project. When this error occurred i deleted the .m class of my admob from compile resources solved this problem.
from state in _objedatasource.StateList()
where listofcountrycodes.Contains(state.CountryCode)
select state
A demonstration of lazy
- as defined above - execution when defined vs execution when accessed: (using 2.12.7 scala shell)
// compiler says this is ok when it is lazy
scala> lazy val t: Int = t
t: Int = <lazy>
//however when executed, t recursively calls itself, and causes a StackOverflowError
scala> t
java.lang.StackOverflowError
...
// when the t is initialized to itself un-lazily, the compiler warns you of the recursive call
scala> val t: Int = t
<console>:12: warning: value t does nothing other than call itself recursively
val t: Int = t
The AJAX request never has the opportunity to NOT follow the redirect (i.e., it must follow the redirect). More information can be found in this answer https://stackoverflow.com/a/2573589/965648
Any ideas?
CSS4 will be fancy if it adds some hooks into walking backwards. Until then it is possible (though not advisable) to use checkbox
and/or radio
input
s to break the usual way that things are connected, and through that also allow CSS to operate outside of its normal scope...
/* Hide things that may be latter shown */
.menu__checkbox__selection,
.menu__checkbox__style,
.menu__hidden {
display: none;
visibility: hidden;
opacity: 0;
filter: alpha(opacity=0); /* Old Microsoft opacity */
}
/* Base style for content and style menu */
.main__content {
background-color: lightgray;
color: black;
}
.menu__hidden {
background-color: black;
color: lightgray;
/* Make list look not so _listy_ */
list-style: none;
padding-left: 5px;
}
.menu__option {
box-sizing: content-box;
display: block;
position: static;
z-index: auto;
}
/* ▼ - \u2630 - Three Bars */
/*
.menu__trigger__selection::before {
content: '\2630';
display: inline-block;
}
*/
/* ▼ - Down Arrow */
.menu__trigger__selection::after {
content: "\25BC";
display: inline-block;
transform: rotate(90deg);
}
/* Customize to look more `select` like if you like */
.menu__trigger__style:hover,
.menu__trigger__style:active {
cursor: pointer;
background-color: darkgray;
color: white;
}
/**
* Things to do when checkboxes/radios are checked
*/
.menu__checkbox__selection:checked + .menu__trigger__selection::after,
.menu__checkbox__selection[checked] + .menu__trigger__selection::after {
transform: rotate(0deg);
}
/* This bit is something that you may see elsewhere */
.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
display: block;
visibility: visible;
opacity: 1;
filter: alpha(opacity=100); /* Microsoft!? */
}
/**
* Hacky CSS only changes based off non-inline checkboxes
* ... AKA the stuff you cannot unsee after this...
*/
.menu__checkbox__style[id="style-default"]:checked ~ .main__content {
background-color: lightgray;
color: black;
}
.menu__checkbox__style[id="style-default"]:checked ~ .main__content .menu__trigger__style[for="style-default"] {
color: darkorange;
}
.menu__checkbox__style[id="style-one"]:checked ~ .main__content {
background-color: black;
color: lightgray;
}
.menu__checkbox__style[id="style-one"]:checked ~ .main__content .menu__trigger__style[for="style-one"] {
color: darkorange;
}
.menu__checkbox__style[id="style-two"]:checked ~ .main__content {
background-color: darkgreen;
color: red;
}
.menu__checkbox__style[id="style-two"]:checked ~ .main__content .menu__trigger__style[for="style-two"] {
color: darkorange;
}
_x000D_
<!--
This bit works, but will one day cause troubles,
but truth is you can stick checkbox/radio inputs
just about anywhere and then call them by id with
a `for` label. Keep scrolling to see what I mean
-->
<input type="radio"
name="colorize"
class="menu__checkbox__style"
id="style-default">
<input type="radio"
name="colorize"
class="menu__checkbox__style"
id="style-one">
<input type="radio"
name="colorize"
class="menu__checkbox__style"
id="style-two">
<div class="main__content">
<p class="paragraph__split">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
</p>
<input type="checkbox"
class="menu__checkbox__selection"
id="trigger-style-menu">
<label for="trigger-style-menu"
class="menu__trigger__selection"> Theme</label>
<ul class="menu__hidden">
<li class="menu__option">
<label for="style-default"
class="menu__trigger__style">Default Style</label>
</li>
<li class="menu__option">
<label for="style-one"
class="menu__trigger__style">First Alternative Style</label>
</li>
<li class="menu__option">
<label for="style-two"
class="menu__trigger__style">Second Alternative Style</label>
</li>
</ul>
<p class="paragraph__split">
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
_x000D_
... pretty gross, but with just CSS and HTML it is possible to touch and re-touch anything but the body
and :root
from just about anywhere by linking the id
and for
properties of radio
/checkbox
input
s and label
triggers; likely someone'll show how to re-touch those at some point.
One additional caveat is that only one input
of a specific id
maybe used, first checkbox
/radio
wins a toggled state in other words... But multiple labels can all point to the same input
, though that would make both the HTML and CSS look even grosser.
... I'm hoping that there is some sort of workaround that exists native to CSS Level 2...
I am not sure about the other pseudo classes, but I :checked
for pre-CSS 3. If I remember correctly, it was something like [checked]
which is why you may find it in the above code, for example,
.menu__checkbox__selection:checked ~ .menu__hidden,
.menu__checkbox__selection[checked] ~ .menu__hidden {
/* rules: and-stuff; */
}
... but for things like ::after
and :hover
, I'm not at all certain in which CSS version those first appeared.
That all stated, please don't ever use this in production, not even in anger. As a joke sure, or in other words just because something can be done does not always mean it should.
This worked for me on iOS 5.0 simulator.
Run the app on the simulator.
Go to the path where you can see something like this:
/Users/arshad/Library/Application\ Support/iPhone\ Simulator/5.0/Applications/34BC3FDC-7398-42D4-9114-D5FEFC737512/…
Copy all the package contents including the app, lib, temp and Documents.
Clear all the applications installed on the simulator so that it is easier to see what is happening.
Run a pre-existing app you have on your simulator.
Look for the same package content for that application as in step 3 and delete all.
Paste the package contents that you have previously copied.
Close the simulator and start it again. The new app icon of the intended app will replace the old one.
You can use abstract adapter with diff utils and filter
SimpleAbstractAdapter.kt
abstract class SimpleAbstractAdapter<T>(private var items: ArrayList<T> = arrayListOf()) : RecyclerView.Adapter<SimpleAbstractAdapter.VH>() {
protected var listener: OnViewHolderListener<T>? = null
private val filter = ArrayFilter()
private val lock = Any()
protected abstract fun getLayout(): Int
protected abstract fun bindView(item: T, viewHolder: VH)
protected abstract fun getDiffCallback(): DiffCallback<T>?
private var onFilterObjectCallback: OnFilterObjectCallback? = null
private var constraint: CharSequence? = ""
override fun onBindViewHolder(vh: VH, position: Int) {
getItem(position)?.let { bindView(it, vh) }
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
return VH(parent, getLayout())
}
override fun getItemCount(): Int = items.size
protected abstract class DiffCallback<T> : DiffUtil.Callback() {
private val mOldItems = ArrayList<T>()
private val mNewItems = ArrayList<T>()
fun setItems(oldItems: List<T>, newItems: List<T>) {
mOldItems.clear()
mOldItems.addAll(oldItems)
mNewItems.clear()
mNewItems.addAll(newItems)
}
override fun getOldListSize(): Int {
return mOldItems.size
}
override fun getNewListSize(): Int {
return mNewItems.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return areItemsTheSame(
mOldItems[oldItemPosition],
mNewItems[newItemPosition]
)
}
abstract fun areItemsTheSame(oldItem: T, newItem: T): Boolean
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return areContentsTheSame(
mOldItems[oldItemPosition],
mNewItems[newItemPosition]
)
}
abstract fun areContentsTheSame(oldItem: T, newItem: T): Boolean
}
class VH(parent: ViewGroup, @LayoutRes layout: Int) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(layout, parent, false))
interface OnViewHolderListener<T> {
fun onItemClick(position: Int, item: T)
}
fun getItem(position: Int): T? {
return items.getOrNull(position)
}
fun getItems(): ArrayList<T> {
return items
}
fun setViewHolderListener(listener: OnViewHolderListener<T>) {
this.listener = listener
}
fun addAll(list: List<T>) {
val diffCallback = getDiffCallback()
when {
diffCallback != null && !items.isEmpty() -> {
diffCallback.setItems(items, list)
val diffResult = DiffUtil.calculateDiff(diffCallback)
items.clear()
items.addAll(list)
diffResult.dispatchUpdatesTo(this)
}
diffCallback == null && !items.isEmpty() -> {
items.clear()
items.addAll(list)
notifyDataSetChanged()
}
else -> {
items.addAll(list)
notifyDataSetChanged()
}
}
}
fun add(item: T) {
items.add(item)
notifyDataSetChanged()
}
fun add(position:Int, item: T) {
items.add(position,item)
notifyItemInserted(position)
}
fun remove(position: Int) {
items.removeAt(position)
notifyItemRemoved(position)
}
fun remove(item: T) {
items.remove(item)
notifyDataSetChanged()
}
fun clear(notify: Boolean=false) {
items.clear()
if (notify) {
notifyDataSetChanged()
}
}
fun setFilter(filter: SimpleAdapterFilter<T>): ArrayFilter {
return this.filter.setFilter(filter)
}
interface SimpleAdapterFilter<T> {
fun onFilterItem(contains: CharSequence, item: T): Boolean
}
fun convertResultToString(resultValue: Any): CharSequence {
return filter.convertResultToString(resultValue)
}
fun filter(constraint: CharSequence) {
this.constraint = constraint
filter.filter(constraint)
}
fun filter(constraint: CharSequence, listener: Filter.FilterListener) {
this.constraint = constraint
filter.filter(constraint, listener)
}
fun getFilter(): Filter {
return filter
}
interface OnFilterObjectCallback {
fun handle(countFilterObject: Int)
}
fun setOnFilterObjectCallback(objectCallback: OnFilterObjectCallback) {
onFilterObjectCallback = objectCallback
}
inner class ArrayFilter : Filter() {
private var original: ArrayList<T> = arrayListOf()
private var filter: SimpleAdapterFilter<T> = DefaultFilter()
private var list: ArrayList<T> = arrayListOf()
private var values: ArrayList<T> = arrayListOf()
fun setFilter(filter: SimpleAdapterFilter<T>): ArrayFilter {
original = items
this.filter = filter
return this
}
override fun performFiltering(constraint: CharSequence?): Filter.FilterResults {
val results = Filter.FilterResults()
if (constraint == null || constraint.isBlank()) {
synchronized(lock) {
list = original
}
results.values = list
results.count = list.size
} else {
synchronized(lock) {
values = original
}
val result = ArrayList<T>()
for (value in values) {
if (constraint!=null && constraint.trim().isNotEmpty() && value != null) {
if (filter.onFilterItem(constraint, value)) {
result.add(value)
}
} else {
value?.let { result.add(it) }
}
}
results.values = result
results.count = result.size
}
return results
}
override fun publishResults(constraint: CharSequence, results: Filter.FilterResults) {
items = results.values as? ArrayList<T> ?: arrayListOf()
notifyDataSetChanged()
onFilterObjectCallback?.handle(results.count)
}
}
class DefaultFilter<T> : SimpleAdapterFilter<T> {
override fun onFilterItem(contains: CharSequence, item: T): Boolean {
val valueText = item.toString().toLowerCase()
if (valueText.startsWith(contains.toString())) {
return true
} else {
val words = valueText.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (word in words) {
if (word.contains(contains)) {
return true
}
}
}
return false
}
}
}
And extend abstract adapter with implements methods
TasksAdapter.kt
import android.annotation.SuppressLint
import kotlinx.android.synthetic.main.task_item_layout.view.*
class TasksAdapter(private val listener:TasksListener? = null) : SimpleAbstractAdapter<Task>() {
override fun getLayout(): Int {
return R.layout.task_item_layout
}
override fun getDiffCallback(): DiffCallback<Task>? {
return object : DiffCallback<Task>() {
override fun areItemsTheSame(oldItem: Task, newItem: Task): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Task, newItem: Task): Boolean {
return oldItem.items == newItem.items
}
}
}
@SuppressLint("SetTextI18n")
override fun bindView(item: Task, viewHolder: VH) {
viewHolder.itemView.apply {
val position = viewHolder.adapterPosition
val customer = item.customer
val customerName = if (customer != null) customer.name else ""
tvTaskCommentTitle.text = customerName + ", #" + item.id
tvCommentContent.text = item.taskAddress
ivCall.setOnClickListener {
listener?.onCallClick(position, item)
}
setOnClickListener {
listener?.onItemClick(position, item)
}
}
}
interface TasksListener : SimpleAbstractAdapter.OnViewHolderListener<Task> {
fun onCallClick(position: Int, item: Task)
}
}
Init adapter
mAdapter = TasksAdapter(object : TasksAdapter.TasksListener {
override fun onCallClick(position: Int, item:Task) {
}
override fun onItemClick(position: Int, item:Task) {
}
})
rvTasks.adapter = mAdapter
and fill
mAdapter?.addAll(tasks)
add custom filter
mAdapter?.setFilter(object : SimpleAbstractAdapter.SimpleAdapterFilter<MoveTask> {
override fun onFilterItem(contains: CharSequence, item:Task): Boolean {
return contains.toString().toLowerCase().contains(item.id?.toLowerCase().toString())
}
})
filter data
mAdapter?.filter("test")
Check if you do not have declared the method getAll() in the model. That causes the controller to think that you are calling a non-static method.
CSS:
#cols {
-moz-column-count: 3;
-moz-column-gap: 20px;
-webkit-column-count: 3;
-webkit-column-gap: 20px;
column-count: 3;
column-gap: 20px;
}
HTML
<div id="cols">
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
<li>List item 6</li>
<li>List item 7</li>
<li>List item 8</li>
<li>List item 9</li>
<li>List item 10</li>
<li>List item 11</li>
<li>List item 12</li>
<li>List item 10</li>
<li>List item 11</li>
<li>List item 12</li>
</ul>
</div>
Check demo : https://codepen.io/pen/
Visit https://play.golang.org/p/dx6PTtuBXQW
package main
import (
"fmt"
"sort"
)
func main() {
mapEg := map[string]string{"c":"a","a":"c","b":"b"}
keys := make([]string, 0, len(mapEg))
for k := range mapEg {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println(keys)
}
This is all you need, no wrapper needed:
.login-icon{
display:inline-block;
font-size: 40px;
line-height: 50px;
background-color:black;
color:white;
width: 50px;
height: 50px;
text-align: center;
vertical-align: bottom;
}
We should always go for equals() method for comparison for two integers.Its the recommended practice.
If we compare two integers using == that would work for certain range of integer values (Integer from -128 to 127) due to JVM's internal optimisation.
Please see examples:
Case 1:
Integer a = 100; Integer b = 100;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
In above case JVM uses value of a and b from cached pool and return the same object instance(therefore memory address) of integer object and we get both are equal.Its an optimisation JVM does for certain range values.
Case 2: In this case, a and b are not equal because it does not come with the range from -128 to 127.
Integer a = 220; Integer b = 220;
if (a == b) { System.out.println("a and b are equal"); } else { System.out.println("a and b are not equal"); }
Proper way:
Integer a = 200;
Integer b = 200;
System.out.println("a == b? " + a.equals(b)); // true
I hope this helps.
I would advise, it is slightly better practise to use string model references for ForeignKey
relationships if utilising an app based approach to seperation of logical concerns .
So, expanding on Martijn Pieters' answer:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
'app_label.Anniversary', on_delete=models.CASCADE)
address = models.ForeignKey(
'app_label.Address', on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
try this
$("label").html(your value);
or $("label").text(your value);
The --no-ff
option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff
.
If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.
For example, the author of this article thinks that --no-ff
option should be default and his reasoning is close to that I outlined above:
Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff
, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff
is not used], whereas it is easily done if the --no-ff
flag was used [because it's just one commit]."
If optimal performance is not a requirement and you just want something dead simple, you can define a basic function to test each character using the string class's built in "isspace" method:
def remove_space(input_string):
no_white_space = ''
for c in input_string:
if not c.isspace():
no_white_space += c
return no_white_space
Building the no_white_space
string this way will not have ideal performance, but the solution is easy to understand.
>>> remove_space('strip my spaces')
'stripmyspaces'
If you don't want to define a function, you can convert this into something vaguely similar with list comprehension. Borrowing from the top answer's join
solution:
>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'
I was also getting the same issue I tried multiple IPs like my public IP and localhost default IP 127.0.0.1 in windows and default gateway but same response. but I forget to check by
C:> ipconfig
ipconfig cleanly say what is my actual IP address of that adapter with which I have connected like I was connected with Wifi adapter my IP address will show me as:
Wireless LAN adapter Wireless Network Connection:
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : fe80::69fa:9475:431e:fad7%11
IPv4 Address. . . . . . . . . . . : 192.168.15.92
I hope this will help you.
You can only access a website throught the port that is bind with the http server. Example: i hava a web server and it is listening for connections on port 123, the you only can get my pages connecting to my 123 port.
If you only care about creating a subprocess and waiting for it, perhaps _spawn* API's in process.h are sufficient. Here's more information about that:
https://docs.microsoft.com/en-us/cpp/c-runtime-library/process-and-environment-control https://en.wikipedia.org/wiki/Process.h
For checking spaces just with bash:
[[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"
There are many toolboxes. Since you mentioned one that is commercially available from MathWorks, I assume you mean how do you get a trial/license
http://www.mathworks.com/products/image/
There is a link for trials, purchase, demos. This will get you in touch with your sales representative. If you know your sales representative, you could just call to get attention faster.
If you mean just a general toolbox that is from a source other than MathWorks, I would check with the producer, as it will vary widely from "Put it on your path." to whatever their purchase and licensing procedure is.
getActionBar().setIcon(android.R.color.transparent);
This worked for me.
There is no need to do the reader loop yourself. The JsonTokener has this built in. E.g.
ttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new
JSONTokener tokener = new JSONTokener(reader);
JSONArray finalResult = new JSONArray(tokener);
In case you want to pass error strings, here is an example from Errors and Exceptions (Python 2.6)
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to printed directly
... x, y = inst # __getitem__ allows args to be unpacked directly
... print 'x =', x
... print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
In iOS 5 you can change the navigationBar title color in this manner:
navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};
Iterative solution as an alternative:
def traverse_nested_dict(d):
iters = [d.iteritems()]
while iters:
it = iters.pop()
try:
k, v = it.next()
except StopIteration:
continue
iters.append(it)
if isinstance(v, dict):
iters.append(v.iteritems())
else:
yield k, v
d = {"a": 1, "b": 2, "c": {"d": 3, "e": {"f": 4}}}
for k, v in traverse_nested_dict(d):
print k, v
In pthread_exit
, ret
is an input parameter. You are simply passing the address of a variable to the function.
In pthread_join
, ret
is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL
.
Long explanation:
In pthread_join
, you get back the address passed to pthread_exit
by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.
.contentBlock {_x000D_
width: {define width}_x000D_
width: 400px;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
right: 0;_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
_x000D_
}
_x000D_
Applying the suggestions mentioned, I've faced the issue of app getting killed whenever default icon gets changed to new icon. So have implemented the code with some tweaks. Step 1). In file AndroidManifest.xml, create for default activity with android:enabled="true" & other alias with android:enabled="false". Your will not contain but append those in with android:enabled="true".
<activity
android:name=".activities.SplashActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/SplashTheme">
</activity>
<!-- <activity-alias used to change app icon dynamically> : default icon, set enabled true -->
<activity-alias
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:name=".SplashActivityAlias1" <!--put any random name started with dot-->
android:enabled="true"
android:targetActivity=".activities.SplashActivity"> <!--target activity class path will be same for all alias-->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
<!-- <activity-alias used to change app icon dynamically> : sale icon, set enabled false initially -->
<activity-alias
android:label="@string/app_name"
android:icon="@drawable/ic_store_marker"
android:roundIcon="@drawable/ic_store_marker"
android:name=".SplashActivityAlias" <!--put any random name started with dot-->
android:enabled="false"
android:targetActivity=".activities.SplashActivity"> <!--target activity class path will be same for all alias-->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity-alias>
Step 2). Make a method that will be used to disable 1st activity-alias that contains default icon & enable 2nd alias that contains icon need to be changed.
/**
* method to change the app icon dynamically
*
* @param context
* @param isNewIcon : true if new icon need to be set; false to set default
* icon
*/
public static void changeAppIconDynamically(Context context, boolean isNewIcon) {
PackageManager pm = context.getApplicationContext().getPackageManager();
if (isNewIcon) {
pm.setComponentEnabledSetting(
new ComponentName(context,
"com.example.dummy.SplashActivityAlias1"), //com.example.dummy will be your package
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context,
"com.example.dummy.SplashActivityAlias"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
} else {
pm.setComponentEnabledSetting(
new ComponentName(context,
"com.example.dummy.SplashActivityAlias1"),
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
pm.setComponentEnabledSetting(
new ComponentName(context,
"com.example.dummy.SplashActivityAlias"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
Step 3). Now call this method depending on your requirement, say on button click or date specific or occasion specific conditions, simply like -
// Switch app icon to new icon
GeneralUtils.changeAppIconDynamically(EditProfileActivity.this, true);
// Switch app icon to default icon
GeneralUtils.changeAppIconDynamically(EditProfileActivity.this, false);
Hope this will help those who face the issue of app getting killed on icon change. Happy Coding :)
I have found this to be a useful pattern to follow:
@RunWith(SpringRunner)
@SpringBootTest(classes = [ TestConfiguration, MyApplication ],
properties = [
"spring.config.name=application-MyTest_LowerImportance,application-MyTest_MostImportant"
,"debug=true", "trace=true"
]
)
Here we override the use of "application.yml" to use "application-MyTest_LowerImportance.yml" and also "application-MyTest_MostImportant.yml"
(Spring will also look for .properties files)
Also included as an extra bonus are the debug and trace settings, on a separate line so you can comment them out if required ;]
The debug/trace are incredibly useful as Spring will dump the names of all the files it loads and those it tries to load.
You will see lines like this in the console at runtime:
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_MostImportant.properties' (file:./config/application-MyTest_MostImportant.properties) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_MostImportant.xml' (file:./config/application-MyTest_MostImportant.xml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_MostImportant.yml' (file:./config/application-MyTest_MostImportant.yml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_MostImportant.yaml' (file:./config/application-MyTest_MostImportant.yaml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_LowerImportance.properties' (file:./config/application-MyTest_LowerImportance.properties) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_LowerImportance.xml' (file:./config/application-MyTest_LowerImportance.xml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_LowerImportance.yml' (file:./config/application-MyTest_LowerImportance.yml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_LowerImportance.yaml' (file:./config/application-MyTest_LowerImportance.yaml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_MostImportant.properties' (file:./application-MyTest_MostImportant.properties) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_MostImportant.xml' (file:./application-MyTest_MostImportant.xml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_MostImportant.yml' (file:./application-MyTest_MostImportant.yml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_MostImportant.yaml' (file:./application-MyTest_MostImportant.yaml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_LowerImportance.properties' (file:./application-MyTest_LowerImportance.properties) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_LowerImportance.xml' (file:./application-MyTest_LowerImportance.xml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_LowerImportance.yml' (file:./application-MyTest_LowerImportance.yml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./application-MyTest_LowerImportance.yaml' (file:./application-MyTest_LowerImportance.yaml) resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_MostImportant.properties' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_MostImportant.xml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_MostImportant.yml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_MostImportant.yaml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.properties' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.xml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.yml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/config/application-MyTest_LowerImportance.yaml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_MostImportant.properties' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_MostImportant.xml' resource not found
DEBUG 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Loaded config file 'file:/Users/xxx/dev/myproject/target/test-classes/application-MyTest_MostImportant.yml' (classpath:/application-MyTest_MostImportant.yml)
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_MostImportant.yaml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_LowerImportance.properties' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_LowerImportance.xml' resource not found
DEBUG 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Loaded config file 'file:/Users/xxx/dev/myproject/target/test-classes/application-MyTest_LowerImportance.yml' (classpath:/application-MyTest_LowerImportance.yml)
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'classpath:/application-MyTest_LowerImportance.yaml' resource not found
TRACE 93941 --- [ main] o.s.b.c.c.ConfigFileApplicationListener : Skipped config file 'file:./config/application-MyTest_MostImportant-test.properties' (file:./config/application-MyTest_MostImportant-test.properties) resource not found
Just for fun, consider the different question one would get with a very literal interpretation of the OP's description: "Write a query to print the list of names of students who have scored the maximum mark in each subject."
Those who've answered here have written queries to list a student if he or she scored the maximum mark in any one subject, but not necessarily in all subjects. Since the question posed by the OP does not ask for subject names in the output, this is a plausible interpretation.
To list the names of students (if any) who have scored the maximum mark in all subjects (excluding subjects with no marks, since arguably there is then no maximum mark then), I think this works, using column names from Michael's SQL Fiddle, which I've adapted here.
select StudentName
from Student
where not exists (
select * from Subject
where exists (
select * from Mark as M1
where M1.SubjectID = Subject.SubjectID
and M1.StudentID <> Student.StudentID
and not exists (
select * from Mark as M2
where M2.StudentID = Student.StudentID
and M2.SubjectID = M1.SubjectID
and M2.MarkRate >= M1.MarkRate
)
)
)
In other words, select a student X's name if there is no subject in which someone's mark for that subject is not matched or exceeded by some mark belonging to X for the same subject. (This query returns a student's name if the student has received more than one mark in a subject, so long as one of those marks is the highest for the subject.)
Which line is throwing the exception? The new MemoryStream(...)
? or the Image.FromStream(...)
? And what is the byteArrayIn
? Is it a byte[]
? I only ask because of the comment "And none of value in it is not greater than 255" - which of course is automatic for a byte[]
.
As a more obvious question: does the binary actually contain an image in a sensible format?
For example, the following (although not great code) works fine:
byte[] data = File.ReadAllBytes(@"d:\extn.png"); // not a good idea...
MemoryStream ms = new MemoryStream(data);
Image img = Image.FromStream(ms);
Console.WriteLine(img.Width);
Console.WriteLine(img.Height);