I was facing the same issue and I tried all the above answers. But unfortunately, none of the above worked.
As a note, I finally solve this by pip uninstall distribute
.
Copied from : https://docs.python.org/2/library/uuid.html (Since the links posted were not active and they keep updating)
>>> import uuid
>>> # make a UUID based on the host ID and current time
>>> uuid.uuid1()
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')
>>> # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')
>>> # make a random UUID
>>> uuid.uuid4()
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')
>>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')
>>> # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
>>> # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'
>>> # get the raw 16 bytes of the UUID
>>> x.bytes
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'
>>> # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
On read csv
, I added an encoding method:
import pandas as pd
dataset = pd.read_csv('sample_data.csv', header= 0,
encoding= 'unicode_escape')
A complete answer for React Router v6 or version 6 just in case needed.
import Dashboard from "./dashboard/Dashboard";
import DashboardDefaultContent from "./dashboard/dashboard-default-content";
import { Route, Routes } from "react-router";
import { useRoutes } from "react-router-dom";
/*Routes is used to be Switch*/
const Router = () => {
return (
<Routes>
<Route path="/" element={<LandingPage />} />
<Route path="games" element={<Games />} />
<Route path="game-details/:id" element={<GameDetails />} />
<Route path="dashboard" element={<Dashboard />}>
<Route path="/" element={<DashboardDefaultContent />} />
<Route path="inbox" element={<Inbox />} />
<Route path="settings-and-privacy" element={<SettingsAndPrivacy />} />
<Route path="*" element={<NotFound />} />
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
);
};
export default Router;
import DashboardSidebarNavigation from "./dashboard-sidebar-navigation";
import { Grid } from "@material-ui/core";
import { Outlet } from "react-router";
const Dashboard = () => {
return (
<Grid
container
direction="row"
justify="flex-start"
alignItems="flex-start"
>
<DashboardSidebarNavigation />
<Outlet />
</Grid>
);
};
export default Dashboard;
Github repo is here. https://github.com/webmasterdevlin/react-router-6-demo
if you have in your layout activity_main
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
you have to put
in your Activity this code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(Color.CYAN);
}
UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;
you might want to use CEIL()
if A
is always a floating point value > 0
and <= 2
On MongoDB 4.4+ and on CentOS 8, I found the path by running:
grep dbPath /etc/mongod.conf
This is a bad way of doing it, but it worked for me when trying to interpret escaped octals passed in a string argument.
input_string = eval('b"' + sys.argv[1] + '"')
It's worth mentioning that there is a difference between eval and ast.literal_eval (eval being way more unsafe). See Using python's eval() vs. ast.literal_eval()?
In my case I was trying to get the value from wrong ResultSet when querying multiple SQL statements.
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
This is a late entry for folks, but below is my implementation. You will also notice I stubbed-out the ability to change the the KEYs default type: the details about which can be found in the following articles:
NOTES:
It should be noted that you cannot use Guid's
for your keys. This is because under the hood they are a Struct
, and as such, have no unboxing which would allow their conversion from a generic <TKey>
parameter.
THE CLASSES LOOK LIKE:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
#region <Constructors>
public ApplicationDbContext() : base(Settings.ConnectionString.Database.AdministrativeAccess)
{
}
#endregion
#region <Properties>
//public DbSet<Case> Case { get; set; }
#endregion
#region <Methods>
#region
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
//modelBuilder.Configurations.Add(new ResourceConfiguration());
//modelBuilder.Configurations.Add(new OperationsToRolesConfiguration());
}
#endregion
#region
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
#endregion
#endregion
}
public class ApplicationUser : IdentityUser<string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
#region <Constructors>
public ApplicationUser()
{
Init();
}
#endregion
#region <Properties>
[Required]
[StringLength(250)]
public string FirstName { get; set; }
[Required]
[StringLength(250)]
public string LastName { get; set; }
#endregion
#region <Methods>
#region private
private void Init()
{
Id = Guid.Empty.ToString();
}
#endregion
#region public
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
#endregion
#endregion
}
public class CustomUserStore : UserStore<ApplicationUser, CustomRole, string, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
#region <Constructors>
public CustomUserStore(ApplicationDbContext context) : base(context)
{
}
#endregion
}
public class CustomUserRole : IdentityUserRole<string>
{
}
public class CustomUserLogin : IdentityUserLogin<string>
{
}
public class CustomUserClaim : IdentityUserClaim<string>
{
}
public class CustomRoleStore : RoleStore<CustomRole, string, CustomUserRole>
{
#region <Constructors>
public CustomRoleStore(ApplicationDbContext context) : base(context)
{
}
#endregion
}
public class CustomRole : IdentityRole<string, CustomUserRole>
{
#region <Constructors>
public CustomRole() { }
public CustomRole(string name)
{
Name = name;
}
#endregion
}
If you want to kill the process that's listening on port 8080, you could use PowerShell. Just combine Get-NetTCPConnection
cmdlet with Stop-Process
.
Tested and should work with PowerShell 5 on Windows 10 or Windows Server 2016. However, I guess that it should also work on older Windows versions that have PowerShell 5 installed.
Here is an example:
PS C:\> Stop-Process -Id (Get-NetTCPConnection -LocalPort 8080).OwningProcess
Confirm
Are you sure you want to perform the Stop-Process operation on the following item: MyTestServer(9408)?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
Assuming you are using a Date range Picker to retrieve the dates. You could do something like to to get what you want.
$('#daterange-btn').daterangepicker({
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
startDate: moment().subtract(29, 'days'),
endDate: moment()
}, function (start, end) {
alert( 'Date is between' + start.format('YYYY-MM-DD h:m') + 'and' + end.format('YYYY-MM-DD h:m')}
compactitem
does the job.
\usepackage{paralist}
...
\begin{compactitem}[$\bullet$]
\item Element 1
\item Element 2
\end{compactitem}
\vspace{\baselineskip} % new line after list
My user account did not have the permissions to alter the database and table, as suggested in this solution.
If, like me, you don't care about the character collation (you are using the '=' operator), you can apply the reverse fix. Run this before your SELECT:
SET collation_connection = 'latin1_swedish_ci';
"" is an actual string, albeit an empty one.
null, however, means that the String variable points to nothing.
a==b
returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.
a.equals(b)
returns false because "" does not equal null, obviously.
The difference is though that since "" is an actual string, you can still invoke methods or functions on it like
a.length()
a.substring(0, 1)
and so on.
If the String equals null, like b, Java would throw a NullPointerException
if you tried invoking, say:
b.length()
If the difference you are wondering about is == versus equals, it's this:
== compares references, like if I went
String a = new String("");
String b = new String("");
System.out.println(a==b);
That would output false because I allocated two different objects, and a and b point to different objects.
However, a.equals(b)
in this case would return true, because equals
for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.
Be warned, though, that Java does have a special case for Strings.
String a = "abc";
String b = "abc";
System.out.println(a==b);
You would think that the output would be false
, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.
Spring 2 introduced ResponseStatusException using this you can return String, different HTTP status code, DTO at the same time.
@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
if(userDto.getId() != null) {
throw new ResponseStatusException(HttpStatus.NOT_ACCEPTABLE,"A new user cannot already have an ID");
}
return ResponseEntity.ok(userService.saveUser(userDto));
}
There are a few answers already, but here is my solution:
I use opacity: 0
and visibility: hidden
. To make sure that visibility
is set before the animation, we have to set the right delays.
I use http://lesshat.com to simplify the demo, for use without this just add the browser prefixes.
(e.g. -webkit-transition-duration: 0, 200ms;
)
.fadeInOut {
.transition-duration(0, 200ms);
.transition-property(visibility, opacity);
.transition-delay(0);
&.hidden {
visibility: hidden;
.opacity(0);
.transition-duration(200ms, 0);
.transition-property(opacity, visibility);
.transition-delay(0, 200ms);
}
}
So as soon as you add the class hidden
to your element, it will fade out.
I had the same problem and I solved as follows define an interface like mine
export class Notification {
id: number;
heading: string;
link: string;
}
and in nofificationService write
allNotifications: Notification[];
//NotificationDetail: Notification;
private notificationsUrl = 'assets/data/notification.json'; // URL to web api
private downloadsUrl = 'assets/data/download.json'; // URL to web api
constructor(private httpClient: HttpClient ) { }
getNotifications(): Observable<Notification[]> {
//return this.allNotifications = this.NotificationDetail.slice(0);
return this.httpClient.get<Notification[]>
(this.notificationsUrl).pipe(map(res => this.allNotifications = res))
}
and in component write
constructor(private notificationService: NotificationService) {
}
ngOnInit() {
/* get Notifications */
this.notificationService.getNotifications().subscribe(data => this.notifications = data);
}
Here is a hightly readable oneliner solution using the ts
command from moreutils
$ cat file | ts prefix | tr -d ' '
And how it's derived step by step:
# Step 0. create the file
$ cat file
line1
line2
line3
# Step 1. add prefix to the beginning of each line
$ cat file | ts prefix
prefix line1
prefix line2
prefix line3
# Step 2. remove spaces in the middle
$ cat file | ts prefix | tr -d ' '
prefixline1
prefixline2
prefixline3
Roughly:-
var accounts = new Dictionary<string, double>();
// Initialise to zero...
accounts["Fred"] = 0;
accounts["George"] = 0;
accounts["Fred"] = 0;
// Add cash.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;
Console.WriteLine("Fred owes me ${0}", accounts["Fred"]);
Login to virtual machine use below command to check ip address. (anyone will work)
If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1
If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine
You need to install Package Control first (from the Python console in Sublime. Visit http://wbond.net/sublime_packages/package_control for more info), and then install emmet from their repository.
Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.
https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY
Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.
The usual method to exit a Python program:
sys.exit()
(to which you can also pass an exit status) or
raise SystemExit
will work fine in a Tkinter program.
Abstraction : you'll never buy a "device", but always buy something more specific : iPhone, GSII, Nokia 3310... Here, iPhone, GSII and N3310 are concrete things, device is abstract.
Encapsulation : you've got several devices, all of them have got a USB port. You don't know what kind of printed circuit there's back, you just have to know you'll be able to plug a USB cable into it.
Abstraction is a concept, which is allowed by encapsulation. My example wasn't the best one (there's no real link between the two blocks).
You can do encapsulation without using abstraction, but if you wanna use some abstraction in your projects, you'll need encapsulation.
Simply go to the directory where the troubling file is, type touch *
without quotes in the console, and you should be good.
First set Storage Engine as InnoDB
then the relation view option enable in structure menu
How do I read a string from input?
You can read a single, whitespace terminated word with std::cin
like this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a word:\n";
string s;
cin>>s;
cout << "You entered " << s << '\n';
}
Note that there is no explicit memory management and no fixed-sized buffer that you could possibly overflow. If you really need a whole line (and not just a single word) you can do this:
#include<iostream>
#include<string>
using namespace std;
int main()
{
cout << "Please enter a line:\n";
string s;
getline(cin,s);
cout << "You entered " << s << '\n';
}
The behavior exact to the one specified by you is impossible in JS as implemented in current browsers. Sorry.
Well, you could in theory make a function with a loop where loop's end condition would be based on time, but this would hog your CPU, make browser unresponsive and would be extremely poor design. I refuse to even write an example for this ;)
Update: My answer got -1'd (unfairly), but I guess I could mention that in ES6 (which is not implemented in browsers yet, nor is it enabled in Node.js by default), it will be possible to write a asynchronous code in a synchronous fashion. You would need promises and generators for that.
You can use it today, for instance in Node.js with harmony flags, using Q.spawn(), see this blog post for example (last example there).
The compiler doesn't know that spe_context_ptr_t is a type. Check that the appropriate typedef is in scope when this code is compiled. You may have forgotten to include the appropriate header file.
I personally prefer using char(1) with values 'Y' and 'N' for databases that don't have a native type for boolean. Letters are more user frendly than numbers which assume that those reading it will now that 1 corresponds to true and 0 corresponds to false.
'Y' and 'N' also maps nicely when using (N)Hibernate.
It seems that you'll need two fields, a choice list for the currency and a number field for the value.
A common technique in such case is to use a div or span for the display (form fields offscreen), and on click switch to the form elements for editing.
Inserts, updates, deletes and reads are generally OK from multiple threads, but Brad's answer is not correct. You have to be careful with how you create your connections and use them. There are situations where your update calls will fail, even if your database doesn't get corrupted.
The basic answer.
The SqliteOpenHelper object holds on to one database connection. It appears to offer you a read and write connection, but it really doesn't. Call the read-only, and you'll get the write database connection regardless.
So, one helper instance, one db connection. Even if you use it from multiple threads, one connection at a time. The SqliteDatabase object uses java locks to keep access serialized. So, if 100 threads have one db instance, calls to the actual on-disk database are serialized.
So, one helper, one db connection, which is serialized in java code. One thread, 1000 threads, if you use one helper instance shared between them, all of your db access code is serial. And life is good (ish).
If you try to write to the database from actual distinct connections at the same time, one will fail. It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.
So, multiple threads? Use one helper. Period. If you KNOW only one thread will be writing, you MAY be able to use multiple connections, and your reads will be faster, but buyer beware. I haven't tested that much.
Here's a blog post with far more detail and an example app.
Gray and I are actually wrapping up an ORM tool, based off of his Ormlite, that works natively with Android database implementations, and follows the safe creation/calling structure I describe in the blog post. That should be out very soon. Take a look.
In the meantime, there is a follow up blog post:
Also checkout the fork by 2point0 of the previously mentioned locking example:
This can happen if curl is asked to do plain HTTP on a server that does HTTPS.
Example:
$ curl http://google.com:443
curl: (52) Empty reply from server
Not possible in Java.
Here's the Scala way:
val m = List(5, 4, 2, 89)
for((el, i) <- m.zipWithIndex)
println(el +" "+ i)
My answer is for Firebase and position 0 is a workaround
Parcelable state;
DatabaseReference everybody = db.getReference("Everybody Room List");
everybody.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
state = listView.onSaveInstanceState(); // Save
progressBar.setVisibility(View.GONE);
arrayList.clear();
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
Messages messagesSpacecraft = messageSnapshot.getValue(Messages.class);
arrayList.add(messagesSpacecraft);
}
listView.setAdapter(convertView);
listView.onRestoreInstanceState(state); // Restore
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
and convertView
position 0 a add a blank item that you are not using
public class Chat_ConvertView_List_Room extends BaseAdapter {
private ArrayList<Messages> spacecrafts;
private Context context;
@SuppressLint("CommitPrefEdits")
Chat_ConvertView_List_Room(Context context, ArrayList<Messages> spacecrafts) {
this.context = context;
this.spacecrafts = spacecrafts;
}
@Override
public int getCount() {
return spacecrafts.size();
}
@Override
public Object getItem(int position) {
return spacecrafts.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@SuppressLint({"SetTextI18n", "SimpleDateFormat"})
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.message_model_list_room, parent, false);
}
final Messages s = (Messages) this.getItem(position);
if (position == 0) {
convertView.getLayoutParams().height = 1; // 0 does not work
} else {
convertView.getLayoutParams().height = RelativeLayout.LayoutParams.WRAP_CONTENT;
}
return convertView;
}
}
I have seen this work temporarily without disturbing the user, I hope it works for you
```yaml
{
"this-json": "looks awesome..."
}
If you want to have keys a different colour to the parameters, set your language as yaml
@Ankanna's answer gave me the idea of going through github's supported language list and yaml
was my best find.
user.no_of_logins += 1
session.commit()
First of all, your description is misleading. Double
is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:
$s = sprintf('%02d', $digit);
For more information, refer to the documentation of sprintf
.
You can use the font-weight attribute on your
For example:
<p>This is my paragraph</p>
You can either have your CSS inline as below:
<p style="font-weight:bold;">This is my paragraph</p>
Or have it in your external CSS stylesheet as below:
p{
font-weight:bold;
}
I am using visual studio 2015. Deleting .vs folder in the project folder helped me to fix this. You must close the visual studio first.
For the URI query use urlencode
/urldecode
; for anything else use rawurlencode
/rawurldecode
.
The difference between urlencode
and rawurlencode
is that
urlencode
encodes according to application/x-www-form-urlencoded (space is encoded with +
) whilerawurlencode
encodes according to the plain Percent-Encoding (space is encoded with %20
).Based on MSDN:
Example: Math calculations (math values) does not changes [STANDARD CALCULATION FOR DEFINED VALUES]
Programatically this can be achieved with SCHTASKS:
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=1074)]]" /EC Security /tn on_shutdown_normal /tr "c:\some.bat"
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6006)]]" /EC Security /tn on_shutdown_6006 /tr "c:\some.bat"
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6008)]]" /EC Security /tn on_shutdown_6008 /tr "c:\some.bat"
Your best bet is to bite the bullet use the DOM Parser - it's the 'right way' to do it. In the long run it'll save you more time than it takes to learn how. Parsing HTML with Regex is known to be unreliable and intolerant of special cases.
Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.
So I would at least change it to:
public class ProfileCollection implements Iterable<Profile> {
private ArrayList<Profile> m_Profiles;
public Iterator<Profile> iterator() {
Iterator<Profile> iprof = m_Profiles.iterator();
return iprof;
}
...
public Profile GetActiveProfile() {
return (Profile)m_Profiles.get(m_ActiveProfile);
}
}
and this should work:
for (Profile profile : m_PC) {
// do stuff
}
Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:
for (Object profile : m_PC) {
// do stuff
}
This is a pretty obscure corner case of Java generics.
If not, please provide some more info about what's going on.
Calculate the total size of the database at the end:
(SELECT
table_name AS `Table`,
round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB`
FROM information_schema.TABLES
WHERE table_schema = "$DB_NAME"
)
UNION ALL
(SELECT
'TOTAL:',
SUM(round(((data_length + index_length) / 1024 / 1024), 2) )
FROM information_schema.TABLES
WHERE table_schema = "$DB_NAME"
)
Watch this video, I had the same question. He shows you how to debug the service as well.
Here are his instructions using the basic C# Windows Service template in Visual Studio 2010/2012.
You add this to the Service1.cs file:
public void onDebug()
{
OnStart(null);
}
You change your Main() to call your service this way if you are in the DEBUG Active Solution Configuration.
static void Main()
{
#if DEBUG
//While debugging this section is used.
Service1 myService = new Service1();
myService.onDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
//In Release this section is used. This is the "normal" way.
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
Keep in mind that while this is an awesome way to debug your service. It doesn't call OnStop()
unless you explicitly call it similar to the way we called OnStart(null)
in the onDebug()
function.
It probably is the # sign like tho others have mentioned because this appears to work just fine.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<select id="#ticket_category_clone">
<option value="hw">Hardware</option>
<option>fsdf</option>
<option>sfsd</option>
<option>sdfs</option>
</select>
<script type="text/javascript">
(function check() {
var e = document.getElementById("#ticket_category_clone");
var str = e.options[e.selectedIndex].text;
alert(str);
if (str === "Hardware") {
alert('Hi');
}
})();
</script>
</body>
LabelEncoding worked for me (basically you've to encode your data feature-wise) (mydata is a 2d array of string datatype):
myData=np.genfromtxt(filecsv, delimiter=",", dtype ="|a20" ,skip_header=1);
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for i in range(*NUMBER OF FEATURES*):
myData[:,i] = le.fit_transform(myData[:,i])
Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.
Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.
jquery.getStyleObject.js:
/*
* getStyleObject Plugin for jQuery JavaScript Library
* From: http://upshots.org/?p=112
*/
(function($){
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
})(jQuery);
Basic usage is pretty simple, but he's written a function for that as well:
$.fn.copyCSS = function(source){
var styles = $(source).getStyleObject();
this.css(styles);
}
Hope that helps.
You could walk up through the parents, noting their position within their parent, until you arrive at the Form.
Edit: Something like (untested):
public Point GetPositionInForm(Control ctrl)
{
Point p = ctrl.Location;
Control parent = ctrl.Parent;
while (! (parent is Form))
{
p.Offset(parent.Location.X, parent.Location.Y);
parent = parent.Parent;
}
return p;
}
In SSMS, "Query" menu item... "Results to"... "Results to File"
Shortcut = CTRL+shift+F
You can set it globally too
"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down
Edit: after comment
In SSMS, "Query" menu item... "SQLCMD" mode
This allows you to run "command line" like actions.
A quick test in my SSMS 2008
:OUT c:\foo.txt
SELECT * FROM sys.objects
Edit, Sep 2012
:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects
Regarding the first (and great) answer from chris who proposed a solution to the situation where the class members are held as a "true composite" members (i.e.- not as pointers nor references):
The note is a bit large, so I will demonstrate it here with some sample code.
When you chose to hold the members as I mentioned, you have to keep in mind also these two things:
For every "composed object" that does not have a default constructor - you must initialize it in the initialization list of all the constructor's of the "father" class (i.e.- BigMommaClass
or MyClass
in the original examples and MyClass
in the code below), in case there are several (see InnerClass1
in the example below). Meaning, you can "comment out" the m_innerClass1(a)
and m_innerClass1(15)
only if you enable the InnerClass1
default constructor.
For every "composed object" that does have a default constructor - you may initialize it within the initialization list, but it will work also if you chose not to (see InnerClass2
in the example below).
See sample code (compiled under Ubuntu 18.04 (Bionic Beaver) with g++
version 7.3.0):
#include <iostream>
using namespace std;
class InnerClass1
{
public:
InnerClass1(int a) : m_a(a)
{
cout << "InnerClass1::InnerClass1 - set m_a:" << m_a << endl;
}
/* No default constructor
InnerClass1() : m_a(15)
{
cout << "InnerClass1::InnerClass1() - set m_a:" << m_a << endl;
}
*/
~InnerClass1()
{
cout << "InnerClass1::~InnerClass1" << endl;
}
private:
int m_a;
};
class InnerClass2
{
public:
InnerClass2(int a) : m_a(a)
{
cout << "InnerClass2::InnerClass2 - set m_a:" << m_a << endl;
}
InnerClass2() : m_a(15)
{
cout << "InnerClass2::InnerClass2() - set m_a:" << m_a << endl;
}
~InnerClass2()
{
cout << "InnerClass2::~InnerClass2" << endl;
}
private:
int m_a;
};
class MyClass
{
public:
MyClass(int a, int b) : m_innerClass1(a), /* m_innerClass2(a),*/ m_b(b)
{
cout << "MyClass::MyClass(int b) - set m_b to:" << m_b << endl;
}
MyClass() : m_innerClass1(15), /*m_innerClass2(15),*/ m_b(17)
{
cout << "MyClass::MyClass() - m_b:" << m_b << endl;
}
~MyClass()
{
cout << "MyClass::~MyClass" << endl;
}
private:
InnerClass1 m_innerClass1;
InnerClass2 m_innerClass2;
int m_b;
};
int main(int argc, char** argv)
{
cout << "main - start" << endl;
MyClass obj;
cout << "main - end" << endl;
return 0;
}
You may not like it, but personally I find
if (x.HasValue && x.Value)
the most readable. It makes it clear you are working with a nullable type and it makes it clear you are first checking whether the nullable type has a value before acting on it conditionally.
If you take your version and replace the variable with x also it reads:
if (x ?? false)
Is that as clear? Is it obvious x is a nullable type? I'll let you decide.
Are you using retrolambda? If so, just do JAVA_HOME=$JAVA8_HOME
.
Source: https://github.com/evant/gradle-retrolambda/issues/74
The issue isn't actually a syntax error, the Hive ParseException is just caused by a reserved keyword in Hive (in this case, end
).
The solution: use backticks around the offending column name:
CREATE EXTERNAL TABLE moveProjects (cid string, `end` string, category string)
STORED BY 'org.apache.hadoop.hive.dynamodb.DynamoDBStorageHandler'
TBLPROPERTIES ("dynamodb.table.name" = "Projects",
"dynamodb.column.mapping" = "cid:cid,end:end,category:category");
With the added backticks around end
, the query works as expected.
IF, HAVING, WHERE, SELECT, UNIQUEJOIN, JOIN, ON, TRANSFORM, MAP, REDUCE, TABLESAMPLE, CAST, FUNCTION, EXTENDED, CASE, WHEN, THEN, ELSE, END, DATABASE, CROSS
Source: This Hive ticket from the Facebook Phabricator tracker
In this particular case the clearest solution is the S.Lott answer
But in some complex logical conditions I would prefer use some boolean algebra to get a clear solution.
Using De Morgan's law ¬(A^B) = ¬Av¬B
not (u0 <= u and u < u0+step)
(not u0 <= u) or (not u < u0+step)
u0 > u or u >= u0+step
then
if u0 > u or u >= u0+step:
pass
... in this case the «clear» solution is not more clear :P
NullPointerException
s are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.
Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerException
s is accidentally declaring an object with local scope when there is an instance variable with the same name.
In your case, the exception occurred in your constructor for Workshop on line 75. <init>
means the constructor for a class. If you look on that line in your code, you'll see the line
denimjeansButton.addItemListener(this);
There are fairly clearly two objects on this line: denimjeansButton
and this
. this
is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this
. denimjeansButton
is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton
or instantiate it.
Solution special chars
$link=mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());
//charset important
mysql_set_charset('utf8',$link);
while Alexey Kukanov's answer may be more efficient, you can also iterate through a queue in a very natural manner, by popping each element from the front of the queue, then pushing it to the back:
#include <iostream>
#include <queue>
using namespace std;
int main() {
//populate queue
queue<int> q;
for (int i = 0; i < 10; ++i) q.push(i);
// iterate through queue
for (size_t i = 0; i < q.size(); ++i) {
int elem = std::move(q.front());
q.pop();
elem *= elem;
q.push(std::move(elem));
}
//print queue
while (!q.empty()) {
cout << q.front() << ' ';
q.pop();
}
}
output:
0 1 4 9 16 25 36 49 64 81
I prefer using the dateutil library for timezone handling and generally solid date parsing. If you were to get an ISO 8601
string like: 2010-05-08T23:41:54.000Z
you'd have a fun time parsing that with strptime, especially if you didn't know up front whether or not the timezone was included. pyiso8601
has a couple of issues (check their tracker) that I ran into during my usage and it hasn't been updated in a few years. dateutil, by contrast, has been active and worked for me:
import dateutil.parser
yourdate = dateutil.parser.parse(datestring)
Use
=LEFT(B2, 2)*3600000 + MID(B2,4,2) * 60000 + MID(B2,7,2)*1000 + RIGHT(B2,3)
You don't want to do this. It is invalid HTML to have more than one element with the same id
. Browsers won't treat that well, and you will have undefined behavior, meaning you have no idea what the browser will give you when you select an element by that id, it could be unpredictable.
You should be using a class, or just iterating through the inputs and keeping track of an index.
Try something like this:
var div2 = document.getElementById('div2');
for(i = j = 0; i < div2.childNodes.length; i++)
if(div2.childNodes[i].nodeName == 'INPUT'){
j++;
var input = div2.childNodes[i];
alert('This is edit'+j+': '+input);
}
I would use return null;
to indicate that there is no data to be returned
Should you also need the parameters:
current_fullpath = request.env['ORIGINAL_FULLPATH'] # If you are browsing http://example.com/my/test/path?param_n=N # then current_fullpath will point to "/my/test/path?param_n=N"
And remember you can always call <%= debug request.env %>
in a view to see all the available options.
Since the MemberwiseClone() method is not public, I created this simple extension method in order to make it easier to clone objects:
public static T Clone<T>(this T obj)
{
var inst = obj.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
return (T)inst?.Invoke(obj, null);
}
Usage:
var clone = myObject.Clone();
To add to @migontech's answer and also his address his comment that you could "probably make it more generic", here's a way to do it. The below will allow you to search by any property:
.filter('getByProperty', function() {
return function(propertyName, propertyValue, collection) {
var i=0, len=collection.length;
for (; i<len; i++) {
if (collection[i][propertyName] == +propertyValue) {
return collection[i];
}
}
return null;
}
});
The call to filter would then become:
var found = $filter('getByProperty')('id', fish_id, $scope.fish);
Note, I removed the unary(+) operator to allow for string-based matches...
A couple of general tips (besides the DOS line ending issue):
cat
is for concatenating files, it's not the only tool that can read files! If a command doesn't read files then use redirection like command < file
.
You can set the field separator with the -F
option so instead of:
cat foo | awk 'BEGIN{FS="|"} {print $2 " " $1}'
Try:
awk -F'|' '{print $2" "$1}' foo
This will output:
com.emailclient.account [email protected]
com.socialsite.auth.accoun [email protected]
To get the desired output you could do a variety of things. I'd probably split()
the second field:
awk -F'|' '{split($2,a,".");print a[2]" "$1}' file
emailclient [email protected]
socialsite [email protected]
Finally to get the first character converted to uppercase is a bit of a pain in awk
as you don't have a nice built in ucfirst()
function:
awk -F'|' '{split($2,a,".");print toupper(substr(a[2],1,1)) substr(a[2],2),$1}' file
Emailclient [email protected]
Socialsite [email protected]
If you want something more concise (although you give up a sub-process) you could do:
awk -F'|' '{split($2,a,".");print a[2]" "$1}' file | sed 's/^./\U&/'
Emailclient [email protected]
Socialsite [email protected]
Yes , Its easy to way we call the function inside the store procedure.
for e.g. create user define Age function and use in select query.
select dbo.GetRegAge(R.DateOfBirth, r.RegistrationDate) as Age,R.DateOfBirth,r.RegistrationDate from T_Registration R
you should be able to access them from $_POST
variable:
foreach ($_POST as $param_name => $param_val) {
echo "Param: $param_name; Value: $param_val<br />\n";
}
Another option would be to use case_when
require(dplyr)
mutate(df, est = case_when(
b == 0 ~ (a - 5)/2.53,
TRUE ~ est
))
This solution becomes even more handy if more than 2 cases need to be distinguished, as it allows to avoid nested if_else
constructs.
I threw this together so that you could do some querying on the results
Declare @dbName varchar(150)
set @dbName = '[YOURDATABASENAME]'
--Total machine connections
--SELECT COUNT(dbid) as TotalConnections FROM sys.sysprocesses WHERE dbid > 0
--Available connections
DECLARE @SPWHO1 TABLE (DBName VARCHAR(1000) NULL, NoOfAvailableConnections VARCHAR(1000) NULL, LoginName VARCHAR(1000) NULL)
INSERT INTO @SPWHO1
SELECT db_name(dbid), count(dbid), loginame FROM sys.sysprocesses WHERE dbid > 0 GROUP BY dbid, loginame
SELECT * FROM @SPWHO1 WHERE DBName = @dbName
--Running connections
DECLARE @SPWHO2 TABLE (SPID VARCHAR(1000), [Status] VARCHAR(1000) NULL, [Login] VARCHAR(1000) NULL, HostName VARCHAR(1000) NULL, BlkBy VARCHAR(1000) NULL, DBName VARCHAR(1000) NULL, Command VARCHAR(1000) NULL, CPUTime VARCHAR(1000) NULL, DiskIO VARCHAR(1000) NULL, LastBatch VARCHAR(1000) NULL, ProgramName VARCHAR(1000) NULL, SPID2 VARCHAR(1000) NULL, Request VARCHAR(1000) NULL)
INSERT INTO @SPWHO2
EXEC sp_who2 'Active'
SELECT * FROM @SPWHO2 WHERE DBName = @dbName
Use as variable to cast the Viewbag data to your desired class in view.
@{
IEnumerable<WebApplication1.Models.Person> personlist = ViewBag.data as
IEnumerable<WebApplication1.Models.Person>;
// You may need to write WebApplication.Models.Person where WebApplication.Models is
the namespace name where the Person class is defined. It is required so that view
can know about the class Person.
}
In view write this
<td>
@(personlist.FirstOrDefault().Name)
</td>
I use a NAnt Build Script to deploy to my different environments. I have it modify my config files via XPath depending on where they're being deployed to, and then it automagically puts them into that environment using Beyond Compare.
Takes a minute or two to setup, but you only need to do it once. Then batch files take over while I go get another cup of coffee. :)
Here's an article I found on it.
with
statementDifferentiating between exceptions that occur in a with
statement is tricky because they can originate in different places. Exceptions can be raised from either of the following places (or functions called therein):
ContextManager.__init__
ContextManager.__enter__
with
ContextManager.__exit__
For more details see the documentation about Context Manager Types.
If we want to distinguish between these different cases, just wrapping the with
into a try .. except
is not sufficient. Consider the following example (using ValueError
as an example but of course it could be substituted with any other exception type):
try:
with ContextManager():
BLOCK
except ValueError as err:
print(err)
Here the except
will catch exceptions originating in all of the four different places and thus does not allow to distinguish between them. If we move the instantiation of the context manager object outside the with
, we can distinguish between __init__
and BLOCK / __enter__ / __exit__
:
try:
mgr = ContextManager()
except ValueError as err:
print('__init__ raised:', err)
else:
try:
with mgr:
try:
BLOCK
except TypeError: # catching another type (which we want to handle here)
pass
except ValueError as err:
# At this point we still cannot distinguish between exceptions raised from
# __enter__, BLOCK, __exit__ (also BLOCK since we didn't catch ValueError in the body)
pass
Effectively this just helped with the __init__
part but we can add an extra sentinel variable to check whether the body of the with
started to execute (i.e. differentiating between __enter__
and the others):
try:
mgr = ContextManager() # __init__ could raise
except ValueError as err:
print('__init__ raised:', err)
else:
try:
entered_body = False
with mgr:
entered_body = True # __enter__ did not raise at this point
try:
BLOCK
except TypeError: # catching another type (which we want to handle here)
pass
except ValueError as err:
if not entered_body:
print('__enter__ raised:', err)
else:
# At this point we know the exception came either from BLOCK or from __exit__
pass
The tricky part is to differentiate between exceptions originating from BLOCK
and __exit__
because an exception that escapes the body of the with
will be passed to __exit__
which can decide how to handle it (see the docs). If however __exit__
raises itself, the original exception will be replaced by the new one. To deal with these cases we can add a general except
clause in the body of the with
to store any potential exception that would have otherwise escaped unnoticed and compare it with the one caught in the outermost except
later on - if they are the same this means the origin was BLOCK
or otherwise it was __exit__
(in case __exit__
suppresses the exception by returning a true value the outermost except
will simply not be executed).
try:
mgr = ContextManager() # __init__ could raise
except ValueError as err:
print('__init__ raised:', err)
else:
entered_body = exc_escaped_from_body = False
try:
with mgr:
entered_body = True # __enter__ did not raise at this point
try:
BLOCK
except TypeError: # catching another type (which we want to handle here)
pass
except Exception as err: # this exception would normally escape without notice
# we store this exception to check in the outer `except` clause
# whether it is the same (otherwise it comes from __exit__)
exc_escaped_from_body = err
raise # re-raise since we didn't intend to handle it, just needed to store it
except ValueError as err:
if not entered_body:
print('__enter__ raised:', err)
elif err is exc_escaped_from_body:
print('BLOCK raised:', err)
else:
print('__exit__ raised:', err)
PEP 343 -- The "with" Statement specifies an equivalent "non-with" version of the with
statement. Here we can readily wrap the various parts with try ... except
and thus differentiate between the different potential error sources:
import sys
try:
mgr = ContextManager()
except ValueError as err:
print('__init__ raised:', err)
else:
try:
value = type(mgr).__enter__(mgr)
except ValueError as err:
print('__enter__ raised:', err)
else:
exit = type(mgr).__exit__
exc = True
try:
try:
BLOCK
except TypeError:
pass
except:
exc = False
try:
exit_val = exit(mgr, *sys.exc_info())
except ValueError as err:
print('__exit__ raised:', err)
else:
if not exit_val:
raise
except ValueError as err:
print('BLOCK raised:', err)
finally:
if exc:
try:
exit(mgr, None, None, None)
except ValueError as err:
print('__exit__ raised:', err)
The need for such special exception handling should be quite rare and normally wrapping the whole with
in a try ... except
block will be sufficient. Especially if the various error sources are indicated by different (custom) exception types (the context managers need to be designed accordingly) we can readily distinguish between them. For example:
try:
with ContextManager():
BLOCK
except InitError: # raised from __init__
...
except AcquireResourceError: # raised from __enter__
...
except ValueError: # raised from BLOCK
...
except ReleaseResourceError: # raised from __exit__
...
remounting /dev/pts works for me. you can do this remotely via ssh if you run ssh like this against the affected machine. ssh doesn't request a tty when running commands like this and therefore this will allow you to remount /dev/pts remotely
ssh user@host -- 'mount -o remount,rw /dev/pts'
You can use the ui
object provided to the events, specifically you want the stop
event, the ui.item
property and .index()
, like this:
$("#sortable").sortable({
stop: function(event, ui) {
alert("New position: " + ui.item.index());
}
});
You can see a working demo here, remember the .index()
value is zero-based, so you may want to +1 for display purposes.
No, you need to loop over the array
for(String s : strList) intList.add(Integer.valueOf(s));
It doesn't really matter (you can quite happily run your site with web/database on the same machine), it's just the easiest step in scaling..
It's exactly what StackOverflow did - starting with single machine running IIS/SQL Server, then when it started getting heavily loaded, a second server was bought and the SQL server was moved onto that.
If performance is not an issue, do not waste money buying/maintaining two servers.
We can use class name instead of using id. html id are should be unique but classes are not. when retrieving data using class name can reduce number of code lines in your js files.
$(document).ready(function ()_x000D_
{_x000D_
$(".class_name").click(function ()_x000D_
{_x000D_
//code_x000D_
});_x000D_
});
_x000D_
If you are concerned about the file's content being served rather than its output. You can use a double extension like: file.inc.php
. It then serves the same purpose of helpfulness and maintainability.
I normally have 2 php files for each page on my site:
welcome.php
in the root folder, containing all of the HTML markup. welcome.inc.php
in the inc
folder, containing all PHP functions specific to the welcome.php
page.EDIT: Another benefit of using the double extention .inc.php
would be that any IDE can still recognise the file as PHP code.
I got the solution. I am able to enable MySQLi extension in php.ini. I just uncommented this line in php.ini:
extension=php_mysqli.dll
Now MySQLi is working well. Here is the php.ini
file path in an Apache 2, PHP 7, and Ubuntu 14.04 environment:
/etc/php/7.0/apache2/php.ini
By default, the MySQLi extension is disabled in PHP 7.
Thank you for all answers! I found it! It calls "Column selection (for Sublime)" and "Column Mode Editing (for Notepad++)" https://www.sublimetext.com/docs/3/column_selection.html
None of the answers helped me since I wanted to achieve something which was exactly the same as mentioned in the question.
I have created a jQuery plugin for this purpose.
/*
* Raj: This file is responsible to display the modals in a stacked fashion. Example:
* 1. User displays modal A
* 2. User now wants to display modal B -> This will not work by default if a modal is already displayed
* 3. User dismisses modal B
* 4. Modal A should now be displayed automatically -> This does not happen all by itself
*
* Trying to solve problem for: http://stackoverflow.com/questions/18253972/bootstrap-modal-close-current-open-new
*
*/
var StackedModalNamespace = StackedModalNamespace || (function() {
var _modalObjectsStack = [];
return {
modalStack: function() {
return _modalObjectsStack;
},
currentTop: function() {
var topModal = null;
if (StackedModalNamespace.modalStack().length) {
topModal = StackedModalNamespace.modalStack()[StackedModalNamespace.modalStack().length-1];
}
return topModal;
}
};
}());
// http://stackoverflow.com/a/13992290/260665 difference between $.fn.extend and $.extend
jQuery.fn.extend({
// https://api.jquery.com/jquery.fn.extend/
showStackedModal: function() {
var topModal = StackedModalNamespace.currentTop();
StackedModalNamespace.modalStack().push(this);
this.off('hidden.bs.modal').on('hidden.bs.modal', function(){ // Subscription to the hide event
var currentTop = StackedModalNamespace.currentTop();
if ($(this).is(currentTop)) {
// 4. Unwinding - If user has dismissed the top most modal we need to remove it form the stack and display the now new top modal (which happens in point 3 below)
StackedModalNamespace.modalStack().pop();
}
var newTop = StackedModalNamespace.currentTop();
if (newTop) {
// 3. Display the new top modal (since the existing modal would have been hidden by point 2 now)
newTop.modal('show');
}
});
if (topModal) {
// 2. If some modal is displayed, lets hide it
topModal.modal('hide');
} else {
// 1. If no modal is displayed, just display the modal
this.modal('show');
}
},
});
Working Fiddle for reference, JSFiddle: https://jsfiddle.net/gumdal/67hzgp5c/
You just have to invoke with my new API "showStackedModal()
" instead of just "modal('show')
". The hide part can still be the same as before and the stacked approach of showing & hiding the modals are automatically taken care.
try this:
<div ng-if="$scope.length == 0" ? true : false></div>
and show or hide
<div ng-show="$scope.length == 0"></div>
else it will be hide
-----------------or--------------------------
if you are using $ctrl than code will be like this:
try this:
<div ng-if="$ctrl.length == 0" ? true : false></div>
and show or hide
<div ng-show="$ctrl.length == 0"></div>
else it will be hide
Similar to solution of mark
with some checking of variables. Also I prefer not to use $variable
but rather the same string I saved it under
save your folder/directory using save dir sdir myproject
and go back to that folder using goto dir gdir myproject
in addition checkout the workings of native pushd and popd
they will save the current folder and this is handy for going back and forth. In this case you can also use popd
after gdir myproject
and go back again
# Save the current folder using sdir yourhandle to a variable you can later access the same folder fast using gdir yourhandle
function sdir {
[[ ! -z "$1" ]] && export __d__$1="`pwd`";
}
function gdir {
[[ ! -z "$1" ]] && cd "${!1}";
}
another handy trick is to combine the two pushd/popd and sdir and gdir wher you replace the cd in the goto dir function in pushd. This enables you to also fly back to your previous folder when making the jump to the saved folder.
# Save the current folder using sdir yourhandle to a variable you can later access the same folder fast using gdir yourhandle
function sdir {
[[ ! -z "$1" ]] && export __d__$1="`pwd`";
}
function gdir {
[[ ! -z "$1" ]] && pushd "${!1}";
}
SELECT ...
SELECT SLEEP(5);
SELECT ...
But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?
Try the element:
$(td).find('a').attr('disabled', 'disabled');
Disabling a link works for me in Chrome: http://jsfiddle.net/KeesCBakker/LGYpz/.
Firefox doesn't seem to play nice. This example works:
<a id="a1" href="http://www.google.com">Google 1</a>
<a id="a2" href="http://www.google.com">Google 2</a>
$('#a1').attr('disabled', 'disabled');
$(document).on('click', 'a', function(e) {
if ($(this).attr('disabled') == 'disabled') {
e.preventDefault();
}
});
Note: added a 'live' statement for future disabled / enabled links.
Note2: changed 'live' into 'on'.
I think this is actually what you're looking for:
.my_container ul
{
list-style: initial;
margin: initial;
padding: 0 0 0 40px;
}
.my_container li
{
display: list-item;
}
For me the issue was updating psql
apt-get
wasn't resolving newer versions, even after update
. The following worked.
Ubuntu
Start with the import of the GPG key for PostgreSQL packages.
sudo apt-get install wget ca-certificates
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
Now add the repository to your system.
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" >> /etc/apt/sources.list.d/pgdg.list'
Install PostgreSQL on Ubuntu
sudo apt-get update
sudo apt-get install postgresql postgresql-contrib
You can use bash arrays
$ str_array=("continuation"
"lines")
then
$ echo "${str_array[*]}"
continuation lines
there is an extra space, because (after bash manual):
If the word is double-quoted,
${name[*]}
expands to a single word with the value of each array member separated by the first character of the IFS variable
So set IFS=''
to get rid of extra space
$ IFS=''
$ echo "${str_array[*]}"
continuationlines
You can use @input with ngOnChanges, to see the changes when it happened.
reference: https://angular.io/api/core/OnChanges
(or)
If you want to pass data between multiple component or routes then go with Rxjs way.
Service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class MessageService {
private subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessages() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
Component.ts
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { MessageService } from './_services/index';
@Component({
selector: 'app',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnDestroy {
messages: any[] = [];
subscription: Subscription;
constructor(private messageService: MessageService) {
// subscribe to home component messages
this.subscription = this.messageService.getMessage().subscribe(message => {
if (message) {
this.messages.push(message);
} else {
// clear messages when empty message received
this.messages = [];
}
});
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
}
var list = [
{prop1:"abc",prop2:"qwe"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}
];
var findProp = p => {
var index = -1;
$.each(list, (i, o) => {
if(o.prop2 == p) {
index = i;
return false; // break
}
});
return index; // -1 == not found, else == index
}
First of all, let's try to make your code a little simpler:
// No need to create a circle unless it is clearly necessary to
// demonstrate the problem
// Your Rect2f defines a default constructor, so let's use it for simplicity.
shared_ptr<Shape> rect(new Rect2f());
Okay, so now we see that the parentheses are clearly balanced. What else could it be? Let's check the following code snippet's error:
int main() {
delete new T();
}
This may seem like weird usage, and it is, but I really hate memory leaks. However, the output does seem useful:
In function 'int main()':
Line 2: error: expected type-specifier before 'T'
Aha! Now we're just left with the error about the parentheses. I can't find what causes that; however, I think you are forgetting to include the file that defines Rect2f
.
Check out this link about multi project setups.
Some things to point out, make sure you have your settings.gradle updated to reference both the app and library modules.
settings.gradle: include ':app', ':libraries:lib1', ':libraries:lib2'
Also make sure that the app's build.gradle has the followng:
dependencies {
compile project(':libraries:lib1')
}
You should have the following structure:
MyProject/
| settings.gradle
+ app/
| build.gradle
+ libraries/
+ lib1/
| build.gradle
+ lib2/
| build.gradle
The app's build.gradle should use the com.android.application
plugin while any libraries' build.gradle should use the com.android.library
plugin.
The Android Studio IDE should update if you're able to build from the command line with this setup.
You could always ensure they're in the same case before the comparison:
if ([[stringX uppercaseString] isEqualToString:[stringY uppercaseString]]) {
// They're equal
}
The main benefit being you avoid the potential issue described by matm regarding comparing nil strings. You could either check the string isn't nil before doing one of the compare:options:
methods, or you could be lazy (like me) and ignore the added cost of creating a new string for each comparison (which is minimal if you're only doing one or two comparisons).
There is no way to know that the two members of the options
array came from variables named size
and color
.
They are also not necessarily called that exclusively, any variable could also point to that array.
var notSize = size;
console.log(options[0]); // It is `size` or `notSize`?
One thing you can do is use an object there instead...
var options = {
size: size,
color: color
}
Then you could access options.size
or options.color
.
Here, I put my answer and its working for swift 4.2.
If your date is already a DateTime
or DateTimeImmutable
you can use the format
method.
$day_of_week = intval($date_time->format('w'));
The format string is identical to the one used by the date function.
To answer the intended question:
$date_time->modify($target_day_of_week - $day_of_week . ' days');
You can ABSOLUTELY do this without using anything MAVEN related. I personally use the NING HttpClient (v1.8.16, to support java6).
For whatever reason, Sonatype makes it incredibly difficulty to figure out what the correct URLs, headers, and payloads are supposed to be; and I had to sniff the traffic and guess... There are some barely useful blogs/documentation there, however it is either irrelevant to oss.sonatype.org
, or it's XML based (and I found out it doesn't even work). Crap documentation on their part, IMHO, and hopefully future seekers can find this answer useful. Many thanks to https://stackoverflow.com/a/33414423/2101812 for their post, as it helped a lot.
If you release somewhere other than oss.sonatype.org
, just replace it with whatever the correct host is.
Here is the (CC0 licensed) code I wrote to accomplish this. Where profile
is your sonatype/nexus profileID (such as 4364f3bbaf163
) and repo
(such as comdorkbox-1003
) are parsed from the response when you upload your initial POM/Jar.
Close repo:
/**
* Closes the repo and (the server) will verify everything is correct.
* @throws IOException
*/
private static
String closeRepo(final String authInfo, final String profile, final String repo, final String nameAndVersion) throws IOException {
String repoInfo = "{'data':{'stagedRepositoryId':'" + repo + "','description':'Closing " + nameAndVersion + "'}}";
RequestBuilder builder = new RequestBuilder("POST");
Request request = builder.setUrl("https://oss.sonatype.org/service/local/staging/profiles/" + profile + "/finish")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic " + authInfo)
.setBody(repoInfo.getBytes(OS.UTF_8))
.build();
return sendHttpRequest(request);
}
Promote repo:
/**
* Promotes (ie: release) the repo. Make sure to drop when done
* @throws IOException
*/
private static
String promoteRepo(final String authInfo, final String profile, final String repo, final String nameAndVersion) throws IOException {
String repoInfo = "{'data':{'stagedRepositoryId':'" + repo + "','description':'Promoting " + nameAndVersion + "'}}";
RequestBuilder builder = new RequestBuilder("POST");
Request request = builder.setUrl("https://oss.sonatype.org/service/local/staging/profiles/" + profile + "/promote")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic " + authInfo)
.setBody(repoInfo.getBytes(OS.UTF_8))
.build();
return sendHttpRequest(request);
}
Drop repo:
/**
* Drops the repo
* @throws IOException
*/
private static
String dropRepo(final String authInfo, final String profile, final String repo, final String nameAndVersion) throws IOException {
String repoInfo = "{'data':{'stagedRepositoryId':'" + repo + "','description':'Dropping " + nameAndVersion + "'}}";
RequestBuilder builder = new RequestBuilder("POST");
Request request = builder.setUrl("https://oss.sonatype.org/service/local/staging/profiles/" + profile + "/drop")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic " + authInfo)
.setBody(repoInfo.getBytes(OS.UTF_8))
.build();
return sendHttpRequest(request);
}
Delete signature turds:
/**
* Deletes the extra .asc.md5 and .asc.sh1 'turds' that show-up when you upload the signature file. And yes, 'turds' is from sonatype
* themselves. See: https://issues.sonatype.org/browse/NEXUS-4906
* @throws IOException
*/
private static
void deleteSignatureTurds(final String authInfo, final String repo, final String groupId_asPath, final String name,
final String version, final File signatureFile)
throws IOException {
String delURL = "https://oss.sonatype.org/service/local/repositories/" + repo + "/content/" +
groupId_asPath + "/" + name + "/" + version + "/" + signatureFile.getName();
RequestBuilder builder;
Request request;
builder = new RequestBuilder("DELETE");
request = builder.setUrl(delURL + ".sha1")
.addHeader("Authorization", "Basic " + authInfo)
.build();
sendHttpRequest(request);
builder = new RequestBuilder("DELETE");
request = builder.setUrl(delURL + ".md5")
.addHeader("Authorization", "Basic " + authInfo)
.build();
sendHttpRequest(request);
}
File uploads:
public
String upload(final File file, final String extension, String classification) throws IOException {
final RequestBuilder builder = new RequestBuilder("POST");
final RequestBuilder requestBuilder = builder.setUrl(uploadURL);
requestBuilder.addHeader("Authorization", "Basic " + authInfo)
.addBodyPart(new StringPart("r", repo))
.addBodyPart(new StringPart("g", groupId))
.addBodyPart(new StringPart("a", name))
.addBodyPart(new StringPart("v", version))
.addBodyPart(new StringPart("p", "jar"))
.addBodyPart(new StringPart("e", extension))
.addBodyPart(new StringPart("desc", description));
if (classification != null) {
requestBuilder.addBodyPart(new StringPart("c", classification));
}
requestBuilder.addBodyPart(new FilePart("file", file));
final Request request = requestBuilder.build();
return sendHttpRequest(request);
}
EDIT1:
How to get the activity/status for a repo
/**
* Gets the activity information for a repo. If there is a failure during verification/finish -- this will provide what it was.
* @throws IOException
*/
private static
String activityForRepo(final String authInfo, final String repo) throws IOException {
RequestBuilder builder = new RequestBuilder("GET");
Request request = builder.setUrl("https://oss.sonatype.org/service/local/staging/repository/" + repo + "/activity")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic " + authInfo)
.build();
return sendHttpRequest(request);
}
I just happened to come by your question and i have a solution. But its in jquery. Its too simple.
$('iframe').contents().find('body').css({"min-height": "100", "overflow" : "hidden"});
setInterval( "$('iframe').height($('iframe').contents().find('body').height() + 20)", 1 );
There you go!
Cheers! :)
Edit: If you have a Rich Text Editor based on the iframe method and not the div method and want it to expand every new line then this code will do the needful.
Try with below logic
driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");
List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));
for(WebElement ele :allElements) {
System.out.println("Name + Number===>"+ele.getText());
String s=ele.getText();
s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
System.out.println("Number==>"+s);
}
====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemedelské objekty (5)
Number==>5
Name + Number===>Komercní objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22
The problem in my case was that the database name was incorrect.
I solved the problem by referring the correct database name in the field as below
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDatabase</property>
You should be able to transfer the Application to another Username. You would need all your old user information to transfer it. The application would remove it's self from old account to new account. Also you could put a limit on how many times you where allowed to transfer it. If you transfer it to the application could expire after a year and force to buy update.
If you want to access event object as well as data passed, you have to pass event
and ticket.id
both as parameters, like following:
HTML
<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">
Javascript
methods: {
addToCart: function (event, id) {
// use event here as well as id
console.log('In addToCart')
console.log(id)
}
}
See working fiddle: https://jsfiddle.net/nee5nszL/
In case you are using vue-router, you may have to use $event in your v-on:input
method like following:
<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">
Here is working fiddle.
You could have two different versions of Python and pip.
Try to:
pip2 install --upgrade pip
and then pip2 install -r requirements.txt
Or pip3
if you are on newer Python version.
Well to make the decimal into a percent you can do this,
float percentage = (correct * 100.0f) / questionNum;
The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.
I think a 2 step approach is best, because c 2-d arrays are just and array of arrays. The first step is to allocate a single array, then loop through it allocating arrays for each column as you go. This article gives good detail.
First go through this tutorial for getting familiar with Android Google Maps and this for API 2.
To retrive the current location of device see this answer or this another answer and for API 2
Then you can get places near by your location using Google Place API and for use of Place Api see this blog.
After getting Placemarks of near by location use this blog with source code to show markers on map with balloon overlay with API 2.
You also have great sample to draw route between two points on map look here in these links Link1 and Link2 and this Great Answer.
After following these steps you will be easily able to do your application. The only condition is, you will have to read it and understand it, because like magic its not going to be complete in a click.
If you are changing the font size, you might want to stop shrinking sizes with this rule:
sup sub, sub sup, sup sup, sub sub{font-size:1em !important;}
I had the same issue (on windows server 2003), check in the IIS console if you have allowed ASP.NET v4 service extension (under IIS / ComputerName / Web Service extensions)
We can force to get latest update of release and snapshot repository with below command :
mvn --update-snapshots clean install
Here is your dataframe:
import pandas as pd
df = pd.DataFrame({
'A': ['a.1', 'a.2', 'a.3'],
'B': ['b.1', 'b.2', 'b.3'],
'C': ['c.1', 'c.2', 'c.3']})
Your answer is in the paragraph "Setting with enlargement" in the section on "Indexing and selecting data" in the documentation on Pandas.
It says:
A DataFrame can be enlarged on either axis via .loc.
So what you need to do is simply one of these two:
df.loc[:, 'D'] = df.loc[:, 'B']
df.loc[:, 'D'] = df['B']
Instead of doing recursion, the parts of the code with checkNextID(ID + 18)
and similar could be replaced with ID+=18
, and then if you remove all instances of return 0
, then it should do the same thing but as a simple loop. You should then put a return 0
at the end and make your variables non-global.
To compare two lists with the order preserved use,
assertThat(actualList, contains("item1","item2"));
Here is an answer: http://www.dba-oracle.com/concepts/synonyms.htm
An Oracle synonym basically allows you to create a pointer to an object that exists somewhere else. You need Oracle synonyms because when you are logged into Oracle, it looks for all objects you are querying in your schema (account). If they are not there, it will give you an error telling you that they do not exist.
Another gotcha I recently came across is that in IE 8, "abcd".substr(-1)
erroneously returns "abcd"
, whereas Firefox 3.6 returns "d"
as it should. slice
works correctly on both.
More on this topic can be found here.
On your command prompt type sqllocaldb start
Use <add name="defaultconnection" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=tododb;Integrated Security=True" providerName="System.Data.SqlClient" />
If you don't want to deal with interactive mode then do this:
Update your last pushed commit
git commit --amend -m "New commit message."
Push your new commit message (this will replace the old last commit message to this new one)
git push origin --force **branch-name**
More on this - https://linuxize.com/post/change-git-commit-message/
It worked for me this way:
Step1: Open System Preference > MySQL > Initialize Database.
Step2: Put password you used while installing MySQL.
Step3: Start MySQL server.
Step4: Come back to MySQL Workbench and double connect/ create a new one.
With a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE)
, you need to either use a list or use shell=True
;
Either of these will work. The former is preferable.
a = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE)
a = subprocess.Popen('cdrecord --help', shell=True, stdout=subprocess.PIPE)
Also, instead of using Popen.stdout.read
/Popen.stderr.read
, you should use .communicate()
(refer to the subprocess documentation for why).
proc = subprocess.Popen(['cdrecord', '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
To identify a WebElement using xpath and javascript you have to use the evaluate()
method which evaluates an xpath expression and returns a result.
document.evaluate() returns an XPathResult based on an XPath expression and other given parameters.
The syntax is:
var xpathResult = document.evaluate(
xpathExpression,
contextNode,
namespaceResolver,
resultType,
result
);
Where:
xpathExpression
: The string representing the XPath to be evaluated.contextNode
: Specifies the context node for the query. Common practice is to pass document
as the context node.namespaceResolver
: The function that will be passed any namespace prefixes and should return a string representing the namespace URI associated with that prefix. It will be used to resolve prefixes within the XPath itself, so that they can be matched with the document. null
is common for HTML documents or when no namespace prefixes are used.resultType
: An integer that corresponds to the type of result XPathResult to return using named constant properties, such as XPathResult.ANY_TYPE
, of the XPathResult constructor, which correspond to integers from 0 to 9.result
: An existing XPathResult to use for the results. null
is the most common and will create a new XPathResultAs an example the Search Box within the Google Home Page which can be identified uniquely using the xpath as //*[@name='q']
can also be identified using the google-chrome-devtools Console by the following command:
$x("//*[@name='q']")
Snapshot:
The same element can can also be identified using document.evaluate()
and the xpath expression as follows:
document.evaluate("//*[@name='q']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
Snapshot:
You are passing pointers (Complex*
) when your function takes references (const Complex&
). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.
To get an object to pass to your function, you would need to dereference your pointers:
Complex::distanta(*firstComplexNumber, *secondComplexNumber);
Or get your function to take pointer arguments.
However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete
what you have new
ed), you're better off not using pointers in the first place:
Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);
Here is an example of concatenation operator:
architecture EXAMPLE of CONCATENATION is
signal Z_BUS : bit_vector (3 downto 0);
signal A_BIT, B_BIT, C_BIT, D_BIT : bit;
begin
Z_BUS <= A_BIT & B_BIT & C_BIT & D_BIT;
end EXAMPLE;
If the number of commits that have not been pushed out is a single-digit number, which it often is, the easiest way is:
$ git checkout
git responds by telling you that you are "ahead N commits" relative your origin. So now just keep that number in mind when viewing logs. If you're "ahead by 3 commits", the top 3 commits in the history are still private.
List<Something> result = new ArrayList<Something>(all);
EnumSet
is a Java Collection, as it implements the Set
interface:
public interface Set<E> extends Collection<E>
So anything you can do with a Collection you can do with an EnumSet
.
As of 2015, this is the best way (Java 8):
tourists.removeIf(Objects::isNull);
Note: This code will throw java.lang.UnsupportedOperationException
for fixed-size lists (such as created with Arrays.asList), including immutable lists.
Try:
System.IO.Directory.Delete(path,true)
This will recursively delete all files and folders underneath "path" assuming you have the permissions to do so.
You have to use double double quotes to escape the double quotes (lol):
g = "abcd """ & a & """"
For managing DataBase Objects in SQL Server i would suggest using Server Management Objects
In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.
flex-basis: 25%;
This will be a lot smoother when testing.
// VARIABLES
$screen-xs: 480px;
$screen-sm: 768px;
$screen-md: 992px;
$screen-lg: 1200px;
$screen-xl: 1400px;
$screen-xxl: 1600px;
// QUERIES
@media screen (max-width: $screen-lg) {
flex-basis: 25%;
}
@media screen (max-width: $screen-md) {
flex-basis: 33.33%;
}
You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.
private void AggiornaContatore()
{
if(this.lblCounter.InvokeRequired)
{
this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});
}
else
{
this.lblCounter.Text = this.index.ToString(); ;
}
}
Please go through this chapter and more from this book to get a clear picture about threading:
http://www.albahari.com/threading/part2.aspx#_Rich_Client_Applications
A correct way to do basic auth in Python3 urllib.request
with certificate validation follows.
Note that certifi
is not mandatory. You can use your OS bundle (likely *nix only) or distribute Mozilla's CA Bundle yourself. Or if the hosts you communicate with are just a few, concatenate CA file yourself from the hosts' CAs, which can reduce the risk of MitM attack caused by another corrupt CA.
#!/usr/bin/env python3
import urllib.request
import ssl
import certifi
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(certifi.where())
httpsHandler = urllib.request.HTTPSHandler(context = context)
manager = urllib.request.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, 'https://domain.com/', 'username', 'password')
authHandler = urllib.request.HTTPBasicAuthHandler(manager)
opener = urllib.request.build_opener(httpsHandler, authHandler)
# Used globally for all urllib.request requests.
# If it doesn't fit your design, use opener directly.
urllib.request.install_opener(opener)
response = urllib.request.urlopen('https://domain.com/some/path')
print(response.read())
I have my images in a separate class library ("MyClassLibrary") and they are placed in the folder "Images". In the example I used "myImage.jpg" as the background image.
ImageBrush myBrush = new ImageBrush();
Image image = new Image();
image.Source = new BitmapImage(
new Uri(
"pack://application:,,,/MyClassLibrary;component/Images/myImage.jpg"));
myBrush.ImageSource = image.Source;
Grid grid = new Grid();
grid.Background = myBrush;
Each version of Visual Studio prior to Visual Studio 2010 is tied to a specific .NET framework. (VS2008 is .NET 3.5, VS2005 is .NET 2.0, VS2003 is .NET1.1) Visual Studio 2010 and beyond allow for targeting of prior framework versions but cannot be used for future releases. You must use Visual Studio 2012 in order to utilize .NET 4.5.
I'd like to emphasize that order of arguments is important.
For me java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 -jar app.jar
command opens debugger port,
but java -jar app.jar -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000
command doesn't.
"By default, when an application calls DriverManager.getConnection(url, ...)
and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.
Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/** @see http://stackoverflow.com/questions/5225700 */
public class H2MemTest {
public static void main(String[] args) throws Exception {
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("create table customer(id integer, name varchar(10))");
st.execute("insert into customer values (1, 'Thomas')");
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select name from customer");
while (rset.next()) {
String name = rset.getString(1);
System.out.println(name);
}
}
}
A single bracket ([
) usually actually calls a program named [
; man test
or man [
for more info. Example:
$ VARIABLE=abcdef
$ if [ $VARIABLE == abcdef ] ; then echo yes ; else echo no ; fi
yes
The double bracket ([[
) does the same thing (basically) as a single bracket, but is a bash builtin.
$ VARIABLE=abcdef
$ if [[ $VARIABLE == 123456 ]] ; then echo yes ; else echo no ; fi
no
Parentheses (()
) are used to create a subshell. For example:
$ pwd
/home/user
$ (cd /tmp; pwd)
/tmp
$ pwd
/home/user
As you can see, the subshell allowed you to perform operations without affecting the environment of the current shell.
(a) Braces ({}
) are used to unambiguously identify variables. Example:
$ VARIABLE=abcdef
$ echo Variable: $VARIABLE
Variable: abcdef
$ echo Variable: $VARIABLE123456
Variable:
$ echo Variable: ${VARIABLE}123456
Variable: abcdef123456
(b) Braces are also used to execute a sequence of commands in the current shell context, e.g.
$ { date; top -b -n1 | head ; } >logfile
# 'date' and 'top' output are concatenated,
# could be useful sometimes to hunt for a top loader )
$ { date; make 2>&1; date; } | tee logfile
# now we can calculate the duration of a build from the logfile
There is a subtle syntactic difference with ( )
, though (see bash reference) ; essentially, a semicolon ;
after the last command within braces is a must, and the braces {
, }
must be surrounded by spaces.
The Web Developer Toolbar has an option to disable caching which makes it very easy to turn it on and off when you need it.
Follow this tutorial Tensorflow GPU I did it and it works perfect.
Attention! - install version 9.0! newer version is not supported by Tensorflow-gpu
Steps:
pip install tensorflow-gpu
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
sentence.sub! 'Robert', 'Joe'
Won't cause an exception if the replaced word isn't in the sentence (the []=
variant will).
The above replaces only the first instance of "Robert".
To replace all instances use gsub
/gsub!
(ie. "global substitution"):
sentence.gsub! 'Robert', 'Joe'
The above will replace all instances of Robert with Joe.
Inverse and default class name mention in Twitter Bootstrap cause them to be black and white color.
Better, you should not override that and add a class near that and write you particular style for that:
my_style{_x000D_
background-color: green;_x000D_
}
_x000D_
Unfortunately, Selenium was only built to work with Elements, not Text nodes.
If you try to use a function like get_element_by_xpath
to target the text nodes, Selenium will throw an InvalidSelectorException
.
One workaround is to grab the relevant HTML with Selenium and then use an HTML parsing library like BeautifulSoup that can handle text nodes more elegantly.
import bs4
from bs4 import BeautifulSoup
inner_html = driver.find_elements_by_css_selector('#a')[0].get_attribute("innerHTML")
inner_soup = BeautifulSoup(inner_html, 'html.parser')
outer_html = driver.find_elements_by_css_selector('#a')[0].get_attribute("outerHTML")
outer_soup = BeautifulSoup(outer_html, 'html.parser')
From there, there are several ways to search for the Text content. You'll have to experiment to see what works best for your use case.
Here's a simple one-liner that may be sufficient:
inner_soup.find(text=True)
If that doesn't work, then you can loop through the element's child nodes with .contents() and check their object type.
BeautifulSoup has four types of elements, and the one that you'll be interested in is the NavigableString type, which is produced by Text nodes. By contrast, Elements will have a type of Tag.
contents = inner_soup.contents
for bs4_object in contents:
if (type(bs4_object) == bs4.Tag):
print("This object is an Element.")
elif (type(bs4_object) == bs4.NavigableString):
print("This object is a Text node.")
Note that BeautifulSoup doesn't support Xpath expressions. If you need those, then you can use some of the workarounds in this thread.
I believe you may simply do:
ImageConverter converter = new ImageConverter();
var bytes = (byte[])converter.ConvertTo(img, typeof(byte[]));
Global variables can be used in Node when used wisely.
Declaration of global variables in Node:
a = 10;
GLOBAL.a = 10;
global.a = 10;
All of the above commands the same actions with different syntaxes.
Use global variables when they are not about to be changed
Here an example of something that can happen when using global variables:
// app.js
a = 10; // no var or let or const means global
// users.js
app.get("/users", (req, res, next) => {
res.send(a); // 10;
});
// permissions.js
app.get("/permissions", (req, res, next) => {
a = 11; // notice that there is no previous declaration of a in the permissions.js, means we looking for the global instance of a.
res.send(a); // 11;
});
Explained:
Run users route first and receive 10;
Then run permissions route and receive 11;
Then run again the users route and receive 11 as well instead of 10;
Global variables can be overtaken!
Now think about using express and assignin res object as global.. And you end up with async error become corrupt and server is shuts down.
When to use global vars?
As I said - when var is not about to be changed.
Anyways it's more recommended that you will be using the process.env
object from the config file.
You could also have embed all of your template views into your main html file. For Example:
<body ng-app="testApp">
<h1>Test App</h1>
<div ng-view></div>
<script type = "text/ng-template" id = "index.html">
<h1>Index Page</h1>
<p>{{message}}</p>
</script>
<script type = "text/ng-template" id = "home.html">
<h1>Home Page</h1>
<p>{{message}}</p>
</script>
</body>
This way if each template requires a different controller then you can still use the angular-router. See this plunk for a working example http://plnkr.co/edit/9X0fT0Q9MlXtHVVQLhgr?p=preview
This way once the application is sent from the server to your client, it is completely self contained assuming that it doesn't need to make any data requests, etc.
No, it is better practice to leave them out.
Without strip(), you can have empty keys and values:
apples<tab>round, fruity things
oranges<tab>round, fruity things
bananas<tab>
Without strip(), bananas is present in the dictionary but with an empty string as value. With strip(), this code will throw an exception because it strips the tab of the banana line.
That's not possible. but you can use an Object Mapper like AutoMapper
Example:
class A
{
public int IntProp { get; set; }
}
class B
{
public int IntProp { get; set; }
public string StrProp { get; set; }
}
In global.asax or application startup:
AutoMapper.Mapper.CreateMap<A, B>();
Usage:
var b = AutoMapper.Mapper.Map<B>(a);
It's easily configurable via a fluent API.
I am assuming this is a custom font. For any custom font this is what you do.
First download and add your font files to your project in Xcode (The files should appear as well in “Target -> Build Phases -> Copy Bundle Resources”).
In your Info.plist file add the key “Fonts provided by application” with type “Array”.
For each font you want to add to your project, create an item for the array you have created with the full name of the file including its extension (e.g. HelveticaNeue-UltraLight.ttf). Save your “Info.plist” file.
label.font = UIFont (name: "HelveticaNeue-UltraLight", size: 30)
I've been in a situation like you (JPA/Hibernate sequence for non @Id field) and I ended up creating a trigger in my db schema that add a unique sequence number on insert. I just never got it to work with JPA/Hibernate
You could let your DataAdapter
do the work. DataAdapter.Fill(DataTable)
will append your new rows to any existing rows in DataTable
.
public class LeadingZerosExample {
public static void main(String[] args) {
int number = 1500;
// String format below will add leading zeros (the %0 syntax)
// to the number above.
// The length of the formatted string will be 7 characters.
String formatted = String.format("%07d", number);
System.out.println("Number with leading zeros: " + formatted);
}
}
I just faced the same issue, I managed to make it work on my machine, however the change I did is not the same way it is mentioned in the documentation so it could be an issue of angular version routing module, mine is Angular 7
It only worked when I changed the lazy module main route entry path with same path as configured at the app-routes.ts
routes = [{path:'', redirectTo: '\home\default', pathMatch: 'full'},
{path: '',
children: [{
path:'home',
loadChildren :'lazy module path'
}]
}];
routes configured at HomeModule
const routes = [{path: 'home', redirectTo: 'default', pathMatch: 'full'},
{path: 'default', component: MyPageComponent},
]
instead of
const routes = [{path: '', redirectTo: 'default', pathMatch: 'full'},
{path: 'default', component: MyPageComponent},
]
Though checkdate
is good, this seems much concise function to validate and also you can give formats. [Source]
function validateDate($date, $format = 'Y-m-d H:i:s') {
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function was copied from this answer or php.net
The extra ->format()
is needed for cases where the date is invalid but createFromFormat
still manages to create a DateTime object. For example:
// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');
// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');
Try this code
$('window').scrollDown(function(){$(#div).hide()});
$('window').scrollUp(function(){ $(#div).show() });
This is what I have come up with so far after studying the rest of the answers. It should be able to support touch-only, mouse-only or hybrid users.
Create a separate hover class for the hover effect. By default, add this hover class to our button.
We do not want to detect the presence of touch support and disable all hover effects from the very beginning. As mentioned by others, hybrid devices are gaining popularity; people may have touch support but want to use a mouse and vice versa. Therefore, only remove the hover class when the user actually touches the button.
The next problem is, what if the user wants to go back to using a mouse after touching the button? To solve that, we need to find an opportune moment to add back the hover class which we have removed.
However, we cannot add it back immediately after removing it, because the hover state is still active. We may not want to destroy and recreate the entire button as well.
So, I thought of using a busy-waiting algorithm (using setInterval) to check the hover state. Once the hover state is deactivated, we can then add back the hover class and stop the busy-waiting, bringing us back to the original state where the user can use either mouse or touch.
I know busy-waiting isn't that great but I'm not sure if there is an appropriate event. I've considered to add it back in the mouseleave event, but it was not very robust. For example, when an alert pops up after the button is touched, the mouse position shifts but the mouseleave event is not triggered.
var button = document.getElementById('myButton');_x000D_
_x000D_
button.ontouchstart = function(e) {_x000D_
console.log('ontouchstart');_x000D_
$('.button').removeClass('button-hover');_x000D_
startIntervalToResetHover();_x000D_
};_x000D_
_x000D_
button.onclick = function(e) {_x000D_
console.log('onclick');_x000D_
}_x000D_
_x000D_
var intervalId;_x000D_
_x000D_
function startIntervalToResetHover() {_x000D_
// Clear the previous one, if any._x000D_
if (intervalId) {_x000D_
clearInterval(intervalId);_x000D_
}_x000D_
_x000D_
intervalId = setInterval(function() {_x000D_
// Stop if the hover class already exists._x000D_
if ($('.button').hasClass('button-hover')) {_x000D_
clearInterval(intervalId);_x000D_
intervalId = null;_x000D_
return;_x000D_
}_x000D_
_x000D_
// Checking of hover state from _x000D_
// http://stackoverflow.com/a/8981521/2669960._x000D_
var isHovered = !!$('.button').filter(function() {_x000D_
return $(this).is(":hover");_x000D_
}).length;_x000D_
_x000D_
if (isHovered) {_x000D_
console.log('Hover state is active');_x000D_
} else {_x000D_
console.log('Hover state is inactive');_x000D_
$('.button').addClass('button-hover');_x000D_
console.log('Added back the button-hover class');_x000D_
_x000D_
clearInterval(intervalId);_x000D_
intervalId = null;_x000D_
}_x000D_
}, 1000);_x000D_
}
_x000D_
.button {_x000D_
color: green;_x000D_
border: none;_x000D_
}_x000D_
_x000D_
.button-hover:hover {_x000D_
background: yellow;_x000D_
border: none;_x000D_
}_x000D_
_x000D_
.button:active {_x000D_
border: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='myButton' class='button button-hover'>Hello</button>
_x000D_
Edit: Another approach I tried is to call e.preventDefault()
within ontouchstart or ontouchend. It appears to stop the hover effect when the button is touched, but it also stops the button click animation and prevents the onclick function from being called when the button is touched, so you have to call those manually in the ontouchstart or ontouchend handler. Not a very clean solution.
The only conditions available in CSS are selectors and @media. Some browsers support some of the CSS 3 selectors and media queries.
You can modify an element with JavaScript to change if it matches a selector or not (e.g. by adding a new class).
You should use:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
&& keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
// Take care of calling this method on earlier versions of
// the platform where it doesn't exist.
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
// This will be called either automatically for you on 2.0
// or later, or by the code above on earlier versions of the
// platform.
return;
}
As defined here: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
If you are using an older version to compile the code, replace android.os.Build.VERSION_CODES.ECLAIR by 5 (you can add a private int named ECLAIR for example)
When you try to look at this at the level of "design patterns" (in general) and "FP versus OOP", the answers you'll find will be murky at best.
Go a level deeper on both axes, though, and consider specific design patterns and specific language features and things become clearer.
So, for example, some specific patterns, like Visitor, Strategy, Command, and Observer definitely change or disappear when using a language with algebraic data types and pattern matching, closures, first class functions, etc. Some other patterns from the GoF book still 'stick around', though.
In general, I would say that, over time, specific patterns are being eliminated by new (or just rising-in-popularity) language features. This is the natural course of language design; as languages become more high-level, abstractions that could previously only be called out in a book using examples now become applications of a particular language feature or library.
(Aside: here's a recent blog I wrote, which has other links to more discussion on FP and design patterns.)
There's no need for a parent POM.
You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.
To do it on the build server, just pass to the mvn
command:
-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases
See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.
It's also possible to set this in your settings.xml
.
Just create a profile there which is enabled and contains the property.
Example settings.xml:
<settings>
[...]
<profiles>
<profile>
<id>nexus</id>
<properties>
<altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
<altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
</settings>
Make sure that credentials for "snapshots" and "releases" are in the <servers>
section of your settings.xml
The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message
Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter
To fix this, you can enforce a newer version of the plug-in:
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8</version>
</plugin>
</plugins>
</pluginManagement>
</build>
Can you load the GUIDs into a scratch table then do a
... WHERE var IN SELECT guid FROM #scratchtable
how about using $nohup
command on linux?
I use it for running my commands on my Bluehost server.
Please advice if I am wrong.
function do_ajax(elem, mydata, filename)
{
$.ajax({
url: filename,
context: elem,
data: mydata,
**contentType: false,
processData: false**
datatype: "html",
success: function (data, textStatus, xhr) {
elem.innerHTML = data;
}
});
}
SET CD=%~DP0
SET REL_PATH=%CD%..\..\build\
call :ABSOLUTE_PATH ABS_PATH %REL_PATH%
ECHO %REL_PATH%
ECHO %ABS_PATH%
pause
exit /b
:ABSOLUTE_PATH
SET %1=%~f2
exit /b
In Java terms, Scala's Seq
would be Java's List
, and Scala's List
would be Java's LinkedList
.
Note that Seq
is a trait
, which is equivalent to Java's interface
, but with the equivalent of up-and-coming defender methods. Scala's List
is an abstract class that is extended by Nil
and ::
, which are the concrete implementations of List
.
So, where Java's List
is an interface
, Scala's List
is an implementation.
Beyond that, Scala's List
is immutable, which is not the case of LinkedList
. In fact, Java has no equivalent to immutable collections (the read only thing only guarantees the new object cannot be changed, but you still can change the old one, and, therefore, the "read only" one).
Scala's List
is highly optimized by compiler and libraries, and it's a fundamental data type in functional programming. However, it has limitations and it's inadequate for parallel programming. These days, Vector
is a better choice than List
, but habit is hard to break.
Seq
is a good generalization for sequences, so if you program to interfaces, you should use that. Note that there are actually three of them: collection.Seq
, collection.mutable.Seq
and collection.immutable.Seq
, and it is the latter one that is the "default" imported into scope.
There's also GenSeq
and ParSeq
. The latter methods run in parallel where possible, while the former is parent to both Seq
and ParSeq
, being a suitable generalization for when parallelism of a code doesn't matter. They are both relatively newly introduced, so people doesn't use them much yet.
const person = {
name: "Lokamn",
dob: 12,
print: function (value,value2) {
console.log(this.dob+value+value2)
}
}
const anotherPerson= {
name: "Pappu",
dob: 12,
}
person.print.call(anotherPerson,1,2)
name: "Lokamn",
dob: 12,
print: function (value,value2) {
console.log(this.dob+value+value2)
}
}
const anotherPerson= {
name: "Pappu",
dob: 12,
}
person.print.apply(anotherPerson,[1,2])
**call and apply function are difference call take separate argument but apply take array like:[1,2,3] **
name: "Lokamn",
dob: 12,
anotherPerson: {
name: "Pappu",
dob: 12,
print2: function () {
console.log(this)
}
}
}
var bindFunction = person.anotherPerson.print2.bind(person)
bindFunction()
Here are three ways to go with this problem :
from datetime import datetime
Now = datetime.now()
StartDate = datetime.strptime(str(Now.year) +'-01-01', '%Y-%m-%d')
NumberOfDays = (Now - StartDate)
print(NumberOfDays.days) # Starts at 0
print(datetime.now().timetuple().tm_yday) # Starts at 1
print(Now.strftime('%j')) # Starts at 1
Try instead of assigning dom properties (which is slow) just pass your value as a parameter to function that actually create your handler:
render: function() {
...
<a style={showStyle} onClick={this.removeTag(i)}></a>
...
removeTag = (customAttribute) => (event) => {
this.setState({inputVal: customAttribute});
}
// For Image with parameter /// AFMultipartFormData
NSDictionary *dictParam =@{@"user_id":strGlobalUserId,@"name":[dictParameter objectForKey:@"Name"],@"contact":[dictParameter objectForKey:@"Contact Number"]};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:webServiceUrl]];
[manager.requestSerializer setValue:strGlobalLoginToken forHTTPHeaderField:@"Authorization"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain",@"application/rss+xml", nil];
[manager POST:@"update_profile" parameters:dictParam constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
if (Imagedata.length>0) {
[formData appendPartWithFileData:Imagedata name:@"profile_pic" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
}
} progress:nil
success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSLog(@"update_profile %@", responseObject);
if ([[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"status"] isEqualToString:@"true"])
{
[self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
[self.navigationController popViewControllerAnimated:YES];
}] animated:YES completion:nil];
}
else
{
[self presentViewController:[global SimpleAlertviewcontroller:@"" Body:[[[responseObject objectForKey:@"response"] objectAtIndex:0] objectForKey:@"response_msg"] handler:^(UIAlertAction *action) {
}] animated:YES completion:nil];
}
[SVProgressHUD dismiss];
} failure:^(NSURLSessionDataTask *_Nullable task, NSError *_Nonnull error)
{
[SVProgressHUD dismiss];
}];
Since you are copying tha same data to all rows, you don't actually need to loop at all. Try this:
Sub ARRAYER()
Dim Number_of_Sims As Long
Dim rng As Range
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Number_of_Sims = 100000
Set rng = Range("C4:G4")
rng.Offset(1, 0).Resize(Number_of_Sims) = rng.Value
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Try and run the following command:
ALTER TABLE `investments`
MODIFY created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
NOT NULL;
and
ALTER TABLE `investments`
MODIFY updated_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
NOT NULL;
The reason you are getting this error is because you are not setting a default value for the created_at
and updated_at
fields. MySQL is not accepting your command since the values for these columns cannot be null.
Take a look at the more recent JCommander.
I created it. I’m happy to receive questions or feature requests.
In my case I had to start a list of exclude extensions from the second line because xcopy ignored the first line.
Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx
name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);
Your pkl
file is, in fact, a serialized pickle
file, which means it has been dumped using Python's pickle
module.
To un-pickle the data you can:
import pickle
with open('serialized.pkl', 'rb') as f:
data = pickle.load(f)
Note gzip
is only needed if the file is compressed:
import gzip
import pickle
with gzip.open('mnist.pkl.gz', 'rb') as f:
train_set, valid_set, test_set = pickle.load(f)
Where each set can be further divided (i.e. for the training set):
train_x, train_y = train_set
Those would be the inputs (digits) and outputs (labels) of your sets.
If you want to display the digits:
import matplotlib.cm as cm
import matplotlib.pyplot as plt
plt.imshow(train_x[0].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()
The other alternative would be to look at the original data:
http://yann.lecun.com/exdb/mnist/
But that will be harder, as you'll need to create a program to read the binary data in those files. So I recommend you to use Python, and load the data with pickle
. As you've seen, it's very easy. ;-)
You can declare multiple type variables on a type or method. For example, using type parameters on the method:
<P, Q> int f(Set<P>, Set<Q>) {
return 0;
}
Use CURRENT_TIMESTAMP
when you need it, instead OF NOW()
(which is MySQL)
You can use IIF for a similar result.
Note that you can nest the IIF statements to handle multiple cases. There is an example here: http://forums.devshed.com/database-management-46/query-ms-access-iif-statement-multiple-conditions-358130.html
SELECT IIf([Combinaison] = "Mike", 12, IIf([Combinaison] = "Steve", 13)) As Answer
FROM MyTable;
I also got this error, but for a .h
file. The fix was to go into the file Properties
(via Solution Explorer's file popup menu) and set the file type correctly. It was set to C/C++ Compiler
instead of the correct C/C++ header
.
I give you the answer in both Objective C and Swift.Before that I want to say
If we use the
dequeueReusableCellWithIdentifier:forIndexPath:
,we must register a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method before calling this method as Apple Documnetation Says
So we add registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier:
Once we registered a class for the specified identifier and a new cell must be created, this method initializes the cell by calling its initWithStyle:reuseIdentifier: method. For nib-based cells, this method loads the cell object from the provided nib file. If an existing cell was available for reuse, this method calls the cell’s prepareForReuse method instead.
in viewDidLoad method we should register the cell
Objective C
OPTION 1:
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
OPTION 2:
[self.tableView registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil] forCellReuseIdentifier:@"cell"];
in above code nibWithNibName:@"CustomCell"
give your nib name instead of my nib name CustomCell
SWIFT
OPTION 1:
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
OPTION 2:
tableView.registerNib(UINib(nibName: "NameInput", bundle: nil), forCellReuseIdentifier: "Cell")
in above code nibName:"NameInput"
give your nib name
Map<String, Integer> map = new HashMap<>();
map.put("test1", 1);
map.put("test2", 2);
Map<String, Integer> map2 = new HashMap<>();
map.forEach(map2::put);
System.out.println("map: " + map);
System.out.println("map2: " + map2);
// Output:
// map: {test2=2, test1=1}
// map2: {test2=2, test1=1}
You can use the forEach
method to do what you want.
What you're doing there is:
map.forEach(new BiConsumer<String, Integer>() {
@Override
public void accept(String s, Integer integer) {
map2.put(s, integer);
}
});
Which we can simplify into a lambda:
map.forEach((s, integer) -> map2.put(s, integer));
And because we're just calling an existing method we can use a method reference, which gives us:
map.forEach(map2::put);
I know this is an old thread but for anyone looking to retrieve a script after ssms crashes do the following
If this is for Cygwin, it installs "pip" as "pip2". Just create a softlink to "pip2" in the same location where "pip2" is installed.
On API 22 The Use Of BasicNamevalue Pair is depricated, instead use the HASMAP for that. To know more about the HasMap visit here more on hasmap developer.android
package com.yubraj.sample.datamanager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.yubaraj.sample.utilities.GeneralUtilities;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by yubraj on 7/30/15.
*/
public class ServerRequestHandler {
private static final String TAG = "Server Request";
OnServerRequestComplete listener;
public ServerRequestHandler (){
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType, OnServerRequestComplete listener){
debug("ServerRequest", "server request called, url = " + url);
if(listener != null){
this.listener = listener;
}
try {
new BackgroundDataSync(getPostDataString(parameters), url, requestType).execute();
debug(TAG , " asnyc task called");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doServerRequest(HashMap<String, String> parameters, String url, int requestType){
doServerRequest(parameters, url, requestType, null);
}
public interface OnServerRequestComplete{
void onSucess(Bundle bundle);
void onFailed(int status_code, String mesage, String url);
}
public void setOnServerRequestCompleteListener(OnServerRequestComplete listener){
this.listener = listener;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
class BackgroundDataSync extends AsyncTask<String, Void , String>{
String params;
String mUrl;
int request_type;
public BackgroundDataSync(String params, String url, int request_type){
this.mUrl = url;
this.params = params;
this.request_type = request_type;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls) {
debug(TAG, "in Background, urls = " + urls.length);
HttpURLConnection connection;
debug(TAG, "in Background, url = " + mUrl);
String response = "";
switch (request_type) {
case 1:
try {
connection = iniitializeHTTPConnection(mUrl, "POST");
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.flush();
writer.close();
os.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
/* String line;
BufferedReader br=new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}*/
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
} else {
response = "";
}
} catch (IOException e) {
e.printStackTrace();
}
break;
case 0:
connection = iniitializeHTTPConnection(mUrl, "GET");
try {
if (connection.getResponseCode() == connection.HTTP_OK) {
response = getDataFromInputStream(new InputStreamReader(connection.getInputStream()));
}
} catch (Exception e) {
e.printStackTrace();
response = "";
}
break;
}
return response;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(TextUtils.isEmpty(s) || s.length() == 0){
listener.onFailed(DbConstants.NOT_FOUND, "Data not found", mUrl);
}
else{
Bundle bundle = new Bundle();
bundle.putInt(DbConstants.STATUS_CODE, DbConstants.HTTP_OK);
bundle.putString(DbConstants.RESPONSE, s);
bundle.putString(DbConstants.URL, mUrl);
listener.onSucess(bundle);
}
//System.out.println("Data Obtained = " + s);
}
private HttpURLConnection iniitializeHTTPConnection(String url, String requestType) {
try {
debug("ServerRequest", "url = " + url + "requestType = " + requestType);
URL link = new URL(url);
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
conn.setRequestMethod(requestType);
conn.setDoInput(true);
conn.setDoOutput(true);
return conn;
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
private String getDataFromInputStream(InputStreamReader reader){
String line;
String response = "";
try {
BufferedReader br = new BufferedReader(reader);
while ((line = br.readLine()) != null) {
response += line;
debug("ServerRequest", "response length = " + response.length());
}
}
catch (Exception e){
e.printStackTrace();
}
return response;
}
private void debug(String tag, String string) {
Log.d(tag, string);
}
}
and Just call the function when you needed to get the data from server either by post or get like this
HashMap<String, String>params = new HashMap<String, String>();
params.put("action", "request_sample");
params.put("name", uname);
params.put("message", umsg);
params.put("email", getEmailofUser());
params.put("type", "bio");
dq.doServerRequest(params, "your_url", DbConstants.METHOD_POST);
dq.setOnServerRequestCompleteListener(new ServerRequestHandler.OnServerRequestComplete() {
@Override
public void onSucess(Bundle bundle) {
debug("data", bundle.getString(DbConstants.RESPONSE));
}
@Override
public void onFailed(int status_code, String mesage, String url) {
debug("sample", mesage);
}
});
Now it is complete.Enjoy!!! Comment it if find any problem.
try using IP instead of pc name. If the ip working, then it might be the name pipe is not enable. If it;s still not working then the login using windows might be disabled.
You can do that by storing cookies on client side.
For an instance
Character.Gorgon gor = new Character.Gorgon();
Then do
gor instanceof Monster
For a Class instance do
Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);
Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:
import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };
See also [1] for more examples.
[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html
I got the same problem in ubuntu 18.04 with nginx. By following the below steps my issue has been fixd:
First open terminal and enter into mysql CLI. To check mysql socket location I write the following command.
mysql> show variables like '%sock%'
I got something like the below :
+-----------------------------------------+-----------------------------+
| Variable_name | Value |
+-----------------------------------------+-----------------------------+
| mysqlx_socket | /var/run/mysqld/mysqlx.sock |
| performance_schema_max_socket_classes | 10 |
| performance_schema_max_socket_instances | -1 |
| socket | /var/run/mysqld/mysqld.sock |
+-----------------------------------------+-----------------------------+
4 rows in set (0.00 sec)
In laravel project folder, look for the database.php file in the config folder. In the mysql section I modified unix_socket according to the above table.
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'database_name',
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'unix_socket' => '/var/run/mysqld/mysqld.sock',
),
Now just save changes, and reload the page and it worked.
Java 8 added a new API for working with dates and times. With Java 8 you can use
import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();
Instant.now()
returns an Instant that represents the current system time. With getEpochSecond()
you get the epoch seconds (unix time) from the Instant
.
For handling subscription I use a "Unsubscriber" class.
Here is the Unsubscriber Class.
export class Unsubscriber implements OnDestroy {
private subscriptions: Subscription[] = [];
addSubscription(subscription: Subscription | Subscription[]) {
if (Array.isArray(subscription)) {
this.subscriptions.push(...subscription);
} else {
this.subscriptions.push(subscription);
}
}
unsubscribe() {
this.subscriptions
.filter(subscription => subscription)
.forEach(subscription => {
subscription.unsubscribe();
});
}
ngOnDestroy() {
this.unsubscribe();
}
}
And You can use this class in any component / Service / Effect etc.
Example:
class SampleComponent extends Unsubscriber {
constructor () {
super();
}
this.addSubscription(subscription);
}
Try installing Web Platform from https://www.microsoft.com/web/platform/
Hope it helps.
java.lang.UnsupportedOperationException
Thrown to indicate that the requested operation is not supported.
To do this for oracle sql, the syntax would be:
,SUBSTR(col,INSTR(col,'-',1,2)+1) AS new_field
for this example, I look for the second '-' and take the substring to the end
n_values = data.income.value_counts()
First unique value count
n_at_most_50k = n_values[0]
Second unique value count
n_greater_50k = n_values[1]
n_values
Output:
<=50K 34014
>50K 11208
Name: income, dtype: int64
Output:
n_greater_50k,n_at_most_50k:-
(11208, 34014)
Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();
if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
// if true center text:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
holder.txtGuestName.setLayoutParams(layoutParams);
} else {
// if false remove center:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
holder.txtGuestName.setLayoutParams(layoutParams);
}